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: I want to print the value between 2 to 5 from 1first columns I want to print the value between 2 to 5 from 1first columns. df5 = pd.DataFrame({ 'colA': ['C4GSP3JOIHJ2', 'CAGPS3JOIHJ2','CALCG3EST2','CLCCV3JOIHJ2','CLCNF3JOIHJ2','CLCQU3JOIHJ2','CLSMS3JOIHJ2','CMICO3JOIHJ2'], }) output look like this A: df...
I want to print the value between 2 to 5 from 1first columns
I want to print the value between 2 to 5 from 1first columns. df5 = pd.DataFrame({ 'colA': ['C4GSP3JOIHJ2', 'CAGPS3JOIHJ2','CALCG3EST2','CLCCV3JOIHJ2','CLCNF3JOIHJ2','CLCQU3JOIHJ2','CLSMS3JOIHJ2','CMICO3JOIHJ2'], }) output look like this
[ "df5['output']=df5['colA'].str[1:6]\n" ]
[ -1 ]
[ "df['output'] = df.colA.apply(lambda x: x[1:6]) \n\nshould work. Docs for apply function: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0074462442_python.txt
Q: issues when using re.finditer with + sign character in string I am using the following code to find the location the start index of some strings as well as a temperature all of which are read from a text file. The array searchString, contains what I'm looking for. It does locate the index of the first character of...
issues when using re.finditer with + sign character in string
I am using the following code to find the location the start index of some strings as well as a temperature all of which are read from a text file. The array searchString, contains what I'm looking for. It does locate the index of the first character of each string. The issue is that unless I put the backslash in front...
[ "You should use the re.escape() function to escape your string pattern. It will escape all the special characters in given string, for example:\n>>> print(re.escape('+25°C'))\n\\+25°C\n>>> print(re.escape('my_pattern with specials+&$@('))\nmy_pattern\\ with\\ specials\\+\\&\\$@\\(\n\nSo replace your searchString wi...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074462437_python.txt
Q: How can I implement (I think via inheritance) a new class, with a parameter of the parent class, and a paremeter which comes from another module? My task is: Write the code for a class called RandomWalker. This class has only one parameter (an instance variable) called position which is initialized at the creatio...
How can I implement (I think via inheritance) a new class, with a parameter of the parent class, and a paremeter which comes from another module?
My task is: Write the code for a class called RandomWalker. This class has only one parameter (an instance variable) called position which is initialized at the creation of a new instance of the class. Write a class called Simulation with, at least, the following instance variables: an instance of RandomWalker called...
[ "No, you don't need to use inheritance in your case - Position is not RandomWalker, but it contains a Random Walker. This is a use case for composition, in Python most easily achieved by assigning an object attribute, just like RandomWalker gets position attribute.\nclass Simulation:\n def __init__(self, random_...
[ 1 ]
[]
[]
[ "class", "initialization", "python", "python_3.x" ]
stackoverflow_0074462492_class_initialization_python_python_3.x.txt
Q: Nothing solves SSLCertVerificationError I am getting the infamous error ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1131) I tried almost all solutions available online so far but no luck. I am using pyoidc (with keycloak ...
Nothing solves SSLCertVerificationError
I am getting the infamous error ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1131) I tried almost all solutions available online so far but no luck. I am using pyoidc (with keycloak and superset) which uses urllib that fails to...
[ "Know this is late but just for other people...\nMy issue was that I was using virtuelenv. So I did:\ncat /usr/local/share/ca-certificates/mycert.crt >> vendor/lib/python3.8/site-packages/certifi/cacert.pem\n\nWith vendor being my virtuelenv folder.\nThanks Cemre for the idea. Took a while to figure this one out.\n...
[ 0 ]
[]
[]
[ "python", "ssl" ]
stackoverflow_0069927923_python_ssl.txt
Q: Authentication for using Google Cloud Platform API through Google Colab I am trying to use the Healthcare API, specifically the Healthcare Natural Language API for which there is this tutorial as well as this other one The tutorial outlines how to run the API on a string; I've been tasked with figuring out how to ...
Authentication for using Google Cloud Platform API through Google Colab
I am trying to use the Healthcare API, specifically the Healthcare Natural Language API for which there is this tutorial as well as this other one The tutorial outlines how to run the API on a string; I've been tasked with figuring out how to make use of the API with a dataset of medical text data. I am most comfortabl...
[ "Instead of using a service account you can use your own credentials, and supply them to your code using the \"application default credentials\". To set this up, make sure the GOOGLE_APPLICATION_CREDENTIALS environment variable is unset, then run gcloud auth application-default login (docs). After going through the...
[ 0 ]
[]
[]
[ "google_cloud_healthcare", "google_cloud_platform", "google_colaboratory", "google_healthcare_api", "python" ]
stackoverflow_0074451204_google_cloud_healthcare_google_cloud_platform_google_colaboratory_google_healthcare_api_python.txt
Q: psycopg2: insert multiple rows with one query I need to insert multiple rows with one query (number of rows is not constant), so I need to execute query like this one: INSERT INTO t (a, b) VALUES (1, 2), (3, 4), (5, 6); The only way I know is args = [(1,2), (3,4), (5,6)] args_str = ','.join(cursor.mogrify("%s", (...
psycopg2: insert multiple rows with one query
I need to insert multiple rows with one query (number of rows is not constant), so I need to execute query like this one: INSERT INTO t (a, b) VALUES (1, 2), (3, 4), (5, 6); The only way I know is args = [(1,2), (3,4), (5,6)] args_str = ','.join(cursor.mogrify("%s", (x, )) for x in args) cursor.execute("INSERT INTO t ...
[ "I built a program that inserts multiple lines to a server that was located in another city. \nI found out that using this method was about 10 times faster than executemany. In my case tup is a tuple containing about 2000 rows. It took about 10 seconds when using this method:\nargs_str = ','.join(cur.mogrify(\"(%s...
[ 286, 226, 104, 36, 32, 7, 3, 3, 2, 2, 2, 1, 1, 0 ]
[ "If you want to insert multiple rows within one insert statemens (assuming you are not using ORM) the easiest way so far for me would be to use list of dictionaries. Here is an example:\n t = [{'id':1, 'start_date': '2015-07-19 00:00:00', 'end_date': '2015-07-20 00:00:00', 'campaignid': 6},\n {'id':2, 'start_d...
[ -1, -1, -1, -4, -5 ]
[ "postgresql", "psycopg2", "python" ]
stackoverflow_0008134602_postgresql_psycopg2_python.txt
Q: ffmpeg issue with Jupyter notebook I am trying to extract frames from a video file using ffmpeg in Python. I installed ffmpeg using Homebrew and ffmpeg-python on the Anaconda-Navigator. Yet when I call ffmpeg on Jupyter notebook as follows !ffmpeg -i "$file" "$rootdir"/"$folder_name"/frame%04d.png I get an erro...
ffmpeg issue with Jupyter notebook
I am trying to extract frames from a video file using ffmpeg in Python. I installed ffmpeg using Homebrew and ffmpeg-python on the Anaconda-Navigator. Yet when I call ffmpeg on Jupyter notebook as follows !ffmpeg -i "$file" "$rootdir"/"$folder_name"/frame%04d.png I get an error saying zsh:1: command not found: ffmpe...
[ "In my experience, using !/usr/bin/ffmpeg was the solution, you can also verify this by trying !whereis ffmpeg and use whatever directory it's in after the ! hope this helps!\n" ]
[ 0 ]
[]
[]
[ "ffmpeg", "python" ]
stackoverflow_0074130520_ffmpeg_python.txt
Q: how to compare two columns in different data frames & replace the values Two dataframes are there, df1 has 2 columns ,name & profession df_1 Name profession srinu senior engineer Azahar engineer vijaya data analyst rahul team lead...
how to compare two columns in different data frames & replace the values
Two dataframes are there, df1 has 2 columns ,name & profession df_1 Name profession srinu senior engineer Azahar engineer vijaya data analyst rahul team lead swapna manager krishna engineer rama ...
[ "You could use:\n# extract the names from df_2\nm = (df_1['Name']\n .str.lower()\n .isin(df_2['Name-empid'].str.extract('(\\w+)-', expand=False))\n )\n\n# match with df_1 ensuring common case\ndf_1.loc[m, 'profession'] = 'Data Scientist'\n\nOutput:\n Name profession\n0 srinu senior engine...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "replace" ]
stackoverflow_0074462625_dataframe_pandas_python_replace.txt
Q: algorithm to know if inserted, substitued or deleted a character (similar to Levenshtein) I want to make a function that keeps track of the transformations made to make one string identical to another one Example: A = batyu B = beauty diff(A,B) has to return: [[1,"Insert", "e"], [5, "Delete"], [3, "Insert", "u"]]\...
algorithm to know if inserted, substitued or deleted a character (similar to Levenshtein)
I want to make a function that keeps track of the transformations made to make one string identical to another one Example: A = batyu B = beauty diff(A,B) has to return: [[1,"Insert", "e"], [5, "Delete"], [3, "Insert", "u"]]\ I used Levenshtein.editops but i want to code the function that does this
[ "The wikipedia article for levenshtein distance gives you the function it uses. Now it's your turn to implement it in python.\nIf you have code that does not do what you expect it to, feel free to post another question detailing what you tried, what you expected and why it didn't work.\nIf you can read C you can al...
[ 0, 0 ]
[]
[]
[ "algorithm", "levenshtein_distance", "python" ]
stackoverflow_0072020784_algorithm_levenshtein_distance_python.txt
Q: Dask lazy initialization very slow for list comprehension I'm trying to see if Dask would be a suitable addition to my project and wrote some very simple test cases to look into it's performance. However, Dask is taking a relatively long time to simply perform the lazy initialization. @delayed def normd(st): ...
Dask lazy initialization very slow for list comprehension
I'm trying to see if Dask would be a suitable addition to my project and wrote some very simple test cases to look into it's performance. However, Dask is taking a relatively long time to simply perform the lazy initialization. @delayed def normd(st): return st.lower().replace(',', '') @delayed def add_vald(v): ...
[ "When creating a delayed object, dask is doing a couple of things:\n\ncalculating a unique key for the object, based on the function and inputs\ncreating a graph object to store the desired operations.\n\nYou could probably do these things a little faster with your own dict comprehension - delayed is intended for c...
[ 0 ]
[]
[]
[ "dask", "dask_delayed", "loops", "parallel_processing", "python" ]
stackoverflow_0053622333_dask_dask_delayed_loops_parallel_processing_python.txt
Q: This queryset contains a reference to an outer query and may only be used in a subquery model ProductFilter has products ManyToManyField. I need to get attribute to_export from product.filters of the highest priority (ProductFilter.priority field) I figured out this filters = ProductFilter.objects.filter( prod...
This queryset contains a reference to an outer query and may only be used in a subquery
model ProductFilter has products ManyToManyField. I need to get attribute to_export from product.filters of the highest priority (ProductFilter.priority field) I figured out this filters = ProductFilter.objects.filter( products__in=[OuterRef('pk')] ).order_by('priority') Product.objects.annotate( filter_to_exp...
[ "This is old, but anyway:\nLooks like the related lookup cannot handle OuterRef here: products__in=[OuterRef('pk')]\nNote: In Django 3.2 the OP's example yields a different error, viz. TypeError: Field 'id' expected a number but got ResolvedOuterRef(pk).\nAs there's only one pk value here, I don't think you need to...
[ 0 ]
[]
[]
[ "django", "django_models", "django_queryset", "python", "sql" ]
stackoverflow_0060518636_django_django_models_django_queryset_python_sql.txt
Q: Unable to config pytesseract in heroku I try to deploy pytesseract app in heroku after doing much researchs online. I added TESSDATA_PREFIX=./.apt/usr/share/tesseract-ocr/4.00/tessdata in Heroku Config vars I have https://github.com/heroku/heroku-buildpack-apt in my heroku buildpack. I have Aptfile containing: tes...
Unable to config pytesseract in heroku
I try to deploy pytesseract app in heroku after doing much researchs online. I added TESSDATA_PREFIX=./.apt/usr/share/tesseract-ocr/4.00/tessdata in Heroku Config vars I have https://github.com/heroku/heroku-buildpack-apt in my heroku buildpack. I have Aptfile containing: tesseract-ocr tesseract-ocr-eng I have pytesse...
[ "The error message indicates a missing library:\nerror while loading shared libraries: libarchive.so.13: cannot open shared object file: No such file or directory\n\nThe apt buildpack doesn't do dependency resolution, so you may have to explicitly include transitive dependencies.\nYou can search https://packages.ub...
[ 0 ]
[]
[]
[ "heroku", "python", "python_tesseract" ]
stackoverflow_0074455213_heroku_python_python_tesseract.txt
Q: Can i use regex within a pytest expression Is it possible to locate tests with pytest using pattern matching, for example i want to find all tests that begin with the letters from a-m i have been trying things like pytest -m ^[aA-mM] pytest --collectonly -k test_^[aA-mM] --quiet Not got it to work so far, is thi...
Can i use regex within a pytest expression
Is it possible to locate tests with pytest using pattern matching, for example i want to find all tests that begin with the letters from a-m i have been trying things like pytest -m ^[aA-mM] pytest --collectonly -k test_^[aA-mM] --quiet Not got it to work so far, is this possible?
[ "Doesn't seem possible according to pytest doc.\nHave you considered marking the tests instead?\nThis helps with filtering them out when you run pytest.\nMore info about marking could be found in the pytest doc about markers...\nor another tutorial about it\nBut in short, for example:\n\njust add @pytest.mark.foo o...
[ 1 ]
[]
[]
[ "pytest", "python" ]
stackoverflow_0074378132_pytest_python.txt
Q: How to find the exponential of a number? What is the easiest/most optimal way of finding the exponential of a number, say x, in Python? i.e. how can I implement e^x? A: The easiest and most optimal way to do e^x in Python is: from math import exp print(exp(4)) Output >>> 54.598150033144236 A: You can use the...
How to find the exponential of a number?
What is the easiest/most optimal way of finding the exponential of a number, say x, in Python? i.e. how can I implement e^x?
[ "The easiest and most optimal way to do e^x in Python is:\nfrom math import exp\n\nprint(exp(4))\n\nOutput\n>>> 54.598150033144236\n\n", "You can use the math.exp() function from the math module (read the docs).\n>>> import math\n>>> x = 4\n>>> print(math.exp(x))\n54.598150033144236\n\n" ]
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074462623_python.txt
Q: Pandas - starting iteration index and slicing with .loc I'm still quite new to Python and programming in general. With luck, I have the right idea, but I can't quite get this to work. With my example df, I want iteration to start when entry == 1. import pandas as pd import numpy as np nan = np.nan a = [0,0,4,4,4...
Pandas - starting iteration index and slicing with .loc
I'm still quite new to Python and programming in general. With luck, I have the right idea, but I can't quite get this to work. With my example df, I want iteration to start when entry == 1. import pandas as pd import numpy as np nan = np.nan a = [0,0,4,4,4,4,6,6] b = [4,4,4,4,4,4,4,4] entry = [nan,nan,nan,nan,1,nan,...
[ "You can use boolean indexing:\n# what are the rows after entry?\nm1 = df['entry'].notna().cummax()\n# in which rows is a>b?\nm2 = df['a'].gt(df['b'])\n\n# set 1 where both conditions are True\ndf.loc[m1&m2, 'exit'] = 1\n\noutput:\n a b entry exit\n0 0 4 NaN NaN\n1 0 4 NaN NaN\n2 4 4 NaN N...
[ 1 ]
[]
[]
[ "pandas", "pandas_loc", "python" ]
stackoverflow_0074462705_pandas_pandas_loc_python.txt
Q: pytest parameterisation and asyncio coroutines I have the following test: @pytest.mark.parametrize( "raw_id", [28815543, "PMC5890441", "doi:10.1007/978-981-10-5203-3_9" "28815543"] ) def test_can_fetch_publication(raw_id): idr = IdReference.build(raw_id) res = asyncio.run(fetch.summary(idr)) a...
pytest parameterisation and asyncio coroutines
I have the following test: @pytest.mark.parametrize( "raw_id", [28815543, "PMC5890441", "doi:10.1007/978-981-10-5203-3_9" "28815543"] ) def test_can_fetch_publication(raw_id): idr = IdReference.build(raw_id) res = asyncio.run(fetch.summary(idr)) assert res == { "id": "28815543", "so...
[ "this is not async code. Fixing the test is trivial, but you will have to change your code, please read the whole text.\nThe part responsible to getting you the same (and therefore an \"already used\") co-routine in this code is the lru_cache.\nJust reset the cache in your test body, preventing you from getting use...
[ 1 ]
[]
[]
[ "pytest", "python", "python_asyncio" ]
stackoverflow_0074459672_pytest_python_python_asyncio.txt
Q: Looping through a list and coloring the text as appropriate based on values I have a large list of names and scores from a survey. I am hoping there is a simple way to loop through the list and color the score red or green based on its value. I have successfully been able to color one of the values but my solution...
Looping through a list and coloring the text as appropriate based on values
I have a large list of names and scores from a survey. I am hoping there is a simple way to loop through the list and color the score red or green based on its value. I have successfully been able to color one of the values but my solution requires a lot of lines and I am hoping there is a quicker way to accomplish thi...
[ "I realize this may be a unique issue but if anyone comes across a similar problem I have found a solution after a lot of trial and error:\nI have added the score.iloc to a list, then under a new function looped through the list and colored as needed:\nglobal avgs\navgs = []\n\ntry:\n one_frame['text'] = score.i...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074433629_python_tkinter.txt
Q: Conditionally join a list of strings in Jinja I have a list like users = ['tom', 'dick', 'harry'] In a Jinja template I'd like to print a list of all users except tom joined. I cannot modify the variable before it's passed to the template. I tried a list comprehension, and using Jinja's reject filter but I haven'...
Conditionally join a list of strings in Jinja
I have a list like users = ['tom', 'dick', 'harry'] In a Jinja template I'd like to print a list of all users except tom joined. I cannot modify the variable before it's passed to the template. I tried a list comprehension, and using Jinja's reject filter but I haven't been able to get these to work, e.g. {{ [name fo...
[ "Use reject filter with sameas test:\n>>> import jinja2\n>>> template = jinja2.Template(\"{{ users|reject('sameas', 'tom')|join(',') }}\")\n>>> template.render(users=['tom', 'dick', 'harry'])\nu'dick,harry'\n\nUPDATE\nIf you're using Jinja 2.8+, use equalto instead of sameas as @Dougal commented; sameas tests with ...
[ 24, 13, 1, 0 ]
[]
[]
[ "jinja2", "python" ]
stackoverflow_0024041885_jinja2_python.txt
Q: How to group redundant values in pytest parametrize test? I am trying to remove redundant rows in my parametrized tests. Redundant - I mean I repeat this kind of code all the time. Here is example of my test: 1 @pytest.mark.parametrize("field, violations", [ 2 (None, [NULL_VIOLATION]), 3 (True, []), 4 ...
How to group redundant values in pytest parametrize test?
I am trying to remove redundant rows in my parametrized tests. Redundant - I mean I repeat this kind of code all the time. Here is example of my test: 1 @pytest.mark.parametrize("field, violations", [ 2 (None, [NULL_VIOLATION]), 3 (True, []), 4 (False, []) 5 ]) 6 def test_validate_field(field: str, vi...
[ "I'd go with the following: put the list of the paths into a variable, which contains a list...\npath_params = [(None, [NULL_VIOLATION]), (True, []), (False, [])]\n\nAnd then, pass that variable into parametrize:\n@pytest.mark.parametrize(\"field, violations\", path_params)\n\nUPD: naturally, this would only work i...
[ 1, 0 ]
[]
[]
[ "pytest", "python", "python_3.x" ]
stackoverflow_0074375816_pytest_python_python_3.x.txt
Q: Moving desired row to the top of pandas Data Frame In pandas, how can I copy or move a row to the top of the Data Frame without creating a copy of the Data Frame? For example, I managed to do almost what I want with the code below, but I have the impression that there might be a better way to accomplish this: impo...
Moving desired row to the top of pandas Data Frame
In pandas, how can I copy or move a row to the top of the Data Frame without creating a copy of the Data Frame? For example, I managed to do almost what I want with the code below, but I have the impression that there might be a better way to accomplish this: import pandas as pd df = pd.DataFrame({'Probe':['Test1','Te...
[ "pandas.concat:\ndf = pd.concat([df.iloc[[n],:], df.drop(n, axis=0)], axis=0)\n\n", "Try this. You don't need to make a copy of the dataframe.\ndf[\"new\"] = range(1,len(df)+1)\n\n Probe Sequence new\n0 Test1 AATGCGT 1\n1 Test2 TGCGTAA 2\n2 Test3 ATGCATG 3\n\n\ndf.ix[2,'new'] = 0\ndf.sort_values...
[ 7, 7, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0038980507_pandas_python.txt
Q: Make an array (1, x, x^2) based on x in dataframe Let's suppose that I have dataframe df similar like: c0 c1 10 2 8 2 4 1 How can I make an np.array for each element of this datafrmae so that I have for each element array (1, x, x^2)? For example for col1, first elemen...
Make an array (1, x, x^2) based on x in dataframe
Let's suppose that I have dataframe df similar like: c0 c1 10 2 8 2 4 1 How can I make an np.array for each element of this datafrmae so that I have for each element array (1, x, x^2)? For example for col1, first element (0) should get the array [1, 2, 4], for c0, for the f...
[ "The numpy approach would be to broadcast to a 3D array:\nout = df.to_numpy()[...,None]**[0,1,2]\n\nOutput:\narray([[[ 1, 10, 100],\n [ 1, 2, 4]],\n\n [[ 1, 8, 64],\n [ 1, 2, 4]],\n\n [[ 1, 4, 16],\n [ 1, 1, 1]]])\n\nIf you want a (2, 3, 3) shape, swap the a...
[ 1 ]
[]
[]
[ "pandas", "polynomials", "python" ]
stackoverflow_0074462806_pandas_polynomials_python.txt
Q: How to create a n to n matrix in python with input value diagonal I am working on a probabilistic calculation and I could run my code for a small matrix like; P_4 = np.array([ [0 ,1 ,0 , 0, 0], [0 ,1/4,3/4, 0, 0], [0 ,0 ,2/4,2/4, 0], [0 ,0 ,0 ,3/4,1/4], [0 ,0 ,0 , 0,...
How to create a n to n matrix in python with input value diagonal
I am working on a probabilistic calculation and I could run my code for a small matrix like; P_4 = np.array([ [0 ,1 ,0 , 0, 0], [0 ,1/4,3/4, 0, 0], [0 ,0 ,2/4,2/4, 0], [0 ,0 ,0 ,3/4,1/4], [0 ,0 ,0 , 0,1 ], ]) However, I would like to create a N*N matrix and to fill ...
[ "Here's one option using linspace and diag.\nn = 5\ndiag = np.linspace(0, 1, n)\ndiag1 = (1 - diag[:-1])\na = np.diag(diag) + np.diag(diag1, 1)\na\n\nOutput:\narray([[0. , 1. , 0. , 0. , 0. ],\n [0. , 0.25, 0.75, 0. , 0. ],\n [0. , 0. , 0.5 , 0.5 , 0. ],\n [0. , 0. , 0. , 0.75, 0.25]...
[ 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074462782_numpy_python.txt
Q: Multiprocess does not apply list change to all processes How i can share list changes between multiprocessing parallel process?, im having trouble with that. import multiprocessing listx = [] def one(): global listx time.sleep(5) if 'ok' not in listx: print('not in') else: print('in') def two():...
Multiprocess does not apply list change to all processes
How i can share list changes between multiprocessing parallel process?, im having trouble with that. import multiprocessing listx = [] def one(): global listx time.sleep(5) if 'ok' not in listx: print('not in') else: print('in') def two(): global listx listx.append('ok') if __name__ == '__main__...
[ "If you don't specifically need multiprocessing, you can use threading, as they share resources. Else, you need to use a pipes and queues to synchronize your resources: doc\n", "You can used a managed list:\nimport multiprocessing\nimport time\n\ndef one(listx):\n time.sleep(5)\n if 'ok' not in listx:\n ...
[ 0, 0 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0074442936_multiprocessing_python.txt
Q: pandas agg using "intermediate" column without recomputing [group size] times the same value Let's say I have a DataFrame df=pd.DataFrame({'a':[1,2,np.nan,3,4,5,3], 'b':[11,22,22,11,22,22,22]}) a b 0 1.0 11 1 2.0 22 2 NaN 22 3 3.0 11 4 4.0 22 5 5.0 22 6 3.0 22 I want compute a reduced datafra...
pandas agg using "intermediate" column without recomputing [group size] times the same value
Let's say I have a DataFrame df=pd.DataFrame({'a':[1,2,np.nan,3,4,5,3], 'b':[11,22,22,11,22,22,22]}) a b 0 1.0 11 1 2.0 22 2 NaN 22 3 3.0 11 4 4.0 22 5 5.0 22 6 3.0 22 I want compute a reduced dataframe where I group by b, and where my column depends on the groupwise mean. Specifically, I want the...
[ "Don't use python's sum, use the vectorial counterpart, it will enable you to compute the mean only once per group:\ndf.groupby('b')['a'].agg(c=lambda s: s.lt(s.mean()).sum())\n\noutput:\n c\nb \n11 1\n22 2\n\nSpeed comparison\n## provided example\n\n# vectorial approach\n1.07 ms ± 33.2 µs per loop (mean ± ...
[ 0, 0 ]
[]
[]
[ "aggregate", "dataframe", "group_by", "pandas", "python" ]
stackoverflow_0074461707_aggregate_dataframe_group_by_pandas_python.txt
Q: How to make countdown in python without using time.sleep method? I'm new to python. I wonder if there any way to make countdown program in python without using any external library and time.sleep method? Please give me an example with code. thanks in advance. A: You could use the Unix Timestamp, which gives you ...
How to make countdown in python without using time.sleep method?
I'm new to python. I wonder if there any way to make countdown program in python without using any external library and time.sleep method? Please give me an example with code. thanks in advance.
[ "You could use the Unix Timestamp, which gives you a precise value of the seconds wich have passed since the first day of 1970. By substracting a startvalue of this from the actual time each checking time, you can calculate the time that has passed since your desired time. You can get the Unixseconds in python with...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0068783625_python.txt
Q: Removing a particular node on a specific line for all .xml files in a folder I would really appreciate if i can get help with this problem, I have got hundreds of .xml files in a folder lets say /annots, and each .xml has a node called <occluded>0</occluded> and I am basically trying to iterate through all the .xm...
Removing a particular node on a specific line for all .xml files in a folder
I would really appreciate if i can get help with this problem, I have got hundreds of .xml files in a folder lets say /annots, and each .xml has a node called <occluded>0</occluded> and I am basically trying to iterate through all the .xml files in the folder /annots and delete that node <occluded>0</occluded> from all...
[ "If you want to do it by line number, you can simply use sed:\nsed -i.bkp -e'19d' annots/*.xml\n\nWill delete line 19 on all *.xml files in folder annots. The original files will be retained with .bkp suffix.\nIf you cannot rely on the line number, but want to parse the XML and delete the tag, xmlstarlet is your fr...
[ 1 ]
[]
[]
[ "linux", "python", "xml", "xml_parsing" ]
stackoverflow_0074462396_linux_python_xml_xml_parsing.txt
Q: Tkinter window background color does not reflect in the window I have used time.sleep(5) to see if the changes are reflected in the window. The window opens in blue color. After I click on the 'Go' button it changes to yellow. But why does it not change to green when it enters the function 'func2'? import time imp...
Tkinter window background color does not reflect in the window
I have used time.sleep(5) to see if the changes are reflected in the window. The window opens in blue color. After I click on the 'Go' button it changes to yellow. But why does it not change to green when it enters the function 'func2'? import time import tkinter global win def func1(): global win win = tkinter....
[ "Basically what happens is that you don't return to the mainloop where the commands and all the other fancy stuff happens / get executed. Without processing the e.g win.configure(bg='green') your window won't get green. So before you change the value of the background color you should make sure to either update_idl...
[ 1, 1 ]
[]
[]
[ "python", "tkinter", "user_interface" ]
stackoverflow_0074462622_python_tkinter_user_interface.txt
Q: RadioButton not selected tkinter I've been learning tkinter and I ran into this thing I don't understand, what does it mean when a radio button has a '-'? it's like is neither marked nor unmarked, is it not returning anything? I grabbed this code from the internet so anyone can see what I mean: from tkinter import...
RadioButton not selected tkinter
I've been learning tkinter and I ran into this thing I don't understand, what does it mean when a radio button has a '-'? it's like is neither marked nor unmarked, is it not returning anything? I grabbed this code from the internet so anyone can see what I mean: from tkinter import * root = Tk() btn1 = StringVar() d...
[ "Use IntVar() instead of StringVar(). In Python 3.8+ Used f-string format.\nHere is code:\nfrom tkinter import *\n\nroot = Tk()\nbtn1 = IntVar()\n\n\ndef do_something():\n val0 = float(entry1.get())\n val1 = val0\n print(f\"The variable values are {val1} and {val0}\")\n print(f\"The method values are {...
[ 0 ]
[]
[]
[ "python", "radio_button", "tkinter" ]
stackoverflow_0074454609_python_radio_button_tkinter.txt
Q: tkinter window without the surrounding I was wondering if there is a way to remove the borders (titlebar with buttons and the edges on each side) of a tkinter window. Does someone know how to do that? Couldn't find any solution for this in the web.
tkinter window without the surrounding
I was wondering if there is a way to remove the borders (titlebar with buttons and the edges on each side) of a tkinter window. Does someone know how to do that? Couldn't find any solution for this in the web.
[]
[]
[ "Try to set borderwidth and highlightthickness to 0\n" ]
[ -1 ]
[ "customization", "python", "titlebar", "tkinter", "window" ]
stackoverflow_0074462908_customization_python_titlebar_tkinter_window.txt
Q: Heroku Django: Looking for wrong GDAL version on new Heroku-22 Stack UPDATE Upgrading Django to version 3.2 has not fixed the error. I am receiving the same error message, just with different versions django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal3.1.0", "...
Heroku Django: Looking for wrong GDAL version on new Heroku-22 Stack
UPDATE Upgrading Django to version 3.2 has not fixed the error. I am receiving the same error message, just with different versions django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal3.1.0", "gdal3.0.0", "gdal2.4.0", "gdal2.3.0", "gdal2.2.0", "gdal2.1.0", "gdal2.0.0...
[ "What version of Django are you using? I suspect it's quite old.\nThe list of supported versions of GDAL for Django 2.1 matches the list in your error message:\n\n2.2\n2.1\n2.0\n1.11\n1.10\n1.9\n\nYou'll have to upgrade to at least Django 3.0 to get support for GDAL 2.4, but even that version is well beyond its ex...
[ 1 ]
[]
[]
[ "django", "gdal", "gis", "heroku", "python" ]
stackoverflow_0074453238_django_gdal_gis_heroku_python.txt
Q: Python Selenium driver.find_element().text returns empty string, but text is visible in the driver.page_source I'm trying to scrape some titles of the videos and to do so I'm using Selenium, but I've encountered a problem. driver.find_element().text returns empty string, but title is for sure located in given XPAT...
Python Selenium driver.find_element().text returns empty string, but text is visible in the driver.page_source
I'm trying to scrape some titles of the videos and to do so I'm using Selenium, but I've encountered a problem. driver.find_element().text returns empty string, but title is for sure located in given XPATH. Here is the fragment of the page source returned by driver.page_source: <div class="title"><a href="/f/4n3x7e31hp...
[ "You have to wait for element to be completely loaded before extracting it text content. WebDriverWait expected_conditions explicit waits should be used for that.\nThis should wait in case the element is visible on the page and the locator is correct:\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom s...
[ 1, 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074462555_python_selenium_selenium_webdriver.txt
Q: Return dataframe variable on multiprocessing I want to import (pd.read_pickle) 4 files at the same time but later in the code I can't use the variables. How can I get the returned dataframes of the functions on multiprocessing. def a(): df1 = pd.read_pickle(r"C:\xampp\htdocs\bi\cache\ventas.pkl") return df...
Return dataframe variable on multiprocessing
I want to import (pd.read_pickle) 4 files at the same time but later in the code I can't use the variables. How can I get the returned dataframes of the functions on multiprocessing. def a(): df1 = pd.read_pickle(r"C:\xampp\htdocs\bi\cache\ventas.pkl") return df1 def b(): df2 = pd.read_pickle(r"C:\xampp\htd...
[ "Judging by your file names, it appears you are running under Windows. If so, any code that creates child processes must be invoked from a if __name__ == '__main__': block.\nWhether you can save any time by using multiprocessing is questionable. The worker functions a, b, c and d are possibly too trivial and doing ...
[ 0 ]
[]
[]
[ "dataframe", "multiprocessing", "multithreading", "pandas", "python" ]
stackoverflow_0074421948_dataframe_multiprocessing_multithreading_pandas_python.txt
Q: convert "tensorflow.python.framework.ops.EagerTensor" to tensorflow.Tensor or torch.Tensor? This my function that SHOULD convert an img or jpeg file to a tensor, so that I can then feed it to my AI but it returns a "tensorflow.python.framework.ops.EagerTensor" and I can't figure out how to convert it to a native f...
convert "tensorflow.python.framework.ops.EagerTensor" to tensorflow.Tensor or torch.Tensor?
This my function that SHOULD convert an img or jpeg file to a tensor, so that I can then feed it to my AI but it returns a "tensorflow.python.framework.ops.EagerTensor" and I can't figure out how to convert it to a native f or torch tensor. def imgprocessing(path): test_img = image.load_img(path, target_size=(28, 2...
[ "Q: I can't figure out how to convert it to a native f or torch tensor.\nError: AttributeError: 'Tensor' object has no attribute 'numpy'\nYou can do it by this step but you may not convert from array to tf.constant within the definition ( tensorflow.python.framework.ops.EagerTensor ). You cannot convert to NumPy wh...
[ 0 ]
[]
[]
[ "python", "pytorch", "tensorflow" ]
stackoverflow_0074462224_python_pytorch_tensorflow.txt
Q: Openpyxl to delete Table row in Excel I'm having a bad time figuring out how to delete an entire empty row. When the row is part of an Excel Table. So I tried with the following code. But it keeps the format of the table and it doesn't work ie for Functions like Count If, because it counts those blank rows. from o...
Openpyxl to delete Table row in Excel
I'm having a bad time figuring out how to delete an entire empty row. When the row is part of an Excel Table. So I tried with the following code. But it keeps the format of the table and it doesn't work ie for Functions like Count If, because it counts those blank rows. from openpyxl import load_workbook as lw wb = lw...
[ "I used this solution:\nimport xlwings as xw\nfrom xlwings.constants import DeleteShiftDirection\n\napp = xw.App(visible=False)\nwb = app.books.open('PathtoFile')\nsht = wb.sheets['SheetName']\n\nendrow = XX #number of target row from you want to delete below\n\n# Delete after endrow till row 10,000\nsht.range(str(...
[ 0 ]
[]
[]
[ "excel", "openpyxl", "python" ]
stackoverflow_0074214146_excel_openpyxl_python.txt
Q: How to loop through indexes from lists nested in a dictionary? I created the following dictionary below (mean_task_dict). This dictionary includes three keys associated with three lists. Each lists includes 48 numeric values. mean_task_dict = { "Interoception": task_mean_intero, "Exterocept...
How to loop through indexes from lists nested in a dictionary?
I created the following dictionary below (mean_task_dict). This dictionary includes three keys associated with three lists. Each lists includes 48 numeric values. mean_task_dict = { "Interoception": task_mean_intero, "Exteroception": task_mean_extero, "Cognitive": task_mean_cognit, ...
[ "Do you want something like this?\nROI_positions = np.array([1, 2, 3])\nfor i in range(len(mean_task_dict)):\n data_ROIs = np.array([\n mean_task_dict[\"Interoception\"][i],\n mean_task_dict[\"Exteroception\"][i],\n mean_task_dict[\"Cognitiv...
[ 2, 0 ]
[]
[]
[ "dictionary", "for_loop", "python" ]
stackoverflow_0074462724_dictionary_for_loop_python.txt
Q: Is there a way to separate a dict into separate data frames with unique names? I'm new to python, so please forgive me if this is a stupid question. I'm trying to separate a bigger dataset into smaller data frames based on a unique row value (station ID). I've done the following, which made a dict and did separate...
Is there a way to separate a dict into separate data frames with unique names?
I'm new to python, so please forgive me if this is a stupid question. I'm trying to separate a bigger dataset into smaller data frames based on a unique row value (station ID). I've done the following, which made a dict and did separate them into smaller data frames, but within this dict? dfs = dict(list(df.groupby('St...
[ "If you need a dict specifically, you can use\ndfs = {name: group for name, group in df.groupby('Station')}\n\nbut that creates copies of data; try iterating over the groups (and names) directly with\nfor name, group in df.groupby('Station'):\n # logic\n\n" ]
[ 0 ]
[]
[]
[ "database", "organization", "pandas", "python" ]
stackoverflow_0074463056_database_organization_pandas_python.txt
Q: Python/matplotlib : getting rid of matplotlib.mpl warning I am using matplotlib using python 3.4. When I start my program, I have the following warning message: C:\Python34-32bits\lib\site-packages\matplotlib\cbook.py:123: MatplotlibDeprecationWarning: The matplotlib.mpl module was deprecated in version 1.3. ...
Python/matplotlib : getting rid of matplotlib.mpl warning
I am using matplotlib using python 3.4. When I start my program, I have the following warning message: C:\Python34-32bits\lib\site-packages\matplotlib\cbook.py:123: MatplotlibDeprecationWarning: The matplotlib.mpl module was deprecated in version 1.3. Use import matplotlib as mpl instead. warnings.warn(message, ...
[ "You can suppress that particular warning, which is probably the preferred way:\nimport warnings\nimport matplotlib.cbook\nwarnings.filterwarnings(\"ignore\",category=matplotlib.cbook.mplDeprecation)\n\n", "you can temporarily suppress a warning, when importing\nimport warnings\n\ndef fxn():\n warnings.warn(\"...
[ 41, 3, 1, 0, 0 ]
[]
[]
[ "deprecation_warning", "matplotlib", "python" ]
stackoverflow_0024502500_deprecation_warning_matplotlib_python.txt
Q: Django Form : cleaned_data.get(field name) is returning None in clean() method I am following the Django documentation of Django form but unable to understand what is the issue in my code. I am writing the below code in the clean method to check if both name and email starts with lowercase s or not but Django is r...
Django Form : cleaned_data.get(field name) is returning None in clean() method
I am following the Django documentation of Django form but unable to understand what is the issue in my code. I am writing the below code in the clean method to check if both name and email starts with lowercase s or not but Django is returning None in cleaned_data.get(field name) method and I am getting "Attribute err...
[ "It seems that form is not receiving any data, that's why it returned NoneType, although you can use default value to prevent error as:\ndef clean(self):\n cleaned_data = super().clean()\n name = cleaned_data.get('name', \"Sujit Singh\")\n email = cleaned_data.get('email', \"sujit123@gmail.com\")\n if n...
[ 1 ]
[]
[]
[ "django", "django_forms", "django_templates", "django_views", "python" ]
stackoverflow_0074461298_django_django_forms_django_templates_django_views_python.txt
Q: Collapse pandas data frame based on column I have a table below , I will like to group and concatenate into a new field based on the siteid using pandas/python <!DOCTYPE html> <html> <style> table, th, td { border:1px solid black; } </style> <body> <table style="width:100%"> <tr> <th>SiteID</th> <th>...
Collapse pandas data frame based on column
I have a table below , I will like to group and concatenate into a new field based on the siteid using pandas/python <!DOCTYPE html> <html> <style> table, th, td { border:1px solid black; } </style> <body> <table style="width:100%"> <tr> <th>SiteID</th> <th>Name</th> <th>Count</th> </tr> <tr> ...
[ "You can use a custom groupby.agg:\nout = (\n (df['Name']+': '+df['Count'].astype(str))\n .groupby(df['SiteID']).agg(', '.join)\n .reset_index(name='Output')\n)\n\noutput:\n SiteID Output\n0 A Conserve: 3, Listed: 5\n1 B Listed: 5\n\nIf you need the leading \"There are\":\...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074462966_pandas_python.txt
Q: Parsing JSON response for individual value I'm having trouble parsing the below JSON Response Dict object to just return/print the 'data' value (testing.test.com). See the dict below: [{'_id': '~1742209152', 'id': '~1742209152', 'createdBy': 'test@test.com', 'createdAt': 1666089754558, '_type': 'case_artifact', '...
Parsing JSON response for individual value
I'm having trouble parsing the below JSON Response Dict object to just return/print the 'data' value (testing.test.com). See the dict below: [{'_id': '~1742209152', 'id': '~1742209152', 'createdBy': 'test@test.com', 'createdAt': 1666089754558, '_type': 'case_artifact', 'dataType': 'domain', 'data': 'testing.test.com'...
[ "your response is a list of dict objects. note that the first opening brackets are [ and not {.\nyou need to address the first (and only) object in your example and then access it as a dict using the 'data' key.\ntry print(observables[0]['data'])\nEDIT:\nafter seeing more of the code in chat room, and figuring out ...
[ 2 ]
[]
[]
[ "json", "jsonresponse", "parsing", "python", "scripting" ]
stackoverflow_0074463094_json_jsonresponse_parsing_python_scripting.txt
Q: confusing about nested for loop in order to increase multiple index The question is asking to create a nested loop to append and increase multiple index in a 2D list,for somehow I can't print the element in the list and i tried to print the length of the list it just return 0. the expect value in the list is: If d...
confusing about nested for loop in order to increase multiple index
The question is asking to create a nested loop to append and increase multiple index in a 2D list,for somehow I can't print the element in the list and i tried to print the length of the list it just return 0. the expect value in the list is: If duration of the music sequence is 1s, starting pitch is 60 and ending pitc...
[ "Calculate the duration of each note by dividing the total duration by the number of notes. Then use this in a list comprehension.\ndef pitches_list(start, end, total_duration):\n duration = total_duration / (end - start + 1)\n return [[i * duration, start + i, duration] for i in range(end - start + 1)]\n\n",...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074449237_python_python_3.x.txt
Q: amending the x-axis of a histogram created with the df.hist function I am using the df.hist function and am looping through variables to create histogram plots. I would like to create plots where the x-axis values are directly below the bars. As one example, I have attached the following plot. Here, I don't want '...
amending the x-axis of a histogram created with the df.hist function
I am using the df.hist function and am looping through variables to create histogram plots. I would like to create plots where the x-axis values are directly below the bars. As one example, I have attached the following plot. Here, I don't want '1.5','2.5' or '3.5' to be displayed on the x-axis and for the numbers '1',...
[ "Since the x-values are discrete, a histogram is not the right tool here. Instead, it seems like you want to create a bar plot. So try replacing df.hist() with df.plot.bar().\n" ]
[ 0 ]
[]
[]
[ "dataframe", "jupyter_notebook", "pandas", "python" ]
stackoverflow_0074463110_dataframe_jupyter_notebook_pandas_python.txt
Q: convert cosine similarity distance to confidence percent I am working to features of images based on deep learning techniques, and for labeling images, I specify the desired label with a threshold using cosine distance. The algorithm is as follows: import math from itertools import izip def dot_product(v1, v2): ...
convert cosine similarity distance to confidence percent
I am working to features of images based on deep learning techniques, and for labeling images, I specify the desired label with a threshold using cosine distance. The algorithm is as follows: import math from itertools import izip def dot_product(v1, v2): return sum(map(lambda x: x[0] * x[1], izip(v1, v2))) def c...
[ "Cosine is a sinosoidal function which is a non-linear function. Thus calculating linear distances from cosine values would be a mistake. One good approximation would be treating cosine angle as linearly spaced and finding distance from cosine inverse function i.e. angle instead of cosine value itself.\n import mat...
[ 0 ]
[]
[]
[ "cosine_similarity", "numpy", "python" ]
stackoverflow_0070859038_cosine_similarity_numpy_python.txt
Q: How can I use python to find specific Thai word in multiple csv file and return list of file name that's contain the word I have like 100+ file in directory and I need to find out which files contain the word in Thai that I looking for Thank you I try this but it doesn't work ` import pandas as pd import re import...
How can I use python to find specific Thai word in multiple csv file and return list of file name that's contain the word
I have like 100+ file in directory and I need to find out which files contain the word in Thai that I looking for Thank you I try this but it doesn't work ` import pandas as pd import re import os FOLDER_PATH = r'C:\Users\project' list = os.listdir(FOLDER_PATH) def is_name_in_csv(word,csv_file): with open(csv_fil...
[ "You don't need regex. You can simply check if word in fileContents. Also, I changed list to paths because list is a built-in python keyword.\nimport os\n\npaths = os.listdir(r'C:\\Users\\project')\n\ndef files_with_word(word:str, paths:list) -> str:\n for path in paths:\n with open(path, \"r\") as f:\n ...
[ 0 ]
[]
[]
[ "csv", "python", "thai" ]
stackoverflow_0074463103_csv_python_thai.txt
Q: error Name 'false' is not defined when adding "justMyCode": false to launch.json in Visual Studio Code when using arguments to run my debugger Name 'false' is not defined when adding "justMyCode": false to launch.json in Visual Studio Code 3 Getting this error when trying to debug my program in python, I'm trying ...
error Name 'false' is not defined when adding "justMyCode": false to launch.json in Visual Studio Code when using arguments to run my debugger
Name 'false' is not defined when adding "justMyCode": false to launch.json in Visual Studio Code 3 Getting this error when trying to debug my program in python, I'm trying to run with these arguments as shown in the configuration "configurations": [ { "name": "Python: Current File", "typ...
[ "So this has worked,\n{\n \"version\": \"0.2.0\",\n \"configurations\": [\n {\n \"name\": \"Python: Current File\",\n \"type\": \"python\",\n \"request\": \"launch\",\n \"program\": \"main.py\",\n \"console\": \"integratedTerminal\",\n \...
[ 0 ]
[]
[]
[ "debugging", "python", "vscode_debugger" ]
stackoverflow_0074462903_debugging_python_vscode_debugger.txt
Q: Convert bytestring to float in python I am working on a project where I read data which is written into memory by a Delphi/Pascal program using memory mapping on a Windows PC. I am now mapping the memory again using pythons mmap and the handle given by the other program and as expected get back a bytestring. I kno...
Convert bytestring to float in python
I am working on a project where I read data which is written into memory by a Delphi/Pascal program using memory mapping on a Windows PC. I am now mapping the memory again using pythons mmap and the handle given by the other program and as expected get back a bytestring. I know that this should represent 13 8-byte floa...
[ "Try using numpys frompuffer function. You will get an array you can than read:\nhttps://numpy.org/doc/stable/reference/generated/numpy.frombuffer.html\nimport numpy as np\n\nbuffer = b'\\xcd\\xcc\\xcc\\xe0\\xe6v\\xb9\\xbf\\x9a\\x99\\x99!F\\xcd&@\\xf5\\xa2\\xc5,.\\xaf\\xbd\\xbf\\x95\\xb0\\xea\\xb5\\xae\\n\\xd9?333/...
[ 1 ]
[]
[]
[ "floating_point", "mmap", "python" ]
stackoverflow_0074463167_floating_point_mmap_python.txt
Q: How to compare different dataframes by column? I have two csv files with 200 columns each. The two files have the exact same numbers in rows and columns. I want to compare each columns separately. The idea would be to compare column 1 value of file "a" to column 1 value of file "b" and check the difference and so ...
How to compare different dataframes by column?
I have two csv files with 200 columns each. The two files have the exact same numbers in rows and columns. I want to compare each columns separately. The idea would be to compare column 1 value of file "a" to column 1 value of file "b" and check the difference and so on for all the numbers in the column (there are 100 ...
[ "df1 = pd.DataFrame(dict(cola=[1,2,3,4], colb=[4,5,6,7]))\ndf2 = pd.DataFrame(dict(cola=[1,2,4,5], colb=[9,7,8,9]))\n\nfor col in df1.columns:\n diff = df1[col].compare(df2[col])\n if diff.shape[0] >= 3:\n print(f'Found {diff.shape[0]} diffs in {col}')\n print(diff)\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "for_loop", "pandas", "python" ]
stackoverflow_0074463001_dataframe_for_loop_pandas_python.txt
Q: I cant click on a button with Selenium Its my first time using selenium and I am developing a project to download a meeting attendence on Microsoft Teams, The code works well and i can get to the screen that I need to make de download The screen, now I just need to click on "Baixar", but it doesn't work, My code: ...
I cant click on a button with Selenium
Its my first time using selenium and I am developing a project to download a meeting attendence on Microsoft Teams, The code works well and i can get to the screen that I need to make de download The screen, now I just need to click on "Baixar", but it doesn't work, My code: BAIXAR = (By.XPATH, '//*[@id="app"]/div/div/...
[ "The wait statement with EC.element_to_be_clikable() will return you boolean (True/False). Hence you can't apply .click() with Boolean.\nInstead use the same wait statement with EC.presence_of_element_located\nobjelement=WebDriverWait(navegador60).until(EC.presence_of_element_located((BAIXAR))\nobjelement.click()\n...
[ 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074461302_python_selenium.txt
Q: Airflow DAG: How to insert data into a table using Python operator, not BigQuery operator? I am trying to insert some data into a table using a simple Python operator, not the BigQuery operator, but I am unsure how to implement this. I am trying to implement this in the form of an Airflow DAG. I have written a sim...
Airflow DAG: How to insert data into a table using Python operator, not BigQuery operator?
I am trying to insert some data into a table using a simple Python operator, not the BigQuery operator, but I am unsure how to implement this. I am trying to implement this in the form of an Airflow DAG. I have written a simple DAG, and I have managed to use the following to insert the data from a GCS Bucket to BigQuer...
[ "You can use BigQuery Python client in a PythonOperator to insert GCS files to BigQuery, example :\nPythonOperator(\n task_id=\"gcs_to_bq\",\n op_kwargs={\n 'dataset': 'dataset',\n 'table': 'table'\n },\n python_callable=load_gcs_files_to_bq\n)\n\ndef load_gcs_files_to_bq(dataset, table):\n ...
[ 0 ]
[]
[]
[ "airflow", "directed_acyclic_graphs", "google_cloud_storage", "python", "sql" ]
stackoverflow_0074462042_airflow_directed_acyclic_graphs_google_cloud_storage_python_sql.txt
Q: Create Columns in Dataframe Inside Loop With Filters Pyspark I want to create columns for each element in list "weeks" and have them be all in one dataframe. Dataframe "df" is filtered based on "weeknum" then the columns are created. At the time it runs but the end dataframe only contains information about the las...
Create Columns in Dataframe Inside Loop With Filters Pyspark
I want to create columns for each element in list "weeks" and have them be all in one dataframe. Dataframe "df" is filtered based on "weeknum" then the columns are created. At the time it runs but the end dataframe only contains information about the last "weeknum". How can I create the columns for all "weeknum" joined...
[ "I would suggest generating all of the required columns first, and then passing it into a select function like this:\nfrom pyspark.sql.functions import col\n\nweeks = [24, 25]\ncols_to_select = []\nfor weeknum in weeks:\n cols_to_select.extend([\n col('0.01').alias(f'units_1_share_wk{weeknum}'),\n ...
[ 0 ]
[]
[]
[ "databricks", "dataframe", "loops", "pyspark", "python" ]
stackoverflow_0074459610_databricks_dataframe_loops_pyspark_python.txt
Q: How to kick a user using slash commands Discord.py I'm trying to make my Discord bot kick a member, and send that "user banned because reason" to a specific channel and not the channel the command was used. The code I'm using: @bot.slash_command(description = "Kick someone", guild_ids=[1041057700823449682]) @comma...
How to kick a user using slash commands Discord.py
I'm trying to make my Discord bot kick a member, and send that "user banned because reason" to a specific channel and not the channel the command was used. The code I'm using: @bot.slash_command(description = "Kick someone", guild_ids=[1041057700823449682]) @commands.has_permissions(kick_members=True) @option("member",...
[ "I believe the cause of your error is your channel definition inside your kick command definition. Try removing the channel definition from your kick command definition and put it inside the function instead. The way I have it setup on my bot, other than the channel definition, is the same as yours and mine works p...
[ 1, 0, 0, 0 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0074447926_discord.py_python.txt
Q: How to propagate SIGTERM to children created via subprocess Given the following Python scripts: a.py: #!/usr/bin/env python3 # a.py import signal import subprocess import os def main(): print('Starting process {}'.format(os.getpid())) subprocess.check_call('./b.py') if __name__ == '__main__': main() ...
How to propagate SIGTERM to children created via subprocess
Given the following Python scripts: a.py: #!/usr/bin/env python3 # a.py import signal import subprocess import os def main(): print('Starting process {}'.format(os.getpid())) subprocess.check_call('./b.py') if __name__ == '__main__': main() b.py: #!/usr/bin/env python3 # b.py import signal import time im...
[ "One solution is to explicitly throw SystemExit from a.py\n#!/usr/bin/env python3\n# a.py\nimport signal\nimport subprocess\nimport os\n\n\ndef cleanup(signum, frame):\n raise SystemExit(signum)\n\ndef main():\n signal.signal(signal.SIGINT, cleanup)\n signal.signal(signal.SIGTERM, cleanup)\n print('Star...
[ 0, 0 ]
[]
[]
[ "python", "sigterm", "subprocess" ]
stackoverflow_0067823770_python_sigterm_subprocess.txt
Q: Django password reset page loading issue I have implemented Forgot Password functionality in my web Blog. I have used Django and my gmail account as mailbox. I tried both the settings in my gmail account by enabling less secure apps/2 step authentications. Blog Flow: User Signup (by providing email id) Login (If ...
Django password reset page loading issue
I have implemented Forgot Password functionality in my web Blog. I have used Django and my gmail account as mailbox. I tried both the settings in my gmail account by enabling less secure apps/2 step authentications. Blog Flow: User Signup (by providing email id) Login (If Forgot Password get password reset link on ema...
[ "I had the same issue and solved it by changing the value of EMAIL_PORT in settings.py\n" ]
[ 0 ]
[]
[]
[ "django", "passwords", "python", "reset" ]
stackoverflow_0060097493_django_passwords_python_reset.txt
Q: Can not rename the table's column name using pandas dataframe I am new in jupyter notebook and python. Recently I'm working in this code but I can't find out the problem. I want to rename "Tesla Quarterly Revenue(Millions of US $)" and "Tesla Quarterly Revenue(Millions of US $).1" into "Data" and "Revenue" but it...
Can not rename the table's column name using pandas dataframe
I am new in jupyter notebook and python. Recently I'm working in this code but I can't find out the problem. I want to rename "Tesla Quarterly Revenue(Millions of US $)" and "Tesla Quarterly Revenue(Millions of US $).1" into "Data" and "Revenue" but it not changed. Here is my code: !pip install pandas !pip install req...
[ "Could not reproduce the issue, it works as expected. May print your originally .columns and compare the values to your dict - Not sure if the source is interpreted differnt by module versions:\nprint(tesla_revenue.columns)\n\nJust in case an alternative:\ntesla_revenue.columns = ['Date','Revenue']\n\nExample\nimpo...
[ 0, 0 ]
[]
[]
[ "data_science", "jupyter", "jupyter_notebook", "python" ]
stackoverflow_0074462791_data_science_jupyter_jupyter_notebook_python.txt
Q: Python Fizzbuzz problems with loop I've searched for the answer for about an hour, and it seems most people have coded fizzbuzz a different way than myself. However, having tried everything to figure out why this simple code will not work I'm getting extremely frustrated. Can anyone point out the simple proble...
Python Fizzbuzz problems with loop
I've searched for the answer for about an hour, and it seems most people have coded fizzbuzz a different way than myself. However, having tried everything to figure out why this simple code will not work I'm getting extremely frustrated. Can anyone point out the simple problem I'm sure I'm having? The code runs but...
[ "The first value it looks at is 1. Since 1%x is only 0 for an x of 1, it goes to the else and returns 1. And then it's done, because that's what return does.\nThat leads to the bigger problem, which is that you are starting a loop and then guaranteeing that you will leave that loop after only one iteration, because...
[ 1, 1, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "fizzbuzz", "loops", "python" ]
stackoverflow_0034101222_fizzbuzz_loops_python.txt
Q: Ordering matrices by column I Have this matrix: matrix: [['I' 'N' 'T' 'E' 'R' 'E' 'S' 'T' 'I' 'N' 'G'] ['D' 'G' 'F' 'F' 'G' 'D' 'A' 'A' 'D' 'V' 'A'] ['A' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ']] Want to order like this, without changing the position of the following rows in alphabethic order, only the first r...
Ordering matrices by column
I Have this matrix: matrix: [['I' 'N' 'T' 'E' 'R' 'E' 'S' 'T' 'I' 'N' 'G'] ['D' 'G' 'F' 'F' 'G' 'D' 'A' 'A' 'D' 'V' 'A'] ['A' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ']] Want to order like this, without changing the position of the following rows in alphabethic order, only the first row: matrix [['E' 'E' 'G' 'I' 'I'...
[ "Assuming this input:\narray([['I', 'N', 'T', 'E', 'R', 'E', 'S', 'T', 'I', 'N', 'G'],\n ['D', 'G', 'F', 'F', 'G', 'D', 'A', 'A', 'D', 'V', 'A'],\n ['A', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']],\n dtype='<U1')\n\nUse indexing and np.argsort:\nout = matriz_senha[:, np.argsort(matriz_senha...
[ 1 ]
[]
[]
[ "arrays", "matrix", "numpy", "python", "slice" ]
stackoverflow_0074462758_arrays_matrix_numpy_python_slice.txt
Q: Discord bot doesn't respond to interaction When I try kicking someone from an account that has no kick permissions, the bot says "the application did not respond". The code I'm using: @bot.slash_command(description = "Kickar alguém", guild_ids=[1041057700823449682]) @has_permissions(kick_members=True) @option("mem...
Discord bot doesn't respond to interaction
When I try kicking someone from an account that has no kick permissions, the bot says "the application did not respond". The code I'm using: @bot.slash_command(description = "Kickar alguém", guild_ids=[1041057700823449682]) @has_permissions(kick_members=True) @option("member",description = "Seleciona o membro") @option...
[ "This is due to the fact that the ctx.respond method actually takes an argument if it's a slash command. What you have is very close, but the correct code would be as follows\nawait ctx.respond(content=\"Hello world!\")\n\nYou simply need to specify the content (does not apply if it's an embed)\n", "I've fixed th...
[ 0, 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074451820_discord_discord.py_python.txt
Q: Why does PyMupdf Document show the error, no attribute 'new_page', when it is a PDF? I'm working on annotating a PDF and I want to change its color. I was guided to this helpful link: https://pymupdf.readthedocs.io/en/latest/faq.html#how-to-add-and-modify-annotations I used the code in the link: # -*- coding: utf-...
Why does PyMupdf Document show the error, no attribute 'new_page', when it is a PDF?
I'm working on annotating a PDF and I want to change its color. I was guided to this helpful link: https://pymupdf.readthedocs.io/en/latest/faq.html#how-to-add-and-modify-annotations I used the code in the link: # -*- coding: utf-8 -*- """ ------------------------------------------------------------------------------- ...
[ "I had some issues with similar attributes and updated the latest version of the pymupdf library using: python -m pip install --upgrade pymupdf\n", "They seem to have named this as _newPage(). The documentation also notes a method called insert_page() which is also not present. Seems like the documentation is o...
[ 1, 0 ]
[]
[]
[ "annotations", "pymupdf", "python" ]
stackoverflow_0068197427_annotations_pymupdf_python.txt
Q: Explain __dict__ attribute I am really confused about the __dict__ attribute. I have searched a lot but still I am not sure about the output. Could someone explain the use of this attribute from zero, in cases when it is used in a object, a class, or a function? A: Basically it contains all the attributes which ...
Explain __dict__ attribute
I am really confused about the __dict__ attribute. I have searched a lot but still I am not sure about the output. Could someone explain the use of this attribute from zero, in cases when it is used in a object, a class, or a function?
[ "Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes.\nQuoting from the documentation for __dict__\n\nA dictionary or other mapping object used to store an object's (writable) attributes.\n\nRemember, everything is an object in Python. When ...
[ 126, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0019907442_python.txt
Q: get files data of folder gdrive without api So I have a problem I just want to get files link from a drive folder but I find out that can only done by API of google drive but I don't want to use API for that. I was thinking I can do that with simple web scrapping but I found out it can not happen because drive use...
get files data of folder gdrive without api
So I have a problem I just want to get files link from a drive folder but I find out that can only done by API of google drive but I don't want to use API for that. I was thinking I can do that with simple web scrapping but I found out it can not happen because drive use server to get link. In simple words I want to kn...
[ "I think you should consult the Terms of service google does not allow web scraping.\nYou should use the Google drive api to do this. If you want to get file data then this is the best way forward.\nGoogle even has serval samples to help you get started manage-downloads\n" ]
[ 0 ]
[]
[]
[ "api", "google_drive_api", "python" ]
stackoverflow_0074463266_api_google_drive_api_python.txt
Q: How to change attribute based on boolean condition I am trying to alter point size based on whether its name exists in a list or not, I've tried many different ways but I keep generating this error. Code: graph = alt.Chart(df).mark_point( filled = False).encode( x=alt.X(axe_x), y=alt.Y(axe_y),...
How to change attribute based on boolean condition
I am trying to alter point size based on whether its name exists in a list or not, I've tried many different ways but I keep generating this error. Code: graph = alt.Chart(df).mark_point( filled = False).encode( x=alt.X(axe_x), y=alt.Y(axe_y), size=alt.condition( (alt.datum.name...
[ "You can use a transform_lookup for this\nimport altair as alt\nimport pandas as pd\nfrom vega_datasets import data\nsource = data.cars()\n# lookup table matching the string to corresonding size\ndf2 = pd.DataFrame({\n 'key': ['Europe', 'Japan', 'USA'],\n 's': [50, 50, 200]\n})\n\nalt.Chart(source).mark_circl...
[ 1 ]
[]
[]
[ "altair", "python" ]
stackoverflow_0074456892_altair_python.txt
Q: How could I compare the results of two csv files that only contains numbers? I have two csv files with 200 columns each. The two files have the exact same numbers in rows and columns. I want to compare each columns separately. The idea would be to compare column 1 value of file "a" to column 1 value of file "b" an...
How could I compare the results of two csv files that only contains numbers?
I have two csv files with 200 columns each. The two files have the exact same numbers in rows and columns. I want to compare each columns separately. The idea would be to compare column 1 value of file "a" to column 1 value of file "b" and check the difference and so on for all the numbers in the column (there are 100 ...
[ "I came up with something and I hope it helps you:\n# file1.csv:\n#\n# 1;1;1\n# 3;3;3\n# 5;5;5\n# 7;7;7\n#\n# files2.csv:\n#\n# 2;2;2\n# 4;3;4\n# 6;5;6\n# 8;8;8\n\nimport csv\n\n# change this to 200 for your file\ncolumns_num = 3\n\n# a dictionary that will hold our columns and the number of differences\ndiff = {} ...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074459330_python.txt
Q: How does automatic differentiation with respect to the input work? I've been trying to understand how automatic differentiation (autodiff) works. There are several implementations of this that can be found in Tensorflow, PyTorch and other programs. There are three aspects of automatic differentiation that currentl...
How does automatic differentiation with respect to the input work?
I've been trying to understand how automatic differentiation (autodiff) works. There are several implementations of this that can be found in Tensorflow, PyTorch and other programs. There are three aspects of automatic differentiation that currently seem vague to me. The exact process used to calculate the gradients H...
[ "I think what you need to understand first is what is a derivative, many math textbooks could help you with that. The notation dx means an infinitesimal variation, so you not actually compute any difference, but do a symbolic operation on your function f that transforms it to a function f' also noted df/dx, which y...
[ 0 ]
[]
[]
[ "autograd", "automatic_differentiation", "differentiation", "math", "python" ]
stackoverflow_0074460500_autograd_automatic_differentiation_differentiation_math_python.txt
Q: pySpark Replacing Null Value on subsets of rows I have a pySpark dataframe, where I have null values that I want to replace - however the value to replace with is different for different groups. My data looks like this (appologies, I dont have a way to past it as text): For group A I want to replace the null valu...
pySpark Replacing Null Value on subsets of rows
I have a pySpark dataframe, where I have null values that I want to replace - however the value to replace with is different for different groups. My data looks like this (appologies, I dont have a way to past it as text): For group A I want to replace the null values with -999; while for group B, I want to replace th...
[ "You can use when:\nfrom pyspark.sql import functions as F\n\n# Loop over all the columns you want to fill\nfor col in ('Col1', 'Col2', 'Col3'):\n # compute here conditions to fill using a value or another\n fill_a = F.col(col).isNull() & (F.col('Group') == 'A')\n fill_b = F.col(col).isNull() & (F.col('Gro...
[ 1, 0 ]
[]
[]
[ "null", "pyspark", "python" ]
stackoverflow_0074456021_null_pyspark_python.txt
Q: How to split multi-dimensional arrays based on the unique indices of another array? I have two torch tensors a and b: import torch torch.manual_seed(0) # for reproducibility a = torch.rand(size = (5, 10, 1)) b = torch.tensor([3, 3, 1, 5, 3, 1, 0, 2, 1, 2]) I want to split the 2nd dimension of a (which is dim = 1...
How to split multi-dimensional arrays based on the unique indices of another array?
I have two torch tensors a and b: import torch torch.manual_seed(0) # for reproducibility a = torch.rand(size = (5, 10, 1)) b = torch.tensor([3, 3, 1, 5, 3, 1, 0, 2, 1, 2]) I want to split the 2nd dimension of a (which is dim = 1 in the Python language) based on the unique values in b. What I have tried so far: # fin...
[ "From your description of the desired result:\n\nI was also expecting the tensors to have the shape (5, number of elements corresponding to unique_values, 1).\n\nI believe you are looking for the count (or frequency) of unique values. If you want to keep using torch.unique, then you can provide the return_counts ar...
[ 2, 1 ]
[]
[]
[ "python", "pytorch", "tensor" ]
stackoverflow_0074462683_python_pytorch_tensor.txt
Q: Numpy SVD gives infinite singular values for array with finite elements I've run into this problem (infinite singular values despite finite entries in an array) several times for relatively small arrays with dimensions around 100 by 100. The arrays are large enough that I've struggled to see a pattern. I give a wo...
Numpy SVD gives infinite singular values for array with finite elements
I've run into this problem (infinite singular values despite finite entries in an array) several times for relatively small arrays with dimensions around 100 by 100. The arrays are large enough that I've struggled to see a pattern. I give a working example below that I found by rounding the values in one of my matrices...
[ "I had the same error on Intel processors. You can fix this by installing the intel-numpy package.\npip install intel-numpy\n\nMore information: https://anaconda.org/intel/numpy\n" ]
[ 1 ]
[]
[]
[ "infinity", "numpy", "python", "svd" ]
stackoverflow_0073243207_infinity_numpy_python_svd.txt
Q: gspread requires an older google-auth Today pip -install --user --upgrade told me gspread 5.7.0 requires google-auth==1.12.0, but you have google-auth 2.14.1 which is incompatible. Please note the huge discrepancy in google-auth version numbers: 1.12 vs 2.14. I think I update my packages often enough, so this hug...
gspread requires an older google-auth
Today pip -install --user --upgrade told me gspread 5.7.0 requires google-auth==1.12.0, but you have google-auth 2.14.1 which is incompatible. Please note the huge discrepancy in google-auth version numbers: 1.12 vs 2.14. I think I update my packages often enough, so this huge jump in google-auth version numbers is a ...
[ "This has been reported and was claimed to be fixed by adding dependabot to maintain dependencies.\nIt was actually fixed in v5.7.1. See Remove fixed version for google dependency system.\n" ]
[ 0 ]
[]
[]
[ "google_auth_library", "gspread", "pip", "python" ]
stackoverflow_0074434493_google_auth_library_gspread_pip_python.txt
Q: How to cast columns in psycopg2's excluded values insert I want to update a table using 2 columns of a pandas dataframe. Here is my code: query = """ update table_1 m set column_1 = e.column_1 from (VALUES %s) AS e (column_2, column_1) where m.column_2= e.column_2::text""" args = (('random_value_...
How to cast columns in psycopg2's excluded values insert
I want to update a table using 2 columns of a pandas dataframe. Here is my code: query = """ update table_1 m set column_1 = e.column_1 from (VALUES %s) AS e (column_2, column_1) where m.column_2= e.column_2::text""" args = (('random_value_2','2022-11-15T13:04:18.844Z'), ('random_value_1','2022-11-15...
[ "Table creation and initial data entry.\ncreate table table_1 (column_1 timestamp, column_2 varchar);\n\ninsert into table_1 values (current_timestamp,'random_value_2'), (current_timestamp, 'random_value_1');\n\nselect * from table_1;\n column_1 | column_2 \n----------------------------+----...
[ 0 ]
[]
[]
[ "postgresql", "psycopg2", "python" ]
stackoverflow_0074458844_postgresql_psycopg2_python.txt
Q: merging a list in a list in Python? I have a list that looks similar to: list = [[[a,b,c], e, f, g], h, i, j] and my desired output is: merged_list = [a,b,c,e,f,g,h,i,j] does anyone know an efficient way to do this? i tried to do some sort of merging lists with the sum function but it didn't work A: first i ma...
merging a list in a list in Python?
I have a list that looks similar to: list = [[[a,b,c], e, f, g], h, i, j] and my desired output is: merged_list = [a,b,c,e,f,g,h,i,j] does anyone know an efficient way to do this? i tried to do some sort of merging lists with the sum function but it didn't work
[ "first i make all your variable into string because it was giving me error of not defined\nso here is the code\n#you have 3 list in total\nlist = [[['a','b','c'], 'e', 'f', 'g'], 'h', 'i', 'j']\n\noutput_list = [] # created a empty list for storing the all data in list\n\nfor list2 in list: # you will get 2 list no...
[ 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074463513_list_python.txt
Q: Pandas updating certain values in large database but not matching dataframe size I have a large database that is containing a certain number per customer per type of item. Each day there will be a lot of updates to a certain type of item of a certain customer. The database will look as following: import pandas as ...
Pandas updating certain values in large database but not matching dataframe size
I have a large database that is containing a certain number per customer per type of item. Each day there will be a lot of updates to a certain type of item of a certain customer. The database will look as following: import pandas as pd df = pd.DataFrame({'customer' : ['customer1', 'customer2'], 'item1': [12, 13], 'i...
[ "We can use 'customer' as the index in both dataframes to make sure we align them correctly. Then all we do is add a reshaped version of df2 onto df based on alignment on index (both rows and columns), and when the item or the customer is a mismatch we use the values from df:\ndf.set_index('customer').add(\n pd....
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074463558_pandas_python.txt
Q: How to use LibTorrent for python to get information about the distribution? I would like to get the distribution data BEFORE uploading. All there is is a magnet link or .torrent file. What do I need to do? A: The question was incorrectly asked by me. I needed to find the size of all the files in the torrent. Thi...
How to use LibTorrent for python to get information about the distribution?
I would like to get the distribution data BEFORE uploading. All there is is a magnet link or .torrent file. What do I need to do?
[ "The question was incorrectly asked by me. I needed to find the size of all the files in the torrent. This is done using:\nhandle = lt.add_magnet_uri(ses, url, params)\nhandle.status().total_wanted\n" ]
[ 1 ]
[]
[]
[ "libtorrent", "python" ]
stackoverflow_0074448565_libtorrent_python.txt
Q: How to change the entry of a MultiIndex columns pandas DataFrame? I have a dataframe df such that df.columns returns MultiIndex([( 'a', 's1', 'm/s'), ( 'a', 's2', '%'), ( 'a', 's3', '°C'), ('b', 'z3', '°C'), ('b', 'z4', 'kPa')], names=['kind', 'name...
How to change the entry of a MultiIndex columns pandas DataFrame?
I have a dataframe df such that df.columns returns MultiIndex([( 'a', 's1', 'm/s'), ( 'a', 's2', '%'), ( 'a', 's3', '°C'), ('b', 'z3', '°C'), ('b', 'z4', 'kPa')], names=['kind', 'names', 'units']) How to change ONLY the column name ('b', 'z3', '°C') in...
[ "You can't modify a MultiIndex, so you will have to recreate it.\nAn handy way might be to transform back and forth to DataFrame.\nAssuming idx the MultiIndex:\nnew_idx = pd.MultiIndex.from_frame(idx.to_frame().replace('°C', 'degC'))\n\nOr use the DataFrame constructor:\nnew_idx = pd.DataFrame(index=idx).rename({'°...
[ 1, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074463487_pandas_python.txt
Q: What is the difference between the Matlab "smooth" function, and the Python "scipy.signal.savgol_filter"? I am currently translating some code written in Matlab, and re-writing it in Python. I have a function below in Matlab: yy = smooth(y, span, 'sgolay', degree) This function is meant to smooth the signal y, us...
What is the difference between the Matlab "smooth" function, and the Python "scipy.signal.savgol_filter"?
I am currently translating some code written in Matlab, and re-writing it in Python. I have a function below in Matlab: yy = smooth(y, span, 'sgolay', degree) This function is meant to smooth the signal y, using the Savitzky-Golay calculation. I found a Python function that applies this calculation to an input signal....
[ "I would compare the impulse response function of both to answer your question. From the below test, I would say it is not a bad idea to think they does the same thing. As mentioned in the comments, boundary cases like samples without neighbors, odd/even samples, etc could be implemented differently.\nspan=5;\ndegr...
[ 1 ]
[]
[]
[ "matlab", "python", "scipy", "signals" ]
stackoverflow_0074435553_matlab_python_scipy_signals.txt
Q: openpyxl - TypeError: __init__() got an unexpected keyword argument 'synchVertical' while using read_excel, python I get this error every time im trying to read my excel file. The strange thing is, its working on the windows pc from my cousin, but on my Macbook. Can anyone help me? Thanks in advance! emp = pd.read...
openpyxl - TypeError: __init__() got an unexpected keyword argument 'synchVertical' while using read_excel, python
I get this error every time im trying to read my excel file. The strange thing is, its working on the windows pc from my cousin, but on my Macbook. Can anyone help me? Thanks in advance! emp = pd.read_excel('./employment_08_09.xlsx') Traceback (most recent call last): File "/opt/anaconda3/lib/python3.9/site-packages...
[]
[]
[ "You are getting this error because Python cannot find the path and therefore you need to change your working directory. You can do this with the Operating system interface in Python.\nChange your working directory using os.chdir(path)\nimport os\nimport pandas as pd\n\nos.chdir(\"/Users/Documents\")\n\n#confirm th...
[ -1 ]
[ "openpyxl", "pandas", "python" ]
stackoverflow_0074463670_openpyxl_pandas_python.txt
Q: How to containerize a python script from a pulled image from docker hub First I am very new to docker, so apologies if this doesn't make sense. This is my situation: I have a data science/machine learning project in a python script (written in a single .py file). I want to containerize this application. I would ne...
How to containerize a python script from a pulled image from docker hub
First I am very new to docker, so apologies if this doesn't make sense. This is my situation: I have a data science/machine learning project in a python script (written in a single .py file). I want to containerize this application. I would need to create a Dockerfile to do that. But since this is a machine learning pr...
[ "You can specify a base image using the FROM command.\nExample:\nFROM continuumio/miniconda3:latest\n\nYou'll want to use the RUN command to install dependencies (assuming you need any more,) the COPY command to get your main.py file into the container, and CMD can be used to set a default command to run when the c...
[ 0 ]
[]
[]
[ "docker", "python" ]
stackoverflow_0074463767_docker_python.txt
Q: How to manually shutdown a socket server? I have a simple socket server, how do I shut it down when I enter "shutdown" in the terminal on the server side? import socket SERVER = "xxxx" PORT = 1234 ADDR = (SERVER, PORT) FORMAT = "utf-8" server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(ADDR)...
How to manually shutdown a socket server?
I have a simple socket server, how do I shut it down when I enter "shutdown" in the terminal on the server side? import socket SERVER = "xxxx" PORT = 1234 ADDR = (SERVER, PORT) FORMAT = "utf-8" server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(ADDR) def handle_connection(conn, addr): ... ...
[ "Close active connections and exit. It can be done with:\nserver.close()\nexit(0)\n\n", "To shutdown you socket server manually by calling server.close(), you whole code should be:\nimport socket \n\nSERVER = \"xxxx\"\nPORT = 1234\nADDR = (SERVER, PORT)\nFORMAT = \"utf-8\"\n\nserver = socket.socket(socket.AF_INET...
[ 0, 0 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0074463032_python_sockets.txt
Q: Sort boxplot and colour by pairs I have some data for conditions that go together by pairs, structured like this: mydata = { "WT_before": [11,12,13], "WT_after": [16,17,18], "MRE11_before": [21,22,23,24,25], "MRE11_after": [26,27,28,29,30], "NBS1_before": [31,32,33,34], "NBS1_after": [36,37...
Sort boxplot and colour by pairs
I have some data for conditions that go together by pairs, structured like this: mydata = { "WT_before": [11,12,13], "WT_after": [16,17,18], "MRE11_before": [21,22,23,24,25], "MRE11_after": [26,27,28,29,30], "NBS1_before": [31,32,33,34], "NBS1_after": [36,37,38,39] } (my real data has more cond...
[ "Seaborn works easiest with a dataframe in \"long form\". In this case, there would be rows with the condition repeated for every value with that condition.\nSeaborn's boxplot accepts an order= keyword, where you can change the order of the x-values. E.g. order=sorted(mydata.keys()) to sort the values alphabetical...
[ 2 ]
[]
[]
[ "matplotlib", "plot", "python", "seaborn" ]
stackoverflow_0074462307_matplotlib_plot_python_seaborn.txt
Q: Remove the missing values from the rows having greater than 5 missing values and then print the percentage of missing values in each column import pandas as pd df = pd.read_csv('https://query.data.world/s/Hfu_PsEuD1Z_yJHmGaxWTxvkz7W_b0') d= df.loc[df.isnull().sum(axis=1)>5] d.dropna(axis=0,inplace=True) print(roun...
Remove the missing values from the rows having greater than 5 missing values and then print the percentage of missing values in each column
import pandas as pd df = pd.read_csv('https://query.data.world/s/Hfu_PsEuD1Z_yJHmGaxWTxvkz7W_b0') d= df.loc[df.isnull().sum(axis=1)>5] d.dropna(axis=0,inplace=True) print(round(100*(1-df.count()/len(df)),2)) i m getting output as Ord_id 0.00 Prod_id 0.00 Ship_id 0.00 Cust_...
[ "Try this way:\ndf.drop(df[df.isnull().sum(axis=1)>5].index,axis=0,inplace=True)\n\nprint(round(100*(1-df.count()/len(df)),2))\n\n", "I think you are trying to find the index of rows with null values sum greater 5. Use np.where instead of df.loc to find the index and then drop them.\nTry:\nimport pandas as pd\nim...
[ 3, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0055207940_pandas_python.txt
Q: My mysqlx python query is inserting a "AS" statement instead of a "SELECT" statement. Why? Here is the python code I am running. def queryOrg(self, OrgID): session = mysqlx.get_session( {'host': db.HOST, 'port': db.PORT, 'user': db.USER, 'password': db.PASSWORD}) org_schema = session.ge...
My mysqlx python query is inserting a "AS" statement instead of a "SELECT" statement. Why?
Here is the python code I am running. def queryOrg(self, OrgID): session = mysqlx.get_session( {'host': db.HOST, 'port': db.PORT, 'user': db.USER, 'password': db.PASSWORD}) org_schema = session.get_schema('Organizations') org_table = org_schema.get_table('Organizations') resu...
[ "Oh! I think I found a solution. the .select() method sets the '*' as a default when nothing is passed into it. Trying to pass [\"*\"] into .select() caused the mysqlx to generate something like 'SELECT * AS * ...' which was causing the problem. This new code works perfectly.\ndef queryOrg(self, OrgID):\n ...
[ 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0074453457_mysql_python.txt
Q: Django CSRF Protection GraphQL API I do have a graphqlAPI which I use for CRUD Operations to my database. The authentication is tokenbased. So if an user wants to make cruds (mutations) to my database, it needs a valid token in order to do that. What I dont know is if my graphql API is also protected against CSRF ...
Django CSRF Protection GraphQL API
I do have a graphqlAPI which I use for CRUD Operations to my database. The authentication is tokenbased. So if an user wants to make cruds (mutations) to my database, it needs a valid token in order to do that. What I dont know is if my graphql API is also protected against CSRF attacks as I exempt this protection with...
[ "If the authentication token is transported in a header field (rather than in a cookie), there is no need for CSRF protection. This is because if a user is tricked into making an unwanted request to the endpoint, the browser will not automatically insert the token into the request, so it will be unauthenticated. Yo...
[ 1 ]
[]
[]
[ "csrf", "django", "graphql", "python" ]
stackoverflow_0074457185_csrf_django_graphql_python.txt
Q: "AttributeError: 'NoneType' object has no attribute 'get_text'" Whenever I tried to run this code: page = requests.get(URL, headers = headers) soup = BeautifulSoup(page.content, 'html.parser') title = soup.find(id="productTitle").get_text() price = soup.find(id="priceblock_ourprice").get_text() converted_price = ...
"AttributeError: 'NoneType' object has no attribute 'get_text'"
Whenever I tried to run this code: page = requests.get(URL, headers = headers) soup = BeautifulSoup(page.content, 'html.parser') title = soup.find(id="productTitle").get_text() price = soup.find(id="priceblock_ourprice").get_text() converted_price = price[0:7] if (converted_price < '₹ 1,200'): send_mail() print(...
[ "import requests\n\n\n\nfrom bs4 import BeautifulSoup \n\nurl = 'https://www.amazon.com/Camera-24-2MP-18-135mm-Essential-Including/dp/B081PMPPM1/ref=sr_1_1_sspa?dchild=1&keywords=Canon+EOS+80D&qid=1593325243&sr=8-1-spons&psc=1&spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUEyU1M0M1JVTkY3WTBVJmVuY3J5cHRlZElkPUEwNDQzMjI5Uk9DM08zQkM1...
[ 3, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0057462202_python.txt
Q: Unwanted characters in the HTML beautified text I have my original web scraped HTML text as this > {"overview":"\\u003cp\\u003e\\u003cspan style=\\"font-size: > 10.5pt;\\"\\u003e\\u003cspan class=\\"TextRun SCXW87260372 BCX0\\" style=\\"margin: 0px; padding: 0px; -webkit-user-drag: none; > -webkit-tap-highlight-co...
Unwanted characters in the HTML beautified text
I have my original web scraped HTML text as this > {"overview":"\\u003cp\\u003e\\u003cspan style=\\"font-size: > 10.5pt;\\"\\u003e\\u003cspan class=\\"TextRun SCXW87260372 BCX0\\" style=\\"margin: 0px; padding: 0px; -webkit-user-drag: none; > -webkit-tap-highlight-color: transparent; color: #000000; font-family: \'Meir...
[ "The problem with the unicode-escape codec is that it decodes the escape codes, but also decodes to latin1. Since you have non-latin1 characters in the stream, re-encode as latin1 to undo the incorrect decoding and decode as utf8 again:\ns='''\\\n{\"overview\":\"\\\\u003cp\\\\u003e\\\\u003cspan style=\\\\\"font-si...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "html", "python", "unicode", "web_scraping" ]
stackoverflow_0074443942_beautifulsoup_html_python_unicode_web_scraping.txt
Q: Why Binance klines last close value with interval is different from others? I am getting the candle stick values from binance api and print them like following. for i in range(0, 10): service = BinanceSpotService() klines = service.get_klines(symbol='BTCUSDT', interval=Client.KLINE_INTERVAL_15MINUTE) p...
Why Binance klines last close value with interval is different from others?
I am getting the candle stick values from binance api and print them like following. for i in range(0, 10): service = BinanceSpotService() klines = service.get_klines(symbol='BTCUSDT', interval=Client.KLINE_INTERVAL_15MINUTE) print(klines[["date", "close"]].tail(2)) each loop prints the last two datas like...
[ "Short Anwer: The most recent kline is still constantly changing.\nIn your example, you do not pass any endTime.\nThis gets then passed over to the Binance API. When there is no defined endTime, the API will return the most recent klines.\nIf startTime and endTime are not sent, the most recent klines are returned.\...
[ 0 ]
[]
[]
[ "binance", "python" ]
stackoverflow_0074419388_binance_python.txt
Q: How to normalize data which contain positive and negative numbers into 0 and 1? I have a dataset that contains negative and positive values. then here I use MinMaxScaler() to normalize the data to 0 and 1. but because the normalized data has negative and positive values in it, the normalization is not optimal, so ...
How to normalize data which contain positive and negative numbers into 0 and 1?
I have a dataset that contains negative and positive values. then here I use MinMaxScaler() to normalize the data to 0 and 1. but because the normalized data has negative and positive values in it, the normalization is not optimal, so the resulting prediction results are not optimal. then I try to change the negative d...
[ "You can change the range of MinMaxScaler to be between [-1,1], if you'd like to keep the smallest number (negative in your case) still negative, but the largest number still positive. Does this help?\n" ]
[ 1 ]
[]
[]
[ "data_analysis", "normalization", "python" ]
stackoverflow_0074463956_data_analysis_normalization_python.txt
Q: Changing the underlying variable's value in a dictionary of variables How can I change the value of a variable using dictionary? Right now I have to check every key of the dictionary and then change the corresponding variable's value. ` list1 = [1, 2, 3] list2 = [4, 5, 6] list3 = [7, 8, 9] dictionary = { "dog...
Changing the underlying variable's value in a dictionary of variables
How can I change the value of a variable using dictionary? Right now I have to check every key of the dictionary and then change the corresponding variable's value. ` list1 = [1, 2, 3] list2 = [4, 5, 6] list3 = [7, 8, 9] dictionary = { "dog": list1, "cat": list2, "mouse": list3 } animal = input("Type dog,...
[ "You can replace the dict value with a new list on the fly -\ndictionary[animal] = [i+1 for i in dictionary[animal]]\nI would suggest to stop using the listx variables and use dict itself to maintain those lists and mappings.\ndictionary = {\n \"dog\": [1, 2, 3],\n \"cat\": [4, 5, 6],\n \"mouse\": [7, 8, 9...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074463899_python_python_3.x.txt
Q: python colorama print all colors I am new to learning Python, and I came across colorama. As a test project, I wanted to print out all the available colors in colorama. from colorama import Fore from colorama import init as colorama_init colorama_init(autoreset=True) colors = [x for x in dir(Fore) if x[0] != "_"...
python colorama print all colors
I am new to learning Python, and I came across colorama. As a test project, I wanted to print out all the available colors in colorama. from colorama import Fore from colorama import init as colorama_init colorama_init(autoreset=True) colors = [x for x in dir(Fore) if x[0] != "_"] for color in colors: print(colo...
[ "The reason why it's printing the color name twice is well described in Patrick's comment on the question.\nIs their a way to access all the Fore Color property so they actualy work as in\nAccording to: https://pypi.org/project/colorama/\nYou can print a colored string using other ways than e.g.print(Fore.RED + 'so...
[ 7, 0 ]
[]
[]
[ "colorama", "properties", "python" ]
stackoverflow_0061686780_colorama_properties_python.txt
Q: Changing style of pandas.DataFrame: Permanently? When I change the style of a pandas.DataFrame, for instance like so # color these columns color_columns = ['roi', 'percent_of_ath'] (portfolio_df .style # color negative numbers red .apply(lambda v: 'color:...
Changing style of pandas.DataFrame: Permanently?
When I change the style of a pandas.DataFrame, for instance like so # color these columns color_columns = ['roi', 'percent_of_ath'] (portfolio_df .style # color negative numbers red .apply(lambda v: 'color: red' if v < 0 else 'color: black', ...
[ "I can give you two recommendations:\n1. Write a simple function to display your dataframes\nThis is by far the simplest and least hacky solution. You could write:\ndef my_style(df:pd.DataFrame, color_columns:list[str]=['roi', 'percent_of_ath']):\n return (df\n .style\n .applymap(lambda v: ...
[ 0 ]
[ "try using this function\ndf.style.applymap()\n\n" ]
[ -4 ]
[ "jupyter_notebook", "pandas", "pandas_styles", "python" ]
stackoverflow_0056176720_jupyter_notebook_pandas_pandas_styles_python.txt
Q: Django ManyToMany all values by default I have the following model: class Product(models.Model): provinces = models.ManyToManyField('Province', related_name='formats') By default, products can be sold in every province. How can I define the model "Product" so that every product created has all provinces by de...
Django ManyToMany all values by default
I have the following model: class Product(models.Model): provinces = models.ManyToManyField('Province', related_name='formats') By default, products can be sold in every province. How can I define the model "Product" so that every product created has all provinces by default? Thanks!
[ "Use the default key. You can't directly set default model values to an iterable like a list, so wrap them in a callable, as the Django documentation advises: https://docs.djangoproject.com/en/1.8/ref/models/fields/\ndef allProvinces():\n return provincesList\n\nprovinces = models.ManyToManyField('Province', rel...
[ 7, 4, 1, 0 ]
[]
[]
[ "django", "django_orm", "python" ]
stackoverflow_0031617838_django_django_orm_python.txt
Q: How to make one single connection to mongodb with multiple databases and collections in pypsark I've got a connectino to mongodb and several databses and collecions inside, I just wanna have one connection an make queries to several collections in pyspark. I think that one connection per query delays the performan...
How to make one single connection to mongodb with multiple databases and collections in pypsark
I've got a connectino to mongodb and several databses and collecions inside, I just wanna have one connection an make queries to several collections in pyspark. I think that one connection per query delays the performance. That's what I have: database_1 = "data_1" database_2 = "data_2" collection_1 = "client_1" collec...
[ "I don't think that's a problem.\nSpark using lazy evaluation which means RDD's are evaluated until at the very end that an action is needed to be done and spark optimization take care of queries and their connection.\nin other words when you do spark.read . that line is just defining the dataframe and spark doesn...
[ 0 ]
[]
[]
[ "pyspark", "python", "python_3.8" ]
stackoverflow_0074464028_pyspark_python_python_3.8.txt
Q: Is there a shorter way to create loops trough the rows when using append? I have a data frame with employees and all the roles that they are able to do. ` Employees ID Brand_Manager Payroll_Manager Accountant Auditor 0 Jessi 1A 1 0 1 0 1 Lara 1B ...
Is there a shorter way to create loops trough the rows when using append?
I have a data frame with employees and all the roles that they are able to do. ` Employees ID Brand_Manager Payroll_Manager Accountant Auditor 0 Jessi 1A 1 0 1 0 1 Lara 1B 1 0 0 1 2 Mike 1C 1 ...
[ "Here's one approach. pandas gives a \"SettingWithCopy\" warning, but I believe this script will always result in the expected behavior.\nimport numpy as np\nimport pandas as pd\n\n#input dataframe\ndf = pd.DataFrame({'Employees': {0: 'Jessi', 1: 'Lara', 2: 'Mike', 3: 'Artur', 4: 'James', 5: 'Claudia', 6: 'Zuzska',...
[ 0 ]
[]
[]
[ "append", "multiple_columns", "python" ]
stackoverflow_0074453795_append_multiple_columns_python.txt
Q: limit the number of colors of an image to a specified number based on prodominant colors in python I want to process images in a way to limit the number of colors to a predetermined and specific number I tried using this method from PIL import image image= Image.open("input.png") result = image.convert('P', palet...
limit the number of colors of an image to a specified number based on prodominant colors in python
I want to process images in a way to limit the number of colors to a predetermined and specific number I tried using this method from PIL import image image= Image.open("input.png") result = image.convert('P', palette=Image.ADAPTIVE, colors=2) result.save("saved.png") for some reason it used to work but now doesn't w...
[ "FIXED :\nthe problem is the color mode\nto be able to use this function you need first to convert the color mode of the image to RGB like this :\nimage = image.convert('RGB')\n\n" ]
[ 1 ]
[]
[]
[ "image_processing", "python", "python_imaging_library" ]
stackoverflow_0074464095_image_processing_python_python_imaging_library.txt
Q: OpenCV cv2 image to PyGame image? def cvimage_to_pygame(image): """Convert cvimage into a pygame image""" return pygame.image.frombuffer(image.tostring(), image.shape[:2], "RGB") The function takes a numpy array taken from the cv2 camera. When I display the returned pyGa...
OpenCV cv2 image to PyGame image?
def cvimage_to_pygame(image): """Convert cvimage into a pygame image""" return pygame.image.frombuffer(image.tostring(), image.shape[:2], "RGB") The function takes a numpy array taken from the cv2 camera. When I display the returned pyGame image on a pyGame window, it appears...
[ "In the shape field width and height parameters are swapped. Replace argument:\nimage.shape[:2] # gives you (height, width) tuple\n\nWith \nimage.shape[1::-1] # gives you (width, height) tuple\n\n", "An other issue that i found : Colors are not right... This is because open cv images are in BGR (Blue Green Red) n...
[ 8, 0 ]
[]
[]
[ "numpy", "opencv", "pygame", "python" ]
stackoverflow_0019306211_numpy_opencv_pygame_python.txt
Q: Numpy - How to get an array of the pattern gamma^t for some 0-t? I am creating a basic gridworld RL problem and I need to calculate the return for some given episode. I currently have the array of rewards, and I would like to element-wise multiply this with a list of the form: [gamma**0, gamma**1, gamma**2, ....] ...
Numpy - How to get an array of the pattern gamma^t for some 0-t?
I am creating a basic gridworld RL problem and I need to calculate the return for some given episode. I currently have the array of rewards, and I would like to element-wise multiply this with a list of the form: [gamma**0, gamma**1, gamma**2, ....] In order to get: [r_0*gamma**0, r_1*gamma**1, r_2*gamma**2, ....] an...
[ "if the example if like this for reward array and gamma is some value:\nn = 20 \nreward = np.random.randint(0, 10, n)\ngamma = 2\n\nnp.sum(reward * (gamma ** np.arange(n)))\n\n" ]
[ 1 ]
[]
[]
[ "arrays", "numpy", "python", "reinforcement_learning" ]
stackoverflow_0074464029_arrays_numpy_python_reinforcement_learning.txt
Q: Django 3.1 - async views - working with querysets Since 3.1 (currently beta) Django have support for async views async def myview(request): users = User.objects.all() This example will not work - since ORM is not yet async ready so what's the current workaround ? you cannot just use sync_to_async with queryse...
Django 3.1 - async views - working with querysets
Since 3.1 (currently beta) Django have support for async views async def myview(request): users = User.objects.all() This example will not work - since ORM is not yet async ready so what's the current workaround ? you cannot just use sync_to_async with queryset - as they it is not evaluated: from asgiref.sync impo...
[ "There is a common GOTCHA: Django querysets are lazy evaluated (database query happens only when you start iterating):\nso instead - use evaluation (with list):\nfrom asgiref.sync import sync_to_async\n\nasync def myview(request):\n users = await sync_to_async(list)(User.objects.all())\n\n", "From Django 4.1 a...
[ 14, 1 ]
[]
[]
[ "asynchronous", "django", "django_3.1", "python" ]
stackoverflow_0062530017_asynchronous_django_django_3.1_python.txt
Q: Reportlab - How to add margin between Tables? So i am trying to create three tables per page, the following code will collide all three tables together with 0 margin between them. I would like some white space between two tables. Is there a configuration for that? doc = SimpleDocTemplate("my.pdf", pagesize=A4) ele...
Reportlab - How to add margin between Tables?
So i am trying to create three tables per page, the following code will collide all three tables together with 0 margin between them. I would like some white space between two tables. Is there a configuration for that? doc = SimpleDocTemplate("my.pdf", pagesize=A4) elements = [] i = 0 for person in persons: data = ...
[ "You could try using the Spacer function to add space between the tables. An example of its use from the documentation is:\nfrom reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer\n\ndef go():\n doc = SimpleDocTemplate(\"hello.pdf\")\n Story = [Spacer(1,2*inch)]\n\n for i in range(100):\n bogustext ...
[ 1 ]
[]
[]
[ "python", "reportlab" ]
stackoverflow_0074463969_python_reportlab.txt
Q: How to create an application which embeds and runs Python code without local Python installation? Hello fellow software developers. I want to distribute a C program which is scriptable by embedding the Python interpreter. The C program uses Py_Initialize, PyImport_Import and so on to accomplish Python embedding. I...
How to create an application which embeds and runs Python code without local Python installation?
Hello fellow software developers. I want to distribute a C program which is scriptable by embedding the Python interpreter. The C program uses Py_Initialize, PyImport_Import and so on to accomplish Python embedding. I'm looking for a solution where I distribute only the following components: my program executable an...
[ "Have you looked at Python's official documentation : Embedding Python into another application?\nThere's also this really nice PDF by IBM : Embed Python scripting in C application.\nYou should be able to do what you want using those two resources.\n", "I simply tested my executable on a computer which hasn't Pyt...
[ 6, 6, 1, 1, 1, 0, 0 ]
[]
[]
[ "c", "distribution", "dll", "python" ]
stackoverflow_0002494468_c_distribution_dll_python.txt
Q: Why is Apache Beam `DoFn.setup()` called more then once after worker startup? I am currently experimenting with a streaming Dataflow pipeline (in Python). I read a stream of data which I like to write into a PG CloudSQL instance. To do so, I am looking for a proper place to create the database connection. As I am ...
Why is Apache Beam `DoFn.setup()` called more then once after worker startup?
I am currently experimenting with a streaming Dataflow pipeline (in Python). I read a stream of data which I like to write into a PG CloudSQL instance. To do so, I am looking for a proper place to create the database connection. As I am writing the data using a ParDo function, I'd thought the DoFn.setup() would be a g...
[ "According to the Beam documentation, the setup method can be invoked more that once :\nDoFn.setup(): Called whenever the DoFn instance is deserialized on the worker. \nThis means it can be called more than once per worker because multiple instances of a given DoFn subclass may be created \n(e.g., due to paralleliz...
[ 2 ]
[]
[]
[ "apache_beam", "google_cloud_dataflow", "python" ]
stackoverflow_0074462039_apache_beam_google_cloud_dataflow_python.txt
Q: Upload file to Google bucket directly from SFTP server using Python I am trying to upload file from SFTP server to GCS bucket using cloud function. But this code not working. I am able to sftp. But when I try to upload file in GCS bucket, it doesn't work, and the requirement is to use cloud function with Python. A...
Upload file to Google bucket directly from SFTP server using Python
I am trying to upload file from SFTP server to GCS bucket using cloud function. But this code not working. I am able to sftp. But when I try to upload file in GCS bucket, it doesn't work, and the requirement is to use cloud function with Python. Any help will be appreciated. Here is the sample code I am trying. This co...
[ "The pysftp cannot work with GCP directly.\nImo, you cannot actually upload a file directly from SFTP to GCP anyhow, at least not from a code running on yet another machine. But you can transfer the file without storing it on the intermediate machine, using pysftp Connection.open (or better using Paramiko SFTPClien...
[ 2, 0, 0 ]
[]
[]
[ "gcs", "pysftp", "python", "sftp" ]
stackoverflow_0070911611_gcs_pysftp_python_sftp.txt
Q: Send image from Flask to React I'm trying to send a randomly generated image from a flask API to my React frontend. I started by just saving the image every time I generate it to the file system then trying to access it with react but this doesn't work with the production build. Now I'm using flask's send_file(), ...
Send image from Flask to React
I'm trying to send a randomly generated image from a flask API to my React frontend. I started by just saving the image every time I generate it to the file system then trying to access it with react but this doesn't work with the production build. Now I'm using flask's send_file(), but I'm not sure of what I'm doing w...
[ "If you want your Flask endpoint to return an image, you don't need to first save it to a file. You can return the image directly after setting appropriate header(s), most importantly content-type:\nfrom flask import request\n\n@app.route(\"/get-image\")\ndef image_endpoint():\n ...\n request.headers[\"conten...
[ 0 ]
[]
[]
[ "flask", "image", "python", "reactjs" ]
stackoverflow_0059084001_flask_image_python_reactjs.txt
Q: How to remove a certain string before printing? answer = input('Enter a number: ') x = 10**(len(answer) - 1) print(answer, end = ' = ') for i in answer: if '0' in i: x = x//10 continue else: print('(' + i + ' * ' + str(x) + ')' , end = '') x = x//10 print(' + ', end...
How to remove a certain string before printing?
answer = input('Enter a number: ') x = 10**(len(answer) - 1) print(answer, end = ' = ') for i in answer: if '0' in i: x = x//10 continue else: print('(' + i + ' * ' + str(x) + ')' , end = '') x = x//10 print(' + ', end = '') so i have this problem, when i enter any num...
[ "you can insert an extra condition in the else block:\nelse:\n print('(' + i + ' * ' + str(x) + ')' , end = '')\n x = x//10\n if x:\n print(' + ', end = '')\n\nthis will help not to insert the last plus when it is not needed\n", "The error is that there is an extra '+' at the end of the output. Th...
[ 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074450970_python.txt