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: How do i reassign the contents of a variables? I'm using google colab and dropdown doesn't allow variables to be used within itself. Therefore, I need that at a certain value in commas, the variable changes to a certain value of the original variable. It sounds complicated, so it's better to look at the code, eve...
How do i reassign the contents of a variables?
I'm using google colab and dropdown doesn't allow variables to be used within itself. Therefore, I need that at a certain value in commas, the variable changes to a certain value of the original variable. It sounds complicated, so it's better to look at the code, everything will become clear there. engine_output_path ...
[]
[]
[ "To change the value of path_var_1, try this\nglobals()['path_var_1'] = 'new value'\n\nOr, if you want to use i\nglobals()[f'path_var_{i}'] = 'next value'\n\n" ]
[ -1 ]
[ "drop_down_menu", "google_colaboratory", "list", "python", "variables" ]
stackoverflow_0074262827_drop_down_menu_google_colaboratory_list_python_variables.txt
Q: How can I reshape a numpy array in a certain way without using a loop? I have been trying to reshape a numpy array by using not more than one loop or even better no loop at all. But after several trials with np.reshape() and np.transpose(), I still do not have a clue how to transform an array like this: array([[1,...
How can I reshape a numpy array in a certain way without using a loop?
I have been trying to reshape a numpy array by using not more than one loop or even better no loop at all. But after several trials with np.reshape() and np.transpose(), I still do not have a clue how to transform an array like this: array([[1,2,6,3,2,5], [9,4,7,3,2,6], [8,4,6,3,2,6], [9,5,0,4,5,2], ...
[ "Note that reshape cannot change the order of the elements in an array, only the strides.\nBut it's quite straightforward to do with sliding_window_view. Of course we just want every other pair of columns, hence the ::window[1], and finalyl you want the pairs of columns as one row, hence the reshape.\nwindow = (a.s...
[ 0, 0, 0 ]
[]
[]
[ "arrays", "numpy", "python", "reshape", "vectorization" ]
stackoverflow_0074264023_arrays_numpy_python_reshape_vectorization.txt
Q: How can I shuffle my deck of cards repeatedly? We have to create a code that will shuffle the deck of cards after showing the first 13 cards. so far this is the portion of my code: deck_of_cards = [ "A-C", "2-C" ,"3-C" ,"4-C" ,"5-C" ,"6-C" ,"7-C" ,"8-C" ,"9-C" ,"10-C" ,"J-C" ,"Q-C" ,"K-C" , "A-D" ...
How can I shuffle my deck of cards repeatedly?
We have to create a code that will shuffle the deck of cards after showing the first 13 cards. so far this is the portion of my code: deck_of_cards = [ "A-C", "2-C" ,"3-C" ,"4-C" ,"5-C" ,"6-C" ,"7-C" ,"8-C" ,"9-C" ,"10-C" ,"J-C" ,"Q-C" ,"K-C" , "A-D" ,"2-D" ,"3-D" ,"4-D" ,"5-D" ,"6-D" ,"7-D" ,"8-D" ,"9...
[ "With the below code snippet via using itertools and random modules, I draw 13 new cards for each draw:\nimport itertools, random\n\ndeck = list(itertools.product(range(1,14),['-S','-H','-D','-C']))\n\nrandom.shuffle(deck)\n\n# draw 13 cards\nprint(\"You got:\")\nfor i in range(13):\n print(f\"{deck[i][0]}{deck[i...
[ 1 ]
[ "If you need to shuffle the cards repeatedly, you can use a loop. It may also help if the shuffling is a function.\ndeck_of_cards = [ \"A-C\", \"2-C\" ,\"3-C\" ,\"4-C\" ,... ,\"Q-S\" ,\"K-S\"]\n\ndef shuffle(a_deck):\n do stuff that makes a new deck by shuffling a_deck\n return shuffled_deck\n\nwhile True: ...
[ -1 ]
[ "python", "python_3.x", "python_itertools" ]
stackoverflow_0074254819_python_python_3.x_python_itertools.txt
Q: importing azure automl environement with a registerd model I am trying to use an azure automl generated model in my code, for supplementray test purposes (so I do not want to deploy it for the moment. I use the following code to load the model: import joblib from azureml.core.model import Model from azureml.core i...
importing azure automl environement with a registerd model
I am trying to use an azure automl generated model in my code, for supplementray test purposes (so I do not want to deploy it for the moment. I use the following code to load the model: import joblib from azureml.core.model import Model from azureml.core import Workspace import os import pickle ws = Workspace.from_con...
[ "The version of python which was auto used in the model generation is the major issue here. Check the current working python version of the model in the conda.yml file as mentioned below.\n\nThe model which currently worked was on 3.7.9.\nBut in the notebook, the version will be different.\n\nDeprecate the version ...
[ 0 ]
[]
[]
[ "anaconda", "automl", "azure", "python" ]
stackoverflow_0073978104_anaconda_automl_azure_python.txt
Q: Custom User class, password isn't hashed when creating user from the form I've coded my own AbstractBaseUser and BaseUserManager. Creating users and superusers via terminal works fine. But there is a problem with creating users via form. All user fields are saved properly except password field, which is not hashed...
Custom User class, password isn't hashed when creating user from the form
I've coded my own AbstractBaseUser and BaseUserManager. Creating users and superusers via terminal works fine. But there is a problem with creating users via form. All user fields are saved properly except password field, which is not hashed (while using set_password()). My models.py: from django.db import models from ...
[ "The * is coming from crispy-forms. From the crispy-form docs...\nIf you don’t like the use of * (asterisk) to denote required fields you have two options:\nAsterisks have an asteriskField class set. So you can hide it using CSS rule:\n.asteriskField {\n display: none;\n}\n\nOverride field.html template with a c...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074257110_django_python.txt
Q: pipdeptree json result to csv The json result of pipdeptree has form: [ { "package": { "key": "ansible-base", "package_name": "ansible-base", "installed_version": "2.10.8", "required_version": "==2.10.8" }, "dependencies": [] }, { ...
pipdeptree json result to csv
The json result of pipdeptree has form: [ { "package": { "key": "ansible-base", "package_name": "ansible-base", "installed_version": "2.10.8", "required_version": "==2.10.8" }, "dependencies": [] }, { "package": { "k...
[ "Try:\nimport pandas as pd\n\n\nlst = [\n {\n \"package\": {\n \"key\": \"ansible-base\",\n \"package_name\": \"ansible-base\",\n \"installed_version\": \"2.10.8\",\n \"required_version\": \"==2.10.8\",\n },\n \"dependencies\": [],\n },\n {\n...
[ 1 ]
[]
[]
[ "flatten", "json", "pandas", "python" ]
stackoverflow_0074264281_flatten_json_pandas_python.txt
Q: A string is the same if they have the same length and differ at most by one letter how would this be done? I did it with def, but is there a simpler way to do it without def, lambda, enumerate and whatnot? def is_one_away(first: str, other: str) -> bool: skip_difference = { -1: lambda i: (i, i+1),...
A string is the same if they have the same length and differ at most by one letter
how would this be done? I did it with def, but is there a simpler way to do it without def, lambda, enumerate and whatnot? def is_one_away(first: str, other: str) -> bool: skip_difference = { -1: lambda i: (i, i+1), 1: lambda i: (i+1, i), 0: lambda i: (i+1, i+1), } try: ...
[ "If I understand the problem correctly, the following should work:\ndef is_one_away(first,other):\n return len(first) == len(other) and sum(x != y for x,y in zip(first,other)) <= 1\n\n", "This is a clean versin of code that works.\ndef is_one_away(first: str, other: str) -> bool:\n \n # check lengths\n ...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074264216_python.txt
Q: ImportError: libcudart.so.10.1: cannot open shared object file: No such file or directory I tried below code and getting the ImportError: libcudart.so.10.1: cannot open shared object file: No such file or directory. I am using cuda-10.0 torch-1.4.0 mmdet-1.2.0 import mmcv from mmdet.apis import init_detector, infe...
ImportError: libcudart.so.10.1: cannot open shared object file: No such file or directory
I tried below code and getting the ImportError: libcudart.so.10.1: cannot open shared object file: No such file or directory. I am using cuda-10.0 torch-1.4.0 mmdet-1.2.0 import mmcv from mmdet.apis import init_detector, inference_detector, show_result_pyplot Here I am providing the complete traceback of the error ---...
[ "There is a compatability issue with your Pytorch/CUDA version and the required detectron2 Pytorch/CUDA version.\nFirst figure out what CUDA version you can using\nnvidia-smi\n\n+-----------------------------------------------------------------------------+\n| NVIDIA-SMI 455.45.01 Driver Version: 455.45.01 CU...
[ 1, 0, 0 ]
[ "The solution is:\n$ sudo apt install nvidia-cuda-toolkit\n\nYou can know that by entering the following:\n$ nvcc --version\n\nCommand 'nvcc' not found, but can be installed with:\n\nsudo apt install nvidia-cuda-toolkit\n\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0064683003_python.txt
Q: How to store two space-separated variables as one element in a list to output the element later as integer datatypes I'd like to append two space-separated integer variables to a list as an element, then later output the contents of the list on newlines. For example, storage = a + 3, b + 3 lst.append(storage) Lat...
How to store two space-separated variables as one element in a list to output the element later as integer datatypes
I'd like to append two space-separated integer variables to a list as an element, then later output the contents of the list on newlines. For example, storage = a + 3, b + 3 lst.append(storage) Later, when printing the elements of the list, I get: for i in lst: print(i) >>> (4, 7) >>> (3, 6) >>> (7, 7) Instead, I...
[ "Test each element to see if it's a tuple, and if it is, use the * operator to spread it as multiple args to print().\n>>> lst = [1, (4, 7), (3, 6), -1, (7, 7), 3]\n>>> for i in lst:\n... if isinstance(i, tuple):\n... print(\">>>\", *i)\n... else:\n... print(\">>>\", i)\n...\n>>> 1\n>>> 4 7\...
[ 2 ]
[]
[]
[ "integer", "list", "python" ]
stackoverflow_0074264489_integer_list_python.txt
Q: Python unit testing: temporary directories, multiple tests, and context managers I've written a small module for work and I'm adding some unittesting. The module writes files that need to be read back in for testing purposes and I'm using tempfile.TemporaryDirectory(). I create the temporary directory in the setUp...
Python unit testing: temporary directories, multiple tests, and context managers
I've written a small module for work and I'm adding some unittesting. The module writes files that need to be read back in for testing purposes and I'm using tempfile.TemporaryDirectory(). I create the temporary directory in the setUp() method of my test class and tear it down in the tearDown() method because clearly, ...
[ "Assuming you don't need to recreate the directory for each test case, you can override unittest.TestCase.run() to customize the behavior of the test execution. docs\nFor example:\nimport tempfile, unittest\n\nclass MyTest(unittest.TestCase):\n def run(self, result=None):\n with tempfile.TemporaryDirector...
[ 0 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0074264367_python_unit_testing.txt
Q: How to remove '\n' from end of strings while using txt files and dictionaries? Everything is working properly except the printing of the list, I have tried multiple ways rstrip(), splitline(), replace(), etc. But perhaps I am not using them correctly. I am fairly new to using dictionaries so I would appreciate som...
How to remove '\n' from end of strings while using txt files and dictionaries?
Everything is working properly except the printing of the list, I have tried multiple ways rstrip(), splitline(), replace(), etc. But perhaps I am not using them correctly. I am fairly new to using dictionaries so I would appreciate some guidance for the current problem. txt file (should already be in a list form): Sho...
[ "The proper solution is to use a computer-readable input file format so you don't have to write your own parser.\nHere's a quick refactoring to your code, though.\nfrom collections import Counter\n\ndef get_items():\n print(\"\"\"Items that repeat twice or more in the lists:\n Item Name Repeat Times\n ...
[ 3, 1 ]
[]
[]
[ "dictionary", "python", "string", "text_files" ]
stackoverflow_0074264453_dictionary_python_string_text_files.txt
Q: Python: How to Install OpenCV on Google cloud functions? I'm using Google cloud functions Gen2 and Python 3.10 and the latest version of gcloud cli and opencv-python==4.6.0.66 and functions-framework==3.2.0 I can't deploy on google cloud, because import cv2 is causing this error ImportError: libGL.so.1: cannot ope...
Python: How to Install OpenCV on Google cloud functions?
I'm using Google cloud functions Gen2 and Python 3.10 and the latest version of gcloud cli and opencv-python==4.6.0.66 and functions-framework==3.2.0 I can't deploy on google cloud, because import cv2 is causing this error ImportError: libGL.so.1: cannot open shared object file: No such file or directory at .import_mod...
[ "Sum up of the problem\nFirst error with libgl can be solved by installing opencv-python-headless (which is CPU only, and doesn't require libgl)\npyzbar in the same way requires zbar to be installed.\n(can't be done in cloud functions environment)\n" ]
[ 1 ]
[]
[]
[ "google_cloud_functions", "google_cloud_platform", "opencv", "python", "python_3.x" ]
stackoverflow_0074263810_google_cloud_functions_google_cloud_platform_opencv_python_python_3.x.txt
Q: Numpy Overflow Error when implementing gradient descent algorithm I was trying to learn the gradient descent algorithm purely for fun and I made some code that seems to work event though it get stuck in a local minimum sometimes but sometimes when I run it works and sometimes it gives an overflow error Output when...
Numpy Overflow Error when implementing gradient descent algorithm
I was trying to learn the gradient descent algorithm purely for fun and I made some code that seems to work event though it get stuck in a local minimum sometimes but sometimes when I run it works and sometimes it gives an overflow error Output when failed: [2 4 6 8] E:\Projects\Python\custom_neural_network\testing\tes...
[ "Numpy arrays cannot auto promote like Python built-in types. This is because they are fixed to a Data Type to make operations faster which is a reason NumPy is good. Although like in your case, you lose the flexibility that when a number overshoots it automatically changes its datatype to accommodate your needs.\n...
[ 0 ]
[]
[]
[ "calculus", "gradient_descent", "numpy", "python", "python_3.x" ]
stackoverflow_0074264293_calculus_gradient_descent_numpy_python_python_3.x.txt
Q: Is there a built-in function in Python 3 like getchar() in C++? I want to do user input in python which is similar to getchar() function used in c++. c++ code: #include<bits/stdc++.h> using namespace std; int main() { char ch; while(1){ ch=getchar(); if(ch==' ') break; cout<<ch; } return 0; } Input: ...
Is there a built-in function in Python 3 like getchar() in C++?
I want to do user input in python which is similar to getchar() function used in c++. c++ code: #include<bits/stdc++.h> using namespace std; int main() { char ch; while(1){ ch=getchar(); if(ch==' ') break; cout<<ch; } return 0; } Input: stack overflow Output: stack In the above code, when a space input fr...
[ "Easiest method:\nJust use split function\na = input('').split(\" \")[0]\nprint(a)\n\nUsing STDIN:\nimport sys\nstr = \"\"\nwhile True:\n c = sys.stdin.read(1) # reads one byte at a time, similar to getchar()\n if c == ' ':\n break\n str += c\nprint(str)\n\nUsing readchar:\nInstall using pip install...
[ 14, 3, 2, 0, 0 ]
[]
[]
[ "c++", "getchar", "input", "python" ]
stackoverflow_0048820375_c++_getchar_input_python.txt
Q: Python VS Code Debugger Fails with Embedded Python I am trying to get my application to use VS Code as an external text editor and debugger. The application runs an embedded python thread and launches an instance of VS Code. When trying to attach the VS Code python debugger, it does not work if the embedded python...
Python VS Code Debugger Fails with Embedded Python
I am trying to get my application to use VS Code as an external text editor and debugger. The application runs an embedded python thread and launches an instance of VS Code. When trying to attach the VS Code python debugger, it does not work if the embedded python thread is not running python code. launch.json { "v...
[ "The VS Code Python Debugger was looking for the python threading module. The debugger worked as expected after importing the python threading module with the embedded python.\n" ]
[ 0 ]
[]
[]
[ "python", "visual_studio_code", "vscode_debugger" ]
stackoverflow_0074240471_python_visual_studio_code_vscode_debugger.txt
Q: Cannot import name 'f1' from 'torchmetrics.functional from torchmetrics.functional import f1 I got the following error while trying to import f1 from the torchmetrics module. I installed the torchmetrics module like this: !pip install torchmetrics But the problem persists. A: Maybe this code snippet will be h...
Cannot import name 'f1' from 'torchmetrics.functional
from torchmetrics.functional import f1 I got the following error while trying to import f1 from the torchmetrics module. I installed the torchmetrics module like this: !pip install torchmetrics But the problem persists.
[ "Maybe this code snippet will be helpful\nfrom torchmetrics import F1Score\ntarget = torch.tensor([0, 1, 2, 0, 1, 2])\npreds = torch.tensor([0, 2, 1, 0, 0, 1])\nf1 = F1Score(num_classes=3)\nf1(preds, target)```\n\n" ]
[ 2 ]
[]
[]
[ "metrics", "python" ]
stackoverflow_0074264544_metrics_python.txt
Q: How to explode column with csv string in PySpark? I have a dataframe like this +---+---------------------+ | id| csv| +---+---------------------+ | 1|a,b,c\n1,2,3\n2,3,4\n| | 2|a,b,c\n3,4,5\n4,5,6\n| | 3|a,b,c\n5,6,7\n6,7,8\n| +---+---------------------+ and I want to explode the string type c...
How to explode column with csv string in PySpark?
I have a dataframe like this +---+---------------------+ | id| csv| +---+---------------------+ | 1|a,b,c\n1,2,3\n2,3,4\n| | 2|a,b,c\n3,4,5\n4,5,6\n| | 3|a,b,c\n5,6,7\n6,7,8\n| +---+---------------------+ and I want to explode the string type csv column, in fact I'm only interested in this column. ...
[ "Using split + from_csv functions along with transform you can do something like:\nfrom pyspark.sql import functions as F\n\n\ndf = spark.createDataFrame([\n (1, r\"a,b,c\\n1,2,3\\n2,3,4\\n\"), (2, r\"a,b,c\\n3,4,5\\n4,5,6\\n\"),\n (3, r\"a,b,c\\n5,6,7\\n6,7,8\\n\")], [\"id\", \"csv\"]\n)\n\ndf1 = df.withColu...
[ 3 ]
[]
[]
[ "apache_spark", "apache_spark_sql", "csv", "pyspark", "python" ]
stackoverflow_0074264562_apache_spark_apache_spark_sql_csv_pyspark_python.txt
Q: Visualizing Market Closing Values in Python Using MatPlotLib and YahooFinance #imports import pandas as pd import yfinance as yf from datetime import date, timedelta from matplotlib import pyplot as plt import numpy as np plt.style.use('fivethirtyeight') #Get Albemarle Information ALBINFO = yf.Ticker("ALB") # V...
Visualizing Market Closing Values in Python Using MatPlotLib and YahooFinance
#imports import pandas as pd import yfinance as yf from datetime import date, timedelta from matplotlib import pyplot as plt import numpy as np plt.style.use('fivethirtyeight') #Get Albemarle Information ALBINFO = yf.Ticker("ALB") # Valid options are 1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, # 5y, 10y and ytd. print(ALBINFO.hi...
[ "You need to store a dataframe(object) in order to use it. In this case, ALBINFO is overwritten:\nimport pandas as pd\nimport yfinance as yf\nfrom datetime import date, timedelta\nfrom matplotlib import pyplot as plt\nimport numpy as np\nplt.style.use('fivethirtyeight')\n\n#Get Albemarle Information\nALBINFO = yf.T...
[ 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074250128_matplotlib_python.txt
Q: Expose/export class instead of module from python file I'm exploring Python and how to structure code. Consider the following project structure <project root>/controllers/user_controller.py This file then contains class UserController: def index(): # Something When importing this from outside, it ends up a...
Expose/export class instead of module from python file
I'm exploring Python and how to structure code. Consider the following project structure <project root>/controllers/user_controller.py This file then contains class UserController: def index(): # Something When importing this from outside, it ends up as import controllers.user_controller controller_instance = ...
[ "One way to do this is just just import the modules into the parent module. In other words imagine you have a directory structure like this:\nmycoolmodule/\nmycoolmodule/__init__.py\nmycoolmodule/coolclass.py\nmycoolmodule/coolutil.py\n\nCode for coolclass.py:\nclass CoolClass:\n ...\n\nCode for coolutil.py:\nc...
[ 36, 1 ]
[]
[]
[ "python" ]
stackoverflow_0049694063_python.txt
Q: Pourquoi mon bot ne veut il pas effacer les messages I wanted to make my bot respond to a command by deleting messages but an error appears: File "C:\Users\Mathis\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 409, in _run_event await coro(*args, **kwargs) File "c:\Users\...
Pourquoi mon bot ne veut il pas effacer les messages
I wanted to make my bot respond to a command by deleting messages but an error appears: File "C:\Users\Mathis\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 409, in _run_event await coro(*args, **kwargs) File "c:\Users\Mathis\Desktop\dev-prog\infinity\lize\boot lize.py", line ...
[ "You need to check that message.content contains at least 2 words before trying to use [1].\n@bot.event\nasync def on_message(message):\n if message.content.startswith(\"!del\"):\n words = message.content.split()\n if len(words) > 1:\n number = int(words[1])\n messages = await...
[ 0 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0074264347_discord.py_python.txt
Q: URSINA No module named 'direct' (sorry for my English), i'm trying to use ursina on visual studio but when i run my code the IDE show a file: texture.py and and in particular the error: no module named 'direct' I try to install direct but there are other error and i don't understand why for me this module is neces...
URSINA No module named 'direct'
(sorry for my English), i'm trying to use ursina on visual studio but when i run my code the IDE show a file: texture.py and and in particular the error: no module named 'direct' I try to install direct but there are other error and i don't understand why for me this module is necessary and in internet i don't found of...
[ "direct is part of panda3d, which is a dependency of ursina. I suggest making sure it installed correctly. Maybe try reinstalling.\n", "It seems panda3d is not correctly installed. Direct is part of panda3d and ursina is made over panda3d, so if direct is not correctly installed, then ursina will not run.\nI reco...
[ 1, 0, 0 ]
[]
[]
[ "python", "ursina" ]
stackoverflow_0074181799_python_ursina.txt
Q: Finding elements by class name inside a loop, selenium I need to scrape in python a page that has some classes that are number like class1, class2, class3, ... classN and I would like to locate the text contained in all those classes. I tried using find_element() function: list = [] for i in range(N-1) list.app...
Finding elements by class name inside a loop, selenium
I need to scrape in python a page that has some classes that are number like class1, class2, class3, ... classN and I would like to locate the text contained in all those classes. I tried using find_element() function: list = [] for i in range(N-1) list.append(driver.find_element(By.CLASS_NAME, "class" + str(i+1) )....
[ "Class_name only accept single class name not multiple.\nInstead use css selector. use python format() function\nlist = []\nfor i in range(N-1):\n list.append(driver.find_element(By.CSS_SELECTOR, \"[class='smh__part smh__home smh__part--{}']\".format(i+1)).text)\n\n\nOR CLASS_NAME with single class value\nlist = ...
[ 2 ]
[]
[]
[ "css_selectors", "python", "selenium", "web_scraping", "webdriver" ]
stackoverflow_0074264511_css_selectors_python_selenium_web_scraping_webdriver.txt
Q: Insert dates starting from 00:00:00 and ending 23:59:59 in pandas I have a following code that groups value from 07:10:00 to 17:30:00. import pandas as pd dict = {"datetime" : ["2022-10-26 07:12:13", "2022-10-26 09:14:43", "2022-10-26 17:25:19"], "value" : [1, 3, 5]} df = pd.DataFrame(dict) df["time"] = pd.to_dat...
Insert dates starting from 00:00:00 and ending 23:59:59 in pandas
I have a following code that groups value from 07:10:00 to 17:30:00. import pandas as pd dict = {"datetime" : ["2022-10-26 07:12:13", "2022-10-26 09:14:43", "2022-10-26 17:25:19"], "value" : [1, 3, 5]} df = pd.DataFrame(dict) df["time"] = pd.to_datetime(df["datetime"]) df = ( df.groupby([pd.Grouper(freq=...
[ "Simple way to achieve:\n\nFirst get the max, min times to find the actual start_time and end_time (you asked for day start time / end time)\nCreate master dataframe with the required time limit and then merge with the actual dataframe.\n\nIncluding changes\nimport pandas as pd\n\n\ndict = {\"datetime\" : [\"2022-1...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074264627_dataframe_pandas_python.txt
Q: BigQuery Dataflow LoadJob get failed rows and skip error throwing when any record failed How to correct handle saving pubsub messages with LoadJob in Dataform? try: job_config = bigquery.LoadJobConfig( source_format=bigquery.SourceFormat.NEWLINE_DELIMITED_JSON, schema_update_options=[ bigquery.SchemaU...
BigQuery Dataflow LoadJob get failed rows and skip error throwing when any record failed
How to correct handle saving pubsub messages with LoadJob in Dataform? try: job_config = bigquery.LoadJobConfig( source_format=bigquery.SourceFormat.NEWLINE_DELIMITED_JSON, schema_update_options=[ bigquery.SchemaUpdateOption.ALLOW_FIELD_ADDITION, bigquery.SchemaUpdateOption.ALLOW_FIELD_RELAXATION ]...
[ "If you use streaming inserts, the BigQuery insertAll API does return failing rows (see response body docs) although I'm not sure what interacting with that looks like from the beam python API.\nYour example here, though, is using file loads and it's expected behavior that a LoadJob will fail if any record is inval...
[ 0 ]
[]
[]
[ "google_bigquery", "google_cloud_dataflow", "python" ]
stackoverflow_0074249094_google_bigquery_google_cloud_dataflow_python.txt
Q: Avoid redundancy in argparse defaults import argparse class A: def __init__(self,val=1): self.val = val if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--val', default=1) args = parser.parse_args() a = A(val=args.val) Quite often I find myself with...
Avoid redundancy in argparse defaults
import argparse class A: def __init__(self,val=1): self.val = val if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--val', default=1) args = parser.parse_args() a = A(val=args.val) Quite often I find myself with a structure as shown above, where a class ...
[ "import argparse\nimport inspect\n\ndef get_default_args(func):\n signature = inspect.signature(func)\n return {\n k: v.default\n for k, v in signature.parameters.items()\n if v.default is not inspect.Parameter.empty\n }\n\nclass A:\n def __init__(self,val=1):\n self.val = va...
[ 0 ]
[]
[]
[ "argparse", "python" ]
stackoverflow_0074264644_argparse_python.txt
Q: Setting up Conda and Python for Stable Diffusion I'm interested in AI generated art and want to setup Stable Diffusion (server?) to emulate some scenes in some works of fiction I've worked on over the years (e.g. "self-made" concept art). However even as a developer I'm completely lost on the provided instructions...
Setting up Conda and Python for Stable Diffusion
I'm interested in AI generated art and want to setup Stable Diffusion (server?) to emulate some scenes in some works of fiction I've worked on over the years (e.g. "self-made" concept art). However even as a developer I'm completely lost on the provided instructions as I'm not familiar with any of the prerequisites inv...
[ "The reason your commands aren't working is that you need to git clone the repository first:\ngit clone https://github.com/CompVis/stable-diffusion.git\n\nWhich will drop a stable-diffusion folder where you ran the command. Once you cd into that directory, you should see an environment.yaml file that you can use fo...
[ 0 ]
[]
[]
[ "artificial_intelligence", "conda", "python", "stable_diffusion" ]
stackoverflow_0074242469_artificial_intelligence_conda_python_stable_diffusion.txt
Q: Python Logging with timezone in I have a Python app running on a server that is not in the the local timezone. Everything works fine but when it runs on the server it's providing the log timestamp with a different timezone. Ideally I would want it to show in local time which should be GMT. What I initially had is:...
Python Logging with timezone in
I have a Python app running on a server that is not in the the local timezone. Everything works fine but when it runs on the server it's providing the log timestamp with a different timezone. Ideally I would want it to show in local time which should be GMT. What I initially had is: logging.basicConfig( handlers=[Rotat...
[ "Maybe you could benefit of the time-zone in the date/time format\n'%d/%m/%Y %H:%M:%S%z'\n\nThis will output\n... 15:41:10+0100 INFO ....\n\n" ]
[ 1 ]
[]
[]
[ "python", "python_logging" ]
stackoverflow_0074263086_python_python_logging.txt
Q: Selenium-ChromeDriver SSL error/handshake failed My script is throwing a ton of SSL errors as below: [19852:2032:0912/202419:ERROR:ssl_client_socket_impl.cc(1141)] handshake failed; returned -1, SSL error code 1, net_error -100 [19852:2032:0912/202419:ERROR:ssl_client_socket_impl.cc(1141)] handshake failed; ret...
Selenium-ChromeDriver SSL error/handshake failed
My script is throwing a ton of SSL errors as below: [19852:2032:0912/202419:ERROR:ssl_client_socket_impl.cc(1141)] handshake failed; returned -1, SSL error code 1, net_error -100 [19852:2032:0912/202419:ERROR:ssl_client_socket_impl.cc(1141)] handshake failed; returned -1, SSL error code 1, net_error -100 Everything...
[ "You can try using the TrustManager packages, here's a sample\n SSLContext sslContext;\n TrustManager[] tmTrustAllCerts = new TrustManager[]{\n new X509TrustManager() {\n public java.security.cert.X509Certificate[] getAcceptedIssuers()\n {\n return n...
[ 0, 0 ]
[ "This is due to the unsafe address error. You can ignore this by adding parameters of \"--ignore-certificate-errors\".\nTake the case in robot framework-selenium as example:\nOpen Browser http://127.0.0.1/8000 Chrome executable_path=C:/path/to/chromedrive options=add_argument(\"--ignore-certific...
[ -1 ]
[ "python", "selenium", "selenium_chromedriver", "ssl" ]
stackoverflow_0039457645_python_selenium_selenium_chromedriver_ssl.txt
Q: Unexpected output with Lock.acquire() and Lock.release() from threading import Thread import threading import time def procesa1(): lock = threading.Lock() lock.acquire() for i in range(3): print(threading.get_ident()) lock.release() if __name__ == "__main__": hilos = [] for i in ...
Unexpected output with Lock.acquire() and Lock.release()
from threading import Thread import threading import time def procesa1(): lock = threading.Lock() lock.acquire() for i in range(3): print(threading.get_ident()) lock.release() if __name__ == "__main__": hilos = [] for i in range(5): hilos.append(Thread(target=procesa1)) ...
[ "The lock doesn't help to synchronize threads because each thread is creating its own lock. You need to create a single lock and pass it as an argument to each thread, so they can share it.\nThis works as expected (I simplified the syntax using with):\ndef procesa1(lock):\n with lock:\n for i in range(3):...
[ 3 ]
[]
[]
[ "concurrency", "locking", "multithreading", "python", "race_condition" ]
stackoverflow_0074264521_concurrency_locking_multithreading_python_race_condition.txt
Q: QuickSort depending on number of elements in array I've done already a quicksort using the median of three element. Now I want to do a task where if the number of ele in array is lower than 1000 it uses my median of three otherwise the pivot is chosen to be the median of 21 equally spaced elements within of the co...
QuickSort depending on number of elements in array
I've done already a quicksort using the median of three element. Now I want to do a task where if the number of ele in array is lower than 1000 it uses my median of three otherwise the pivot is chosen to be the median of 21 equally spaced elements within of the considered subset Here is the median of three: def quickSo...
[ "Example code for median of 3 medians of 3. Med3 of 3 sorts a[lo], a[md], a[hi].\nMed9(a, lo, hi)\n{\n md = lo + (hi - lo) / 2\n d = (hi - lo + 1) / 8;\n Med3(a, lo, lo + d, lo + 2 * d);\n Med3(a, md - d, md, md + d);\n Med3(a, hi - 2 * d, hi - d, hi);\n Med3(a, lo + d, md, hi - d);\n return a[...
[ 0 ]
[]
[]
[ "arrays", "python", "quicksort" ]
stackoverflow_0074256166_arrays_python_quicksort.txt
Q: JavaScript is not available. (Python) I am trying to scrape data from a Twitter webpage using Python but instead of getting the data back, I keep getting "Javascript is not available". I've enabled Javascript in my browser(chrome) but nothing changes. Here is the error --> <h1>JavaScript is not available.</h1> <p>...
JavaScript is not available. (Python)
I am trying to scrape data from a Twitter webpage using Python but instead of getting the data back, I keep getting "Javascript is not available". I've enabled Javascript in my browser(chrome) but nothing changes. Here is the error --> <h1>JavaScript is not available.</h1> <p>We’ve detected that JavaScript is disabled ...
[ "I will never advise scraping twitter by violating their policies, you should use an API instead! But for the Javascript part, just pass user agent in headers in your requests.\nfrom bs4 import BeautifulSoup\nimport requests\n\nuser_agent = 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like G...
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "python_requests" ]
stackoverflow_0074263895_beautifulsoup_python_python_requests.txt
Q: Can't show image with opencv when importing av When importing the PyAv module, I am unable to show an image with opencv using imshow() Code without the PyAv module (works as expected) import cv2 img = cv2.imread("test_image.jpeg") cv2.imshow('image', img) cv2.waitKey(0) Code with the import (doesn't work, just h...
Can't show image with opencv when importing av
When importing the PyAv module, I am unable to show an image with opencv using imshow() Code without the PyAv module (works as expected) import cv2 img = cv2.imread("test_image.jpeg") cv2.imshow('image', img) cv2.waitKey(0) Code with the import (doesn't work, just hangs) import cv2 import av img = cv2.imread("test_i...
[ "So it is a known issue, mentioned here, but it is possible to use the workaround mentioned in the post, here is a quick rundown of how I did it:\nNOTE: Do this in a python virtualenv or you might run into problems in the long run\n\nFind which version of ffmpeg PyAv uses (currently it's 'ffmpeg-4.4.1-5') and downl...
[ 3, 1 ]
[]
[]
[ "ffmpeg", "opencv", "pyav", "python" ]
stackoverflow_0072604912_ffmpeg_opencv_pyav_python.txt
Q: Enlarge font of title on a pie chart Python I would like to enlarge this and edit the color of this please - plt.title("Groups %") unable to enlarge this without receiving errors
Enlarge font of title on a pie chart Python
I would like to enlarge this and edit the color of this please - plt.title("Groups %") unable to enlarge this without receiving errors
[]
[]
[ "Here is a simple example to show how one can do the followings for a pie chart:\n\nto change the figure size\nto change the font size of labels\nto change the font size of title\n\ncode:\nimport matplotlib.pyplot as plt\n\n# data\ncats = ['a', 'b', 'c']\nvals = [0.35, 0.45, 0.20]\n\nfig = plt.figure(figsize=(6,6))...
[ -1 ]
[ "font_size", "matplotlib", "pie_chart", "python", "title" ]
stackoverflow_0074264811_font_size_matplotlib_pie_chart_python_title.txt
Q: splitting a string into a list in an alternate way so I have a string as shown below seqs = """>UDW38231.1 |surface glycoprotein|MS|GenBank|ssRNA(+) MFVFLVLLPLVSSQCVNLRTRTQLPPAYTNSFTRGVYYPDKVFRSSVLHSTQDLFLPFFS NVTWFHAIHVSGTNGTKRFDNPVLPFNDGVYFASIEKSNIIRGWIFGTTLDSKTQSLIIV NNATNVVIKVCEFQFCNDPFLDVYYHKNNKSWMESGVYSSANNC...
splitting a string into a list in an alternate way
so I have a string as shown below seqs = """>UDW38231.1 |surface glycoprotein|MS|GenBank|ssRNA(+) MFVFLVLLPLVSSQCVNLRTRTQLPPAYTNSFTRGVYYPDKVFRSSVLHSTQDLFLPFFS NVTWFHAIHVSGTNGTKRFDNPVLPFNDGVYFASIEKSNIIRGWIFGTTLDSKTQSLIIV NNATNVVIKVCEFQFCNDPFLDVYYHKNNKSWMESGVYSSANNCTFEYVSQPFLMDLEGK QGNFKNLREFVFKNIDGYFKIYSKHTPINLVRDLPQGFS...
[ "FWIW, I think your existing solution is fine (and it's probably faster than what I'm about to suggest), but if you want something that involves append rather than split and replace you could do:\n>>> seq_list = []\n>>> for c in seqs:\n... if c == \">\":\n... seq_list.append(\"\")\n... elif c != \"\...
[ 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074264817_list_python.txt
Q: Pass tuple parameters to smart contracts using web3.py I am using web3.py to pass a tuple type parameter to the contract smart, {'considerationToken': '0x0000000000000000000000000000000000000000', 'considerationIdentifier': 0, 'considerationAmount': 1950000000000000, 'offerer': '0xf6d4434b802877d7f17c3383ce0dee...
Pass tuple parameters to smart contracts using web3.py
I am using web3.py to pass a tuple type parameter to the contract smart, {'considerationToken': '0x0000000000000000000000000000000000000000', 'considerationIdentifier': 0, 'considerationAmount': 1950000000000000, 'offerer': '0xf6d4434b802877d7f17c3383ce0deeef85b3a1eb', 'zone': '0x000000000000000000000000000000000000...
[ "The error said you are trying to use Dict instead of Tuple.\nDid you try it like this?\nmyContract.functions.fulfillBasicOrder(\n \"0x0000000000000000000000000000000000000000\",\n 0,\n 1950000000000000,\n \"0xf6d4434b802877d7f17c3383ce0deeef85b3a1eb\",\n \"0x0000000000000000000000000000000000000000\...
[ 0 ]
[]
[]
[ "python", "web3py" ]
stackoverflow_0073986205_python_web3py.txt
Q: Pandas resample interpolate behavior is odd When asking pandas to resample this dataframe using interpolate it fails to do so properly simply propagating the first value forwards. Can someone explain this behavior? Using a recent version of pandas and using python 3.8 import pandas as pd data = {'time': pd.to_time...
Pandas resample interpolate behavior is odd
When asking pandas to resample this dataframe using interpolate it fails to do so properly simply propagating the first value forwards. Can someone explain this behavior? Using a recent version of pandas and using python 3.8 import pandas as pd data = {'time': pd.to_timedelta([0., 1.1, 2.2, 3.3, 4.4], unit='s'), 'data'...
[ "You need to first resample to a smaller unit and interpolate to get intermediate values. Then resample to seconds to get the data with equidistant timesteps.\ndf1.resample('ms').interpolate().resample('s').asfreq()\n\n data\ntime \n0 days 00:00:00 100.000000\n0 days 00:...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074264300_pandas_python.txt
Q: Sorting for the max on several columns I have a data frame and I need to sort it samples by several columns. For example, having the below data frame, it needs to sort by the maximum price and maximum horse-power for each different company. company price horse-power toyota 20000 100 toyota ...
Sorting for the max on several columns
I have a data frame and I need to sort it samples by several columns. For example, having the below data frame, it needs to sort by the maximum price and maximum horse-power for each different company. company price horse-power toyota 20000 100 toyota 20000 125 bmw 40000 150 ...
[ "groupby with a max\ndf.groupby('company',as_index=False).max()\n\ncompany price horse-power\n0 audi 35000 180\n1 bmw 45000 200\n2 toyota 25000 125\n3 volkswagen 33000 130\n\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "python", "sorting" ]
stackoverflow_0074264964_dataframe_python_sorting.txt
Q: Extract data field from a byte data type (data is obtained using paramiko on python) Reading nvram remotely from a Mac using SSH on paramiko package (python3), my readback data stdout.read() seems to have bytes as its data type. data_readback= stdout.read() print(type(data_readback)) #print data type of read back...
Extract data field from a byte data type (data is obtained using paramiko on python)
Reading nvram remotely from a Mac using SSH on paramiko package (python3), my readback data stdout.read() seems to have bytes as its data type. data_readback= stdout.read() print(type(data_readback)) #print data type of read back data print(data_readback[0:60]) #printing first 60 characters of read back data **Result...
[ "Does this work for you?\ndata_as_bytes = b'boot-args\\tdebug=0x104c0c\\nnauto-boot\\ttrue\\nboot-volume\\tEF57347C'\n\ndata_as_string = str(data_as_bytes, \"ascii\")\n\noutput = data_as_string.split()\nentries = dict([(x, y) for x, y in zip(output[::2], output[1::2])])\nprint(entries['boot-args']) # debug=0x104c0...
[ 2 ]
[]
[]
[ "byte", "paramiko", "python", "string" ]
stackoverflow_0074198301_byte_paramiko_python_string.txt
Q: How to use pandas read csv I have a dataframe where all the column names are dates. When I use .read_csv(), pandas reads these column names as strings. Is there a way to specify that I want the column names to be datetime objects. Ideally I need this to be done as part of the .read_csv() call, rather than an addit...
How to use pandas read csv
I have a dataframe where all the column names are dates. When I use .read_csv(), pandas reads these column names as strings. Is there a way to specify that I want the column names to be datetime objects. Ideally I need this to be done as part of the .read_csv() call, rather than an additional line afterwards. For examp...
[ "either you define the whole column as a datetime or as an integer... there is no way you can define the header as a datetime and the values as a different thing.\nOn the other hand you cannot define your columns as datetime, because the values are just integers... I think you are approaching your problem in a wron...
[ 0, -1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074262632_pandas_python.txt
Q: How to calculate corect way the entropy on image? When I want to calculate the entropy on an image I got only blank white image. How can I do it in the correct way? def entropy_of_image(image): image_gray = rgb2gray(image) f_size = 20 radi = list(range(1,10)) entropy_tmp = entropy(image_gray, disk(...
How to calculate corect way the entropy on image?
When I want to calculate the entropy on an image I got only blank white image. How can I do it in the correct way? def entropy_of_image(image): image_gray = rgb2gray(image) f_size = 20 radi = list(range(1,10)) entropy_tmp = entropy(image_gray, disk(radi[8])) plt.savefig('images/tmpentropy.jpg') ...
[ "When you write plt.savefig('images/tmpentropy.jpg'), what do you think pyplot will write to that JPEG file? You didn't give pyplot any array to write. savefig writes the current figure window to file. Because you didn't create a figure window, or write anything to that figure window, there is nothing to save to th...
[ 0 ]
[]
[]
[ "image_processing", "python", "scikit_image" ]
stackoverflow_0074250097_image_processing_python_scikit_image.txt
Q: How to convert 2022-10-27T00:00:00.000+00:00 into a standard date in YYYY-MM-DD format Can someone please explain how to convert this 2022-10-27T00:00:00.000+00:00 date string value into the YYYY-MM-DD format in python output should look like this : 2022-10-27 can anyone please help me here A: If it is a string ...
How to convert 2022-10-27T00:00:00.000+00:00 into a standard date in YYYY-MM-DD format
Can someone please explain how to convert this 2022-10-27T00:00:00.000+00:00 date string value into the YYYY-MM-DD format in python output should look like this : 2022-10-27 can anyone please help me here
[ "If it is a string just use\nvariableHoldingString[0:10]\n\nRef: https://thispointer.com/python-how-to-get-first-n-characters-in-a-string/#:~:text=To%20get%20the%20first%20N,and%20end_index_pos%20as%20N%20i.e.&text=The%20value%20of%20step_size%20will,characters%20of%20the%20given%20string.\n", "It appears that yo...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074265179_python.txt
Q: Django admin database error on Bluehost shared hosting Using django with sqlite3 on bluehost shared hosting. If I try to view any of my models (Users, for example) via the admin panel I get an error, but if I manually enter the url to any specific object, there is no problem. So, www.domain.com/admin/auth/user/ t...
Django admin database error on Bluehost shared hosting
Using django with sqlite3 on bluehost shared hosting. If I try to view any of my models (Users, for example) via the admin panel I get an error, but if I manually enter the url to any specific object, there is no problem. So, www.domain.com/admin/auth/user/ throws this error: Database error. Something's wrong with y...
[ "Database error\nSomething’s wrong with your database installation. Make sure the appropriate database tables have been created, and make sure the database is readable by the appropriate user.\n" ]
[ 0 ]
[]
[]
[ "django", "django_admin", "python", "shared_hosting" ]
stackoverflow_0036320705_django_django_admin_python_shared_hosting.txt
Q: how to convert multiple html files to excel xlsx files import pandas as pd a = "/Users/abhijitchavan/Desktop/yes/SearchResult1.xls" tables = pd.read_html(a) table = tables[0] print(table) table.to_excel('/Users/abhijitchavan/Desktop/yes/dd.xlsx') THE ABOVE CODE WORKES PERFECT, BUT IT CONVERTS ONLY ONE FILE AT ...
how to convert multiple html files to excel xlsx files
import pandas as pd a = "/Users/abhijitchavan/Desktop/yes/SearchResult1.xls" tables = pd.read_html(a) table = tables[0] print(table) table.to_excel('/Users/abhijitchavan/Desktop/yes/dd.xlsx') THE ABOVE CODE WORKES PERFECT, BUT IT CONVERTS ONLY ONE FILE AT A TIME, HOW CAN I INPUT MULTIPLE FILES AND CONVERT THEM AT S...
[ "import pandas as pd\nfiles = [\"/Users/abhijitchavan/Desktop/yes/SearchResult1.xls\",\"/Users/abhijitchavan/Desktop/yes/SearchResult2.xls\"]\nfor i in range(0,len(files)):\n a=files[i]\n tables = pd.read_html(a)\n table = tables[0]\n print(table)\n table.to_excel('/Users/abhijitchavan/Desktop/yes/dd...
[ 0 ]
[]
[]
[ "excel", "html", "pandas", "python" ]
stackoverflow_0074258697_excel_html_pandas_python.txt
Q: Sum only for repeated values in two another columns I have the following dataframe: col1 col2 col3 0 prog1 id001 1 1 prog2 id001 0 2 prog2 id001 1 3 prog1 id002 0 4 prog3 id002 0 5 prog4 id002 1 6 prog2 id003 0 7 prog5 ...
Sum only for repeated values in two another columns
I have the following dataframe: col1 col2 col3 0 prog1 id001 1 1 prog2 id001 0 2 prog2 id001 1 3 prog1 id002 0 4 prog3 id002 0 5 prog4 id002 1 6 prog2 id003 0 7 prog5 id003 1 8 prog5 id003 1 9 prog3 i...
[ "You can use .transform to generate the pd.Series directly.\nGroup on \"col1\" and sum the values in \"col3\".\ndf[\"sum_prog\"] = df.groupby([\"col1\"]).col3.transform(\"sum\")\n\nOut\n col1 col2 col3 sum_prog\n0 prog1 id001 1 1\n1 prog2 id001 0 1\n2 prog2 id001 1 1...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074265276_dataframe_pandas_python.txt
Q: How to set a custom day of week mapping I am trying to create my own custom day of the week mapping using python. I have used a few different methods such as dayofweek and isoweekday. Yet all of these dont provide me with what I need. 0 2026-01-01 00:00:00 1 2026-01-01 01:00:00 2 2026-01-01 02:00:00 3 ...
How to set a custom day of week mapping
I am trying to create my own custom day of the week mapping using python. I have used a few different methods such as dayofweek and isoweekday. Yet all of these dont provide me with what I need. 0 2026-01-01 00:00:00 1 2026-01-01 01:00:00 2 2026-01-01 02:00:00 3 2026-01-01 03:00:00 4 2026-01-01 04:00:00...
[ "As per pandas documentation for weekday, it mentions that:\n\nThe day of the week with Monday=0, Sunday=6.\n\nWhich means, you just need to add 2 to the weekday value as you want to shift Monday from 0 to 2, then take modulo by 8\n# df is your dataframe, and date is the column name consisting pandas Timestamp\n>>>...
[ 1 ]
[]
[]
[ "date", "datetime", "pandas", "python" ]
stackoverflow_0074265262_date_datetime_pandas_python.txt
Q: python replit database throwing typeError I was trying to make functions to save, get, and get all for the Replit Python database. It doesn't work and I can't find out why. Get all function: def loadAll(user): if user in db.keys(): return db[user] if user not in db.keys(): db[user] = {} ...
python replit database throwing typeError
I was trying to make functions to save, get, and get all for the Replit Python database. It doesn't work and I can't find out why. Get all function: def loadAll(user): if user in db.keys(): return db[user] if user not in db.keys(): db[user] = {} return db[user] It throws an error at ret...
[ "I solved it by changing the database key to not just be the user.\n", "Replit Database doesn't support integers as keys. Stringify the key beforehand.\n" ]
[ 0, 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0069730646_discord_discord.py_python.txt
Q: How to make convert return string in xlsx2csv? https://github.com/dilshod/xlsx2csv This project has only one file, which looks easy to understand, but I don't know how to modify it so that it outputs the result string instead of directly inputting it into the file. I want it not to output to a file, but to return ...
How to make convert return string in xlsx2csv?
https://github.com/dilshod/xlsx2csv This project has only one file, which looks easy to understand, but I don't know how to modify it so that it outputs the result string instead of directly inputting it into the file. I want it not to output to a file, but to return a string. But I can't understand the code. How shoul...
[ "\noutput = io.StringIO()\nXlsx2csv(r\"C:\\Users\\Gaoyongxian\\PycharmProjects\\Y_searcher\\demo.xlsx\", outputencoding=\"utf-8\").convert(output,0)\nwith open(\"demo.txt\",\"w\",encoding=\"utf8\") as f:\n print(output.getvalue())\n f.write(output.getvalue())\n\n\n" ]
[ 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0074236562_csv_python.txt
Q: AIOHTTP: Client example I have just installed AIOHTTP on my mac Python 3.10.8 Visual Studio Code Version: 1.72.2 Package Version ------------------ ------- aiodns 3.0.0 aiohttp 3.8.3 aiosignal 1.2.0 async-timeout 4.0.2 attrs 22.1.0 cffi 1.1...
AIOHTTP: Client example
I have just installed AIOHTTP on my mac Python 3.10.8 Visual Studio Code Version: 1.72.2 Package Version ------------------ ------- aiodns 3.0.0 aiohttp 3.8.3 aiosignal 1.2.0 async-timeout 4.0.2 attrs 22.1.0 cffi 1.15.1 charset-normalizer 2.1.1 ...
[ "As per this,\nsession = aiohhtp.ClientSession(connector=aiohttp.TCPConnector(verify_ssl=False))\n\nThis is something similar to verify=False in requests library.\n", "I found the answer. The Getting Started Client example does not work with 3.10....\nSwitch between 3.9 and 3.10 is easy way to reproduce the error...
[ 0, 0 ]
[]
[]
[ "aiohttp", "python" ]
stackoverflow_0074261872_aiohttp_python.txt
Q: python data class default value for str to None I have a dataclass like this: from dataclasses import dataclass @dataclass class DataClassCard: rank: str = None suit: str I am getting an error saying: TypeError: non-default argument 'suit' follows default argument Is there anyway to set this default va...
python data class default value for str to None
I have a dataclass like this: from dataclasses import dataclass @dataclass class DataClassCard: rank: str = None suit: str I am getting an error saying: TypeError: non-default argument 'suit' follows default argument Is there anyway to set this default value? Finally calling: queen_of_hearts = DataClassCard...
[ "Fields with a default value must come after any fields without a default. Just put suit above\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x", "python_dataclasses" ]
stackoverflow_0074265345_python_python_3.x_python_dataclasses.txt
Q: Unexpected output (Python exercise) My code is not printing the correct result for the test case `2 6 1 alex 1 Alex 2 sam 1 alix 1 Alix 2 caM ` as it should result in "alex, sam", yet it results in "alex, Alex" (After reading the following instructions youll understand why). Was hoping I can get some insight as t...
Unexpected output (Python exercise)
My code is not printing the correct result for the test case `2 6 1 alex 1 Alex 2 sam 1 alix 1 Alix 2 caM ` as it should result in "alex, sam", yet it results in "alex, Alex" (After reading the following instructions youll understand why). Was hoping I can get some insight as to what is wrong with my code. Exercise: ...
[ "You have to convert the name to lower or upper case.\nBecause to python alex and Alex are different things. You can convert a string to lowercase using the string method lower().\nLike this :\nstudent_name = selection[1].lower()\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074265346_python.txt
Q: Adding a random number of characters to message to encrypt input Beginner question Hi, I'm struggling to figure out a way to encrypt this message. Ideally my program should work like this: 1. Ask for input of a word/message to encrypt. This could include letters and spaces. 2. Generate a number between 2 and 20 ...
Adding a random number of characters to message to encrypt input
Beginner question Hi, I'm struggling to figure out a way to encrypt this message. Ideally my program should work like this: 1. Ask for input of a word/message to encrypt. This could include letters and spaces. 2. Generate a number between 2 and 20 (i'll call it x for now) 3. Then randomly select characters of length...
[ "The main problem with your code is that you are not accumulating the random characters into a string or list. Instead, you are continually overwriting the random choice so that only the choice in the last pass through the loop is retained. The easiest fix is to eliminate the loop completely and use random.choices ...
[ 3, 1 ]
[]
[]
[ "encryption", "python" ]
stackoverflow_0074264638_encryption_python.txt
Q: Python scrape with selenium element not found I am trying to get a timestamp from a website but element can't be located. The b-gray-800 is a child from stories-list details = driver.find_element("xpath","//div[@id='stories-list']") res = details.find_elements("xpath","./div[@class = 'b-gray-800']") for items in r...
Python scrape with selenium element not found
I am trying to get a timestamp from a website but element can't be located. The b-gray-800 is a child from stories-list details = driver.find_element("xpath","//div[@id='stories-list']") res = details.find_elements("xpath","./div[@class = 'b-gray-800']") for items in res: print(items.get_attribute('data-story-times...
[ "If you are using xpath to locate an element, you dont have to transverse to that element, you can directly access that element no matter how deep it is.\nAlso, you are using deprecated methods in selenium.\nFor your case, I recommend using IDs and Classes to reach your goal:\ndetails = driver.find_element(By.ID,\"...
[ 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074262949_python_selenium.txt
Q: py4j.protocol.Py4JError: org.apache.spark.api.python.PythonUtils.getEncryptionEnabled does not exist in the JVM I am currently on JRE: 1.8.0_181, Python: 3.6.4, spark: 2.3.2 I am trying to execute following code in Python: from pyspark.sql import SparkSession spark = SparkSession.builder.appName('Basics').getOrCr...
py4j.protocol.Py4JError: org.apache.spark.api.python.PythonUtils.getEncryptionEnabled does not exist in the JVM
I am currently on JRE: 1.8.0_181, Python: 3.6.4, spark: 2.3.2 I am trying to execute following code in Python: from pyspark.sql import SparkSession spark = SparkSession.builder.appName('Basics').getOrCreate() This fails with following error: spark = SparkSession.builder.appName('Basics').getOrCreate() Traceback (m...
[ "Using findspark is expected to solve the problem:\nInstall findspark\n$pip install findspark\nIn you code use:\nimport findspark\nfindspark.init() \n\nOptionally you can specify \"/path/to/spark\" in the init method above; findspark.init(\"/path/to/spark\")\n", "As outlined @ pyspark error does not exist in the ...
[ 35, 29, 18, 9, 4, 4, 3, 2, 2, 2, 1, 0, 0 ]
[]
[]
[ "pyspark", "python", "python_3.x" ]
stackoverflow_0053217767_pyspark_python_python_3.x.txt
Q: insert a single random string from a list, one at a time, every 2 seconds, only one note at a time should appear in tkinter listbox I'm using tkinter and I need to display one string from a list containing 6 strings in the gui listbox. I need each string to display on its own every 2 seconds and I need the program...
insert a single random string from a list, one at a time, every 2 seconds, only one note at a time should appear in tkinter listbox
I'm using tkinter and I need to display one string from a list containing 6 strings in the gui listbox. I need each string to display on its own every 2 seconds and I need the program to start on the click of a button. Right now, my program is outputting all of the items in the list so far, I can output the strings as ...
[ "Create a function that inserts one note, and then use after to call it every two seconds.\ndef practice_key_of_c():\n c = [\"C\",\"Dm\",\"Em\",\"F\",\"G\",\"Am\"]\n list1.insert(END, random.choice(c))\n window.after(2000, practice_key_of_c)\n\n" ]
[ 0 ]
[]
[]
[ "list", "python", "tkinter" ]
stackoverflow_0074265472_list_python_tkinter.txt
Q: is a numpy FFT on real values actually hermitian? I am a bit confused on the symmetry of the output of np.fft.fftn(). According to Numpy's FFT page, if the input array is real, then the output is Hermitian. According to that page, this means that "the component at frequency fk is the complex conjugate of the compo...
is a numpy FFT on real values actually hermitian?
I am a bit confused on the symmetry of the output of np.fft.fftn(). According to Numpy's FFT page, if the input array is real, then the output is Hermitian. According to that page, this means that "the component at frequency fk is the complex conjugate of the component at frequency -fk ." However, this Wikipedia page ...
[ "TL;DR: The result of numpy fft on a real array is not Hermitian.\nThe correct statement would be\n\nthe result of numpy fft on a real array is Hermitian-symmetric.\n\nBefore Answering\nOn the page you mentioned [1], I found more information about what is \"Hermitian\" [2].\nIn numpy's context, when a signal is ca...
[ 0 ]
[]
[]
[ "fft", "math", "numpy", "python" ]
stackoverflow_0070758915_fft_math_numpy_python.txt
Q: Identify image file from table in MS Word I read an MS-Word file using docx python library. The word file contains tables (only 1 column in tables) like table1, table2 and so on. I need to read it table by table. Whenever a row has one or more picture file i need to display "image file found" in table# and row#" ...
Identify image file from table in MS Word
I read an MS-Word file using docx python library. The word file contains tables (only 1 column in tables) like table1, table2 and so on. I need to read it table by table. Whenever a row has one or more picture file i need to display "image file found" in table# and row#" Here is what i have done. The inline_shapes pro...
[ "python-docx doesn't yet support this scenario very well but here's one way to approach it:\nfrom docx.api import Document\n\ndoc = Document(\"demo.docx\")\n\nfor table_index, table in enumerate(doc.tables):\n for row_index, row in enumerate(table.rows):\n for cell_index, cell in enumerate(row.cells):\n ...
[ 0 ]
[]
[]
[ "python", "python_docx" ]
stackoverflow_0049666591_python_python_docx.txt
Q: Properly displaying pyplot scatter plot with X/Y histograms and a colorbar I saw this tutorial on how to make a scatter plot with a histogram for the x and y axes and I thought it would be neat to also tack on a colorbar for an extra dimension of information. To do this, I utilized "the make_axes_locatable" functi...
Properly displaying pyplot scatter plot with X/Y histograms and a colorbar
I saw this tutorial on how to make a scatter plot with a histogram for the x and y axes and I thought it would be neat to also tack on a colorbar for an extra dimension of information. To do this, I utilized "the make_axes_locatable" function, like so: import numpy as np import matplotlib.pyplot as plt from mpl_toolkit...
[ "After getting a suggestion form @r-beginners , I tried tweaking this code to place a colorbar in the upper right, perpendicular to the histogram axes. This way, it doesn't distort the width/heights of the other shared axes:\n# some random data\ntx = np.random.randn(1000)\nty = np.random.randn(1000)\ntz = np.random...
[ 0 ]
[]
[]
[ "colorbar", "histogram", "matplotlib", "python", "scatter_plot" ]
stackoverflow_0074241110_colorbar_histogram_matplotlib_python_scatter_plot.txt
Q: Daily updating a dataframe in python and applying possible changes I have a dataframe that has connected to a database. The dataframe is updating every day and I want to write code to compare the today's dataframe with the yesterday's dataframe. If there is any changes in today's dataframe then uses that for the r...
Daily updating a dataframe in python and applying possible changes
I have a dataframe that has connected to a database. The dataframe is updating every day and I want to write code to compare the today's dataframe with the yesterday's dataframe. If there is any changes in today's dataframe then uses that for the rest of code otherwise just stop running the code and exit. I have the fo...
[ "You can save your variables using pickle:\nimport pickle\n\n\ndef save_obj(obj, name):\n os.mkdir(f'obj') if not os.path.exists('obj') else None\n\n with open(f'obj/{name}.pkl', 'wb') as f:\n pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)\n\n\ndef load_obj(name):\n try:\n with open(f'obj/{name...
[ 0 ]
[]
[]
[ "comparison", "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0074265530_comparison_dataframe_numpy_pandas_python.txt
Q: Can’t figure out how to make a counter work in a if statement python Ok I have asked how to do this and I keep getting my thing closed so I had to use my second account ok here’s my code I want to be able to make the second button to appear when the clicker (my counter) is at 7 it works at 0 which is my clickers s...
Can’t figure out how to make a counter work in a if statement python
Ok I have asked how to do this and I keep getting my thing closed so I had to use my second account ok here’s my code I want to be able to make the second button to appear when the clicker (my counter) is at 7 it works at 0 which is my clickers starting number I have tried many things to make this button appear on cert...
[ "I don't know if this solves your problem as I don't understand it very well but here it is:\nI have focused only on your GUI window so this is the modified part of the code.\n.\n.\n.\n\nfrom tkinter import *\n\nwindow = Tk()\nwindow.title(\"Clicky clicker *UNPLAYABLE*\")\nwindow.geometry(\"500x500\")\n#end of wind...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074262547_python_tkinter.txt
Q: Python Starting Thread From Function Inside Class TypeError takes 2 positional args but 3 were given def tfunc(this.args.dir, folder): for file in os.listdir(folder): this.executeFile(os.path.join(this.args.dir, file)) def executeFiles(this): for folders1 in os.listdir(this.args.dir): ...
Python Starting Thread From Function Inside Class TypeError takes 2 positional args but 3 were given
def tfunc(this.args.dir, folder): for file in os.listdir(folder): this.executeFile(os.path.join(this.args.dir, file)) def executeFiles(this): for folders1 in os.listdir(this.args.dir): for folders2 in os.listdir("downloaded/" + os.path.join(folders1)): t = threading.Thre...
[ "You should not pass this to args. this would be passed to tfunc automatically.\nt = threading.Thread(target=this.tfunc, args=(folders2, ))\n\n" ]
[ 0 ]
[]
[]
[ "class", "python" ]
stackoverflow_0074265713_class_python.txt
Q: How to change background and foreground color of a Tkinter Window on Mac OS X? I'm trying to set up a GUI window with Tkinter, but somehow I always end up with a blackscreen. Text is (if displayed) always black and so is the background color. However, when I run tkinter._test() the buttons "Click me!" and "QUIT" a...
How to change background and foreground color of a Tkinter Window on Mac OS X?
I'm trying to set up a GUI window with Tkinter, but somehow I always end up with a blackscreen. Text is (if displayed) always black and so is the background color. However, when I run tkinter._test() the buttons "Click me!" and "QUIT" are displayed properly. Is this about background / forground colors, or am I missing ...
[ "There is a mistake in the code:\ntkinter takes fg as foreground color and bg as background color\nso your code should be something like this :\nimport tkinter\n\ngui = tkinter.Tk()\ngui.title('Random GUI')\ngui.geometry('600x400')\n\nlabel1 = tkinter.Label(gui, text='Hello World', fg='black', bg='white')\nlabel1.p...
[ 0, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0071529085_python_tkinter.txt
Q: How do i make a login signup system in python? im trying to write code in python that basically its so that in the terminal you input whether you want to signup or log in if you already signed up i cant really figure out how to make it so that the signup input gets stored in a dictionary and then later when you tr...
How do i make a login signup system in python?
im trying to write code in python that basically its so that in the terminal you input whether you want to signup or log in if you already signed up i cant really figure out how to make it so that the signup input gets stored in a dictionary and then later when you try to enter the username and password it makes sure i...
[ "You have a typo in your last line, it should be username instead of user. Also : instead of ,\naccounts.update({username: password})\n\nThat will make your program not fail in both options.\nHowever, first, you are not checking properly the password, you need to grab the user and check if the password corresponds ...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x", "replit" ]
stackoverflow_0074265826_python_python_3.x_replit.txt
Q: Read CSV - The process cannot access the file When reading or writing CSV-files sometimes the file can´t be accessed: The process cannot access the file because another process has locked a portion of the file I want my code to retry the reading/writing until it works. Here is a draft how i would make a while loop...
Read CSV - The process cannot access the file
When reading or writing CSV-files sometimes the file can´t be accessed: The process cannot access the file because another process has locked a portion of the file I want my code to retry the reading/writing until it works. Here is a draft how i would make a while loop until the file could be read. But how can i test i...
[ "You don't need the extra boolean (bool is a very bad variable name anyway) and you don't need READING_DID_WORK, just rely on the OSError that will be raised.\nA simple wrapper function:\nimport time\n\n...\n\ndef read_file_with_retry(file_name, encoding=\"utf-16(LE)\"):\n while True:\n try:\n ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074265904_python.txt
Q: Django: Call custom function within generic views I'm new to Django and am using Django's generic editing views to add/edit/delete entities. Eg, the views for adding and editing look like this: class QuoteCreate(CreateView): template_name = 'quotes/quote_form.html' model = Quote fields = ['quote_text']...
Django: Call custom function within generic views
I'm new to Django and am using Django's generic editing views to add/edit/delete entities. Eg, the views for adding and editing look like this: class QuoteCreate(CreateView): template_name = 'quotes/quote_form.html' model = Quote fields = ['quote_text'] class QuoteUpdate(UpdateView): model = Quote ...
[ "You can call a view within another, which in your example could look like:\nviews.py\nclass QuoteCreate(CreateView):\n template_name = 'quotes/quote_form.html'\n model = Quote\n fields = ['quote_text']\n object_change = notify_function(foo)\n\n\nclass QuoteUpdate(UpdateView):\n model = Quote\n fi...
[ 0, 0 ]
[]
[]
[ "django", "django_generic_views", "function", "python" ]
stackoverflow_0062727762_django_django_generic_views_function_python.txt
Q: Create a dabatase from a textfile got an error message in python I have a TXT file like these: state sex year name count AK F 1920 Mary 14 AK F 1920 Eva 12 AK M 1920 Ben 14 AK M 1920 Will 12 I have more than 500'000 rows and it has no header, but the first column is state, the second column is gender, third...
Create a dabatase from a textfile got an error message in python
I have a TXT file like these: state sex year name count AK F 1920 Mary 14 AK F 1920 Eva 12 AK M 1920 Ben 14 AK M 1920 Will 12 I have more than 500'000 rows and it has no header, but the first column is state, the second column is gender, third is year and fourth shows name and fifth shows how many ba...
[ "Assuming your text file contains comma separated values:\nwith open(\"data/all.TXT\", \"r\") as f:\n result = f.readlines()\nresult = [x.split(\",\") for x in result]\n\nimport sqlite3 as sq3\n\ncon = sq3.connect(\"popular.db\")\n\ncon.execute(\n \"\"\"\n CREATE TABLE IF NOT EXISTS popname (\n id ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074265683_python.txt
Q: How to select a dict key that is inside a list of dicts holding list and more dicts I have a list called: all_players = [] A method called get_teams() which takes an URL and returns a list that holds dicts of a team name and URL of the team, and example of the output will be teams = get_teams(url) will return [{...
How to select a dict key that is inside a list of dicts holding list and more dicts
I have a list called: all_players = [] A method called get_teams() which takes an URL and returns a list that holds dicts of a team name and URL of the team, and example of the output will be teams = get_teams(url) will return [{'name': 'Dallas', 'url': 'https://en.wikipedia.org/wiki/2021%E2%80%9322_Dallas_Mavericks_...
[ "You were close to the answer. So in this step of your program your all_players list should look something like this:\nall_players = {\n \"Dallas\": [\n {\n \"name\": \"Dāvis Bertāns\",\n \"url\": \"https://en.wikipedia.org/wiki/D%C4%81vis_Bert%C4%81ns\",\n },\n {\n ...
[ 1 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074265631_dictionary_list_python.txt
Q: Why do I keep getting this error "ERROR: Command errored out with exit status 1:" when running packages like pynput and keyboard on replit? I am trying to make a game with python on Replit and it will not run certain packages that I have already pip installed. This is the code I ran: import keyboard while True: ...
Why do I keep getting this error "ERROR: Command errored out with exit status 1:" when running packages like pynput and keyboard on replit?
I am trying to make a game with python on Replit and it will not run certain packages that I have already pip installed. This is the code I ran: import keyboard while True: if keyboard.read_key() == "p": print("pressed p") break while True: if keyboard.is_pressed("q"): print("pressed q...
[ "You can't do this in repl.it sadly\n" ]
[ 0 ]
[]
[]
[ "python", "replit" ]
stackoverflow_0074263601_python_replit.txt
Q: beautiful soup how to avoid writing too many try catch blocks? I am using beautiful soup library to extract out data from webpages. Sometimes we have the case where element could not be found in the webpage itself, and if we try to access the sub element than we get error like 'NoneType' object has no attribute 'f...
beautiful soup how to avoid writing too many try catch blocks?
I am using beautiful soup library to extract out data from webpages. Sometimes we have the case where element could not be found in the webpage itself, and if we try to access the sub element than we get error like 'NoneType' object has no attribute 'find'. Like let say for the below code res = requests.get(url) soup =...
[ "I don't know if this is the most efficient way, but you can pass a lambda expression to the error_handler:\ndef error_handler(_):\n try:\n return _()\n except:\n return None\n\nprimary_name = error_handler(lambda: soup.find('div', {\"class\": \"company-header\"}).find('p', {\"class\": \"heading...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "design_patterns", "python", "web", "web_scraping" ]
stackoverflow_0074265369_beautifulsoup_design_patterns_python_web_web_scraping.txt
Q: Python: how to shorten this loop? The code seems a bit long for something that trivial. Is there a pythonic way to shorten it? fruit = None for _fruit in basket: if _fruit['name'] != 'banana': continue fruit = _fruit A: fruit = None for _fruit in basket: if _fruit['name'] == 'banana': fruit =...
Python: how to shorten this loop?
The code seems a bit long for something that trivial. Is there a pythonic way to shorten it? fruit = None for _fruit in basket: if _fruit['name'] != 'banana': continue fruit = _fruit
[ "fruit = None\nfor _fruit in basket:\n if _fruit['name'] == 'banana':\n fruit = _fruit\n\n", "Assuming basket is a list:\nfruit = [x for x in basket if x != \"banana\"]\n\nThis also allows to have better performance due to comprehension list https://www.w3schools.com/python/python_lists_comprehension.as...
[ 1, 0 ]
[ "Based on your initial conditions. Try this,\nfruit, = [_fruit for _fruit in basket if _fruit['name'] == 'banana'][-1:] or (None, )\n\nThis allows:\n\nIf there are multiple _fruits have name banana, assign the last one to fruit.\nIf not, assign None to fruit.\n\n", "If you want to have in minimum code lines\n1) \...
[ -1, -1 ]
[ "python", "python_3.x", "refactoring" ]
stackoverflow_0074265288_python_python_3.x_refactoring.txt
Q: How to make a PyQT4 window jump to the front? I want to make a PyQT4 window(QtGui.QMainWindow) jump to the front when the application received a specified message from another machine. Usually the window is minimized. I tried the raise_() and show() method but it doesn't work. A: This works: # this will remove m...
How to make a PyQT4 window jump to the front?
I want to make a PyQT4 window(QtGui.QMainWindow) jump to the front when the application received a specified message from another machine. Usually the window is minimized. I tried the raise_() and show() method but it doesn't work.
[ "This works:\n# this will remove minimized status \n# and restore window with keeping maximized/normal state\nwindow.setWindowState(window.windowState() & ~QtCore.Qt.WindowMinimized | QtCore.Qt.WindowActive)\n\n# this will activate the window\nwindow.activateWindow()\n\nBoth are required for me on Win7. \nsetWindow...
[ 23, 11, 5, 1, 0, 0 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0012118939_pyqt4_python.txt
Q: Find intersection of two Vectors with numpy Is there a way I can calculate the intersection of these two vectors? I am aware how to do that by hand, but not with numpy. I looked into numpy.intersect1d, but that wasn't a help. A: Essentially you are trying to solve 3 equations, with 2 unkowns. This does not alwa...
Find intersection of two Vectors with numpy
Is there a way I can calculate the intersection of these two vectors? I am aware how to do that by hand, but not with numpy. I looked into numpy.intersect1d, but that wasn't a help.
[ "Essentially you are trying to solve 3 equations, with 2 unkowns. This does not always have a solution as vectors do not always intersect in 3d. You could solve for the best solution using least squares. If the error is 0 (or the rank is 2), then they do intersect:\nv1 = np.array([4, 2, -1]).T\nc1 = np.array([6, 3,...
[ 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074265725_numpy_python.txt
Q: How to find body of a webpage using beautifulsoup I want to check if there is any content available on more than 500 webpages, using beautiful soup. This is the is script I wrote. It works, but somewhere it stops. If I fix the error it shows a different one. Below is the code I tried. I just want to be sure the pa...
How to find body of a webpage using beautifulsoup
I want to check if there is any content available on more than 500 webpages, using beautiful soup. This is the is script I wrote. It works, but somewhere it stops. If I fix the error it shows a different one. Below is the code I tried. I just want to be sure the page has a body. I'm unsure how to handle timeouts. Maybe...
[ "select() returns a list, not a string, so it will always compare not equal to '', whether it's successful or not. Just test if the result is not empty.\nUse try/except to catch the timeout error.\ntry:\n res = requests.get(full_https_url, timeout=40)\n soup = bs4.BeautifulSoup(res.text, 'html.parser')\n ...
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "python_3.x" ]
stackoverflow_0074265912_beautifulsoup_python_python_3.x.txt
Q: Append or combine column wise torch tensors of different shapes Tensors A and B below share the row size. The 6 and 3 refers to the columns of the 2 data frame, but the B tensor has at each cell a vector of size 256. A= torch.Size([17809, 6]) B= torch.Size([17809, 3, 256]) How do I append combine these tensors? M...
Append or combine column wise torch tensors of different shapes
Tensors A and B below share the row size. The 6 and 3 refers to the columns of the 2 data frame, but the B tensor has at each cell a vector of size 256. A= torch.Size([17809, 6]) B= torch.Size([17809, 3, 256]) How do I append combine these tensors? More detail: A column of 'A' is a numeric vector like 'Age', In B one ...
[ "You can apply torch.nn.Embedding on A to embedding numeric vector then use torch.cat to concat embeding of A and B on the axis=1.\n(In the below code I use random tensors).\nimport torch\nfrom torch import nn\n\nnum_embeddings = 10 # fill base Age\nembedding_dim = 256 # fill base of B tensor\nembedding = nn.Embedd...
[ 1 ]
[]
[]
[ "python", "pytorch", "tensor" ]
stackoverflow_0074265925_python_pytorch_tensor.txt
Q: No module named _sqlite3 I am trying to run a Django app on my VPS running Debian 5. When I run a demo app, it comes back with this error: File "/usr/local/lib/python2.5/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/usr/local/lib/python2.5/site-packages/dj...
No module named _sqlite3
I am trying to run a Django app on my VPS running Debian 5. When I run a demo app, it comes back with this error: File "/usr/local/lib/python2.5/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/usr/local/lib/python2.5/site-packages/django/db/backends/sqlite3/base....
[ "It seems your makefile didn't include the appropriate .so file. You can correct this problem with the steps below:\n\nInstall sqlite-devel (or libsqlite3-dev on some Debian-based systems)\nRe-configure and re-compiled Python with ./configure --enable-loadable-sqlite-extensions && make && sudo make install\n\n\nNot...
[ 228, 87, 80, 30, 27, 27, 13, 13, 11, 9, 8, 5, 4, 3, 3, 3, 2, 2, 2, 1, 1, 0, 0, 0, 0 ]
[ "You need to install pysqlite in your python environment:\n $ pip install pysqlite\n\n", "Try copying _sqlite3.so so that Python can find it.\nIt should be as simple as:\ncp /usr/lib64/python2.6/lib-dynload/_sqlite3.so /usr/local/lib/python2.7/\n\nTrust me, try it.\n" ]
[ -3, -4 ]
[ "debian", "python", "python_import", "sqlite" ]
stackoverflow_0001210664_debian_python_python_import_sqlite.txt
Q: Method in one Python Treeview Class to affect instance of different Treeview class My Python program has two classes that are basically modified versions of Tkinter's Treeview Widget. The reason for the two different classes is that they have different methods for when items within them are double-clicked, selecte...
Method in one Python Treeview Class to affect instance of different Treeview class
My Python program has two classes that are basically modified versions of Tkinter's Treeview Widget. The reason for the two different classes is that they have different methods for when items within them are double-clicked, selected etc. The program creates an instance of each class, named tree_dialog_tv1 and tree_dia...
[ "What I like to do in such cases is to use a common master, mostly a tk.Frame. It is a convenient way to connect two or more widgets which each other, since tkinter already stores the master for each widget, which can be addressed in a class with self.master. This way you can easily address every widget in the pare...
[ 1 ]
[]
[]
[ "python", "tkinter", "treeview" ]
stackoverflow_0074265089_python_tkinter_treeview.txt
Q: Openpyxl - Empty Cells being added when copy and pasting data My script copies data from each sheet from one excel workbook to the first sheet in another workbook. The script will also sort the data based on the value in column A. My issue is that my current output is adding empty cells between data. I'm not sure ...
Openpyxl - Empty Cells being added when copy and pasting data
My script copies data from each sheet from one excel workbook to the first sheet in another workbook. The script will also sort the data based on the value in column A. My issue is that my current output is adding empty cells between data. I'm not sure why this is happening. Does anyone know why? Thank you. from openp...
[ "After Debugging your code finally got the point you are applying mr2 += 1 when Value = C and you giving enter after value of C comes.\nCode which solve your problem:\nfrom openpyxl import load_workbook\nfrom openpyxl import Workbook\n\nwb = load_workbook('testData.xlsx')\nwb2 = load_workbook('testTemplate.xlsx')\n...
[ 0 ]
[]
[]
[ "copy", "excel", "openpyxl", "paste", "python" ]
stackoverflow_0074263738_copy_excel_openpyxl_paste_python.txt
Q: Gensim topic modelling with suggested initial inputs? I'm doing am LDA topic model on a medium sized corpus using gensim in python. We already know roughly some of the topics we're expecting. In particular, we know that a particular topic definitely exists within the corpus and we want the model to find that topic...
Gensim topic modelling with suggested initial inputs?
I'm doing am LDA topic model on a medium sized corpus using gensim in python. We already know roughly some of the topics we're expecting. In particular, we know that a particular topic definitely exists within the corpus and we want the model to find that topic for us so that we can extract the elements of the corpus t...
[ "As LDA is traditionally an unsupervised method, it's more common to let it tell you what topics it finds by its rules, then see which (if any) of those match your preconceptions.\nGensim has no way to pre-seed an LDA model/session with biases towards finding/defining certain topics.\nYou might use your conceptions...
[ 0 ]
[]
[]
[ "gensim", "lda", "python" ]
stackoverflow_0074264268_gensim_lda_python.txt
Q: How to filter minute data using day and symbol? Assuming I have a dataframe of minute OHLC: index timestamp open high ... vwap symbol cum_volume cum_volume_25k 0 2020-11-05 09:00:00+00:00 2020-11-05 09:00:00+00:00 11.2000 11.2000 ... 11.1997...
How to filter minute data using day and symbol?
Assuming I have a dataframe of minute OHLC: index timestamp open high ... vwap symbol cum_volume cum_volume_25k 0 2020-11-05 09:00:00+00:00 2020-11-05 09:00:00+00:00 11.2000 11.2000 ... 11.199735 AAL 1360 0 1 2020-1...
[ "As an option, you can create columns with dates in each dataframe.\ndfd['day'] = dfd['timestamp'].dt.date\ndfm['day'] = dfm['timestamp'].dt.date\n\nMake grouping in the minute chart by the 'day' column. Create an empty dataframe and fill in where there are dates and symbol matches.\nimport pandas as pd\n\ndfd['tim...
[ 1 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074249127_numpy_pandas_python.txt
Q: While loop keeps printing constantly, doesn't allow for user input I'm trying to complete this assignment asking user for a number and if it's not -1 then it should loop. if it's -1 then to calculate the average of the other numbers. I'm getting stuck with the actual loop - it endlessly keeps printing the message ...
While loop keeps printing constantly, doesn't allow for user input
I'm trying to complete this assignment asking user for a number and if it's not -1 then it should loop. if it's -1 then to calculate the average of the other numbers. I'm getting stuck with the actual loop - it endlessly keeps printing the message to user to enter a different number - as in the picture - and doesn't gi...
[ "You need to include the input function in the loop if you want it to work. I corrected the rest of your code as well, you don't need the if condition. More generally you should avoid to use break, it often means you are doing something wrong with your loop condition. Here it is redondant and the code after break i...
[ 1, 0, 0, 0 ]
[]
[]
[ "break", "input", "python", "while_loop" ]
stackoverflow_0074266024_break_input_python_while_loop.txt
Q: Openpyxl - How can I iterate through a column to copy values and sort based on condition I am new to Python. I am trying to write a script which will copy values from one excel file to another and sort them based on the value in column A. My code is only copying the final value that meets the condition, not all va...
Openpyxl - How can I iterate through a column to copy values and sort based on condition
I am new to Python. I am trying to write a script which will copy values from one excel file to another and sort them based on the value in column A. My code is only copying the final value that meets the condition, not all values. What am I doing wrong? from openpyxl import load_workbook wb = load_workbook('testData...
[ "increase mr2 by 1 when value == \"C\"\nfor j in range(1, mc + 1):\n if ws.cell(row=i,column=j).value == \"A\":\n ws2.cell(row=mr2 + 1,column=j).value = ws.cell(row=i,column=j+1).value\n elif ws.cell(row=i,column=j).value == \"B\":\n ws2.cell(row=mr2 + 1,column=j+1).value = ws.cell(row=i,column=...
[ 0, 0 ]
[]
[]
[ "copy", "excel", "openpyxl", "paste", "python" ]
stackoverflow_0074242803_copy_excel_openpyxl_paste_python.txt
Q: Tensorflow : Invalid reduction dimension in tf.range I want to find the point in an interior set closest to a boundary set without using a point twice: @tf.function(experimental_relax_shapes=True) def Test(interior, bound): for i in tf.range(bound.shape[0]): tf.autograph.experimental.set_loop_options(s...
Tensorflow : Invalid reduction dimension in tf.range
I want to find the point in an interior set closest to a boundary set without using a point twice: @tf.function(experimental_relax_shapes=True) def Test(interior, bound): for i in tf.range(bound.shape[0]): tf.autograph.experimental.set_loop_options(shape_invariants=[(interior, tf.TensorShape([None]))]) ...
[ "I solved the problem by removing @tf.function and calling the function outside @tf.function and then using the output as input for a @tf.function. The error also occurs when calling the separate function inside a @tf.function. It is not the most beautiful solution and I still don't understand why it doesn't work i...
[ 0 ]
[]
[]
[ "for_loop", "python", "range", "tensorflow" ]
stackoverflow_0074209626_for_loop_python_range_tensorflow.txt
Q: scrapy: NotImplementedError parse callback not defined I have started writing a scrapy spider and I keep getting this error when I run the spider in VS Code. Traceback (most recent call last): File "/usr/lib/python3/dist-packages/twisted/internet/defer.py", line 654, in _runCallbacks current....
scrapy: NotImplementedError parse callback not defined
I have started writing a scrapy spider and I keep getting this error when I run the spider in VS Code. Traceback (most recent call last): File "/usr/lib/python3/dist-packages/twisted/internet/defer.py", line 654, in _runCallbacks current.result = callback(current.result, *args, **kw) File "/...
[ "Samir Das\n\n\ndef login(self, response):\n csrf_token = response.css('[name=\"csrf_token\"]::attr(value)').get()\n form_data = {\n 'csrf_token': csrf_token,\n 'username': 'samircd4',\n 'password': '123456'\n }\n return FormRequest.from_response(response, formdata=f...
[ 0 ]
[]
[]
[ "python", "scrapy" ]
stackoverflow_0071943233_python_scrapy.txt
Q: Cleaning date column in python with multiple date formats I am cleaning up a dataframe that has date of birth and date of death as a string. There are multiple formats of dates in those columns. Some contain just year (which is all I need). These are the formats of dates: Jan 10 2020 1913 10/8/2019 June 14th 1980...
Cleaning date column in python with multiple date formats
I am cleaning up a dataframe that has date of birth and date of death as a string. There are multiple formats of dates in those columns. Some contain just year (which is all I need). These are the formats of dates: Jan 10 2020 1913 10/8/2019 June 14th 1980 All I need is the year from each date. I have not been having...
[ "The simplest way is to use a parser which will accept these and other formats:\nimport pandas as pd\nfrom dateutil import parser \n\ndf = pd.DataFrame({\"mydates\":[\"Jan 10 2020\", \"1913\", \"10/8/2019\", \"June 14th 1980\"]})\ndf['years'] = df['mydates'].apply(parser.parse).dt.strftime('%Y')\nprint(df)\n\n", ...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074266124_python.txt
Q: Python - a function that determines the first n prime numbers IM VERY NEW TO PYTHON, THANKS FOR UNDERSTANDING Write a function that determines the first n prime numbers. The value of n is taken from a user input. The program should print all the prime numbers requested. After doing this task, the program should as...
Python - a function that determines the first n prime numbers
IM VERY NEW TO PYTHON, THANKS FOR UNDERSTANDING Write a function that determines the first n prime numbers. The value of n is taken from a user input. The program should print all the prime numbers requested. After doing this task, the program should ask the user again if they would like to print another set of prime n...
[ "Found the answer to my question;\njust put while True, on the def redo() function.\n" ]
[ -1 ]
[]
[]
[ "python" ]
stackoverflow_0074265561_python.txt
Q: How to fit polynomial function to time series data that minimizes least square error? I have time series data. I want to group the data in 10 minute bins and I want to fit polynomial functions to each of the 10 minute bins that minimize that least square errors. So, from 15:20 to 15:30 would be one bin and have it...
How to fit polynomial function to time series data that minimizes least square error?
I have time series data. I want to group the data in 10 minute bins and I want to fit polynomial functions to each of the 10 minute bins that minimize that least square errors. So, from 15:20 to 15:30 would be one bin and have its own polynomial function, from 15:30 to 15:40 would be another bin and have its own polyno...
[ "There are many ways. Here is one:\ndef convertToMinutes( hhmm:str):\n parts = hhmm.split(':')\n return int( parts[0])*24 + int( parts[1])\n\ndef parseLine( line):\n parts = line.split()\n minutes = convertToMinutes( parts[0])\n var = int(parts[1])\n return minutes, var\n\ndef polyRegression( tuples:list):\n ...
[ 1 ]
[]
[]
[ "dataframe", "numpy", "pandas", "python", "scipy" ]
stackoverflow_0074264072_dataframe_numpy_pandas_python_scipy.txt
Q: how to print only a part of each element of a list in python output? So I have this code that I shortened a bit to be within character limit as shown below in python 3 import re seqs = """>UDW38231.1 |surface glycoprotein|MS|GenBank|ssRNA(+) MFVFLVLLPLVSSQCVNLRTRTQLPPAYTNSFTRGVYYPDKVFRSSVLHSTQDLFLPFFS NVTWFHAIHVS...
how to print only a part of each element of a list in python output?
So I have this code that I shortened a bit to be within character limit as shown below in python 3 import re seqs = """>UDW38231.1 |surface glycoprotein|MS|GenBank|ssRNA(+) MFVFLVLLPLVSSQCVNLRTRTQLPPAYTNSFTRGVYYPDKVFRSSVLHSTQDLFLPFFS NVTWFHAIHVSGTNGTKRFDNPVLPFNDGVYFASIEKSNIIRGWIFGTTLDSKTQSLIIV NNATNVVIKVCEFQFCNDPFLDVY...
[ "Use a regular expression to get everything up to (+) and print just that.\nfor x in rbd:\n indication = re.search(r'^.*\\(\\+\\)', x.group(0)).group(0)\n print(f\"{indication} has the rbd domain{x.span()}\\n\")\n\n" ]
[ 1 ]
[]
[]
[ "list", "python", "python_3.x" ]
stackoverflow_0074265985_list_python_python_3.x.txt
Q: Delect white space of list in python How can I delect the white space in a list? I have: text = [" Hello", " how are ","you "] I want: text = ["Hello","how are","you"] A: That's not the question you want to ask. You want to ask "how can I delete leading and trailing spaces?" You use .strip for...
Delect white space of list in python
How can I delect the white space in a list? I have: text = [" Hello", " how are ","you "] I want: text = ["Hello","how are","you"]
[ "That's not the question you want to ask. You want to ask \"how can I delete leading and trailing spaces?\" You use .strip for that.\ntext = [s.strip() for s in text]\n\n", "List = [\" Hello\", \" how are \",\"you \"]\nList = [value.strip() for value in List]\nprint(List)\n\n", "You can use st...
[ 1, 0, 0, 0 ]
[]
[]
[ "list", "python", "whitespace" ]
stackoverflow_0074266335_list_python_whitespace.txt
Q: Pandas to parquet file I am trying to save a pandas object to parquet with the following code: LABL = datetime.now().strftime("%Y%m%d_%H%M%S") df.to_parquet("/data/TargetData_Raw_{}.parquet".format(LABL)) this gives me the error: ArrowTypeError: ("Expected bytes, got a 'float' object", 'Conversion failed for colu...
Pandas to parquet file
I am trying to save a pandas object to parquet with the following code: LABL = datetime.now().strftime("%Y%m%d_%H%M%S") df.to_parquet("/data/TargetData_Raw_{}.parquet".format(LABL)) this gives me the error: ArrowTypeError: ("Expected bytes, got a 'float' object", 'Conversion failed for column Pre-Rumour_Date with type...
[ "Try: df.astype(str).to_parquet(\"/data/TargetData_Raw_{}.parquet\".format(LABL))\n" ]
[ 1 ]
[]
[]
[ "pandas", "parquet", "python" ]
stackoverflow_0068826636_pandas_parquet_python.txt
Q: How to print out the dictionary with for loop? Python I would like to print the item of dictionary. how to do that? this is my code {'naruto': [900, 170], 'onepiece': [600, 60]} for key, value in stock_dict1.items(): for value in stock_dict1.values(): print(key, value[0], value[1]) when I pri...
How to print out the dictionary with for loop? Python
I would like to print the item of dictionary. how to do that? this is my code {'naruto': [900, 170], 'onepiece': [600, 60]} for key, value in stock_dict1.items(): for value in stock_dict1.values(): print(key, value[0], value[1]) when I print out, the result will be like this: how to do that? narut...
[ "Using str.ljust and iterable unpacking:\ndata = {'naruto': [900, 170], 'onepiece': [600, 60]}\n\nfor movie, nums in data.items():\n print(movie.ljust(11, ' '), *nums)\n\n\nnaruto 900 170\nonepiece 600 60\n \n\n", "The following code snippet provides the easy way for beginner.\nTry this:\nd = {'naru...
[ 1, 1 ]
[]
[]
[ "dictionary", "for_loop", "printing", "python" ]
stackoverflow_0074266211_dictionary_for_loop_printing_python.txt
Q: Website creates a new non-existent webpage after I visit website/class_id My website creates a new non-existent website, after I visit my website/näytä_luokka/# (also, class_id). If I try to go to a page that is in the same urls.py file, I get an error because it tries to find a page website/näytä_luokka/luokat i...
Website creates a new non-existent webpage after I visit website/class_id
My website creates a new non-existent website, after I visit my website/näytä_luokka/# (also, class_id). If I try to go to a page that is in the same urls.py file, I get an error because it tries to find a page website/näytä_luokka/luokat instead of going to website/luokat. This happens through navbar. If I try to go ...
[ "The path in your urls.py\npath('näytä_luokka/<luokka_id>', views.näytä_luokka, name=\"näytä-luokka\"),\nSpecifically, the <luokka_id> is what is creating a webpage for you. That is what is supposed to happen in a path like that. It's the beauty of what Django can do; create urls dynamically, in this case a page ...
[ 2, 1 ]
[]
[]
[ "django", "django_templates", "django_urls", "django_views", "python" ]
stackoverflow_0074265025_django_django_templates_django_urls_django_views_python.txt
Q: Python class method fixed argument I saw a piece of python code here. I want to know why the programmer has defined width=0 and height=0 ? aren't they supposed to be received by the init method ? class Rectangle: sides = 4 def __init__(self, width=0, height=0): self.width = width self.hei...
Python class method fixed argument
I saw a piece of python code here. I want to know why the programmer has defined width=0 and height=0 ? aren't they supposed to be received by the init method ? class Rectangle: sides = 4 def __init__(self, width=0, height=0): self.width = width self.height = height def calculate_area(se...
[ "These are default values. He assigned width and height to 0 by default if he didn't pass arguments in initialization.\nSo:\nrectangle_1 = Rectangle (5, 10) -> means width =5 and height=10\nwhile\nrectangle_1 = Rectangle () -> doesn't error instead by the default value\nwidth =0 and height=0.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074266304_python.txt
Q: Using Regular Expression to narrow down dictionary based on Wordle rules I am trying to do Wordle Solver as my resume project. I want to develop some word suggestions by narrowing down dictionary of words using RegEx. Is it possible to write RegEx such that it searches for words in the dictionary that satisfy thes...
Using Regular Expression to narrow down dictionary based on Wordle rules
I am trying to do Wordle Solver as my resume project. I want to develop some word suggestions by narrowing down dictionary of words using RegEx. Is it possible to write RegEx such that it searches for words in the dictionary that satisfy these 3 conditions? Word that starts with the letter 'C' does not contain letter ...
[ "This is just an example. You could do some little helper functions to make it more flexible. functions like \"letter isn't in the word at all\", \"specific letter at 3rd position\" ....\ndic = {'words': ['value', 'cache', 'cacao', 'racer', 'house']}\n\nfilt = [x for x in dic['words'] if all([x[0].upper()=='C', 'T'...
[ 2, 2 ]
[ "You can just get the Wordle dictionary from here:\nhttps://static.nytimes.com/newsgraphics/2022/01/25/wordle-solver/assets/solutions.txt\n" ]
[ -1 ]
[ "python", "python_3.x", "regex" ]
stackoverflow_0072244428_python_python_3.x_regex.txt
Q: Creating white space in Python so text look aligned I have the following code: names = ['William T. Riker', 'Jean-Luc Picard', 'Worf', 'Deanna Troi'] function ='The Team' for name in names: print(name,":", function) This produces the following output: William T. Riker : The Team Jean-Luc Picard : The Team W...
Creating white space in Python so text look aligned
I have the following code: names = ['William T. Riker', 'Jean-Luc Picard', 'Worf', 'Deanna Troi'] function ='The Team' for name in names: print(name,":", function) This produces the following output: William T. Riker : The Team Jean-Luc Picard : The Team Worf : The Team Deanna Troi : The Team The project which ...
[ "Try this small change to find max length first\nmax_len = max(len(x) for x in names)\n\nfor name in names:\n print(name.ljust(max_len),\":\", function)\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074266442_python.txt
Q: why is my class getting the wrong values? I recently started exploring classes and I have made my first class (sort of) but it doesn't seem to be working. I have code creating the class and function, then takes the values and blits an image to certain coordinates. for some reason It takes the values from inside...
why is my class getting the wrong values?
I recently started exploring classes and I have made my first class (sort of) but it doesn't seem to be working. I have code creating the class and function, then takes the values and blits an image to certain coordinates. for some reason It takes the values from inside the class instead of what I told it to have. ...
[ "The image is blit in the constructor. At this point the coordinates are not yet changed. You have add a method that blits the object:\nclass MTC() :\n def __init__(self,) :\n self.Tx = 0\n self.Ty = 0\n\n def dra():\n Screen.blit(TC,(self.Tx,self.Ty))\n\nCall the draw method in the appli...
[ 2, 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074266421_pygame_python.txt
Q: 403 error in web-scraping a specific website with Python I'm trying to open the following UK parliament website from my colab environment, but I haven't been able to make it work without 403 errors. The header restriction is too strict. Following several answers for previous similar questions, I've tried much more...
403 error in web-scraping a specific website with Python
I'm trying to open the following UK parliament website from my colab environment, but I haven't been able to make it work without 403 errors. The header restriction is too strict. Following several answers for previous similar questions, I've tried much more extended versions of the header but still does not work. Is t...
[ "The website is under cloudflare protection. As Andrew Ryan already has stated about the possible solution.I also used cloudscraper but didn't work and still getting 403 then i use playwright with bs4 and now it's working like a charm.\nExample:\nfrom playwright.sync_api import sync_playwright\nfrom bs4 import Be...
[ 1 ]
[]
[]
[ "http_status_code_403", "python", "web_scraping" ]
stackoverflow_0074266158_http_status_code_403_python_web_scraping.txt
Q: Linked List Recursive Value Sum I am trying to recursively determine the sum of the values in a linked list. I am aware of one recursive solution that works: def sum_list_rec1(head_node: Node): if head_node == None: return 0 return head_node.value + sum_list_rec1(head_node.next) However, I am trying...
Linked List Recursive Value Sum
I am trying to recursively determine the sum of the values in a linked list. I am aware of one recursive solution that works: def sum_list_rec1(head_node: Node): if head_node == None: return 0 return head_node.value + sum_list_rec1(head_node.next) However, I am trying to use the pattern where a variable ...
[ "Integers in Python are immutable, so every time you do val_sum += head_node.value you are basically creating a new integer, and the code is equivalent to val_sum = val_sum + hash_node.values.\nA simple way to circumvent this problem is to wrap the integer inside an object:\nclass IntWrap:\n def __init__(self, i...
[ 2, 1 ]
[]
[]
[ "linked_list", "python", "recursion", "singly_linked_list" ]
stackoverflow_0074266381_linked_list_python_recursion_singly_linked_list.txt
Q: Function that receives an integer n>0 and tells whether its digits (in base 10) form a nondecreasing sequence (each digit is >= to the previous one) Write a function nondec(n) that receives an integer n>0 and reports whether its digits (in base 10) form a nondecreasing sequence (that is, each digit is greater or e...
Function that receives an integer n>0 and tells whether its digits (in base 10) form a nondecreasing sequence (each digit is >= to the previous one)
Write a function nondec(n) that receives an integer n>0 and reports whether its digits (in base 10) form a nondecreasing sequence (that is, each digit is greater or equal to the previous one). I am having trouble with this exercise. My code so far is: def nondec(n): ''' >>> nondec(113355779) True >>> no...
[ "Maybe this is the code you are looking for:\ndef nondec(n):\n '''\n >>> nondec(113355779)\n True\n >>> nondec(44569)\n True\n >>> nondec(346234)\n False\n >>> nondec(222)\n True\n >>> nondec(789)\n True\n >>> nondec(55555)\n True\n >>> nondec(1234123)\n False\n >>> n...
[ 3, 1, 0 ]
[ "The variable n should be an integer. You should cast n to int inside your loop.\ndef nondec(n):\n '''\n >>> nondec(113355779)\n True\n >>> nondec(44569)\n True\n >>> nondec(346234)\n False\n >>> nondec(222)\n True\n >>> nondec(789)\n True\n >>> nondec(55555)\n True\n >>> n...
[ -1 ]
[ "math", "python", "python_3.x" ]
stackoverflow_0074266250_math_python_python_3.x.txt
Q: Define a Voronoi cell max radius (python) My question is similar to this one (R + ggplot) but for Python. Question How to generate a (2D) Voronoi diagram where cells have a maximum extend / growth limit ? it would result in some cells with curved boundary (circle arc), and some space regions not filled by any cel...
Define a Voronoi cell max radius (python)
My question is similar to this one (R + ggplot) but for Python. Question How to generate a (2D) Voronoi diagram where cells have a maximum extend / growth limit ? it would result in some cells with curved boundary (circle arc), and some space regions not filled by any cell. An image processing interpretation of the de...
[ "After some thinking, here is an approach using Shapely and using the intersection between computed circles (360 vertices) and each voronoi cell.\nPerformance is not convincing since we create 360 points and a polygon + 1 intersection computation for each cell... (at least it is a bounded ...).\nHowever, the underl...
[ 0 ]
[]
[]
[ "python", "scipy_spatial", "voronoi" ]
stackoverflow_0074266553_python_scipy_spatial_voronoi.txt
Q: Python selenium how to wait until element is gone/becomes stale? I am trying to programmatically solve the problem presented at this address: https://www.arealme.com/brain-memory-game/en/, in short it will display several flashing numbers in a row, and asking you to input the numbers in reverse order. Now here are...
Python selenium how to wait until element is gone/becomes stale?
I am trying to programmatically solve the problem presented at this address: https://www.arealme.com/brain-memory-game/en/, in short it will display several flashing numbers in a row, and asking you to input the numbers in reverse order. Now here are the details, when you get to the website, there will be a start butto...
[ "to wait till any elelemt becomes invisible we have this Expected conditions :\ninvisibility_of_element\n\nalso in code I could see :\nclass invisibility_of_element(invisibility_of_element_located):\n \"\"\" An Expectation for checking that an element is either invisible or not\n present on the DOM.\n\n el...
[ 1, 0, 0 ]
[]
[]
[ "python", "python_3.x", "selenium" ]
stackoverflow_0068949169_python_python_3.x_selenium.txt
Q: ELSE not executing in the program fruits = ["mango", "banana", "apple", "yolk", "mulberry"] letter = input("Enter the letter you want to search: ") letter2 = input("Enter the second letter you want to search: ") for word in fruits: if word[0].startswith(letter) and word[1].startswith(letter2): result = wo...
ELSE not executing in the program
fruits = ["mango", "banana", "apple", "yolk", "mulberry"] letter = input("Enter the letter you want to search: ") letter2 = input("Enter the second letter you want to search: ") for word in fruits: if word[0].startswith(letter) and word[1].startswith(letter2): result = word if result == word: pr...
[ "Why are you comparing with 'startwith'? you can compare it directly like this:\nif word[0] == letter1 and word[1] == letter2:\n\nDo something like this:\nfruits = [\"mango\", \"banana\", \"apple\", \"yolk\", \"mulberry\"]\nletter = input(\"Enter the letter you want to search: \")\nletter2 = input(\"Enter the secon...
[ 0, 0, 0, 0 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0074265295_if_statement_python.txt