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: OpenCV multiple template matching - Improving matching I try to recognize 4 the same fiducial marks on a map. With help of the internet, I have created something, but I am looking for ways to improve the search, since the result is far from perfect. What I tried so far: Changing the threshold Trying different cv2...
OpenCV multiple template matching - Improving matching
I try to recognize 4 the same fiducial marks on a map. With help of the internet, I have created something, but I am looking for ways to improve the search, since the result is far from perfect. What I tried so far: Changing the threshold Trying different cv2 methods Making the image and the template smaller This is ...
[ "Here is how I would do that in Python/OpenCV. Mostly the same as yours with several changes.\nFirst, I would not bother computing the dim for resize. I would just use your scale_percent/100 so a fraction. Resize permits that in place of the size.\nSecond, I would threshold your images and invert the template so t...
[ 1 ]
[]
[]
[ "opencv", "python", "template_matching" ]
stackoverflow_0074232586_opencv_python_template_matching.txt
Q: Pydantic root_validator with pre=True recieves dicts instead of actual input object I have two pydantic models, A and B. Model B is a kind of refactoring of A, and should be able to parse its values natively. I constructed a root_validator with pre=True, which checks for instances of A and parses them into a norma...
Pydantic root_validator with pre=True recieves dicts instead of actual input object
I have two pydantic models, A and B. Model B is a kind of refactoring of A, and should be able to parse its values natively. I constructed a root_validator with pre=True, which checks for instances of A and parses them into a normal B object. The pydantic docs state: root validators can have pre=True, in which case th...
[ "The .parse_obj method is meant to be called with a dict (basically, it is expecting a dict that you would use liek MyModel(**some_dict).\nIf the object it receives is not a dict, it is coerced to a dict:\n@classmethod\ndef parse_obj(cls: Type['Model'], obj: Any) -> 'Model':\n obj = cls._enforce_dict_if_root(obj...
[ 1 ]
[]
[]
[ "parsing", "pydantic", "python", "validation" ]
stackoverflow_0074256132_parsing_pydantic_python_validation.txt
Q: Groupby and Sum without pandas for CSV values here is the given data format USERID, USERNAME, EVENTID, DATE, AMOUNT 001,User1,EV-001,2020-01-01,1000 E001,User1,EV-001,2021-01-01,1000 E001,User1,EV-002,2020-03-01,300 E001,User1,EV-002,2020-04-01,500 E002,User2,EV-003,2020-01-02,100 E002,User2,EV-003,2020-02-02,200 ...
Groupby and Sum without pandas for CSV values
here is the given data format USERID, USERNAME, EVENTID, DATE, AMOUNT 001,User1,EV-001,2020-01-01,1000 E001,User1,EV-001,2021-01-01,1000 E001,User1,EV-002,2020-03-01,300 E001,User1,EV-002,2020-04-01,500 E002,User2,EV-003,2020-01-02,100 E002,User2,EV-003,2020-02-02,200 E002,User3,EV-003,2020-03-02,300 E003,User4,EV-004,...
[ "I'm a little confused as to what you're trying to do. Your dictionary/hash table approach would be the way to do this when not using pandas but you need to reorganize your dictionary.\nAssuming you are trying to sum(AMOUNT) for each EVENTID for each USERID then you need to have the dictionary setup with USERID as ...
[ 1 ]
[]
[]
[ "dictionary", "python", "python_3.x" ]
stackoverflow_0074255984_dictionary_python_python_3.x.txt
Q: How print dataframe column names that have a particular value? I'm currently doing this for each column: df['slope'].isin(['?']) How do I print all columns that have at least one value '?'? Data set looks like this: age sex cp trestbps chol fbs restecg thalach exang oldpeak slope ca thal target 0 ...
How print dataframe column names that have a particular value?
I'm currently doing this for each column: df['slope'].isin(['?']) How do I print all columns that have at least one value '?'? Data set looks like this: age sex cp trestbps chol fbs restecg thalach exang oldpeak slope ca thal target 0 28.0 1.0 2.0 130 132 0 2 185 0 0 ? ? ? 0 I'm look...
[ "You can do it like this:\nfor col in df.columns:\n if df[col].astype('str').str.contains(r'\\?').any():\n print(col)\n\n", "you can use:\ndf= df.loc[: , (df == '?').any()]\n#or columns\n\ncol_list=df.loc[: , (df == '?').any()].columns.to_list()\n\n#if you are looking \"isin\"\ndf= df.loc[: , df.apply(la...
[ 1, 1, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074256231_dataframe_pandas_python.txt
Q: PyQt6 Create a bar with minimum features on minimizing the window I want to create a bar with minimum control features when minimizing the main application window, similar to the bar in the image below but in PyQt6. Currently, I am creating a new small screen on the minimize action but I could not remove the bar ...
PyQt6 Create a bar with minimum features on minimizing the window
I want to create a bar with minimum control features when minimizing the main application window, similar to the bar in the image below but in PyQt6. Currently, I am creating a new small screen on the minimize action but I could not remove the bar which has the close, minimize and maximize buttons from it.
[ "I eventually got it and I was able to write the below code to produce it\nclass FloatingDialogBar(QWidget):\n\n def __init__(self, parent=None, project: str = None, task: str = None):\n super(FloatingDialogBar, self).__init__(parent)\n\n self.project = project if project else 'N/A'\n self.t...
[ 0 ]
[]
[]
[ "minimize", "pyqt", "pyqt5", "pyqt6", "python" ]
stackoverflow_0074252245_minimize_pyqt_pyqt5_pyqt6_python.txt
Q: How to remove whitespace under dynamic Plotly table? I have a dynamic Plotly table. She get dataframe from SQL query using Pandas. Height of table constantly changing and i don't set current value. After setting table she must send as photo using aiogram Telegram bot. How to remove whitespace under table, which ar...
How to remove whitespace under dynamic Plotly table?
I have a dynamic Plotly table. She get dataframe from SQL query using Pandas. Height of table constantly changing and i don't set current value. After setting table she must send as photo using aiogram Telegram bot. How to remove whitespace under table, which arises if i don't set current height? figure = go.Figure(dat...
[ "I solved the problem. I multiplied the number of rows by the row height and added the header height to that. To avoid problems with cells that contain two lines, I went through the dataframe and determined experimentally how many characters are in a cell that contains two lines. Further, using these values, I dete...
[ 0 ]
[]
[]
[ "data_science", "plotly", "plotly_python", "python" ]
stackoverflow_0074247128_data_science_plotly_plotly_python_python.txt
Q: While function issue i want to generate a random number and loop it until it matches my statement in python import random as ra random=ra.randint(0,100) while random==56: if random==56: print('this is it') i cant get pass it i am a beginer and as far as i have learned while loops are used to run ...
While function issue
i want to generate a random number and loop it until it matches my statement in python import random as ra random=ra.randint(0,100) while random==56: if random==56: print('this is it') i cant get pass it i am a beginer and as far as i have learned while loops are used to run the program until the cond...
[ "You need to trace through your code by hand. If you did that here, you'd realize that random was never changing. And it's a bad practice to name your variables after reserved words or standard modules.\nimport random\n\nwhile True:\n rand=random.randint(0,100)\n if rand==56:\n print('this is it')\n ...
[ 1 ]
[]
[]
[ "python", "while_loop" ]
stackoverflow_0074256395_python_while_loop.txt
Q: Replacing Pandas Dataframe Column with Dictionary Values Based on a Condition I have the following dataframe import pandas as pd movies = {'name': ['Movie A', 'Movie B', 'Movie C', 'Movie D', 'Movie E'], 'genre' : ['Action', 'Crime', 'Drama', 'Comedy', 'Animation'], 'runtime' : [0, 100, 0, 120,0]} df = pd.DataFr...
Replacing Pandas Dataframe Column with Dictionary Values Based on a Condition
I have the following dataframe import pandas as pd movies = {'name': ['Movie A', 'Movie B', 'Movie C', 'Movie D', 'Movie E'], 'genre' : ['Action', 'Crime', 'Drama', 'Comedy', 'Animation'], 'runtime' : [0, 100, 0, 120,0]} df = pd.DataFrame(movies) I also have the following dictionary which contains the median runtime...
[ "Use Series.where and check Series.ne. All non-zero values will be untouched, all zeros will be filled based on the mapping:\ndf['runtime'] = df['runtime'].where(df['runtime'].ne(0),\n df['genre'].map(genre_dict))\n\nprint(df)\n\n name genre runtime\n0 Movie A Acti...
[ 1, 0 ]
[]
[]
[ "dataframe", "dictionary", "pandas", "python" ]
stackoverflow_0074256368_dataframe_dictionary_pandas_python.txt
Q: Filter out values that are close together in numpy For a small project, I need to filter out values that are close together (distance is given by a parameter) in a numpy array. The values in the numpy array are always sorted and every value is unique. Let's view an example: sample_array = np.array([1, 7, 15, 16, 1...
Filter out values that are close together in numpy
For a small project, I need to filter out values that are close together (distance is given by a parameter) in a numpy array. The values in the numpy array are always sorted and every value is unique. Let's view an example: sample_array = np.array([1, 7, 15, 16, 18, 19, 26, 33]) For a given distance, I want to remove ...
[ "any implementation of this will involve a loop, now in python, this loop will look as follows:\nimport numpy as np\n\ndef rem_dist(arr,dist):\n new = [arr[0]]\n for n in arr[1:]:\n if n - new[-1] > dist:\n new.append(n)\n return np.array(new)\n\nsample_array = np.array([1, 7, 15, 16, 18,...
[ 0 ]
[]
[]
[ "numpy", "python", "python_3.x" ]
stackoverflow_0074256282_numpy_python_python_3.x.txt
Q: PyGame window stopped showing up I've been learning python and decided to play around with PyGame. The PyGame window randomly stops showing up when I run the script. I don't get any errors or anything, the PyGame window just won't appear. The scripts used to work, now they don't. I had this issue before and restar...
PyGame window stopped showing up
I've been learning python and decided to play around with PyGame. The PyGame window randomly stops showing up when I run the script. I don't get any errors or anything, the PyGame window just won't appear. The scripts used to work, now they don't. I had this issue before and restarted my computer a few times and eventu...
[ "Handle the closing window properly , use pygame.quit().\nfor event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n\n", "This issue usually comes when you are exiting pygame window just after calling it. It can be resolved by exiting the pygame on...
[ 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0065730255_pygame_python.txt
Q: Replacing value in csv using pandas isn't working I'm working on a mock back end for an application; practicing OOP. I'm trying to replace a value in a .csv table and everything seems to be going well until the end where the code simply doesnt change anything. I've tried debugging as shown further down and it show...
Replacing value in csv using pandas isn't working
I'm working on a mock back end for an application; practicing OOP. I'm trying to replace a value in a .csv table and everything seems to be going well until the end where the code simply doesnt change anything. I've tried debugging as shown further down and it shows the values im using are correct def test2(fname, ...
[ " def test2(fname, lname, amount):\n # Open csv\n with open('clients.csv','r') as f:\n read = csv.reader(f)\n\n\n # Find row index of client\n for index, row in enumerate(read):\n if fname in row[0]:\n if lname in row[1]:\n i = index - 1\n ...
[ 0 ]
[]
[]
[ "csv", "pandas", "python" ]
stackoverflow_0074255316_csv_pandas_python.txt
Q: pygame.display.set_icon(pygame.image obj) doesn't work in python 3.9.1 I was using python 3.8 and everything was ok, but when I updated my python to 3.9 I figured out that pygame.display.set_icon doesn't work :/ (No errors, No warnings) Here's the code: import pygame pygame.init() scr = pygame.display.set_mode((0,...
pygame.display.set_icon(pygame.image obj) doesn't work in python 3.9.1
I was using python 3.8 and everything was ok, but when I updated my python to 3.9 I figured out that pygame.display.set_icon doesn't work :/ (No errors, No warnings) Here's the code: import pygame pygame.init() scr = pygame.display.set_mode((0, 0)) fps = pygame.time.Clock() pygame.display.set_caption("Caption Here!") p...
[ "See pygame.display.set_icon():\n\n[...] Some systems do not allow the window icon to change after it has been shown. This function can be called before pygame.display.set_mode() to create the icon before the display mode is set.\n\nSet the icon before pygame.display.set_mode((0, 0)):\npygame.display.set_icon(pygam...
[ 1, 0, 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0065454856_pygame_python.txt
Q: Why python didn't see nltk module? I cant run my programm because nltk module is missing but i just intstalled it and it just right here in the folder I tried to reinstall my python, and tried to change python interpreter but nothing worked A: How have you actually installed nltk? You can check if it's actually ...
Why python didn't see nltk module?
I cant run my programm because nltk module is missing but i just intstalled it and it just right here in the folder I tried to reinstall my python, and tried to change python interpreter but nothing worked
[ "How have you actually installed nltk?\nYou can check if it's actually installed with pip freeze.\nWhat might be happening here is that you could have another version of python installed, so make sure that you actually call the same interpreter for checking and installing with pip, in your case E:/pythonProject1/Sc...
[ 0 ]
[]
[]
[ "nltk", "pycharm", "python" ]
stackoverflow_0074256500_nltk_pycharm_python.txt
Q: How to capture interlaced stdin and stdout from a Python subprocess I am trying to write a Python script that automatically grades a Python script submitted by a student, where the student's script uses the input() function to get some information from the user. Suppose the student's script is something simple lik...
How to capture interlaced stdin and stdout from a Python subprocess
I am trying to write a Python script that automatically grades a Python script submitted by a student, where the student's script uses the input() function to get some information from the user. Suppose the student's script is something simple like this: name = input('Enter your name: ') print(f'Hello {name}!') The po...
[ "Here's the solution I came up with. I expect there is a more elegant way to do it, but it works on the Ubuntu Linux computer that the automated test scripts run on. I have not tried it on Windows, but I believe it will not work since os.set_blocking() is only supported on Unix per the os module documentation.\nimp...
[ 0 ]
[]
[]
[ "python", "stdin", "stdout", "subprocess" ]
stackoverflow_0074248637_python_stdin_stdout_subprocess.txt
Q: Removing invalid values to correctly recreate cumulative data in pandas I have a data set with statistics that I collect from text. The processing method sometimes does not work correctly, and I need to correct the output data. I know they are supposed to be cumulative, but sometimes I get incorrect data. Time ser...
Removing invalid values to correctly recreate cumulative data in pandas
I have a data set with statistics that I collect from text. The processing method sometimes does not work correctly, and I need to correct the output data. I know they are supposed to be cumulative, but sometimes I get incorrect data. Time series data that should accumulate over time. Right now I'm getting the followin...
[ "You can do that using numpy:\ndf['value'] = np.where(df['value'] < df['value'][0], np.nan, df['value'])\n\nOutput:\n date value\n0 2021-07-20 21347.0\n1 2021-07-24 21739.0\n2 2021-08-02 nan\n3 2021-08-03 nan\n4 2021-08-06 22947.0\n5 2021-08-17 nan\n\n", "Can you try this:\nimport nump...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074256483_pandas_python.txt
Q: Why am I receiving "invalid color argument" error? I am following this tutorial building checkers game but I am receiving this error while building the Checkers piece in the piece.py module. I am trying to print the RED pieces and gives me an error with the self.color (see error below). I have followed everything ...
Why am I receiving "invalid color argument" error?
I am following this tutorial building checkers game but I am receiving this error while building the Checkers piece in the piece.py module. I am trying to print the RED pieces and gives me an error with the self.color (see error below). I have followed everything as closely as possible, but I still receive the error. t...
[ "I think that instead of importing the colors, as you did from checkers.constants import BLACK, ROWS, RED, SQUARE_SIZE, COLS, WHITE , you should define them yourself by using RGB. Like this\n\nRED = (255, 0, 0)\n\n\nWHITE = (255, 255, 255)\n\n\nBLACK = (0, 0, 0)\n\n" ]
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074253214_pygame_python.txt
Q: Summarize price from items in dictionary I'm struggling with making the program to summarize price of the products. prices_and_their_products = { "Apple": 1, "Water": 2, "Grape": 3 } shopping_list = ['Apple', 'Water'] I want the program to print "3". The code I was trying to do it: total = 0 for parti...
Summarize price from items in dictionary
I'm struggling with making the program to summarize price of the products. prices_and_their_products = { "Apple": 1, "Water": 2, "Grape": 3 } shopping_list = ['Apple', 'Water'] I want the program to print "3". The code I was trying to do it: total = 0 for particular_items in shopping_list: total += pri...
[ "It seems to me the code you have now is fine. It does print 1 then 3 because print is indented inside of the for loop, so if you want it just to print 3 you could unindent the print statement so that it only runs after the loop.\n\n\n#!/usr/bin/env python\n\nprices_and_their_products = {\n \"Apple\": 1,\n \"...
[ 1, 0, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074256582_dictionary_list_python.txt
Q: How to export specific div from webpage to dataframe? I want to export a specific div from the webpage. In this case, I want to export div with id "producer-votes-wrapper"; this part of the page has all the numbers(data) I want to get. Using previous examples and questions, I tried to do it by myself, but could no...
How to export specific div from webpage to dataframe?
I want to export a specific div from the webpage. In this case, I want to export div with id "producer-votes-wrapper"; this part of the page has all the numbers(data) I want to get. Using previous examples and questions, I tried to do it by myself, but could not get the desired result. The current code looks like the f...
[ "You can use js2py/requests to get the list, for example:\nimport js2py\nimport requests\n\n\napi_url = \"https://eos.hyperion.eosrio.io/v2/state/get_voters?producer=eoseouldotio&limit=100\"\ndata = requests.get(api_url).json()\n\njs_func = \"\"\"\\\n function $(num) {\n\n var CHAIN = 'eos';\n var CORE...
[ 0 ]
[]
[]
[ "dataframe", "html_parsing", "pandas", "python", "python_3.x" ]
stackoverflow_0074256416_dataframe_html_parsing_pandas_python_python_3.x.txt
Q: Scrapy not Downloading Images Developer Environment Windows 11 PyCharm Community Edition 2021.3.1 Python 3.10 I am following this tutorial Download Images By Python and Scrapy and I cannot get my script to work. spider.py import scrapy class WikiSpider(scrapy.Spider): name = 'wiki' start_urls = ['https:...
Scrapy not Downloading Images
Developer Environment Windows 11 PyCharm Community Edition 2021.3.1 Python 3.10 I am following this tutorial Download Images By Python and Scrapy and I cannot get my script to work. spider.py import scrapy class WikiSpider(scrapy.Spider): name = 'wiki' start_urls = ['https://en.wikipedia.org/wiki/Real_Madri...
[ "You are close. The part that I think is causing is that you have not created the appropriate Field for the images results in your yielded dictionary.\nI would suggest using a custom scrapy Item with the fields preset, you can do this in the same file as your spider to make it easier, then you should just add all ...
[ 0 ]
[]
[]
[ "python", "scrapy", "web_scraping" ]
stackoverflow_0074250020_python_scrapy_web_scraping.txt
Q: How to pass several columns from a DataFrame all together in Word2Vec While using Word2Vec algorithm, how to pass several text columns from a pandas data frame all together for the model to train. Image showing columns present in DataFrame][1] [1]: https://i.stack.imgur.com/80iiq.png 'task' is the name of the data...
How to pass several columns from a DataFrame all together in Word2Vec
While using Word2Vec algorithm, how to pass several text columns from a pandas data frame all together for the model to train. Image showing columns present in DataFrame][1] [1]: https://i.stack.imgur.com/80iiq.png 'task' is the name of the dataframe. Code is as follows: import gensim from gensim import corpora, models...
[ "According to the documentation, you can pass a list of lists of tokens. That means, it would look like [[token, token, ...], [token, token, ...], ...] which is of the shape (N, 1).\nNow, since you have several columns, you have a few solutions to try:\n\nNot considering class column, having a feature dataset with ...
[ 0 ]
[]
[]
[ "dataframe", "nlp", "python", "vectorization", "word2vec" ]
stackoverflow_0071705100_dataframe_nlp_python_vectorization_word2vec.txt
Q: Creating quiz game with function does not update the global score variable I'm trying to code a quiz game, which every time you get a correct answer adds 1 point; at the end of the game the program prints out the number of points. The thing is, I'm trying to code it by using a function. def qea(x, y, z): if x ...
Creating quiz game with function does not update the global score variable
I'm trying to code a quiz game, which every time you get a correct answer adds 1 point; at the end of the game the program prints out the number of points. The thing is, I'm trying to code it by using a function. def qea(x, y, z): if x == y: print("Correct!") z += 1 else: print('Wrong!')...
[ "You should return the new value and assign it back to points:\ndef qea(x, y, z):\n if x == y:\n print(\"Correct!\")\n z += 1\n else:\n print('Wrong!')\n return z\n\npoints = 0\n\nquestion1 = input(\"Who is the president of USA?: \").upper()\nanswer1 = \"JOE BIDEN\"\npoints = qea(quest...
[ 1, 0 ]
[]
[]
[ "function", "global_variables", "python" ]
stackoverflow_0074256670_function_global_variables_python.txt
Q: How do I create a function that creates a list of an attribute from all objects inside a class? I need a function that collects a specific integer attribute common in all objects inside a class, to then add it to a list to later sum them all up. Note that the objects created are not part of the list originally, bu...
How do I create a function that creates a list of an attribute from all objects inside a class?
I need a function that collects a specific integer attribute common in all objects inside a class, to then add it to a list to later sum them all up. Note that the objects created are not part of the list originally, but created separately. class Phones: def __init__(self, ram): self.ram = ram def ram_...
[ "If you want Phones to be able to iterate over every phone object, you might want to define a class attribute that tracks all the instances of the class.\nclass Phones:\n all_phones = []\n\n def __init__(self, ram):\n self.ram = ram\n self.all_phones.append(self)\n\n @classmethod\n def ram...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074256742_python.txt
Q: How to keep consecutive rows based on values of two different columns in datatframe I have a dataframe : Blocks Response RT Name 1 7 True 4630 ya__79891 2 7 True 4610 ya__79891 3 6 True 4390 ya__798...
How to keep consecutive rows based on values of two different columns in datatframe
I have a dataframe : Blocks Response RT Name 1 7 True 4630 ya__79891 2 7 True 4610 ya__79891 3 6 True 4390 ya__79891 4 6 True 5190 ya__79891 5 6 ...
[ "Try this:\ndf[df.groupby(['Blocks', 'Response'])['RT'].transform('size') > 2]\n\nOutput:\n Blocks Response RT Name\n3 6 True 4390 ya__79891\n4 6 True 5190 ya__79891\n5 6 True 4260 ya__79891\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0074256639_dataframe_pandas_python_python_3.x.txt
Q: Implicit Differentiation Sympy I've been doing derivatives in sympy, and I didn't know how that would syntactically be written. I tried looking it up, but none of the solutions made sense. For example, if I'm trying to differentiate x**5 + y**2 + z**4 = 8xyz by computation, how would I do that? Would z be a symbol...
Implicit Differentiation Sympy
I've been doing derivatives in sympy, and I didn't know how that would syntactically be written. I tried looking it up, but none of the solutions made sense. For example, if I'm trying to differentiate x**5 + y**2 + z**4 = 8xyz by computation, how would I do that? Would z be a symbol, or a function like in regular deri...
[ "For two variables you can use idiff. \nIn your case, the simplest way is to set x and y to be functions of z, like\nx = Function('x')(z)\ny = Function('y')(z)\n\nThen normal diff(expr, z) will take the derivative correctly. \n", "You commented you used idiff, here is the corresponding code for those who want to ...
[ 7, 0 ]
[]
[]
[ "differentiation", "implicit", "python", "python_3.x", "sympy" ]
stackoverflow_0035449011_differentiation_implicit_python_python_3.x_sympy.txt
Q: How to randomly select a sample of data according to specified proportions in Python Pandas? I have DataFrame in Python Pandas like below: ID TG 111 0 222 0 333 1 444 1 555 0 ... ... Above DataFrame has 5 000 000 rows, with: 99.40 % -> 0 0.60% -> 1 And I need to randomly select sample of this data, so as...
How to randomly select a sample of data according to specified proportions in Python Pandas?
I have DataFrame in Python Pandas like below: ID TG 111 0 222 0 333 1 444 1 555 0 ... ... Above DataFrame has 5 000 000 rows, with: 99.40 % -> 0 0.60% -> 1 And I need to randomly select sample of this data, so as to have 5% of '1' in column TG. So as a result I need to have DataFrame with observ...
[ "I'm sure there is some more performant way but maybe this works using .sample? Based on a dataset of 5_000 rows.\nzeros = df.query(\"TG.eq(0)\")\nfrac = int(round(.05 * len(zeros), 0))\nones = df.query(\"TG.ne(0)\").sample(n=frac)\n\ndf = pd.concat([ones, zeros]).reset_index(drop=True)\nprint(df[\"TG\"].value_coun...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "random", "sample" ]
stackoverflow_0074256627_dataframe_pandas_python_random_sample.txt
Q: How to share sensitive data among programs while keeping the possibility of comparing them with other local data? Context As part of my studies, I am creating a bot capable of detecting scam messages, in Python 3. One of the problems I am facing is the detection of fraudulent websites. Currently, I have a list of ...
How to share sensitive data among programs while keeping the possibility of comparing them with other local data?
Context As part of my studies, I am creating a bot capable of detecting scam messages, in Python 3. One of the problems I am facing is the detection of fraudulent websites. Currently, I have a list of domain names saved in a CSV file, containing both known domains considered safe (discord.com, google.com, etc.), and kn...
[ "At the end I think I'll use yet another solution. I'm thinking of using the MySQL database to store domain names, but only use it in my script to synchronize to it, keeping a local CSV version.\nIn short, the workflow I'm imagining:\n\nI edit my SQL table when I want to add/remove items to it\nWhen the bot is laun...
[ 1 ]
[]
[]
[ "hash", "locality_sensitive_hash", "python", "security" ]
stackoverflow_0074249810_hash_locality_sensitive_hash_python_security.txt
Q: How to select elements in a Dataframe that is created from Global Temp View using Spark Sql I need to store an obect in Global Temp View and read values later using Spark Sql. I am getting an error while selecting from the dataframe which is created from the global temp view. Error Message: Job aborted due to stag...
How to select elements in a Dataframe that is created from Global Temp View using Spark Sql
I need to store an obect in Global Temp View and read values later using Spark Sql. I am getting an error while selecting from the dataframe which is created from the global temp view. Error Message: Job aborted due to stage failure: Task 15 in stage 8.0 failed 4 times, most recent failure: Lost task 15.3 in stage 8.0 ...
[ "You cannot convert a spark temp table into a dataframe. The spark temp table was created with a struct and you can't do the reverse while reading from it.\nMay be you can convert the dictionary into a json and then store it as a data frame into the temp table\n" ]
[ 0 ]
[]
[]
[ "dataframe", "dictionary", "pyspark", "python" ]
stackoverflow_0074256538_dataframe_dictionary_pyspark_python.txt
Q: Python function help, does someone can tell me why it doesent work? my task is to write a python program removes all characters or strings from a string (text) specified in a list (strings_list). I got it like this but this doesen't work. Anybody can tell me what i got wrong or did I use a wrong function? Thanks!!...
Python function help, does someone can tell me why it doesent work?
my task is to write a python program removes all characters or strings from a string (text) specified in a list (strings_list). I got it like this but this doesen't work. Anybody can tell me what i got wrong or did I use a wrong function? Thanks!! def remove_strings(text, strings_list): for strings_list in remove_s...
[ "\ndef removechar(text, strings_list):\n newstrings = []\n for i in strings_list:\n \n if text in i:\n newtext = \"\"\n newtext = i\n newtext = newtext.replace(text, \"\")\n newstrings.append(newtext)\n else:\n newstrings.append(i...
[ -1 ]
[]
[]
[ "function", "python" ]
stackoverflow_0074256782_function_python.txt
Q: Why Depth-First-Search code is not working in some cases? This is the graph So, I try DFS code like this # Using a Python dictionary to act as an adjacency list graph = { 'A' : ['B','C'], 'B' : ['D', 'E'], 'C' : ['G', 'H'], 'D' : [], 'E' : ['F'], 'G' : [], 'H' : ['I'], 'F' : [], 'I' : ['J'], 'J' : [] } visited =...
Why Depth-First-Search code is not working in some cases?
This is the graph So, I try DFS code like this # Using a Python dictionary to act as an adjacency list graph = { 'A' : ['B','C'], 'B' : ['D', 'E'], 'C' : ['G', 'H'], 'D' : [], 'E' : ['F'], 'G' : [], 'H' : ['I'], 'F' : [], 'I' : ['J'], 'J' : [] } visited = [] # Set to keep track of visited nodes of graph. visited_new ...
[ "With the way your code is written above, your function will only return a result if the original goal is in the neighbor list of the original node ('C' is in A's neighbor list so it hits if neighbour == goal: ... return. However, for the recursive calls you are not checking to see the result of dfs (which is not c...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074256728_python.txt
Q: Pycharm expected type 'optional[bytes]' got 'str' instead I am using rsplit to split up a path name, rootPath = os.path.abspath(__file__) rootPath = (rootPath.rsplit('/', 1)[0]).rsplit('/', 1)[0] But Pycharm warns, expected type optional [bytes], got str instead In python doc, it stated using sep as the delimi...
Pycharm expected type 'optional[bytes]' got 'str' instead
I am using rsplit to split up a path name, rootPath = os.path.abspath(__file__) rootPath = (rootPath.rsplit('/', 1)[0]).rsplit('/', 1)[0] But Pycharm warns, expected type optional [bytes], got str instead In python doc, it stated using sep as the delimiter string. So how to fix this?
[ "It seems like rootPath is being treated as a bytes object (a small bug maybe?) or the warning is for another part. \nIn general, what PyCharm and the error is essentially warning you about is that the parameter has to either be None or bytes. That's what Optional means, Optional[type] is either None or type which...
[ 12, 0, 0 ]
[]
[]
[ "pycharm", "python", "python_3.x", "split" ]
stackoverflow_0039447741_pycharm_python_python_3.x_split.txt
Q: Point Cloud transformation using Python I have a point cloud with around 75 million points and I have already read the data files using laspy and they are stored in an array that looks like [x y z] where x values are in a column, y values are in a column and z values are in another column. I also have a derived 3x...
Point Cloud transformation using Python
I have a point cloud with around 75 million points and I have already read the data files using laspy and they are stored in an array that looks like [x y z] where x values are in a column, y values are in a column and z values are in another column. I also have a derived 3x3 Rotation Matrix and a 3x1 Translation vecto...
[ "I am not sure if laspy outputs that data as NumPy arrays. If it doesn't then you would first convert your list of points into a numpy array. Next you can simply apply the transformation to the full matrix. You can try something like this:\npoint_cloud_array = np.array(point_cloud)\ntransformed_point_cloud = rotati...
[ 1 ]
[]
[]
[ "laspy", "point_clouds", "python", "transformation" ]
stackoverflow_0074256648_laspy_point_clouds_python_transformation.txt
Q: From several TXT create an excel book where each txt is a different sheet I am trying to read several TXT files, I make some modifications to them and then I convert them into a DataFrame with Pandas and there I also run some modification processes, so far everything is fine, everything works perfect, I do it thro...
From several TXT create an excel book where each txt is a different sheet
I am trying to read several TXT files, I make some modifications to them and then I convert them into a DataFrame with Pandas and there I also run some modification processes, so far everything is fine, everything works perfect, I do it through a for loop but at the moment of save the xlsx file and create the first she...
[ "I was able to solve my problem and here is the script:\nfrom netmiko import ConnectHandler\nfrom datetime import datetime\nimport re\nfrom pathlib import Path\nimport os\nimport pandas as pd\nfrom openpyxl import load_workbook\n\nruta = Path(\"E:\\Python\\Visual Studio Code Proyects\\M2M Real\\Archivos\")\n\ndef i...
[ 1, 0 ]
[]
[]
[ "excel", "pandas", "python" ]
stackoverflow_0074248207_excel_pandas_python.txt
Q: Selenium Crashes on Chrome Start I'm trying to make selenium open a user profile so i can automate stuff in my google accounts without having to login every time, with the code below i have managed to open chrome but as soon as it opens, it crashes, here's my code. (My OS is MacOS Ventura) My chromdriver and my Go...
Selenium Crashes on Chrome Start
I'm trying to make selenium open a user profile so i can automate stuff in my google accounts without having to login every time, with the code below i have managed to open chrome but as soon as it opens, it crashes, here's my code. (My OS is MacOS Ventura) My chromdriver and my Google Chrome are in the same version fr...
[ "The path provided for Profile 2 seems to be the original one located in library.\nIf your browser is open at the same time it can cause conflicts.\nI recommend to make a copy of the original folder and use it instead.\nIn case you don't know how to access it:\n\nFinder > Go > Press Option Key (Library appears) > L...
[ 1 ]
[]
[]
[ "google_chrome", "python", "selenium", "selenium_chromedriver", "selenium_webdriver" ]
stackoverflow_0074255604_google_chrome_python_selenium_selenium_chromedriver_selenium_webdriver.txt
Q: Error loading ASGI app. Attribute "app" not found in module "main" I installed FASTAPI and was running below mentioned code from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"} and am getting below mentioned error in console on executing the file (venv) D:...
Error loading ASGI app. Attribute "app" not found in module "main"
I installed FASTAPI and was running below mentioned code from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"} and am getting below mentioned error in console on executing the file (venv) D:\FASTAPI>uvicorn main:app --reload INFO: Will watch for changes in t...
[ "\nFirst look the project tree. The main.py file is under app directory.\n\nIn my project like this:\nfastapi \n -> app\n -> main.py\n\n\nCopy codes to main.py:\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n@app.get(\"/\")\nasync def root():\n return {\"message\": \"Hello World\"}\n\nRun the server:\...
[ 2, 1, 1, 0 ]
[ "your folder should be in C/:\nname src and then create main.pyenter image description here\n" ]
[ -1 ]
[ "fastapi", "python" ]
stackoverflow_0069952385_fastapi_python.txt
Q: pyspark: ValueError: Some of types cannot be determined after inferring I have a pandas data frame my_df, and my_df.dtypes gives us: ts int64 fieldA object fieldB object fieldC object fieldD object fieldE object dtype: object Then I am trying to convert the pan...
pyspark: ValueError: Some of types cannot be determined after inferring
I have a pandas data frame my_df, and my_df.dtypes gives us: ts int64 fieldA object fieldB object fieldC object fieldD object fieldE object dtype: object Then I am trying to convert the pandas data frame my_df to a spark data frame by doing below: spark_my_df = sc.c...
[ "In order to infer the field type, PySpark looks at the non-none records in each field. If a field only has None records, PySpark can not infer the type and will raise that error.\nManually defining a schema will resolve the issue\n>>> from pyspark.sql.types import StructType, StructField, StringType\n>>> schema = ...
[ 55, 16, 7, 4, 1, 0 ]
[]
[]
[ "pandas", "pyspark", "python", "python_2.7", "spark_dataframe" ]
stackoverflow_0040517553_pandas_pyspark_python_python_2.7_spark_dataframe.txt
Q: Django: Can I use objects.filter() for generic foreignkey? symbol.py class Symbol(BaseModel): name = models.CharField(max_length=30,) class Meta: abstract = True class StockSymbol(Symbol): market = models.CharField(max_length=10,) my_daily_price = GenericRelation(MyDailyPrice) daily_pric...
Django: Can I use objects.filter() for generic foreignkey?
symbol.py class Symbol(BaseModel): name = models.CharField(max_length=30,) class Meta: abstract = True class StockSymbol(Symbol): market = models.CharField(max_length=10,) my_daily_price = GenericRelation(MyDailyPrice) daily_price.py class DailyPrice(BaseModel): content_type = models.Fore...
[ "You can filter with content_type and object_id, instead of content_object.\nfrom django.contrib.admin.options import get_content_type_for_model\nsymbol = StockSymbol.objects.first()\nMyDailyPrice.objects.filter(content_type=get_content_type_for_model(symbol), object_id=symbol.pk)\n\n", "I wrapped up @Akash's ans...
[ 10, 0 ]
[]
[]
[ "django", "foreign_keys", "generic_foreign_key", "python" ]
stackoverflow_0048605567_django_foreign_keys_generic_foreign_key_python.txt
Q: Build the full path filename in Python I need to pass a file path name to a module. How do I build the file path from a directory name, base filename, and a file format string? The directory may or may not exist at the time of call. For example: dir_name='/home/me/dev/my_reports' base_filename='daily_report' form...
Build the full path filename in Python
I need to pass a file path name to a module. How do I build the file path from a directory name, base filename, and a file format string? The directory may or may not exist at the time of call. For example: dir_name='/home/me/dev/my_reports' base_filename='daily_report' format = 'pdf' I need to create a string '/home...
[ "This works fine:\nos.path.join(dir_name, base_filename + '.' + filename_suffix)\n\nKeep in mind that os.path.join() exists only because different operating systems use different path separator characters. It smooths over that difference so cross-platform code doesn't have to be cluttered with special cases for eac...
[ 404, 65, 32, 2, 0, 0, 0 ]
[]
[]
[ "filenames", "python" ]
stackoverflow_0007132861_filenames_python.txt
Q: Building individual classes, count and show in separate DF I use a DataFrame looking like this: Index Type Value 0 A 4 1 A 9 2 C 51 3 B 40 4 C 32 5 C 14 I want to classify the items from the DataFrame in the classes/ranges 0-1, 11-50, 51...
Building individual classes, count and show in separate DF
I use a DataFrame looking like this: Index Type Value 0 A 4 1 A 9 2 C 51 3 B 40 4 C 32 5 C 14 I want to classify the items from the DataFrame in the classes/ranges 0-1, 11-50, 51-100 and create a separate DataFrame which shows the amount of T...
[ "You can accomplish this in two lines:\ndf['class'] = pd.cut(df['Value'], [0, 10, 50, 100])\ndf.groupby('class')['Type'].value_counts().rename(\"count\").reset_index().pivot('class', 'Type', 'count').fillna(0).astype(int)\n\nThe first line creates the classes that you're after, and the second gives the counts. Your...
[ 0 ]
[]
[]
[ "dataframe", "histogram", "pandas", "python" ]
stackoverflow_0074256928_dataframe_histogram_pandas_python.txt
Q: Ylabel ticks position without object oriented format This is the code i wrote. I need to locate the ylabel of imshow (the image at top-right) at bottom as in the image, while leaving the yticks with 0 at bottom and 5 on top. Another way could be to develop all this in an object explicit format, but I'm really dumb...
Ylabel ticks position without object oriented format
This is the code i wrote. I need to locate the ylabel of imshow (the image at top-right) at bottom as in the image, while leaving the yticks with 0 at bottom and 5 on top. Another way could be to develop all this in an object explicit format, but I'm really dumb, so if you use it, please change all the plot positions s...
[ "There are some options:\nTo invert axis only: use extent in imshow. This option can change x axis too\nimage = plt.imshow(field_matrix, cmap=plt.cm.Blues, extent=(-0.2, 9.8, -0.2, 9.8))\n\nTo invert axis and plot: use origin in imshow\nimage = plt.imshow(field_matrix, cmap=plt.cm.Blues, origin='lower')\n\nOr, use ...
[ 0 ]
[]
[]
[ "label", "matplotlib", "python" ]
stackoverflow_0074255425_label_matplotlib_python.txt
Q: Run script at specific time with Python I want to run the following at 22:00 PM everyday using import datetime. I'm trying to use a codeRan boolean to trigger it, but I can't get it to work. It's always False: import datetime timeNow = datetime.datetime.now() # 2022-10-31 10:23:10.461374 timeHour = timeNow.strfti...
Run script at specific time with Python
I want to run the following at 22:00 PM everyday using import datetime. I'm trying to use a codeRan boolean to trigger it, but I can't get it to work. It's always False: import datetime timeNow = datetime.datetime.now() # 2022-10-31 10:23:10.461374 timeHour = timeNow.strftime("%H") # 22 timeFull = timeNow.strftime("%X...
[ "The code as you wrote it will run the code print(timeHour + \" That is correct!\") and print 22 That is correct! if your script is run between 10pm-11pm. However, you have not included a loop in your code, so you would need to use some external method to call the script frequently to check whether it is time to r...
[ 1, 0 ]
[]
[]
[ "date", "datetime", "loops", "python", "time" ]
stackoverflow_0074256876_date_datetime_loops_python_time.txt
Q: I Have 3 Variables NAME, DIRECTORY, FILE_EXTENSION how to make a file with this information? def createfile(name, location, extension): print(name, extension, location) I have this code and I need to make a file with these variables I have tried a couple of things but they never seemed to work. A: Here is a...
I Have 3 Variables NAME, DIRECTORY, FILE_EXTENSION how to make a file with this information?
def createfile(name, location, extension): print(name, extension, location) I have this code and I need to make a file with these variables I have tried a couple of things but they never seemed to work.
[ "Here is a code using tkinter to get the name of the folder by an Entry widget. The code focuses on pdf files, but can be substituted for any file type.\nThis function is called fisrt with the path of your file or your locations, passing the path as 'files' *arg.\ndef replace_slash(files):\n\n ficheros=[]\n\n ...
[ 0, 0 ]
[]
[]
[ "file", "operating_system", "python" ]
stackoverflow_0074256824_file_operating_system_python.txt
Q: How to extract .zst files into a pandas dataframe I'm a bit of a beginner when it comes to Python, but one of my projects from school needs me to perform classification algorithms on this reddit popularity dataset. The files are huge .zst files and can be found here: https://files.pushshift.io/reddit/submissions/ ...
How to extract .zst files into a pandas dataframe
I'm a bit of a beginner when it comes to Python, but one of my projects from school needs me to perform classification algorithms on this reddit popularity dataset. The files are huge .zst files and can be found here: https://files.pushshift.io/reddit/submissions/ Anyway, I'm just not sure how to extract this onto a d...
[ "The file has been compressed using Zstandard (https://github.com/facebook/zstd), a compression library. \nThe easiest thing to do for you will probably be to install python-zstandard (https://pypi.org/project/zstandard/) using\npip install zstandard\n\nand then in a python script run something like \nimport zstand...
[ 3, 2, 2, 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python", "zstd" ]
stackoverflow_0061067762_dataframe_pandas_python_zstd.txt
Q: Shape mismatch: if categories is an array, it has to be of shape (n_features) **Here is the code I'm trying to execute to encode the values of the first column of my data set using dummy values ** # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dat...
Shape mismatch: if categories is an array, it has to be of shape (n_features)
**Here is the code I'm trying to execute to encode the values of the first column of my data set using dummy values ** # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Data.csv') # divide dataset to dependent variable(feat...
[ "A more convenient way to encode categorical features is using pandas' facilities. I implement this as follows:\ndf = pd.DataFrame({'feature':['French', 'Germany', 'Germany', 'Spain']})\nlabelencoder = LabelEncoder()# Assigning numerical values and storing in another column\ndf['categorical_feature'] = labelencoder...
[ 0, 0 ]
[]
[]
[ "machine_learning", "one_hot_encoding", "python", "scikit_learn" ]
stackoverflow_0074237965_machine_learning_one_hot_encoding_python_scikit_learn.txt
Q: Shape mismatch: if categories is an array, it has to be of shape (n_features,) Here is the code I'm trying to execute to encode the values of the first column of my data set using dummy values. import numpy as py import matplotlib.pyplot as plt import pandas as pd DataSet = pd.read_csv('Data.csv') x=DataSet.ilo...
Shape mismatch: if categories is an array, it has to be of shape (n_features,)
Here is the code I'm trying to execute to encode the values of the first column of my data set using dummy values. import numpy as py import matplotlib.pyplot as plt import pandas as pd DataSet = pd.read_csv('Data.csv') x=DataSet.iloc[:, :-1].values y=DataSet.iloc[:,3].values from sklearn.impute import SimpleImpute...
[ "Your second doesn't seem to be a categorical features, you should only one_hot_encode features which can take a finite number of discrete value. Like the first column which can only take a limited number of value ('spain', 'germany', 'france')\nIf you only encode de the first column you can do:\nfrom sklearn.prepr...
[ 0, 0 ]
[]
[]
[ "anaconda", "data_science", "machine_learning", "python" ]
stackoverflow_0062633492_anaconda_data_science_machine_learning_python.txt
Q: Copying substring that starts with "C" and ends with all the values after "D" in one dataframe and putting the substring into a new dataframe The above photo is data stored in df_input. I would like extract the "C#D#" part from the 'Visit' column and place it into the column of a new dataframe I created (df_output...
Copying substring that starts with "C" and ends with all the values after "D" in one dataframe and putting the substring into a new dataframe
The above photo is data stored in df_input. I would like extract the "C#D#" part from the 'Visit' column and place it into the column of a new dataframe I created (df_output['VISIT']). Additionally, there could be up to two numeric values that follow after the "D". I'm not sure if I am supposed to use '.str.extract' a...
[ "You can use a simple regex to recognize your pattern and then you can apply a function to dataframe to apply the recognizer to the whole column:\nimport pandas as pd\nimport re\n\ndef extract(year):\n matches = re.findall('C\\dD\\d{1,2}', year)\n if matches:\n return matches[0] # Assuming you only wa...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "string", "substring" ]
stackoverflow_0074256971_dataframe_pandas_python_string_substring.txt
Q: Restoring db in odoo 14 Facing an error in Odoo 14 during the restoring process and also while running the server on the terminal. Surprisingly it can run on the web, just can't proceed with the login with an error when doing the same. Traceback (most recent call last): File "/home/me/usr/oishi_odoo14/addons/web...
Restoring db in odoo 14
Facing an error in Odoo 14 during the restoring process and also while running the server on the terminal. Surprisingly it can run on the web, just can't proceed with the login with an error when doing the same. Traceback (most recent call last): File "/home/me/usr/oishi_odoo14/addons/web/controllers/main.py", line 9...
[ "First approach for this issue is: to re-create the custom-field: (example: \"res_partner.gender\") in your custom module, in the corresponding model which _inherit=res_partner...\nAnother approach:\nI had a similar problem, because i had delete a custom-field from a model, but this field was still used in a view.\...
[ 0 ]
[]
[]
[ "odoo", "odoo_14", "postgresql", "python", "restore" ]
stackoverflow_0074223658_odoo_odoo_14_postgresql_python_restore.txt
Q: While loop wont stop in simple python number guessing game Here is my function # guess the number you chooses def number_guess_you(): import random bound = int(input('What is your number between? 1 - ? ')) valid_bound = isinstance(bound, int) and bound>1 while valid_bound==False: bound = i...
While loop wont stop in simple python number guessing game
Here is my function # guess the number you chooses def number_guess_you(): import random bound = int(input('What is your number between? 1 - ? ')) valid_bound = isinstance(bound, int) and bound>1 while valid_bound==False: bound = int(input(''' \nPLEASE SELECT AN INTEGER GREATER THAN 1 ...
[ "# guess the number you chooses\ndef number_guess_you():\n \n import random\n bound = int(input('What is your number between? 1 - ? '))\n valid_bound = isinstance(bound, int) and bound>1\n while valid_bound==False:\n bound = int(input('''\n \\nPLEASE SELECT AN INTEGER GREATER THAN 1\n ...
[ 0 ]
[]
[]
[ "numbers", "python", "python_3.x", "while_loop" ]
stackoverflow_0074256816_numbers_python_python_3.x_while_loop.txt
Q: How do I test an exception being raised in Python? I am trying to write an unit test to test a part of a method. I am trying to test the part where an Exception is thrown and a LoggableException is reraised. For the unittest to force an Exception thrown, I patch logging.info to throw an Exception. The current beha...
How do I test an exception being raised in Python?
I am trying to write an unit test to test a part of a method. I am trying to test the part where an Exception is thrown and a LoggableException is reraised. For the unittest to force an Exception thrown, I patch logging.info to throw an Exception. The current behavior is patched function throws an Exception (correct) ...
[ "You need to assert the raise of the exception, with unittest you can do it like with self.assertRaises.\nIn your case you can extend your test class from unittest.TestCase and do:\n with self.assertRaises(LoggableException):\n self.server.cat_work()\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x", "python_unittest", "unit_testing" ]
stackoverflow_0074257066_python_python_3.x_python_unittest_unit_testing.txt
Q: Flask server not accepting values from JS ajax function Python code - from flask import Flask from flask_cors import CORS import cgi app = Flask(__name__) CORS(app) form = cgi.FieldStorage() var1 = form.getvalue('var1') @app.route("/", methods=['GET', 'POST']) def apicall(): if len(var1)>1: return 'receiv...
Flask server not accepting values from JS ajax function
Python code - from flask import Flask from flask_cors import CORS import cgi app = Flask(__name__) CORS(app) form = cgi.FieldStorage() var1 = form.getvalue('var1') @app.route("/", methods=['GET', 'POST']) def apicall(): if len(var1)>1: return 'received value from JS function' if __name__ == "__main__": ap...
[ "If you follow the example here, then your python code should be something like\n@app.route(\"/\", methods=['GET', 'POST'])\ndef apicall():\n if request.method == 'POST':\n data = request.get_json() # Get all the data passed in (as JSON)\n var1 = data.get('var1', None)\n if var1 and len(var1...
[ 1 ]
[]
[]
[ "flask", "javascript", "python" ]
stackoverflow_0074255696_flask_javascript_python.txt
Q: Is there a way to merge point clouds attributes in python? I have two point clouds (.las file). The coordinates of points (x, y,z) are the same in both the data, but one dataset has intensity attribute, while the other one has classification attribute only. I would like to merge these information, and obtain a poi...
Is there a way to merge point clouds attributes in python?
I have two point clouds (.las file). The coordinates of points (x, y,z) are the same in both the data, but one dataset has intensity attribute, while the other one has classification attribute only. I would like to merge these information, and obtain a point cloud with x,y,z, intensity and classification attributes. I ...
[ "If it is the same exact point-cloud, then shouldn't the order be the same?\nIf the order is the same then you can just do something like:\nnew_pc = np.column_stack([point_cloud1, point_cloud2[:, classification_index])\n\nIf they are not in the exact same order initially, then just sort both of them out by the x,y,...
[ 0 ]
[]
[]
[ "las", "point_clouds", "python" ]
stackoverflow_0074178622_las_point_clouds_python.txt
Q: How can i fix concatenate tuple (not "list") to tuple I'm trying to create a minimum reproducible example, while doing so, i came across this error. How can i solve this? Traceback (most recent call last): File "<string>", line 22, in <module> File "<string>", line 10, in verified TypeError: can only concatenate...
How can i fix concatenate tuple (not "list") to tuple
I'm trying to create a minimum reproducible example, while doing so, i came across this error. How can i solve this? Traceback (most recent call last): File "<string>", line 22, in <module> File "<string>", line 10, in verified TypeError: can only concatenate tuple (not "list") to tuple import json # Python3 progra...
[ "You forgot to call the conversion function for some parameter in your function.\nI tested and corrected your code, call it this way:\nis_verified = verified(\n convert(data['k_signer']),\n data['d_pk'],\n convert(data['d_signer']),\n data['sig'],\n convert(data['addr']),\n convert(data['seed']),\...
[ 2, 0 ]
[]
[]
[ "list", "python", "tuples" ]
stackoverflow_0074257104_list_python_tuples.txt
Q: Grpc python SSLV3_ALERT_HANDSHAKE_FAILURE I'm working in a project which is based on Grpc. Nevertheless I have a problem when I try to connect to my service with the following code: import grpc from grpc_health.v1 import health_pb2 from grpc_health.v1 import health_pb2_grpc with open('ca_chain_pem_path', 'rb') as...
Grpc python SSLV3_ALERT_HANDSHAKE_FAILURE
I'm working in a project which is based on Grpc. Nevertheless I have a problem when I try to connect to my service with the following code: import grpc from grpc_health.v1 import health_pb2 from grpc_health.v1 import health_pb2_grpc with open('ca_chain_pem_path', 'rb') as f: ca = f.read() credentials = grpc.ssl_ch...
[ "I had the same issue with the same result.\nI've found that issue - grpcioo failing on TLS with ED25519 algorithm\nAs it's proposed in issue, I have reinstalled grcpio with that environment variable\nexport GRPC_PYTHON_BUILD_SYSTEM_OPENSSL=1\nand ssl error was gone.\n", "if it's a private certificate I think you...
[ 1, 0 ]
[]
[]
[ "grpc", "handshake", "openssl", "python" ]
stackoverflow_0071053456_grpc_handshake_openssl_python.txt
Q: Trying to figure out the equivalent of C++ arrays in Python My code is: for X in range(16): appleX = 0 middleTileX = -350 + (distance/2) appleX[X] += middleTileX + distance*X and I'm trying to get a list of 16 numbers and store them on appleX, I then want to run so that a randomizer will pick a random...
Trying to figure out the equivalent of C++ arrays in Python
My code is: for X in range(16): appleX = 0 middleTileX = -350 + (distance/2) appleX[X] += middleTileX + distance*X and I'm trying to get a list of 16 numbers and store them on appleX, I then want to run so that a randomizer will pick a random number on the list (let's say number 5) and then it will look on...
[ "You just need list comprehension.\n\nI'm trying to get a list of 16 numbers and store them on appleX, I\nthen want to run so that a randomizer will pick a random number on the\nlist (let's say number 5) and then it will look on the 5th stored\nnumber in the \"array\" or list in python.\n\nresult = [middleTitleX + ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074257131_python.txt
Q: how would i insert a user's input into a Microsoft access through an Entry box screenshot of errorso I have successfully connected my Microsoft database to python and want to take the user's input through an entry box and insert the data into the database however I am struggling with doing so. this is my code from...
how would i insert a user's input into a Microsoft access through an Entry box
screenshot of errorso I have successfully connected my Microsoft database to python and want to take the user's input through an entry box and insert the data into the database however I am struggling with doing so. this is my code from tkinter import* import tkinter as tk from tkinter import ttk from re import S impor...
[ "When you run into problems where you can't receive the output of a function, one option typically is to modify some mutable data type (either list, dict or by defining a global variable which in reality is modifying the mtuable globals() dict. This technique would look something like\nshared = {\"name\": None}\nde...
[ 0 ]
[]
[]
[ "ms_access", "pyodbc", "python", "tkinter" ]
stackoverflow_0074257049_ms_access_pyodbc_python_tkinter.txt
Q: The Multi indexing here is not clear where it starts, or maybe i do not understand it well I need to understand the slicing in multiIndexing, for example: health_data subject Bob Guido Sue type HR Temp HR Temp HR Temp year visit 2013 1 31.0 38.7 32.0 36.7 35.0 37.2 2 44.0 37.7 50.0 35.0 29.0 36.7 2014 1 30.0 37.4...
The Multi indexing here is not clear where it starts, or maybe i do not understand it well
I need to understand the slicing in multiIndexing, for example: health_data subject Bob Guido Sue type HR Temp HR Temp HR Temp year visit 2013 1 31.0 38.7 32.0 36.7 35.0 37.2 2 44.0 37.7 50.0 35.0 29.0 36.7 2014 1 30.0 37.4 39.0 37.8 61.0 36.9 2 47.0 37.8 48.0 37.3 51.0 36.5 And by doing the fo...
[ "If I interpret your data correctly, we can rebuild your df as follows, using pd.MultiIndex.from_tuples and the regular df constructor pd.DataFrame, to gain some clarity about its structure:\nimport pandas as pd\nimport numpy as np\n\ntuples_columns = [('Bob', 'HR'), ('Bob', 'Temp'), ('Guido', 'HR'), \n ...
[ 2 ]
[]
[]
[ "multi_index", "pandas", "python" ]
stackoverflow_0074256968_multi_index_pandas_python.txt
Q: How do I get access to the numbers or score that i've given the words in my dictionary This is the code: word_count = {} with open(file, "r") as fi: for line in fi: words = line.split() for word in words: word = word.lower() if word not in word_count: ...
How do I get access to the numbers or score that i've given the words in my dictionary
This is the code: word_count = {} with open(file, "r") as fi: for line in fi: words = line.split() for word in words: word = word.lower() if word not in word_count: word_count[word] = 0 word_count[word] += 1 print(word_count) Output:...
[ "You should use the dict.values() method. Like this:\nword_freq = {'thou': 2, 'ancient,': 1, 'free': 1}\n\navg = sum(word_freq.values())/len(word_freq)\nprint(avg)\n\n", "\nI want to somehow get access to the numbers 2,1 and 1 so I can get the\naverage usage of the words in my text file. So my question is how do ...
[ 1, 0, 0, 0 ]
[]
[]
[ "average", "dictionary", "python", "text_files", "typeerror" ]
stackoverflow_0074257191_average_dictionary_python_text_files_typeerror.txt
Q: Replace string in list using dictionary in Python How can I replace string in list using dictionary? I have text = ["h#**o+","+&&&orld"] replacement = {"#":"e","*":"l","+":"w","&":""} I want: correct = ["Hellow World"] I have try: def correct(text,replacement): for word, replacement in replaceme...
Replace string in list using dictionary in Python
How can I replace string in list using dictionary? I have text = ["h#**o+","+&&&orld"] replacement = {"#":"e","*":"l","+":"w","&":""} I want: correct = ["Hellow World"] I have try: def correct(text,replacement): for word, replacement in replacement.items(): text = text.replace(word, replaceme...
[ "What you have is mostly correct except your correct function seems to be wanting to correct only a single str (e.g. \"h#**o+\" => \"hellow\"), whereas your variable text is currently a list or strs. So if you want to get \"hellow world\" you need to call correct multiple times to get a list of corrected words, wh...
[ 4, 2, 0 ]
[]
[]
[ "dictionary", "list", "python", "replace", "string" ]
stackoverflow_0074256470_dictionary_list_python_replace_string.txt
Q: Is there a way to stop user credentials caching with Spotipy? I am using spotipy to create a small web app. I have everything working fine, but would like to implement a log out / log in button. From looking through the spotipy and spotify endpoint api docs, i can't seem to find a way to stop the users credentials...
Is there a way to stop user credentials caching with Spotipy?
I am using spotipy to create a small web app. I have everything working fine, but would like to implement a log out / log in button. From looking through the spotipy and spotify endpoint api docs, i can't seem to find a way to stop the users credentials caching. Does anyone know of a way to do this? i would like it so ...
[ "almost two years late, so sorry, but it would appear the only way to stop using the .cache file is the following\nwhen you make your oauth object, in a function,\ndef spotipy_oauth(ci, cs, ru, sc):\n return spotipy.oauth2.SpotifyOAuth(client_id=ci, client_secret=cs, redirect_uri=ru, scope=sc)\n\nyou get the acc...
[ 0 ]
[]
[]
[ "flask", "python", "spotify", "spotipy" ]
stackoverflow_0065415311_flask_python_spotify_spotipy.txt
Q: I'm trying to run a simple print script in Visual Studio Code with Python, but nothing shows up in terminal or output I've tried doing so much stuff, but nothing works. My code and directory: Terminal after I try running it: I tried disabling some extensions. Nothing I tried running the command in my terminal. N...
I'm trying to run a simple print script in Visual Studio Code with Python, but nothing shows up in terminal or output
I've tried doing so much stuff, but nothing works. My code and directory: Terminal after I try running it: I tried disabling some extensions. Nothing I tried running the command in my terminal. Nothing. I tried looking at other posts about it. Nothing.
[ "If you run the script from VSCode UI, you should see the output in OUTPUT tab. In your screenshot you are checking in TERMINAL\noutput tab check\nNonetheless, as others have mentioned, you can execute it through the TERMINAL as well, typing python hi.py\n", "You are not running your terminal in the same path whe...
[ 0, 0 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0074257129_python_visual_studio_code.txt
Q: jinja2.exceptions.UndefinedError: 'forms.SignupForm object' has no attribute 'hidden_tag' This code used to work and has since become deprecated. It is now giving an error" "jinja2.exceptions.UndefinedError: 'forms.SignupForm object' has no attribute 'hidden_tag'". I have been researching and can't seem to identif...
jinja2.exceptions.UndefinedError: 'forms.SignupForm object' has no attribute 'hidden_tag'
This code used to work and has since become deprecated. It is now giving an error" "jinja2.exceptions.UndefinedError: 'forms.SignupForm object' has no attribute 'hidden_tag'". I have been researching and can't seem to identify what has changed. Can anyone help? **forms.py** from flask_wtf import Form from wtforms impor...
[ "You code looks fine except for the Form Object, try to change the import line to:\nfrom flask_wtf import FlaskForm\n\nin you form classes inherit from FaskForm instead of the Form class.\nIn order to generate the csrf token, you must have a secret key, this is usually the same as your Flask app secret key. If you ...
[ 0 ]
[]
[]
[ "flask", "flask_wtforms", "python" ]
stackoverflow_0074257194_flask_flask_wtforms_python.txt
Q: Selenium and Scrapy Cannot Load a Page Completely I am trying to scrape the products information from vmware official website using selenium plus scrapy. But I never can load the page completely with code, even with longer waiting time. Here is my script. class VmwareSpiderSpider(scrapy.Spider): name = 'vmwar...
Selenium and Scrapy Cannot Load a Page Completely
I am trying to scrape the products information from vmware official website using selenium plus scrapy. But I never can load the page completely with code, even with longer waiting time. Here is my script. class VmwareSpiderSpider(scrapy.Spider): name = 'vmware_spider' allowed_domains = ['customerconnect.vmwar...
[ "All the required datum are loaded via API calls json response as get method. If you press F12 then you will find network tab which is selected and refresh the url from far top left circular icon and click on XHR,name, headers, preview and you will get everything about API url\nimport scrapy\nimport json\n \nAPI_UR...
[ 1 ]
[]
[]
[ "python", "scrapy", "selenium", "web_scraping" ]
stackoverflow_0074257257_python_scrapy_selenium_web_scraping.txt
Q: how to get string value out of tf.tensor which dtype is string I want to use tf.data.Dataset.list_files function to feed my datasets. But because the file is not image, I need to load it manually. The problem is tf.data.Dataset.list_files pass variable as tf.tensor and my python code can not handle tensor. How ca...
how to get string value out of tf.tensor which dtype is string
I want to use tf.data.Dataset.list_files function to feed my datasets. But because the file is not image, I need to load it manually. The problem is tf.data.Dataset.list_files pass variable as tf.tensor and my python code can not handle tensor. How can I get string value from tf.tensor. The dtype is string. train_data...
[ "You can use tf.py_func to wrap load_audio_file().\nimport tensorflow as tf\n\ntf.enable_eager_execution()\n\ndef load_audio_file(file_path):\n # you should decode bytes type to string type\n print(\"file_path: \",bytes.decode(file_path),type(bytes.decode(file_path)))\n return file_path\n\ntrain_dataset = ...
[ 33, 0, 0, 0 ]
[]
[]
[ "python", "tensorflow", "tensorflow_datasets" ]
stackoverflow_0056122670_python_tensorflow_tensorflow_datasets.txt
Q: How to calculate the explicit price matching various Bollinger band standard deviation levels? Utilizing 1min data I want to know the exact price at which the various standard deviation levels equal that price. Bollinger Bands commonly use 2 standard deviations and a rolling period of 20 to calculate the current l...
How to calculate the explicit price matching various Bollinger band standard deviation levels?
Utilizing 1min data I want to know the exact price at which the various standard deviation levels equal that price. Bollinger Bands commonly use 2 standard deviations and a rolling period of 20 to calculate the current level for these standard deviations. What I'm trying to do is take the previous 19 1min candles to ge...
[ "Your system of three equations is infeasible for real-valued prices above abs(stddev_level) > 4.36, so the solver returns complex solutions.\nYou can see this just by trying a range of prices:\nfor p in range(3900,3950,2):\n test_price = temp_minute_list\n test_price[19] = p\n x = np.array(test_price)\n ...
[ 0 ]
[]
[]
[ "finance", "python", "sympy" ]
stackoverflow_0074257196_finance_python_sympy.txt
Q: Big Query query selecting by range of columns as one might in Python In python I can select a ranges of columns to create a new dataset. Can this be done in Big Query? For example, I have a table with many columns (57), and I want to query columns 6-40. In python I can df = df.iloc[:, 6:41]. As far as I can tell, ...
Big Query query selecting by range of columns as one might in Python
In python I can select a ranges of columns to create a new dataset. Can this be done in Big Query? For example, I have a table with many columns (57), and I want to query columns 6-40. In python I can df = df.iloc[:, 6:41]. As far as I can tell, all I can do in Big Query use a select statement that lists by name, colum...
[ "Consider below - this is the closest I can think of\nexecute immediate format('select %s from your_table', (\n select string_agg(split(kv, ':')[offset(0)], ',' order by offset) list\n from (select * from your_table limit 1) t, \n unnest([translate(to_json_string(t), '{}\"', '')]) rec,\n unnest(split(rec)) kv ...
[ 1 ]
[]
[]
[ "google_bigquery", "python", "sql" ]
stackoverflow_0074238358_google_bigquery_python_sql.txt
Q: Search records between two dataframes python Good afternoon, I am new to programming, I would like to ask you for help with the following: I have two DataFrames df1 and df2 df1 is composed of the following registers: ID Nombre Teléfono C0001 ANTONIO 345 C0002 LAURA 326 C0003 CAMILO 289 C0004 JOSE 245 df2 is ...
Search records between two dataframes python
Good afternoon, I am new to programming, I would like to ask you for help with the following: I have two DataFrames df1 and df2 df1 is composed of the following registers: ID Nombre Teléfono C0001 ANTONIO 345 C0002 LAURA 326 C0003 CAMILO 289 C0004 JOSE 245 df2 is made up of these other registers: ...
[ "Combine Series.isin with the unary ~ operator to invert the boolean values, and use the series to select from df2:\ndf2[~df2.ID.isin(df1.ID)]\n\n ID Nombre Teléfono\n4 C0005 NATALIA 345\n5 C0006 ERIKA 326\n6 C0007 LINA 289\n7 C0008 CRISTINA 245\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "isin", "pandas", "python" ]
stackoverflow_0074257368_dataframe_isin_pandas_python.txt
Q: AttributeError: 'dict' object has no attribute 'distinct' I have a bson file, and i dont know what have inside of the file. So, a read the file. And now, i still trying to found the value of each key, but not is easy. Because, i receive the messange: AttributeError: 'dict' object has no attribute 'distinct' What ...
AttributeError: 'dict' object has no attribute 'distinct'
I have a bson file, and i dont know what have inside of the file. So, a read the file. And now, i still trying to found the value of each key, but not is easy. Because, i receive the messange: AttributeError: 'dict' object has no attribute 'distinct' What i do? Am I writing more code? What am I doing wrong?
[ "When I do understand your question, read_content['_id'] should suffice.\nSo the code should be:\nread_content = bson.json_util.loads(content)\nprint(read_content['_id'])\n\n" ]
[ 0 ]
[]
[]
[ "bson", "dictionary", "python" ]
stackoverflow_0074257360_bson_dictionary_python.txt
Q: How to implement histogram equalization for images in tensorflow? I'm a Deep Learning and Tensorflow novice. I'm trying to modify cifar10 tensorflow tutorial for using it with faces input images. How can I compute histogram equalization? Is it possible to wrap solutions similar to the one in: Histogram equalizatio...
How to implement histogram equalization for images in tensorflow?
I'm a Deep Learning and Tensorflow novice. I'm trying to modify cifar10 tensorflow tutorial for using it with faces input images. How can I compute histogram equalization? Is it possible to wrap solutions similar to the one in: Histogram equalization of grayscale images with NumPy ?
[ "For grayscale uint8 image you can use something like this:\ndef tf_equalize_histogram(image):\n values_range = tf.constant([0., 255.], dtype = tf.float32)\n histogram = tf.histogram_fixed_width(tf.to_float(image), values_range, 256)\n cdf = tf.cumsum(histogram)\n cdf_min = cdf[tf.reduce_min(tf.where(tf...
[ 10, 0 ]
[]
[]
[ "image_processing", "python", "tensorflow" ]
stackoverflow_0042835247_image_processing_python_tensorflow.txt
Q: Why node-fetch and cURL get response with status 200 but python requests returns with 403? I've opened the https://www.investing.com/economic-calendar/ page and then with the network tab in dev tools opened, pressed the "Next Week" button on the page. Then just copied the displayed query as cURL. So now, when I r...
Why node-fetch and cURL get response with status 200 but python requests returns with 403?
I've opened the https://www.investing.com/economic-calendar/ page and then with the network tab in dev tools opened, pressed the "Next Week" button on the page. Then just copied the displayed query as cURL. So now, when I running the following cURL request in the terminal: curl 'https://www.investing.com/economic-cale...
[]
[]
[ "No Luck bro. i have tried it in curlconverter as well but have not able to run it yet. But if you are using any unix systems , you can try running the below code though. (If windows, you can anyway use cygwin)\n#One option:\nimport os\nresult = os.popen('''curl 'https://www.investing.com/economic-calendar/Service/...
[ -2 ]
[ "curl", "http_status_code_403", "python", "python_3.x", "web_scraping" ]
stackoverflow_0074257170_curl_http_status_code_403_python_python_3.x_web_scraping.txt
Q: Generating txt file from HTML file using python Have been trying to implement the HTML to plain text conversion and had some issues so far. From an HTML format like this: <style> .first{ text-align: center; } .second{ margin-left: 20px; } </style> <p class="first">Hello world to all</p> <p class="second">Wha...
Generating txt file from HTML file using python
Have been trying to implement the HTML to plain text conversion and had some issues so far. From an HTML format like this: <style> .first{ text-align: center; } .second{ margin-left: 20px; } </style> <p class="first">Hello world to all</p> <p class="second">What is this</p> I should get an output as: ...
[ "[I can't comment as to which library is best, but personally I am more familiar with bs4, so the solution utilizes BeautifulSoup.] I don't know of any modules that already have something for this [beyond those you have already tried], but the function below can probably be edited/configured for what you need:\n# w...
[ 0 ]
[]
[]
[ "beautifulsoup", "css", "python", "python_3.x" ]
stackoverflow_0074249278_beautifulsoup_css_python_python_3.x.txt
Q: Dimension error by using Patch Embedding for video processing I am working on one of the transformer models that has been proposed for video classification. My input tensor has the shape of [batch=16 ,channels=3 ,frames=16, H=224, W=224] and for applying the patch embedding on the input tensor it uses the followin...
Dimension error by using Patch Embedding for video processing
I am working on one of the transformer models that has been proposed for video classification. My input tensor has the shape of [batch=16 ,channels=3 ,frames=16, H=224, W=224] and for applying the patch embedding on the input tensor it uses the following scenario: patch_dim = in_channels * patch_size ** 2 self.to_patch...
[ "The input tensor has shape [batch=16, channels=3, frames=16, H=224, W=224], while Rearrange expects dimensions in order [ b t c h w ]. You expect channels but pass frames. This leads to a last dimension of (p1 * p2 * c) = 16 * 16 * 16 = 4096.\nPlease try to align positions of channels and frames:\nfrom torch impor...
[ 4 ]
[]
[]
[ "einops", "python", "pytorch" ]
stackoverflow_0074237285_einops_python_pytorch.txt
Q: AWS: Error Describing ECR Images When Deploying Lambda in Terraform I'm trying to deploy a lambda as a container using Terraform. Here is my project structure: project ├── README.md ├── lambda_functions │ ├── Dockerfile │ └── index.py ├── terraform └── lambda.tf I am running terraform init, terraform plan...
AWS: Error Describing ECR Images When Deploying Lambda in Terraform
I'm trying to deploy a lambda as a container using Terraform. Here is my project structure: project ├── README.md ├── lambda_functions │ ├── Dockerfile │ └── index.py ├── terraform └── lambda.tf I am running terraform init, terraform plan and terraform apply from the terraform folder. variable "region" { def...
[ "You may want to specify the interpreter explicitly. In case you are on Windows, cmd will be used by default, which will stop execution after ecr get-login-password.\nAlso, you would can specify the workind directory for the script, so you don't need to do a change directory.\nresource \"null_resource\" \"ecr_image...
[ 3 ]
[]
[]
[ "amazon_web_services", "dockerfile", "infrastructure_as_code", "python", "terraform" ]
stackoverflow_0074257294_amazon_web_services_dockerfile_infrastructure_as_code_python_terraform.txt
Q: Saving cross section of 3d object by Trimesh - Python After obtaining the cross section of a 3D object having sphere holes inside it as shown in the picture below, I couldn't find a way to save it as either numpy array or any image format. I used the Trimesh code below to take the section: slice = tm_build.section...
Saving cross section of 3d object by Trimesh - Python
After obtaining the cross section of a 3D object having sphere holes inside it as shown in the picture below, I couldn't find a way to save it as either numpy array or any image format. I used the Trimesh code below to take the section: slice = tm_build.section(plane_origin=tm_build.centroid, plan...
[ "The following code snippet allows you to save your section as a png image file.\nimport io\n\nimport trimesh\nimport PIL.Image as Image\n\nmesh_path = r\"path\\to\\mesh\"\n\nmesh = trimesh.load_mesh(mesh_path, process=False, maintain_order=True)\nsection = mesh.section(plane_origin=[0, 0, 0], plane_normal=[0, 0, 1...
[ 0 ]
[]
[]
[ "3d", "mesh", "python", "trimesh" ]
stackoverflow_0074248100_3d_mesh_python_trimesh.txt
Q: My "IF " and Elif Statements are not Working So if and elif statements are not working def weight_converter(): print("Welcome to Weight Converter") operation = int(input(" 1. Gram to Pound \n 2. Pound into Gram")) if operation == " 1": gram_one = int(input("Grams needed to convert to pound: ")) pr...
My "IF " and Elif Statements are not Working
So if and elif statements are not working def weight_converter(): print("Welcome to Weight Converter") operation = int(input(" 1. Gram to Pound \n 2. Pound into Gram")) if operation == " 1": gram_one = int(input("Grams needed to convert to pound: ")) print("You have", gram_one * 453.57,"pounds") eli...
[ "Your code snippet should be like one of the below code snippets:\ndef weight_converter():\n print(\"Welcome to Weight Converter\")\n operation = int(input(\" 1. Gram to Pound \\n 2. Pound into Gram\"))\n if operation == 1:\n gram_one = int(input(\"Grams needed to convert to pound: \"))\n print(\"You ha...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074257527_python.txt
Q: Hackerrank python stdin and stdout I am still trying to figure out python by myself I've been trying to solve Day 6 problem of hackerrank. Below is my approach to the problem, it is asking me to print the output in stdin and stdout and mine doesn't seem to work. Also, this code works on jupyter notebook giving me ...
Hackerrank python stdin and stdout
I am still trying to figure out python by myself I've been trying to solve Day 6 problem of hackerrank. Below is my approach to the problem, it is asking me to print the output in stdin and stdout and mine doesn't seem to work. Also, this code works on jupyter notebook giving me a right output, but the output is (hcekr...
[ "In your code snippet, the below lines cause that you'll not have good results:\n\nprint(numbers) # numbers doesn't return anything that you want to print!\n\n\nand\n\ndef numbers(): # you should pass x to your function\n\n\nYou just need to change your numbers() and main() functions as below:\ndef numbers(x):\n ...
[ 1 ]
[]
[]
[ "python", "stdin", "stdout" ]
stackoverflow_0074257551_python_stdin_stdout.txt
Q: Calling class function saved as attribute I have two classes and a "use" class function that performs multiple actions using the various attributes as the inputs so that I can just call the one function and get different results based on which class object is referenced. Where I am getting stuck is that I want to ...
Calling class function saved as attribute
I have two classes and a "use" class function that performs multiple actions using the various attributes as the inputs so that I can just call the one function and get different results based on which class object is referenced. Where I am getting stuck is that I want to have part of the use function check the 'effect...
[ "When accessing methods of classes C and P, you will only be able to access them from the class namespace. C.add will work, but add will not.\nFurthermore if you call c.add(4) it will be the same thing as calling C.add(c, 4) because it will implicitly pass the instance c into the class (C) method C.add. You cannot ...
[ 0, 0 ]
[]
[]
[ "attributes", "class", "function", "python" ]
stackoverflow_0074257586_attributes_class_function_python.txt
Q: What's wrong with my code?Valid Palindrome 2- Leetcode 680 Given a string s, return true if the s can be palindrome after deleting at most one character from it. Example 1: Input: s = "aba" Output: true Example 2: Input: s = "abca" Output: true Explanation: You could delete the character 'c'. Example 3: Input: s...
What's wrong with my code?Valid Palindrome 2- Leetcode 680
Given a string s, return true if the s can be palindrome after deleting at most one character from it. Example 1: Input: s = "aba" Output: true Example 2: Input: s = "abca" Output: true Explanation: You could delete the character 'c'. Example 3: Input: s = "abc" Output: false For this problem in leetcode my code has...
[ "Imagine the string 'abbab'. First you check index 0 and 4 with the values \"a\" and \"b\". They are not the same, but the \"b\" at index 1 matches the \"b\" at index 4. So you move forward to 1 and 4. Next is 2 and 3 and those are \"b\" and \"a\" and those don't match too. End of the story.\nabbab\nl r\n\nabbab\...
[ 0, 0 ]
[]
[]
[ "palindrome", "python", "reverse", "string" ]
stackoverflow_0074257374_palindrome_python_reverse_string.txt
Q: python's webbrowser launches IE, instead of default browser, on Windows relative path I'm attempting to launch a local html file from python in the default browser (right now my default is Google Chrome if I double-click on a .html file, Chrome launches.) When I use python's webbrowser.open(), IE launches instead,...
python's webbrowser launches IE, instead of default browser, on Windows relative path
I'm attempting to launch a local html file from python in the default browser (right now my default is Google Chrome if I double-click on a .html file, Chrome launches.) When I use python's webbrowser.open(), IE launches instead, with a blank address bar. Python 2.7.1 (r271:86832, Nov 27 2010, 17:19:03) [MSC v.1500 64 ...
[ "My main issue was a bad URL by attempting prepend file:// to a relative path. It can be fixed with this:\nwebbrowser.open('file://' + os.path.realpath(filename))\n\nUsing webbrowser.open will try multiple methods until one \"succeeds\", which is a loose definition.\nThe WindowsDefault class calls os.startfile() w...
[ 29, 16, 11, 3, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "browser", "default", "python", "python_webbrowser", "windows" ]
stackoverflow_0005916270_browser_default_python_python_webbrowser_windows.txt
Q: Wrong variable is loaded with os.getenv(), not the variable in .env .env STAGING_BUCKET=our-staging-bucket common.py (in same directory as .env) import os STAGING_BUCKET = os.getenv('STAGING_BUCKET') print(STAGING_BUCKET) When we run our airflow project locally, we receive a different value diff-staging-bucket f...
Wrong variable is loaded with os.getenv(), not the variable in .env
.env STAGING_BUCKET=our-staging-bucket common.py (in same directory as .env) import os STAGING_BUCKET = os.getenv('STAGING_BUCKET') print(STAGING_BUCKET) When we run our airflow project locally, we receive a different value diff-staging-bucket for our STAGING_BUCKET variable. We recently changed this variable in our ...
[ "os.getenv gets environment variables. Environment variables are usually set, in unix, by shell command such as export or setenv (depending on the shell). Those commands may be in shell init files, such as .bashrc or .cshrc\n.env is not one of them. What you put in that file has no specific meaning. It is just a fi...
[ 1, 1 ]
[]
[]
[ "environment_variables", "python" ]
stackoverflow_0074257513_environment_variables_python.txt
Q: Range function won't skip a value even when defined(Python) I am trying to find the odd numbers in a range of numbers, and adding them all up. I set my variable which is the range of numbers (5) I then made a function which had the for statement, looking for the numbers in range from 1 to 1+num(this is for inclu...
Range function won't skip a value even when defined(Python)
I am trying to find the odd numbers in a range of numbers, and adding them all up. I set my variable which is the range of numbers (5) I then made a function which had the for statement, looking for the numbers in range from 1 to 1+num(this is for including the number) and the comma after that to skip every other num...
[ "The third parameter in the range is the incremental value of the iterator which means that you want it to be 2, not 1, as you want to skip every other number. (By default its value is 1).\ndef sumOfOdds():\n sum = 0\n for i in range(1, 1+num, 2): # Here we set it to 2\n sum = sum+i\n \n print(...
[ 1, 1 ]
[ "To add to the provided response, I would add that there's a more pythonic way to write it using the reduce function:\ndef sumOfOdds():\n return reduce(lambda x, y: x + y, range(1, 1 + num, 2))\n\nAlso, let's say you'd like to pass the list to iterate as a parameter, you can use the following writing in Python\n...
[ -1 ]
[ "python", "range" ]
stackoverflow_0074257623_python_range.txt
Q: How can I convert a string which is a list of dictionaries into a list So I have a string "[{"type": "add", "qty": "24", "obj": "SPM", "location": "Piedmont Road."}]" How can I convert this into just a list of dictionary [{"type": "add", "qty": "24", "obj": "SPM", "location": "Piedmont Road."}] I tried ast.literal...
How can I convert a string which is a list of dictionaries into a list
So I have a string "[{"type": "add", "qty": "24", "obj": "SPM", "location": "Piedmont Road."}]" How can I convert this into just a list of dictionary [{"type": "add", "qty": "24", "obj": "SPM", "location": "Piedmont Road."}] I tried ast.literal_eval but I got invalid syntax error. EDIT: I had quotes in my string, remov...
[ "Is your input always a valid JSON string? If it is, you can use the standard JSON parser to convert your string into the result you seek:\nimport json\n\ndef main():\n inp = '[{\"type\": \"add\", \"qty\": \"24\", \"obj\": \"SPM\", \"location\": \"Piedmont Road.\"}]'\n print(json.loads(inp))\n\nmain()\n\nRes...
[ 1 ]
[]
[]
[ "dictionary", "list", "python", "string" ]
stackoverflow_0074257691_dictionary_list_python_string.txt
Q: How to use go to verify whether the plaintext password is the same as the salt md5 password? Python: # generate password ldap_salted_md5.hash("123456") # verify password ldap_salted_md5.verify("123456","{SMD5}991RjK3DQCT+ri/yxQB613Yuxdg=") # return true shell: # generate password slappasswd -h {SMD5} -s "123456"...
How to use go to verify whether the plaintext password is the same as the salt md5 password?
Python: # generate password ldap_salted_md5.hash("123456") # verify password ldap_salted_md5.verify("123456","{SMD5}991RjK3DQCT+ri/yxQB613Yuxdg=") # return true shell: # generate password slappasswd -h {SMD5} -s "123456" # return {SMD5}ZmDHoIiZZG/weuCNkLj189sFoPM= # verify password by python ldap_salted_md5.verify(...
[ " saltPassword := strings.Replace(user.Password, \"{SMD5}\", \"\", -1)\n decodeSaltPassword, _ := base64.StdEncoding.DecodeString(saltPassword)\n checksum := decodeSaltPassword[0:16]\n salt := decodeSaltPassword[16:]\n\n md5Ctx := md5.New()\n md5Ctx.Write([]byte(bindSimpleP...
[ 0 ]
[]
[]
[ "go", "python" ]
stackoverflow_0074233350_go_python.txt
Q: How to check the status of a website using selenium I'm working on some urls. I want to check the status of a website using selenium. I tried to check the status via urllib it says status is ok but sometime when I enter that url to selenium or check it in browser it's not working. so is there any method I can chec...
How to check the status of a website using selenium
I'm working on some urls. I want to check the status of a website using selenium. I tried to check the status via urllib it says status is ok but sometime when I enter that url to selenium or check it in browser it's not working. so is there any method I can check the status of a website with selenium so that I can kno...
[ "Selenium is a really heavy package, so steer away from using it unless you really have to use it. In this case, you don't need to use Selenium at all to check the status. All you need to do is use the requests library. Like this:\nimport requests\n\n\n# check the status of a list of websites\ndef check_status_urls...
[ 0 ]
[]
[]
[ "python", "python_3.x", "selenium", "selenium_webdriver" ]
stackoverflow_0074257682_python_python_3.x_selenium_selenium_webdriver.txt
Q: Fix TypeError: int() argument must be a string, a bytes-like object or a number, not 'Response' Trying to scrap text from different pages using a while loop. but getting TypeError: int() argument must be a string, a bytes-like object or a number, not 'Response' I am using beautiful soup and global variable to incr...
Fix TypeError: int() argument must be a string, a bytes-like object or a number, not 'Response'
Trying to scrap text from different pages using a while loop. but getting TypeError: int() argument must be a string, a bytes-like object or a number, not 'Response' I am using beautiful soup and global variable to increase the page number. import re from bs4 import BeautifulSoup , Comment import requests page = 1 tot...
[ "Don't use the same variable name for multiple variables.\nChange this\n page = requests.get(url)\n soup = BeautifulSoup(page.text, 'html.parser')\n\nto\n response = requests.get(url)\n soup = BeautifulSoup(response.text, 'html.parser')\n\nor something because you're already using page f...
[ 1 ]
[]
[]
[ "beautifulsoup", "global_variables", "python", "typeerror", "web_scraping" ]
stackoverflow_0074256442_beautifulsoup_global_variables_python_typeerror_web_scraping.txt
Q: python preprocess image of table with multiple colors using cv2 and pytesseract I'm having trouble preprocessing an image so that it's read correctly The multicolor is messing up the OCR, not sure which preprocessing steps to take so that it interprets it correctly. I need it to work for multiple colors too, as I...
python preprocess image of table with multiple colors using cv2 and pytesseract
I'm having trouble preprocessing an image so that it's read correctly The multicolor is messing up the OCR, not sure which preprocessing steps to take so that it interprets it correctly. I need it to work for multiple colors too, as I have more tables that have accents of blue, green, brown, etc... Here is my code so ...
[ "That's not a simple question. There are some whole PhD dissertations about this.\nBut, well, in your case, if all your images are of this kind, an adaptative threshold (behaving differently when background is \"greyish\" and when background is purple)\nOTSU is not at all convenient here. OTSU's postulate is that y...
[ 2 ]
[]
[]
[ "image_processing", "ocr", "opencv", "python", "tesseract" ]
stackoverflow_0074257404_image_processing_ocr_opencv_python_tesseract.txt
Q: can't import gdal in python? I have gdal installed and running on Ubuntu Jaunty but I can't run gdal2tiles because I get the error: Traceback (most recent call last): File "/usr/local/bin/gdal2tiles.py", line 42, in <module> import gdal ImportError: No module named gdal When I open python and type import gd...
can't import gdal in python?
I have gdal installed and running on Ubuntu Jaunty but I can't run gdal2tiles because I get the error: Traceback (most recent call last): File "/usr/local/bin/gdal2tiles.py", line 42, in <module> import gdal ImportError: No module named gdal When I open python and type import gdal I get the same error. I've set ...
[ "Ith seems to be a \"Python Path\" issue.  Python libraries are looked-up within a defined path. Try\nimport sys\nsys.path\n\nIf the directory where the gdal.py and related files is not in this list, then Python cannot find it. That's for the \"diagnostics\" part. To fix the situation, you have several options......
[ 15, 0 ]
[]
[]
[ "gdal", "python" ]
stackoverflow_0001538725_gdal_python.txt
Q: how do i display a grid of images (and have them them transparent until a keyboard key is pressed) any language. im wanting to make a program that will show what ability's im using in a game and have the picture of the ability's in a grid like ortholinear keyboard keys. it would be cool if the abilitys where tansp...
how do i display a grid of images (and have them them transparent until a keyboard key is pressed)
any language. im wanting to make a program that will show what ability's im using in a game and have the picture of the ability's in a grid like ortholinear keyboard keys. it would be cool if the abilitys where tansparent untill the key is pressed then go opaque until i let go. iv been trying to find out how to do it w...
[ "I suggest you give this link a read: Monitor keypress in tkinter without focus\nYou can refer to the answer that is not accepted, it shows how to accept key even if the program is not focus on.\nMy suggestion is that, you create a \"ability layout\" in tkinter, then you assign the key of the ability layout to the ...
[ 0 ]
[]
[]
[ "c++", "html", "javascript", "python" ]
stackoverflow_0074257626_c++_html_javascript_python.txt
Q: Repeat items in list and maintain order of occurrence until maximum length of list is reached I have a list of values in a list. The length of the list is variable from 1-5. If the list is less than the maximum_length then the list should be expanded, but should never exceed the max length. I want to expand the li...
Repeat items in list and maintain order of occurrence until maximum length of list is reached
I have a list of values in a list. The length of the list is variable from 1-5. If the list is less than the maximum_length then the list should be expanded, but should never exceed the max length. I want to expand the list incrementally to distribute the items across the list starting from the first item. Below is the...
[ "Use sort as explained in the comments and to maintain the distribution of the original list, the sort key should be the index of the element in your original list.\nmax_len = 5\ncurrent_list = ['1','2','3','4']\ninter = [current_list * max_len][0][:max_len] # assume we stick with your function\n# ['1', '2', '3',...
[ 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074257498_list_python.txt
Q: How to make a 3D plot (X, Y, Z), assigning Z values to X,Y ordered pairs? I am trying to plot a 3D chart, where my Z values would be assigned to each [X,Y] ordered pair. For example, these are my X, Y and Z values: X = [1,2,3,4,5] Y = [1,2,3,4,5] Z = [10, 20, 30, 40, 50, 10, 20, 30, 40, 50, 10, 20, 30, 40, 50, 10,...
How to make a 3D plot (X, Y, Z), assigning Z values to X,Y ordered pairs?
I am trying to plot a 3D chart, where my Z values would be assigned to each [X,Y] ordered pair. For example, these are my X, Y and Z values: X = [1,2,3,4,5] Y = [1,2,3,4,5] Z = [10, 20, 30, 40, 50, 10, 20, 30, 40, 50, 10, 20, 30, 40, 50, 10, 20, 30, 40, 50, 10, 20, 30, 40, 50,] And the Z values, correspond to the foll...
[ "you can do it using np.meshgrid\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nX = [1,2,3,4,5]\nY = [1,2,3,4,5]\nZ = [10, 20, 30, 40, 50, 10, 20, 30, 40, 50, 10, 20, 30, 40, 50, 10, 20, 30, 40, 50, 10, 20, 30, 40, 50,]\n\nxy = np.array(np.meshgrid(X,Y)).reshape(-1,...
[ 1, 0, 0 ]
[]
[]
[ "matplotlib", "mplot3d", "multidimensional_array", "numpy", "python" ]
stackoverflow_0061791309_matplotlib_mplot3d_multidimensional_array_numpy_python.txt
Q: Write nested lists in a csv file keeping the exact format I need to store nested lists in a csv file in the exact python format, i.e., [[1,2,3],[4,5,6],[7,8,9]]. I would like to stick to the csv module, so I wrote the simple code below: import csv matrix = [[1,2,3],[4,5,6],[7,8,9]] with open ('matrix.txt','w',ne...
Write nested lists in a csv file keeping the exact format
I need to store nested lists in a csv file in the exact python format, i.e., [[1,2,3],[4,5,6],[7,8,9]]. I would like to stick to the csv module, so I wrote the simple code below: import csv matrix = [[1,2,3],[4,5,6],[7,8,9]] with open ('matrix.txt','w',newline='') as f: content=csv.writer(f) content.writerow(...
[ "One of the easiest way if you are only looking to store your list in the file and not rely on csv module altogether would be to use simple file reader and writer provided by python.\nSee if this helps:\n>>> import ast\n>>> \n>>> # Step 1: Storage\n>>> matrix = [[1,2,3],[4,5,6],[7,8,9]]\n>>> # Storing matrix as str...
[ 1 ]
[]
[]
[ "csv", "nested_lists", "python" ]
stackoverflow_0074257518_csv_nested_lists_python.txt
Q: How do you use beautifulsoup and selenium to scrape html inside shadow dom? I'm trying to make an automation program to scrape part of a website. But this website is made out of javascript, and the part of the website I want to scrape is in a shadow dom. So I figured out that I should use selenium to go to that we...
How do you use beautifulsoup and selenium to scrape html inside shadow dom?
I'm trying to make an automation program to scrape part of a website. But this website is made out of javascript, and the part of the website I want to scrape is in a shadow dom. So I figured out that I should use selenium to go to that website and use this code to access elements in shadow dom def expand_shadow_elemen...
[ "You would use BeautifulSoup here as follows:\nsoup = BeautifulSoup(driver.page_source, 'lxml')\nmy_parts = soup.select('h3') # for example\n\n", "Most likely you need to wait for an element to show in the code so you need to set Implicit Wait or Explicit Wait, then once an element is loaded you can soup that p...
[ 0, 0, 0 ]
[]
[]
[ "beautifulsoup", "python", "selenium", "shadow_dom", "web_scraping" ]
stackoverflow_0074252734_beautifulsoup_python_selenium_shadow_dom_web_scraping.txt
Q: Why isn't on_message working with my discordpy code? My on_message code isn't working can someone tell me what's wrong or tell me what I did wrong? There are no errors in the console saying I did something wrong also the bot has permissions to send messages. @client.listen('on_message') async def on_message(messag...
Why isn't on_message working with my discordpy code?
My on_message code isn't working can someone tell me what's wrong or tell me what I did wrong? There are no errors in the console saying I did something wrong also the bot has permissions to send messages. @client.listen('on_message') async def on_message(message): if message.content.lower == "good morning": awai...
[ "message.content is a str, making message.content.lower a function which will never be equal to any of your string conditions.\nAdditionally, your code will be more efficient if you compute message.content.lower() once at the start of the function instead of once per conditional and you can also reduce the number o...
[ 1 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074257788_discord_discord.py_python.txt
Q: How do I get a function to identify a variable I've identified My program is trying to create a program that identifies a program that includes 3 functions: 1 to identify the length, 1 to make sure they're are not any spaces and 1 that makes sure that the program checks that you're using at least 1 number and lett...
How do I get a function to identify a variable I've identified
My program is trying to create a program that identifies a program that includes 3 functions: 1 to identify the length, 1 to make sure they're are not any spaces and 1 that makes sure that the program checks that you're using at least 1 number and letter. I basically have almost everything that I want, I'm just not und...
[ "Here is the kind of organization you need. The validation functions just do validation. It is up to the caller to decide what to do with the information.\ndef passLength(password):\n return 5 < len(password) < 15\n\ndef passSpace(password):\n return ' ' not in password\n\ndef main():\n while True:\n ...
[ 0 ]
[]
[]
[ "exception", "loops", "methods", "python" ]
stackoverflow_0074257791_exception_loops_methods_python.txt
Q: How to use loops to merge PDF files using Python from PyPDF2 import PdfFileReader, PdfFileWriter, PdfFileMerger merger =PdfFileMerger() merger.append(PdfFileReader(open("seperated1 PDF file556.pdf", 'rb'))) merger.append(PdfFileReader(open("seperated1 PDF file557.pdf", 'rb'))) merger.append(PdfFileReader(open("s...
How to use loops to merge PDF files using Python
from PyPDF2 import PdfFileReader, PdfFileWriter, PdfFileMerger merger =PdfFileMerger() merger.append(PdfFileReader(open("seperated1 PDF file556.pdf", 'rb'))) merger.append(PdfFileReader(open("seperated1 PDF file557.pdf", 'rb'))) merger.append(PdfFileReader(open("seperated1 PDF file558.pdf", 'rb'))) merger.append(PdfF...
[ "Did you mean this?\nfrom PyPDF2 import PdfFileReader, PdfFileWriter, PdfFileMerger\n\nmerger = PdfFileMerger()\n\nfor n in range(1,601):\n merger.append(PdfFileReader(open(f\"seperated1 PDF file{n}.pdf\", 'rb')))\n\nmerger.write(\"output01.pdf\")\n\n" ]
[ 0 ]
[]
[]
[ "merge", "pdf", "python" ]
stackoverflow_0074257823_merge_pdf_python.txt
Q: Will using F-strings to request data cause SQL injections? I'm unfamiliar with how injection attacks work. Will using f-strings in .execute() make me vulnerable to injection, if I only request data (not update/insert)? Similarly, let's say I'm trying to edit a column. How can I put in my own variables through .exe...
Will using F-strings to request data cause SQL injections?
I'm unfamiliar with how injection attacks work. Will using f-strings in .execute() make me vulnerable to injection, if I only request data (not update/insert)? Similarly, let's say I'm trying to edit a column. How can I put in my own variables through .execute() without an f-string? i.e. new_date = '30/10/2022' my_dat...
[ "Yes, it will leave you vulnerable, only if new_date can be changed by users. For example, let's say new_date is set to 30/10/2022; DROP DATABASE users -- by a user. The f-string will then resolve to\nUPDATE people SET birthday=30/10/2022; DROP DATABASE users -- WHERE name=\"Odin\"\n\nIf this query is sent to your ...
[ 1 ]
[]
[]
[ "database", "python", "sql_injection", "sqlite" ]
stackoverflow_0074257869_database_python_sql_injection_sqlite.txt
Q: How to redirect logged in user with url params? In my Django project I am trying to make the http://127.0.0.1:8000/ which is the home page to redirect to the Login in Page if user is not logged in however there is a user who is logged in I want http://127.0.0.1:8000/ to become http://127.0.0.1:8000/username/ I hav...
How to redirect logged in user with url params?
In my Django project I am trying to make the http://127.0.0.1:8000/ which is the home page to redirect to the Login in Page if user is not logged in however there is a user who is logged in I want http://127.0.0.1:8000/ to become http://127.0.0.1:8000/username/ I have tried different answers but nothing specific lead t...
[ "You can use settings.LOGIN_URL and settings.LOGIN_REDIRECT_URL so:\nclass LoginView(LoginView):\n template_name = 'login.html'\n login_url='login'\n\n def get_success_url(self):\n user=self.request.user.username\n return reverse('home', args=(user))\n\nIn settings.py:\nLOGIN_URL='some_app_na...
[ 9 ]
[]
[]
[ "django", "django_authentication", "django_urls", "django_views", "python" ]
stackoverflow_0074257818_django_django_authentication_django_urls_django_views_python.txt
Q: "RuntimeError: no running event loop" with "asyncio.get_running_loop()" in Python I'm trying to run the code below with asyncio.get_running_loop(): import asyncio async def test(): for _ in range(3): print("Test") await asyncio.sleep(1) loop = asyncio.get_running_loop() # Here loop.run_until...
"RuntimeError: no running event loop" with "asyncio.get_running_loop()" in Python
I'm trying to run the code below with asyncio.get_running_loop(): import asyncio async def test(): for _ in range(3): print("Test") await asyncio.sleep(1) loop = asyncio.get_running_loop() # Here loop.run_until_complete(test()) But, I got the error below: RuntimeError: no running event loop I...
[ "You got the error because asyncio.get_running_loop() tried to get a running event loop but there is no running event loop to get:\nasyncio.get_running_loop():\n\nReturn the running event loop in the current OS thread.\nIf there is no running event loop a RuntimeError is raised. This\nfunction can only be called fr...
[ 0 ]
[]
[]
[ "asynchronous", "event_loop", "python", "python_3.x", "python_asyncio" ]
stackoverflow_0074257941_asynchronous_event_loop_python_python_3.x_python_asyncio.txt
Q: How to specify the code to terminate if a specific word is entered as input? the code is about a game like hangman. It has 3 input : guess_num, length, guess. It should terminate the whole program if in any of that input the word stop or exit is entered.my break statement only works for each part of the program. ...
How to specify the code to terminate if a specific word is entered as input?
the code is about a game like hangman. It has 3 input : guess_num, length, guess. It should terminate the whole program if in any of that input the word stop or exit is entered.my break statement only works for each part of the program. for example each input only terminates its part. how can i code this to terminate ...
[ "You can use sys.exit() to terminate the program.\n import sys\n if guess.lower() == \"stop\" or guess.lower() == \"exit\":\n print(\"Game Ends!\")\n sys.exit()\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074257485_python.txt
Q: Removing dates within 'n' days of each other in Dictionaries I have a dictionary where the values of the dictionary are lists of dates. For each key, if, in the list of dates, there are dates within 30 days (or more generally n days) of each other, I only want to take the last listed date. For example, I have a di...
Removing dates within 'n' days of each other in Dictionaries
I have a dictionary where the values of the dictionary are lists of dates. For each key, if, in the list of dates, there are dates within 30 days (or more generally n days) of each other, I only want to take the last listed date. For example, I have a dictionary as follows: a : ['2020-12-11'] b : ['2020-05-30', '2022-...
[ "Just loop through the dict, then loop through inner list, transform values to datetime and compare them with last value in inner list\ntest_dict = {\n \"a\" : ['2020-12-11'],\n \"b\" : ['2020-05-30', '2022-09-11'] ,\n \"c\" : ['2021-07-28', '2022-07-20', '2022-07-07', '2022-06-30'] ,\n \"d\" : ['2022-0...
[ 1 ]
[]
[]
[ "date", "datetime", "dictionary", "pandas", "python" ]
stackoverflow_0074242088_date_datetime_dictionary_pandas_python.txt
Q: In `subprocess` functions, what is the default encoding when `text=True`? In functions like subprocess.run and subprocess.check_output, the option text=True (and its legacy alias universal_newlines=True) causes the output to be decoded as text and converted to str, instead of returning bytes. I know that you can s...
In `subprocess` functions, what is the default encoding when `text=True`?
In functions like subprocess.run and subprocess.check_output, the option text=True (and its legacy alias universal_newlines=True) causes the output to be decoded as text and converted to str, instead of returning bytes. I know that you can select a specific output encoding with encoding=. But I do not see in the docume...
[ "The answer is actually in the docs, albeit a little buried:\n\nIf encoding or errors are specified, or text is true, file objects for stdin, stdout and stderr are opened in text mode using the specified encoding and errors or the io.TextIOWrapper default.\n\nFollowing the link to the docs for io.TextIOWrapper, you...
[ 0 ]
[]
[]
[ "character_encoding", "python", "subprocess" ]
stackoverflow_0074257943_character_encoding_python_subprocess.txt
Q: mysql not installing I am getting error while installing mysql in virtual environment.But why?If i run the command from cmd under env environment it installs.But from vs code showing fatal error A: The reason may be in the virtual environment, you can recreate a new virtual environment and install the mysqlclie...
mysql not installing
I am getting error while installing mysql in virtual environment.But why?If i run the command from cmd under env environment it installs.But from vs code showing fatal error
[ "The reason may be in the virtual environment, you can recreate a new virtual environment and install the mysqlclient package again.\nOr if you can successfully install it in an external cmd window, this does not affect your use in vscode.\n" ]
[ 0 ]
[]
[]
[ "django", "mysql", "python", "visual_studio_code" ]
stackoverflow_0074226495_django_mysql_python_visual_studio_code.txt