content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: python undetected chromedriver fail to run I'm scrapping a website using selenium but I get detected all the time. I decided to use Undetected chromedriver. But I get the following error Traceback (most recent call last): File "undt.py", line 746, in <module> booter() File "undt.py", line 92, in booter ...
python undetected chromedriver fail to run
I'm scrapping a website using selenium but I get detected all the time. I decided to use Undetected chromedriver. But I get the following error Traceback (most recent call last): File "undt.py", line 746, in <module> booter() File "undt.py", line 92, in booter driver = uc.Chrome(options=option) File "C:\U...
[ "Try the below code, its working:\nfrom selenium import webdriver\nimport undetected_chromedriver as uc\n\ndriver = uc.Chrome(use_subprocess=True)\ndriver.maximize_window()\n\ndriver.get(\"https://tempail.com/\")\n\n" ]
[ 0 ]
[]
[]
[ "python", "selenium", "undetected_chromedriver" ]
stackoverflow_0074627303_python_selenium_undetected_chromedriver.txt
Q: Upload tsv file to google colab TSV(Tab separated Value) extension file can't be uploaded to google colab using pandas Used this to upload my file import io df2 = pd.read_csv(io.BytesIO(uploaded['Filename.csv'])) import io stk = pd.read_csv(io.BytesIO(uploaded['train.tsv'])) A tsv file should be uploaded and rea...
Upload tsv file to google colab
TSV(Tab separated Value) extension file can't be uploaded to google colab using pandas Used this to upload my file import io df2 = pd.read_csv(io.BytesIO(uploaded['Filename.csv'])) import io stk = pd.read_csv(io.BytesIO(uploaded['train.tsv'])) A tsv file should be uploaded and read into the dataframe stk
[ "To save tsv file on google colab, .to_csv function can be used as follows:\ndf.to_csv('path_in_drive/filename.tsv', sep='\\t', index=False, header=False)\nstk = pd.read_csv('path_in_drive/filename.tsv') #to read the file\n", "Don't know if this is a solution to your problem as it doesn't upload the files, but w...
[ 1, 0, 0 ]
[]
[]
[ "google_colaboratory", "pandas", "python", "svm" ]
stackoverflow_0057285697_google_colaboratory_pandas_python_svm.txt
Q: sympy lambdify with numexpr and sqrt I'm trying to speed up some numeric code generated by lambdify using numexpr. Unfortunately, the numexpr-based function breaks when using the sqrt function, even though it's one of the supported functions. This reproduces the issue for me: import sympy import numpy as np import...
sympy lambdify with numexpr and sqrt
I'm trying to speed up some numeric code generated by lambdify using numexpr. Unfortunately, the numexpr-based function breaks when using the sqrt function, even though it's one of the supported functions. This reproduces the issue for me: import sympy import numpy as np import numexpr from sympy.utilities.lambdify im...
[]
[]
[ "you can change np.sqrt(9) to numexpr.evaluate('9**0.5')\n" ]
[ -1 ]
[ "numexpr", "numpy", "python", "sympy" ]
stackoverflow_0029807509_numexpr_numpy_python_sympy.txt
Q: aws Glue job: how to merge multiple output .csv files in s3 I created an aws Glue Crawler and job. The purpose is to transfer data from a postgres RDS database table to one single .csv file in S3. Everything is working, but I get a total of 19 files in S3. Every file is empty except three with one row of the datab...
aws Glue job: how to merge multiple output .csv files in s3
I created an aws Glue Crawler and job. The purpose is to transfer data from a postgres RDS database table to one single .csv file in S3. Everything is working, but I get a total of 19 files in S3. Every file is empty except three with one row of the database table in it as well as the headers. So every row of the datab...
[ "Can you try the following?\nimport sys\nfrom awsglue.transforms import *\nfrom awsglue.utils import getResolvedOptions\nfrom pyspark.context import SparkContext\nfrom awsglue.context import GlueContext\nfrom awsglue.job import Job\n\n## @params: [JOB_NAME]\nargs = getResolvedOptions(sys.argv, ['JOB_NAME'])\n\nsc =...
[ 7, 0 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "aws_glue", "jobs", "python" ]
stackoverflow_0055515251_amazon_s3_amazon_web_services_aws_glue_jobs_python.txt
Q: Selecting hover on plotly choropleth map I am currently working on a map project using choropleth from plotly.express and this map combines two traces: one is the choropleth map with area defined by colors and the second one bubbles to put over some selected countries (not all). I have two dataframes, one with iso...
Selecting hover on plotly choropleth map
I am currently working on a map project using choropleth from plotly.express and this map combines two traces: one is the choropleth map with area defined by colors and the second one bubbles to put over some selected countries (not all). I have two dataframes, one with iso alpha-3 code and the regional area they are a...
[ "Ok so I will share how I handled the issue which is not perfect but it will maybe help.\nThe \"solution\" was to remove every data from the first figure by disabling them with hover_data as follow in the choropleth map variables:\nhover_data={\"alpha-3\":False,\"sub-region\":False}\n\nThis solution isn't perfect a...
[ 0 ]
[]
[]
[ "choropleth", "plotly", "python", "python_3.x" ]
stackoverflow_0074614344_choropleth_plotly_python_python_3.x.txt
Q: Unix socket credential passing in Python How is Unix socket credential passing accomplished in Python? A: Internet searches on this topic came up with surprisingly few results. I figured I'd post the question and answer here for others interested in this topic. The following client and server applications demons...
Unix socket credential passing in Python
How is Unix socket credential passing accomplished in Python?
[ "Internet searches on this topic came up with surprisingly few results. I figured I'd post the question and answer here for others interested in this topic.\nThe following client and server applications demonstrate how to accomplish this on Linux with the standard python interpreter. No extensions are required but,...
[ 23, 1 ]
[]
[]
[ "credentials", "linux", "python", "sockets" ]
stackoverflow_0007982714_credentials_linux_python_sockets.txt
Q: Why some variables have changed and some have not? Why the variables a, c, d have not changed, but b has changed? a = 0 b = [] c = [] d = 'a' def func_a(a): a += 1 def func_b(b): b += [1] def func_c(c): c = [2] def func_d(d): d += 'd' func_a(a) func_b(b) fun...
Why some variables have changed and some have not?
Why the variables a, c, d have not changed, but b has changed? a = 0 b = [] c = [] d = 'a' def func_a(a): a += 1 def func_b(b): b += [1] def func_c(c): c = [2] def func_d(d): d += 'd' func_a(a) func_b(b) func_c(c) func_d(d) print('a = ', a) print('b = ', b) prin...
[ "This is related by local and global scope, you can update using change the name of function parameter names;\na = 0\n\n\ndef func_a(local_a):\n global a\n a += 1\n\nfunc_a(a)\nprint('a = ', a)\n# output: a = 1\n\n\"global a\" meaning this function will use the global scope of a.\nIf you try to use with this...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074627501_python.txt
Q: How to install awscli using pip in library/node Docker image I'm trying to install awscli using pip (as per Amazon's recommendations) in a custom Docker image that comes FROM library/node:6.11.2. Here's a repro: FROM library/node:6.11.2 RUN apt-get update && \ apt-get install -y \ python \ pyt...
How to install awscli using pip in library/node Docker image
I'm trying to install awscli using pip (as per Amazon's recommendations) in a custom Docker image that comes FROM library/node:6.11.2. Here's a repro: FROM library/node:6.11.2 RUN apt-get update && \ apt-get install -y \ python \ python-pip \ python-setuptools \ groff \ less...
[ "Adding python-dev as per this other answer works, but throws an alarming number of compiler warnings (errors?), so I went with a variation of @SergeyKoralev's answer, which needed some tweaking before it worked.\nHere's the changes I needed to make this work:\n\nChange to python3 and pip3 everywhere.\nAdd a statem...
[ 28, 7, 5, 5, 0 ]
[]
[]
[ "amazon_web_services", "docker", "pip", "python" ]
stackoverflow_0046038891_amazon_web_services_docker_pip_python.txt
Q: Case-insensitve search using PyKeePass I am using PyKeePass to programatically access a KeePass database. This code: from pykeepass import PyKeePass try: kp = PyKeePass("info.kdbx", password="12345") except Exception, e: print "Got exception",e lstEntry = kp.find_entries_by_notes(".*Chocolate.*",regex=Tr...
Case-insensitve search using PyKeePass
I am using PyKeePass to programatically access a KeePass database. This code: from pykeepass import PyKeePass try: kp = PyKeePass("info.kdbx", password="12345") except Exception, e: print "Got exception",e lstEntry = kp.find_entries_by_notes(".*Chocolate.*",regex=True) print lstEntry print lstEntry[0].notes ...
[ "From the PyKeePass documentation, the syntax is:\n\nfind_entries_by_notes (notes, regex=False, flags=None, tree=None, history=False, first=False)\nwhere title, username, password, url, notes and path are strings. These functions have optional regex boolean and flags string arguments, which means to interpret the s...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0044909986_python.txt
Q: Printing value in a bytes class object I have a variable like this: result = b'{"Results": {"WebServiceOutput0": [{"Label": 7.0, "f0": 0.0, "f1": 0.0, "f2": 0.0, "f3": 0.0, "f4": 0.0, "f5": 0.0, "f6": 0.0, "f7": 0.0, "f8": 0.0, "f9": 0.0, "f10": 0.0, "f11": 0.0, "f12": 0.0, "f13": 0.0, "f14": 0.0, "f15": 0.0, "f1...
Printing value in a bytes class object
I have a variable like this: result = b'{"Results": {"WebServiceOutput0": [{"Label": 7.0, "f0": 0.0, "f1": 0.0, "f2": 0.0, "f3": 0.0, "f4": 0.0, "f5": 0.0, "f6": 0.0, "f7": 0.0, "f8": 0.0, "f9": 0.0, "f10": 0.0, "f11": 0.0, "f12": 0.0, "f13": 0.0, "f14": 0.0, "f15": 0.0, "f16": 0.0, "f17": 0.0, "f18": 0.0, "f19": 0.0,...
[ "You can use:\nimport json\nd = json.loads(result.decode('utf-8'))['Results']['WebServiceOutput0'][0]\n\nd['Scored Labels']\n# 1.7306872933250431e-07\n\nmax_p = max((k for k in d if k.startswith('Scored Probabilities_')), key=d.get)\n# 'Scored Probabilities_7'\n\nd[max_p]\n# 0.9999483485221952\n\n" ]
[ 1 ]
[]
[]
[ "max", "python" ]
stackoverflow_0074627798_max_python.txt
Q: How to post an image on a website with python requests Trying to post an image from file to this website [https://demo.neural-university.ru/emotion-recognition.html?ysclid=lauqlu1uq6710345308] It asks to post an image like this: curl -X POST -F "od_content=@1.jpg" https://srv2.demo.neural-university.ru/emotion_rec...
How to post an image on a website with python requests
Trying to post an image from file to this website [https://demo.neural-university.ru/emotion-recognition.html?ysclid=lauqlu1uq6710345308] It asks to post an image like this: curl -X POST -F "od_content=@1.jpg" https://srv2.demo.neural-university.ru/emotion_recognition/ I tried it with the file "user_photo_510495289.jpg...
[ "Are you sure this endpoint is not needed for authorization?\nI think it needs authorization, you can use it this code;\nimport requests\n\nurl = \"your URL\"\n\npayload={}\nfiles=[\n ('upload_file',('20220212235319_1509.jpg',open('/20220212235319_1509.jpg','rb'),'image/jpeg'))\n]\nheaders = {\n 'Accept-Language'...
[ 0 ]
[]
[]
[ "api", "python", "python_requests" ]
stackoverflow_0074627342_api_python_python_requests.txt
Q: Group by for time series - where dates matter I have the following information project stage date 33 New 3-sep-2022 33 New 10-sep-2022 33 Preparation 11-sep-2022 33 Preparation 21-sep-2022 33 Preparation 23-sep-2022 33 New 24-sep-2022 33 New 28-sep-2022 I want to get the information of the beginning and e...
Group by for time series - where dates matter
I have the following information project stage date 33 New 3-sep-2022 33 New 10-sep-2022 33 Preparation 11-sep-2022 33 Preparation 21-sep-2022 33 Preparation 23-sep-2022 33 New 24-sep-2022 33 New 28-sep-2022 I want to get the information of the beginning and end of each stage of the project, so ...
[ "You can use:\ndf['date'] = pd.to_datetime(df['date'])\n\ngroup = df['stage'].ne(df['stage'].shift()).cumsum()\n\nout = (df\n .groupby(['project', 'stage', group], sort=False)\n .agg(**{'begin_stage': ('date', 'min'), 'end_stage': ('date', 'max')})\n .droplevel(-1)\n .apply(lambda s: s.dt.strftime('%-d-%b-%...
[ 0 ]
[]
[]
[ "group_by", "pandas", "python", "time_series" ]
stackoverflow_0074627878_group_by_pandas_python_time_series.txt
Q: tokenize sentence to remove stop words: stop words are not being removed My code below should take a sentence from database, tokenize it by word and then remove stopwords accordingly. For some reason when I call the removestopwords function in my for loop it does not work. Any suggestions? When I call the removest...
tokenize sentence to remove stop words: stop words are not being removed
My code below should take a sentence from database, tokenize it by word and then remove stopwords accordingly. For some reason when I call the removestopwords function in my for loop it does not work. Any suggestions? When I call the removestopwords function with any inserted sentence it works just fine. import nltk im...
[ "I received an error when trying to run\nfrom nltk.corpus import stopwords\nThe documentation from NLTK says to use the following for stop words\n>>> import nltk\n>>> nltk.download()\n\nnltk.org/data.html\nOnce I used nltk.download() for the stopwords I slightly modified your function to incorporate list comprehens...
[ 0 ]
[]
[]
[ "for_loop", "python", "stop_words" ]
stackoverflow_0074627790_for_loop_python_stop_words.txt
Q: Why are attributes defined outside __init__ in popular packages like SQLAlchemy or Pydantic? I'm modifying an app, trying to use Pydantic for my application models and SQLAlchemy for my database models. I have existing classes, where I defined attributes inside the __init__ method as I was taught to do: class Meas...
Why are attributes defined outside __init__ in popular packages like SQLAlchemy or Pydantic?
I'm modifying an app, trying to use Pydantic for my application models and SQLAlchemy for my database models. I have existing classes, where I defined attributes inside the __init__ method as I was taught to do: class Measure: def __init__( self, t_received: int, mac_address: str, da...
[ "Defining attributes of a class in the class namespace directly is totally acceptable and is not special per se for the packages you mentioned. Since the class namespace is (among other things) essentially a blueprint for instances of that class, defining attributes there can actually be useful, when you want to e....
[ 1, 0 ]
[]
[]
[ "attributes", "class", "pydantic", "python", "sqlalchemy" ]
stackoverflow_0074612809_attributes_class_pydantic_python_sqlalchemy.txt
Q: Django - write Python code in an elegant way I have a situation as shown below: in models.py: class singer(models.Model): name = models.CharField() nickName = models.CharField() numSongs= models.IntegerField() class writer(models.Model): name = models.CharField() num...
Django - write Python code in an elegant way
I have a situation as shown below: in models.py: class singer(models.Model): name = models.CharField() nickName = models.CharField() numSongs= models.IntegerField() class writer(models.Model): name = models.CharField() numBooks = models.IntegerField() class weeklyTi...
[ "keep same table for singer/writer ans use type field. You can also filter easily.\nmodels.py be like:-\nartistTypes = (\n ('Singer', 'Singer'),\n ('Writer', 'Writer'),\n )\n\nclass artistName(models.Model):\n name = models.CharField()\n nickName = models.CharField()\n artistType = m...
[ 0 ]
[]
[]
[ "django", "django_models", "django_queryset", "django_rest_framework", "python" ]
stackoverflow_0074627398_django_django_models_django_queryset_django_rest_framework_python.txt
Q: How to pass dbfs path of local dependency wheel file in install_requires field of setup.py I am trying to install custom wheel file which requires another wheel file to install from databricks dbfs path. How to provide dbfs path in setup.py install_requires section . Note: I am aware of passing local path but not ...
How to pass dbfs path of local dependency wheel file in install_requires field of setup.py
I am trying to install custom wheel file which requires another wheel file to install from databricks dbfs path. How to provide dbfs path in setup.py install_requires section . Note: I am aware of passing local path but not dbfs path. Can someone help? I tried to provide path using dbfs:// but it did not work.
[ "You can directly install or upload wheel file as shown in the below image.\nGo to cluster -> install library\n\nFor more information refer this link to installing wheel file.\n" ]
[ 0 ]
[]
[]
[ "azure_databricks", "bigdata", "databricks", "python", "python_wheel" ]
stackoverflow_0074624872_azure_databricks_bigdata_databricks_python_python_wheel.txt
Q: How to use AutoML Library with IPU/TPU? I want to use AutoML Library Autogluon with Paperspace IPU/Kaggle TPU instance for specification reasons (big RAM, big space, and fast training time). For IPU, when I try to fit the Autogluon predictor class, the library only recognizes the available IPU but not using it. Ho...
How to use AutoML Library with IPU/TPU?
I want to use AutoML Library Autogluon with Paperspace IPU/Kaggle TPU instance for specification reasons (big RAM, big space, and fast training time). For IPU, when I try to fit the Autogluon predictor class, the library only recognizes the available IPU but not using it. How to make the Autogluon use the IPU? For TPU,...
[ "As far as I can tell, the Autogluon library does not currently support using IPUs. The Poplar SDK supports PyTorch and PyTorch Lightning, which Autogluon is based on, so the library could in principle be supported. I'd be really interested to hear more about what you want to use Autogluon for!\nIn the meantime, th...
[ 0 ]
[]
[]
[ "automl", "ipu", "python", "tpu" ]
stackoverflow_0074567293_automl_ipu_python_tpu.txt
Q: How to list of elements and use those elements as a header of pandas dataframe? I have a list with some elements. For example: list= [name, phone_number,age,gender] I want to use these elements as a header or column name in a pandas dataframe. I would really appreciate your ideas. A: Assuming you put all the val...
How to list of elements and use those elements as a header of pandas dataframe?
I have a list with some elements. For example: list= [name, phone_number,age,gender] I want to use these elements as a header or column name in a pandas dataframe. I would really appreciate your ideas.
[ "Assuming you put all the values ​​that will be used as headers into an array using this code:\nimport pandas as pd \ndata = pd.read_csv(\"yourtable.csv\")\ni = 0\nheaders = []\nwhile i < len(data. index):\n headers.append(data.loc[i, \"header of headers\"])\n i = i + 1\n\n\n\nYou can create your table using\nd...
[ 0 ]
[]
[]
[ "bigdata", "pandas", "python" ]
stackoverflow_0074627811_bigdata_pandas_python.txt
Q: Clustering of similar items There are items of data like this: item1 = { "path": "/some/path", "data": { "a": [0, 1, 2, ...], #numpy array "b": [4, 9, 4, ...], #numpy array "c": [7, 1, 0, ...], #numpy array } } And I compare each item with each other. After that I have pairs like this: pairs = [...
Clustering of similar items
There are items of data like this: item1 = { "path": "/some/path", "data": { "a": [0, 1, 2, ...], #numpy array "b": [4, 9, 4, ...], #numpy array "c": [7, 1, 0, ...], #numpy array } } And I compare each item with each other. After that I have pairs like this: pairs = [] pair = { "a": item1, "b": i...
[ "I found a solution. At first I reduced the item pairs by applying a threshold for diff (keep pairs having diff < 10000000).\nThen I run this code to create the clusters (groups):\ndef get_groups(self, pairs):\n\n def contains(list, filter):\n for x in list:\n if filter(x):\n ret...
[ 0 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074626666_numpy_pandas_python.txt
Q: A simple way of selecting the previous row in a column and performing an operation? I'm trying to create a forecast which takes the previous day's 'Forecast' total and adds it to the current day's 'Appt'. Something which is straightforward in Excel but I'm struggling in pandas. At the moment all I can get in pan...
A simple way of selecting the previous row in a column and performing an operation?
I'm trying to create a forecast which takes the previous day's 'Forecast' total and adds it to the current day's 'Appt'. Something which is straightforward in Excel but I'm struggling in pandas. At the moment all I can get in pandas using .loc is this: pd.DataFrame({'Date': ['2022-12-01', '2022-12-02','2022-12-03','2...
[ "You can use mask and cumsum:\ndf['Forecast'] = df['Forecast'].mask(df['Forecast'].eq(0), df['Appt']).cumsum()\n\n# or\ndf['Forecast'] = np.where(df['Forecast'].eq(0), df['Appt'], df['Forecast']).cumsum()\n\nOutput:\n Date Appt Forecast\n0 2022-12-01 12 37\n1 2022-12-01 10 47\n2 202...
[ 0, 0 ]
[]
[]
[ "pandas", "python", "time_series" ]
stackoverflow_0074627930_pandas_python_time_series.txt
Q: SDK is not defined for Run Configuration When I'm trying to run my project in PyCharm I'm getting an error: SDK is not defined for Run Configuration. I tried to set a new interpreter and tried everything. What does "SDK" mean and where can I configure it? A: I just had this same issue (see my comment above). W...
SDK is not defined for Run Configuration
When I'm trying to run my project in PyCharm I'm getting an error: SDK is not defined for Run Configuration. I tried to set a new interpreter and tried everything. What does "SDK" mean and where can I configure it?
[ "I just had this same issue (see my comment above). What worked for me was to go into \"Edit Configurations\", delete the configuration that was copied over from the original PC, and create my own configuration (basically with the same inputs as before).\n", "This might happen if a run configuration was imported ...
[ 2, 1, 0, 0 ]
[]
[]
[ "pycharm", "python" ]
stackoverflow_0074076140_pycharm_python.txt
Q: Converting .txt to .pdf I have code to convert a .txt file to a .pdf. I'm 99% sure that it converts the file to .pdf, but it won't output the PDF file. Below is my code. I got it from an online website, btw. from fpdf import FPDF pdf = FPDF() pdf.add_page() pdf.set_font("Arial", size=15) f = open("text-file-na...
Converting .txt to .pdf
I have code to convert a .txt file to a .pdf. I'm 99% sure that it converts the file to .pdf, but it won't output the PDF file. Below is my code. I got it from an online website, btw. from fpdf import FPDF pdf = FPDF() pdf.add_page() pdf.set_font("Arial", size=15) f = open("text-file-name.txt", "r") for x in f: ...
[ "There are 2 things to be aware of:\n\nNot every encoding (in your case latin-1) can represent every possible character. An encoding maps bit-patterns to characters. An encoding that uses 7 bits (and an 8th check-bit) is only able to represent 2^7 characters. The designers of the encoding thus have to make decision...
[ 0 ]
[]
[]
[ "pdf", "python", "replit", "txt" ]
stackoverflow_0074555378_pdf_python_replit_txt.txt
Q: Pillow not recognizing Libraqm installation on Mac OS I need to be able to render text in python in various fonts and using various writing systems that use variable substitution of characters (Arabic, Hindi, Bengali). On a previous machine I had no issue doing this, but I just moved into a new machine with the sa...
Pillow not recognizing Libraqm installation on Mac OS
I need to be able to render text in python in various fonts and using various writing systems that use variable substitution of characters (Arabic, Hindi, Bengali). On a previous machine I had no issue doing this, but I just moved into a new machine with the same conda environment and it doesn't seme to work. Mac OS 12...
[ "On Mac Os 12.6.1 and Python 3.10.8 System Interpreter I was able to get libraqm to work with Pillow. Configuration follows:\n\nPython Interpreter version 10.8 installed with Homebrew.\nLibraqm version 0.9.0 installed with Homebrew.\nPillow version 9.3.0 installed with pip.\n\nFirst, I tried using a python venv, a...
[ 0, 0 ]
[]
[]
[ "image_processing", "python", "python_3.x", "python_imaging_library" ]
stackoverflow_0074608140_image_processing_python_python_3.x_python_imaging_library.txt
Q: Why am I getting wrong matrix I'm trying to print the following matrix and vector, A = np.array ([[2,1,4,1], [3,4,-1,-1] , [1,-4,1,5] , [2,-2,1,3]], float) v = np.array([-4, 3, 9, 7], float) But I'm getting this instead A = [[ 1. 0.5 2. 0.5] [ 0. 1. -2.8 -1. ] [-0. -0. 1. -0. ] [-0. -0. -0. 1....
Why am I getting wrong matrix
I'm trying to print the following matrix and vector, A = np.array ([[2,1,4,1], [3,4,-1,-1] , [1,-4,1,5] , [2,-2,1,3]], float) v = np.array([-4, 3, 9, 7], float) But I'm getting this instead A = [[ 1. 0.5 2. 0.5] [ 0. 1. -2.8 -1. ] [-0. -0. 1. -0. ] [-0. -0. -0. 1. ]] v = [-2. 3.6 -2. 1. ] If ...
[ "I guess right syntax is this?\nimport numpy as np\nA = np.array ([[2,1,4,1], [3,4,-1,-1] , [1,-4,1,5] , [2,-2,1,3]], dtype = float)\nprint(A)\n\nGives #\n[[ 2. 1. 4. 1.]\n [ 3. 4. -1. -1.]\n [ 1. -4. 1. 5.]\n [ 2. -2. 1. 3.]]\n\n" ]
[ 1 ]
[]
[]
[ "matrix", "numpy", "python", "vector" ]
stackoverflow_0074628036_matrix_numpy_python_vector.txt
Q: Django Bash completion not working on manage.py I am trying out the django_bash_completion script provided by Django but can't use it with python manage.py command. I am trying out the django_bash_completion script provided by Django. I have added it to active script in the virtual environment. It works with djang...
Django Bash completion not working on manage.py
I am trying out the django_bash_completion script provided by Django but can't use it with python manage.py command. I am trying out the django_bash_completion script provided by Django. I have added it to active script in the virtual environment. It works with django-admin but can't use it with python manage.py comman...
[ "You have to run manage.py <tab><tab> not python manage.py <tab><tab>\nAs the Official Documentation says: https://docs.djangoproject.com/en/dev/ref/django-admin/#bash-completion\n", "I've been using this old original bash-completion for Django. still works :) you don't need to ./manage.py ... try python manage.p...
[ 4, 0 ]
[]
[]
[ "bash_completion", "django", "django_manage.py", "python" ]
stackoverflow_0057937578_bash_completion_django_django_manage.py_python.txt
Q: python, pygsheets question - how to gain the color of each cell in a column, fast? i have this code, that checks color of each cell in a google sheets worksheet. that would be ok, but for 1200 rows, it takes 400 seconds to do so, so i wanted to ask if someone know of a better way to check color of a each cell in a...
python, pygsheets question - how to gain the color of each cell in a column, fast?
i have this code, that checks color of each cell in a google sheets worksheet. that would be ok, but for 1200 rows, it takes 400 seconds to do so, so i wanted to ask if someone know of a better way to check color of a each cell in a column(i couldnt find how to check only 1 column, and not the whole sheet), and put it ...
[ "I believe your goal is as follows.\n\nYou want to retrieve the values from only one column instead of all cells.\nYou want to achieve this using pygsheets.\n\nIn this case, how about using get_col instead of get_all_values? When this is reflected in your script, how about the following modification?\nFrom:\ncells ...
[ 0 ]
[]
[]
[ "google_sheets", "google_sheets_api", "pygsheets", "python" ]
stackoverflow_0074627208_google_sheets_google_sheets_api_pygsheets_python.txt
Q: Find the top N keys with highest values in Redis I have Redis database with user_id: rating stucture and I need to get the N users with the highest rating (value), like: u_345: 198 u_144: 180 u_267: 179 The idea I have: take a list of all the keys, and for each key get its value (db.mget(db.keys())), after sort b...
Find the top N keys with highest values in Redis
I have Redis database with user_id: rating stucture and I need to get the N users with the highest rating (value), like: u_345: 198 u_144: 180 u_267: 179 The idea I have: take a list of all the keys, and for each key get its value (db.mget(db.keys())), after sort by value and get first N. Is there a better way? I use ...
[ "It seems like you should follow the pattern of using Sorted Set as a secondary index.\nSee: https://redis.io/topics/indexes\n", "You should use ZRANGE (https://redis.io/commands/zrange/).\nUsing your dataset, you could use this approach:\nZADD ratingindex 198 u_345\nZADD ratingindex 180 u_144\nZADD ratingindex 1...
[ 2, 1 ]
[]
[]
[ "python", "redis" ]
stackoverflow_0058252864_python_redis.txt
Q: how to convert xls to xlsx I have some *.xls (excel 2003) files, and I want to convert those files into xlsx (excel 2007). I use the uno python package, when I save the documents, I can set the Filter name: MS Excel 97 But there is no Filter name like 'MS Excel 2007', How can set the the filter name to convert xls...
how to convert xls to xlsx
I have some *.xls (excel 2003) files, and I want to convert those files into xlsx (excel 2007). I use the uno python package, when I save the documents, I can set the Filter name: MS Excel 97 But there is no Filter name like 'MS Excel 2007', How can set the the filter name to convert xls to xlsx ?
[ "You need to have win32com installed on your machine. Here is my code:\nimport win32com.client as win32\nfname = \"full+path+to+xls_file\"\nexcel = win32.gencache.EnsureDispatch('Excel.Application')\nwb = excel.Workbooks.Open(fname)\n\nwb.SaveAs(fname+\"x\", FileFormat = 51) #FileFormat = 51 is for .xlsx extensi...
[ 44, 27, 23, 12, 7, 6, 6, 3, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "python", "uno" ]
stackoverflow_0009918646_python_uno.txt
Q: How to set new values to row based on the same substring from other column? This is an example of a bigger data. Imagine I have a dataframe like this: df = pd.DataFrame({"CLASS":["AG_1","AG_2","AG_3","MAR","GOM"], "TOP":[200, np.nan, np.nan, 600, np.nan], "BOT":[230, 250, 380,...
How to set new values to row based on the same substring from other column?
This is an example of a bigger data. Imagine I have a dataframe like this: df = pd.DataFrame({"CLASS":["AG_1","AG_2","AG_3","MAR","GOM"], "TOP":[200, np.nan, np.nan, 600, np.nan], "BOT":[230, 250, 380, np.nan, 640]}) df Out[49]: CLASS TOP BOT 0 AG_1 200.0 230.0 1 AG_2...
[ "generic case: filling all groups\nI would use fillna with a groupby.shift using a custom group extracting the substring from CLASS with str.extract:\ngroup = df['CLASS'].str.extract('([^_]+)', expand=False)\ndf['TOP'] = df['TOP'].fillna(df.groupby(group)['BOT'].shift())\n\nOutput:\n CLASS TOP BOT\n0 AG_1 ...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074628225_pandas_python.txt
Q: How to save duplicate records in SQLAlchemy? I'm creating an application where it simulates a football album for each user, the logic is that each user can open packages and receive players that in the future can be associated with teams that the user himself created. To save all the players that a user can receiv...
How to save duplicate records in SQLAlchemy?
I'm creating an application where it simulates a football album for each user, the logic is that each user can open packages and receive players that in the future can be associated with teams that the user himself created. To save all the players that a user can receive I created a Player model ( many-to-many relation...
[ "To me it looks like you need an intermediate table. You have a db.Model \"Player\" with basic information as on a player card. Then a \"User\" and a \"Team\" model. The team has a relation to the user, now you create a \"UserCollection\" db.Model, which contains references such as PlayerId, UserId and TeamId if se...
[ 0 ]
[ "You should use \"ManytoManyField\" like this;\nfrom django.db import models\n\nclass Publication(models.Model):\n title = models.CharField(max_length=30)\n\n class Meta:\n ordering = ['title']\n\n def __str__(self):\n return self.title\n\nclass Article(models.Model):\n headline = models.C...
[ -1 ]
[ "database_design", "python", "sqlalchemy" ]
stackoverflow_0074628003_database_design_python_sqlalchemy.txt
Q: How to group tuples with adjacent indices in a python 2-dimensional tuple? How to group tuples with adjacent indices in a python 2-dimensional tuple? I'm not familiar with the zip function yet. I've written the code like this, but it doesn't work very well. Any help would be appreciated. Thank you!! coords = ((1, ...
How to group tuples with adjacent indices in a python 2-dimensional tuple?
How to group tuples with adjacent indices in a python 2-dimensional tuple? I'm not familiar with the zip function yet. I've written the code like this, but it doesn't work very well. Any help would be appreciated. Thank you!! coords = ((1, 2), (3, 4), (5, 6), (7, 8)) coords = tuple(zip(coords[0::2], coords[1::2])) prin...
[ "Your code was almost there. This is one way you can make it work,\ncoords = ((1, 2), (3, 4), (5, 6), (7, 8))\n\ncoords = tuple(x + y for x, y in zip(coords[0::2], coords[1::2]))\n\nLike in your code, it loops through two slices of coords using zip. But now it takes each element of the two slices (x and y) and adds...
[ 8, 2 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0074628099_python_tuples.txt
Q: How to stop functions from giving errors when using variables not defined in the function? I am creating several experiments in python and have various functions which will be common across these experiments. I thus wanted to create a script only containing these functions which I could import at the beginning of ...
How to stop functions from giving errors when using variables not defined in the function?
I am creating several experiments in python and have various functions which will be common across these experiments. I thus wanted to create a script only containing these functions which I could import at the beginning of the experimental script to avoid half of the script being taken up with 'generic setup lines'. S...
[ "You can pass on the win you want blanked out as an argument to the blank_screen function:\nimport functions \nwin = visual.Window([1440,900], color=[-1,-1,-1], fullscr=True)\ndur = 4\nfunctions.blank_screen(duration=dur, win=win)\n\nand\ndef blank_screen(duration, win):\n blank = TextStim(win, text='')\n bla...
[ 4 ]
[]
[]
[ "function", "python" ]
stackoverflow_0074628261_function_python.txt
Q: How can I convert an undirected graph generated by the Barabasi-Albert model to a directed one? I have used the Barabasi-Albert model in networkx to generate a graph with n=200 and m=2. This gives me an undirected graph but I want a directed graph so that I can plot the in and out degree distributions. Would plott...
How can I convert an undirected graph generated by the Barabasi-Albert model to a directed one?
I have used the Barabasi-Albert model in networkx to generate a graph with n=200 and m=2. This gives me an undirected graph but I want a directed graph so that I can plot the in and out degree distributions. Would plotting the in and out degrees be possible? This is my code: N=200 m=2 G_barabasi=nx.barabasi_albert_grap...
[ "An easy way is to use the .to_directed method on the existing graph:\nfrom networkx import barabasi_albert_graph\nG = barabasi_albert_graph(200, 2)\nprint(G.is_directed())\n# False\nG_directed = G.to_directed()\nprint(G_directed.is_directed())\n# True\n\n" ]
[ 0 ]
[]
[]
[ "complex_networks", "graph", "graph_theory", "networkx", "python" ]
stackoverflow_0074628089_complex_networks_graph_graph_theory_networkx_python.txt
Q: Pygame program keeps crashing and the display window won't cooperate, Trying to design and call open a basic customized pygame window that pops up right after the program starts. The window I'm producing gets minimized by default instead of just opening. It's also not updating the color, and it immediately crashes...
Pygame program keeps crashing and the display window won't cooperate,
Trying to design and call open a basic customized pygame window that pops up right after the program starts. The window I'm producing gets minimized by default instead of just opening. It's also not updating the color, and it immediately crashes when I open the tab that it's in. # I'm running Windows 10 with Spyder (Py...
[ "The problem is in the following line:\nif __name__ == \"__space_shooter__\":\n\nThe __name__ variable will not contain the file name of the current script. If the script is ran directly, it will contain \"__main__\". If the script is imported by another script, it will contain the file name of that other script.\n...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074623774_python.txt
Q: Attaching a decorator to all functions within a class I don't really need to do this, but was just wondering, is there a way to bind a decorator to all functions within a class generically, rather than explicitly stating it for every function. I suppose it then becomes a kind of aspect, rather than a decorator and...
Attaching a decorator to all functions within a class
I don't really need to do this, but was just wondering, is there a way to bind a decorator to all functions within a class generically, rather than explicitly stating it for every function. I suppose it then becomes a kind of aspect, rather than a decorator and it does feel a bit odd, but was thinking for something lik...
[ "The cleanest way to do this, or to do other modifications to a class definition, is to define a metaclass.\nAlternatively, just apply your decorator at the end of the class definition using inspect:\nimport inspect\n\nclass Something:\n def foo(self): \n pass\n\nfor name, fn in inspect.getmembers(Somethi...
[ 42, 37, 12, 7, 2, 2, 0, 0, 0 ]
[ "You could override the __getattr__ method. It's not actually attaching a decorator, but it lets you return a decorated method. You'd probably want to do something like this:\nclass Eggs(object):\n def __getattr__(self, attr):\n return decorate(getattr(self, `_` + attr))\n\nThere's some ugly recursion hid...
[ -1 ]
[ "class", "class_method", "decorator", "oop", "python" ]
stackoverflow_0003467526_class_class_method_decorator_oop_python.txt
Q: K Prototype initialization kept repeating initializing centroids and initializing clusters step I am working on implementing k-Prototype clustering in Python. The data frame shape is (1870995, 28). I have set kproto = KPrototypes(n_clusters=3, verbose=2,max_iter=20). However, the initialization keeps repeating "in...
K Prototype initialization kept repeating initializing centroids and initializing clusters step
I am working on implementing k-Prototype clustering in Python. The data frame shape is (1870995, 28). I have set kproto = KPrototypes(n_clusters=3, verbose=2,max_iter=20). However, the initialization keeps repeating "initializing centroids" and "initializing clusters" and doesn't start iteration steps. Is my data fram...
[ "I believe what you have is calling the proto method, you should also call the fit_predict method on it, something like below:\nkproto = KPrototypes(n_clusters=3, verbose=2, max_iter=20).\n\nkproto.fit_predict(df, categorical=[3, 4, 5]) # categorical column indices\n\n" ]
[ 0 ]
[]
[]
[ "arrays", "cluster_analysis", "prototype", "python" ]
stackoverflow_0072814400_arrays_cluster_analysis_prototype_python.txt
Q: Problems to connect SFTP with SSH and passprash in Synapse with Python I am trying to connect to a SFTP that use username, passphrase, SSH key (no password needed) in notebook in Synapse. SSH key is kept as a secreat in Key Vault. Have runned into different errors so far: Host = "sftp.xxxxx.no" Username = "xxxxx"...
Problems to connect SFTP with SSH and passprash in Synapse with Python
I am trying to connect to a SFTP that use username, passphrase, SSH key (no password needed) in notebook in Synapse. SSH key is kept as a secreat in Key Vault. Have runned into different errors so far: Host = "sftp.xxxxx.no" Username = "xxxxx" Passphrase = "xxxxx" port = 22 from notebookutils import mssparkutils SSHk...
[ "You have public key stored in your key vault. Not a private key.\nYou cannot authenticate using public key. You have to store the private key to the vault.\n" ]
[ 0 ]
[]
[]
[ "azure_synapse", "python", "sftp" ]
stackoverflow_0074597291_azure_synapse_python_sftp.txt
Q: How to include flags using condition in pyspark dataframe i have a dataframe as shown below df: id vehicle production asIs EU EU_variant status 1 A3345 PQ1298 FV1 FV1_variant OK 2 A3346 A3346 PQ1287 FV2 FV2_variant NOT_OK 3 A3346 A3346 PQ1207...
How to include flags using condition in pyspark dataframe
i have a dataframe as shown below df: id vehicle production asIs EU EU_variant status 1 A3345 PQ1298 FV1 FV1_variant OK 2 A3346 A3346 PQ1287 FV2 FV2_variant NOT_OK 3 A3346 A3346 PQ1207 FV2 FV2_variant NOT_OK 4 A3347 ...
[ "You can use collect_set on status field to get the distinct statuses on your desired partition. use the result to flag the records. collect_set returns an array field which can be used to check the length (using size) and its contents (using array_contains).\nsee example below\ndata_sdf. \\\n withColumn('vehicl...
[ 1 ]
[]
[]
[ "pyspark", "python", "python_3.x" ]
stackoverflow_0074627447_pyspark_python_python_3.x.txt
Q: Misunderstanding numpy.vectorize I want to apply a function to each row in a vector. Even on a simple example like the one below I cant get it to work. I make a function that takes two vectors and applies the dot product to them. import numpy as np def func(x,y): return np.dot(x,y) y=np.array([0, 1, 2]) x=np...
Misunderstanding numpy.vectorize
I want to apply a function to each row in a vector. Even on a simple example like the one below I cant get it to work. I make a function that takes two vectors and applies the dot product to them. import numpy as np def func(x,y): return np.dot(x,y) y=np.array([0, 1, 2]) x=np.array([0, 1, 2]) print(func(x,y)) ...
[ "The first trick to do is to exclude y argument (it is a fixed value\nfor all rows from x).\nThe second trick is to pass the signature: Both arguments are arrays and\nthe result is a scalar.\nSo, to vectorize your function, run:\nvfunc = np.vectorize(func, excluded=['y'], signature='(n),(n)->()')\n\nThen, when you ...
[ 1 ]
[]
[]
[ "arrays", "function", "numpy", "python", "vectorization" ]
stackoverflow_0074627108_arrays_function_numpy_python_vectorization.txt
Q: (Django) Why my login only work for db table:auth_user can't work another table:myapp_user? Sorry bad English! I have a login function in my project like: from django.contrib.auth.forms import AuthenticationForm from django.contrib import auth from django.http import HttpResponseRedirect from django.shortcuts impo...
(Django) Why my login only work for db table:auth_user can't work another table:myapp_user?
Sorry bad English! I have a login function in my project like: from django.contrib.auth.forms import AuthenticationForm from django.contrib import auth from django.http import HttpResponseRedirect from django.shortcuts import render def log_in(request): form = AuthenticationForm(request.POST) if request.metho...
[ "Did you add custom user model in settings.py file\nadd following line in settings.py\nreplace users with your app name in which your custom User model is present\nAUTH_USER_MODEL = 'users.User'\n\n" ]
[ 0 ]
[]
[]
[ "django", "postgresql", "python" ]
stackoverflow_0074628103_django_postgresql_python.txt
Q: Django invalid literal for int() with base 10: '??????? ???????' when i try to migrate I'm trying to create a new tables in a new app added to my project .. makemigrations worked great but migrate is not working .. here is my models blog/models.py from django.db import models # Create your models here. from fosta...
Django invalid literal for int() with base 10: '??????? ???????' when i try to migrate
I'm trying to create a new tables in a new app added to my project .. makemigrations worked great but migrate is not working .. here is my models blog/models.py from django.db import models # Create your models here. from fostania_web_app.models import UserModel class Tag(models.Model): tag_name = models.CharFie...
[ "Error message: ValueError: invalid literal for int() with base 10: '??? ??? ?????'\nAs per exception int() with base 10: '??? ??? ?????' doesn't qualify as int.\nCheck in blog.0001_initial migrations for '??? ??? ?????' and modify that value with a valid int.\nYou might have accidentally provided garbage default v...
[ 5, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0050991402_django_python.txt
Q: Fill by group and between two values I want to fill all rows between two values by group. For each group, var1 has two values equal to 1, and I want to fill the missing rows between the two 1s. var1 represents what I have, var2 represents what I want, var3 shows what I am obtaining with my code, but it is not what...
Fill by group and between two values
I want to fill all rows between two values by group. For each group, var1 has two values equal to 1, and I want to fill the missing rows between the two 1s. var1 represents what I have, var2 represents what I want, var3 shows what I am obtaining with my code, but it is not what I want (different from var2): var1 group ...
[ "Assuming the values are only 1 or NaN, you can groupby.ffill and groupby.bfill and only keep the values that are identical:\ng = df.groupby('group')['var1']\n\ns1 = g.ffill()\ns2 = g.bfill()\n\ndf['var2'] = s1.where(s1.eq(s2))\n\nOutput:\n var1 group var2\n0 NaN 1 NaN\n1 NaN 1 NaN\n2 1....
[ 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074628433_dataframe_pandas_python.txt
Q: Can we add an extension using python sdk compute_client.virtual_machines.begin_create_or_update to Azure VM it creates? Morning, I have a need to have the AADLoginForLinux extension added to the vms I spin up with the python sdk compute_client.virtual_machines.begin_create_or_update call. I see I could maybe do a ...
Can we add an extension using python sdk compute_client.virtual_machines.begin_create_or_update to Azure VM it creates?
Morning, I have a need to have the AADLoginForLinux extension added to the vms I spin up with the python sdk compute_client.virtual_machines.begin_create_or_update call. I see I could maybe do a rest call to add extensions, but I was wondering if it could be done with the sdk call instead? Anybody have a sample/exampl...
[ "I tried to reproduce the same in my environment and got the below results:\nI created an Azure Virtual Machine using the below code:\ncredential = AzureCliCredential()\nsubscription_id = os.environ[\"AZURE_SUBSCRIPTION_ID\"] = \"XXXXXXXX\"\nresource_client = ResourceManagementClient(credential, subscription_id)\nR...
[ 1 ]
[]
[]
[ "azure", "python", "sdk", "virtual_machine" ]
stackoverflow_0074477495_azure_python_sdk_virtual_machine.txt
Q: By Knowing class name, how to get class key with its default value | PYTHON I have multiple class in one file(a.py). On other file (b.py) i know some class name. In same file b.py i need the complete key, value of the class. a.py file: class CarCompany(BaseModel): audi: Optional[str] = 'Good' bmw: Optional...
By Knowing class name, how to get class key with its default value | PYTHON
I have multiple class in one file(a.py). On other file (b.py) i know some class name. In same file b.py i need the complete key, value of the class. a.py file: class CarCompany(BaseModel): audi: Optional[str] = 'Good' bmw: Optional[str] = 'Good' tata: Optional[str] = 'Good'` class CarYear(BaseModel): 2...
[ "I got the solution by\nvar_dict = final_var.__class__.__dict__\nall_fields = var_dict['__fields__']\n\ndefault_val = next((v.__getattribute__('default') for i, v in all_fields.items()), None)\n\n" ]
[ 0 ]
[]
[]
[ "pydantic", "python", "python_3.x" ]
stackoverflow_0074598965_pydantic_python_python_3.x.txt
Q: displaying grid of images in jupyter notebook I have a dataframe with a column containing 495 rows of URLs. I want to display these URLs in jupyter notebook as a grid of images. The first row of the dataframe is shown here. Any help is appreciated. id latitude longitude owner title ...
displaying grid of images in jupyter notebook
I have a dataframe with a column containing 495 rows of URLs. I want to display these URLs in jupyter notebook as a grid of images. The first row of the dataframe is shown here. Any help is appreciated. id latitude longitude owner title url 23969985288 37.721238 ...
[ "Your idea of using IPython.core.display with HTML is imho the best approach for that kind of task. matplotlib is super inefficient when it comes to plotting such a huge number of images (especially if you have them as URLs).\nThere's a small package I built based on that concept - it's called ipyplot\nimport ipypl...
[ 15, 7, 0 ]
[ "I can only do it by \"brute force\":\nHowever, I only manage to do it manually:\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\n%matplotlib inline\n\nimg1=mpimg.imread('Variable_8.png')\nimg2=mpimg.imread('Variable_17.png')\nimg3=mpimg.imread('Variable_18.png')\n ...\n\nfig, ((ax1, a...
[ -2 ]
[ "html", "jupyter_notebook", "matplotlib", "python" ]
stackoverflow_0047508168_html_jupyter_notebook_matplotlib_python.txt
Q: django gives me error 404 when i try to use unicode urls there is a problem when django uses Arabic slugs . It can accepts them . But when you go for its url . It can't find a matching query in database for them . It gives me 404 . this is the urls.py and my url : from django.urls import path , re_path from django...
django gives me error 404 when i try to use unicode urls
there is a problem when django uses Arabic slugs . It can accepts them . But when you go for its url . It can't find a matching query in database for them . It gives me 404 . this is the urls.py and my url : from django.urls import path , re_path from django.contrib.sitemaps import GenericSitemap from .models import C...
[ "The problem is not the Arabic characters, but the underscore. You can include it with:\nre_path(r'detail/(?P<slug>[\\w_-]+)/$', detail_course, name='detail_courses')\nThat being said, normally a slug does not contain an underscore, so your slugging algorithm does not seem to work properly.\nYou can use Django's sl...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074628492_django_python.txt
Q: Python pytest hangs. For instance, "pytest --version" simply hangs The following hangs: PS C:\Users\Fowler> pytest --version Notes: I am in Windows 10. By hang, I mean at least 5 minutes of waiting for the pytest --version to return... While waiting for pytest, python.exe is using 100% of a logical processor o...
Python pytest hangs. For instance, "pytest --version" simply hangs
The following hangs: PS C:\Users\Fowler> pytest --version Notes: I am in Windows 10. By hang, I mean at least 5 minutes of waiting for the pytest --version to return... While waiting for pytest, python.exe is using 100% of a logical processor on my computer. I uninstalled all python installations with windows insta...
[ "Fixed. \nThe answer appears to be \n\nUninstall python via the windows apps and features\nRemove the c:\\program files\\python38 directory\nRemove the ..\\AppData\\Roaming\\Python directory\nReinstall\n\nNot sure what the \"root\" problem was, but a total wipe of python fixed it. Note that the python windows ins...
[ 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "pytest", "python" ]
stackoverflow_0059043307_pytest_python.txt
Q: How to visualize communities from a list in igraph python I have a community list as the following list_community. How do I edit the code below to make the community visible? from igraph import * list_community = [['A', 'B', 'C', 'D'],['E','F','G'],['G', 'H','I','J']] list_nodes = ['A', 'B', 'C', 'D','E','F','G',...
How to visualize communities from a list in igraph python
I have a community list as the following list_community. How do I edit the code below to make the community visible? from igraph import * list_community = [['A', 'B', 'C', 'D'],['E','F','G'],['G', 'H','I','J']] list_nodes = ['A', 'B', 'C', 'D','E','F','G','H','I','J'] tuple_edges = [('A','B'),('A','C'),('A','D'),('B',...
[ "In igraph you can use the VertexCover to draw polygons around clusters (as also suggested by Szabolcs in his comment). You have to supply the option mark_groups when plotting the cover, possibly with some additional palette if you want. See some more detail in the documentation here.\nIn order to construct the Ver...
[ 2, 1 ]
[]
[]
[ "graph", "igraph", "networking", "python", "visualization" ]
stackoverflow_0074597504_graph_igraph_networking_python_visualization.txt
Q: OR operation not working in removing string part I've been trying to parse a string and to get rid of parts of the string using the remove() function. In order to find the part which I wanted to remove I used an OR operator. However, it does not produce the outcome I expected. Can you help me? My code looks like t...
OR operation not working in removing string part
I've been trying to parse a string and to get rid of parts of the string using the remove() function. In order to find the part which I wanted to remove I used an OR operator. However, it does not produce the outcome I expected. Can you help me? My code looks like this: import numpy as np x = '-1,0;1,0;0,-1;0,+1' x =...
[ "Modifying lists that you are currently itterating over is not a good approch. Instead take a new list and append values in else.\nx = '-1,0;1,0;0,-1;0,+1'\n\nx = x.split(';')\n\nnew = []\n\nfor i in x:\n if ('+' in i) or ('-' in i):\n pass\n else:\n new.append(i)\n \nx = ';'.join(new) \np...
[ 2, 1 ]
[]
[]
[ "conditional_statements", "if_statement", "python" ]
stackoverflow_0074628308_conditional_statements_if_statement_python.txt
Q: How to make a nested array in python I have a python dictionary (league_managers) showing Ids to names; {1443956: 'Sean McBride', 1281609: 'Maghnus Og Dunne', 4841686: 'Pearse Bowes', 406739: 'Adam Mcconville', 196345: 'Niall McCurdy', 808057: 'John McDonald', 6365597: 'Tony Cassidy', 1322001: 'Tiarnan Mccaffrey',...
How to make a nested array in python
I have a python dictionary (league_managers) showing Ids to names; {1443956: 'Sean McBride', 1281609: 'Maghnus Og Dunne', 4841686: 'Pearse Bowes', 406739: 'Adam Mcconville', 196345: 'Niall McCurdy', 808057: 'John McDonald', 6365597: 'Tony Cassidy', 1322001: 'Tiarnan Mccaffrey', 350275: 'Eoghan McCurdy', 4820159: 'Ciara...
[ "def get_event(id): #call your event api here\n return str(id) + \"_event\"\n\ndef get_points(): #call your points api here\n return 100\n\n\nd = {1443956: 'Sean McBride', 1281609: 'Maghnus Og Dunne', 4841686: 'Pearse Bowes', 406739: 'Adam Mcconville', 196345: 'Niall McCurdy', 808057: 'John McDonald', 6365597...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074628467_python.txt
Q: Error: Failure while executing; `cp -pR /private/tmp/d20221129-9397-882a6m/ca-certificates/. /usr/local/Cellar/ca-certificates` exited with 1 When i install python by brew, it shows error: cp: /private/tmp/d20221129-9397-882a6m/ca-certificates/./2022-10-11: unable to copy ACL to /usr/local/Cellar/ca-certificates/....
Error: Failure while executing; `cp -pR /private/tmp/d20221129-9397-882a6m/ca-certificates/. /usr/local/Cellar/ca-certificates` exited with 1
When i install python by brew, it shows error: cp: /private/tmp/d20221129-9397-882a6m/ca-certificates/./2022-10-11: unable to copy ACL to /usr/local/Cellar/ca-certificates/./2022-10-11: Permission denied cp: utimensat: /usr/local/Cellar/ca-certificates/.: Permission denied Error: Failure while executing; `cp -pR /priva...
[ "I had the same issue and managed to fix it the following way:\nI saw that the upgrade script tried to copy files from\n/private/tmp/d20221130-21318-e53mkn/ca-certificates/./2022-10-11 to /usr/local/Cellar/ca-certificates/./2022-10-11 and I got a Permission denied meaning - I (the current mac user) could not edit/c...
[ 0 ]
[]
[]
[ "homebrew", "python" ]
stackoverflow_0074608872_homebrew_python.txt
Q: Converting Mathematica Fourier series code to Python I have some simple Mathematica code that I'm struggling to convert to Python and could use some help: a = ((-1)^(n))*4/(Pi*(2 n + 1)); f = a*Cos[(2 n + 1)*t]; sum = Sum[f, {n, 0, 10}]; Plot[sum, {t, -2 \[Pi], 2 \[Pi]}] The plot looks like this: For context, I...
Converting Mathematica Fourier series code to Python
I have some simple Mathematica code that I'm struggling to convert to Python and could use some help: a = ((-1)^(n))*4/(Pi*(2 n + 1)); f = a*Cos[(2 n + 1)*t]; sum = Sum[f, {n, 0, 10}]; Plot[sum, {t, -2 \[Pi], 2 \[Pi]}] The plot looks like this: For context, I have a function f(t): I need to plot the sum of the firs...
[ "modifying your code, look the part which are different, mostly the mistake was in the part which you are not calculating based on n 0-10 :\nn = np.arange(0,10)\nt = np.linspace(-2 * np.pi, 2 *np.pi, 10000)\ndef a(n):\n return ((-1)**(n))*4/(np.pi*(2*n+1))\nf = 0\nfor i in n:\n f += a(i)*np.cos((2*i +1) * t)\...
[ 0 ]
[]
[]
[ "fft", "python", "wolfram_mathematica" ]
stackoverflow_0074623175_fft_python_wolfram_mathematica.txt
Q: Read ZIP files from S3 without downloading the entire file We have ZIP files that are 5-10GB in size. The typical ZIP file has 5-10 internal files, each 1-5 GB in size uncompressed. I have a nice set of Python tools for reading these files. Basically, I can open a filename and if there is a ZIP file, the tools se...
Read ZIP files from S3 without downloading the entire file
We have ZIP files that are 5-10GB in size. The typical ZIP file has 5-10 internal files, each 1-5 GB in size uncompressed. I have a nice set of Python tools for reading these files. Basically, I can open a filename and if there is a ZIP file, the tools search in the ZIP file and then open the compressed file. It's all...
[ "Here's an approach which does not need to fetch the entire file (full version available here).\nIt does require boto (or boto3), though (unless you can mimic the ranged GETs via AWS CLI; which I guess is quite possible as well).\nimport sys\nimport zlib\nimport zipfile\nimport io\n\nimport boto\nfrom boto.s3.conne...
[ 6, 3, 2, 0 ]
[]
[]
[ "amazon_s3", "boto", "boto3", "python", "zip" ]
stackoverflow_0051351000_amazon_s3_boto_boto3_python_zip.txt
Q: Pre-existing high-contrast palettes from the ANSI color set, to use in a terminal app? Looking to convey more information in a Rich Table by using colors (specifically to track which modules given classes come from). On the web, it's fairly easy on find color palettes that are optimized for contrast, rather than e...
Pre-existing high-contrast palettes from the ANSI color set, to use in a terminal app?
Looking to convey more information in a Rich Table by using colors (specifically to track which modules given classes come from). On the web, it's fairly easy on find color palettes that are optimized for contrast, rather than esthetics. Here's a 6 color example. Then it's just question of using the RGB/HSL specs to ...
[ "OK, well, that was simple, no need to mess around with from_rgb, because of what styles support.\nAnd, after reading Will's answer, I've modified my original solution to use saved themes. Thanks again for an awesome library, Will!\n\nAlternatively you can use a CSS-like syntax to specify a color with a “#” follow...
[ 1, 1 ]
[]
[]
[ "python", "rich", "tui" ]
stackoverflow_0074608971_python_rich_tui.txt
Q: python program to return exit code 0 if passes and 1 if fails I have a text file that includes a word like "test". Now what i am trying to do is using python i am opening that text file and search for that word. If the word exists then the python program should return exit code 0 or else 1. This is the code that i...
python program to return exit code 0 if passes and 1 if fails
I have a text file that includes a word like "test". Now what i am trying to do is using python i am opening that text file and search for that word. If the word exists then the python program should return exit code 0 or else 1. This is the code that i have written that returns 0 or 1. word = "test" def check(): ...
[ "I think you are looking for sys.exit(), but since you edited your question, I am not sure anymore. Try this:\nimport sys\n\nword = \"test\"\n\ndef check():\n with open(\"tex.txt\", \"r\") as file:\n for line_number, line in enumerate(file, start=1): \n if word in line:\n return...
[ 1 ]
[]
[]
[ "error_code", "python", "python_3.x" ]
stackoverflow_0074628734_error_code_python_python_3.x.txt
Q: "No columns to parse from file" error when trying to transform string into Pandas dataframe I have a string object ("textData") which contains CSV data. I'm able to save it as CSV by: with open(fileName, "w") as text_file: print(textData, file=text_file) but I would like to work with the data in panda...
"No columns to parse from file" error when trying to transform string into Pandas dataframe
I have a string object ("textData") which contains CSV data. I'm able to save it as CSV by: with open(fileName, "w") as text_file: print(textData, file=text_file) but I would like to work with the data in pandas before saving the csv. So I'm trying to get the data into a pandas df. import pandas as pd from...
[ "The error is in the parts you aren't showing us, because your code works fine. I'm guessing you don't have newlines separating the lines.\nC:\\tmp>type x.py\n\ntextData=\"\"\"\\\nR$M21,2021-06-08,1.3236,1.3238,1.3226,1.3237,290,343\nR$M21,2021-06-09,1.3232,1.3243,1.3231,1.3233,48,343\nR$M21,2021-06-10,1.3239,1.32...
[ 2, 0 ]
[]
[]
[ "csv", "pandas", "python", "python_3.x", "stringio" ]
stackoverflow_0068492173_csv_pandas_python_python_3.x_stringio.txt
Q: Fetch Candlestick/Kline data from Binance API using Python (preferably requests) to get JSON Dat I am developing a telegram bot that fetches Candlestick Data from Binance API. I am unable to get JSON Data as a response. The following code is something that I tried. import requests import json import urllib.r...
Fetch Candlestick/Kline data from Binance API using Python (preferably requests) to get JSON Dat
I am developing a telegram bot that fetches Candlestick Data from Binance API. I am unable to get JSON Data as a response. The following code is something that I tried. import requests import json import urllib.request `url = "https://api.binance.com/api/v1/klines" response = requests.request("GET", url) print(...
[ "you are missing the mandatory parameters symbol and interval, the query should be like this:\nhttps://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1h\nyou need to import only requests:\nimport requests\n\nmarket = 'BTCUSDT'\ntick_interval = '1h'\n\nurl = 'https://api.binance.com/api/v3/klines?symbol='+mar...
[ 29, 4, 0 ]
[]
[]
[ "api", "binance", "candlestick_chart", "json", "python" ]
stackoverflow_0051358147_api_binance_candlestick_chart_json_python.txt
Q: How to activate an existing virtualenv projects? I'm a beginner to Django and Python, and I've never used virtualenv before. However, I do know the exact commands to activate and deactivate virtual environments (online search). However, this learning course takes time and sometimes I need to split the work over 2 ...
How to activate an existing virtualenv projects?
I'm a beginner to Django and Python, and I've never used virtualenv before. However, I do know the exact commands to activate and deactivate virtual environments (online search). However, this learning course takes time and sometimes I need to split the work over 2 days. When I create a virtualenv today and do some wor...
[ "Even though pipenv had so many problems. I suggest you use it when you are new to virtual env.\nJust\npip install pipenv\ncd $your-work-directory\npipenv shell\n\nThen you created your project env.\nYou can active it by:\ncd $your-work-directory\npipenv shell\n\nYou can install packages by:\ncd $your-work-director...
[ 1, 0, 0, 0 ]
[]
[]
[ "cmd", "django", "python", "windows" ]
stackoverflow_0062383619_cmd_django_python_windows.txt
Q: Looking for the simplest way to scale x-axis labels of a data frame plot I'm plotting two columns from a data frame as follows: ax=df[['Fp1','Fp2']].plot(title='Channels Fp1 and Fp2') ax.set_xlabel("time (sec)") ax.set_ylabel("mV") What is the simplest way to scale the values shown on the axis axis? Currently, th...
Looking for the simplest way to scale x-axis labels of a data frame plot
I'm plotting two columns from a data frame as follows: ax=df[['Fp1','Fp2']].plot(title='Channels Fp1 and Fp2') ax.set_xlabel("time (sec)") ax.set_ylabel("mV") What is the simplest way to scale the values shown on the axis axis? Currently, they are the index values. I simply want to divide each label value by 1/200 so ...
[ "You can set the ticks manually:\nax.set_xticks(df.index, [i / 200 for i in df.index])\n\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074628768_pandas_python.txt
Q: Get rid of excessive logs I'm trying to remove excessive logs in my framework. During test run lot's of useless log records are shown in the console, e.g. logs of urllib3, faker and so on. I'm using Loguru library (tried 'logging' library too -- same result). Already tried: adding option '--log-level' to the brow...
Get rid of excessive logs
I'm trying to remove excessive logs in my framework. During test run lot's of useless log records are shown in the console, e.g. logs of urllib3, faker and so on. I'm using Loguru library (tried 'logging' library too -- same result). Already tried: adding option '--log-level' to the browser options for Selenium (no af...
[ "Issue was related to the pytest.\nThis post helped. Just need to add -p no:logging to the run command or to the pytest.ini file\n" ]
[ 0 ]
[]
[]
[ "logging", "loguru", "python", "webdriver" ]
stackoverflow_0074628804_logging_loguru_python_webdriver.txt
Q: Debugging a Neural Network TLDR I have been trying to fit a simple neural network on MNIST, and it works for a small debugging setup, but when I bring it over to a subset of MNIST, it trains super fast and the gradient is close to 0 very quickly, but then it outputs the same value for any given input and the final...
Debugging a Neural Network
TLDR I have been trying to fit a simple neural network on MNIST, and it works for a small debugging setup, but when I bring it over to a subset of MNIST, it trains super fast and the gradient is close to 0 very quickly, but then it outputs the same value for any given input and the final cost is quite high. I had been ...
[ "Solved\nI solved my neural network. A brief description follows in case it helps anyone else. Thanks to all those that helped with suggestions. \nBasically, I had implemented it with a fully matrix approach ie. the backpropagation uses all examples each time. I later tried implementing it as a vector approach ie. ...
[ 1, 0 ]
[]
[]
[ "backpropagation", "machine_learning", "mnist", "neural_network", "python" ]
stackoverflow_0042140866_backpropagation_machine_learning_mnist_neural_network_python.txt
Q: Saving XML files using ElementTree I'm trying to develop simple Python (3.2) code to read XML files, do some corrections and store them back. However, during the storage step ElementTree adds this namespace nomenclature. For example: <ns0:trk> <ns0:name>ACTIVE LOG</ns0:name> <ns0:trkseg> <ns0:trkpt lat="38.5" lo...
Saving XML files using ElementTree
I'm trying to develop simple Python (3.2) code to read XML files, do some corrections and store them back. However, during the storage step ElementTree adds this namespace nomenclature. For example: <ns0:trk> <ns0:name>ACTIVE LOG</ns0:name> <ns0:trkseg> <ns0:trkpt lat="38.5" lon="-120.2"> <ns0:ele>6.385864</ns0:ele...
[ "In order to avoid the ns0 prefix the default namespace should be set before reading the XML data.\nET.register_namespace('', \"http://www.topografix.com/GPX/1/1\")\nET.register_namespace('', \"http://www.topografix.com/GPX/1/0\")\n\n", "You need to register all your namespaces before you parse xml file.\nFor exa...
[ 89, 46, 1, 1, 0 ]
[]
[]
[ "elementtree", "python" ]
stackoverflow_0008983041_elementtree_python.txt
Q: How to fill the nans using groupby and filling values from another dataframe I have the input dataframe(df1) with Ids, subids and features, having the nans in the features columns, df1 = pd.DataFrame({'Id': ['A1', 'A2', 'A3', 'B1', 'B2'], 'Subid':['A', 'A', 'A', 'B', 'B'], 'featur...
How to fill the nans using groupby and filling values from another dataframe
I have the input dataframe(df1) with Ids, subids and features, having the nans in the features columns, df1 = pd.DataFrame({'Id': ['A1', 'A2', 'A3', 'B1', 'B2'], 'Subid':['A', 'A', 'A', 'B', 'B'], 'feature1':[2.6, 6.3, np.nan, np.nan, 3.3], 'feature2':[55, np.nan, np.nan...
[ "You can use a merge before fillna:\nout = df1.fillna(df1[['Subid']].merge(df2, how='left'))\n\nOutput:\n Id Subid feature1 feature2 feature3 feature4 feature5\n0 A1 A 2.600000 55.000000 0.266667 22.000000 17.333333\n1 A2 A 6.300000 18.333333 0.500000 22.666667 17.333333\n2 A3 A ...
[ 2, 1, 0 ]
[]
[]
[ "fillna", "group_by", "lambda", "pandas", "python" ]
stackoverflow_0074628746_fillna_group_by_lambda_pandas_python.txt
Q: I am trying to find out the id of the product sold month by month from 15 months of csv data and how many times it was sold in python But there is a lot of duplicate codes when I do that way in bottom. what should I do to avoid duplicate and do it in a shorter way? image of codes output of codes here the data impo...
I am trying to find out the id of the product sold month by month from 15 months of csv data and how many times it was sold in python
But there is a lot of duplicate codes when I do that way in bottom. what should I do to avoid duplicate and do it in a shorter way? image of codes output of codes here the data import numpy as np import pandas as pd train_purchases = pd.read_csv(r"C:\Users\Can\Desktop\dressipi_recsys2022\train_purchases.csv") first...
[ "you can use something like this:\nstart = '2020-01-01'\nend = '2021-03-31'\nfirst_day = pd.date_range(start, end, freq='MS').astype(str).to_list() #get first day of month given range\nend_day = pd.date_range(start, end, freq='M').strftime(\"%Y-%m-%d 23:59:59\").astype(str).to_list() #get last day of month of given...
[ 0 ]
[]
[]
[ "csv", "frequency", "numpy", "pandas", "python" ]
stackoverflow_0074617948_csv_frequency_numpy_pandas_python.txt
Q: prints the sum of the numbers -5 to 0 in python Ok so I am very new to python and I am supposed to make a code that gives me this output input= -5 output = (-5)+(-4)+(-3)+(-2)+(-1)=-15 but I just can't wrap my head around it I thought I could just somehow flip this while True: output = "" num = int(inpu...
prints the sum of the numbers -5 to 0 in python
Ok so I am very new to python and I am supposed to make a code that gives me this output input= -5 output = (-5)+(-4)+(-3)+(-2)+(-1)=-15 but I just can't wrap my head around it I thought I could just somehow flip this while True: output = "" num = int(input("enter a integer: ")) if num == 0: exit...
[ "n = int(input(\"Enter a integer: \"))\nres = \"\"\ns = 0\nx,y = [n,0] if n < 0 else [1, n+1]\nfor i in range(x, y, 1):\n res += f\"({i}) +\"\n s += i\nres = res[:-2] + \"=\" + str(s)\nprint()\nprint(res)\n\n", "This code will handle both positive and negative num.\nwhile True:\n num = int(input(\"enter ...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074628524_python.txt
Q: How can I add a Subject to my email to send via SMTP? How can I add a subject in it like I did in a normal message? When I am trying to send an email with the code below, it is showing with no Subject: import smtplib, ssl email = "fromemailhere" password = "passwordhere" receiver = "toemailhere" message = """ He...
How can I add a Subject to my email to send via SMTP?
How can I add a subject in it like I did in a normal message? When I am trying to send an email with the code below, it is showing with no Subject: import smtplib, ssl email = "fromemailhere" password = "passwordhere" receiver = "toemailhere" message = """ Hello World """ port = 465 sslcontext = ssl.create_default_c...
[ "It is fairly straight forward. Use email library (documentation). AFAIK it is a standard built in library, so no additional installation required. Your could would look like this:\nimport smtplib, ssl\nfrom email.mime.text import MIMEText\n\nemail = \"fromemailhere\"\npassword = \"passwordhere\"\nreceiver = \"toem...
[ 1 ]
[]
[]
[ "python", "python_3.x", "ssl" ]
stackoverflow_0074628823_python_python_3.x_ssl.txt
Q: Change data type of a specific column of a pandas dataframe I want to sort a dataframe with many columns by a specific column, but first I need to change type from object to int. How to change the data type of this specific column while keeping the original column positions? A: df['colname'] = df['colname'].asty...
Change data type of a specific column of a pandas dataframe
I want to sort a dataframe with many columns by a specific column, but first I need to change type from object to int. How to change the data type of this specific column while keeping the original column positions?
[ "df['colname'] = df['colname'].astype(int) works when changing from float values to int atleast.\n", "I have tried following:\ndf['column']=df.column.astype('int64')\n\nand it worked for me.\n", "You can use reindex by sorted column by sort_values, cast to int by astype:\ndf = pd.DataFrame({'A':[1,2,3],\n ...
[ 31, 10, 6, 2, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0041590884_pandas_python.txt
Q: Convert .opus to .wav in Python I want to classify audio clip files using Tensorflow. But my audio files are in .opus format. From my research I need them to be in .wav format. Therefore, I have to convert them. I would like to do this in Python, because I am working in a Jupyter notebook. I want to do this for hu...
Convert .opus to .wav in Python
I want to classify audio clip files using Tensorflow. But my audio files are in .opus format. From my research I need them to be in .wav format. Therefore, I have to convert them. I would like to do this in Python, because I am working in a Jupyter notebook. I want to do this for hundreds of files. All I found so far w...
[ "One can use this in Python:\nopus_path = 'something.opus'\nwav_path = 'something.wav'\nos.system(f'ffmpeg -i \"{opus_path}\" -vn \"{wav_path}\"')\n\nThis can obviously be applied in a loop if you want:\nfor opus_path,wav_path in zip(opus_paths,wav_paths):\n os.system(f'ffmpeg -i \"{opus_path}\" -vn \"{wav_path}...
[ 1 ]
[]
[]
[ "audio", "opus", "python", "tensorflow", "wav" ]
stackoverflow_0074603951_audio_opus_python_tensorflow_wav.txt
Q: the compiled code path to the location of the error is shown and not the executable path I searched a lot about this problem although there are many trials of other people but this problem I couldn't find or may be I am using wrong terms while searching. I am using this method to create an executable for my python...
the compiled code path to the location of the error is shown and not the executable path
I searched a lot about this problem although there are many trials of other people but this problem I couldn't find or may be I am using wrong terms while searching. I am using this method to create an executable for my python code. Everything runs fine but when I run the code and there is an error. The path to the fil...
[ "I found a solution by trial and error. I had to add in setup.py in options\n\"replace_paths\": [(\"*\", \"\")]\n\nThe solution was shown in enter link description here\nnow I have the path to error starting by the folder of the compiled source code\nBefore: user/Desktop/projectFolder/..../something.py\nNow: projec...
[ 0 ]
[]
[]
[ "cx_freeze", "exe", "python" ]
stackoverflow_0074618798_cx_freeze_exe_python.txt
Q: Is it bad practice to add methods to a class outside of the class? For example, I have a class Foo that I do not have access to the source of (specifics are unimportant). class Foo: def __init__(self): self.x: int = 0 I want to extend this class, adding a new explicit constructor, I understand the typ...
Is it bad practice to add methods to a class outside of the class?
For example, I have a class Foo that I do not have access to the source of (specifics are unimportant). class Foo: def __init__(self): self.x: int = 0 I want to extend this class, adding a new explicit constructor, I understand the typical way to do this is class Foo(Foo): @staticmethod from_x(x: i...
[ "If there is no specific reason to define a method not inside of the class definition it would be preferred to keep everything together. So it is definitely better to define your method in your class to provide better readability of your code. Especially if other persons will have to work with your code it could be...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074628870_python_python_3.x.txt
Q: 'Series' object has no attribute 'tax_code' i have a dataframe with 2 columns user_id and tax_code and many rows. I imported this library https://pypi.org/project/python-codicefiscale/ and i need to verify if a tax_code is valid or not. i tried to define this function that doesnt give me back errors. def valid(): ...
'Series' object has no attribute 'tax_code'
i have a dataframe with 2 columns user_id and tax_code and many rows. I imported this library https://pypi.org/project/python-codicefiscale/ and i need to verify if a tax_code is valid or not. i tried to define this function that doesnt give me back errors. def valid(): from codicefiscale import codicefiscale i...
[ "\nFirstly i dont know if this causes any problems but avoid importing\ninside your code, to my best of knowledge importing always goes in\nthe beginning\nSecondly i think your error is caused on the if statement. There you\ntry to search for the 'tax_code' as it is a Dataframe attribute. Try\nusing it inside [''] ...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074628956_pandas_python.txt
Q: getting TimeoutException when using expected_conditions in heroku I have a selenium robot that worked perfectly locally but on heroku TimeoutException raises whenever its on a expected_condition (element_to_be_clickable, visibility_of_element_located and presence_of_element_located). Anyone knows how to fix this p...
getting TimeoutException when using expected_conditions in heroku
I have a selenium robot that worked perfectly locally but on heroku TimeoutException raises whenever its on a expected_condition (element_to_be_clickable, visibility_of_element_located and presence_of_element_located). Anyone knows how to fix this problem in heroku. here is an example where I used expected_conditions e...
[ "I guess you didn't define the screen size for the driver while in headless mode the default screen size is 800,600.\nSo, to make your Selenium code working try setting the screen size to maximal or 1920,1080. As following:\nfrom selenium.webdriver.chrome.options import Options\n\noptions = Options()\noptions.add_a...
[ 0 ]
[]
[]
[ "heroku", "python", "screen_size", "selenium", "webdriverwait" ]
stackoverflow_0074628847_heroku_python_screen_size_selenium_webdriverwait.txt
Q: Reduce user's coins by 1 for each extra time taken after a specific limit - Python Imagine a situation where users have 10 coins and have 40 second to do a task. I want to implement something like this: if total time taken by the user is 50, reduce the coin by 1, similary if it's 60, reduce 2 and so on... How shou...
Reduce user's coins by 1 for each extra time taken after a specific limit - Python
Imagine a situation where users have 10 coins and have 40 second to do a task. I want to implement something like this: if total time taken by the user is 50, reduce the coin by 1, similary if it's 60, reduce 2 and so on... How should I implement this in python. PS: In short, I wanna reduce coins for each 10 seconds el...
[ "Python has a time library you can use. Something like this maybe.\nimport time\n\ncoins = 10\n\n\ndef user_task():\n start_time = time.time()\n # user completes task here\n end_time = time.time()\n time_taken = end_time - start_time\n\n return time_taken\n \n\ntotal_time_taken = user_task()\n\nif ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074628724_python.txt
Q: Elif syntax error with nested if conditions The interpreter gives me a syntax error when it reaches elif in the code below. Why? while walls: rand_wall = walls[int(random.random()*len(walls))-1] if rand_wall[1] != 0 and rand_wall[1] != mazeheight-1: if maze[rand_wall[0][rand_wall[1]-1] == "u" and m...
Elif syntax error with nested if conditions
The interpreter gives me a syntax error when it reaches elif in the code below. Why? while walls: rand_wall = walls[int(random.random()*len(walls))-1] if rand_wall[1] != 0 and rand_wall[1] != mazeheight-1: if maze[rand_wall[0][rand_wall[1]-1] == "u" and maze[rand_wall[0][rand_wall[1]+1] == "c": ...
[ "There are some closing brackets missing.\nwhile walls:\n rand_wall = walls[int(random.random()*len(walls))-1]\n if rand_wall[1] != 0 and rand_wall[1] != mazeheight-1:\n if maze[rand_wall[0][rand_wall[1]-1] == \"u\" and maze[rand_wall[0][rand_wall[1]+1]]] == \"c\": # added two closing brackets before t...
[ 0, 0 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0074629035_if_statement_python.txt
Q: Mutual TLS with self signed certificates, with requests in python I created both client and server certificates: # client openssl req -new -newkey rsa:4096 -x509 -sha256 -days 365 -nodes -out ssl/client.crt -keyout ssl/client.key # server openssl req -new -newkey rsa:4096 -x509 -sha256 -days 365 -nodes -out ssl/se...
Mutual TLS with self signed certificates, with requests in python
I created both client and server certificates: # client openssl req -new -newkey rsa:4096 -x509 -sha256 -days 365 -nodes -out ssl/client.crt -keyout ssl/client.key # server openssl req -new -newkey rsa:4096 -x509 -sha256 -days 365 -nodes -out ssl/server.crt -keyout ssl/server Then with python I have the following: im...
[ "\ntlsv1 alert unknown ca\n\nThe server is sending a TLS alert back since it cannot validate your client certificate - the certificate authority (ca) which signed the certificate is unknown to the server. You either need to disable client certificate validation in your server or (better) make the server trust your ...
[ 0, 0 ]
[]
[]
[ "mtls", "python", "python_3.9", "python_requests", "ssl" ]
stackoverflow_0074294395_mtls_python_python_3.9_python_requests_ssl.txt
Q: How to set a max column length for streamlit-aggrid If I have a really long column entry that takes up most of the table (like below) how do I set the table options such that it gets truncated? import streamlit as st from st_aggrid import AgGrid import pandas as pd df = pd.DataFrame({'some short column': ['a', '...
How to set a max column length for streamlit-aggrid
If I have a really long column entry that takes up most of the table (like below) how do I set the table options such that it gets truncated? import streamlit as st from st_aggrid import AgGrid import pandas as pd df = pd.DataFrame({'some short column': ['a', 'b', 'c'], 'some long column': ['all co...
[ "Use the fit_columns_on_grid_load param, this is False by default.\nAgGrid(df, fit_columns_on_grid_load=True)\n\n", "Combined with @ferdy's answer. If I use:\ngb = GridOptionsBuilder.from_dataframe(df, min_column_width=30)\nAgGrid(df, gridOptions=gb.build(), fit_columns_on_grid_load=True)\n\nThen it works securel...
[ 2, 1, 1 ]
[]
[]
[ "ag_grid", "python", "streamlit" ]
stackoverflow_0072624323_ag_grid_python_streamlit.txt
Q: How do i replace a column in a numpy array with 0 given that the column contains the number 0? I am trying to make a program that replaces entire columns of matrices if the column contains a 0. I tried making a numpy array, x, and running the command: x[:, np.where(x <= 0)] = 0 The desired outcome would be that t...
How do i replace a column in a numpy array with 0 given that the column contains the number 0?
I am trying to make a program that replaces entire columns of matrices if the column contains a 0. I tried making a numpy array, x, and running the command: x[:, np.where(x <= 0)] = 0 The desired outcome would be that the sum of all columns containing 0 would be 0.
[ "X[:, (X==0).any(axis=0)]=0\n\nExplanation\n(X==0) is matrix of booleans of the same shape than X, saying if each element of X is 0\n(X==0).any() says is True iff at least of those booleans is True\n(X==0).any(axis=0) does that only along axis 0, so it gives an array of n booleans, one per columns, each of them Tru...
[ 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074629136_numpy_python.txt
Q: Flip a Y coordinate within a min-max range I'm calculating a Y coordinate which represents a value on a y-axis on a chart I'm drawing in PIL, to display on an LCD display. I set a start_y and an end_y. The (physical) top of the screen is y = 0. I get my y coordinate as follows: start_y = 10 # 10 pixels from top of...
Flip a Y coordinate within a min-max range
I'm calculating a Y coordinate which represents a value on a y-axis on a chart I'm drawing in PIL, to display on an LCD display. I set a start_y and an end_y. The (physical) top of the screen is y = 0. I get my y coordinate as follows: start_y = 10 # 10 pixels from top of screen end_y = 60 # 60 pixels from top of scree...
[ "because of the nature of the equation, it will give the value of the total pixels from the top of the chart as your min max and start end also start from the top. If you want the remaining pixels, You will have to subtract the current answer from the highest pixel possible which is end_y. Your equation will become...
[ 2 ]
[]
[]
[ "charts", "math", "python" ]
stackoverflow_0074628945_charts_math_python.txt
Q: Sklearn regression with label encoding I'm attempting to use sklearn's linear regression model to predict fantasy players points. I have numeric stats for each player and obviously their name which I have encoded with the Label encoder function. My question is when performing the linear regression the encoded valu...
Sklearn regression with label encoding
I'm attempting to use sklearn's linear regression model to predict fantasy players points. I have numeric stats for each player and obviously their name which I have encoded with the Label encoder function. My question is when performing the linear regression the encoded values included in the training it doesn't seem ...
[ "Apart from one hot encoding (which might create way too many columns in this case), mean target encoding does exactly what you need (encodes the category with its mean target value). You should be vary about the target leakage in case of rare categories though. sklearn-compatible category_encoders library provides...
[ 1 ]
[]
[]
[ "linear_regression", "one_hot_encoding", "python", "scikit_learn" ]
stackoverflow_0074628815_linear_regression_one_hot_encoding_python_scikit_learn.txt
Q: Do Tensorflow have documentation in VS Code? My goal is to use Tensorflow in Visual Studio Code. However, the documentation is non existant. I can import it but there is a warning when I hover the import statement What I've did: Install tensorflow on Mac Mini M1 with %pip install tensorflow-macos %pip install te...
Do Tensorflow have documentation in VS Code?
My goal is to use Tensorflow in Visual Studio Code. However, the documentation is non existant. I can import it but there is a warning when I hover the import statement What I've did: Install tensorflow on Mac Mini M1 with %pip install tensorflow-macos %pip install tensorflow-metal
[ "The problem is addressed in this thread- https://github.com/tensorflow/tensorflow/issues/56231\nThe solution that worked for me is by creating a symlink in lib/pythonx.x/site-packages/tensorflow\nln -s ../keras/api/_v2/keras/ keras\n\n" ]
[ 0 ]
[]
[]
[ "macos", "python", "python_3.x", "tensorflow", "tensorflow2.0" ]
stackoverflow_0074628773_macos_python_python_3.x_tensorflow_tensorflow2.0.txt
Q: Pandas dataframe conditional column update based on another dataframe I have two dataframes with two columns each - 'MeetingId' and 'TAB'. The first dataframe is the full table, but it has some errors in the 'TAB' column. The second dataframe has the solutions to the errors. I would like to replace the 'TAB' colum...
Pandas dataframe conditional column update based on another dataframe
I have two dataframes with two columns each - 'MeetingId' and 'TAB'. The first dataframe is the full table, but it has some errors in the 'TAB' column. The second dataframe has the solutions to the errors. I would like to replace the 'TAB' column of the first dataframe with the 'TAB' column of the second datafrmae if t...
[ "df['TAB'] = df.apply(lambda x: df2[df2['MeetingId'] == x['MeetingId']]['TAB'].values[0], axis=1)\n\nOR\ndf.loc[df['MeetingId'].isin(df2['MeetingId']), 'TAB'] = df2['TAB']\n\nExample:\n> df\n\n MeetingId TAB\n0 123 True\n1 124 False\n\n> df2\n\n MeetingId TAB\n0 123 False\n1 ...
[ 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074629249_dataframe_pandas_python.txt
Q: Making a calculator to find the number of days until Christmas [Feedback] I've made a calculator to find the number of days until Christmas. I'm asking anyone to give me any feedback that might help me improve this calculator in any way possible. The calculator works perfectly fine, but I am requesting feedback on...
Making a calculator to find the number of days until Christmas [Feedback]
I've made a calculator to find the number of days until Christmas. I'm asking anyone to give me any feedback that might help me improve this calculator in any way possible. The calculator works perfectly fine, but I am requesting feedback on this to make it as simple as possible. # Made using Python Language (Translate...
[]
[]
[ "There are some mistakes in it. Like the 354th day is christmas as when I type in yes, it shows 24 days left when there is more 26 days. And if someone types no you should add-on something to that also like an elif statement. And add an else statement for the input if they type anyhting else then the answer should ...
[ -1 ]
[ "python", "time" ]
stackoverflow_0074629211_python_time.txt
Q: Generate one plot per revealjs slide in python for loop using Quarto I'm trying to generate a slide deck consisting of several plots using Quarto with revealjs output format. I need to generate these plots with plotly through a loop, but that is messing up my output. I'm getting the plots lined up vertically, whic...
Generate one plot per revealjs slide in python for loop using Quarto
I'm trying to generate a slide deck consisting of several plots using Quarto with revealjs output format. I need to generate these plots with plotly through a loop, but that is messing up my output. I'm getting the plots lined up vertically, which doesn't fit the slide size. What I want to achieve is one plot per slide...
[ "You can do this very easily just by generating markdown slide header dynamically in each iteration of loop using display(Markdown(\"Slide header\")) along with chunk option output: asis.\n---\ntitle: \"For Loops in Quarto\"\nformat: \n revealjs:\n theme: default\ncode-fold: true\nexecute: \n echo: false\n...
[ 0 ]
[]
[]
[ "plotly", "python", "quarto" ]
stackoverflow_0074626298_plotly_python_quarto.txt
Q: iterate through list of lists and check if list contains all "False" I am having issue with my code that works fine on sample code and should also work on test code but it doesn't. I am having a list of lists that contain True/False but as STRING! List looks like this: ['True', 'True', 'True'] ['False', 'False', '...
iterate through list of lists and check if list contains all "False"
I am having issue with my code that works fine on sample code and should also work on test code but it doesn't. I am having a list of lists that contain True/False but as STRING! List looks like this: ['True', 'True', 'True'] ['False', 'False', 'False'] ['False', 'False', 'False'] ['False', 'False', 'False'] ['True', '...
[ "If you're loading your data from somewhere external, is may not do what you expect, since it compares object identity, not contents. (You should never use is unless you know exactly what you're doing).\nThis seems to work fine:\nfor case in [\n ['True', 'True', 'True'],\n ['False', 'False', 'False'],\n ['...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074629321_python.txt
Q: Unsure how to remove whitespace from strings current_price = int(input()) last_months_price = int(input()) print("This house is $" + str(current_price), '.', "The change is $" + str(current_price - last_months_price) + " since last month.") print("The estimated monthly mortgage is ${:.2f}".format((current_p...
Unsure how to remove whitespace from strings
current_price = int(input()) last_months_price = int(input()) print("This house is $" + str(current_price), '.', "The change is $" + str(current_price - last_months_price) + " since last month.") print("The estimated monthly mortgage is ${:.2f}".format((current_price * 0.051) / 12), '.') This produces: This ho...
[ "You can give print an additional parameter: sep, like this:\nprint(\"This house is $\" + str(current_price), '.', \"The change is $\" +\n str(current_price - last_months_price) + \" since last month.\", sep='')\n\nbecause the default is an empty space after the comma.\n", "Maybe try f-string injection\nprin...
[ 2, 1, 0 ]
[]
[]
[ "python", "python_3.6", "removing_whitespace" ]
stackoverflow_0063550872_python_python_3.6_removing_whitespace.txt
Q: Fill missing values in list based on a condition I will try to explain my issue with simple example. Let's say I've a list lis = ['Elemnt-1' , 'Elemnt-2' , 'Elemnt-3' , '' , '' , 'Elemnt-6' , 'Elemnt-7'] How can I fill this missing values such that list will become. lis = ['Elemnt-1' , 'Elemnt-2' , 'Elemnt-3' , '...
Fill missing values in list based on a condition
I will try to explain my issue with simple example. Let's say I've a list lis = ['Elemnt-1' , 'Elemnt-2' , 'Elemnt-3' , '' , '' , 'Elemnt-6' , 'Elemnt-7'] How can I fill this missing values such that list will become. lis = ['Elemnt-1' , 'Elemnt-2' , 'Elemnt-3' , 'Elemnt-2' , 'Elemnt-3' , 'Elemnt-6' , 'Elemnt-7'] Exp...
[ "Because you're looking 2 back to fill the empty spots, we skip the first 2 indeces as there's nothing before theme. Here I define a func that does this:\ndef filler(l: list):\n for i in range(2, len(l)):\n if l[i] == '':\n l[i] = l[i-2]\n return l\n\nprint(filler(['Elemnt-1' , 'Elemnt-2' , ...
[ 1, 1, 1, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074624986_list_python.txt
Q: Is highlighting a segment of px.scatter_mapbox plot possible? Using Dash graphs to create a placeholder for scatter line plot and scattermapbox. html.Div([ html.Div(id='graphs', children=[ dcc.Graph({'type':'graph', 'index':1}, figure=blank_fig('plotly_dark')), dcc.Graph({'type':'graph', 'index':1},...
Is highlighting a segment of px.scatter_mapbox plot possible?
Using Dash graphs to create a placeholder for scatter line plot and scattermapbox. html.Div([ html.Div(id='graphs', children=[ dcc.Graph({'type':'graph', 'index':1}, figure=blank_fig('plotly_dark')), dcc.Graph({'type':'graph', 'index':1}, figure=blank_fig('plotly_dark'))] ]) The figures are initialized ...
[ "To achieve this I successfully used px.line_mapbox() function.\n" ]
[ 0 ]
[]
[]
[ "plotly_dash", "plotly_express", "python" ]
stackoverflow_0074575298_plotly_dash_plotly_express_python.txt
Q: Importing custom python module with dependencies I have the following folder structure: files structure └── App/ ├── main.py ├── functions.py └── models/ └── model1/ ├── utils/ │ └── file2.py └── file1.py inside main.py file: import functions inside functions.py from models.model1 import file1 inside file1.py fr...
Importing custom python module with dependencies
I have the following folder structure: files structure └── App/ ├── main.py ├── functions.py └── models/ └── model1/ ├── utils/ │ └── file2.py └── file1.py inside main.py file: import functions inside functions.py from models.model1 import file1 inside file1.py from utils import file2 When running main.py I am gettin...
[ "my-app/ \n├─ main.py \n├─ functions.py \n├─ models/ |\n ├─ model1/ │ \n ├─ utils/ │ \n ├─ file2.py | \n ├─ file1.py |\n\nBased on this information, it looks like you can use import utils.file2 because they are in the same directory.\n" ]
[ 0 ]
[]
[]
[ "import", "init", "package", "python" ]
stackoverflow_0074622309_import_init_package_python.txt
Q: How to combine multiple csv as columns in python? I have 10 .txt (csv) files that I want to merge together in a single csv file to use later in analysis. when I use pd.append, it always merges the files below each other. I use the following code: master_df = pd.DataFrame() for file in os.listdir(os.getcwd()): ...
How to combine multiple csv as columns in python?
I have 10 .txt (csv) files that I want to merge together in a single csv file to use later in analysis. when I use pd.append, it always merges the files below each other. I use the following code: master_df = pd.DataFrame() for file in os.listdir(os.getcwd()): if file.endswith('.txt'): files = pd.read_csv...
[ "To merge DataFrames side by side, you should use pd.concat.\nframes = []\n\nfor file in os.listdir(os.getcwd()):\n if file.endswith('.txt'):\n files = pd.read_csv(file, sep='\\t', skiprows=[1])\n frames.append(files)\n\n# axis = 0 has the same behavior of your original approach\nmaster_df = pd.con...
[ 1 ]
[]
[]
[ "csv", "merge", "pandas", "python" ]
stackoverflow_0074629257_csv_merge_pandas_python.txt
Q: i have a log file and i want to write a python code to increment second column value by 1 hour and 9th column value by 1 I have the log file dataset placed in a unix directory which looks like this: i want to increase the value of Pcode by 1 for all lines and incremnet the timestamp column by 1 hour 12345432,10-11...
i have a log file and i want to write a python code to increment second column value by 1 hour and 9th column value by 1
I have the log file dataset placed in a unix directory which looks like this: i want to increase the value of Pcode by 1 for all lines and incremnet the timestamp column by 1 hour 12345432,10-11-2011,11:11:12.435,0,0,XVC_AS,12,14,81,12345412,qweds 12345433,10-11-2011,18:12:45.124,0,0,XVC_AS,12,15,77,12345445,qweds 1234...
[]
[]
[ "First remove the spaces from your headers (for clarity), then import as CSV into Pandas:\nimport pandas as pd\ndf = pd.read_csv('file.csv')\n\nIncreasing Pcode is simple:\nf['Pcode'] = df['Pcode']+1\n\nBut your timestamps have an issue. Normally you could treat them as timestamps and add an hour, but your timestam...
[ -1 ]
[ "python", "python_2.7" ]
stackoverflow_0074629160_python_python_2.7.txt
Q: Find all matching pattern in a string I'm trying to get all substrings that matching a specific pattern from a larger string, I have a string like that : string = "{\huge \centering \bf{RAPPORT JOURNALIER \\ ***bouee*** \\ \formatDate{***day***}{***month***}{***year***}} \\ \small generated on~\today~at~\currentti...
Find all matching pattern in a string
I'm trying to get all substrings that matching a specific pattern from a larger string, I have a string like that : string = "{\huge \centering \bf{RAPPORT JOURNALIER \\ ***bouee*** \\ \formatDate{***day***}{***month***}{***year***}} \\ \small generated on~\today~at~\currenttime \par}" and I want to get in a list all ...
[ "Yes, you can use the \"re\" module for this.\nimport re\n\nre.findall('\\*{3}(.+?)\\*{3}', string)\n\nHere, we tell it to match substrings that consist of three asterisks, any number of any characters, then three more asterisks. Then, we use parenthesis to mark the inside characters as our \"capturing group,\" so ...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074629473_python_python_3.x.txt
Q: Jupyter Notebook kernel dies when I increase the number of samples I am trying to execute the following python code: plt.figure(figsize=(9,6)) plt.title("Dendrograms for number of clusters") dend = sch.dendrogram(sch.linkage(scaled, method='ward')) When I execute the above code with 12000 samples it works fin...
Jupyter Notebook kernel dies when I increase the number of samples
I am trying to execute the following python code: plt.figure(figsize=(9,6)) plt.title("Dendrograms for number of clusters") dend = sch.dendrogram(sch.linkage(scaled, method='ward')) When I execute the above code with 12000 samples it works fine. However, when I increase the samples to 24000 it shows that Kernel ap...
[ "This was an issue with scipy package. I downgraded the package scipy from 1.7.3 to 1.7.1 and it is working. However, the downgraded version of scipy has an issue of maximum recursion depth exceeded while getting str of an object. The second issue can be resolved by expanding the limit.\n" ]
[ 0 ]
[]
[]
[ "jupyter_notebook", "python" ]
stackoverflow_0074619570_jupyter_notebook_python.txt
Q: remove entire rows from df if the word occurs list of stowwords: stop_w = ["in", "&", "the", "|", "and", "is", "of", "a", "an", "as", "for", "was"] df: words frequency the company 10 green energy 9 founded in 8 gases for 8 electricity 5 I would like to remove entire row if it contains ANY of given stopwords...
remove entire rows from df if the word occurs
list of stowwords: stop_w = ["in", "&", "the", "|", "and", "is", "of", "a", "an", "as", "for", "was"] df: words frequency the company 10 green energy 9 founded in 8 gases for 8 electricity 5 I would like to remove entire row if it contains ANY of given stopwords, in this example output should be: ...
[ "The | character has a meaning, it means or in python's terms, so you need to escape that meaning in order to use it in your stop words list. You escape that with a backslash \\ (see more here)\nHaving said that you can do:\nstop_w = [\"in\", \"&\", \"the\", \"\\|\", \"and\", \"is\", \"of\", \"a\", \"an\", \"as\", ...
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074629401_dataframe_pandas_python.txt
Q: How do you make text which changes in tkinter? i am currently making a celsius to Fahrenheit converter gui but I can' figure out how to add text which changes each time a conversion happens. Can any of you help? from tkinter import * import tkinter inputValue=0 root=Tk() root.geometry('250x170') def retrieve_input...
How do you make text which changes in tkinter?
i am currently making a celsius to Fahrenheit converter gui but I can' figure out how to add text which changes each time a conversion happens. Can any of you help? from tkinter import * import tkinter inputValue=0 root=Tk() root.geometry('250x170') def retrieve_input(): inputValue =textBox.get("1.0","end-1c") ...
[ "Use:\nlabelname.config(text = text)\n\n", "You are missing widget pack(). Replace this:\nlabel1.config(text=inputValue)\n\nto:\nlabel1.pack()\n\nand add this label1.config(text=inputValue) in retrieve_input()function.\nResult before enter input:\n\nResult after:\n\n" ]
[ 0, 0 ]
[]
[]
[ "python", "tkinter", "user_interface" ]
stackoverflow_0071699765_python_tkinter_user_interface.txt
Q: Cannot get python scripting working under WSH I'm trying to get WSH to run Python .pys scripts and I'm hitting a wall - I've tried this on two machines now, W7x64 and Server2012, same result both time, cscript always comes back with: CScript Error: Can't find script engine "Python" Procedure (all happening under ...
Cannot get python scripting working under WSH
I'm trying to get WSH to run Python .pys scripts and I'm hitting a wall - I've tried this on two machines now, W7x64 and Server2012, same result both time, cscript always comes back with: CScript Error: Can't find script engine "Python" Procedure (all happening under local admin account): Installed Python 3.5.1 (x86)...
[ "It appears that python on Windows is a PITA. So, I had your problem as well, I followed the following steps:\n\nDownload Python from python.org. (you probably already have\nthat) \nDownload PyWin32 from SourceForge.\nDownload SetupTools from python.org.\nOn your desktop or in the Start menu, right-click on My Comp...
[ 1, 0 ]
[]
[]
[ "python", "pywin32", "wsh" ]
stackoverflow_0035034877_python_pywin32_wsh.txt
Q: How to get specific objects from two list of dictionaries on a specific key value? I have two lists of dictionaries: timing = [ {"day_name": "sunday"}, {"day_name": "monday"}, {"day_name": "tuesday"}, {"day_name": "wednesday"}, {"day_name": "thursday"}, {"day_name": "friday"}, {"day_nam...
How to get specific objects from two list of dictionaries on a specific key value?
I have two lists of dictionaries: timing = [ {"day_name": "sunday"}, {"day_name": "monday"}, {"day_name": "tuesday"}, {"day_name": "wednesday"}, {"day_name": "thursday"}, {"day_name": "friday"}, {"day_name": "saturday"}, ] hours_detail = [ {"day_name": "sunday", "peak_hour": False}, ...
[ "If pricing = hour_detail then obj[\"pricing\"] must be a list as it can have multiple value.\nYou have to create a new list in your loop for time_instance in timing: and append every time time_instance[\"day_name\"] == pricing_instance[\"day_name\"].\nExemple:\ndata = []\n\nfor time_instance in timing:\n curre...
[ 1, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074629179_python_python_3.x.txt
Q: KeyError Received unregistered task of type '' on celery while task is registered I'm a bit new in celery configs. I have a task named myapp.tasks.my_task for example. I can see myapp.tasks.my_task in registered tasks of celery when I use celery inspect registered. doesn't it mean that the task is successfully reg...
KeyError Received unregistered task of type '' on celery while task is registered
I'm a bit new in celery configs. I have a task named myapp.tasks.my_task for example. I can see myapp.tasks.my_task in registered tasks of celery when I use celery inspect registered. doesn't it mean that the task is successfully registered? why it raises the following error for it: KeyError celery.worker.consumer.cons...
[ "It means that Celery can't find the implementation of the task my_app.tasks.my_task when it was called. Some possible solutions you may want to look at:\nPossible Solution 1:\nYou probably haven't configured correctly either:\n\nCelery imports e.g. celery_app.conf.update(imports=['my_app.tasks']) or celery_app.con...
[ 2, 0, 0 ]
[]
[]
[ "celery", "celery_task", "django", "python", "python_3.x" ]
stackoverflow_0068888941_celery_celery_task_django_python_python_3.x.txt
Q: streamlit dataframe - live input values Is it possible to add live values to the streamlit dataframe, then save it as a new dataframe and continue with dataframe manipulation ? Let's say I upload on streamlit a dataframe like below: word frequency weight apple 3 green 2 house 5 I want USER to input the values...
streamlit dataframe - live input values
Is it possible to add live values to the streamlit dataframe, then save it as a new dataframe and continue with dataframe manipulation ? Let's say I upload on streamlit a dataframe like below: word frequency weight apple 3 green 2 house 5 I want USER to input the values in "weight" column and save it...
[ "As mentioned in the comments, you can currently use the streamlit-aggrid component to do this (guide on how to do this here). We're in the process of revamping st.dataframe, and the ability to edit the values is part of that (should be released in the next few months).\n" ]
[ 2 ]
[]
[]
[ "pandas", "python", "streamlit" ]
stackoverflow_0074603090_pandas_python_streamlit.txt
Q: Faster Numpy: Contiguous Number Replacement Can someone help me make this faster? import numpy as np # an array to split a = np.array([0,0,1,0,1,1,1,0,1,1,0,0,0,1]) # idx where the number changes idx = np.where(np.roll(a,1)!=a)[0][1:] # split of array into groups aout = np.split(a,idx) # sum of each group sums...
Faster Numpy: Contiguous Number Replacement
Can someone help me make this faster? import numpy as np # an array to split a = np.array([0,0,1,0,1,1,1,0,1,1,0,0,0,1]) # idx where the number changes idx = np.where(np.roll(a,1)!=a)[0][1:] # split of array into groups aout = np.split(a,idx) # sum of each group sumseg = [aa.sum() for aa in aout] #fill criteria id...
[ "Better solution 1D:\nWe can use a convolution:\naout = ((np.convolve(a,[1,1,1],mode='same')>1)&(a>0)).astype(a.dtype)\n# aout = array([0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0])\n\nBetter solution 2D:\nfrom scipy.signal import convolve2d\n\na = np.array([[1, 1, 0, 0, 0, 0, 1, 0, 0, 1],\n [1, 0, 1, 0, ...
[ 3 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074628646_numpy_python.txt
Q: Check if file in directory has corresponding MD5 file I am working on file integrity check and I want to check in a given directory if the file has it's corresponding MD5 hash file and return all file names which have the corresponding md5 hash. for example: inside directory [ abc.bin abc.bin.md5 efg.bin q...
Check if file in directory has corresponding MD5 file
I am working on file integrity check and I want to check in a given directory if the file has it's corresponding MD5 hash file and return all file names which have the corresponding md5 hash. for example: inside directory [ abc.bin abc.bin.md5 efg.bin qwerty.bin qwerty.bin.md5 xyc.bin ] the return values: ...
[ "You could do something like this:\n#get a list of files and directories in the current directory\nfile_list = os.listdir('.')\n\n#produce a list of candidate files (files ending with `md5`). Perhaps there is a more elegant way of doing this, but it works. \ncandidates = [x for x in file_list if x.split('.')[-1] ==...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074619521_python.txt