content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Python - XML find nodes then remove I have the following XML file: <customer> <id>807997287</id> <dateCreated>2022-11-13T00:00:00Z</dateCreated> <status>Created</status> <client> <id>807997223</id> <firstname>Jeff</firstname> <lastname>Smith</lastname> <address> ...
Python - XML find nodes then remove
I have the following XML file: <customer> <id>807997287</id> <dateCreated>2022-11-13T00:00:00Z</dateCreated> <status>Created</status> <client> <id>807997223</id> <firstname>Jeff</firstname> <lastname>Smith</lastname> <address> <id>4388574</id> <hom...
[ "You are probably looking for something like\n##for elem in root.findall('.//*[id]'):\nEDIT\nfor elem in root.findall('.//id/..'):\n id = elem.find('.//id')\n elem.remove(id)\nprint(ET.tostring(root).decode())\n\nOutput should be your expected output.\n" ]
[ 0 ]
[]
[]
[ "elementtree", "python", "xml" ]
stackoverflow_0074291464_elementtree_python_xml.txt
Q: Why my code is giving the error name 'sin' is not defined? I'm trying to implement a code for the following function: f(x) = sen(2πx), x ∈ [0, 2], to get the graph of it. But I'm getting the return that the sine is not defined. I'm not quite understanding what I would have to correct. I would be grateful if someon...
Why my code is giving the error name 'sin' is not defined?
I'm trying to implement a code for the following function: f(x) = sen(2πx), x ∈ [0, 2], to get the graph of it. But I'm getting the return that the sine is not defined. I'm not quite understanding what I would have to correct. I would be grateful if someone can help me Code I used: import math import numpy as np import...
[ "Because the sine function is defined inside numpy, so you should explicitly specify the library where the function is defined:\ndef f(x): return np.sin*(2*np.pi*x)\n\n", "The problem is that you are trying to use the sin function without import it. You can find the function in the numpy package:\nimport numpy as...
[ 1, 1, 0 ]
[]
[]
[ "math", "python" ]
stackoverflow_0074266331_math_python.txt
Q: JSON to CSV: keys to header issue I am trying to convert a very long JSON file to CSV. I'm currently trying to use the code below to accomplish this. import json import csv with open('G:\user\jsondata.json') as json_file: jsondata = json.load(json_file) data_file = open('G:\user\jsonoutput.csv', 'w', newli...
JSON to CSV: keys to header issue
I am trying to convert a very long JSON file to CSV. I'm currently trying to use the code below to accomplish this. import json import csv with open('G:\user\jsondata.json') as json_file: jsondata = json.load(json_file) data_file = open('G:\user\jsonoutput.csv', 'w', newline='') csv_writer = csv.writer(data_fil...
[ "Could you try to read it normally, and then cobert it to csv using .to_csv like this:\ndf = pd.read_json('G:\\user\\jsondata')\n#df = pd.json_normalize(df['Column Name']) #if you want to normalize it\n\n\ndv.to_csv('example.csv')\n\n", "If want to use csv and json modules to do this then can do it in two passes....
[ 0, 0 ]
[]
[]
[ "csv", "json", "python" ]
stackoverflow_0074291778_csv_json_python.txt
Q: ModuleNotFoundError: No module named 'pip._internal' Recently I updated Python version Python 3.9.14 from Python3.6. I am running django project, so while running it and also while installing any dependencies, getting this error message - ModuleNotFoundError: No module named 'pip._internal' How to solve this. Gett...
ModuleNotFoundError: No module named 'pip._internal'
Recently I updated Python version Python 3.9.14 from Python3.6. I am running django project, so while running it and also while installing any dependencies, getting this error message - ModuleNotFoundError: No module named 'pip._internal' How to solve this. Getting the below error for pip3 version: Traceback (most rece...
[ "I've tried this solution previously and it works:\ncurl https://bootstrap.pypa.io/get-pip.py -o get-pip.py\npython3 get-pip.py --force-reinstall\n\n", "First, you want:\npython3 -m pip install --upgrade pip\n # ^ note no 3 ^ in either place\n\nsince the module is always named pip, it's just ...
[ 0, 0 ]
[]
[]
[ "pip", "python", "python_3.x" ]
stackoverflow_0074290275_pip_python_python_3.x.txt
Q: Problem understanding Linked Lists in Python I'm learning about data structures and algorithms and I'm starting to learn about constructing linked lists from scratch in python. Right now I understand how they work and the components that go into making them (Nodes, data/address, Head/Tail, etc), but I'm having a r...
Problem understanding Linked Lists in Python
I'm learning about data structures and algorithms and I'm starting to learn about constructing linked lists from scratch in python. Right now I understand how they work and the components that go into making them (Nodes, data/address, Head/Tail, etc), but I'm having a really hard time wrapping my brain around how they ...
[ "class Node:\n def __init__(self, value, next=None):\n self.value = value\n # NODE POINTS TO THE NEXT ELEMENT IF PROVIDED ELSE NONE\n self.next = next\n\nclass LinkedList:\n def __init__(self):\n # INIT AN EMPTY LINKED LIST\n self.head = None\n self.tail = None\n \...
[ 1, 1 ]
[]
[]
[ "class", "data_structures", "linked_list", "oop", "python" ]
stackoverflow_0074291774_class_data_structures_linked_list_oop_python.txt
Q: Collapsing rows I have the following table below: I would like to collapse Code_1 and Code_2 columns based on ID and Date. Based on what I have found online, I have tried the below snippet of code but it does not seem to be working. df= df.groupby(['ID','Date']).agg(''.join) DF: ID Date Count_Code1 Count_Code2 Co...
Collapsing rows
I have the following table below: I would like to collapse Code_1 and Code_2 columns based on ID and Date. Based on what I have found online, I have tried the below snippet of code but it does not seem to be working. df= df.groupby(['ID','Date']).agg(''.join) DF: ID Date Count_Code1 Count_Code2 Code_1 Code_2 A1...
[ "# groupby and take the group's max\ndf.groupby(['ID','Date'], as_index=False).max() \n\n ID Date Code_1 Code_2\n0 A1 2022-02-02 AAAA BBBB\n1 A1 2022-03-14 AAAA 0\n2 C1 2022-04-20 AAAA BBBB\n\nAlternate Solution\n# replace 0 with null, and ffill, bfill null values on grouped rows\n#...
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074291981_pandas_python.txt
Q: Finding consecutive numbers in seperate arrays If I have an array of arrays of numbers e.g. [[0, 5, 6, 11], [8, 9, 12], [7, 10, 13]] how do I find numbers that are consecutive with one from each array? So I would like my output to be [11,12,13] Also I need it to be flexible to number of arrays and length of arrays...
Finding consecutive numbers in seperate arrays
If I have an array of arrays of numbers e.g. [[0, 5, 6, 11], [8, 9, 12], [7, 10, 13]] how do I find numbers that are consecutive with one from each array? So I would like my output to be [11,12,13] Also I need it to be flexible to number of arrays and length of arrays. I found this solution: def find_continuous_items(d...
[ "You don't need to make cartesian product of all you sublists. You can loop through your first sublist, then check the remainding sublists for subsequent numbers.\nLike this,\nnested_lst = [[0, 5, 6, 11], [8, 9, 12], [7, 10, 13]]\nnum_sublst = len(nested_lst)\nresult = [] # all consecutive number lists we will fin...
[ 2 ]
[]
[]
[ "list", "numbers", "python" ]
stackoverflow_0074291801_list_numbers_python.txt
Q: Django logging configuration star notation Let's say I have the following Django logging config: LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "console": { "class": "logging.StreamHandler", }, }, "root": { "handlers": ["console"],...
Django logging configuration star notation
Let's say I have the following Django logging config: LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "console": { "class": "logging.StreamHandler", }, }, "root": { "handlers": ["console"], "level": "WARNING", }, "loggers...
[ "Of course, you can construct the relevant dict dynamically, using an approach such as this:\nfrom pprint import pprint\n\nclass DynamicLoggerDict(dict):\n def __init__(self, data, common, apps):\n super().__init__(data)\n for app in apps:\n key = f'{app}.management.commands'\n ...
[ 0 ]
[]
[]
[ "django", "logging", "python", "python_logging" ]
stackoverflow_0074281732_django_logging_python_python_logging.txt
Q: Use mock or create real instance with workaround while testing I have class MyClass in file main.py class MyClass: def __init__(self, a=1, b=2, c=3): self.a = a self.b = b self.c = c self.d = None self.e = None self.f = None def method_1(self): retu...
Use mock or create real instance with workaround while testing
I have class MyClass in file main.py class MyClass: def __init__(self, a=1, b=2, c=3): self.a = a self.b = b self.c = c self.d = None self.e = None self.f = None def method_1(self): return self.a + self.b def method_2(self): return self.d + ...
[ "Main difference between the 3 methods\nI think that the main difference between the 3 test methods is:\n\ntest_method_2_v1() invokes method_1() of MyClass\ntest_method_2_v2() and test_method_2_v3() don't invoke method_1() of MyClass\n\nThis means that test_method_2_v1() executes an indirect test of method_1() whil...
[ 0 ]
[]
[]
[ "mocking", "python", "unit_testing" ]
stackoverflow_0074289626_mocking_python_unit_testing.txt
Q: How to accumulate total in tuple? I have a tuple like this: fruit_list_amount = [('16', 'Watermeloenen'), ('360', 'Watermeloenen'), ('6', 'Watermeloenen'), ('75', 'Watermeloenen'), ('9', 'Watermeloenen'), ('688', 'Appels'), ('22','Sinaasappels')] And I try to return total for each label. So 16 ...
How to accumulate total in tuple?
I have a tuple like this: fruit_list_amount = [('16', 'Watermeloenen'), ('360', 'Watermeloenen'), ('6', 'Watermeloenen'), ('75', 'Watermeloenen'), ('9', 'Watermeloenen'), ('688', 'Appels'), ('22','Sinaasappels')] And I try to return total for each label. So 16 + 360 + 6... for Watermeloenen So I try...
[ "Build a dictionary keyed on fruit name. You can then directly look up the total \"count\"\nfruit_list_amount = [('16', 'Watermeloenen'), ('360', 'Watermeloenen'), ('6', 'Watermeloenen'), ('75', 'Watermeloenen'), ('9', 'Watermeloenen'), ('688', 'Appels'), ('22','Sinaasappels')] \n\nfruit_dict = {}\n\nfor n, f in fr...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074291960_python.txt
Q: Python selecting variables based inside function I'm trying to create function that can pull information from an API library and I am having a hard time figuring out how to pass a variable selection into the function without being read as a value. code example: def get_list(api, val = None): response =[] l...
Python selecting variables based inside function
I'm trying to create function that can pull information from an API library and I am having a hard time figuring out how to pass a variable selection into the function without being read as a value. code example: def get_list(api, val = None): response =[] list = api for i in list: response.append(f...
[ "When you call this function with devices, you are passing the argument 'name' as your \"val\" which you then loop over and append to results.\nIt would be helpful if you could also include what your desired result here would be since that is not clear at the moment.\n", "I'm using a LibrenmsAPI library to read d...
[ 1, 0, 0, 0 ]
[]
[]
[ "api", "python" ]
stackoverflow_0074289523_api_python.txt
Q: Pandas ffill() to fill missing data I am currently trying to fill blanks in a data frame that looks like the following: AL|ATFC|Year Latitude Longitude 0 AL011851 NaN NaN 1 NaN 28.0N 94.8W 2 NaN 28.0N 95.4W 3 NaN 28.0N 96.0W 4 NaN ...
Pandas ffill() to fill missing data
I am currently trying to fill blanks in a data frame that looks like the following: AL|ATFC|Year Latitude Longitude 0 AL011851 NaN NaN 1 NaN 28.0N 94.8W 2 NaN 28.0N 95.4W 3 NaN 28.0N 96.0W 4 NaN 28.1N 96.5W 5 NaN 28....
[ "You could replace the 'AL|ATFC|Year' NaN by np.nan, and then do use fillna function. I reproduced only the first 3 rows:\nimport pandas as pd\n\ndata = {'AL|ATFC|Year' : ['AL011851', 'NaN', 'NaN'],\n 'Latitude': ['NaN', '28.0N', '28.0N'],\n 'Longitude': ['NaN', '94.8W', '95.4W']}\n\ndf = pd.DataFrame...
[ 1, 0 ]
[]
[]
[ "dataframe", "ffill", "nan", "pandas", "python" ]
stackoverflow_0074291275_dataframe_ffill_nan_pandas_python.txt
Q: How to plot pct_change for many stock names in Python I have a data set with prices of 6 major stocks i.e., Google, Amazon etc. My plan is to create a plot which would show a percent change, pct_change()of column known as close_value. As you can see my ticker_symbol is an object. I tried and changed it to float be...
How to plot pct_change for many stock names in Python
I have a data set with prices of 6 major stocks i.e., Google, Amazon etc. My plan is to create a plot which would show a percent change, pct_change()of column known as close_value. As you can see my ticker_symbol is an object. I tried and changed it to float because of the string error but then I lost all ticker names ...
[ "Does this work?\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Create Sample DataFrame\ndf1 = pd.DataFrame({'day_date': ['2020-05-28', '2020-05-27', '2020-05-26', '2020-05-22'], \n 'ticker_symbol': ['AAPL', 'AAPL','TSLA','TSLA'],\n 'close_val...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074291130_dataframe_pandas_python.txt
Q: Python with solcx don't find evm (vs code) I was following this course on ytb and after making the same code than him I encoutered a problem with solcx. Tanks a lot in advance. This is the error message (i'm french so the first line is french but i think you'll understand): Information�: impossible de trouver des ...
Python with solcx don't find evm (vs code)
I was following this course on ytb and after making the same code than him I encoutered a problem with solcx. Tanks a lot in advance. This is the error message (i'm french so the first line is french but i think you'll understand): Information�: impossible de trouver des fichiers pour le(s) mod�le(s) sp�cifi�(s). Trace...
[ "there is a missing \",\" somehow in between \"evm.bytecode\" and \"evm.bytecode.sourceMap\", thus no evm related generate in the compiled_code.json\n" ]
[ 0 ]
[]
[]
[ "evm", "python", "solidity", "visual_studio_code" ]
stackoverflow_0071039279_evm_python_solidity_visual_studio_code.txt
Q: Return active GCP project name programatically for both local dev and deployed Cloud Run projects I am working on code that will leverage GCP's CI/CD build > deploy. Part of that process is staging it as a test deploy and running integration tests in a non-production project. That code will ultimately be promoted ...
Return active GCP project name programatically for both local dev and deployed Cloud Run projects
I am working on code that will leverage GCP's CI/CD build > deploy. Part of that process is staging it as a test deploy and running integration tests in a non-production project. That code will ultimately be promoted to a production project. As a result, I would like to be able to dynamically adjust which project the d...
[ "The CLI configuration information is stored in a file. The format is INI. For Python use the configparser package.\nWindows:\nC:\\Users\\%USERNAME%\\AppData\\Roaming\\gcloud\\configurations\\config_default\n\nLinux:\n~/.config/gcloud/configurations/config_default\n\n" ]
[ 1 ]
[]
[]
[ "google_cloud_platform", "python" ]
stackoverflow_0074290882_google_cloud_platform_python.txt
Q: Can someone explain why I keep getting these errors in Flask? I keep getting these errors in my Flask app: malloc(): unsorted double linked list corrupted double free or corruption (!prev) basically I'm calling the pos() method and trying to get the year attribute from my JS page in order to use it in my query.....
Can someone explain why I keep getting these errors in Flask?
I keep getting these errors in my Flask app: malloc(): unsorted double linked list corrupted double free or corruption (!prev) basically I'm calling the pos() method and trying to get the year attribute from my JS page in order to use it in my query... but it doesn't work and instead returns some malloc error can som...
[ "So I figured out what I was doing wrong. MySQLdb simply isn't built to support multiple cursors using one MySQL connection. I got this from their site: \"Two threads simply cannot share a connection while a transaction is in progress, in addition to not being able to share it during query execution.\" So the only ...
[ 0 ]
[]
[]
[ "flask", "mysql", "python" ]
stackoverflow_0074268708_flask_mysql_python.txt
Q: Center-/middle-align text with PIL? How would I center-align (and middle-vertical-align) text when using PIL? A: Deprecation Warning: textsize is deprecated and will be removed in Pillow 10 (2023-07-01). Use textbbox or textlength instead. Code using textbbox instead of textsize. from PIL import Image, ImageDra...
Center-/middle-align text with PIL?
How would I center-align (and middle-vertical-align) text when using PIL?
[ "\nDeprecation Warning: textsize is deprecated and will be removed in Pillow 10 (2023-07-01). Use textbbox or textlength instead.\n\nCode using textbbox instead of textsize.\nfrom PIL import Image, ImageDraw, ImageFont\n\n\ndef create_image(size, bgColor, message, font, fontColor):\n W, H = size\n image = Ima...
[ 206, 86, 38, 24, 12, 2, 2, 1, 0, 0 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0001970807_python_python_imaging_library.txt
Q: find local maxima and their indices in a python list I have a large data set and I am trying to find the local maxima and their indices. I have made it to get the local maxima but can't find a way to get their indices. The thing is that I need the maxima only for positive values and we should ignore the negative v...
find local maxima and their indices in a python list
I have a large data set and I am trying to find the local maxima and their indices. I have made it to get the local maxima but can't find a way to get their indices. The thing is that I need the maxima only for positive values and we should ignore the negative values. In other words, it would be like splitting the list...
[ "def global_peaks(test_data):\n counter1 = []\n index = []\n global_peak = []\n global_idx = []\n for idx, data in enumerate(test_data):\n if data > 0:\n counter1.append(data)\n index.append(idx)\n else:\n if(len(counter1) != 0):\n global_...
[ 1 ]
[]
[]
[ "indices", "maxima", "python" ]
stackoverflow_0074291821_indices_maxima_python.txt
Q: Creating numpy array with a specific pattern I'm trying to create a numpy array of intergers ascending intergers (1,2,3,...), such that the n is repeated n times. For example for maximum number 4 I would like my_arr = [1,2,2,3,3,3,4,4,4,4] Now this is easy using a for loop my_arr = numpy.array([]) max = 4 for i i...
Creating numpy array with a specific pattern
I'm trying to create a numpy array of intergers ascending intergers (1,2,3,...), such that the n is repeated n times. For example for maximum number 4 I would like my_arr = [1,2,2,3,3,3,4,4,4,4] Now this is easy using a for loop my_arr = numpy.array([]) max = 4 for i in range(1,max + 1): my_arr = numpy.append(my_a...
[ "Use np.repeat:\nimport numpy as np\n\ndef pattern(n):\n x = np.arange(1, n + 1)\n return np.repeat(x, x)\n\n# >>> pattern(4)\n# array([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])\n\n", "There is a builtin way to do this.\nimport numpy as np\n\n\ndef builtinway(maxval=10):\n arr = list(range(1, maxval+1))\n return...
[ 3, 1 ]
[]
[]
[ "numpy", "optimization", "python" ]
stackoverflow_0074292035_numpy_optimization_python.txt
Q: Merge two dataframes based on some similar columns I am guessing the answer is out there but my googling is not finding it. I have two dataframes (eventually will have a bunch) that I want to merge together. Eventually this dataframe should grow into something with many rows and columns. df1 Init Date 2021-01-0...
Merge two dataframes based on some similar columns
I am guessing the answer is out there but my googling is not finding it. I have two dataframes (eventually will have a bunch) that I want to merge together. Eventually this dataframe should grow into something with many rows and columns. df1 Init Date 2021-01-01 00:00:00 2021-01-01 06:00:00 2021-01-01 12:00:00 2021-...
[ "pd.concat([df, df2])\n\n\n Init Date 2021-01-01 00:00:00 2021-01-01 06:00:00 2021-01-01 12:00:00 2021-01-01 18:00:00 2021-01-02 00:00:00\n0 2021-01-01 37.3 35.29 35.72 41.28 NaN\n0 2021-01-01 06:00:00 ...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074291911_dataframe_pandas_python.txt
Q: finding the index of the start of the last repeating sequence in the list e.g.the index of first element of the last repeating in list [2, 7, 3, 3, 3, 1, 1] would be 5 How do I solve this WITHOUT using the builtin index() function? def get_index_of_last_repeating_sequence(l:list[int]): index =0 while ...
finding the index of the start of the last repeating sequence in the list
e.g.the index of first element of the last repeating in list [2, 7, 3, 3, 3, 1, 1] would be 5 How do I solve this WITHOUT using the builtin index() function? def get_index_of_last_repeating_sequence(l:list[int]): index =0 while l[index] != l[index-1]: index+=1 .... return ...
[ "You can solve this by iterating over list backwards and finding the first sequence of repeated items.\ndef get_index_of_last_repeating_sequence(lst: list[int]):\n repeated = None\n kk = len(lst) - 1\n while kk >= 1:\n if lst[kk] == lst[kk - 1]:\n repeated = lst[kk]\n if repeated ...
[ 1 ]
[]
[]
[ "duplicates", "indexing", "loops", "python", "while_loop" ]
stackoverflow_0074291906_duplicates_indexing_loops_python_while_loop.txt
Q: Expected 2D array, got 1D array instead: how do i solve it? i've been trying to develop a linear regression model using my cleaned datasets. Here is my datasets: https://docs.google.com/spreadsheets/d/1G7URct9yPAxEETLrb_F1McN-bgKp_r8cykmCOmojhT0/edit?usp=sharing i've processed the data with label encoder and just ...
Expected 2D array, got 1D array instead: how do i solve it?
i've been trying to develop a linear regression model using my cleaned datasets. Here is my datasets: https://docs.google.com/spreadsheets/d/1G7URct9yPAxEETLrb_F1McN-bgKp_r8cykmCOmojhT0/edit?usp=sharing i've processed the data with label encoder and just split it with train_test_split cols = ['nama_pasar','komoditas'] ...
[ "Your x is a 2d array and has been trained like that hence when you want a prediction you need to pass an 2d array Try the below.\nLR.predict([[1, 10, 4]])\n\n", "As for your second question (and your comment): You got the order for the train-test-split wrong.\nX_train, y_train, X_test, y_test = train_test_split(...
[ 1, 1 ]
[]
[]
[ "arrays", "numpy", "pandas", "python", "scikit_learn" ]
stackoverflow_0074291912_arrays_numpy_pandas_python_scikit_learn.txt
Q: how to use "tzdata" file with pyarrow.compute.assume_timezone Im trying to use the method pyarrow.compute.assume_timezone but i get the error: pyarrow.lib.ArrowInvalid: Cannot locate timezone 'UTC': Unable to get Timezone database version from C:\Users\Nick\Downloads\tzdata\ I tried download the db from https://ww...
how to use "tzdata" file with pyarrow.compute.assume_timezone
Im trying to use the method pyarrow.compute.assume_timezone but i get the error: pyarrow.lib.ArrowInvalid: Cannot locate timezone 'UTC': Unable to get Timezone database version from C:\Users\Nick\Downloads\tzdata\ I tried download the db from https://www.iana.org/time-zones without success Anyone got it work ? import p...
[ "Indeed there is doc how to install in Arrow, thanks @Matt Johnson-Pint\nI made a script to install it if anyone wants\ndef download_tzdata_windows(\n base_dir=None,\n year=2022,\n name=\"tzdata\"\n):\n import os\n import tarfile\n import urllib3\n\n http = urllib3.PoolManager()\n folder = b...
[ 1 ]
[]
[]
[ "pyarrow", "python", "timezone", "tzdata" ]
stackoverflow_0074267313_pyarrow_python_timezone_tzdata.txt
Q: Multiprocessing in Flask with a function that runs forever For a school project, I am required to control some LEDs on a Raspberry Pi through C remotely. Using pigpio, I have managed to create the following is code snippet from the shared library file I have created: #include <stdio.h> #include <pigpio.h> void in...
Multiprocessing in Flask with a function that runs forever
For a school project, I am required to control some LEDs on a Raspberry Pi through C remotely. Using pigpio, I have managed to create the following is code snippet from the shared library file I have created: #include <stdio.h> #include <pigpio.h> void initialise_pins(int LED_1, int LED_2){ gpioInitialise(); /*Ini...
[ "There is a mistake in your code:\np = Process(target=blink_lights(), args=(), daemon=True)\n\nIt starts blink_lights loop and can not even return something to assign to target parameter. So, obviously you need to remove function call like this:\np = Process(target=blink_lights, args=(), daemon=True)\n\nBut multipr...
[ 0 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0069856222_flask_python.txt
Q: Python fibbonaci sequence I'm a beginner with python, and I'm trying to make a script that will print the fibonacci sequence as a list, or a specified number in the sequence based on a given number. This probably sounds confusing, so let me show you guys the code, and then explain. number = 1 last = 0 before_la...
Python fibbonaci sequence
I'm a beginner with python, and I'm trying to make a script that will print the fibonacci sequence as a list, or a specified number in the sequence based on a given number. This probably sounds confusing, so let me show you guys the code, and then explain. number = 1 last = 0 before_last = 0 def Fibonacci(number, l...
[ "When Question == \"Number\", your for loop iterates over the sequence range (int(X) - 2, int(X) - 1). When you input 10 for X, this evaluates to range(8, 9), which is of length one. As a result, the loop is only executed once. Since both loops are otherwise the same, and count is never used inside the loop body...
[ 2, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "fibonacci", "python", "terminal" ]
stackoverflow_0027538818_fibonacci_python_terminal.txt
Q: Python package with multiple "packages"? Assume I have a project which looks like uilities.py api_1.py api_2.py api_3.py foo.py bar.py baz.py The utilites and api calls does nothing by their own, but they form 90% of the contents of foo.py, bar.py and baz.py. The contents of foo.py, bar.py and baz.py. are very b...
Python package with multiple "packages"?
Assume I have a project which looks like uilities.py api_1.py api_2.py api_3.py foo.py bar.py baz.py The utilites and api calls does nothing by their own, but they form 90% of the contents of foo.py, bar.py and baz.py. The contents of foo.py, bar.py and baz.py. are very bare bones, including the commandline interface...
[ "You can declare them as console scripts in the setup for building the package for distribution.\nMore details here: https://setuptools.pypa.io/en/latest/userguide/entry_point.html\n" ]
[ 2 ]
[]
[]
[ "python", "python_packaging" ]
stackoverflow_0074292292_python_python_packaging.txt
Q: Python - Save all data with a key missing or present I am retrieving data via api and I want to save all data regardless if a key is missing or not. Here is my code which saves the data only when the key is present. #get all of the initial users initialUsers = requests.get(url, headers=headers) data = initialUser...
Python - Save all data with a key missing or present
I am retrieving data via api and I want to save all data regardless if a key is missing or not. Here is my code which saves the data only when the key is present. #get all of the initial users initialUsers = requests.get(url, headers=headers) data = initialUsers.json() userData = data['data'] # write to a txt fil...
[ "Assuming that you want to save some \"default data\" if the data is not found:\n# ...\nwith open('Users.txt', 'x', encoding='utf-8') as f:\n for i in userData:\n default_data = {\"username\":\"\", \"first_name\":\"\", \"last_name\":\"\"}\n output = i.get('presence_id', default_data) # this will ne...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074291625_python.txt
Q: Drop rows from Dask DataFrame where column count is not equal I have a CSV file which I want to normalize for SQL input. I want to drop every line, where's the column count not equal to a certain number within a row, this way I can ignore the bad lines, where column shift can happen. In the past, I used AWK to nor...
Drop rows from Dask DataFrame where column count is not equal
I have a CSV file which I want to normalize for SQL input. I want to drop every line, where's the column count not equal to a certain number within a row, this way I can ignore the bad lines, where column shift can happen. In the past, I used AWK to normalize this CSV dataset, but I want to implement this program in Py...
[ "The question is not easy to understand. From the first statement it appears as if you are working with a single file, is that correct?\nIf so, if there are unnamed columns, then there will be an attempt by pandas (or dask via pandas) to 'fix' the structure by adding missing column labels with something like 'Untit...
[ 2, 1, 1 ]
[]
[]
[ "dask", "dask_dataframe", "dataframe", "pandas", "python" ]
stackoverflow_0074269282_dask_dask_dataframe_dataframe_pandas_python.txt
Q: Flask Showing Shape of Uploaded CSV File I have app.py file: from flask import Flask, request, render_template import pandas as pd app = Flask(__name__) @app.route('/upload', methods=['GET', 'POST']) def upload(): if request.method == 'POST': df = pd.read_csv(request.files.get('file')) return...
Flask Showing Shape of Uploaded CSV File
I have app.py file: from flask import Flask, request, render_template import pandas as pd app = Flask(__name__) @app.route('/upload', methods=['GET', 'POST']) def upload(): if request.method == 'POST': df = pd.read_csv(request.files.get('file')) return render_template('upload.html', shape=df.shape...
[ "Here is the solution:\nCreate a templates folder and put your upload.html file inside the templates folder. Since, you do not have it inside the templates folder, flask is returning you jinga2 template not found error.\nJust like all the images need to be inside static folder, all the html templates need to be ins...
[ 1 ]
[]
[]
[ "flask", "pandas", "python" ]
stackoverflow_0074289930_flask_pandas_python.txt
Q: How do I iterate through a list of dictionaries? I need to take an inputted time, for example "12:20", and print a 5x3 ASCII clock representation of it. But I don't know how how iterate through a list of dictionaries, which I think is the simplest way to solve this problem. time = input("enter a time HH:MM") my_li...
How do I iterate through a list of dictionaries?
I need to take an inputted time, for example "12:20", and print a 5x3 ASCII clock representation of it. But I don't know how how iterate through a list of dictionaries, which I think is the simplest way to solve this problem. time = input("enter a time HH:MM") my_list = [ {"0": "000", "1": " 1 ","2":"222","3":"333","4"...
[ "You were almost there. You just overlooked a few fundamentals. Such as: you have to get the entire line before you print it, names matter, and you can't print a colon if you don't include one in your segments.\nimport re\n\ntime_valid = re.compile(r'^\\d{2}:\\d{2}$')\n\nwhile not time_valid.match((time := input(\"...
[ 0 ]
[]
[]
[ "ascii", "clock", "python" ]
stackoverflow_0074291189_ascii_clock_python.txt
Q: Python Pandas Stock Data Gap Fill I'm testing a strategy to trade on gap fill. Given that AAPL created an upward gap on 2022-10-04 and filled this gap on 2022-10-07 (and there will be multiple gaps), how to identify if the nearest upward gap is filled in a pythonic way? Code: import pandas_datareader as pdr df = ...
Python Pandas Stock Data Gap Fill
I'm testing a strategy to trade on gap fill. Given that AAPL created an upward gap on 2022-10-04 and filled this gap on 2022-10-07 (and there will be multiple gaps), how to identify if the nearest upward gap is filled in a pythonic way? Code: import pandas_datareader as pdr df = pdr.data.DataReader('AAPL', 'yahoo', st...
[ "Ok - while this is not exactly what you were hoping for, I think I have something that somewhat satisfies the requirements. I have not done anything with additional hierarchies of gaps, however, have accommodated for the base gap (or what you are calling upward gap 1).\n\nThe check_gap value (orange) is used to id...
[ 0 ]
[]
[]
[ "pandas", "python", "time_series" ]
stackoverflow_0074287381_pandas_python_time_series.txt
Q: Pandas ASSIGN function - use dynamic column name in loop I have the following pseudocode: for col in df.columns: df.assign('Test_' + str(col) = 1) This code won't work. But how do I use a string in the assign operator? A: You can use ** and do: df.assign(**{ "Test_"+col: 1 for col in df.columns })...
Pandas ASSIGN function - use dynamic column name in loop
I have the following pseudocode: for col in df.columns: df.assign('Test_' + str(col) = 1) This code won't work. But how do I use a string in the assign operator?
[ "You can use ** and do:\ndf.assign(**{\n \"Test_\"+col: 1 for col in df.columns\n })\n\n col1 col2 col3 col4 Test_col1 Test_col2 Test_col3 Test_col4\n0 1 0 1 0 1 1 1 1\n1 0 0 1 0 1 1 1 1\n2 0 ...
[ 3 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074292394_pandas_python.txt
Q: Looping .to_csv Not Saving to Folders I'm trying to get this loop to save multiple dataframes from csv files to individual txt files (using .to_csv) for data analysis. The csv files are across multiple folders in the same parent folder. I do have to join the dataframes with another fixed set of values, which is my...
Looping .to_csv Not Saving to Folders
I'm trying to get this loop to save multiple dataframes from csv files to individual txt files (using .to_csv) for data analysis. The csv files are across multiple folders in the same parent folder. I do have to join the dataframes with another fixed set of values, which is my "W_I0_df" dataframe, hence the second to l...
[ "Found that adding \"subfolder_path\" to glob.glob('/.csv') before \"'/.csv'\" fixes the problem. The code should instead be:\nW_I0_data_path = \"C:/Users/.../W_L3_I0_000_exd.csv\"\nW_I0_df = pd.read_csv(W_I0_data_path, index_col=None, usecols=[3], names=['I0 Intensity (C/s)'], header=0)\nW_dir_path = 'C:/Users/......
[ 0 ]
[]
[]
[ "loops", "pandas", "python", "python_3.x", "text" ]
stackoverflow_0074283899_loops_pandas_python_python_3.x_text.txt
Q: how to create a number "limit" in a range I have this code, it works just fine. But I need to create a limit that is the count(in my case 10). Can you help me with a simple solution? def multiples(m, count): for i in range(0,count*m,m): print(i) multiples(3, 10) A: In python 3 you could do t...
how to create a number "limit" in a range
I have this code, it works just fine. But I need to create a limit that is the count(in my case 10). Can you help me with a simple solution? def multiples(m, count): for i in range(0,count*m,m): print(i) multiples(3, 10)
[ "In python 3 you could do the following:\ndef multiples(m, count):\n for i in range(count//m):\n print((i+1)*m)\n \nmultiples(3, 10)\n\nThe double // in the range would make sure that it yields an integer value of the number of times it is contained. The print would then simply iterate through all...
[ 0 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0074292188_for_loop_python.txt
Q: Event wait for a specified message I'm trying to create an event in a command that will wait for a specified user but it didn't work : await bot.wait_for('message', check=check("282859044593598464")) if message.author.id == "282859044593598464": I want to specify what the message contains. A: Use def check(mess...
Event wait for a specified message
I'm trying to create an event in a command that will wait for a specified user but it didn't work : await bot.wait_for('message', check=check("282859044593598464")) if message.author.id == "282859044593598464": I want to specify what the message contains.
[ "Use\ndef check(message):\n return message.author.id == 282859044593598464\n\nawait bot.wait_for('message', check=check)\n\nThen if you want to make more checks, just change the code in the function, and make it so that it return True if it is what you want (for example specific content) and False if it isn't.\nF...
[ 0 ]
[]
[]
[ "discord.py", "pycord", "python" ]
stackoverflow_0074292303_discord.py_pycord_python.txt
Q: Display n-digit number with same sums on even,uneven indexes. Python I need to implement recursive version of the function mentioned in the tittle. My problem is that I don't know how to implemnt it as recursion. I've only done it with loops. def n_sums(n:int): for i in range(10**(n-1),10**n): i=str(i)...
Display n-digit number with same sums on even,uneven indexes. Python
I need to implement recursive version of the function mentioned in the tittle. My problem is that I don't know how to implemnt it as recursion. I've only done it with loops. def n_sums(n:int): for i in range(10**(n-1),10**n): i=str(i) sum1=0 sum2=0 for j in range(len(i)): ...
[ "Could you do something like this?\ndef n_sums_recursive(n: int, i: int = 0, sum1: int = 0, sum2: int = 0):\n if i == 0:\n i = 10**(n-1)\n if i < 10**n:\n i = str(i)\n for j in range(len(i)):\n if j % 2 == 0:\n sum1 += int(i[j])\n else:\n ...
[ 0 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0074292422_python_recursion.txt
Q: How to pass arguments to ros launch file from bash script and how to create ros launch file running python script with those parser arguments I have a python script which runs as follows: rosrun camera_calibrator cameracalibrator.py --size 12x8 --square 0.05 image:=/topic_name I have launch file are follows: <lau...
How to pass arguments to ros launch file from bash script and how to create ros launch file running python script with those parser arguments
I have a python script which runs as follows: rosrun camera_calibrator cameracalibrator.py --size 12x8 --square 0.05 image:=/topic_name I have launch file are follows: <launch> <node name="image_pub_sub_node" pkg="image_pub" type="image_pub_sub" output="screen"/> <node name="cameracalibrator_node" pkg="camera_cali...
[ "The roslaunch command line accept arguments, so yes it is possible to do this.\nIn your launch file, you must declare the arguments like this :\n<launch>\n <arg name=\"foldername\" default=\"whatever_you_want\" />\n</launch>\n\nThen, you want to check the list of parameters supported by the nodes that you ...
[ 1 ]
[]
[]
[ "bash", "parsing", "python", "ros" ]
stackoverflow_0074292282_bash_parsing_python_ros.txt
Q: Replacing values in a list by looping without making the size of the list smaller/larger I have a list li. When I loop over it and replace zeros with new values the size of the list changes. I want to keep the same size but be able to manipulate the list. str0 = "Hi" str1 = "Bye" li = [[[0, 0] for y in range(len(...
Replacing values in a list by looping without making the size of the list smaller/larger
I have a list li. When I loop over it and replace zeros with new values the size of the list changes. I want to keep the same size but be able to manipulate the list. str0 = "Hi" str1 = "Bye" li = [[[0, 0] for y in range(len(str1)+1)] for x in range(len(str0)+1)] #correct size print(li) #output: [[[0, 0], [0, 0], [0,...
[ "If I get your explanation correct you would like to have\nprint(li)\n[[[0, 0], [0, 0], [0, 0], [0, 0]],\n [[1, 1], [0, 0], [0, 0], [0, 0]],\n [[2, 2], [0, 0], [0, 0], [0, 0]]]\n\nFor that you can do one of the following:\n# a)\nfor i in range(0, len(str0) + 1):\n li[i][0] = [i, i]\n\na solution I found here:\n#...
[ 0 ]
[]
[]
[ "for_loop", "list", "loops", "matrix", "python" ]
stackoverflow_0074292260_for_loop_list_loops_matrix_python.txt
Q: TypeError: not supported between instances of 'NoneType' and 'float' I am doing flappyBird game with neat from Tech with Tim tutorial and I created self.type inside Bird Class which means that bird is controllable by keyboard input or neat class, but I am getting this error after finish last generation: C:/Us...
TypeError: not supported between instances of 'NoneType' and 'float'
I am doing flappyBird game with neat from Tech with Tim tutorial and I created self.type inside Bird Class which means that bird is controllable by keyboard input or neat class, but I am getting this error after finish last generation: C:/Users/papadi166/Documents/MEGAsync/AppDev/FlappyBird/main.py:185: Deprecatio...
[ "For me, Declaring ge[x].fitness in a for loop before worked.\n# put this above the other for loops\nfor x, bird in enumerate(birds):\n ge[x].fitness = 0\n\n" ]
[ 0 ]
[]
[]
[ "flappy_bird_clone", "neat", "python" ]
stackoverflow_0063756197_flappy_bird_clone_neat_python.txt
Q: No output? Counting characters in a phrase I'm learning Python and such in Zybooks, the prompt is: "Write a program whose input is a string which contains a character and a phrase, and whose output indicates the number of times the character appears in the phrase. Examples: Input: n Monday Output: 1 Input: z Tod...
No output? Counting characters in a phrase
I'm learning Python and such in Zybooks, the prompt is: "Write a program whose input is a string which contains a character and a phrase, and whose output indicates the number of times the character appears in the phrase. Examples: Input: n Monday Output: 1 Input: z Today is Monday Output: 0 Input: n It's a sunny ...
[ "Made it a little prettier for you too\ndef main():\n print('Enter your phrase:')\n phrase = input()\n print('Enter your character:')\n character = input()\n output = search(phrase, character)\n #str(output) casts the return value of the function from an integer to a string \n print('The charac...
[ 0 ]
[]
[]
[ "count", "python" ]
stackoverflow_0074292106_count_python.txt
Q: ImportError: cannot import name 'ParamSpec' from 'typing_extensions' when using Django websockets with channels and twisted libraries We did not update any lib or new lib added. During deployment of Django web application, got the following error: Traceback (most recent call last): File "/usr/local/lib/python3.7...
ImportError: cannot import name 'ParamSpec' from 'typing_extensions' when using Django websockets with channels and twisted libraries
We did not update any lib or new lib added. During deployment of Django web application, got the following error: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/celery/fixups/django.py", line 118, in django_setup django.setup() File "/usr/local/lib/python3.7/site-packages/django...
[ "So, it turned out that I did not update any library. But, in requirements.txt, only channels library specific version was mentioned so while deployment the version of channels stayed the same. Meanwhile twisted library is a 3rd level dependency and not directly mentioned in my requirements.txt.\nSo twisted librar...
[ 0 ]
[]
[]
[ "django", "django_channels", "python", "twisted", "websocket" ]
stackoverflow_0074288898_django_django_channels_python_twisted_websocket.txt
Q: Boto3 some image objects downloading, some displayed inline I am running a code to upload files to S3 using boto3 - client = boto3.client('s3',region_name='us-west-1') client.upload_file("FILENAME","BUCKETNAME","OBJECTNAME",ExtraArgs={'Metadata': {'Content-Type': 'image/png'}}) bucket_location = boto3.clie...
Boto3 some image objects downloading, some displayed inline
I am running a code to upload files to S3 using boto3 - client = boto3.client('s3',region_name='us-west-1') client.upload_file("FILENAME","BUCKETNAME","OBJECTNAME",ExtraArgs={'Metadata': {'Content-Type': 'image/png'}}) bucket_location = boto3.client('s3').get_bucket_location(Bucket="BUCKETNAME") url2 = "htt...
[ "Found the issue, it was a caching problem on my end. After clearing the cache, all the images are displayed inline.\n" ]
[ 0 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "boto3", "python" ]
stackoverflow_0074213149_amazon_s3_amazon_web_services_boto3_python.txt
Q: How do I load the images and the csv file for object detection in tensorflow? Data loader in Image Classification Small Target Image CSV File I am new to object detection and don't know how to use the dataloader for the task. In image clasification, I know that we can load data for image classification from image_...
How do I load the images and the csv file for object detection in tensorflow?
Data loader in Image Classification Small Target Image CSV File I am new to object detection and don't know how to use the dataloader for the task. In image clasification, I know that we can load data for image classification from image_dataset_from_directory in tensorflow and I am looking for similar function to load ...
[ "You can pass your csv file to below code to create an annotation files.\ndef annotation(row):\n annotation = {}\n area = (row.xmax -row.xmin)*(row.ymax - row.ymin)\n annotation[\"segmentation\"] = []\n annotation[\"iscrowd\"] = 0\n annotation[\"area\"] = area\n annotation[\"image_id\"] = row.file...
[ 0 ]
[]
[]
[ "object_detection", "python", "tensorflow" ]
stackoverflow_0073697816_object_detection_python_tensorflow.txt
Q: TypeError: unsupported operand type(s) for +=: 'Tag' and 'Tag' I'm trying to scrap HTML data from a website and then add my own CSS style to the code. I'm using Beautiful soup to scrap the data and convert my own tag to HTML. This is the code word = t.clipboard_get() # Web Scrapping url="...
TypeError: unsupported operand type(s) for +=: 'Tag' and 'Tag'
I'm trying to scrap HTML data from a website and then add my own CSS style to the code. I'm using Beautiful soup to scrap the data and convert my own tag to HTML. This is the code word = t.clipboard_get() # Web Scrapping url="https://www.vajehyab.com/?q=" response = requests.get(f"{ur...
[ "(I strongly recommend reading the docs a bit.)\nI think what you're looking for is .append\nmeaning.append(css)\n\nshould do what you're wanting to.\n" ]
[ 0 ]
[]
[]
[ "beautifulsoup", "html", "python", "type_conversion", "web_scraping" ]
stackoverflow_0074289356_beautifulsoup_html_python_type_conversion_web_scraping.txt
Q: Counting the special character and character in an array and giving the sum of the numbers in an array ar=input("Enter the elements:").split() sum=0 cr=0 for i in range(len(ar)): if(not ar[i].isalpha()): a=int(ar[i]) sum=sum+a else: cr=cr+1 print("Sum of the elements is :",sum) pr...
Counting the special character and character in an array and giving the sum of the numbers in an array
ar=input("Enter the elements:").split() sum=0 cr=0 for i in range(len(ar)): if(not ar[i].isalpha()): a=int(ar[i]) sum=sum+a else: cr=cr+1 print("Sum of the elements is :",sum) print(" No of Characters in the array:",cr) I can count the character but idk what to do for speci...
[ "You check if it's neither alpha niether numeric:\nar=input(\"Enter the elements:\")\nchar_count = 0\nspecial_char_count = 0\n\nfor char in ar:\n if char.isalpha():\n char_count += 1\n continue\n \n if not char.isnumeric():\n special_char_count += 1\n \nprint(\"Sum of alpha: \", cha...
[ 0 ]
[]
[]
[ "arrays", "python", "special_characters" ]
stackoverflow_0074292496_arrays_python_special_characters.txt
Q: How to install lxml? The following error appears when i try pip install lxml C:\Program Files\Python311>pip install lxml Collecting lxml Using cached lxml-4.9.1.tar.gz (3.4 MB) Preparing metadata (setup.py) ... done Installing collected packages: lxml DEPRECATION: lxml is being installed using the legacy 'se...
How to install lxml?
The following error appears when i try pip install lxml C:\Program Files\Python311>pip install lxml Collecting lxml Using cached lxml-4.9.1.tar.gz (3.4 MB) Preparing metadata (setup.py) ... done Installing collected packages: lxml DEPRECATION: lxml is being installed using the legacy 'setup.py install' method, be...
[ "First you can download the lxml-3.4.2-cp34-none-win_amd64.whl and try to install it, if you have something wrong try with the win_32 version:\nVisit this link : How to install lxml on Windows\ngood luck\n" ]
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "python_requests", "scrapy", "selenium" ]
stackoverflow_0074292365_beautifulsoup_python_python_requests_scrapy_selenium.txt
Q: How To create a Cloud Run container by using Python Library? How to create a container of cloud run by python library like from google.cloud import run_v2, I am not getting any example for creating container with by python code A: Well, first you need to create a service account and credentials here https://cons...
How To create a Cloud Run container by using Python Library?
How to create a container of cloud run by python library like from google.cloud import run_v2, I am not getting any example for creating container with by python code
[ "Well, first you need to create a service account and credentials here https://console.cloud.google.com/apis/credentials?project=\nNext, you need to either download the key or use any other authentication method, in my example, the key.\n# init credentials\nfrom google.oauth2 import service_account\ncredentials = s...
[ 0 ]
[]
[]
[ "google_apis_explorer", "google_cloud_functions", "google_cloud_platform", "python" ]
stackoverflow_0072300934_google_apis_explorer_google_cloud_functions_google_cloud_platform_python.txt
Q: Python using timedelta around DST hour I have a script that receives regular pings, and whenever the last ping is more than 10 minutes ago it throws an error and goes into panic mode. Simplified example: from datetime import datetime import time from random import randint class Checker: def __init__(self): ...
Python using timedelta around DST hour
I have a script that receives regular pings, and whenever the last ping is more than 10 minutes ago it throws an error and goes into panic mode. Simplified example: from datetime import datetime import time from random import randint class Checker: def __init__(self): self.last_ping = datetime.now() ...
[ "A way to avoid DST issues: use UTC. Ex:\nfrom datetime import datetime, timezone\n\nclass Checker:\n def __init__(self):\n self.last_ping = datetime.now(timezone.utc)\n\n def ping(self):\n self.last_ping = datetime.now(timezone.utc)\n\n def panic_if_stale(self):\n if (datetime.now(tim...
[ 2 ]
[]
[]
[ "datetime", "dst", "python", "timezone" ]
stackoverflow_0074291715_datetime_dst_python_timezone.txt
Q: AttributeError: 'builtin_function_or_method' object has no attribute 'split'. What is wrong? class SquareMatrix: def __init__(self, order): self.order = order self.rows = [ [0 for j in range(order)] for i in range(order)] def __str__(self): x = '' f...
AttributeError: 'builtin_function_or_method' object has no attribute 'split'. What is wrong?
class SquareMatrix: def __init__(self, order): self.order = order self.rows = [ [0 for j in range(order)] for i in range(order)] def __str__(self): x = '' for row in self.rows: x = x + ' '.join(map(str, row))+'\n' return x def se...
[ "It looks like the problem is in your load method:\n @classmethod\n def load(cls, filename):\n y = open(filename, 'r')\n y = y.read\n y = SquareMatrix.parse(y)\n return y\n\nThe line y = y.read is not calling the read function, it's just a reference to the function, so SquareMatrix.pa...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074291551_python.txt
Q: How to add body content in RedirectResponse using FastAPI/Starlette? I would like to use an audio file inside the /check_base endpoint. However, I can't send the file in the body of the RedirectResponse. The /check endpoint returns a RedirectResponse, which only accepts a URL parameter. Please help me on this. Her...
How to add body content in RedirectResponse using FastAPI/Starlette?
I would like to use an audio file inside the /check_base endpoint. However, I can't send the file in the body of the RedirectResponse. The /check endpoint returns a RedirectResponse, which only accepts a URL parameter. Please help me on this. Here is my code: @router.post("/check") async def check( request: Request...
[ "A redirection in the HTTP protocol is basically a header, i.e., the Location response header, indicating the URL to redirect a page to. That being said, it does not prevent one to provide body in the response as well. Since FastAPI/Starlette's RedirectResponse does not provide the relevant content parameter, which...
[ 0 ]
[]
[]
[ "fastapi", "python", "redirect", "starlette" ]
stackoverflow_0074290776_fastapi_python_redirect_starlette.txt
Q: Python : Is there a Way to Rotate and Reposition a rectangle in 2D? Hey Guys I am searching for a possible solution for this: I have Points which build a rectangle. Now I am trying to transform it: Rotation r for x-Degress (lets say 30 degrees clockwise) this is the hardest for me Move in X and Y Direction (lets ...
Python : Is there a Way to Rotate and Reposition a rectangle in 2D?
Hey Guys I am searching for a possible solution for this: I have Points which build a rectangle. Now I am trying to transform it: Rotation r for x-Degress (lets say 30 degrees clockwise) this is the hardest for me Move in X and Y Direction (lets say 1 to the X and 10) ((already solved, but maybe more elegant way?) sca...
[ "I believe you are looking for a function like this:\ndef rotate(x_list, y_list, angle):\n angle = math.radians(angle)\n new_x = []\n new_y = []\n centre_x = sum(x_list)/len(x_list)\n centre_y = sum(y_list)/len(y_list)\n print(centre_x, centre_y)\n for i in range(len(x_list)):\n x = cent...
[ 0 ]
[]
[]
[ "python", "rotation", "rotational_matrices" ]
stackoverflow_0074291227_python_rotation_rotational_matrices.txt
Q: Gtk4 Gtk.Video() doesn't play It's been a while now that Gtk4 shipped out, with a new Gtk.Video() component that allows to display a video in a Gtk window without resorting to using Gstreamer. It's a very simple class with only a handful of subclasses (4) methods (10) & attributes (2). But no matter how hard I try...
Gtk4 Gtk.Video() doesn't play
It's been a while now that Gtk4 shipped out, with a new Gtk.Video() component that allows to display a video in a Gtk window without resorting to using Gstreamer. It's a very simple class with only a handful of subclasses (4) methods (10) & attributes (2). But no matter how hard I try, I can't find a single example (? ...
[ "Ok, I found out that I missed a library:\nsudo apt install libgtk-4-media-gstreamer\n\nDit the trick, it works now. It's very slow but it works.\n" ]
[ 0 ]
[]
[]
[ "gtk4", "python", "video" ]
stackoverflow_0074201946_gtk4_python_video.txt
Q: Check if a value is present at another relative date in a table I have a series of data with dates and events that occurred on those dates (one line per event). I would like to know if a given event has occurred again two days after the first occurrence. Example of a table : date event 01/01/2000 a 01/01/2000 ...
Check if a value is present at another relative date in a table
I have a series of data with dates and events that occurred on those dates (one line per event). I would like to know if a given event has occurred again two days after the first occurrence. Example of a table : date event 01/01/2000 a 01/01/2000 b 01/01/2000 c 01/01/2000 d 02/01/2000 e 02/01/2000 f 02/01/2000...
[ "The best way to handle this type of issue is to join the table on itself and then check for rows where your condition is True.\nExample\n### Setup Start ###\nimport pandas as pd\nevents = [\n('01/01/2000', 'a'),\n('01/01/2000', 'b'),\n('01/01/2000', 'c'),\n('01/01/2000', 'd'),\n('02/01/2000', 'e'),\n('02/01/2000',...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074290009_pandas_python.txt
Q: ModuleNotFoundError: No module named 'webapp.user' at urls.py, I want to import webapp/user/views.py/ConfirmEmailView. so write code like this > from webapp.user.views import ConfirmEmailView and here is my Directory Structure.. but when I run this, error arises.. daesin_back-django-1 | Traceback (most recent ca...
ModuleNotFoundError: No module named 'webapp.user'
at urls.py, I want to import webapp/user/views.py/ConfirmEmailView. so write code like this > from webapp.user.views import ConfirmEmailView and here is my Directory Structure.. but when I run this, error arises.. daesin_back-django-1 | Traceback (most recent call last): daesin_back-django-1 | File "manage.py", li...
[ "Your root package directory is not the webapp package. Your root package is determined by the location of manage.py. So you have to import your ConfirmEmailView by calling: from user.views import ConfirmEmailView.\nYou will probably need to put all django apps into a dedicated package like \"apps\" if you want to ...
[ 3 ]
[]
[]
[ "django", "django_rest_framework", "python", "python_3.x" ]
stackoverflow_0074292630_django_django_rest_framework_python_python_3.x.txt
Q: How to highlight certain table rows in Plotly? In my table from a dataset I need to highlight rows in bold that contain "All" in columns Building, Floor or Teams: My code : headerColor = 'darkgrey' rowEvenColor = 'lightgrey' rowOddColor = 'white' fig_occ_fl_team = go.Figure(data=[go.Table( header=dict( val...
How to highlight certain table rows in Plotly?
In my table from a dataset I need to highlight rows in bold that contain "All" in columns Building, Floor or Teams: My code : headerColor = 'darkgrey' rowEvenColor = 'lightgrey' rowOddColor = 'white' fig_occ_fl_team = go.Figure(data=[go.Table( header=dict( values=list(final_table_occ_fl_team.columns), line_...
[ "You can add the bold style to your dataframe prior to creating the table as follows:\nimport pandas as pd\n\ndf = pd.DataFrame().from_dict(data)\n\nindices = df.index[(df[[\"Building\",\"Floor\",\"Team\"]] == \"All\").all(1)]\n\nfor i in indices:\n for j in range(len(df.columns)):\n df.iloc[i,j] = \"<b>{...
[ 0 ]
[]
[]
[ "pandas", "plotly_python", "python" ]
stackoverflow_0074288062_pandas_plotly_python_python.txt
Q: PaddleOCR freezes on MacOs Ventura M1 This is my First ever post here I have been working on a python script to get text from photos using PaddleOCR. Obviously everything works as expected on Windows x64. I managed to install paddleocr successfully on my MacBook Pro M1 by manually compiling a few dependencies lik...
PaddleOCR freezes on MacOs Ventura M1
This is my First ever post here I have been working on a python script to get text from photos using PaddleOCR. Obviously everything works as expected on Windows x64. I managed to install paddleocr successfully on my MacBook Pro M1 by manually compiling a few dependencies like MuPdf and lanms-neo however, the script h...
[ "I've got an M1 Mac, got it working last week with these versions:\npip install paddlepaddle==2.3.2\npip install paddleocr==2.6.1.0\npip install opencv-python==4.5.5.64\n\n" ]
[ 0 ]
[]
[]
[ "apple_m1", "paddle_paddle", "paddleocr", "python", "python_3.x" ]
stackoverflow_0074255404_apple_m1_paddle_paddle_paddleocr_python_python_3.x.txt
Q: Python- fit logarithmic model courve on a data I want to fit better my model to my data. Now I use this code: import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit as sc x_value=np.array([30000,27850,25590,23900,22400,20470,19450,18120,17130,16180,15340,14620,13730,13400,12790,12...
Python- fit logarithmic model courve on a data
I want to fit better my model to my data. Now I use this code: import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit as sc x_value=np.array([30000,27850,25590,23900,22400,20470,19450,18120,17130,16180,15340,14620,13730,13400,12790,12460,12060,11760,11440,11200,10940,10780,10720,10530]...
[ "I guess two possible causes for the discrepancy of your result :\n\nConfusion between x and y in the code versus data, as already mentioned in chrslg's comment.\nModel function not well convenient. The simple power function might be not sufficient. I suggest to consider some shifts (a) on y and (c) on x as shown i...
[ 1, 1 ]
[]
[]
[ "curve_fitting", "logarithm", "python" ]
stackoverflow_0074289689_curve_fitting_logarithm_python.txt
Q: Using groupby to get % of subtotal by group data = {'car': ['ford', 'ford','ford','toyota', 'honda', 'toyota','kia', 'nissan','honda'], 'colorblue': [1,1,0,1,1,0,0,0,1], 'colorred': [0,0,1,0,0,1,0,0,0], 'colorblack': [0,0,0,0,0,0,1,1,0], 'volume': [1,1,1,1,1,1,1,1,1] } df =...
Using groupby to get % of subtotal by group
data = {'car': ['ford', 'ford','ford','toyota', 'honda', 'toyota','kia', 'nissan','honda'], 'colorblue': [1,1,0,1,1,0,0,0,1], 'colorred': [0,0,1,0,0,1,0,0,0], 'colorblack': [0,0,0,0,0,0,1,1,0], 'volume': [1,1,1,1,1,1,1,1,1] } df = pd.DataFrame(data) df df['colorbluepercent'] =...
[ "One convenient way is to use value_counts(normalize=True) in your groupby, which returns the count of each value divided by the total count in each group:\n>>> df.groupby(\"car\").colorblue.value_counts(normalize=True)\ncar colorblue\nford 1 0.666667\n 0 0.333333\nhonda 1 ...
[ 0, 0 ]
[]
[]
[ "python", "transform" ]
stackoverflow_0074283521_python_transform.txt
Q: How to delete and then create topics correctly in a script for Kafka? I am working on a script to refresh my topics on an AWS managed Kafka cluster. I need to wipe out the existing data whenever I run the script and I did it by deleting and creating the same topics again. I expect the script to print out successfu...
How to delete and then create topics correctly in a script for Kafka?
I am working on a script to refresh my topics on an AWS managed Kafka cluster. I need to wipe out the existing data whenever I run the script and I did it by deleting and creating the same topics again. I expect the script to print out successful deletion and successful creation when I repeatedly run it. But deletion/c...
[ "Topic deletion is an async operation on the server side. Your future result only captures the response of the request (topic being marked for deletion), not the actual cluster deleting all replicas.\nRelated Kafka - delete a topic completely\n", "Had the same issue.\nThe topic deletion command is issued by your ...
[ 1, 0 ]
[]
[]
[ "apache_kafka", "confluent_kafka_python", "python" ]
stackoverflow_0073115898_apache_kafka_confluent_kafka_python_python.txt
Q: Increment the alphabets I am practicing for an interview and one of the past questions asked to the interviewes is to - "Write a program that increments the alphabet such that A becomes B, Z becomes AA, and ABZ becomes ACA." I need help on understanding how I could achieve the intended result. I tried using a simp...
Increment the alphabets
I am practicing for an interview and one of the past questions asked to the interviewes is to - "Write a program that increments the alphabet such that A becomes B, Z becomes AA, and ABZ becomes ACA." I need help on understanding how I could achieve the intended result. I tried using a simple function which increments ...
[ "Appears similar to Potential interview question: building a pseudocode string incrementer similar to Excel columns\n\nEssentially, it asks to build a string incrementer so that A + 1 = B... Z + 1 = AA, AA + 1 = AB... ZZ + 1 = AAA... and so forth.\nCode\ndef incr(s):\n '''\n Incremental for string s\n ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074292052_python.txt
Q: Python regex. Get the last word from a sequence I have a line like this: jsdata="l7Bhpb;_;CJWKh4 cECq7c;_;CJWKiA" data-ved="2ahUKEwjxq7L29Yr7AhWM7qQKHRABDVEQ2esEegQIGxAE"> I need to get the word CJWKiA. But I don't understand how to write it in the regex language. My failed attempt: jsdata=\".+?;.+?\" This returns...
Python regex. Get the last word from a sequence
I have a line like this: jsdata="l7Bhpb;_;CJWKh4 cECq7c;_;CJWKiA" data-ved="2ahUKEwjxq7L29Yr7AhWM7qQKHRABDVEQ2esEegQIGxAE"> I need to get the word CJWKiA. But I don't understand how to write it in the regex language. My failed attempt: jsdata=\".+?;.+?\" This returns the entire string, including the word I need :( I do...
[ "/jsdata=\"[^\"]*;([^;\"]*)\"/gm\n\nYou can't have double quotes in the attribute.\n" ]
[ 1 ]
[]
[]
[ "python", "python_re", "regex" ]
stackoverflow_0074292837_python_python_re_regex.txt
Q: Use AWS wrangler without AWS cli I'm running the following code through AWS wrangler import awswrangler as wr my_query = wr.athena.read_sql_query( sql="""select "$path" as path from table""", database='db', workgroup='workgroup' ) But I don't wish to use static methods such as Aws Cli or configurations f...
Use AWS wrangler without AWS cli
I'm running the following code through AWS wrangler import awswrangler as wr my_query = wr.athena.read_sql_query( sql="""select "$path" as path from table""", database='db', workgroup='workgroup' ) But I don't wish to use static methods such as Aws Cli or configurations file to store my creds. How do I add th...
[ "I had to create a boto3 session and pass it as a parameter value\nmy_session = boto3.Session(region_name=\"REGION\", \\ \naws_access_key_id=\"YOUR_ACCESS_KEY\", aws_secret_access_key=\"YOUR_SECRET_ACCESS_KEY\")\n\nmy_query = wr.athena.read_sql_query(\n sql=\"\"\"select \"$path\" as path from table\"\"\",\n ...
[ 1 ]
[]
[]
[ "amazon_athena", "aws_data_wrangler", "python" ]
stackoverflow_0074292965_amazon_athena_aws_data_wrangler_python.txt
Q: How can I see log messages when unit testing in PyCharm? I'm sure this is a simple fix, but I'd like to view log messages in the PyCharm console while running a unit test. The modules I'm testing have their own loggers, and normally I'd set a root logger to catch the debugging messages at a certain level, and pipe...
How can I see log messages when unit testing in PyCharm?
I'm sure this is a simple fix, but I'd like to view log messages in the PyCharm console while running a unit test. The modules I'm testing have their own loggers, and normally I'd set a root logger to catch the debugging messages at a certain level, and pipe the other logs to a file. But I can't figure out how this wor...
[ "The only solution I've found is to do the normal logging setup at the top of the file with tests in it (assuming you're just running one test or test class): logging.basicConfig(level=logging.DEBUG). Make sure you put that before most import statements or the default logging for those modules will have already bee...
[ 23, 2, 2, 1, 1, 0 ]
[ "Add a stream handler, pointing to sys.stdout if doctest or pytest is running: \n import logging\n import sys\n logger = logging.getLogger()\n\n def setup_doctest_logger(log_level:int=logging.DEBUG):\n \"\"\"\n\n :param log_level:\n :return:\n\n >>> logger.info('test') # ...
[ -1 ]
[ "pycharm", "python" ]
stackoverflow_0024470062_pycharm_python.txt
Q: Python: How to prevent special characters in input My problem is when I enter a number in the input field, it becomes number with special character. I don't know why it's adding extra characters to input. You can see the example. I entered just 5.2 and it became '5.2& """ length of rectangle = a width of rectangle...
Python: How to prevent special characters in input
My problem is when I enter a number in the input field, it becomes number with special character. I don't know why it's adding extra characters to input. You can see the example. I entered just 5.2 and it became '5.2& """ length of rectangle = a width of rectangle = b calculate the area and perimeter of the rectangle "...
[ "For me It's working fine...See my output..\nNote: It throws error at last line in your code because you can't concatenate a str with an int.\nSo, you need to convert int to str before concatenating your variables\na = 6\nb = float(input(\"width: \"))\nprint(b)\n\narea = a*b\nperimeter = (2*a) + (2*b)\n\nprint(\"ar...
[ 1, 0 ]
[]
[]
[ "python", "python_3.9", "string" ]
stackoverflow_0074292353_python_python_3.9_string.txt
Q: Building Python and OpenSSL from source, but ssl module fails I'm trying to build Python and OpenSSL from source in a container. Both seem to build correctly, but Python does not successfully create the _ssl module. I've found a few guides online that say to un-comment and lines from Python-3.X.X/Modules/Setup an...
Building Python and OpenSSL from source, but ssl module fails
I'm trying to build Python and OpenSSL from source in a container. Both seem to build correctly, but Python does not successfully create the _ssl module. I've found a few guides online that say to un-comment and lines from Python-3.X.X/Modules/Setup and add the --openssldir=/usr/local/ssl flag to the ./configure step ...
[ "\nFollowing modules built successfully but were removed because they could not be imported:\n_hashlib _ssl \n\nCould not build the ssl module!\nPython requires an OpenSSL 1.0.2 or 1.1 compatible libssl with X509_VERIFY_PARAM_set1_host().\nLibreSSL 2.6.4 and earlier ...
[ 3, 1, 0 ]
[]
[]
[ "docker", "linux", "openssl", "python", "ssl" ]
stackoverflow_0060536472_docker_linux_openssl_python_ssl.txt
Q: Use annotations on Pytnon 3.6.5 I'm working on a project where I was asked to code some validations using Chain of Responsibility. I am currently using python 3.9.2 on my machine, but the project on docker is on 3.6.5 This piece of code works nice on my machine, but it breaks on Docker: from __future__ import anno...
Use annotations on Pytnon 3.6.5
I'm working on a project where I was asked to code some validations using Chain of Responsibility. I am currently using python 3.9.2 on my machine, but the project on docker is on 3.6.5 This piece of code works nice on my machine, but it breaks on Docker: from __future__ import annotations from abc import ABC, abstract...
[ "I've found this answer on github and I'm reposting it in case anyone ends up here like me.\nAs pointed out by @ForceBru annotations as part of __future__ was introduced with Python 3.7+, so you'll need to add de dependency manually (or move up the python version, which I would recommend)\nTo add the dependency do ...
[ 0 ]
[]
[]
[ "chain_of_responsibility", "django", "python" ]
stackoverflow_0066640159_chain_of_responsibility_django_python.txt
Q: Can't open camera by index on Raspberry-pi4 So, i installed the official Raspberry-pi OS "Raspberry pi OS Lite 64" and installed OpenCV. But when trying to call cv2.VideoCapture(1) an error appears (i have USB camera): [ WARN:0@0.021 ] global /io/opencv/modules/videoio/src/cap_v4l.cpp (902) open VIDEOIO(V4L2:/dev/...
Can't open camera by index on Raspberry-pi4
So, i installed the official Raspberry-pi OS "Raspberry pi OS Lite 64" and installed OpenCV. But when trying to call cv2.VideoCapture(1) an error appears (i have USB camera): [ WARN:0@0.021 ] global /io/opencv/modules/videoio/src/cap_v4l.cpp (902) open VIDEOIO(V4L2:/dev/video0): can't open camera by index. My code: i...
[ "Ohh, i just turned off my Raspberry-pi and wait about 30 minutes. Know it works...\n" ]
[ 0 ]
[]
[]
[ "opencv", "python", "raspberry_pi4", "usb_camera" ]
stackoverflow_0074291451_opencv_python_raspberry_pi4_usb_camera.txt
Q: Different accuracy for cross_val_score and train_test_split I am testing RandomForestClassifier on simple dataset from sklearn. When I split the data with train_test_split, I get accuracy=0.89. If I use cross-validation with cross_val_score with same parameters of classifier, accuracy is smaller - about 0.83. Why?...
Different accuracy for cross_val_score and train_test_split
I am testing RandomForestClassifier on simple dataset from sklearn. When I split the data with train_test_split, I get accuracy=0.89. If I use cross-validation with cross_val_score with same parameters of classifier, accuracy is smaller - about 0.83. Why? Here is the code: from sklearn.model_selection import cross_val_...
[ "Cross validation is used to run multiple experiments on different splits of data and then average their results. This is to ensure that the result of the experiment is not biased by one split, as it is in your case.\nYour chosen seed along with some luck gave you a test train split which has higher accuracy than t...
[ 2, 1 ]
[]
[]
[ "cross_validation", "python", "random_forest", "scikit_learn" ]
stackoverflow_0074292786_cross_validation_python_random_forest_scikit_learn.txt
Q: How to add two columns of a Stata/CSV file in python I have a CSV file with two columns (permno_adj and publn_year) and I want to combine them but don't know how to do it. The code I am using: patents = pd.read_csv('E:/Work/file.csv') patents = patents[['publn_nr', 'permno_adj', 'publn_year', 'IPC1']].dropna().dr...
How to add two columns of a Stata/CSV file in python
I have a CSV file with two columns (permno_adj and publn_year) and I want to combine them but don't know how to do it. The code I am using: patents = pd.read_csv('E:/Work/file.csv') patents = patents[['publn_nr', 'permno_adj', 'publn_year', 'IPC1']].dropna().drop_duplicates().reset_index(drop=True) patents = patents[(...
[ "You could concatenate like string\npatents['new_column'] = patents['permno_adj'].astype(str) + patents['publn_year'].astype(str)\n\n", "follow assign function pandas assign\nd = {'col1': ['c11', 'c12'], 'col2': ['c21', 'c22']}\ndf = pd.DataFrame(d)\ndf = df.assign(col3=df['col1'] + df['col2'])\ndf\n col1 col2 ...
[ 1, 1 ]
[]
[]
[ "csv", "pandas", "python" ]
stackoverflow_0074293031_csv_pandas_python.txt
Q: Extracting a column out I have a list of array of the form. params = [[array([7.30946927, 2.40445369])], [array([7.30886254, 2.40241312])], [array([7.21275251, 2.09358208])], [array([7.61757898, 0.15745312])], [array([7.76890152, 2.70100186])], [array([7.82943027, 2.39066977])], [array([7.20117715, 2.0525955...
Extracting a column out
I have a list of array of the form. params = [[array([7.30946927, 2.40445369])], [array([7.30886254, 2.40241312])], [array([7.21275251, 2.09358208])], [array([7.61757898, 0.15745312])], [array([7.76890152, 2.70100186])], [array([7.82943027, 2.39066977])], [array([7.20117715, 2.05259557])], [array([7.21455828, 2....
[ "values = []\nfor i in params :\n values.append(i[0][0])\n\nprint(values)\n\n" ]
[ 0 ]
[]
[]
[ "columnsorting", "python" ]
stackoverflow_0074293096_columnsorting_python.txt
Q: Python: Limit the maximum amount of decimals in all print calls I have a script with a lot of print calls. I want to limit all the printed numbers to a maximum of 5 decimals, but changing it by hand with f_strings or formatting would be a lot of work. Is there any way to specify at the beginning of the script that...
Python: Limit the maximum amount of decimals in all print calls
I have a script with a lot of print calls. I want to limit all the printed numbers to a maximum of 5 decimals, but changing it by hand with f_strings or formatting would be a lot of work. Is there any way to specify at the beginning of the script that whenever I call a print function or use an f string, I do not want t...
[ "As I do not think there is a method of setting a float precision for the entire code, maybe a not-so-elegant custom print method that takes in multiple parameters would be useful. For example-\ndef myprint(dict_to_print: Dict[str,float], precision:int)->None:\n to_print = f\"\"\n for key, value in dict_to_pr...
[ 0 ]
[]
[]
[ "f_string", "formatting", "numpy", "python" ]
stackoverflow_0074292290_f_string_formatting_numpy_python.txt
Q: How can I disconnect telethon client, when an event handler does not received any new message event, even after waiting for specific time? I wanna disconnect client if I didn't received any message even after waiting for 2 minutes. But it keeps on waiting for ever. I feel await_for is an alternative but I looking ...
How can I disconnect telethon client, when an event handler does not received any new message event, even after waiting for specific time?
I wanna disconnect client if I didn't received any message even after waiting for 2 minutes. But it keeps on waiting for ever. I feel await_for is an alternative but I looking for solution right here itself anyone please help. Thanks in advance.!! client.connect() #send message in chat @client.on(events.NewMessage) as...
[ "\nDissconnect is an asynchronous function i.e coroutine.\nUse await client.disconnect() instead.\n\n" ]
[ 0 ]
[]
[]
[ "python", "telegram", "telethon" ]
stackoverflow_0071061905_python_telegram_telethon.txt
Q: How do I structure this small project? A Garage holds a list of Cars. Each Car can only belong to one Garage. Garages can add/remove cars. Cars can move Garages. Garages need to keep track of which Cars they have. Cars need to store which Garage they are in. I have three files: car.py import garage class Car: ...
How do I structure this small project?
A Garage holds a list of Cars. Each Car can only belong to one Garage. Garages can add/remove cars. Cars can move Garages. Garages need to keep track of which Cars they have. Cars need to store which Garage they are in. I have three files: car.py import garage class Car: def __init__(self, garage: garage.Garage): ...
[ "All the relations between your classes are architectual concers. But in your case you can check out forward references.\nFrom pep docs\n\nWhen a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later.\n\nThat being said, you should pass y...
[ 1 ]
[]
[]
[ "python", "python_import" ]
stackoverflow_0074292990_python_python_import.txt
Q: exploding multiple columns in Pandas Need to explode the data on multiple columns in pandas input dataframe: df SRCA SRCB SRC_CNTA SRC_CNTB A,B G,H 1 1 E,C,D Z,Y,K 2 2 code that is used for this is: df.set_index(['SRC_CNTA','SRC_CNTB']).apply(pd.Series.explode).reset_index() T...
exploding multiple columns in Pandas
Need to explode the data on multiple columns in pandas input dataframe: df SRCA SRCB SRC_CNTA SRC_CNTB A,B G,H 1 1 E,C,D Z,Y,K 2 2 code that is used for this is: df.set_index(['SRC_CNTA','SRC_CNTB']).apply(pd.Series.explode).reset_index() This will exclude the index columns and to ...
[ "We can use apply (the vectorized version, so it's not slow) to split and explode both columns. Then we join back on index:\nexpl = df[[\"SRCA\", \"SRCB\"]].apply(lambda col: col.str.split(\",\").explode()).add_suffix(\"_EXP\")\ndf = df.join(expl).reset_index(drop=True)\n\n SRCA SRCB SRC_CNTA SRC_CNTB SRCA_E...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074293149_pandas_python.txt
Q: Python: Extracting all data from dictionary columns and put them into columns I have a table that includes a column that includes a dictionary. In this dictionary, there is a key, and a list of dictionary values as follow: id dict_vals 123 {'key_a':[{'a':1,'b':8,'c':7},{'a':14,'b':6,'c':8},{'a':9,'b':4,'c':9},.....
Python: Extracting all data from dictionary columns and put them into columns
I have a table that includes a column that includes a dictionary. In this dictionary, there is a key, and a list of dictionary values as follow: id dict_vals 123 {'key_a':[{'a':1,'b':8,'c':7},{'a':14,'b':6,'c':8},{'a':9,'b':4,'c':9},...,{'a_t':67,'b_t':41,'c_t':6}]} 345 {'key_a':[{'a':5,'b':82,'c':72},{'a':4,...
[ "Try this:\n\nFor removing the last element in list you can return list with slicing like this [:-1].\nYou can extract dataframe from each dict and use pd.merge for merging all dataframes.\nYou can use functools.reduce for merging multiple dfs.\nYou can use pandas.apply with axis=1 and iterate each row and find the...
[ 1, 0 ]
[]
[]
[ "dictionary", "pandas", "python" ]
stackoverflow_0074292532_dictionary_pandas_python.txt
Q: Dividing of a table into groups of directly/indirectly connected elements in Python I have following table (elements from col. A and B are linked - building kind of a graph with direct & indirect connections). I am looking for a way to create separate groups (=lists) that will only contain elements that are only l...
Dividing of a table into groups of directly/indirectly connected elements in Python
I have following table (elements from col. A and B are linked - building kind of a graph with direct & indirect connections). I am looking for a way to create separate groups (=lists) that will only contain elements that are only linked to each other (directly & indirectly), such as: {a, b, d, x} and {c, y, z}. I figu...
[ "EDIT\nWhat you are looking for is to find all connected components in an undirected graph. You can use the code given here https://www.geeksforgeeks.org/connected-components-in-an-undirected-graph/:\n\n# Python program to print connected\n# components in an undirected graph\n \n \nclass Graph:\n \n # init funct...
[ 2, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074292048_pandas_python.txt
Q: Python: how to access list of dictionary and matching the value of key element I have a list of dictionary like this, I want to loop through all the "message" value and then if the value match "App init" , then i will sys.exit(0) if the "message" value match "Error" I will sys.Exit(1). But the problem is I don't ...
Python: how to access list of dictionary and matching the value of key element
I have a list of dictionary like this, I want to loop through all the "message" value and then if the value match "App init" , then i will sys.exit(0) if the "message" value match "Error" I will sys.Exit(1). But the problem is I don't see the code match the( log[index]['message'] in 'App init') conditon since I don't...
[ "log[index]['message'] in 'App init' should be reversed: 'App init' in log[index]['message']. The same for ERROR\n" ]
[ 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074252621_dictionary_list_python.txt
Q: Why does cd not work after For Loop in batch file? I am trying to write a simple batch file that will go through steps to either activate existing or create new virtual environments. Creating and activating the newly create virtual environment works as expected, but the problem arises when I try to activate an ex...
Why does cd not work after For Loop in batch file?
I am trying to write a simple batch file that will go through steps to either activate existing or create new virtual environments. Creating and activating the newly create virtual environment works as expected, but the problem arises when I try to activate an existing virtual environment. Below is the code that I hav...
[ "For anybody who might stumble upon this problem.\nIt seems that the direct calling of batch files is sometimes executes and then exits. I believe direct calling exits after completion in certain instances, which would explain why it appeared that the code above wasn't working. I have solved this issue by replaci...
[ 0 ]
[]
[]
[ "batch_file", "cmd", "python" ]
stackoverflow_0074290214_batch_file_cmd_python.txt
Q: TypeError: __init__() missing 1 required positional argument: 'head' my compiler is giving error at line 51 I am trying to learn linked list in ppython. This is a really simple code. All I am trying to do here is to call a class's constructor. But it is giving me an error. It is saying: #This is the code I have wr...
TypeError: __init__() missing 1 required positional argument: 'head' my compiler is giving error at line 51
I am trying to learn linked list in ppython. This is a really simple code. All I am trying to do here is to call a class's constructor. But it is giving me an error. It is saying: #This is the code I have written please help me resolve this problem class node: def __init__(self,data): self.data=data ...
[ "The problem here is that you're calling linkedlist constructor with no arguments:\n mylist=linkedlist()\n\nwhereas in the class definition it has one positional arguments 'head':\nclass linkedlist:\n def __init__(self, head):\n\nTo fix the error you'd need to provide 'head' argument to the constructor, e.g.\nmy...
[ 1, 0 ]
[]
[]
[ "data_structures", "linked_list", "python", "singly_linked_list" ]
stackoverflow_0074293226_data_structures_linked_list_python_singly_linked_list.txt
Q: why I am getting this error even though I have installed openai? I tried to uninstall and reinstall it but still getting this errors A: Try to run this code with cmd sometimes it happens code doesn't work on vs but work fine when run on cmd and also put " on line 4 after key
why I am getting this error even though I have installed openai?
I tried to uninstall and reinstall it but still getting this errors
[ "Try to run this code with cmd sometimes it happens code doesn't work on vs but work fine when run on cmd and also put \" on line 4 after key\n" ]
[ 1 ]
[]
[]
[ "openai", "python" ]
stackoverflow_0074291048_openai_python.txt
Q: can you get results returned other than using pandas on yolov5? in yolov5 tutorial it says pandas().xyxy[0] to get results from inference. results = model(testa) # inference boxes = results.pandas().xyxy[0] # gets the results but is it possible to use something else (like polars) than pandas to get the results r...
can you get results returned other than using pandas on yolov5?
in yolov5 tutorial it says pandas().xyxy[0] to get results from inference. results = model(testa) # inference boxes = results.pandas().xyxy[0] # gets the results but is it possible to use something else (like polars) than pandas to get the results returned? because using pandas is so slow and my code needs to be fast...
[ "You can process detections with NumPy. It is not clear what you desire. In my case, based on the detection class and X0 coordinate, I want to make a decision. The \"boxes\" array consists of bbox coordinates, confidence score and class id, respectively. I used the 'xywhn' format that returns normalized coordinates...
[ 0 ]
[]
[]
[ "pandas", "python", "yolov5" ]
stackoverflow_0072073489_pandas_python_yolov5.txt
Q: Function returning a key value from a dict within a list I have a list that contains dicts - I want a function that returns a key value from a dict within that list. Explanation below. The below function simulate_tournament takes a list as input and is supposed to return a string (not a list/dict) by way of indexi...
Function returning a key value from a dict within a list
I have a list that contains dicts - I want a function that returns a key value from a dict within that list. Explanation below. The below function simulate_tournament takes a list as input and is supposed to return a string (not a list/dict) by way of indexing. When I try to get the return value I need (a string which ...
[ "Your first function takes teams - a list of dicts - as a parameter and returns a name of a team. So the following line:\nteams = simulate_tournament(teams)\n\nmakes no sense, because you are replacing your list of dicts with a string containing a team name. That is why\nteams[0][\"team\"]\n\ncreates an error.\nTo ...
[ 0 ]
[]
[]
[ "dictionary", "list", "python", "recursion" ]
stackoverflow_0074293206_dictionary_list_python_recursion.txt
Q: Using a classmethod to wrap class functions, but not as an alternate constructor I've gotten in the habit of using classmethods to wrap class functions rather than as an alternate constructor. It seems great to keep all relevant functions within the class namespace rather than defining a wrapper function in the ge...
Using a classmethod to wrap class functions, but not as an alternate constructor
I've gotten in the habit of using classmethods to wrap class functions rather than as an alternate constructor. It seems great to keep all relevant functions within the class namespace rather than defining a wrapper function in the general namespace. I've been told this is unpythonic and I haven't seen this pattern els...
[ "\"unpythonic\" is rather subjective (in most cases :-) ). Although I'd myself opt for using the function pattern in most places - it may make sense in certain projects, or even in certain parts of larger projects to prefer using the class namespace as you want.\nThat said, nothing against your pattern. If it does ...
[ 0, 0 ]
[]
[]
[ "class_method", "design_patterns", "python", "python_3.x" ]
stackoverflow_0070039175_class_method_design_patterns_python_python_3.x.txt
Q: With python what is the most efficient way to tokenize a string (SELFIES) to a list? I am currently working with SELFIES (self-referencing embedded strings, github : https://github.com/aspuru-guzik-group/selfies) which is basically a string representation of a molecule. Basically it is a sequence of tokens that ar...
With python what is the most efficient way to tokenize a string (SELFIES) to a list?
I am currently working with SELFIES (self-referencing embedded strings, github : https://github.com/aspuru-guzik-group/selfies) which is basically a string representation of a molecule. Basically it is a sequence of tokens that are defined by brackets , e.g. propane would be written as "[C][C][C]". I would like to find...
[ "With regex you can do it as follows:\nimport re\n\ndef get_selfie_chars(selfie):\n return re.findall(r\".*?]\", selfie)\n\nIf a point should be a separate match then:\n return re.findall(r\"\\.|.*?]\", selfie)\n\n", "Another:\nselfies.replace(']', '] ').split()\n\nBenchmark with 50 tokens (since you said t...
[ 1, 1, 0 ]
[]
[]
[ "performance", "python", "regex", "string", "tokenize" ]
stackoverflow_0074292354_performance_python_regex_string_tokenize.txt
Q: redirecting to homepage after user submits a blog post? I'm very new to using Django and coding in general. So I have figured out how to make the form submit to my database but now when it submits, it just brings you to the blank blog_post view and I'm not understanding how to redirect correctly. here is the views...
redirecting to homepage after user submits a blog post?
I'm very new to using Django and coding in general. So I have figured out how to make the form submit to my database but now when it submits, it just brings you to the blank blog_post view and I'm not understanding how to redirect correctly. here is the views.py: from django.shortcuts import render, redirect from .mode...
[ "Assuming you want to redirect in home.html which is rendered by postslist view so the view should be like this:\ndef blog_post(request):\n\n if request.method == \"POST\":\n form=PostForm(request.POST)\n if form.is_valid():\n form.instance.user = request.user\n form.save()\n ...
[ 3, 3 ]
[]
[]
[ "django", "django_forms", "django_urls", "django_views", "python" ]
stackoverflow_0074292984_django_django_forms_django_urls_django_views_python.txt
Q: Python interleave stdin/stdout of subprocess similar to terminal I'm writing an autograder for student assignments. Some of the assignments are to write programs that read from STDIN and print to STDOUT. Currently, my grader passes the input in a single batch and then reads all the STDOUT as a single batch (impl: ...
Python interleave stdin/stdout of subprocess similar to terminal
I'm writing an autograder for student assignments. Some of the assignments are to write programs that read from STDIN and print to STDOUT. Currently, my grader passes the input in a single batch and then reads all the STDOUT as a single batch (impl: I use subprocess.run(..., input="blue\n7\n".encode(), capture_output=T...
[ "The comments from Charles Duffy, together with information from this answer to another question let to my current solution.\nInstead of running the student submission through Popen (or derivative), I call it programmatically with runpy.run_path:\nrunpy.run_path(script_name, _globals, '__main__')\n\nThis allows me ...
[ 1 ]
[]
[]
[ "pytest", "python", "subprocess" ]
stackoverflow_0074238842_pytest_python_subprocess.txt
Q: Locust: No statistics shown I'm new to Locust, and I am attempting to log statistics for a POST request, and I'm using the following code along with a generic call to locust. import json from locust import HttpUser, task, between import cfg class BasicUser(HttpUser): wait_time = between(1, 3) v1_data = j...
Locust: No statistics shown
I'm new to Locust, and I am attempting to log statistics for a POST request, and I'm using the following code along with a generic call to locust. import json from locust import HttpUser, task, between import cfg class BasicUser(HttpUser): wait_time = between(1, 3) v1_data = json.load(open("v1_sample_data.jso...
[ "The catch_response=True is the culprit.\nFrom the documentation:\n\ncatch_response – (optional) Boolean argument that, if set, can be used to make a request return a context manager to work as argument to a with statement. This will allow the request to be marked as a fail based on the content of the response, eve...
[ 1 ]
[]
[]
[ "locust", "python" ]
stackoverflow_0074293444_locust_python.txt
Q: Training a decision tree on two different feature sets python scikit I am trying to train a decision tree using scikit. One of my feature sets looks something like this: X = [[0, 0], [1, 1]] Y = ['a','b'] #class labels The other feature set looks like this: Z = [[1,2,0.5],[2,1,0.5],[0.5,2,2] Y = ['a','b','a'] #c...
Training a decision tree on two different feature sets python scikit
I am trying to train a decision tree using scikit. One of my feature sets looks something like this: X = [[0, 0], [1, 1]] Y = ['a','b'] #class labels The other feature set looks like this: Z = [[1,2,0.5],[2,1,0.5],[0.5,2,2] Y = ['a','b','a'] #class labels I know that if I have only one feature set, I can do this: c...
[ "Calling .fit() will overwrite any attributes of the object.\nOne possibility here would be two train two classifiers on independent features and labels, and combine them to \"vote\" on the final output.\nFor example, initialize two classifiers with similar labels but different feature sets:\nfrom sklearn.tree impo...
[ 1 ]
[]
[]
[ "python", "scikit_learn" ]
stackoverflow_0074283097_python_scikit_learn.txt
Q: How to fetch data from postgres existing tables to Django? I have a Postgres Database and it has plenty of tables in it, using Django I need to query or get all the table rows into my views.py. After reading I understood that creating a model in models.py will create a new table into my DB which is not what I need...
How to fetch data from postgres existing tables to Django?
I have a Postgres Database and it has plenty of tables in it, using Django I need to query or get all the table rows into my views.py. After reading I understood that creating a model in models.py will create a new table into my DB which is not what I need. Is using django a good way to fetch data from postgres or shou...
[ "You can inspect the existing database schema by\npython manage.py inspectdb\n\nfor adding the database model to models.py\npython manage.py inspectdb > models.py\n\n" ]
[ 0 ]
[]
[]
[ "django", "postgresql", "python" ]
stackoverflow_0070770011_django_postgresql_python.txt
Q: Python Logging in Datadog All Error Status I do not understand why DataDog is showing all statuses as errors. enter image description here The script is pretty straightforward. import logging from pythonjsonlogger import jsonlogger logger = logging.getLogger() logHandler = logging.StreamHandler() formatter = jso...
Python Logging in Datadog All Error Status
I do not understand why DataDog is showing all statuses as errors. enter image description here The script is pretty straightforward. import logging from pythonjsonlogger import jsonlogger logger = logging.getLogger() logHandler = logging.StreamHandler() formatter = jsonlogger.JsonFormatter() logHandler.setFormatter(...
[ "This is likely due to the Python standard logging module defaulting to use stderr as its output stream. From the StreamHandler constructor documentation\nReturns a new instance of the StreamHandler class. If stream is specified, the instance will use it for logging output; otherwise, sys.stderr will be used.\nhttp...
[ 0 ]
[]
[]
[ "datadog", "logging", "python" ]
stackoverflow_0073807939_datadog_logging_python.txt
Q: In Django Models, At Admin Area, how to auto assign the 'requesting' user to one of the foreign key User relation field In the following mode in my project, I want to assign the author variable of class upon the creation of model, on user end this could be done via request.user but as the class can be only instan...
In Django Models, At Admin Area, how to auto assign the 'requesting' user to one of the foreign key User relation field
In the following mode in my project, I want to assign the author variable of class upon the creation of model, on user end this could be done via request.user but as the class can be only instantiated from the admin area, this doesn't work. class Blog(models.Model): title = models.CharField(max_length=300) content...
[ "The auto_created=… field [Django-doc] is about model inheritance, it does not add the logged in user: the model layer is request unaware, and there is not per se a \"logged in user\". You thus remodel this to:\nfrom django.conf import settings\nfrom django.db import models\n\n\nclass Blog(models.Model):\n title...
[ 2 ]
[]
[]
[ "django", "python", "web" ]
stackoverflow_0074293376_django_python_web.txt
Q: How to iterate a mixed of nested list and dict and filter items I have an example object which is mixed of lists and dicts: { "field_1" : "aaa", "field_2": [ { "field_3" : "bbb", ..... "field_4" : "ccc", "field_need_to_filter" : False, }, { "fi...
How to iterate a mixed of nested list and dict and filter items
I have an example object which is mixed of lists and dicts: { "field_1" : "aaa", "field_2": [ { "field_3" : "bbb", ..... "field_4" : "ccc", "field_need_to_filter" : False, }, { "field_5" : "ddd", ..... "field_6": [ { ...
[ "Try recursion:\ndct = {\n \"field_1\": \"aaa\",\n \"field_2\": [\n {\n \"field_3\": \"bbb\",\n \"field_4\": \"ccc\",\n \"field_need_to_filter\": False,\n },\n {\n \"field_5\": \"ddd\",\n \"field_6\": [\n {\n ...
[ 2, 0 ]
[]
[]
[ "dictionary", "list", "literate_programming", "nested_loops", "python" ]
stackoverflow_0074293262_dictionary_list_literate_programming_nested_loops_python.txt
Q: how can I get inside of my virtual environment? I want to know how can I enter in my pipenv shell there is this command : pipenv shell but every time I write this in the command line , it says "launching subshell in virtual environment...". but I just want to get inside of that , I dont want any subshells to be cr...
how can I get inside of my virtual environment?
I want to know how can I enter in my pipenv shell there is this command : pipenv shell but every time I write this in the command line , it says "launching subshell in virtual environment...". but I just want to get inside of that , I dont want any subshells to be created.
[ "Type the following into the terminal/cmd: \nIn Windows:\nvenv\\Scripts\\activate.bat\n\nIn Linux/macOS:\n$ . venv/bin/activate\n\n" ]
[ 0 ]
[]
[]
[ "pip", "pipenv", "python", "terminal", "virtual_environment" ]
stackoverflow_0074292585_pip_pipenv_python_terminal_virtual_environment.txt
Q: Can I create my own email using my IP address as the domain name? In theory a domain is just a glorified IP address, so if I take my public IP, Ex. 12.34.56.78 then is there a way for me to send emails from the alias of noreply@12.34.56.78? If so do I need to setup a custom email server? I don't need to receive em...
Can I create my own email using my IP address as the domain name?
In theory a domain is just a glorified IP address, so if I take my public IP, Ex. 12.34.56.78 then is there a way for me to send emails from the alias of noreply@12.34.56.78? If so do I need to setup a custom email server? I don't need to receive emails just send them. Also if it won't work, how come? TY
[ "Yes, you can.\nThere is nothing preventing you from sending an email to (test@test.com) or (test@10.10.10.10) in theory. As long as the mail server accepts hostnames and IP addresses.\nHowever, in reality, this just isn't the case.\nFor one, spam prevention has greatly increased in the past few years making most s...
[ 1 ]
[]
[]
[ "email", "flask_mail", "ip", "python", "smtp" ]
stackoverflow_0074293415_email_flask_mail_ip_python_smtp.txt
Q: Convert comma separated unique values in to multiple columns filled with binary values(0/1) How to convert comma separated values in to multiple columns using python DataFrame, as shown in the figure? A: You can split each string base ',' then use pd.get_dummies: s = df['col1'].str.split(',') df_new = pd.get_dum...
Convert comma separated unique values in to multiple columns filled with binary values(0/1)
How to convert comma separated values in to multiple columns using python DataFrame, as shown in the figure?
[ "You can split each string base ',' then use pd.get_dummies:\ns = df['col1'].str.split(',')\ndf_new = pd.get_dummies(s.apply(pd.Series).stack()).groupby(level=0).sum()\nprint(df_new)\n\nOutput:\n s1 s2 s3 s4 s5\n0 1 1 1 0 0\n1 1 1 0 0 0\n2 0 1 0 0 0\n3 1 0 0 0 0\n4 0 ...
[ 3, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074293125_dataframe_pandas_python.txt
Q: Extract data from Dell Community Forum for a specific date I want to extract the username, post title, post time and the message content from a Dell Community Forum thread of a particular date and store it into an excel file. For example, URL: https://www.dell.com/community/Inspiron-Desktops/I-am-getting-time-sync...
Extract data from Dell Community Forum for a specific date
I want to extract the username, post title, post time and the message content from a Dell Community Forum thread of a particular date and store it into an excel file. For example, URL: https://www.dell.com/community/Inspiron-Desktops/I-am-getting-time-sync-errror-and-the-last-synced-time-shown-as/m-p/8290678#M36017 I w...
[ "it seems to me you have an issue with your selectors and the fact that you're searching for them in the general scope (the entire HTML body). My approach would be to narrow down 'components' and search inside them:\n\nLocate the div that holds all comments\nSearch inside it for each comment comment container\nGet ...
[ 0, 0 ]
[]
[]
[ "beautifulsoup", "csvwriter", "python", "web_scraping" ]
stackoverflow_0074292169_beautifulsoup_csvwriter_python_web_scraping.txt
Q: Want to add '?id= ' in urls.py I have urls.py in my project. I want to create URL like localhost:8000/v1/user?id=1 Can anyone help me how I can create the above URL. Thanks A: The part right from the question mark (?) is the query string [wiki]. The urls.py do not inspect the querystring, they only care about th...
Want to add '?id= ' in urls.py
I have urls.py in my project. I want to create URL like localhost:8000/v1/user?id=1 Can anyone help me how I can create the above URL. Thanks
[ "The part right from the question mark (?) is the query string [wiki]. The urls.py do not inspect the querystring, they only care about the path (the part left from the question mark).\nThe urls.py thus uses:\nurlpatterns = [path('/v1/user', some_view)]\nin the view you then can access the last value that associate...
[ 3 ]
[]
[]
[ "django", "python", "url" ]
stackoverflow_0074293559_django_python_url.txt
Q: accessing postgresql database in python using functions Let me start off by saying I am extremely new to Python and Postgresql so I feel like I'm in way over my head. My end goal is to get connected to the dvdrental database in postgresql and be able to access/manipulate the data. So far I have: created a .config...
accessing postgresql database in python using functions
Let me start off by saying I am extremely new to Python and Postgresql so I feel like I'm in way over my head. My end goal is to get connected to the dvdrental database in postgresql and be able to access/manipulate the data. So far I have: created a .config folder and a database.ini is within there with my login cred...
[ "The fact that you established the connection is honestly the hardest step. I know it can be overwhelming but you're on the right track.\nJust copy these three lines from connect into the select_from_table method\nparams = config()\nconn = psycopg.connect(**params)\ncursor = conn.cursor()\n\nIt will look like this ...
[ 1 ]
[]
[]
[ "postgresql", "python" ]
stackoverflow_0074293008_postgresql_python.txt
Q: How to get the top rated products in the following case? I'm using Django==3.2 and Django-rest-framework==3.12.4 . I have two modals with following names Product and ProductRating. As you can see below: class Product(models.Model): user = models.ForeignKey(User,related_name='userprofile', on_delete=model...
How to get the top rated products in the following case?
I'm using Django==3.2 and Django-rest-framework==3.12.4 . I have two modals with following names Product and ProductRating. As you can see below: class Product(models.Model): user = models.ForeignKey(User,related_name='userprofile', on_delete=models.CASCADE) name = models.CharField(("name"), max_len...
[ "You can use Avg database function\nfrom django.db.models import Avg, Q\n\nProduct.objects.annotate(avg_rate=Avg(\"product__stars\", filter=Q(product__is_remove=False))).order_by(\"avg_rate\")\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "django_rest_framework", "python" ]
stackoverflow_0074291213_django_django_models_django_rest_framework_python.txt
Q: Selecting mysql record from python I'm trying to set commands for updating and deleting records in a mysql database from a tkinter python gui. I copied the commands straight from a youtube tutorial that uses the same libraries that I'm using yet they don't work. The terminal throws me this error: "mysql.connector....
Selecting mysql record from python
I'm trying to set commands for updating and deleting records in a mysql database from a tkinter python gui. I copied the commands straight from a youtube tutorial that uses the same libraries that I'm using yet they don't work. The terminal throws me this error: "mysql.connector.errors.ProgrammingError: 1054 (42S22): U...
[ "in this snippet\ndef borrar_registro():\n \n conn=mysql.connector.connect(host=\"localhost\",\n user=\"root\",\n password=\"Baelca1\", database=\"Lista_datos_Baelca\")\n cursor1=conn.cursor() \n cursor1.execute('''DELETE FROM ticket WHERE oid='''+indice)\n conn.commit()\n conn.close...
[ 0 ]
[]
[]
[ "mysql", "python", "python_3.x" ]
stackoverflow_0074196902_mysql_python_python_3.x.txt