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: Is there a function in tkinter to figure out the screen orientation Trying to make an app for Android as my school project I'm using tkinter and wanted to know if there's a function that can just tell you the screens orientation I tried using a loop to compare the screens height and width and then determine the or...
Is there a function in tkinter to figure out the screen orientation
Trying to make an app for Android as my school project I'm using tkinter and wanted to know if there's a function that can just tell you the screens orientation I tried using a loop to compare the screens height and width and then determine the orientation that way but the window didn't appear because of the loop. Pls ...
[ "If your end user is using a single monitor, you can probably get away with something like this\nroot = tk.Tk()\n\n\ndef get_screen_orientation():\n width, height = root.winfo_screenwidth(), root.winfo_screenheight()\n if width >= height:\n return 'Landscape'\n return 'Portrait'\n\nIt gets trickier ...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074350077_python_tkinter.txt
Q: how to remove space in string list python So i have list contains with 1 string. biner_pass = ['00001111000000000000111111111111 00001111111111111111000011111111 11111111111100000000000000000000 11111111111111110000111111111111'] all i want is to remove the space and join all the binary. i was trying using bi...
how to remove space in string list python
So i have list contains with 1 string. biner_pass = ['00001111000000000000111111111111 00001111111111111111000011111111 11111111111100000000000000000000 11111111111111110000111111111111'] all i want is to remove the space and join all the binary. i was trying using binerpass = ''.join(biner_pass.split(' ')) or bin...
[ "The string is the 0-th element of a list with 1 element. Therefore you need\nbiner_pass[0].replace(\" \", \"\")\n\n", "IIUC, You can use replace.\nbiner_pass = ['0000111100000000000011111111111100001111111111111111000011111111 1111111111110000000000000000000011111111111111110000111111111111']\nbiner_pass[0] = bi...
[ 2, 1, 1, 0 ]
[]
[]
[ "list", "python", "replace", "space", "split" ]
stackoverflow_0074350194_list_python_replace_space_split.txt
Q: Looking for a solution to speed up `pyspark.sql.GroupedData.applyInPandas` processing on a large dataset I'm working with a dataset stored in S3 bucket (parquet files) consisting of a total of ~165 million records (with ~30 columns). Now, the requirement is to first groupby a certain ID column then generate 250+ f...
Looking for a solution to speed up `pyspark.sql.GroupedData.applyInPandas` processing on a large dataset
I'm working with a dataset stored in S3 bucket (parquet files) consisting of a total of ~165 million records (with ~30 columns). Now, the requirement is to first groupby a certain ID column then generate 250+ features for each of these grouped records based on the data. Building these features is quite complex using mu...
[ "First things first: is your data partitioned enough to take advantage of all of your workers? If some part of your process causes it to coalesce to e.g. a single partition, then you're basically running single-threaded.\nBeyond that, I don't know for certain without seeing the code, but here's a subtle behaviour t...
[ 0 ]
[]
[]
[ "amazon_web_services", "bigdata", "pandas", "pyspark", "python" ]
stackoverflow_0070367933_amazon_web_services_bigdata_pandas_pyspark_python.txt
Q: How to multiply two functions in python I'm writing code for find parameter and area of different 2D objects. I decide to use local functions for this or the code become deep nested code. when I run this code it's says "TypeError: unsupported operand type(s) for *: 'function' and 'function'" #Area Of Rectangle Sec...
How to multiply two functions in python
I'm writing code for find parameter and area of different 2D objects. I decide to use local functions for this or the code become deep nested code. when I run this code it's says "TypeError: unsupported operand type(s) for *: 'function' and 'function'" #Area Of Rectangle Section def rectanglearea(a, b): length = a ...
[ "You just need your function(s) to return values and be careful with your naming so you don't use the same name for variables and functions which will only confuse you if not the compiler.\nHere is simple version to demonstrate:\ndef prompt(s):\n while True:\n try:\n w = float(input(f'{s}: '))\...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074350099_python.txt
Q: UnboundLocalError: cannot access local variable 'command' where it is not associated with a value If I don't give this program a voice command within aprox 3 seconds after "listeng..." is being prompted, I get the "UnboundLocalError" mentioned in the title. Looking for any advice on how to get the program to wait ...
UnboundLocalError: cannot access local variable 'command' where it is not associated with a value
If I don't give this program a voice command within aprox 3 seconds after "listeng..." is being prompted, I get the "UnboundLocalError" mentioned in the title. Looking for any advice on how to get the program to wait for my next voice command without shutting down. Sorry if stupid question, this is my first ever progra...
[ "The issue is that an exception happens somewhere in take_command(), and no value gets associated with command, so it can't be returned.\nNever, ever use a bare try: ... except: pass, as as you've noticed, you can then never tell what's actually going wrong.\nChange that function to something like\ndef take_command...
[ 1, 0, 0 ]
[]
[]
[ "python", "voice" ]
stackoverflow_0074350156_python_voice.txt
Q: Desnormalize a table with python I'm confused when i have to desnormalize a table with pandas For example, i have this table: And I would like to desnormalize and receive something like that: I'd appreciate your help A: Try: df["tmp"] = df.groupby("Idn")["Idn"].transform("cumcount") + 1 x = df.pivot(index="Id...
Desnormalize a table with python
I'm confused when i have to desnormalize a table with pandas For example, i have this table: And I would like to desnormalize and receive something like that: I'd appreciate your help
[ "Try:\ndf[\"tmp\"] = df.groupby(\"Idn\")[\"Idn\"].transform(\"cumcount\") + 1\n\nx = df.pivot(index=\"Idn\", columns=\"tmp\")\nx.columns = [f\"{name}{c}\" for name, c in x.columns]\nprint(x.reset_index())\n\nPrints:\n Idn test_m1 test_m2 test_m3 date1 date2 date3 test_p1 test_p2 test_p3\n...
[ 0 ]
[]
[]
[ "pandas", "pivot", "pivot_table", "python" ]
stackoverflow_0074350207_pandas_pivot_pivot_table_python.txt
Q: How can I load and access content (buttons, sliders, etc.) from my XIB's windows into my python script? - PyObj-C Right now I am having trouble figuring out in my PyObj-C project within Objective-C how I can use the class methods for the contents in NSView in windows in my XIB file. For example finding and changin...
How can I load and access content (buttons, sliders, etc.) from my XIB's windows into my python script? - PyObj-C
Right now I am having trouble figuring out in my PyObj-C project within Objective-C how I can use the class methods for the contents in NSView in windows in my XIB file. For example finding and changing via it's methods my slider (NSSlider) or date picker (NSDatePicker), it's state or colors or whatever with instance m...
[ "So it turns out it wasn't that complicated at all. All you have to do to access and change UI element's properties etc. (e.g. an NSSlider, NSTextFieldCell, anything) you need to make it in an IBOutlet.\nVery simple.\n1. First make a variable with a name you want to call your UI element as:\nclass mainWindow(prefWi...
[ 0 ]
[]
[]
[ "cocoa", "objective_c", "pyobjc", "python" ]
stackoverflow_0074339238_cocoa_objective_c_pyobjc_python.txt
Q: How to pass command line arguments to a python file from a script I have a file 'train.py' which takes command line arguments to run. Some arguments are necessary and some are optional For Example. .\train.py --counter arg1 --opt optional_arg Now, I would like to write a new file called 'script.py' which will im...
How to pass command line arguments to a python file from a script
I have a file 'train.py' which takes command line arguments to run. Some arguments are necessary and some are optional For Example. .\train.py --counter arg1 --opt optional_arg Now, I would like to write a new file called 'script.py' which will import this 'train.py' and pass the argumets in that script and execute '...
[ "One way is to use the os module and command line via Python:\nscript.py \nimport os\n\n# define some args\narg1 = '74.2'\noptional_arg = 'disable'\n\nos.system(\"python train.py --counter\" + arg1 + \"--opt\" + optional_arg)\n\n", "One approach would be to define the actions in train.py as a function:\ndef train...
[ 5, 3, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0047310576_python_python_3.x.txt
Q: Python lists with 0 slice set to string I'm struggling to make sense of the following for a python list: L = [] L[0:] = 'string' # equivalently L[:] = 'string' and here L = ['s','t','r','i', 'n', 'g'] why does python do this? I know this is the expected behaviour of running list('string') but I'm not sure h...
Python lists with 0 slice set to string
I'm struggling to make sense of the following for a python list: L = [] L[0:] = 'string' # equivalently L[:] = 'string' and here L = ['s','t','r','i', 'n', 'g'] why does python do this? I know this is the expected behaviour of running list('string') but I'm not sure how to explain this behaviour.
[ "by making the left-hand-side L[:], you force the right-hand side to be an iterable (if you try, for example L[:] = 1, it will result in a TypeError). Therefore, L[:] = some_iterable_thing translates as iterate over some_iterable_thing and assign it to elements of the L list.\nExamples:\nL[:] = 1,2,3 ==> [1,2,3]\nL...
[ 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074350301_list_python.txt
Q: Create a filter on a column in Python I currently have a file with data that looks like this. I am trying to get it to look like this. All I need is the filter added. I need to have this filter created in Python but I am not sure how. I do not need to go through Pandas and I have tried openpyxl. My caveat is tha...
Create a filter on a column in Python
I currently have a file with data that looks like this. I am trying to get it to look like this. All I need is the filter added. I need to have this filter created in Python but I am not sure how. I do not need to go through Pandas and I have tried openpyxl. My caveat is that I am not currently filtering anything. I ...
[ "For the solution, I followed openpyxl's documentation and used this to create a filter by Batch Number.\nws.auto_filter.ref = 'A:A'\nws.auto_filter.add_filter_column(0,[\"Batch IDS\"])\n\nThis worked for me! Hope it helps someone else.\nOpenpyxl does not filter for you just creates the filter\n" ]
[ 1 ]
[]
[]
[ "openpyxl", "pandas", "python" ]
stackoverflow_0074350293_openpyxl_pandas_python.txt
Q: How to call a verification function from views to templates? I have a function to check if the user is a staff: class VerificateUser(): def allowed_user(request): if request.user.is_staff: return True In my template, I’m going to show this section only for staff users, but this is not work...
How to call a verification function from views to templates?
I have a function to check if the user is a staff: class VerificateUser(): def allowed_user(request): if request.user.is_staff: return True In my template, I’m going to show this section only for staff users, but this is not working. {% url if not allowed_user %} <h1> Welcome to the show </...
[ "You can do this sort of thing in many ways, but simply you can do by the following way-\n{% if request.user.is_authenticated %}\n <p>Welcome,{{request.user.first_name}} </p> \n{% endif %}\n\nrequest object is by default available in all of your Django templates context.\n", "Since you are using a cla...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074350271_django_python.txt
Q: Cannot install "mediapipe" library I am trying pip3 install mediapipe but I am getting an error: ERROR: Could not find a version that satisfies the requirement mediapipe ERROR: No matching distribution found for mediapipe My Python version is 3.7.9 and pip version is 20.3.1. A: I solved it by typing py -m pip ...
Cannot install "mediapipe" library
I am trying pip3 install mediapipe but I am getting an error: ERROR: Could not find a version that satisfies the requirement mediapipe ERROR: No matching distribution found for mediapipe My Python version is 3.7.9 and pip version is 20.3.1.
[ "I solved it by typing py -m pip install mediapipe instead.\n", "I had the same issue trying to install MediaPipe via pip using macOs 10.13 with Python 3.7.10. I ended up looking at the \"Download Files\" in Mediapipe's PyPi (https://pypi.org/project/mediapipe/#files) and found out that all wheel files for macOs ...
[ 5, 1, 0, 0, 0, 0 ]
[]
[]
[ "mediapipe", "pip", "python" ]
stackoverflow_0065172162_mediapipe_pip_python.txt
Q: how to know at what date time my ebs volume got unattached I have to delete my unattached ebs volumes only if that ebs is unattached for last weeks. for that I need to find exact date & time of ebs got unattached from ec2. A: There are two ways to achieve this- Manual- Use AWS cloudtrail to find the event and ge...
how to know at what date time my ebs volume got unattached
I have to delete my unattached ebs volumes only if that ebs is unattached for last weeks. for that I need to find exact date & time of ebs got unattached from ec2.
[ "There are two ways to achieve this-\nManual- Use AWS cloudtrail to find the event and get the timestamp from event. Delete the resource manually.\nAutomatically- Create a script, probably using python boto3 to find unattached ebs for 1 week and delete. Either schedule it using Lambda or add it as a cron in any ser...
[ 0 ]
[]
[]
[ "amazon_ec2", "amazon_web_services", "boto3", "python" ]
stackoverflow_0074344135_amazon_ec2_amazon_web_services_boto3_python.txt
Q: How to change colors of stacked barplot with Plotly? I have started to use Plotly recently. I wanted to choose the colors, but I have the same color for my column and my legend. What I have, the same color per age group: What I would like to achieve: My code x = ['18-25', '25-35', '35-45','45-55','55-65'] plot ...
How to change colors of stacked barplot with Plotly?
I have started to use Plotly recently. I wanted to choose the colors, but I have the same color for my column and my legend. What I have, the same color per age group: What I would like to achieve: My code x = ['18-25', '25-35', '35-45','45-55','55-65'] plot = px.Figure(data=[ go.Bar( name=...
[ "You can change the color by marker_color and add it to each go.Bar:\nx = ['18-25', '25-35', '35-45','45-55','55-65']\n\nplot = go.Figure(data=[\n go.Bar(\n name='Bulle de Babel',\n x=x,\n y=[97, 204, 192, 145, 96],\n marker_color='#FDCCFF'\n ...
[ 1 ]
[]
[]
[ "bar_chart", "cptbarplot", "plotly", "python" ]
stackoverflow_0074348692_bar_chart_cptbarplot_plotly_python.txt
Q: Export chart as image with python xlwings I have been working on creating Excel reports automatically using Python and xlwings. Within these reports there are multiple charts and graphs which I now want to use in a pptx presentation keeping the same formatting and design. For the generation of the pptx I am curren...
Export chart as image with python xlwings
I have been working on creating Excel reports automatically using Python and xlwings. Within these reports there are multiple charts and graphs which I now want to use in a pptx presentation keeping the same formatting and design. For the generation of the pptx I am currently using python-pptx. An ideal solution would ...
[ "You can implement a solution based on xlwings by falling back to the underlying pywin32 object and by adopting the solution from VBA, see e.g.: https://stackoverflow.com/a/11939249/918626\nTo learn about how to work on the underlying pywin32 object, see: http://docs.xlwings.org/en/stable/missing_features.html\n", ...
[ 1, 0 ]
[]
[]
[ "excel", "powerpoint", "python", "python_pptx", "xlwings" ]
stackoverflow_0041346906_excel_powerpoint_python_python_pptx_xlwings.txt
Q: Use sympy.solve with np.deg2rad in equation I want to use sympy.solve to solve an equation to a variable. Inside of the equation there is 'np.deg2rad', 'np.tan' and 'np.pi'. For example I want the equation 'a-np.tan(np.deg2rad(b))*np.pi' solved for a. This is my code: import numpy as np import math import sympy as...
Use sympy.solve with np.deg2rad in equation
I want to use sympy.solve to solve an equation to a variable. Inside of the equation there is 'np.deg2rad', 'np.tan' and 'np.pi'. For example I want the equation 'a-np.tan(np.deg2rad(b))*np.pi' solved for a. This is my code: import numpy as np import math import sympy as sy a,b = sy.symbols('a b') sy.solve(a-np.tan(np...
[ "If you are trying to solve an equation symbolically then you should use the symbolic routines from SymPy. NumPy's functions like deg2rad etc cannot work with symbols:\nIn [1]: import sympy as sym\n\nIn [2]: a, b = sym.symbols('a, b')\n\nIn [4]: sym.solve(a - sym.tan(b*sym.pi/180)*sym.pi, a)\nOut[4]: \n⎡ ⎛π⋅b⎞⎤...
[ 2 ]
[]
[]
[ "numpy", "python", "sympy" ]
stackoverflow_0074350499_numpy_python_sympy.txt
Q: When trying to build TensorFlow from source: Inconsistent CUDA toolkit path: /usr vs /usr/lib On a fresh LambdaLabs GPU instance I install Bazel with Bazelisk: wget https://github.com/bazelbuild/bazelisk/releases/download/v1.8.1/bazelisk-linux-amd64 chmod +x bazelisk-linux-amd64 sudo mv bazelisk-linux-amd64 /usr/l...
When trying to build TensorFlow from source: Inconsistent CUDA toolkit path: /usr vs /usr/lib
On a fresh LambdaLabs GPU instance I install Bazel with Bazelisk: wget https://github.com/bazelbuild/bazelisk/releases/download/v1.8.1/bazelisk-linux-amd64 chmod +x bazelisk-linux-amd64 sudo mv bazelisk-linux-amd64 /usr/local/bin/bazel Then I download the TF source: git clone https://github.com/tensorflow/tensorflow.g...
[ "can you run these commands!? If see versions then build with Bazel see any error !? My environment is not different I running on Windows 10 no simulation but as warning messages they will not allowed in next versions for GPU support ( actually they warning for many time but I still using Windows 10 as many users )...
[ 0 ]
[]
[]
[ "linux", "python", "tensorflow" ]
stackoverflow_0074349598_linux_python_tensorflow.txt
Q: Check a file if the same thing is written 3 times I'm very new to accessing files. I want to see if the same thing is written 3 times in a text file and if it is replace it with something that is written only one time so it is balanced. Any idea how I can do that? Edit: if it is possible only if they are in 2 sepa...
Check a file if the same thing is written 3 times
I'm very new to accessing files. I want to see if the same thing is written 3 times in a text file and if it is replace it with something that is written only one time so it is balanced. Any idea how I can do that? Edit: if it is possible only if they are in 2 separate lines in the file Edit 2 : file example: John-Alex...
[ "Here is the code that will check if a line in a file is repeated 3 or more times:\nnames = {}\nwith open(\"your_file.txt\", \"r\") as file:\n text = file.read()\n lines = file.readlines()\n\nfor line in lines:\n for name in line.split(\"-\"):\n if name in names.keys():\n names[name] += 1...
[ -1 ]
[]
[]
[ "python" ]
stackoverflow_0074350579_python.txt
Q: I want to put a input variable before print (menu) but I want it to be printed after the menu Can anyone help I am a beginner? I want the variable choice to be displayed after the menu is but I need the variable to be on top so the name inserted can be shown beside add player name. choice = input("Input your menu ...
I want to put a input variable before print (menu) but I want it to be printed after the menu
Can anyone help I am a beginner? I want the variable choice to be displayed after the menu is but I need the variable to be on top so the name inserted can be shown beside add player name. choice = input("Input your menu choice: ") choice = False if choice == "1": name = input("What is your name? ") print(" ...
[ "How about defining a string first like this?\nimport random\n\nname = 'Anonomous'\n\nplaying = True\n\nwhile playing == True:\n print(\" Menu \")\n print(\"------------------------------------------\")\n print(f\"[1] Add player name: {name} \")\n print(\"[2] Play gue...
[ 1, 0 ]
[]
[]
[ "boolean", "input", "python", "variable_assignment", "variables" ]
stackoverflow_0074350412_boolean_input_python_variable_assignment_variables.txt
Q: How to print the printing full cpd from pgmpy? I'm trying to get the example in Insurance data representation with Bayesian networks to work. See the section Maximum Likelihood Estimation. The data I got from the bnlearn package in R and then uploaded it my google drive. The data The picture below shows ... I beli...
How to print the printing full cpd from pgmpy?
I'm trying to get the example in Insurance data representation with Bayesian networks to work. See the section Maximum Likelihood Estimation. The data I got from the bnlearn package in R and then uploaded it my google drive. The data The picture below shows ... I believe this is showing missing columns. How do I fix th...
[ "\nOpen file \"pgmpy/factors/discrete/CPD.py\"\n\n\n\nIn class \"TabularCPD(DiscreteFactor)\",\nfine the line \"cdf_str = self._truncate_strtable(cdf_str)\"\n(This line is in \"def _make_table_str (~)\")\n\n\n\n\ncdf_str = self._truncate_strtable(cdf_str)\nmake this line deactivate by add \"#\"\n--> # cdf_str = sel...
[ 4, 0 ]
[]
[]
[ "google_colaboratory", "pgmpy", "python" ]
stackoverflow_0070625490_google_colaboratory_pgmpy_python.txt
Q: Error -> name 'result' is not defined - time series project in python I am writing a code to get the p-value in Python. def adfuller_test(GDP): result=adfuller(GDP) labels = ['ADF Test Statistic','p-value','#Lags Used','Number of Observations'] for value,label in zip(result,labels): print(label...
Error -> name 'result' is not defined - time series project in python
I am writing a code to get the p-value in Python. def adfuller_test(GDP): result=adfuller(GDP) labels = ['ADF Test Statistic','p-value','#Lags Used','Number of Observations'] for value,label in zip(result,labels): print(label+' : '+str(value) ) if result[1] <= 0.05: print("strong eviden...
[ "Unless you pasted the code here incorrectly, you clearly have an indentation problem. Needs to be written like this:\ndef adfuller_test(GDP):\n result=adfuller(GDP)\n labels = ['ADF Test Statistic','p-value','#Lags Used','Number of Observations']\n for value,label in zip(result,labels):\n print(lab...
[ 0, 0 ]
[]
[]
[ "jupyter_notebook", "p_value", "python", "time_series" ]
stackoverflow_0074349459_jupyter_notebook_p_value_python_time_series.txt
Q: How to build a sorting algorithm with 2 keys in Python? I'm aware that Python has a very nice function sorted() for this but I'd like to implement my own function to understand the logic. I have a list of strings and I'd like to sort them first by length, then alphabetically. For example, Input: ['daring','adequat...
How to build a sorting algorithm with 2 keys in Python?
I'm aware that Python has a very nice function sorted() for this but I'd like to implement my own function to understand the logic. I have a list of strings and I'd like to sort them first by length, then alphabetically. For example, Input: ['daring','adequate','bold','bait','cold','beautiful'] Output: ['bait','bold',...
[ "You can do this by adding a 'key function' that maps an item into a tuple (item_length, item) prior with pivot in your algorithm. For example:\ndef quick_sort(sequence, key_fn):\n length = len(sequence)\n if length <=1:\n return sequence\n else:\n pivot = sequence.pop()\n\n items_greater ...
[ 0, 0, 0 ]
[]
[]
[ "python", "quicksort", "sorting" ]
stackoverflow_0074350616_python_quicksort_sorting.txt
Q: Report pyparsing syntaxError while catkin_make I met a strange problem when using catkin_make with python function enabled in cmakelists.txt, which is shown below: cmake_minimum_required(VERSION 3.0.2) project(transmit) set(Python3_INCLUDE_DIRS "/usr/include/python3.6m") set(Python3_LIBRARIES "/usr/lib/python3.6/c...
Report pyparsing syntaxError while catkin_make
I met a strange problem when using catkin_make with python function enabled in cmakelists.txt, which is shown below: cmake_minimum_required(VERSION 3.0.2) project(transmit) set(Python3_INCLUDE_DIRS "/usr/include/python3.6m") set(Python3_LIBRARIES "/usr/lib/python3.6/config-3.6m-x86_64-linux-gnu/libpython3.6.so") set(PY...
[ "You’re using ROS Melodic which officially supports Python2.7 by default. The package you’re trying to use is written for Python3, but it’s trying to be imported as a Python2.7 script. To fix this you’ll need to either find the Python2.7 version of the package, or upgrade everything to ROS Noetic, which targets Pyt...
[ 0, 0 ]
[]
[]
[ "cmake", "python", "ros" ]
stackoverflow_0074052879_cmake_python_ros.txt
Q: Download PDF in Firefox I'm downloading PDF files with selenium and firefox. I'm facing problems because right after downloading the pdf the file opens in the browser. How can I download the pdf and not open it in the browser? def __init__(self): self.options = webdriver.FirefoxOptions() self.options.set_p...
Download PDF in Firefox
I'm downloading PDF files with selenium and firefox. I'm facing problems because right after downloading the pdf the file opens in the browser. How can I download the pdf and not open it in the browser? def __init__(self): self.options = webdriver.FirefoxOptions() self.options.set_preference("browser.download.f...
[ "you have to include the options in driver instantiation statement:\nself.firefox = webdriver.Firefox(service=Service(GeckoDriverManager().install()), options = self.options)\n\n" ]
[ 0 ]
[]
[]
[ "geckodriver", "python", "selenium", "selenium_firefoxdriver" ]
stackoverflow_0074349062_geckodriver_python_selenium_selenium_firefoxdriver.txt
Q: Recursively search a dictionary of lists to find all connections between keys of that dictionary I have a dictionary of lists, whose values are connections to other keys in that same dictionary. I need a summarized list of the connections between all of the keys regardless of how many levels the keys are away from...
Recursively search a dictionary of lists to find all connections between keys of that dictionary
I have a dictionary of lists, whose values are connections to other keys in that same dictionary. I need a summarized list of the connections between all of the keys regardless of how many levels the keys are away from each other. I can make this work with a bunch of for loops that keep searching back through the same ...
[ "Here's a solution using a depth-first search.\ndef dfs(v,component,unseen,adj):\n for w in adj[v]:\n if w in unseen:\n component.append(w)\n unseen.remove(w)\n dfs(w,component,unseen,adj)\n\nunseen = set(sampleDict)\ncomponents = []\nwhile unseen:\n v = unseen.pop()\n ...
[ 1, 0 ]
[]
[]
[ "dictionary", "list", "python", "recursion" ]
stackoverflow_0074350530_dictionary_list_python_recursion.txt
Q: Pycharm Not Displaying Line on Plot I am trying to plot a graph from a for-loop from z=0 to z=3.8 in 0.001 increments. I then have the program solve for X_e and I would like to plot z on the y-axis and X_e on the x-axis. However, when I run the code, the program provides all the values for z and X_e and shows a pl...
Pycharm Not Displaying Line on Plot
I am trying to plot a graph from a for-loop from z=0 to z=3.8 in 0.001 increments. I then have the program solve for X_e and I would like to plot z on the y-axis and X_e on the x-axis. However, when I run the code, the program provides all the values for z and X_e and shows a plot but no line is created. Below is my co...
[ "You're passing single points to plt.plot. Use np.cos (which is vectorized) and skip the loop:\nz = np.arange(0, 3.8, 0.001)\nX_e = -q_0 * heated_parameter / (G * circumference * area * hfg) * H/3.14 * np.cos(3.14 * z/H) - cp * (T_sat - T_f_in)/hfg\n\nplt.plot(X_e, z)\n\nOutput:\n\nYou might also consider using np....
[ 0 ]
[]
[]
[ "matplotlib", "numpy", "python" ]
stackoverflow_0074350757_matplotlib_numpy_python.txt
Q: Output alternatives in Python Is there any alternatives to the print statement for output in Python. Also, how can I format my output text to be color-coded? I'm a beginner programmer, pretty new to it. Thanks A: sys.stdout.write() Is one alternative. You can also write to sys.stderr. Personally, I use sys.stdo...
Output alternatives in Python
Is there any alternatives to the print statement for output in Python. Also, how can I format my output text to be color-coded? I'm a beginner programmer, pretty new to it. Thanks
[ "sys.stdout.write()\n\nIs one alternative. You can also write to sys.stderr. Personally, I use sys.stdout when I need to pass a generic \"stream\" to some function that will write to it. And open file is a stream, and sys.stdout is a stream. This way my function can be parametrized to write either to output or to f...
[ 19, 2 ]
[ "You can use PrettyPrint for print data \n", "IceCream — Never use print() to debug again\nYou should try the package called IceCream\nTo install it, please use the following:\npip install icecream\n\nFor details on how to use it, please click here\nAn example:\nfrom icecream import ic\na = 3\ndef duplicate(i):\n...
[ -1, -1 ]
[ "python" ]
stackoverflow_0002570269_python.txt
Q: Count values of each row in pandas dataframe only for consecutive numbers I got a pandas dataframe that looks like this: I want to count how many rows are for each id and print the result. The problem is I want to count that ONLY for consecutive numbers in "frame num". For example: if frame num is: [1,2,3,45,47,1...
Count values of each row in pandas dataframe only for consecutive numbers
I got a pandas dataframe that looks like this: I want to count how many rows are for each id and print the result. The problem is I want to count that ONLY for consecutive numbers in "frame num". For example: if frame num is: [1,2,3,45,47,122,123,124,125] and id is [1,1,1,1,1,1,1,1,1] it should print: 3 1 1 4 (and do ...
[ "You can use pandas.DataFrame.shift() for finding consecutive numbers then use itertools.groupby for creating a list of counting consecutive.\nimport pandas as pd\nfrom itertools import chain\nfrom itertools import groupby\n\n# Example input dataframe\ndf = pd.DataFrame({\n 'num' : [1,2,3,45,47,122,123,124,125,1...
[ 1 ]
[]
[]
[ "logic", "pandas", "python" ]
stackoverflow_0074350408_logic_pandas_python.txt
Q: How to make a directory and put all the files generated in to that directory? I have a script which generates multiple files after running the script. So i need all this files that is generated to be stored in to the directory created. and also if i run the script i need the the script to check if that directory a...
How to make a directory and put all the files generated in to that directory?
I have a script which generates multiple files after running the script. So i need all this files that is generated to be stored in to the directory created. and also if i run the script i need the the script to check if that directory already exist or not. if exist remove the previous contents in the directory and th...
[ "a) if the new directory doesn't exist, you need to change to it prior to create the files. b) if the new directory was created in a previous run, your files are never created in the current run (watch out for indentation!). Modifying a bit your script, this will always create the files in the new directory, whethe...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074350696_python_python_3.x.txt
Q: Python mixins : how to deal with *args, **kwargs when calling super()? In the following example I show some mixins that may or may not use *args or **kwargs: class AMixin(): def __init__(self, **kwargs): print("AMixin") self.a = 'a' + str(kwargs.get('a', '')) class BMixin(): def __...
Python mixins : how to deal with *args, **kwargs when calling super()?
In the following example I show some mixins that may or may not use *args or **kwargs: class AMixin(): def __init__(self, **kwargs): print("AMixin") self.a = 'a' + str(kwargs.get('a', '')) class BMixin(): def __init__(self, **kwargs): print("BMixin") self.b = 'b'...
[ "You can make your mixins inherit from a base-class that stops the super call to object.\nclass BaseMixin:\n def __init__(self, *args, **kwargs):\n pass\n\n\nclass AMixin(BaseMixin):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n print(\"AMixin\")\n se...
[ 1, 1 ]
[]
[]
[ "mixins", "oop", "python", "traits" ]
stackoverflow_0074350679_mixins_oop_python_traits.txt
Q: Keep Secret Keys Out One of the causes of the local_settings.py anti-pattern is that putting SECRET_KEY, AWS keys, etc.. values into settings files has problem: Secrets often should be just that: secret! Keeping them in version control means that everyone with repository access has access to them. My question is...
Keep Secret Keys Out
One of the causes of the local_settings.py anti-pattern is that putting SECRET_KEY, AWS keys, etc.. values into settings files has problem: Secrets often should be just that: secret! Keeping them in version control means that everyone with repository access has access to them. My question is how to keep all keys as s...
[ "The original question was about how to keep secrets in environment variables. This is discussed extensively in the book Two Scoops of Django. Below is a summary of what they said, followed by a caveat about using this technique.\nStarting on page 48 (Section 5.3) of the edition for 1.11:\n\nEvery operating system ...
[ 7, 6, 6, 5, 2, 2, 0 ]
[ "You may need to use os.environ.get(\"SOME_SECRET_KEY\")\n" ]
[ -1 ]
[ "django", "python", "settings" ]
stackoverflow_0014786072_django_python_settings.txt
Q: Locking a file in Python I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as they are often only Unix based or Windows based. A: Alright, so I ended up going with the code I wrote here, on my...
Locking a file in Python
I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as they are often only Unix based or Windows based.
[ "Alright, so I ended up going with the code I wrote here, on my website link is dead, view on archive.org (also available on GitHub). I can use it in the following fashion:\nfrom filelock import FileLock\n\nwith FileLock(\"myfile.txt\"):\n # work with the file as it is now locked\n print(\"Lock acquired.\")\n...
[ 164, 49, 43, 25, 18, 15, 9, 9, 4, 2, 2, 1, 0, 0, 0 ]
[]
[]
[ "file_locking", "python" ]
stackoverflow_0000489861_file_locking_python.txt
Q: Why does dropna not drop na? From my understanding, dropna for pandas in python drops rows with an empty entry. import pandas as pd the_data = pd.read_csv("EnzymeTrainingData.csv") the_data.dropna(inplace = True) seqs = the_data["protein_sequence"] amino_numeros = seqs.apply(len) hands = amino_numeros.apply(lambda...
Why does dropna not drop na?
From my understanding, dropna for pandas in python drops rows with an empty entry. import pandas as pd the_data = pd.read_csv("EnzymeTrainingData.csv") the_data.dropna(inplace = True) seqs = the_data["protein_sequence"] amino_numeros = seqs.apply(len) hands = amino_numeros.apply(lambda n : float(n*(n + 1))/2) the_pH = ...
[ "When you drop rows like that, pandas does not renumber the index. If you drop the row at index 69, then there will be nothing at index 69. Your range is going by row number, but the the_pH[i] notation does a lookup by index.\nYou can either redo the index, or you can use iterrows to iterate the rows one by one, ...
[ 3 ]
[]
[]
[ "data_science", "dataframe", "pandas", "python" ]
stackoverflow_0074350952_data_science_dataframe_pandas_python.txt
Q: Updating a dictionary of dictionaries Current issue: Taking input to select a dictionary key, and add in a quantity key:value pair to that nested dictionary. This is my attempt menu = { 1: {"item": "Green Beret Omelette", "price": "$12.99"}, 2: {"item": "Get to the Chopped Salad", "price": "$14.99"}, 3...
Updating a dictionary of dictionaries
Current issue: Taking input to select a dictionary key, and add in a quantity key:value pair to that nested dictionary. This is my attempt menu = { 1: {"item": "Green Beret Omelette", "price": "$12.99"}, 2: {"item": "Get to the Chopped Salad", "price": "$14.99"}, 3: {"item": "Pump You Up Protein Shake", "pr...
[ "Try this:\n# Use 'dict.update()` with inputting a dict with key and value as you like\nmenu[selection].update({\"quantity\": count})\n\nRun with input:\nPlease select your item:\n1\nEnter quantity: \n2\n\nOutput:\n# print(menu)\n{1: {'item': 'Green Beret Omelette', 'quantity': 2, 'price': '$12.99'},\n 2: {'item': ...
[ 1, 1 ]
[]
[]
[ "dictionary", "python", "python_3.x" ]
stackoverflow_0074350813_dictionary_python_python_3.x.txt
Q: regex in python to extract number I want regex for the following test cases so that i can get the proper output:- Test Cases: Input: address = "73/75 agedabout 56 years, residing at j,j 59 moil" Output: 60 address = "12th street t.vial age 46yrs, residing at D.NO 59 Eswaran Koil St" Output: 46 address = "Room...
regex in python to extract number
I want regex for the following test cases so that i can get the proper output:- Test Cases: Input: address = "73/75 agedabout 56 years, residing at j,j 59 moil" Output: 60 address = "12th street t.vial age 46yrs, residing at D.NO 59 Eswaran Koil St" Output: 46 address = "Room no 43 R.Kesavan aged about 37 years, r...
[ "Try (txt is your text from the question) (regex demo.):\nimport re\n\npat = re.compile(r\"(\\d+)\\s*ye?a?rs?|aged?\\D*(\\d+)\")\n\nfor a, b in pat.findall(txt):\n age = b if a == \"\" else a\n print(age)\n\nPrints:\n56\n46\n37\n56\n61\n63\n9\n\n" ]
[ 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074350723_python_regex.txt
Q: How to submit HTML form value using FastAPI and Jinja2 Templates? I am facing the following issue while trying to pass a value from an HTML form <input> element to the form's action attribute and send it to the FastAPI server. This is how the Jinja2 (HTML) template is loaded: # Test TEMPLATES @app.get("/test",res...
How to submit HTML form value using FastAPI and Jinja2 Templates?
I am facing the following issue while trying to pass a value from an HTML form <input> element to the form's action attribute and send it to the FastAPI server. This is how the Jinja2 (HTML) template is loaded: # Test TEMPLATES @app.get("/test",response_class=HTMLResponse) async def read_item(request: Request): ret...
[ "Option 1\nYou can have the category name defined as Form parameter in the backend, and submit a POST request from the frontend using an HTML <form>, as described in Method 1 of this answer.\napp.py\nfrom fastapi import FastAPI, Form, Request\nfrom fastapi.responses import HTMLResponse\nfrom fastapi.templating impo...
[ 0, 0 ]
[]
[]
[ "fastapi", "html", "jinja2", "python" ]
stackoverflow_0074318682_fastapi_html_jinja2_python.txt
Q: Read every line in a file then save every line as an accessible string So I'm reading every line with this code: with open ('file.txt') as f: for line in f: but I want to save every line as a global accessible string. Any way I can do that? A: Contents of example file foo.txt : Hello there Program : def c...
Read every line in a file then save every line as an accessible string
So I'm reading every line with this code: with open ('file.txt') as f: for line in f: but I want to save every line as a global accessible string. Any way I can do that?
[ "Contents of example file foo.txt :\nHello there\n\n\nProgram :\ndef can_we_read_it():\n print(\"Here is the contents:\")\n print(foo)\n\n\ndef get_text(*args, **kwargs) -> str:\n with open(*args, **kwargs) as file:\n return file.read()\n\n\nfoo = get_text(\"foo.txt\", \"r\") # foo is available in t...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074348584_python.txt
Q: google.protobuf validation - python I am trying to implement a validation for protobuf files in Python. I don't want to use an external package. I tried: desc_set = descriptor_pb2.FileDescriptorSet() descriptor_bytes = str.encode(descriptor) desc_set.ParseFromString(descriptor_bytes) pool = descriptor_pool.Descri...
google.protobuf validation - python
I am trying to implement a validation for protobuf files in Python. I don't want to use an external package. I tried: desc_set = descriptor_pb2.FileDescriptorSet() descriptor_bytes = str.encode(descriptor) desc_set.ParseFromString(descriptor_bytes) pool = descriptor_pool.DescriptorPool() desc = descriptor_pb2.FileDesc...
[ "Your code was non-reproducible and didn't work for me as-was:\nPython 3.10.6\n\ngrpcio==1.50.0\ngrpcio-tools==1.50.0\nprotobuf==4.21.9\n\nHowever:\nRenaming (!) the field to name (per the style guide):\nsyntax = \"proto2\";\n\npackage employees;\n\nmessage Employees {\n required string name = 1;\n required i...
[ 0 ]
[]
[]
[ "protobuf_python", "protocol_buffers", "python", "validation" ]
stackoverflow_0074329772_protobuf_python_protocol_buffers_python_validation.txt
Q: VS Code Live Share - errno 2 No such file or directory I'm having an issue with Visual Studio Code live share - errno 2 No such file or directory to more exact. The error happens when my friend, who is connected to my collaboration session, tries to run the code on his side. The same happens when I connect to his ...
VS Code Live Share - errno 2 No such file or directory
I'm having an issue with Visual Studio Code live share - errno 2 No such file or directory to more exact. The error happens when my friend, who is connected to my collaboration session, tries to run the code on his side. The same happens when I connect to his session and try to run his code. From what I understand from...
[ "You could try having a shared terminal. Then at least you can execute things remotely on the host machine\n" ]
[ 0 ]
[]
[]
[ "python", "visual_studio_code", "visual_studio_liveshare", "vscode_liveshare" ]
stackoverflow_0061835563_python_visual_studio_code_visual_studio_liveshare_vscode_liveshare.txt
Q: "TypeError: only length-1 arrays can be converted to Python scalars" when working with i-based logarithms I'm trying to make a matplotlib plot of the function logi(x) (an i-based log). Here is my code: from pylab import * import cmath x = linspace(-8,8,500) z = cmath.log(x,1j) plot(x,real(z),label='real') plot(x...
"TypeError: only length-1 arrays can be converted to Python scalars" when working with i-based logarithms
I'm trying to make a matplotlib plot of the function logi(x) (an i-based log). Here is my code: from pylab import * import cmath x = linspace(-8,8,500) z = cmath.log(x,1j) plot(x,real(z),label='real') plot(x,imag(z),label='imag') legend() show() The problem is that it throws TypeError: only length-1 arrays can be c...
[ "If the array has complex dtype, then np.log will return complex results:\nIn [58]: x = np.linspace(-8,8,11).astype(complex) \nIn [59]: x\nOut[59]: \narray([-8. +0.j, -6.4+0.j, -4.8+0.j, -3.2+0.j, -1.6+0.j, 0. +0.j,\n 1.6+0.j, 3.2+0.j, 4.8+0.j, 6.4+0.j, 8. +0.j])\n\nIn [60]: np.log(x)\nC:\\Users\\pau...
[ 0 ]
[]
[]
[ "cmath", "matplotlib", "numpy", "python" ]
stackoverflow_0074350376_cmath_matplotlib_numpy_python.txt
Q: Python how to build dictionary from nested protobuf definitions This is my first time working with grpc/protobuf tech. so far so good I have coded grpc methods for simple (flat?) protobuf definitions. However I have run into nested protobuf declarations and have no idea how to formulate the dictionary payload. Unf...
Python how to build dictionary from nested protobuf definitions
This is my first time working with grpc/protobuf tech. so far so good I have coded grpc methods for simple (flat?) protobuf definitions. However I have run into nested protobuf declarations and have no idea how to formulate the dictionary payload. Unfortunately the team the created these files is offering little to no ...
[ "I munged your proto file to get it to work for me (as I don't have all your dependencies):\nx.proto:\nsyntax = \"proto3\";\n\n// (ADDED:dazwilkin) to compile\nmessage Context {\n string project_id = 1;\n}\n\nmessage UpdateClusterRequest {\n Context context = 1;\n // myapp.infrastructure.common.MyAppEnviro...
[ 0 ]
[]
[]
[ "dictionary", "grpc_python", "protocol_buffers", "python" ]
stackoverflow_0074323787_dictionary_grpc_python_protocol_buffers_python.txt
Q: How do I run Python code that returns a CSV to replace the data in a Google Sheet? I have a Python script that returns a CSV. I want to view this data in a Google Sheet. Right now, I have to run my Python code, overwrite my old CSV file with my new data, then go into Google Sheets and import the new CSV and overw...
How do I run Python code that returns a CSV to replace the data in a Google Sheet?
I have a Python script that returns a CSV. I want to view this data in a Google Sheet. Right now, I have to run my Python code, overwrite my old CSV file with my new data, then go into Google Sheets and import the new CSV and overwrite the Google Sheets data. I want this to happen automatically. How do I do that? I t...
[ "I think looking at the Google Sheets Python API might help: https://developers.google.com/sheets/api/quickstart/python\nYou'll have to do some setup, but this way you can interact with Google Sheets through Python.\n" ]
[ 0 ]
[]
[]
[ "google_sheets", "python" ]
stackoverflow_0074351097_google_sheets_python.txt
Q: Can I combine two querysets when one has a rank annotation and the other doesn't? I am trying to write a search feature and can't figure out how to combine the results of a rank-annotated search and a non-rank-annotated search. Let's say I have the following model: class Song(models.Model): filename=models.Cha...
Can I combine two querysets when one has a rank annotation and the other doesn't?
I am trying to write a search feature and can't figure out how to combine the results of a rank-annotated search and a non-rank-annotated search. Let's say I have the following model: class Song(models.Model): filename=models.CharField(max_length=120, db_index=True) title=models.CharField(max_length=120, db_ind...
[ "You can work with:\nfrom django.db.models import Q\n\nquery_results = Song.objects.annotate(\n rank=SearchRank(F('title_vector'), query)\n).filter(Q(title_vector=query) | Q(filename__icontains=query))\nor the same, but perhaps more elegant:\nfrom django.db.models import Q\n\nquery_results = Song.objects.annotat...
[ 0 ]
[]
[]
[ "django", "django_searchvector", "python" ]
stackoverflow_0074351181_django_django_searchvector_python.txt
Q: Letter Count Dictionary My homework problem is to write a Python function called LetterCount() which takes a string as an argument and returns a dictionary of letter counts. However, my code includes white space and commas as a part of the dictionary which i don't want. Can you please help me out. How do i remove ...
Letter Count Dictionary
My homework problem is to write a Python function called LetterCount() which takes a string as an argument and returns a dictionary of letter counts. However, my code includes white space and commas as a part of the dictionary which i don't want. Can you please help me out. How do i remove the white space from my list?...
[ "For the letter count, the best way is to use the dictionary.\ns = \"string is an immutable object\"\ndef letter_count(s):\n d = {}\n for i in s:\n d[i] = d.get(i,0)+1\n return d\n\nOutput:\n{'a': 2, ' ': 4, 'c': 1, 'b': 2, 'e': 2, 'g': 1, 'i': 3, 'j': 1, 'm': 2, 'l': 1, 'o': 1, 'n': 2, 's': 2, 'r':...
[ 6, 3, 3, 1, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0005664494_dictionary_python.txt
Q: Why I have this value error when training U-net? I am a beginner in deep_learning and my graduation thesis is about semantic segmentation. However I received a ValueError when using library "segmentation-models" Docs of the library Part of my codes are as follows and my error occur at validation_data=(x_val, y_val...
Why I have this value error when training U-net?
I am a beginner in deep_learning and my graduation thesis is about semantic segmentation. However I received a ValueError when using library "segmentation-models" Docs of the library Part of my codes are as follows and my error occur at validation_data=(x_val, y_val)) import tensorflow as tf import segmentation_models ...
[ "It seems that you have 3 channels, but the shape of the output has only 1 channel.\nThe UNET initialization has a parameter called classes, which defines the output shape. You should probably set this to classes=3 when definining the model.\nSee documentation in\nhttps://segmentation-models.readthedocs.io/en/lates...
[ 1 ]
[]
[]
[ "deep_learning", "numpy", "python", "semantic_segmentation", "unet_neural_network" ]
stackoverflow_0074351194_deep_learning_numpy_python_semantic_segmentation_unet_neural_network.txt
Q: Collisions in PyGame I'm trying to program a simple simulator of collisions between blocks with PyGame. I've tried to watch several videos online on how to detect collisions in a better way and I've managed to write this function: def block_collisions(self, block1, block2, collision_tolerance=10): """ check wh...
Collisions in PyGame
I'm trying to program a simple simulator of collisions between blocks with PyGame. I've tried to watch several videos online on how to detect collisions in a better way and I've managed to write this function: def block_collisions(self, block1, block2, collision_tolerance=10): """ check whether the two passed block...
[ "Your problem is similar to the one described in the question Sometimes the ball doesn't bounce off the paddle in pong game.\nWhen the blocks collide then they overlap and the direction of movement of the blocks is reversed. If the energy and thus the movement is not sufficient to separate the blocks, i.e. to move ...
[ 0 ]
[]
[]
[ "collision", "collision_detection", "pygame", "python" ]
stackoverflow_0067771995_collision_collision_detection_pygame_python.txt
Q: Loop through table and print in specific column order I have a table of videos with title, release and synopsis among other fields. I'd like to loop over each row and print columns in a specific order: con = sqlite3.connect("videos.db") cur = con.cursor() videos = "SELECT * FROM videos" for videos in cur.execute...
Loop through table and print in specific column order
I have a table of videos with title, release and synopsis among other fields. I'd like to loop over each row and print columns in a specific order: con = sqlite3.connect("videos.db") cur = con.cursor() videos = "SELECT * FROM videos" for videos in cur.execute('SELECT * FROM videos;'): print("title:",videos[2]) ...
[ "As long as I know, the first element of the array returned, so videos in your case, contains the list of the columns returned by you SQL request.\nSo here's something you could do :\nvideos = cur.execute('SELECT * FROM videos;')\n\n# Get the index of the columns\ntitle_index = videos[0].index(\"title\");\nrelease_...
[ 0 ]
[]
[]
[ "for_loop", "python", "sqlite" ]
stackoverflow_0074351125_for_loop_python_sqlite.txt
Q: How do I retrieve a username with Python keyring? I have a Mercurial keyring on my Windows 7 machine. I am using the Python keyring library to get user credentials from the Mercurial keyring. I can retrieve the password for a given username with: keyring.get_password('Mercurial', 'user@@etc') Is there a similar f...
How do I retrieve a username with Python keyring?
I have a Mercurial keyring on my Windows 7 machine. I am using the Python keyring library to get user credentials from the Mercurial keyring. I can retrieve the password for a given username with: keyring.get_password('Mercurial', 'user@@etc') Is there a similar function to retrieve the username?
[ "On Windows I was able to get both username and password (i.e. the \"credentials\") using\nc = keyring.get_credential(\"servicename\", None)\nNote that this does not work on macOS, the keyring backend does not have capabilities to search for entries - i.e. you need to know the username. I suppose that native code w...
[ 11, 9, 6, 1, 0 ]
[]
[]
[ "python", "python_keyring", "windows" ]
stackoverflow_0015235139_python_python_keyring_windows.txt
Q: How to importing database from csv file in django? In my webapp I need put a page where the user can create a database from a csv fileupload. I try do this using a def how done in here https://docs.djangoproject.com/en/4.1/topics/http/file-uploads/, but, dont work. I guess the models is working sucessfully, becaus...
How to importing database from csv file in django?
In my webapp I need put a page where the user can create a database from a csv fileupload. I try do this using a def how done in here https://docs.djangoproject.com/en/4.1/topics/http/file-uploads/, but, dont work. I guess the models is working sucessfully, because the others forms. forms.py class FileFieldForm(ModelFo...
[ "You can read the CSV file with pandas and transform each line to a dict:\nimport pandas as pd\ndf = pd.read_csv('your path file')\ndict_df = df.to_dict(orient='records')\n\nand later you can use the 'super' method to instance each dict element and save in the db:\nfirst change your \"init\" method:\nclass FileFiel...
[ 0 ]
[]
[]
[ "django", "django_forms", "html", "python" ]
stackoverflow_0074351114_django_django_forms_html_python.txt
Q: Access data in a nested df I am using a library to get stock data. The data is then put into a df but in a nested form. I want to get data from two specific columns but the date column key is not recognised. import numpy as np from yahooquery import Ticker mydata = Ticker('WMT', asynchronous=True) # the above re...
Access data in a nested df
I am using a library to get stock data. The data is then put into a df but in a nested form. I want to get data from two specific columns but the date column key is not recognised. import numpy as np from yahooquery import Ticker mydata = Ticker('WMT', asynchronous=True) # the above returns a yahoo.ticker.Ticker obje...
[ "I tried it out, and I believe you can use pandas.DataFrame.reset_index\nCode:\ndf.reset_index()[[\"date\",\"close\"]]\n\nOutput:\n\n" ]
[ 2 ]
[]
[]
[ "python", "yahoo_api" ]
stackoverflow_0074351281_python_yahoo_api.txt
Q: How to assign variables to worker Thread in Python PyQt5? I have designed a GUI program using pyqt5. I have a main thread and a worker thread. When the GUI starts, i get some inputs from user such as age, name, ... and i want to process the inputs in worker. For example How can i send the inputs which i get using ...
How to assign variables to worker Thread in Python PyQt5?
I have designed a GUI program using pyqt5. I have a main thread and a worker thread. When the GUI starts, i get some inputs from user such as age, name, ... and i want to process the inputs in worker. For example How can i send the inputs which i get using self.ui.firstname.text() to the worker? in other words, self.ui...
[ "You can acomplish this by adding a new property to your worker class. Just make sure it doesn't shadow any other property, method, slot or signal from the object. With this, you can now pass data to your thread from initialization, via the parameter area:\nclass Worker(QObject):\n finished = pyqtSignal()\n d...
[ 1 ]
[]
[]
[ "pyqt5", "python" ]
stackoverflow_0074348042_pyqt5_python.txt
Q: Groupby and lag all columns of a dataframe? I want to lag every column in a dataframe, by group. I have a frame like this: import numpy as np import pandas as pd index = pd.date_range('2015-11-20', periods=6, freq='D') df = pd.DataFrame(dict(time=index, grp=['A']*3 + ['B']*3, col1=[1,2,3]*2, col2=['a','b','c...
Groupby and lag all columns of a dataframe?
I want to lag every column in a dataframe, by group. I have a frame like this: import numpy as np import pandas as pd index = pd.date_range('2015-11-20', periods=6, freq='D') df = pd.DataFrame(dict(time=index, grp=['A']*3 + ['B']*3, col1=[1,2,3]*2, col2=['a','b','c']*2)).set_index(['time','grp']) which looks lik...
[ "IIUC, you can simply use level=\"grp\" and then shift by -1:\n>>> shifted = df.groupby(level=\"grp\").shift(-1)\n>>> df.join(shifted.rename(columns=lambda x: x+\"_lag\"))\n col1 col2 col1_lag col2_lag\ntime grp \n2015-11-20 A 1 a 2 b\n2015-...
[ 28, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0033907537_pandas_python.txt
Q: How to make tables with X amount of booleans with all possible values? How do i iterate through all possible X boolean values? i.e i have 2 booleans, how do i make a table with all truths and falses? like: A 0 0 1 1 B 0 1 0 1 A: Try to iterate over the 2 ** number of variables integers. The following example fo...
How to make tables with X amount of booleans with all possible values?
How do i iterate through all possible X boolean values? i.e i have 2 booleans, how do i make a table with all truths and falses? like: A 0 0 1 1 B 0 1 0 1
[ "Try to iterate over the 2 ** number of variables integers. The following example for 4 variables:\nvariables = ['A', 'B', 'C', 'D'] ...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074351218_python_python_3.x.txt
Q: How to avoid quadratic time in Python? I've created a graph G with NetworkX, where my nodes are movies and actors, and there's an edge if an actor partecipated in a movie. I have a dictionary for all actors and all movies. I want to find the pair of movies that share the largest number of actors. I thought that th...
How to avoid quadratic time in Python?
I've created a graph G with NetworkX, where my nodes are movies and actors, and there's an edge if an actor partecipated in a movie. I have a dictionary for all actors and all movies. I want to find the pair of movies that share the largest number of actors. I thought that the solution could be something like that: ...
[ "Based on my understanding of what each variable you're working with means, I think that the following should work. This makes use of Joel's \"movie size\" heuristic.\nNotably, the sorting process is O(n log(n)), so it has no impact on the overall O(n2) complexity.\ndef question3():\n def comp_func(pair):\n ...
[ 0 ]
[]
[]
[ "dictionary", "for_loop", "list", "networkx", "python" ]
stackoverflow_0074329852_dictionary_for_loop_list_networkx_python.txt
Q: How to fix "ImportError: DLL load failed" while importing win32api I'm setting up an autoclicker in Python 3.8 and I need win32api for GetAsyncKeyState but it always gives me this error: >>> import win32api Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: DLL load failed while ...
How to fix "ImportError: DLL load failed" while importing win32api
I'm setting up an autoclicker in Python 3.8 and I need win32api for GetAsyncKeyState but it always gives me this error: >>> import win32api Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: DLL load failed while importing win32api: The specified module could not be found. I'm on Win...
[ "Solved\nIf you are working in a miniconda on conda environment. You could just install pywin32 using conda instead of pip.\nThis solved my problem:\nconda install pywin32\n\n", "For my case, install and reinstall pywin32 doesn't help. After copied the two files from [installation directory of Anaconda]\\Lib\\sit...
[ 97, 60, 45, 36, 13, 13, 8, 8, 5, 4, 3, 3, 3, 3, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "That is Simple. After Many Tries, I Discovered a Solution. Just Type the Following Commands in Windows 10. I am Using Pycharm, Python Version 3.9\nNote:- This Works for All Python Versions !!\npip uninstall pywin32\n\npip install pywin32\n\nThat is Simple.\nif That Does Not Work, Then Try:-\npip uninstall win32api...
[ -1, -1 ]
[ "pip", "python", "python_3.x", "pywin32", "winapi" ]
stackoverflow_0058612306_pip_python_python_3.x_pywin32_winapi.txt
Q: update a value in a dictionary in nested list in pymongo i have the following data in the mongodb database { "_id" : ObjectId("633c1dc6d3f3452751698332"), "col_1" : 153.618639317759, "col_2" : 276.7287225, "col_3" : "A2", "col_4" : "R18", "col_5" : [ { "f" : 0, ...
update a value in a dictionary in nested list in pymongo
i have the following data in the mongodb database { "_id" : ObjectId("633c1dc6d3f3452751698332"), "col_1" : 153.618639317759, "col_2" : 276.7287225, "col_3" : "A2", "col_4" : "R18", "col_5" : [ { "f" : 0, "Z" : 2.87673627341312 }, { "...
[ "Query\n\nfind the member of col_5 that has \"f=4\" , $ holds that member\nand then set col_5.$.z=1000\n\n*use updateOne or updateMany based on your needs (multi true is like updateMany)\nPlaymongo\nupdate(\n{\"col_5\": {\"$elemMatch\": {\"f\": {\"$eq\": 4}}}},\n{\"$set\": {\"col_5.$.Z\": 1000}},\n{\"multi\": true}...
[ 0 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0074350491_mongodb_pymongo_python.txt
Q: Why isn't tensorflow installing? I can't install tensorflow! Showing this error! ERROR: Could not find a version that satisfies the requirement tensorflow (from versions: none) ERROR: No matching distribution found for tensorflow I installed Python 3.11, but I got the same error message again. I googled the error...
Why isn't tensorflow installing?
I can't install tensorflow! Showing this error! ERROR: Could not find a version that satisfies the requirement tensorflow (from versions: none) ERROR: No matching distribution found for tensorflow I installed Python 3.11, but I got the same error message again. I googled the error and tried some of the things which we...
[ "Currently, Tensorflow is not yet supported for your python version which is \"3.11\". Check here for the supported systems and versions.\nMy recommendation is to use a virtual environment or a conda environment and install a supported version of python for the corresponding TensorFlow version.\nCheck here to see h...
[ 6 ]
[]
[]
[ "cmd", "pip", "python", "python_3.x", "tensorflow" ]
stackoverflow_0074350485_cmd_pip_python_python_3.x_tensorflow.txt
Q: How to run multiple async functions alternately without sleeping in Python? When running the code with await asyncio.sleep(1) below: import asyncio async def test1(): for _ in range(0, 3): print("Test1") await asyncio.sleep(1) # Here async def test2(): for _ in range(0, 3): ...
How to run multiple async functions alternately without sleeping in Python?
When running the code with await asyncio.sleep(1) below: import asyncio async def test1(): for _ in range(0, 3): print("Test1") await asyncio.sleep(1) # Here async def test2(): for _ in range(0, 3): print("Test2") await asyncio.sleep(1) # Here async def test3()...
[ "The way to do this, as put by different people in the comments, is to call await asyncio.sleep(0). What maters is not the sleep call: with 0, it will indeed not pause, and resume the code immediately if there are no pending tasks in the event loop.\nWhat really matters is that one have to explicitly return control...
[ 2, 1 ]
[]
[]
[ "asynchronous", "python", "python_3.x", "python_asyncio", "sleep" ]
stackoverflow_0074350626_asynchronous_python_python_3.x_python_asyncio_sleep.txt
Q: return max value from a list of dictionary in python Update: I have already accepted the answer. However, if anyone could explain about why I got error message "keyerror:1 " in my method 2 in the question, I will be very happy with that. Thank you! ----------------original question ---------------- I 'm completing...
return max value from a list of dictionary in python
Update: I have already accepted the answer. However, if anyone could explain about why I got error message "keyerror:1 " in my method 2 in the question, I will be very happy with that. Thank you! ----------------original question ---------------- I 'm completing one exercise, but whatever I have tried, nothing was cor...
[ "So thanks to @12944qwerty and @Barmer's help, this problem is solved like this:\nclass Car:\n def __init__(self,make:str,top_speed:int):\n self.make=make\n self.top_speed=top_speed\n\n @staticmethod\n def fastest_car(list):\n list.sort(key = lambda x : x.top_speed)\n print(\"Sort by speed\")\n re...
[ 0, 0 ]
[]
[]
[ "dictionary", "oop", "python", "python_3.x" ]
stackoverflow_0074351005_dictionary_oop_python_python_3.x.txt
Q: build numpy d-dim array from iterator of (d-1)-dim array I have a use case, and I simplify it to following question: import numpy as np def get_matrix(i): # get a matrix N * M return ( (i, i + 1, i + 1.2), (i + 1, i / 2, i * 3.2), (i / 3, i * 2, i / 4), (i / 5, i * 2.1, i + 2.2...
build numpy d-dim array from iterator of (d-1)-dim array
I have a use case, and I simplify it to following question: import numpy as np def get_matrix(i): # get a matrix N * M return ( (i, i + 1, i + 1.2), (i + 1, i / 2, i * 3.2), (i / 3, i * 2, i / 4), (i / 5, i * 2.1, i + 2.2), ) K = 10000 # build a n-d array K * N * M arr = np.arr...
[ "Ah, so this is a new feature for np.fromiter. Just going by the example in the docs, the following worked:\nK = 10000\nN = 4\nM = 3\n\n# build a n-d array K * N * M\narr = np.fromiter(\n (get_matrix(i) for i in range(K)), \n dtype=np.dtype((np.float32, (N, M))),\n count=K\n)\n\nNote, I used the count argu...
[ 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074351073_numpy_python.txt
Q: Tricky update values from one dataset with another using Pandas (with conditions) I'd like to create a new dataset (df3) by updating values based on the [area] and [Date] column match. Here are the two datasets. df1 contains the update, df2 contains the file that will be updated with df1 data. If there is no date ...
Tricky update values from one dataset with another using Pandas (with conditions)
I'd like to create a new dataset (df3) by updating values based on the [area] and [Date] column match. Here are the two datasets. df1 contains the update, df2 contains the file that will be updated with df1 data. If there is no date or area match, the bb, aa and cc values will be 0. DATA df1 Date area bb ...
[ "You can use:\n# ensure same data\n# you could also keep the strings and pad the zeros\ndf1['Date'] = pd.to_datetime(df1['Date'])\ndf2['Date'] = pd.to_datetime(df2['Date'])\n\nkeys = ['Date', 'area']\n# align df1 on df2's keys and fill with 0s\ndf3 = (df2[keys+['stat']]\n .merge(df1, on=keys, how='left')\n .fillna(...
[ 3 ]
[]
[]
[ "merge", "numpy", "pandas", "python" ]
stackoverflow_0074351510_merge_numpy_pandas_python.txt
Q: Saving retrieved documents from API I am currently trying to download a cif file from materialsproject.org which is only possible via an API. They told me to use Mybinder.org to run their code: from mp_api.client import MPRester from pymatgen.analysis.diffraction.xrd import XRDCalculator from pymatgen.symmetry.ana...
Saving retrieved documents from API
I am currently trying to download a cif file from materialsproject.org which is only possible via an API. They told me to use Mybinder.org to run their code: from mp_api.client import MPRester from pymatgen.analysis.diffraction.xrd import XRDCalculator from pymatgen.symmetry.analyzer import SpacegroupAnalyzer with MPR...
[ "The little you've provided (which may be all they told you?) assumes prior knowledge of or familiarity with Python and/or MyBinder. If they didn't provide you that then perhaps they directed you to other materials and resources on their sites?\nHere's how you'd accomplish this, I think, without the authors helping...
[ 0 ]
[]
[]
[ "download", "python" ]
stackoverflow_0074330082_download_python.txt
Q: I want to use playsound, but i get: TypeError: 'module' object is not callable this error import turtle,random import playsound t = turtle.Turtle() s = turtle.Screen() t.speed(0) colors = ["red", "blue", "yellow", "green","cyan","orange","brown","pink","purple"] s.bgcolor("orange") t.penup() t.goto(-200, -10) t.pe...
I want to use playsound, but i get: TypeError: 'module' object is not callable this error
import turtle,random import playsound t = turtle.Turtle() s = turtle.Screen() t.speed(0) colors = ["red", "blue", "yellow", "green","cyan","orange","brown","pink","purple"] s.bgcolor("orange") t.penup() t.goto(-200, -10) t.pendown() def h(): t.lt(90) t.forward(120) t.rt(90) t.forward(25) t.rt(90) ...
[ "That's because you are not referring playsound and python thinks it's a def function. When you import playsound try doing:\nfrom playsound import *\n\nor do:\nfrom playsound import playsound\n\nOtherwise, you can also change the actual code itself and do:\nplaysound.playsound(r\"C:\\\\Users\\\\Freddy\\PycharmProje...
[ 0 ]
[]
[]
[ "playsound", "python", "turtle_graphics" ]
stackoverflow_0074351018_playsound_python_turtle_graphics.txt
Q: Insert into database fails My code: @app.route('/projects/create', methods=["POST", "GET"]) def add(): if request.method == "POST": id = request.form["id"] name = request.form["name"] text = request.form["s_text"] try: projects.db.executemany("INSERT INTO projects ...
Insert into database fails
My code: @app.route('/projects/create', methods=["POST", "GET"]) def add(): if request.method == "POST": id = request.form["id"] name = request.form["name"] text = request.form["s_text"] try: projects.db.executemany("INSERT INTO projects (?,?,?)", [id], [name], [text]) ...
[ "You don't have many rows, you have one. You need to use the VALUES keyword to signal that values are coming. And your three fields need to be ONE list. You need\nprojects.db.execute(\"INSERT INTO projects VALUES (?,?,?)\", [id, name, text] )\n\n" ]
[ 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0074350963_python_sqlite.txt
Q: Automation of program execution on linux I have to perform several experiments in order to analyse certain results for a class assignment. For each result, I have to run a line of code by varying the parameters from terminal. I was wondering if there is a way to automate this and thus save me the trouble of runnin...
Automation of program execution on linux
I have to perform several experiments in order to analyse certain results for a class assignment. For each result, I have to run a line of code by varying the parameters from terminal. I was wondering if there is a way to automate this and thus save me the trouble of running the program and changing the values each tim...
[ "For more involved process operations, one should use the subprocess module in stdlib Python... but if you just want a one-off run of this command line, you can just use plain old os.system function - The followin code:\nimport os\n\nfor nt in range(1,21): ...
[ 1 ]
[]
[]
[ "linux", "python", "terminal" ]
stackoverflow_0074351562_linux_python_terminal.txt
Q: Python Selenium selectors - Dropdown icon? I have this drop icon element. How do I need to use it with the Xpath? or which I need to use? is a burger dropdown menu. I don't know how to use it with the XPath A: driver.find_element(By.XPATH, "//i[@class='q-icon material-icons']").click()
Python Selenium selectors - Dropdown icon?
I have this drop icon element. How do I need to use it with the Xpath? or which I need to use? is a burger dropdown menu. I don't know how to use it with the XPath
[ "driver.find_element(By.XPATH, \"//i[@class='q-icon material-icons']\").click()\n\n" ]
[ 0 ]
[]
[]
[ "python", "selector", "selenium", "xpath" ]
stackoverflow_0074351221_python_selector_selenium_xpath.txt
Q: How can I send a dice/casino/darts sticker as animated in telethon? I tried to send game stickers in telethon, but I could only send football and basketball stickers as games. Other stickers was static. A: Those are not 'sticker' they're emoji. You send them as MediaDice file objects import telethon await client...
How can I send a dice/casino/darts sticker as animated in telethon?
I tried to send game stickers in telethon, but I could only send football and basketball stickers as games. Other stickers was static.
[ "Those are not 'sticker' they're emoji. You send them as MediaDice file objects\nimport telethon\nawait client.send_file(chat, \ntelethon.types.InputMediaDice(''))\n\n" ]
[ 0 ]
[]
[]
[ "python", "telethon" ]
stackoverflow_0074351445_python_telethon.txt
Q: Basic Low-pass filter for audio processing- Python I am receiving audio with a mic and want to filter out high frequency signal. I have followed all the step to design a simple lowpass filter but I get the error below if x.shape[axis] <= edge: IndexError: tuple index out of range My codes are below; import pyaudio...
Basic Low-pass filter for audio processing- Python
I am receiving audio with a mic and want to filter out high frequency signal. I have followed all the step to design a simple lowpass filter but I get the error below if x.shape[axis] <= edge: IndexError: tuple index out of range My codes are below; import pyaudio import sys import time import matplotlib.pyplot as plt ...
[ "Regardless of any other problems there might be, you're passing a bytestring to the filter, and a bytstring has an \"empty\" shape, so even trying to access axis=0 results in the error you're seeing.\nYou probably want to convert to a numpy array, and then convert back, by changing the appropriate line to -\nfdata...
[ 1 ]
[]
[]
[ "digital_filter", "python", "raspberry_pi3", "signal_processing" ]
stackoverflow_0074348744_digital_filter_python_raspberry_pi3_signal_processing.txt
Q: Extract sentence containing specific word and add symbols around it? I need to (1) extract sentences containing specific words, (2) add asterisk symbols around the specific word,(3)keep one sentence per row if multiple sentences match any of the term I'm searching for, and (4) drop the rows that don't contain any ...
Extract sentence containing specific word and add symbols around it?
I need to (1) extract sentences containing specific words, (2) add asterisk symbols around the specific word,(3)keep one sentence per row if multiple sentences match any of the term I'm searching for, and (4) drop the rows that don't contain any of the words I'm searching for. My dataset looks like this. text I like ...
[ "here is one way to do it\nAssumption: the sentences ends with a period in the text column\n# split the string on period (.) and explode to make rows out of it\ndf2=df['text'].str.split('.').explode()\n\n# find if list of words exists in the sentences, \n# use replace to add * around the words\n\ndf2=df['text'].str...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074350115_pandas_python.txt
Q: Other ways to get the return values from "yield" in "async" functions in Python? When using async for statement in async def call_test() as shown below: import asyncio async def test(): yield "One" yield "Two" yield "Three" async def call_test(): async for i in test(): # Here print(i) as...
Other ways to get the return values from "yield" in "async" functions in Python?
When using async for statement in async def call_test() as shown below: import asyncio async def test(): yield "One" yield "Two" yield "Three" async def call_test(): async for i in test(): # Here print(i) asyncio.run(call_test()) I could get the return values below from yield in async def te...
[ "For async generators, you have to await the built-in anext instead of calling next:\n...\nprint(await anext(x))\n...\n\n" ]
[ 0 ]
[]
[]
[ "asynchronous", "python", "python_3.x", "python_asyncio", "yield" ]
stackoverflow_0074347400_asynchronous_python_python_3.x_python_asyncio_yield.txt
Q: Why is the Boolean value of [None] True and the Boolean value of [] False? I was working on a project and stumbled across this weird anomaly, apparently the Boolean value for any list or tuple with an None value is True Input print(bool([])) # empty list print(bool(())) # empty tuple print(bool([None])) # list wi...
Why is the Boolean value of [None] True and the Boolean value of [] False?
I was working on a project and stumbled across this weird anomaly, apparently the Boolean value for any list or tuple with an None value is True Input print(bool([])) # empty list print(bool(())) # empty tuple print(bool([None])) # list with None print(bool((None,))) # tuple with None Output False False True True ...
[ "A tuple or a list evaluate to False in a boolean context if they're empty. (None,) and [None] are a tuple/list with 1 element (the element None), hence not empty... therefore they evaluate to True in a boolean context\n" ]
[ 3 ]
[]
[]
[ "boolean", "list", "python", "tuples" ]
stackoverflow_0074351754_boolean_list_python_tuples.txt
Q: Django migration Re-order column I've been confused,if there's any way how to order column when migrate in Django, In the first place In my case I don't have is_person in my models then eventually I want to add is_person after paid in my models like the example below in models.py, then the problem is even I corre...
Django migration Re-order column
I've been confused,if there's any way how to order column when migrate in Django, In the first place In my case I don't have is_person in my models then eventually I want to add is_person after paid in my models like the example below in models.py, then the problem is even I correctly ordered the value in my models wh...
[ "Django does not care about the order of the columns, and some SQL databases do not seem to worry too much either. In some SQL dialects, like MySQL, you can indeed can specify the \"insertion point\" with:\nALTER table table_name ADD COLUMN my_column INTEGER AFTER other_column\nBut this is not standardized SQL. For...
[ 1, 0 ]
[]
[]
[ "django", "migrate", "python" ]
stackoverflow_0065215636_django_migrate_python.txt
Q: How to webscrape old school website that uses frames I am trying to webscrape a government site that uses frameset. Here is the URL - https://lakecounty.in.gov/departments/voters/election-results-c/2022GeneralElectionResults/index.htm I've tried using splinter/selenium url = "https://lakecounty.in.gov/departments/...
How to webscrape old school website that uses frames
I am trying to webscrape a government site that uses frameset. Here is the URL - https://lakecounty.in.gov/departments/voters/election-results-c/2022GeneralElectionResults/index.htm I've tried using splinter/selenium url = "https://lakecounty.in.gov/departments/voters/election-results-c/2022GeneralElectionResults/index...
[ "As mentioned you could go for the frames and its src:\nBeautifulSoup(r.text).select('frame')[1].get('src')\n\nor directly to the menu.htm:\nimport requests\nfrom bs4 import BeautifulSoup\n\nr = requests.get('https://lakecounty.in.gov/departments/voters/election-results-c/2022GeneralElectionResults/menu.htm')\n\nli...
[ 1 ]
[]
[]
[ "python", "web_scraping" ]
stackoverflow_0074351433_python_web_scraping.txt
Q: Count one's in given submatrices I have a binary matrix of size M*N. I'm given K queries where each consists of given sub-matrix, with upper left coord (x1,y1) and lower right coord (x2,y2). My task is to find how many one's are in each submatrix. I should find the best solution in terms of time complexity. How ca...
Count one's in given submatrices
I have a binary matrix of size M*N. I'm given K queries where each consists of given sub-matrix, with upper left coord (x1,y1) and lower right coord (x2,y2). My task is to find how many one's are in each submatrix. I should find the best solution in terms of time complexity. How can I achieve that? I suppose that I sho...
[ "Let C(x1, y1, x2, y2) be the number of ones in a sub-matrix with upper left coord (x1, y1) and lower right coord (x2, y2) (i.e. x2 >= x1 and y2 >= y1), and let (1, 1) be the upper-left corner of the MxN binary matrix. Then:\n\nIf x1 > 1 and y1 > 1: C(x1, y1, x2, y2) = C(1, 1, x2, y2) - C(1, 1, x2, y1-1) - C(1, 1, ...
[ 1 ]
[]
[]
[ "algorithm", "binary_data", "data_structures", "matrix", "python" ]
stackoverflow_0074350606_algorithm_binary_data_data_structures_matrix_python.txt
Q: JavaScript TextEncoder / TextDecoder equivalent in python I wanted to get the same results we got by using TextEncoder and TextDecoder on javascript but couldn't find real code solution the soluction I found doesn't give me the real same results. exp: const textencoder = new TextEncoder(); console.log(textencoder....
JavaScript TextEncoder / TextDecoder equivalent in python
I wanted to get the same results we got by using TextEncoder and TextDecoder on javascript but couldn't find real code solution the soluction I found doesn't give me the real same results. exp: const textencoder = new TextEncoder(); console.log(textencoder.encode('$')); //[36] const textdecoder = TextDecoder(); consol...
[ "after a many tries and search, I got the solution form a friend and I decided to share it with you, may someone need it some day;\nclass TextEncoder():\n def __init__(self):\n pass\n \n def encode(self, text):\n \"\"\"\n exp:\n >>> textencoder = TextEncoder()\n >...
[ 1 ]
[]
[]
[ "arrays", "javascript", "python" ]
stackoverflow_0074351880_arrays_javascript_python.txt
Q: Clean up this list to only keep the most recent crawl based on the year I have a list which looks like this: [<GET https://web.archive.org/web/20110518083020id_/http://www.rollsroyce.com/about/index.jsp>, <GET https://web.archive.org/web/20110617060411id_/http://www.rollsroyce.com/about/index.jsp>, <GET https://we...
Clean up this list to only keep the most recent crawl based on the year
I have a list which looks like this: [<GET https://web.archive.org/web/20110518083020id_/http://www.rollsroyce.com/about/index.jsp>, <GET https://web.archive.org/web/20110617060411id_/http://www.rollsroyce.com/about/index.jsp>, <GET https://web.archive.org/web/20110810011112id_/http://www.rollsroyce.com/about/index.jsp...
[ "This is my answer but I'm not sure if it's correct:\n# deduplicate the array, keep only one entry per URL per year\nitems_to_keep = []\nyear_dict = {}\nfor i in my_array:\n url = i.split('id_/')[1]\n datetime_str = i.split('web/')[1].split('id_/')[0]\n datetime_obj = datetime.datetime.strptime(datetime_st...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074351879_python.txt
Q: Pipenv package hash does not match lock file We have a lock file which has not changed since April 2021. Recently, we have started seeing the following error on pipenv install --deploy: ERROR: THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE. If you have updated the package versions, please update...
Pipenv package hash does not match lock file
We have a lock file which has not changed since April 2021. Recently, we have started seeing the following error on pipenv install --deploy: ERROR: THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS FILE. If you have updated the package versions, please update the hashes. Otherwise, examine the package conten...
[ "Thanks to @Ouroborus for the answer:\ne0... is for the .tar.gz (source) package, 9d... is for the .whl package. (See the \"view hashes\" links on PyPI's gunicorn files page) I'm not sure why your systems are choosing to download the wheel now when they downloaded the source previously. However, those are both vali...
[ 0 ]
[]
[]
[ "gunicorn", "pipenv", "pypi", "python" ]
stackoverflow_0074306906_gunicorn_pipenv_pypi_python.txt
Q: Using for loop variable on a getattr() function I have a class Person with the attributes name and level class Person: def __init__(self, name, level): self.name = name self.level = level let's say i have a bunch of objects from that class with different attributes p1 = Person("p...
Using for loop variable on a getattr() function
I have a class Person with the attributes name and level class Person: def __init__(self, name, level): self.name = name self.level = level let's say i have a bunch of objects from that class with different attributes p1 = Person("person1", "5") p2 = Person("person2", "10") p3 = Perso...
[ "You have a few faults, each of which is obscuring other parts of the program.\nStart by making a list of the people:\npeople_list = [p1, p2, p3]\n\nThen you can iterate directly over the list:\ndef lvlFinder(people_list):\n for item in people_list:\n y = item.level\n print(y)\n\nFinall...
[ 1, 0 ]
[]
[]
[ "python", "renpy" ]
stackoverflow_0074351833_python_renpy.txt
Q: Plotly change color mapping interactively based on data frame values I have a data frame from which I want to create a scatter plot from, which I do via import plotly.express as px fig = px.scatter(df, x="X", y="Y", color="size") I want interactively change the color mapping by a dropdown menu for all columns in ...
Plotly change color mapping interactively based on data frame values
I have a data frame from which I want to create a scatter plot from, which I do via import plotly.express as px fig = px.scatter(df, x="X", y="Y", color="size") I want interactively change the color mapping by a dropdown menu for all columns in the data frame (beside X, Y). What I need is to probably set this one up c...
[ "I created a working example below to demonstrate how you can change the color of the trace based on some column value.You could use similar concept to change size as well.\nI don't like to mix Plotly Express and Graph Objects traces as it can be quite confusing. I prefer to use Graph Objects library as it gives th...
[ 1 ]
[]
[]
[ "interactive", "pandas", "plotly", "python" ]
stackoverflow_0074350641_interactive_pandas_plotly_python.txt
Q: Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything It seems easy to get the From To Subject etc via import email b = email.message_from_string(a) bbb = b['from'] ccc = b['to'] assuming that "a" is the raw-email string which looks something like this. a ...
Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything
It seems easy to get the From To Subject etc via import email b = email.message_from_string(a) bbb = b['from'] ccc = b['to'] assuming that "a" is the raw-email string which looks something like this. a = """From root@a1.local.tld Thu Jul 25 19:28:59 2013 Received: from a1.local.tld (localhost [127.0.0.1]) by a1....
[ "To be highly positive you work with the actual email body (yet, still with the possibility you're not parsing the right part), you have to skip attachments, and focus on the plain or html part (depending on your needs) for further processing.\nAs the before-mentioned attachments can and very often are of text/plai...
[ 141, 98, 16, 14, 4, 1, 0 ]
[ "Here's the code that works for me everytime (for Outlook emails):\n#to read Subjects and Body of email in a folder (or subfolder)\n\nimport win32com.client \n#import package\n\noutlook = win32com.client.Dispatch(\"Outlook.Application\").GetNamespace(\"MAPI\") \n#create object\n\n#get to the desired folder (MyEma...
[ -3 ]
[ "email", "mod_wsgi", "python", "python_2.7", "wsgi" ]
stackoverflow_0017874360_email_mod_wsgi_python_python_2.7_wsgi.txt
Q: Python assignment (school) dinner options without loops I've got to create a 4 meal option, of which 3 meals also have sauce options. No loop and/or functions are allowed. So I got 4 meals; 1) Steak, 2) Mussels, 3) Scampi, 4) Quinoa The user get's asked what meals he wants, by inserting the corresponding number. A...
Python assignment (school) dinner options without loops
I've got to create a 4 meal option, of which 3 meals also have sauce options. No loop and/or functions are allowed. So I got 4 meals; 1) Steak, 2) Mussels, 3) Scampi, 4) Quinoa The user get's asked what meals he wants, by inserting the corresponding number. Any other number should result in a; "We do not serve this". T...
[ "I recognize doing these kinds of things when I just started out. No worries, just keep improving! That said, here is something to think about:\nIf you create a variable for each combination of \"maaltijd\" and \"saus\", you'll have to add an enormous amount of code every time you add either one. One improvement wo...
[ 0, 0 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0074351090_if_statement_python.txt
Q: Regex: capture specific string with conditions Im trying to just capture the following string: u00 because i need to replace it to \u00. Sometimes this characters appear with a \ before, in that case, i don't want to capture it. At other times, the simbol is ", i want to capture it, but just the u00, not "u00 Im t...
Regex: capture specific string with conditions
Im trying to just capture the following string: u00 because i need to replace it to \u00. Sometimes this characters appear with a \ before, in that case, i don't want to capture it. At other times, the simbol is ", i want to capture it, but just the u00, not "u00 Im trying this: file_modified = re.sub(r'[^\\|^\s](u00)'...
[ "Just match it optionally:\nfile_modified = re.sub(r'\\\\?u00', r'\\\\u00', original_file)\n\nHere,\n\n\\\\?u00 - matches an optional \\ and u00\n\\\\u00 - is a replacement pattern that replaces with \\u00\n\nThus, even if there was a \\ before u00, it won't disappear and won't get doubled, but if it was missing, ...
[ 1, 0 ]
[]
[]
[ "python", "regex", "string", "substring" ]
stackoverflow_0074351838_python_regex_string_substring.txt
Q: Python: drop value=0 row in specific columns. If there is just one 0, delete whole row I know this question has been asked many times but it just doesnt work for me and i dont know why. I need to see a graph without zero values, but it only shows a graph with them no matter what i try These are the first 5 rows fr...
Python: drop value=0 row in specific columns. If there is just one 0, delete whole row
I know this question has been asked many times but it just doesnt work for me and i dont know why. I need to see a graph without zero values, but it only shows a graph with them no matter what i try These are the first 5 rows from .csv file. I need this kind of values 0 2022-10-24T12:12:35Z 44.61 1 2022-10-24T12:12:...
[ "# select rows that has value 0\n# then take negation of it and return the DF using LOC\n\ndf=df.loc[~df['value'].eq(0)]\n\n\n", "This would return all rows that do not have a 0 in any of your columns.\ndataset2.loc[~(dataset2==0).all(axis=1)]\n\nAlternatively you could replace 'COLUMN' with your column name to o...
[ 1, 0 ]
[]
[]
[ "dataframe", "dataset", "pandas", "python", "python_3.x" ]
stackoverflow_0074352097_dataframe_dataset_pandas_python_python_3.x.txt
Q: INSEE API Module not found in PyQGIS I'm a beginner in programming. I made a script that allows me to create and export maps in a full automatize way in PyQGIS. My goal here with this API, is to add some data with the "siret" number on each maps. But even before I could try to do that, I'm stuck after the installa...
INSEE API Module not found in PyQGIS
I'm a beginner in programming. I made a script that allows me to create and export maps in a full automatize way in PyQGIS. My goal here with this API, is to add some data with the "siret" number on each maps. But even before I could try to do that, I'm stuck after the installation of this API in a terminal. I'm follow...
[ "QGIS ships a python interpreter for itself. It doesn't recognize packages installed via your default python installation.\nYou seem to be on windows, so one way to install a package would be to find the OSGeo4W shell (OSGeo4W64.bat), which is located in the QGIS installation folder. Open it, then execute:\n\npy3_e...
[ 0, 0 ]
[]
[]
[ "api", "pyqgis", "python" ]
stackoverflow_0069955038_api_pyqgis_python.txt
Q: List comprehension - check for partial string present in a separate list(complete match)? I am trying to match partials from a list with a complete match in the other list. match_list = ['abc', 'bcc'] # etc files = os.listdir() files = ['hello-abc', 'bye-abc', 'byebyebcc', 'byehelloxyz'] # List comprehension to...
List comprehension - check for partial string present in a separate list(complete match)?
I am trying to match partials from a list with a complete match in the other list. match_list = ['abc', 'bcc'] # etc files = os.listdir() files = ['hello-abc', 'bye-abc', 'byebyebcc', 'byehelloxyz'] # List comprehension to match partial 'hello-abc'(example) in files with element 'abc' in files. # this wont work fil...
[ "You can use any().\nmatch_list = ['abc', 'bcc'] # etc\nfiles = ['hello-abc', 'bye-abc', 'byebyebcc', 'byehelloxyz']\nfiles = [i for i in files if any(m in i for m in match_list)]\nprint(files) \n# ['hello-abc', 'bye-abc', 'byebyebcc']\n\nExplanation:\nfor i in files: \n print(i , [[m, (m in i)] for m in match_l...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074352116_python.txt
Q: Using an expression as an input to a function? Say I wanted to create a redundant function that joins 2 dataframes: def foo(df1, df2, how = None, on = None): df = pd.merge(df1, df2, how = how, on = on) return df how is a string argument so thats not a problem. However, the on argument would be an expression...
Using an expression as an input to a function?
Say I wanted to create a redundant function that joins 2 dataframes: def foo(df1, df2, how = None, on = None): df = pd.merge(df1, df2, how = how, on = on) return df how is a string argument so thats not a problem. However, the on argument would be an expression... lets say: df1.id == df2.id join_df = foo(df1, d...
[ "I think you're trying to do it as it is in SQL. Try this:\ndef foo(df1, df2, how = None, right_on=None, left_on=None):\n df = pd.merge(df1, df2, how = how, right_on=right_on, left_on=left_on)\n return df\n\nthe right_on gets the column name from df1, and the left_on gets it from df2.\njoin_df = foo(df1, df2, h...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074352023_dataframe_pandas_python.txt
Q: Merge two arrays from a given index - PYTHON I am wondering if there is an easy way to 'append' new elements to an array, but not at the end Imagine I have a vector a = np.array([1,2,3,4,5,6]) I want to append a new vector b = np.array([1,1,1,1]) to a, starting from element 3 so that the new array would be c = ...
Merge two arrays from a given index - PYTHON
I am wondering if there is an easy way to 'append' new elements to an array, but not at the end Imagine I have a vector a = np.array([1,2,3,4,5,6]) I want to append a new vector b = np.array([1,1,1,1]) to a, starting from element 3 so that the new array would be c = np.array([1,2,3,5,6,7,1]) that is the last 3 ele...
[ "Using numpy with pad:\na = np.array([1,2,3,4,5,6])\nb = np.array([1,1,1,1])\n# or\n# a = [1,2,3,4,5,6]\n# b = [1,1,1,1]\n\nn = 3\nextra = len(b)-len(a)+n\n\nc = np.pad(a, (0, extra))\nc[n:] += b\n\nOutput:\narray([1, 2, 3, 5, 6, 7, 1])\n\n" ]
[ 1 ]
[]
[]
[ "append", "arrays", "merge", "numpy", "python" ]
stackoverflow_0074352117_append_arrays_merge_numpy_python.txt
Q: db and asynchrony. how to combine? The problem is that the database does not have time to be processed and there is a call on the second circle. How to make the database processing happen and the cycle goes on. asynchronously async def send_mes_to_users(client): async with client: user = 'userrrrrrrrr'...
db and asynchrony. how to combine?
The problem is that the database does not have time to be processed and there is a call on the second circle. How to make the database processing happen and the cycle goes on. asynchronously async def send_mes_to_users(client): async with client: user = 'userrrrrrrrr' try: if db.check_in...
[ "You are running two tasks at the same time (with gather). You're likely to run into a race condition. If you need to synchronize a \"critical section\", consider using an asyncio.Lock:\ndb_lock = asyncio.Lock()\n\nasync def send_mes_to_users(client):\n async with client:\n user = 'userrrrrrrrr'\n ...
[ 1, 1 ]
[]
[]
[ "asynchronous", "python", "telegram", "telethon" ]
stackoverflow_0074352076_asynchronous_python_telegram_telethon.txt
Q: Django form.as_p DateField not showing input type as date Working on my first django app, and I have a model defined with some DateFields, and then a ModelForm off of that model i.e. models.py class MyModel(models.Model): ... my_date = models.DateField('my date') ... class MyModelForm(ModelForm): ...
Django form.as_p DateField not showing input type as date
Working on my first django app, and I have a model defined with some DateFields, and then a ModelForm off of that model i.e. models.py class MyModel(models.Model): ... my_date = models.DateField('my date') ... class MyModelForm(ModelForm): class Meta: model = MyModel fields = '__all__' ...
[ "You can create a custom widget:\nfrom django import forms\n\nclass DateInput(forms.DateInput):\n input_type = 'date'\n\nclass MyModelForm(forms.ModelForm):\n class Meta:\n model = MyModel\n fields = '__all__'\n widgets = {\n 'my_date': DateInput()\n }\n\n", "There's n...
[ 57, 45, 11, 4, 1, 0, 0, 0 ]
[ "Installation\n\nRun pip install django-datetimepicker\nAdd 'datetimepicker' to your INSTALLED_APPS\n\nBasic usage\nHere is an example of how to use the widget.\n. Assign the DateTimePicker to a DateTimeField, DateField or TimeField.\nfrom django import forms\nfrom datetimepicker.widgets import DateTimePicker\n\n\n...
[ -1 ]
[ "django", "django_forms", "python" ]
stackoverflow_0022846048_django_django_forms_python.txt
Q: running subprocess with combined cd and pwd I run subprocess in jupyter to get the core path. I have to go one folder up and then call pwd Running: import subprocess mypath=subprocess.run("(cd .. && pwd)") leads to a "No such file or directory: '(cd .. && pwd)' error. I guess the cd calls a directory call. Can y...
running subprocess with combined cd and pwd
I run subprocess in jupyter to get the core path. I have to go one folder up and then call pwd Running: import subprocess mypath=subprocess.run("(cd .. && pwd)") leads to a "No such file or directory: '(cd .. && pwd)' error. I guess the cd calls a directory call. Can you help me out?
[ "Frame challenge: subprocess is the wrong tool for this job.\nimport os.path\n\nmypath = os.path.abspath(os.path.dirname(os.getcwd()))\n\n...is both faster and portable to non-UNIXy operating systems.\n", "for a single shell command (where the arguments are not separated from the command), you need to set shell =...
[ 3, 1, 0 ]
[]
[]
[ "command_line", "pwd", "python", "shell", "subprocess" ]
stackoverflow_0074350122_command_line_pwd_python_shell_subprocess.txt
Q: Creating new column based on conditions from a separate dataframe Dataframe A: osiId hostName infrastructureOnly hostMemoryGigabytes timeFrameEnd 0 3706509458083282923 None False 15.998997 2022-10-08 16:00:00 1 -3839344128100363916 None ...
Creating new column based on conditions from a separate dataframe
Dataframe A: osiId hostName infrastructureOnly hostMemoryGigabytes timeFrameEnd 0 3706509458083282923 None False 15.998997 2022-10-08 16:00:00 1 -3839344128100363916 None False 15.512978 2022-10-08 16:00:00 ...
[ "If you drop the last row from your second df, and just know that the results will be divided by 16 for any records that match that last row, you can use merge_asof to merge to the nearest higher value.\nThen you can use a few lines to use one hostUnits vs the other based on infrastuctureOnly, and lastly you can di...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0074352016_dataframe_pandas_python_python_3.x.txt
Q: How to extract only numeric digit from a .csv file name from big query location using python I have one csv file name in my Google cloud storage bucket and the name of the file is like 'select_tb22322_c' this. Now I need to create a variable in python 'MAIL' and in this variable I need to extract only 22322 from t...
How to extract only numeric digit from a .csv file name from big query location using python
I have one csv file name in my Google cloud storage bucket and the name of the file is like 'select_tb22322_c' this. Now I need to create a variable in python 'MAIL' and in this variable I need to extract only 22322 from the above .csv file name. That means in MAIL variable I will have only 22322. What would be the pyt...
[ "Assuming the pattern for \"select_tb22322_c\" is unique. You can create a regex to capture the digit in this pattern. See approach below:\nfrom google.cloud import storage\nimport re\n\nstorage_client = storage.Client()\nbucket = storage_client.get_bucket('your-bucket-name')\n\nblobs = bucket.list_blobs()\n\nfor b...
[ 1 ]
[]
[]
[ "extract", "google_bigquery", "python" ]
stackoverflow_0074345586_extract_google_bigquery_python.txt
Q: Extracting a portion of a big numpy array based on rows and columns I have over 1 million row (1,125,000 to be exact) and 150 column numpy array. I want to be able to extract certain portion of this array for all of its columns however only certain rows. For example, the first subset array (df) to have all the col...
Extracting a portion of a big numpy array based on rows and columns
I have over 1 million row (1,125,000 to be exact) and 150 column numpy array. I want to be able to extract certain portion of this array for all of its columns however only certain rows. For example, the first subset array (df) to have all the columns of the original big array but only include the (:, 56:67, 56:67) [ba...
[ "IIUC, it looks like you can reshape big_array so that you have a shape of (50,150, 150,3), so that the last dimension is the number of column in big_array or 150 in your real case but you can use big_array.shape[1] as well. Then select all the data you want with the same slicing that you do in the loop except take...
[ 0 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074351978_numpy_pandas_python.txt
Q: How to convert list of dimension 0 tensors, each attached with gradient, to a dimension 1 tensor with only one gradient? I'm trying to make some adjustments to some pre-existing code, and can get a list that looks like the following: [tensor(0.5209, grad_fn=<SqueezeBackward0>), tensor(0.5572, grad_fn=<SqueezeBackw...
How to convert list of dimension 0 tensors, each attached with gradient, to a dimension 1 tensor with only one gradient?
I'm trying to make some adjustments to some pre-existing code, and can get a list that looks like the following: [tensor(0.5209, grad_fn=<SqueezeBackward0>), tensor(0.5572, grad_fn=<SqueezeBackward0>), tensor(0.7117, grad_fn=<SqueezeBackward0>), tensor(0.5730, grad_fn=<SqueezeBackward0>), tensor(0.3471, grad_fn=<Squeez...
[ "Using torch.hstack, you can put all tensors into a large one with one grad_fn.\ntensors = [...] # some tensors with grad_fn\ntorch.hstack(tensors) # grad_fn is CatBackward0\n\n" ]
[ 2 ]
[]
[]
[ "deep_learning", "python", "pytorch" ]
stackoverflow_0074351376_deep_learning_python_pytorch.txt
Q: "Error binding parameter 0" using executemany() executemany() fails to insert a datetime value. Error : sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type. #!/usr/bin/env python3 # Download EOD data from Yahoo import sqlite3, datetime import pandas as pd import yfinance as yf con = sq...
"Error binding parameter 0" using executemany()
executemany() fails to insert a datetime value. Error : sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type. #!/usr/bin/env python3 # Download EOD data from Yahoo import sqlite3, datetime import pandas as pd import yfinance as yf con = sqlite3.connect('sec_master.db') now = datetime.dateti...
[ "Try writing a simple function check the type of each item before insert_into_db(), like\ndef check_type(yf):\n for thing in yf:\n print(f\"the thing {thing} has type {type(thing)}\")\n\nThen call it here:\nif __name__ == \"__main__\":\n tickers = obtain_tickers()\n for t in tickers:\n yf_data = yf...
[ 0 ]
[]
[]
[ "pandas", "python", "sqlite" ]
stackoverflow_0074351905_pandas_python_sqlite.txt
Q: Extract data from a text file using Python in a specific format I'm trying to extract pieces of data from a text file, then insert it into a CSV file, in order to do that I'm trying to get the data extracted and get it as prepared as possible to be able to insert it into the CSV file, I have a file full of text th...
Extract data from a text file using Python in a specific format
I'm trying to extract pieces of data from a text file, then insert it into a CSV file, in order to do that I'm trying to get the data extracted and get it as prepared as possible to be able to insert it into the CSV file, I have a file full of text that looks like this: Date TimeStamp Name Action Depar...
[ "If the only extra spaces are in the Department column, you could do this. I am assuming you don't want a spaced header and a blank line in the CSV file as that would be odd.\nimport csv\n\nwith open('input.txt', newline='') as fin, open('output.csv', 'w', newline='') as fout:\n reader = csv.reader(fin, delimit...
[ 0 ]
[]
[]
[ "file", "file_io", "python", "python_3.x" ]
stackoverflow_0074352169_file_file_io_python_python_3.x.txt
Q: Setting text properties in matplotlib (condensed, expanded, and small-caps) I'm trying to create a matplotlib plot with several pieces of text in it, but I have trouble setting some of the text properties to desirable values. Specifically, I'm having trouble creating text of 'small-caps' variant and 'condensed'/'e...
Setting text properties in matplotlib (condensed, expanded, and small-caps)
I'm trying to create a matplotlib plot with several pieces of text in it, but I have trouble setting some of the text properties to desirable values. Specifically, I'm having trouble creating text of 'small-caps' variant and 'condensed'/'expanded' stretch. I've tried the following python script import matplotlib.pyplot...
[ "It seems as if \"small caps\" are actually not supported in matplotlib (even though the documentation suggests otherwise). They have an open issue on it since 2017: issue #8552\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "python", "text" ]
stackoverflow_0032415628_matplotlib_python_text.txt
Q: How to get center of set of points using Python I would like to get the center point(x,y) of a figure created by a set of points. How do I do this? A: If you mean centroid, you just get the average of all the points. x = [p[0] for p in points] y = [p[1] for p in points] centroid = (sum(x) / len(points), sum(y) /...
How to get center of set of points using Python
I would like to get the center point(x,y) of a figure created by a set of points. How do I do this?
[ "If you mean centroid, you just get the average of all the points.\nx = [p[0] for p in points]\ny = [p[1] for p in points]\ncentroid = (sum(x) / len(points), sum(y) / len(points))\n\n", "If the set of points is a numpy array positions of sizes N x 2, then the centroid is simply given by:\ncentroid = positions.mea...
[ 44, 14, 10, 3 ]
[]
[]
[ "matplotlib", "python", "triangulation" ]
stackoverflow_0004355894_matplotlib_python_triangulation.txt
Q: Why does python think that the request() function is the get() function? My requests library doesn't have any issues except in this class function I created. import requests from requests import request class Business: def __init__(self, url, api_key): self.url = url self.api_key = api_key ...
Why does python think that the request() function is the get() function?
My requests library doesn't have any issues except in this class function I created. import requests from requests import request class Business: def __init__(self, url, api_key): self.url = url self.api_key = api_key def send_valid_request(self, category, location): headers = {'Autho...
[ "Like the error message says, requests.request only takes two positional arguments. The others need to be passed by name:\nresponse = request('GET', url, params=params, headers=headers)\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x", "python_requests" ]
stackoverflow_0074352224_python_python_3.x_python_requests.txt
Q: How to disable the size limit of the QPushButton in the QTableWidget in PyQt5? I am trying to find solution by some time but nothing works so far.. I made a simple QTableWidget in PyQt5 and while casual QTableWidgetItems and QLabel resizes well using the option .resizeColumnsToContents(), the QPushButton somehow k...
How to disable the size limit of the QPushButton in the QTableWidget in PyQt5?
I am trying to find solution by some time but nothing works so far.. I made a simple QTableWidget in PyQt5 and while casual QTableWidgetItems and QLabel resizes well using the option .resizeColumnsToContents(), the QPushButton somehow keeps its minimum width which makes the column too wide. I tried using setMinimumWidt...
[ "When using widgets in item views, the header auto resizing uses the widget's size hint, not the minimum size.\nA QPushButton normally has a wider size hint (even if it doesn't have text), so you have two options:\n\nuse a QToolButton instead (which is normally smaller by default);\ncreate a subclass of QPushButton...
[ 1 ]
[]
[]
[ "pyqt5", "python", "qpushbutton", "qtablewidget", "resize" ]
stackoverflow_0074342970_pyqt5_python_qpushbutton_qtablewidget_resize.txt