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: Pandas : Add column to another column I'm confused on how do I add a column to another in pandas Here is what I'm trying to do : from pandas import DataFrame df1 = DataFrame({'a':[1,2], 'b':[3,4]}) concat((df1['a'], df1['b'].rename({'b':'a'}))).reset_index(drop=True) Which do return what I want : A serie with my ...
Pandas : Add column to another column
I'm confused on how do I add a column to another in pandas Here is what I'm trying to do : from pandas import DataFrame df1 = DataFrame({'a':[1,2], 'b':[3,4]}) concat((df1['a'], df1['b'].rename({'b':'a'}))).reset_index(drop=True) Which do return what I want : A serie with my 4 values. What I don't understand is : Why ...
[ "pandas series doesn't contain columns.\nIf you want to use column by Dataframe, use df[['a']] instead df['a']\n& you want change column's name need axis or columns\npd.concat([df1[['a']], df1[['b']].rename(columns={'b':'a'})]).reset_index(drop=True)\n\noutput:\n a\n0 1\n1 2\n2 3\n3 4\n\nIf I create your...
[ 2, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074429956_dataframe_pandas_python.txt
Q: Django: Send mail to admin on every error raised I have a project where we process data from various sources. My problem is I want a to send email every time there is an error or error raise my me. Currently I do something like this where on every raise I send a email. But I want a system where on every error ther...
Django: Send mail to admin on every error raised
I have a project where we process data from various sources. My problem is I want a to send email every time there is an error or error raise my me. Currently I do something like this where on every raise I send a email. But I want a system where on every error there would be a email sent. # send an email alert email_...
[ "You can use try: and except: like such:\n try:\n <do something>\n except Exception as e:\n email_content = email_content + e\n BaseScraper.email_alert_for_error(\n subject,\n email_content,\n [\"admin@mail.com\"],\n )\n\nHere a list of keyword for exception: https:/...
[ 3 ]
[]
[]
[ "django", "django_signals", "python" ]
stackoverflow_0074430006_django_django_signals_python.txt
Q: How to run together python3.10 and python3.7? I have a code which is written with python3.7 Because of python3.7 doesnt have switch-case I wrote another code script with python3.10 I need to run these two code snippets together. I dont know how to do it due to version difference. I cannot change the code with pyth...
How to run together python3.10 and python3.7?
I have a code which is written with python3.7 Because of python3.7 doesnt have switch-case I wrote another code script with python3.10 I need to run these two code snippets together. I dont know how to do it due to version difference. I cannot change the code with python3.7 because it has pysnmp and it runs only 3.7 ve...
[ "\nI cannot change the code with python3.7 because it has pysnmp and it runs only 3.7 version.\n\nThe original version of pysnmp is not supported anymore (due to unfortunate circumstances), and a maintained fork is now available as pysnmplib. This version supports Python >= 3.8. Using that instead will allow you to...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074429358_python_python_3.x.txt
Q: How can I define the buildozer.spec requirements when converting Python Kivy to APK? I would like to convert my python kivy project into an APK file through Google Colab. In this process I have to define the requirements in the buildozer.spec manually, namely I have to give the dependencies. Here is my imported mo...
How can I define the buildozer.spec requirements when converting Python Kivy to APK?
I would like to convert my python kivy project into an APK file through Google Colab. In this process I have to define the requirements in the buildozer.spec manually, namely I have to give the dependencies. Here is my imported modules in my main.py file: from kivymd.app import MDApp from kivy.uix.widget import Widget ...
[ "In your spec file, in the requirements you should have something like this:\nrequirements=kivy,kivymd,python,android\n\nNow kivy garden is installed as a normal package as stated here, so these should be all requirements that you need in your spec file. If your app crashes at startup there can be also other proble...
[ 0 ]
[]
[]
[ "android", "apk", "buildozer", "kivy", "python" ]
stackoverflow_0074428695_android_apk_buildozer_kivy_python.txt
Q: How do I use .apply(func) with a conditional function (pandas) I have the following Pd series count area volume formula quantity 0 1.0 22 NaN count 1.0 1 1.0 15 NaN count 1.0 2 1.0 1.4 NaN area 1.4 3 1.0 0.6 ...
How do I use .apply(func) with a conditional function (pandas)
I have the following Pd series count area volume formula quantity 0 1.0 22 NaN count 1.0 1 1.0 15 NaN count 1.0 2 1.0 1.4 NaN area 1.4 3 1.0 0.6 10 volume 100 The quantity column is based on the val...
[ "You can try something like this:\ndf.apply(lambda x: x['volume']*10 if x['formula'] == 'volume' else x['quantity'], axis=1)\n\nprint(df)\n\n count area volume formula quantity ans\n0 1.0 22.0 NaN count 1.0 1.0\n1 1.0 15.0 NaN count 1.0 1.0\n2 1.0 1.4 NaN ar...
[ 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074429952_pandas_python.txt
Q: How to print a star instead of a number? I need to write a function numbers_around(n, k) that prints the numbers smaller and larger than n in order. Instead of the number n, it should print an asterisk. What I've done: def numbers_around(n, k): for n in range((n-k),(n+k+1)): print(n, end=' ') print...
How to print a star instead of a number?
I need to write a function numbers_around(n, k) that prints the numbers smaller and larger than n in order. Instead of the number n, it should print an asterisk. What I've done: def numbers_around(n, k): for n in range((n-k),(n+k+1)): print(n, end=' ') print() numbers_around(15, 3) numbers_arou...
[ "You are using the same name for two variables, this is bad practice. If you change one of the variable in the for loop and check if it is equal to the original number you can print out a \"*\" when needed like so:\ndef numbers_around(n, k):\n for i in range((n-k),(n+k+1)):\n if i == n:\n print...
[ 5 ]
[]
[]
[ "function", "numbers", "python", "python_3.x", "stars" ]
stackoverflow_0074430144_function_numbers_python_python_3.x_stars.txt
Q: How to pass a python wordcloud element to svgwrite method to generate a svg of the wordcloud? I am trying to generate a svg of the word_cloud being formed out of some hardcoded strings(as of now, later these strings will be dynamically generated). Below is the Python code to generate word_cloud: from os import pa...
How to pass a python wordcloud element to svgwrite method to generate a svg of the wordcloud?
I am trying to generate a svg of the word_cloud being formed out of some hardcoded strings(as of now, later these strings will be dynamically generated). Below is the Python code to generate word_cloud: from os import path from wordcloud import WordCloud d = path.dirname(__file__) # Read the whole text. #text = open(p...
[ "Facing some issues using matplotlib (which will use raster graphics in combination with wordcloud although it will be saved as \".svg\"), i have figured out another way\nwordcloud = WordCloud()\nwordcloud.generate_from_frequencies(frequencies=features)\nwordcloud_svg = wordcloud.to_svg(embed_font=True)\nf = open(\...
[ 4, 2, 0 ]
[]
[]
[ "python", "python_2.7", "svg", "svgwrite" ]
stackoverflow_0044715044_python_python_2.7_svg_svgwrite.txt
Q: Gunicorn, Flask Server, Nginx: Timeout Error I'm currently trying to connect to a flask server running with gunicorn from outside the local network through a reverse proxy with nginx but I get Timeout errors every time I'm trying to connect. So here's my setup: Flask file: from flask import Flask app = Flask(__nam...
Gunicorn, Flask Server, Nginx: Timeout Error
I'm currently trying to connect to a flask server running with gunicorn from outside the local network through a reverse proxy with nginx but I get Timeout errors every time I'm trying to connect. So here's my setup: Flask file: from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "<h1...
[ "I think you run gunicorn at 127.0.0.1 that listen at local network. Try change to 0.0.0.0 listen on every available network interface and run again\n" ]
[ 0 ]
[]
[]
[ "flask", "gunicorn", "nginx", "python", "wsgi" ]
stackoverflow_0074425846_flask_gunicorn_nginx_python_wsgi.txt
Q: Python async MySQL lib for caching duplicate read queries in transaction Suppose I have web request handler in python which processes some complex logic using MySQL queries. I wrap request in some readable methods, for ex: START TRANSACTION get_some_users_in_range("select users where id>1 and id<24") get_user("se...
Python async MySQL lib for caching duplicate read queries in transaction
Suppose I have web request handler in python which processes some complex logic using MySQL queries. I wrap request in some readable methods, for ex: START TRANSACTION get_some_users_in_range("select users where id>1 and id<24") get_user("select users where id=10") get_user("select users where id=10") get_user("select...
[ "You can wrap your function with functools.lru_cache: https://docs.python.org/3/library/functools.html#functools.lru_cache\nHere is the async version of the same functionality: https://github.com/aio-libs/async-lru\nAn excellent library that has more caching strategies (check their readme, they also have async supp...
[ 0 ]
[]
[]
[ "mysql", "python", "python_3.x", "python_asyncio" ]
stackoverflow_0055355903_mysql_python_python_3.x_python_asyncio.txt
Q: Is there any Solution for this Login syntax>? Ive this Django Login and Registration form but the registration form is fetching in database auth_user but not in helloworld_register This is my Registration code def Register(request): if request.method =='POST': username=request.POST['username'] ...
Is there any Solution for this Login syntax>?
Ive this Django Login and Registration form but the registration form is fetching in database auth_user but not in helloworld_register This is my Registration code def Register(request): if request.method =='POST': username=request.POST['username'] email=request.POST['email'] first_nam...
[ "First of all, I would like to correct the terminology. Both snippets you provided are not Forms but Views. And 'auth_user' is not a database, its a table, as I will assume for 'helloworld_register'.\nRelated to your first problem, it seems that you are using Django's default User model. And by default this model u...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074428035_django_python.txt
Q: Python List with if Condition I have two lists and I want to use both in if condition together. In case only One list this can do easily like if list_name : # if list a : for more than 2 lists this method is not working. although we can use separately if or using len(a) like comparison. I am searching for sim...
Python List with if Condition
I have two lists and I want to use both in if condition together. In case only One list this can do easily like if list_name : # if list a : for more than 2 lists this method is not working. although we can use separately if or using len(a) like comparison. I am searching for simple & beautiful result. a = [1,2,34...
[ "In Python, instead of using & in if statements, we use and.\nThis is how you can check both lists in the same if:\na = [1, 2, 3, 4]\nb = [5, 6, 7, 8]\n\nif a and b:\n print(\"a and b are both valid!\")\n\nYou can read more about Python if statements here.\n", "Inside if-statements, lists are automatically eva...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074429639_python.txt
Q: frontfill or backfill of STRING column at resample() in pandas is there any methode while doing resampling() to ffill() or bfill() a object column? Suppose we have: Date Sort Value 2022-10-23 15:40:41 A 1 2022-10-23 18:43:13 B 2 2022-10-24 15:40:41 C 3 2022-10-24 18:43:13 D 4 i would like to have following r...
frontfill or backfill of STRING column at resample() in pandas
is there any methode while doing resampling() to ffill() or bfill() a object column? Suppose we have: Date Sort Value 2022-10-23 15:40:41 A 1 2022-10-23 18:43:13 B 2 2022-10-24 15:40:41 C 3 2022-10-24 18:43:13 D 4 i would like to have following results with: df.resample("15min").mean() Date Sort ...
[ "You can specify the aggregation functions for your columns separately, for example:\ndf = df.resample(\"15min\").agg({\"Sort\": min, \"Value\": np.mean}).ffill()\n\nOutput:\n Sort Value\nDate\n2022-10-23 15:30:00 A 1.0\n2022-10-23 15:45:00 A 1.0\n2022-10-23 16:00:00 A 1.0\n202...
[ 0, 0 ]
[]
[]
[ "pandas", "pandas_resample", "python" ]
stackoverflow_0074430223_pandas_pandas_resample_python.txt
Q: How to mock query for joined tables in SQLAlchemy and alchemy-mock when where-statement filters data from multiple tables? I have schema: CREATE SCHEMA problem AUTHORIZATION blockchain; CREATE TABLE problem.users ( id serial PRIMARY KEY NOT NULL, nick varchar NOT NULL ); CREATE TABLE problem.passwords_ke...
How to mock query for joined tables in SQLAlchemy and alchemy-mock when where-statement filters data from multiple tables?
I have schema: CREATE SCHEMA problem AUTHORIZATION blockchain; CREATE TABLE problem.users ( id serial PRIMARY KEY NOT NULL, nick varchar NOT NULL ); CREATE TABLE problem.passwords_keys ( id serial PRIMARY KEY NOT NULL, user_id serial references problem.users, password varchar NOT NULL, valid b...
[ "I've finally found out - there is no problem with querying joined tables - it is problem that mock.call.filter should be called once even for multiple filters.\nSo instead of:\nsession = UnifiedAlchemyMagicMock(data=[\n (\n [\n mock.call.query(schema.PasswordsKey),\n mock.call.join(...
[ 0 ]
[]
[]
[ "alchemy_mock", "python", "python_mock", "sqlalchemy", "unit_testing" ]
stackoverflow_0073797089_alchemy_mock_python_python_mock_sqlalchemy_unit_testing.txt
Q: python very long compilation time I am using plt.hist() function to show histogram. When I tried it on a smaller dataset, everything works fine. However, my original dataset contains nearly 30k samples, for which I need to show on that histogram 6 values per sample. I am aware this is a lot, but what I need help w...
python very long compilation time
I am using plt.hist() function to show histogram. When I tried it on a smaller dataset, everything works fine. However, my original dataset contains nearly 30k samples, for which I need to show on that histogram 6 values per sample. I am aware this is a lot, but what I need help with is how to make the compilation time...
[ "The greater the value of 'bins', the less the thickness of the lines\ntry:\nplt.hist(values, bins=250)\n\n", "\nBut I am not sure what exactly bins do. Will this result in printing the histogram too general for my data or will it just take 50 first values from my data?\n\nYou can imagine bins as a partition of y...
[ 0, 0 ]
[]
[]
[ "bins", "histogram", "matplotlib", "performance", "python" ]
stackoverflow_0074430118_bins_histogram_matplotlib_performance_python.txt
Q: How to display a list of strings dynamically in python I have a list of strings in python which are in form of an arithmetic problem. So: p_list = ['32 + 5', '4 - 1', '345 + 2390'] I would love each of the list to be arranged in this manner 32 4 345 + 5 - 1 + 2390 ---- --- ------ So esse...
How to display a list of strings dynamically in python
I have a list of strings in python which are in form of an arithmetic problem. So: p_list = ['32 + 5', '4 - 1', '345 + 2390'] I would love each of the list to be arranged in this manner 32 4 345 + 5 - 1 + 2390 ---- --- ------ So essentially i want the numbers to be right aligned and four spac...
[ "If your objective is to print out the equations, this function arranges them in your desired way:\ndef arithmetic_format(eq_list, sep = 4):\n top = mid = bot = \"\"\n sep = \" \" * sep\n for eq in eq_list:\n chars = eq.split()\n width = len(max(chars, key=len)) + 2\n top += chars[0].r...
[ 1, 0 ]
[ "Try this:\np_list = ['32 + 5', '4 - 1', '345 + 2390']\nup= []\ndown=[]\n\nfor op in p_list:\n new = op.split(' ')\n up.append(new[0] + ' '*4)\n if new[1] == '-':\n down.append(str(0 - int(new[-1])) + ' '*4)\n else:\n down.append('+' + new[-1] + ' '*3)\nfor index,value in enumerate(up):\n ...
[ -1 ]
[ "python", "string" ]
stackoverflow_0074429364_python_string.txt
Q: Django: saving unique value without duplicate it I'm trying to save unique name in the database but the problem I can save the same with different letters, for example I can save (IT, it, iT, It) I don't want to save it like that. Model: class Service(models.Model): id = models.UUIDField(primary_key=True, def...
Django: saving unique value without duplicate it
I'm trying to save unique name in the database but the problem I can save the same with different letters, for example I can save (IT, it, iT, It) I don't want to save it like that. Model: class Service(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.Cha...
[ "A very simple solution:\nclass Service(models.Model):\n name = models.CharField(max_length=50, unique=True)\n ....\n\n def clean(self):\n self.name = self.name.capitalize()\n\n", "this one helped me\nclass Service(models.Model):\n name = models.CharField(max_length=50, unique=True, null=False,...
[ 0, 0 ]
[]
[]
[ "django", "django_models", "postgresql", "python" ]
stackoverflow_0074429245_django_django_models_postgresql_python.txt
Q: How to use the find function to help replace a word in a sentence? I'm working on my Python homework of: Write a program that requests a sentence, a word in the sentence, and another word and then displays the sentence with the first word replaced by the second. The hint says to use the method "find" to help solve...
How to use the find function to help replace a word in a sentence?
I'm working on my Python homework of: Write a program that requests a sentence, a word in the sentence, and another word and then displays the sentence with the first word replaced by the second. The hint says to use the method "find" to help solve it but i can't think of a way to do so. sentence = input("Enter a sente...
[ "It is literally called .replace()\nresult = sentence.replace(word, replacement)\n\n", "Normally you can use replace method but if your teacher says so.\nWe will just find where the word starts at the sentence and we will cut this word and place our new one.\nsentence = input(\"Enter a sentence.\")\nword = input(...
[ 0, 0 ]
[]
[]
[ "developer_tools", "find", "python", "python_2.7", "python_3.x" ]
stackoverflow_0074430234_developer_tools_find_python_python_2.7_python_3.x.txt
Q: Why couldn't I import np.typing.NDArray, but now I can? I'm running into a weird situation with Python imports. Does someone know how this works? I have: import numpy as np values: Union[Sequence[int], np.typing.NDArray] probs: Union[Sequence[float], np.typing.NDArray] ​Now that fails because np.typing can't be i...
Why couldn't I import np.typing.NDArray, but now I can?
I'm running into a weird situation with Python imports. Does someone know how this works? I have: import numpy as np values: Union[Sequence[int], np.typing.NDArray] probs: Union[Sequence[float], np.typing.NDArray] ​Now that fails because np.typing can't be imported this way. I guess since that is not defined in the i...
[ "After you run import\nimport numpy.typing as npt \n\ninterpreter \"find out\" addition parts of np.\nYou can check this with:\nimport numpy as np\nlen(dir(np)) # 602 (in my case)\n\nimport numpy.typing as npt\nlen(dir(np)) # 604\n\n" ]
[ 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0071064845_numpy_python.txt
Q: thresholding in 3 color : black, white, and gray , instead of just black and white I expect can threshold in 3 color : black, white, and gray , instead of just black and white, that later on I can separate the sticker out from original img now my .py script can thresholding, make image's color to black and white c...
thresholding in 3 color : black, white, and gray , instead of just black and white
I expect can threshold in 3 color : black, white, and gray , instead of just black and white, that later on I can separate the sticker out from original img now my .py script can thresholding, make image's color to black and white color import numpy as np import glob import matplotlib.pyplot as plt import skimage.io im...
[ "binary_mask = blurred_image < t\n\nAs you are evaluating a boolean expression on the right, this will give either false (0) or true (1) as target values for your mask (which makes sense if you actually need a mask, it's a binary image).\nIf you want to separate the sticker regions only (so remove everything grey),...
[ 1 ]
[]
[]
[ "image_processing", "opencv", "python", "scikit_image" ]
stackoverflow_0074429723_image_processing_opencv_python_scikit_image.txt
Q: Scrapy scraping nested text using css selectors I have the following html code: <div class='article'> <p>Lorem <strong>ipsum</strong> si ammet</p> </div> So to get the text data as: Lorem ipsum si ammet, so I tried to use: response.css('div.article >p::text ').extract() But I only receive only lorem sie ammet. ...
Scrapy scraping nested text using css selectors
I have the following html code: <div class='article'> <p>Lorem <strong>ipsum</strong> si ammet</p> </div> So to get the text data as: Lorem ipsum si ammet, so I tried to use: response.css('div.article >p::text ').extract() But I only receive only lorem sie ammet. How can I get both <p> and <strong> texts using CSS ...
[ "One liner solution.\n\"\".join(a.strip() for a in response.css(\"div.article *::text\").extract())\n\ndiv.article * means to scrape everything inside the div.article\nOr an easy way to write it\ntext = \"\"\nfor a in response.css(\"div.article *::text\").extract()\n text += a.strip()\n\nBoth approaches are same...
[ 3, 0 ]
[]
[]
[ "css", "python", "scrapy" ]
stackoverflow_0049516650_css_python_scrapy.txt
Q: How to use the inbuilt FindAllPathsOfLengthN() methods in rdkit..? I recently came across a inbuilt method in rdkit called : FindAllPathsOfLengthN i tried to find path length of 2 in a caffine molecule. below is the code i executed... but it produced has no attribute error please help. mol = Chem.MolFromSmi...
How to use the inbuilt FindAllPathsOfLengthN() methods in rdkit..?
I recently came across a inbuilt method in rdkit called : FindAllPathsOfLengthN i tried to find path length of 2 in a caffine molecule. below is the code i executed... but it produced has no attribute error please help. mol = Chem.MolFromSmiles("CN1C=NC2=C1C(=O)N(C)C(=O)N2C") mol rdkit.findAllPaths...
[ "Sorry guys i found the answer...\nI just needed to import a submodule and use the method.\n import rdkit\n\n from rdkit.Chem import rdmolops\n\n mol=Chem.MolFromSmiles(\"c1occ(NC(F)(F)F)c1N(O)C\")\n mol\n\n print(len(list(rdkit.Chem.rdmolops.FindAllPathsOfLengthN(mol,2))))\n\n print(len(list(rdkit.Chem.rdmol...
[ 0 ]
[]
[]
[ "python", "rdkit" ]
stackoverflow_0074430264_python_rdkit.txt
Q: Filter dropdown in django forms In forms, I am trying to filter marketplace drop down field that belong to the logged in user based on its group. Its listing all the dropdown field items. I tried below but I think something is wrong with the filter part. class InfringementForm(ModelForm): def __init__(self, us...
Filter dropdown in django forms
In forms, I am trying to filter marketplace drop down field that belong to the logged in user based on its group. Its listing all the dropdown field items. I tried below but I think something is wrong with the filter part. class InfringementForm(ModelForm): def __init__(self, user, *args, **kwargs): super(Infringe...
[ "Try this inside __init__() method:\ndef __init__(self, user, *args, **kwargs): \n self.user = user \n super(InfringementForm,self).__init__(*args, **kwargs)\n self.fields['marketplace'].queryset = Marketplace.objects.filter(groups__user=self.user)\n\n", "final answer is adding self.user = user in th...
[ 1, 0, 0 ]
[]
[]
[ "django", "django_forms", "django_models", "django_queryset", "python" ]
stackoverflow_0074425896_django_django_forms_django_models_django_queryset_python.txt
Q: Why doesn't the "if" condtion work properly alone in this python script? I wrote a simple python script that creates a 7x7 list of dots '.', I want to change the diagonal to stars '*'. Here is my script n=7 l=['.']*n m=[l]*n for i in range(n): for j in range(n): if i==j: m[i][j]='*' pr...
Why doesn't the "if" condtion work properly alone in this python script?
I wrote a simple python script that creates a 7x7 list of dots '.', I want to change the diagonal to stars '*'. Here is my script n=7 l=['.']*n m=[l]*n for i in range(n): for j in range(n): if i==j: m[i][j]='*' print(*m[i]) Here is the output I get * . . . . . . * * . . . . . * * * . . . ...
[ "It's not because of the if condition not working, but this m = [l] * n creates an array of size n, with all being the same copy of the array l, like [l, l, l, l, l, l, l]\nYou can see what I am saying with this script:\nl=['.']*n\nm=[l]*n\nm[1][1] = '*'\n\nm is now:\n[\n ['.', '*', '.', '.', '.', '.', '.'], \n ...
[ 2, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074430446_list_python.txt
Q: How to schedule a python/R script to run on a powerBI dataset I already have a R script that will dump the data from a given dataset in powerBI to .csv file in local desktop. But I want to schedule this script to run every day. How can this be achieved? Can this be achieved without using gateway tool available in ...
How to schedule a python/R script to run on a powerBI dataset
I already have a R script that will dump the data from a given dataset in powerBI to .csv file in local desktop. But I want to schedule this script to run every day. How can this be achieved? Can this be achieved without using gateway tool available in internet blogs like https://community.powerbi.com/t5/Community-Blog...
[ "You can use some sort of Task Scheduler depending on the OS you're using, or you can download On-Premise Gateway Personal Mode (Here) and run it through that on Power BI Service.\nThis gateway will be available only when using your account and this is great if your R script is embedded inside Power Query, then wit...
[ 0 ]
[]
[]
[ "powerbi", "python", "r" ]
stackoverflow_0074428621_powerbi_python_r.txt
Q: Random fill colour for shapes in Python(TKinter) I am wondering how to get a random color out of a list to use in the draw_rectangle() colors = ["red", "orange", "yellow", "green", "blue", "violet"] canvas.create_rectangle(self.x, self.y, self.x + 60, self.y + 60, fill = random.choice(colors)) This causes my cod...
Random fill colour for shapes in Python(TKinter)
I am wondering how to get a random color out of a list to use in the draw_rectangle() colors = ["red", "orange", "yellow", "green", "blue", "violet"] canvas.create_rectangle(self.x, self.y, self.x + 60, self.y + 60, fill = random.choice(colors)) This causes my code to crash, what else can I try?
[ "de=(\"%02x\"%random.randint(0,255))\nre=(\"%02x\"%random.randint(0,255))\nwe=(\"%02x\"%random.randint(0,255))\nge=\"#\"\ncolor=ge+de+re+we\n\nand in tkinter put \nfill=color\n\neasy\nyou can also make\nfill=\"#\"+(\"%06x\"%random.randint(0,16777215))\n\n", "You can use random.choice like this\nimport random\nco...
[ 4, 3, 0 ]
[ "You can use choice, from package random\nrandom.choice(color)\n\n" ]
[ -1 ]
[ "list", "python", "random", "tkinter" ]
stackoverflow_0022950997_list_python_random_tkinter.txt
Q: Match opening hours dataframes Pandas I want to match a dataframe that contains for each day of the week the opening and closing hours with a dataframe that contains a datetime column. The first dataframe I have is: day_of_week start end 0 1 08:00 18:00 1 2 08:00 18:00 2 3 ...
Match opening hours dataframes Pandas
I want to match a dataframe that contains for each day of the week the opening and closing hours with a dataframe that contains a datetime column. The first dataframe I have is: day_of_week start end 0 1 08:00 18:00 1 2 08:00 18:00 2 3 08:00 18:00 3 4 08...
[ "If the start and end hours are the same across all days, then you can simply use:\ndf2['DuringHours'] = np.where((df2['day_of_week'] <= 5) & \\\n (df2.index.hour >= 8) & \\\n (df2.index.hour <= 18) > 0,True,False)\n\nReturning:\n e...
[ 0 ]
[]
[]
[ "datetime", "pandas", "python" ]
stackoverflow_0074430574_datetime_pandas_python.txt
Q: How to smooth list of numerical values in Python? I have a collection of lists of integer values in python like the following: [0, 0, 1, 0, 1, 0, 0, 2, 1, 1, 1, 2, 1] Now I would like to have a somewhat "smoothed" sequence where each value with the same preceding and following value (which both differ from the ce...
How to smooth list of numerical values in Python?
I have a collection of lists of integer values in python like the following: [0, 0, 1, 0, 1, 0, 0, 2, 1, 1, 1, 2, 1] Now I would like to have a somewhat "smoothed" sequence where each value with the same preceding and following value (which both differ from the central value in question) is replaced with this preceedi...
[ "A straightforward loop should do the trick:\n_list = [0, 0, 1, 0, 1, 0, 0, 2, 1, 1, 1, 2, 1]\n\nfor i in range(1, len(_list)-1):\n if _list[i-1] == _list[i+1]:\n _list[i] = _list[i-1]\n\nprint(_list)\n\nOutput:\n[0, 0, 0, 0, 0, 0, 0, 2, 1, 1, 1, 1, 1]\n\n", "arr = [0, 0, 1, 0, 1, 0, 0, 2, 1, 1, 1, 2, 1...
[ 1, 0, 0 ]
[]
[]
[ "python", "sequence", "smoothing" ]
stackoverflow_0074430304_python_sequence_smoothing.txt
Q: Streamlit image/file upload to deta drive This was also on streamlit discussion I want to help others who are facing the same problem! A: Hi this question I found on streamlit discussions, Posting answer on stack overflow might help others who are facing a similar problem. U can find the anser here. If we use st...
Streamlit image/file upload to deta drive
This was also on streamlit discussion I want to help others who are facing the same problem!
[ "Hi this question I found on streamlit discussions, Posting answer on stack overflow might help others who are facing a similar problem. U can find the anser here.\nIf we use st.image() it works because you are taking the input from st.file_uploader() or st.camera_input(), and displaying it through st.image.\nIt wo...
[ 1, 0 ]
[]
[]
[ "file_upload", "python", "streamlit" ]
stackoverflow_0074423171_file_upload_python_streamlit.txt
Q: In Python, how do I split a string and keep the separators? Here's the simplest way to explain this. Here's what I'm using: re.split('\W', 'foo/bar spam\neggs') >>> ['foo', 'bar', 'spam', 'eggs'] Here's what I want: someMethod('\W', 'foo/bar spam\neggs') >>> ['foo', '/', 'bar', ' ', 'spam', '\n', 'eggs'] The rea...
In Python, how do I split a string and keep the separators?
Here's the simplest way to explain this. Here's what I'm using: re.split('\W', 'foo/bar spam\neggs') >>> ['foo', 'bar', 'spam', 'eggs'] Here's what I want: someMethod('\W', 'foo/bar spam\neggs') >>> ['foo', '/', 'bar', ' ', 'spam', '\n', 'eggs'] The reason is that I want to split a string into tokens, manipulate it, ...
[ "The docs of re.split mention:\n\nSplit string by the occurrences of pattern. If capturing\nparentheses are used in pattern, then the text of all groups in the\npattern are also returned as part of the resulting list.\n\nSo you just need to wrap your separator with a capturing group:\n>>> re.split('(\\W)', 'foo/bar...
[ 418, 47, 32, 17, 12, 4, 4, 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002136556_python_regex.txt
Q: BeautifulSoup get text from tag searching by Title I'm scrapping a webpage with python that provides different documents and I want to retrieve some information from them. The document gives the information in two ways, there's this one where it gives it like this: Company name: Company name which is solved in thi...
BeautifulSoup get text from tag searching by Title
I'm scrapping a webpage with python that provides different documents and I want to retrieve some information from them. The document gives the information in two ways, there's this one where it gives it like this: Company name: Company name which is solved in this question, and another one that goes like Title: and th...
[ "Link do not contain such Denomination but you can adapt and proceed like:\nfor e in soup.select('span:-soup-contains(\"Title:\") + div'):\n print(e.get_text(strip=True))\n\nIn newer code avoid old syntax findAll() instead use find_all() or select() with css selectors - For more take a minute to check docs\nExam...
[ 2 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074430358_beautifulsoup_python_web_scraping.txt
Q: 'str' object has no attribute 'str' - not sure why I have the following code. I want to create a list 'newvalues' containing the number of 'luck' trials ('numberoftrials') on a given date, where this value will equal 0 if there are no 'luck' trials on that date. However, I get the error 'str' object has no attribu...
'str' object has no attribute 'str' - not sure why
I have the following code. I want to create a list 'newvalues' containing the number of 'luck' trials ('numberoftrials') on a given date, where this value will equal 0 if there are no 'luck' trials on that date. However, I get the error 'str' object has no attribute 'str' when I try to check whether a row in the column...
[ "I solved my issue using an 'if string is in row' method:\nfor i in range(0,len(numberofeachconditiononthatdate)): \n if 'luck' in numberofeachconditiononthatdate['condition'].iloc[i]:\n newvalue = numberofeachconditiononthatdate['numberoftrials'].iloc[i]\n newvalues.append(newvalue)\n else:\n...
[ 1 ]
[]
[]
[ "dataframe", "jupyter_notebook", "pandas", "python" ]
stackoverflow_0074430647_dataframe_jupyter_notebook_pandas_python.txt
Q: Bjontegaard calculation using only one pair of PSNR and BitRate I want to calculate the BD-Rate for two different video encoding settings using the python script below. Using 4 RD Points (R1 and PSNR1 are the reference RD Points of the Video1 while R2 and PSNR2 are the new tests with different video settings of Vi...
Bjontegaard calculation using only one pair of PSNR and BitRate
I want to calculate the BD-Rate for two different video encoding settings using the python script below. Using 4 RD Points (R1 and PSNR1 are the reference RD Points of the Video1 while R2 and PSNR2 are the new tests with different video settings of Video2) the script works fine ie from bjontegaard_metric import * R...
[ "According to IETF at https://tools.ietf.org/id/draft-ietf-netvc-testing-06.html#rfc.section.4.2 number 2 At least four points must be computed. These points should be the same quantizers when comparing two versions of the same codec. So any lesser points than 4 are not valid for reliable results.\n1. Rate/distorti...
[ 0 ]
[]
[]
[ "encoding", "python", "video", "video_compression" ]
stackoverflow_0074428840_encoding_python_video_video_compression.txt
Q: Using 'isin()' function to compare values in two different pandas series - unhashable type: 'Series' I have the following code. I am trying to check if a 'date-time' value in the column numberofeachconditiononthatdate['Date'] is in the column 'luckonthatdate['Date']'. If it is, then I want that particular date-tim...
Using 'isin()' function to compare values in two different pandas series - unhashable type: 'Series'
I have the following code. I am trying to check if a 'date-time' value in the column numberofeachconditiononthatdate['Date'] is in the column 'luckonthatdate['Date']'. If it is, then I want that particular date-time value to be assigned to the variable 'value'. If not, then I want the variable 'value' to equal 0. In ot...
[ "Instead of an explicit for loop, you can optimise it using merge. You can do something like:\nnumberofeachconditiononthatdate = (numberofeachconditiononthatdate\n .merge(luckonthatdate[['Date', 'luck']], how='left', on='Date'))\n\nnumberofeachconditiononthatdate['luck'] = numberofe...
[ 0, 0, 0 ]
[]
[]
[ "dataframe", "jupyter_notebook", "pandas", "python", "series" ]
stackoverflow_0074429641_dataframe_jupyter_notebook_pandas_python_series.txt
Q: During handling of the above exception ([Errno 13] Permission denied: 'new1234567.csv'), another exception occurred I am trying to create a csv file using pandas in the AWS EC2 instance(Linux OS) using the below code. import pandas as pd df = pd.DataFrame(listlead) df.to_csv('new1234567.csv') I am getting an erro...
During handling of the above exception ([Errno 13] Permission denied: 'new1234567.csv'), another exception occurred
I am trying to create a csv file using pandas in the AWS EC2 instance(Linux OS) using the below code. import pandas as pd df = pd.DataFrame(listlead) df.to_csv('new1234567.csv') I am getting an error 'Permission denied' from the server. But when I run it on the local system(Windows OS) it was working fine. I try to ch...
[ "It seems like you don't have permission to create a csv file in the folder you're working in, on the server.\nWhen you rundf.to_csv('new1234567.csv'), it looks for a file named new1234567.csv inside the current directory, and if it doesn't exists, it tries creates it - which is also the reason you're not able to d...
[ 0 ]
[]
[]
[ "linux", "pandas", "python" ]
stackoverflow_0074430660_linux_pandas_python.txt
Q: How to add a role with discord.py? Basically I am making a authentication system and the user is doing /claim <key> I already made the key check system: if its correct or incorrect. How do I make it so it gives the user the role "Premium" if the key is correct? I was trying to do the following: member = ct...
How to add a role with discord.py?
Basically I am making a authentication system and the user is doing /claim <key> I already made the key check system: if its correct or incorrect. How do I make it so it gives the user the role "Premium" if the key is correct? I was trying to do the following: member = ctx.author role = get(member.serve...
[ "It is unclear what the get() function is doing. I assume it is discord.utils.get. Normally the servers are called guilds within discord.\nA role is added by await member.add_roles(role) where member = await guild.fetch_member(discord_user_ctx.id), and the guild is guild = await self.bot.fetch_guild(YOUR_GUILD_ID)\...
[ 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074430716_discord_discord.py_python.txt
Q: How do I run a script when an api endpoint is hit? Here is how I want my program to work. Step 2 is what I am unsure of how to implement. Client makes API call to /email endpoint /email endpoint has a script run that gather emails from GMAIL API Put contents into response object Returns response object back to cl...
How do I run a script when an api endpoint is hit?
Here is how I want my program to work. Step 2 is what I am unsure of how to implement. Client makes API call to /email endpoint /email endpoint has a script run that gather emails from GMAIL API Put contents into response object Returns response object back to client I understand how to make a static api response. Bu...
[ "I saw the flask tag in your post.\nI only played around with flask for certain interviews, but know enough to say calling a python script outside your running server is somewhat of an antipattern.\nI assume your backend is a flask app, so ideally, you'd want to wrap whatever script you have in your python script f...
[ 0 ]
[]
[]
[ "flask", "python", "uri" ]
stackoverflow_0074430590_flask_python_uri.txt
Q: How to calculate sum of first n elements in dataframe column by condition? I have dataframe enter image description here how to calculate sum of lets 3 first negative elements of first column? I tried loc and ilocs but they sum all negative elements in column. I expected -3 A: Filter first negative values - less...
How to calculate sum of first n elements in dataframe column by condition?
I have dataframe enter image description here how to calculate sum of lets 3 first negative elements of first column? I tried loc and ilocs but they sum all negative elements in column. I expected -3
[ "Filter first negative values - less like 0, then first 3 and sum:\nout = df.loc[df.a.lt(0), 'a'].head(3).sum()\n\nout = df.loc[df.a.lt(0), 'a'].iloc[:3].sum()\n\nEDIT: If need first column select by positionm not by label a:\nout = df.iloc[df.iloc[:, 0].lt(0).to_numpy(), 0].iloc[:3].sum()\n\n" ]
[ 0 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074430895_numpy_pandas_python.txt
Q: cannot import name 'BisectingKMeans' from 'sklearn.cluster' (C:\Users\Administrator\anaconda3\lib\site-packages\sklearn\cluster\__init__.py) When I try to use sklearn.cluster.BisectingKMeans in my jupyter notebook, an ImportError occured. It is said in the document that this method is new in version 1.1, and my sc...
cannot import name 'BisectingKMeans' from 'sklearn.cluster' (C:\Users\Administrator\anaconda3\lib\site-packages\sklearn\cluster\__init__.py)
When I try to use sklearn.cluster.BisectingKMeans in my jupyter notebook, an ImportError occured. It is said in the document that this method is new in version 1.1, and my scikit-learn version is 1.1.3. I was using the base environment so it's not an issue of lacking package in current environment. enter image descript...
[ "This works on my machine:\nfrom sklearn.cluster import BisectingKMeans\nAlso:\nimport sklearn\nsklearn.__version__\n> 1.1.2\n\nMaybe you have a typo?\n" ]
[ 0 ]
[]
[]
[ "anaconda", "cluster_computing", "jupyter_notebook", "python", "scikit_learn" ]
stackoverflow_0074430885_anaconda_cluster_computing_jupyter_notebook_python_scikit_learn.txt
Q: Left shift each row of 2D Numpy array independently A = np.array([[4, 3, 2], [1, 2, 3], [0, -1, 5]]) shift = np.array([1,2,1]) out = np.array([[3, 2, np.nan], [3, np.nan, np.nan], [-1, 5, np.nan]]) I want to left shift the 2D numpy array towards the left f...
Left shift each row of 2D Numpy array independently
A = np.array([[4, 3, 2], [1, 2, 3], [0, -1, 5]]) shift = np.array([1,2,1]) out = np.array([[3, 2, np.nan], [3, np.nan, np.nan], [-1, 5, np.nan]]) I want to left shift the 2D numpy array towards the left for each row independently as given by the shift vector an...
[ "import numpy as np\n\nA = np.array([[4, 3, 2],\n [1, 2, 3],\n [0, -1, 5]])\n\nshift = np.array([1,2,1])\n\n\nx,y = A.shape\nres = np.full(x*y,np.nan).reshape(x,y)\n\nfor i in range(x):\n for j in range(y):\n res[i][:(y-shift[i])]=A[i][shift[i]:]\nprint(res)\n\n", "Using Roll r...
[ 0, 0, 0 ]
[]
[]
[ "numpy", "python", "vector" ]
stackoverflow_0074430596_numpy_python_vector.txt
Q: How to stop a task generated by Tornado spawn_task I am writing a WebSocket server using Python's Tornado framework. class MyHandler(WebSocketHandler): def open(self, device: str): async def aTask(): while True: # do something again and again until the connection closes ...
How to stop a task generated by Tornado spawn_task
I am writing a WebSocket server using Python's Tornado framework. class MyHandler(WebSocketHandler): def open(self, device: str): async def aTask(): while True: # do something again and again until the connection closes IOLoop.current().spawn_task(aTask) def on_clos...
[ "Set an attribute on the current instance which you can check in the while loop. Set the attribute to False when connection closes:\ndef open(self, device):\n setattr(self, 'is_open', True)\n\n while self.is_open:\n # ...\n\ndef on_close(self):\n setattr(self, 'is_open', False)\n\n" ]
[ 1 ]
[]
[]
[ "async_await", "event_loop", "python", "tornado", "websocket" ]
stackoverflow_0074425578_async_await_event_loop_python_tornado_websocket.txt
Q: Want to replace comma with decimal point in text file where after each number there is a comma in python eg Arun,Mishra,108,23,34,45,56,Mumbai o\p I want is Arun,Mishra,108.23,34,45,56,Mumbai Tried to replace the comma with dot but all the demiliters are replaced with comma tried text.replace(',','.') but replac...
Want to replace comma with decimal point in text file where after each number there is a comma in python
eg Arun,Mishra,108,23,34,45,56,Mumbai o\p I want is Arun,Mishra,108.23,34,45,56,Mumbai Tried to replace the comma with dot but all the demiliters are replaced with comma tried text.replace(',','.') but replacing all the commas with dot
[ "You can use regex for these kind of tasks:\nimport re\n\nold_str = 'Arun,Mishra,108,23,34,45,56,Mumbai'\nnew_str = re.sub(r'(\\d+)(,)(\\d+)', r'\\1.\\3', old_str, 1)\n>>> 'Arun,Mishra,108.23,34,45,56,Mumbai'\n\nThe search pattern r'(\\d+)(,)(\\d+)' was to find a comma between two numbers. There are three capture g...
[ 2, 0, 0 ]
[ "First split the string using s.split() and then replace ',' in 2nd element\nafter replacing join the string back again.\ns= 'Arun,Mishra,108,23,34,45,56,Mumbai '\nls = s.split(',')\nls[2] = '.'.join([ls[2], ls[3]])\nls.pop(3)\ns = ','.join(ls)\n\n", "It changes all the commas to dots if dot have numbers before a...
[ -1, -1 ]
[ "csv", "data_analysis", "python", "python_3.x", "python_re" ]
stackoverflow_0074430512_csv_data_analysis_python_python_3.x_python_re.txt
Q: not enough values to unpack (expected 2, got 1) when loop through dict I have a list of dicts like this: zip_values = [{'Spain': '43004'}, {'Spain': '43830'}, {'Spain': '46003'}, {'Spain': '50006'}, {'Portugal': ''}, {'Portugal': '1000-155'}, {'Portugal': '1000-226'}, {'Portugal': '1050-175'}, {'Portugal': '1050-1...
not enough values to unpack (expected 2, got 1) when loop through dict
I have a list of dicts like this: zip_values = [{'Spain': '43004'}, {'Spain': '43830'}, {'Spain': '46003'}, {'Spain': '50006'}, {'Portugal': ''}, {'Portugal': '1000-155'}, {'Portugal': '1000-226'}, {'Portugal': '1050-175'}, {'Portugal': '1050-190'}, {'Portugal': '1070-041'}, {'Portugal': '1150-101'}, {'Portugal': '1150...
[ "You are trying to iterate over a list of dictionaries, for key, value in zip_values would try to map the key and value to a dictionary object(e.g. - {'Spain': '43004'}) which is not supported. Had it been a list/tuple(e.g. [ Spain', '43004'] it would have worked.\nTry something like this -\nfor d in zip_values:\n ...
[ 2, 1 ]
[]
[]
[ "dictionary", "key_value", "python" ]
stackoverflow_0074430928_dictionary_key_value_python.txt
Q: How to get the values at the pixels of a bokeh image glyph in hover tool? I have generated a bokeh 2d-histogram plot as mentioned in this StackOverflow answer. The code and respective image is given below. In the code, the count of data-points per bin is in the entries in H. How can I get access to an individual p...
How to get the values at the pixels of a bokeh image glyph in hover tool?
I have generated a bokeh 2d-histogram plot as mentioned in this StackOverflow answer. The code and respective image is given below. In the code, the count of data-points per bin is in the entries in H. How can I get access to an individual pixel-index to get the value at respective index in H and show it in the hover-t...
[ "I don't know the raw Bokeh code to do this, but in HoloViews it's:\nimport numpy as np, holoviews as hv\nhv.extension('bokeh')\n\na = np.array([1, 1.5, 2, 3, 4, 5])\nb = np.array([15, 16, 20, 35, 45, 50])\nH, xe, ye = np.histogram2d(a, b, bins=5)\n\nimg = hv.Image(H[::-1], bounds=(-1,-1,1,1), vdims=['image_index']...
[ 1 ]
[]
[]
[ "bokeh", "bokehjs", "histogram2d", "holoviews", "python" ]
stackoverflow_0074410016_bokeh_bokehjs_histogram2d_holoviews_python.txt
Q: Can I use a variable inside a parameter of a function in py-cord? My Problem I'm trying to use a variable that selects a certain list depending on a user input from the operation_select slash command in py-cord. Whenever I run the script the aircraft option in the select_role command always has no choices. I expec...
Can I use a variable inside a parameter of a function in py-cord?
My Problem I'm trying to use a variable that selects a certain list depending on a user input from the operation_select slash command in py-cord. Whenever I run the script the aircraft option in the select_role command always has no choices. I expected this because I defined the variable with [ ] already. import shutil...
[ "As far as I know it is not possible to assign a dynamic variable to the command. However there are 2 solutions I can think of.\n\ncallback functions can be used inside a command. This makes it possible to dynamically search a big pile of results. Of course this can be altered such that the top results are the airc...
[ 0 ]
[]
[]
[ "bots", "discord", "function", "pycord", "python" ]
stackoverflow_0074337283_bots_discord_function_pycord_python.txt
Q: Consume multiple messages at a time I am using an external service (Service) to process some particular type of objects. The Service works faster if I send objects in batches of 10. My current architecture is as follows. A producer broadcasts objects one-by-one, and a bunch of consumers pull them (one-by-one) from...
Consume multiple messages at a time
I am using an external service (Service) to process some particular type of objects. The Service works faster if I send objects in batches of 10. My current architecture is as follows. A producer broadcasts objects one-by-one, and a bunch of consumers pull them (one-by-one) from a queue and send them to The Service. Th...
[ "You cannot batch messages in the consumer callback, but you could use a thread safe library and use multiple threads to consume data. The advantage here is that you can fetch five messages on five different threads and combine the data if needed.\nAs an example you can take a look on how I would implement this usi...
[ 4, 0 ]
[]
[]
[ "pika", "python", "rabbitmq" ]
stackoverflow_0023933033_pika_python_rabbitmq.txt
Q: pandas.read_excel() na_values not working correctly As title states, after reviewing docs I am reading an .xlsx file, with a column 'HOUR' which has many values, when an instance has value 99, i want to convert to None I have tried the na_values param with different values: na_values = ['99'] na_values = [r'99'] ...
pandas.read_excel() na_values not working correctly
As title states, after reviewing docs I am reading an .xlsx file, with a column 'HOUR' which has many values, when an instance has value 99, i want to convert to None I have tried the na_values param with different values: na_values = ['99'] na_values = [r'99'] na_values = 99 ... To then read the excel like this: acc...
[ "Just apply replace method on the dataframe after reading the excel file:\ndf.replace(99, np.nan)\n\nIf you want to replace values for only specific column like Hour:\ndf['HOUR'].replace(99, np.nan)\n\nUpdate:\nI think you want to know why read_excel() method isn't working with the na values you provided, if you ch...
[ 0, 0 ]
[]
[]
[ "dataframe", "excel", "missing_data", "pandas", "python" ]
stackoverflow_0074423168_dataframe_excel_missing_data_pandas_python.txt
Q: cfg file not resolved when trying to import python library from zip included to a path I use Spark 2.4.0 + K8s cluster deployment mode + python 3.5. I pack all libraries into zip archive and send it to AWS S3, then attach to context sc = pyspark.SparkContext(appName=args.job_name, environment=environment) sc.addP...
cfg file not resolved when trying to import python library from zip included to a path
I use Spark 2.4.0 + K8s cluster deployment mode + python 3.5. I pack all libraries into zip archive and send it to AWS S3, then attach to context sc = pyspark.SparkContext(appName=args.job_name, environment=environment) sc.addPyFile('s3a://.../libs.zip') sc.addPyFile('s3a://.../code.zip') Import works, I can import a...
[ "Some pip-installed packages are not safe to be compressed into a zip. For example, used Airflow v1.10.15 was not ZIP-safe (not sure about new versions)\n" ]
[ 1 ]
[]
[]
[ "apache_spark", "kubernetes", "pyspark", "python" ]
stackoverflow_0053620517_apache_spark_kubernetes_pyspark_python.txt
Q: Python - forcing function inputs I need to force function inputs to take specific values. Without writing if, else blocks inside the function, is there any way to specify certain inputs beforehand ? def product(product_type = ['apple','banana']): print(product_type) But the function requires product_type as s...
Python - forcing function inputs
I need to force function inputs to take specific values. Without writing if, else blocks inside the function, is there any way to specify certain inputs beforehand ? def product(product_type = ['apple','banana']): print(product_type) But the function requires product_type as single string (product('apple') or prod...
[ "\nWithout writing if, else blocks inside the function, is there any way to specify certain inputs beforehand ?\n\nNot really.\nYou can use typing with an Enum or a Literal but that assumes a type checker is actually being run on the codebase in all cases.\nPython is otherwise dynamically, it will not normally vali...
[ 1 ]
[]
[]
[ "python", "type_hinting" ]
stackoverflow_0074430947_python_type_hinting.txt
Q: Change a dataframe of floats and objects into a binary dataframe whilst retaining string values of column and row headers This is my dataset: Name Test1 Test3 Test2 Quiz Boo 0.9 0 0 1.0 Buzz 0.8 0.7 0 0 Bree 0 0 1.0 0 How I want my result dataset: Name Test1 Test3 Test2 Quiz Boo 1 0 0 1 Buzz 1 1 0 0 Bree ...
Change a dataframe of floats and objects into a binary dataframe whilst retaining string values of column and row headers
This is my dataset: Name Test1 Test3 Test2 Quiz Boo 0.9 0 0 1.0 Buzz 0.8 0.7 0 0 Bree 0 0 1.0 0 How I want my result dataset: Name Test1 Test3 Test2 Quiz Boo 1 0 0 1 Buzz 1 1 0 0 Bree 0 0 1 0 I tried the df.astype to int64 - but this changed all values below 1 to 0. I also tried: df1 = d...
[ "df.set_index('Name').astype('float').gt(0.4).astype('int').reset_index()\n\noutput:\n Name Test1 Test3 Test2 Quiz\n0 Boo 1 0 0 1\n1 Buzz 1 1 0 0\n2 Bree 0 0 1 0\n\n", "It depends of treshold - if need 1 if values greater like 0.4 c...
[ 2, 1 ]
[]
[]
[ "dataframe", "floating_point", "integer", "pandas", "python" ]
stackoverflow_0074431108_dataframe_floating_point_integer_pandas_python.txt
Q: How to detect if a device on COM port is hanged? I have a temperature measurement device with which i can communicate using pyserial module on COM port. I can read and write from and to the device from USB interface. Now the device hangs sometimes and i can no longer read or write values to the device. The python ...
How to detect if a device on COM port is hanged?
I have a temperature measurement device with which i can communicate using pyserial module on COM port. I can read and write from and to the device from USB interface. Now the device hangs sometimes and i can no longer read or write values to the device. The python script always hangs on the following initialization fu...
[ "Freezing inside the serial constructor means that something is wrong on the usb-to-serial level, while the serial backend might still function properly. Problem with driver or hardware can't have a general solution.\nSome thoughts:\n\nTerminating the process, while a read operation is ongoing may leave the serial ...
[ 0 ]
[]
[]
[ "com_port", "pyserial", "python", "serial_port", "usb" ]
stackoverflow_0074429989_com_port_pyserial_python_serial_port_usb.txt
Q: Python - Selenium (XPath) "Message: no such element: Unable to locate element" im trying to interact with a website. I want to apply some filters but i have an error, my code does not recognize the xpath. from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.c...
Python - Selenium (XPath) "Message: no such element: Unable to locate element"
im trying to interact with a website. I want to apply some filters but i have an error, my code does not recognize the xpath. from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By options=Options() options.add_argument('--windoes-size=1920,1080...
[ "You should use another XPATH for option choosing.\nSeems like ids for options may be generated dynamically.\nSo you can try following XPATHs for different filters:\n//button[@value=\"m5\"] # Last 5 minutes button\n//button[@value=\"h1\"] # Last hour\n//button[@value=\"h6\"] # Last 6 hours\n//button[@value=\"...
[ 1 ]
[ "Have you tried using CSS_SELECTOR? I was working with Selenium recently, and sometimes when XPATH was not working, CSS_SELECTOR was.\nfolder=driver.find_element(By.CSS_SELECTOR, \"selector here\")\n\n" ]
[ -1 ]
[ "python", "selenium", "selenium_chromedriver", "selenium_webdriver", "web_scraping" ]
stackoverflow_0074431140_python_selenium_selenium_chromedriver_selenium_webdriver_web_scraping.txt
Q: How do check for a palindrome in Python? I am given word and I have to check if the word is a palindrome. My program works well until I play around with the case of the word. def isPalindrome(word): reversedWord = word[::-1] palindrome = true for n in range(len(word)): if(word[n] != reversedWor...
How do check for a palindrome in Python?
I am given word and I have to check if the word is a palindrome. My program works well until I play around with the case of the word. def isPalindrome(word): reversedWord = word[::-1] palindrome = true for n in range(len(word)): if(word[n] != reversedWord[i]) palindrome = false retur...
[ "You are already reversing the string. Just return reversedWord.lower() == word.lower() instead of checking character by character.\n", "You need to normalise the string to either upper- or lower-case.\ndef isPalindrome(word):\n word = word.lower()\n return word == word[::-1]\n\n", "The simplest form to this ...
[ 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074431099_python.txt
Q: add columns with duplicate key with pandas I have a dataframe that looks like this: key variable1 variable2 variable3 A x 5 s A x 6 t A x 6 t B x 5 s B x 6 t B x 6 t And I would like t...
add columns with duplicate key with pandas
I have a dataframe that looks like this: key variable1 variable2 variable3 A x 5 s A x 6 t A x 6 t B x 5 s B x 6 t B x 6 t And I would like to create a new dataframe with this structure key...
[ "Use DataFrame.set_index with GroupBy.cumcount for counter, reshape by DataFrame.unstack and last set new columns names in list comprehension:\ndf1 = (df.set_index(['key',df.groupby('key').cumcount()])\n .unstack()\n .sort_index(axis=1, level=1))\n\ndf1.columns = [f'variable{x}' for x in range(1, le...
[ 1 ]
[]
[]
[ "database", "dataframe", "duplicates", "pandas", "python" ]
stackoverflow_0074431230_database_dataframe_duplicates_pandas_python.txt
Q: Spark SQL Row_number() PartitionBy Sort Desc I've successfully create a row_number() partitionBy by in Spark using Window, but would like to sort this by descending, instead of the default ascending. Here is my working code: from pyspark import HiveContext from pyspark.sql.types import * from pyspark.sql import R...
Spark SQL Row_number() PartitionBy Sort Desc
I've successfully create a row_number() partitionBy by in Spark using Window, but would like to sort this by descending, instead of the default ascending. Here is my working code: from pyspark import HiveContext from pyspark.sql.types import * from pyspark.sql import Row, functions as F from pyspark.sql.window import ...
[ "desc should be applied on a column not a window definition. You can use either a method on a column:\nfrom pyspark.sql.functions import col, row_number\nfrom pyspark.sql.window import Window\n\nF.row_number().over(\n Window.partitionBy(\"driver\").orderBy(col(\"unit_count\").desc())\n)\n\nor a standalone functi...
[ 115, 3, 1, 0, 0, 0 ]
[]
[]
[ "apache_spark", "apache_spark_sql", "pyspark", "python", "window_functions" ]
stackoverflow_0035247168_apache_spark_apache_spark_sql_pyspark_python_window_functions.txt
Q: stuck in creating python quizz hi My code as shown below, when i am trying to execute this code the result always gives me the else clause output, not able to understand where part of code is not working can you help me with it. Even if i type the correct answer still the out put is of else clause quizz = { 'Q...
stuck in creating python quizz
hi My code as shown below, when i am trying to execute this code the result always gives me the else clause output, not able to understand where part of code is not working can you help me with it. Even if i type the correct answer still the out put is of else clause quizz = { 'Question1':{ 'question':'what is ...
[ "input() returns the result without the trailing '\\n'. Just remove it from the answers in quizz, and it will work.\n", "quizz = {\n 'Question1':{\n 'question':'what is the capital of India ',\n 'answer':'Delhi\\n'\n },\n 'Question2':{\n 'question':'what is the capital of germany ',\n 'answer...
[ 2, 0, 0 ]
[ "You Have To Remove \\n At Answer\nSo The Code Will Be:\nquizz = {\n 'Question1':{\n 'question':'what is the capital of India ',\n 'answer':'Delhi'\n },\n 'Question2':{\n 'question':'whenter code hereat is the capital of germany ',\n 'answer':'Berlin'\n }\n}\nscore = 0\nfor key,value in quiz...
[ -1 ]
[ "python" ]
stackoverflow_0074431211_python.txt
Q: Github Actions to Google Cloud Functions "Constraint constraints/gcp.resourceLocations violated for projects/GOOGLE_PROJECT_ID attempting GenerateU I am trying to build a Python application that is stored in Github that I want to run on Google Cloud Functions. I have followed this tutorial: https://blog.leandrotol...
Github Actions to Google Cloud Functions "Constraint constraints/gcp.resourceLocations violated for projects/GOOGLE_PROJECT_ID attempting GenerateU
I am trying to build a Python application that is stored in Github that I want to run on Google Cloud Functions. I have followed this tutorial: https://blog.leandrotoledo.org/deploying-google-cloud-functions-using-github-actions-and-workload-identity-authentication/ .github/workflows/main.yaml looks like this (with wor...
[ "There can be multiple Scenarios which could lead to the error you are facing.\nCould you please verify if your service account has enough permissions like iam.serviceAccountUser and iam.cloudFunctionsDeveloper role on project? You can check the details in document.\nHave you checked the Stackoverflow linked in t...
[ 0 ]
[]
[]
[ "google_cloud_functions", "python" ]
stackoverflow_0074402940_google_cloud_functions_python.txt
Q: Display Keyboard integration for a project I have built on a Tkinter based GUI, I would like to run it on a touch display. Does anyone know a way or a way to have an on-screen keyboard, that is installed on a Raspberry Pi, that open up when an input field is clicked in the gui ? I would be very grateful for any in...
Display Keyboard integration
for a project I have built on a Tkinter based GUI, I would like to run it on a touch display. Does anyone know a way or a way to have an on-screen keyboard, that is installed on a Raspberry Pi, that open up when an input field is clicked in the gui ? I would be very grateful for any input
[ "You might have to do some correction regarding the spacing in the code\nbecause StackOverFlow, doesn't support pasting the code \"Wide\".\nHere is total code for on-screen Keyboard using tkinter model in python :-\nfrom tkinter import *\nimport ttkthemes as td\nfrom tkinter import ttk\n\n\ndef select(value):\n ...
[ 1 ]
[]
[]
[ "python", "raspberry_pi", "tkinter", "user_interface" ]
stackoverflow_0074429877_python_raspberry_pi_tkinter_user_interface.txt
Q: How to add boxes to a grid layout with PyQt5 I'm trying to make a grid layout where the top is message box and the bottom a horizontal box with 3 buttons. The code I'm using is this: import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * def on_button_clicked(b): print(...
How to add boxes to a grid layout with PyQt5
I'm trying to make a grid layout where the top is message box and the bottom a horizontal box with 3 buttons. The code I'm using is this: import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * def on_button_clicked(b): print(b.text(), "was pressed.") app = QApplication(sys...
[ "Change\nwindow.addWidget(bottom_box, 0, 1)\nto\nwindow.addLayout(bottom_box, 0, 1)\n" ]
[ 0 ]
[]
[]
[ "pyqt5", "python" ]
stackoverflow_0071644743_pyqt5_python.txt
Q: How do I separate 1 column "0.1.2 Contaminated land" to 2 columns "0.1.2" & Contaminated land" (Pandas) I have the following column in pandas Code 0.1.2 Contaminated land 1.1.1 Standard foundations (default) 1.1.2 Specialist foundations 8.1.2 Preparatory groundworks How do I separate it into the following be...
How do I separate 1 column "0.1.2 Contaminated land" to 2 columns "0.1.2" & Contaminated land" (Pandas)
I have the following column in pandas Code 0.1.2 Contaminated land 1.1.1 Standard foundations (default) 1.1.2 Specialist foundations 8.1.2 Preparatory groundworks How do I separate it into the following below? Column A Column B 0.1.2 Contaminated land 1.1.1 Standard foundations (default) 1...
[ "Use .str.split() with 1 as the split count and expand=True to expand into series, then assign back to your df.\nimport pandas as pd\n\ndf = pd.DataFrame({\"code\": [\n '0.1.2 Contaminated land',\n '1.1.1 Standard foundations (default)',\n '1.1.2 Specialist foundations',\n '8.1.2 Preparatory groundworks...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074431323_pandas_python.txt
Q: (Jax) Reshape pytree containing arrays of different shapes I have a pytree containing arrays that have different shapes, for example it contains: observations of shape (5, 3, 250, 23) dones of shape (5, 3, 250) I want to reshape my pytree so that the first two dimensions are merged, which would give something li...
(Jax) Reshape pytree containing arrays of different shapes
I have a pytree containing arrays that have different shapes, for example it contains: observations of shape (5, 3, 250, 23) dones of shape (5, 3, 250) I want to reshape my pytree so that the first two dimensions are merged, which would give something like (15, 250, ...) for every object in my pytree. I usually use t...
[ "Sorry for the post it was kind of trivial. I post the answer just in case:\njax.tree_map(lambda x: jnp.reshape(x, newshape=(15, *x.shape[2:])),my_pytree)\n\n" ]
[ 0 ]
[]
[]
[ "jax", "numpy", "python", "reshape", "treemap" ]
stackoverflow_0074431127_jax_numpy_python_reshape_treemap.txt
Q: Generate random inputs using a fuzzer Let me take a very small example of what I am looking for. def add_two_numbers(x, y): return x + y I want to input n number of times, the random values for x and y. Is there any python fuzzing library that I can use for generating such values (integers, strings, alphanumeric, ...
Generate random inputs using a fuzzer
Let me take a very small example of what I am looking for. def add_two_numbers(x, y): return x + y I want to input n number of times, the random values for x and y. Is there any python fuzzing library that I can use for generating such values (integers, strings, alphanumeric, etc.) If you guys can suggest a few python ...
[]
[]
[ "Random is a library with a bunch of useful features, here's some of the features.\nimport random\nnum = random.randint(1,100) # generates a random whole number between 1 and 100\nprint(num)\nnum = random.random() # generates a random float number less than 1\nprint(num)\nnum = random.uniform(1,100) #generates a ra...
[ -1 ]
[ "fuzzing", "python", "random_data" ]
stackoverflow_0074431049_fuzzing_python_random_data.txt
Q: Fastest way to join coulmn values in pandas dataframe? Problem: Given a large data set (3 million rows x 6 columns) what's the fastest way to join values of columns in a single pandas data frame, based on the rows where the mask is true? My current solution: import pandas as pd import numpy as np # Note: Real d...
Fastest way to join coulmn values in pandas dataframe?
Problem: Given a large data set (3 million rows x 6 columns) what's the fastest way to join values of columns in a single pandas data frame, based on the rows where the mask is true? My current solution: import pandas as pd import numpy as np # Note: Real data will be 3 millon rows X 6 columns, df = pd.DataFrame({'t...
[ "IMHO you can save a lot of time by using\ndf[['d0', 'd1', 'd2']].sum(axis=1)\n\ninstead of\ndf[['d0', 'd1', 'd2']].agg(''.join, axis=1)\n\nAnd I think instead of using np.where you could just do:\ndf.loc[mask, 'd0'] = df.loc[mask, ['d0', 'd1', 'd2']].sum(axis=1)\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "large_data", "optimization", "pandas", "python" ]
stackoverflow_0074427116_dataframe_large_data_optimization_pandas_python.txt
Q: How can I show payment update for a specific appointment? So I'm trying to make a section under each appointment details that shows their payment transactions of the appointment specifically. all my tries so far didn't work, i can only show all payment updates which is not the wanted result obviously. this is the ...
How can I show payment update for a specific appointment?
So I'm trying to make a section under each appointment details that shows their payment transactions of the appointment specifically. all my tries so far didn't work, i can only show all payment updates which is not the wanted result obviously. this is the code: views.py the view for updating payments def edit_payment(...
[ "You can try belew querysets, one of which @raphael already mentioned in above comment.\nPaymentUpDate.objects.filter(appointment=appointment)\n\nOr:\nPaymentUpDate.objects.filter(appointment_id=id)\n\nBut I seriously think that ...filter(appointment=id) should also work can you please check whether the PaymentUpDa...
[ 3, 2 ]
[]
[]
[ "django", "django_models", "django_queryset", "django_views", "python" ]
stackoverflow_0074423690_django_django_models_django_queryset_django_views_python.txt
Q: Using pytest to reuse the same dataframe across modules in a class I am trying to reuse the same dataframe in pytest. I have initialised it in the init method but I would like to change it into a pytest fixture then pass it through to each of the methods. I am struggling to use pytest to apply this. import pytest ...
Using pytest to reuse the same dataframe across modules in a class
I am trying to reuse the same dataframe in pytest. I have initialised it in the init method but I would like to change it into a pytest fixture then pass it through to each of the methods. I am struggling to use pytest to apply this. import pytest import utils import numpy as np import pandas as pd from datetime import...
[ "You should define a new function with @pytest.fixture decorator.\nUsually fixtures are defined in file name conftest.py. However you are allowed to define it in test files as well.\nSo based on your example I believe you want to achieve something like this:\nclass TestGetDatesCorrespondingToReference:\n def tes...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "pytest", "python", "testing" ]
stackoverflow_0074425543_dataframe_pandas_pytest_python_testing.txt
Q: Keras symbolic inputs/outputs do not implement `__len__` error I want to make an AI playing my custom environment, unfortunately, when I run my code, following error accrues: File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.2\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_umd.py", line 198, i...
Keras symbolic inputs/outputs do not implement `__len__` error
I want to make an AI playing my custom environment, unfortunately, when I run my code, following error accrues: File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.2\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_umd.py", line 198, in runfile pydev_imports.execfile(filename, global_vars, local_va...
[ "As mentioned here, you need to install a newer version of keras-rl:\n!pip install keras-rl2\n\nYou also need to add an extra dimension to your input shape and a Flatten layer at the end, since Keras expects this when working with the DQN agent:\ndef build_model(states, actions):\n model = tf.keras.Sequential()\...
[ 7, 0 ]
[]
[]
[ "keras", "python", "python_3.x", "reinforcement_learning", "tensorflow" ]
stackoverflow_0071978756_keras_python_python_3.x_reinforcement_learning_tensorflow.txt
Q: How to Make Rendering Fail if Object has no Attribute? If an object obj has no attribute foo, then I would like referring to {{obj.foo}} in a Jinja2 template to fail when rendering. Currently I'm getting the template text with empty variables. How to get the standard AttributeError exception instead? Sample code l...
How to Make Rendering Fail if Object has no Attribute?
If an object obj has no attribute foo, then I would like referring to {{obj.foo}} in a Jinja2 template to fail when rendering. Currently I'm getting the template text with empty variables. How to get the standard AttributeError exception instead? Sample code looks like this: class Foo: pass env = Environment( ...
[ "Initialize your environment with StrictUndefined as the undefined class.\nenv = Environment(\n loader=PackageLoader(\"mydistro\"),\n autoescape=select_autoescape(),\n undefined=StrictUndefined,\n) \n\n" ]
[ 2 ]
[]
[]
[ "jinja2", "python" ]
stackoverflow_0074431481_jinja2_python.txt
Q: Streamlit AgGrid, output table does not update values after being changed I am building a table that updates the values of an output DF into a csv file (or whatever output defined). I defined a generate_agrid(df) function that outputs a class that contains a data method that is a pd.DataFrame. When I run the code ...
Streamlit AgGrid, output table does not update values after being changed
I am building a table that updates the values of an output DF into a csv file (or whatever output defined). I defined a generate_agrid(df) function that outputs a class that contains a data method that is a pd.DataFrame. When I run the code grid_table = generate_agrid(df), the grid_table generated contains the original...
[ "Found the issue, it was just a small parameter that was activated.\nWhile instantiating the AgGrid, I had to eliminate the reload_data=True parameter. Doing that, everything worked as expected and the data could be successfully updated after manually inputting and pressing \"update\"\nThis is how AgGrid must be in...
[ 0 ]
[]
[]
[ "ag_grid", "pandas", "python", "streamlit" ]
stackoverflow_0074413233_ag_grid_pandas_python_streamlit.txt
Q: How to remove special characters from txt files using Python from glob import glob pattern = "D:\\report\\shakeall\\*.txt" filelist = glob(pattern) def countwords(fp): with open(fp) as fh: return len(fh.read().split()) print "There are" ,sum(map(countwords, filelist)), "words in the files. " "From dire...
How to remove special characters from txt files using Python
from glob import glob pattern = "D:\\report\\shakeall\\*.txt" filelist = glob(pattern) def countwords(fp): with open(fp) as fh: return len(fh.read().split()) print "There are" ,sum(map(countwords, filelist)), "words in the files. " "From directory",pattern import os uniquewords = set([]) for root, dirs, fil...
[ "import re\nstring = open('a.txt').read()\nnew_str = re.sub('[^a-zA-Z0-9\\n\\.]', ' ', string)\nopen('b.txt', 'w').write(new_str)\n\nIt will change every non alphanumeric char to white space.\n", "I'm pretty new and I doubt this is very elegant at all, but one option would be to take your string(s) after reading ...
[ 9, 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0011902022_python.txt
Q: Execution of function on first time open only Context:- I will convert my code to exe that's why the code won't be readable. I am trying to prevent copying of my paid software. in which I am using machine GUID as a Licence Question: How to run a function only on a first-time startup? Here I have written the part o...
Execution of function on first time open only
Context:- I will convert my code to exe that's why the code won't be readable. I am trying to prevent copying of my paid software. in which I am using machine GUID as a Licence Question: How to run a function only on a first-time startup? Here I have written the part of the code - result = _winreg.QueryValueEx(key...
[ "Context:- I will convert my code to exe that's why the code won't be readable. I am trying to prevent copying of my paid software. in which I am using machine GUID as a Licence.\nresult = _winreg.QueryValueEx(key, \"MachineGuid\")\nID = str(result)\n\nlicence_path = 'C:\\\\Program Files\\\\Common Files\\\\System\\...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074415583_python.txt
Q: Documenting UTF-8 Python code with Doxygen The following code is not parsed correctly by doxygen, the "Module Docstring" is not shown in the resulting documentation: # -*- coding: utf-8 -*- """ Module Docstring """ If I delete the first line, it's parsed correctly. But I NEED to set up the encoding, as I use non-...
Documenting UTF-8 Python code with Doxygen
The following code is not parsed correctly by doxygen, the "Module Docstring" is not shown in the resulting documentation: # -*- coding: utf-8 -*- """ Module Docstring """ If I delete the first line, it's parsed correctly. But I NEED to set up the encoding, as I use non-ASCII characters on my code. Did anyone have the...
[ "You can specify the input encoding configuration variable:\nhttp://www.doxygen.nl/manual/config.html#cfg_input_encoding\nThe variable should be set to UTF-8 (all caps, hyphen required, no spaces) as specified at http://www.gnu.org/software/libiconv/\nHope this helps. Happy documenting :-)\n", "Looking at this l...
[ 1, 0, 0 ]
[]
[]
[ "doxygen", "python", "utf_8" ]
stackoverflow_0015747065_doxygen_python_utf_8.txt
Q: How to determine the indexes of characters in a string from the user? The user enters, for example, "Hello". How to make the "print" output the indexes of all the letters l if "l" in user_sms: print() A: Check if this solves your problem for i in range(len(user_sms)): if user_sms[i]=='l': print(i)...
How to determine the indexes of characters in a string from the user?
The user enters, for example, "Hello". How to make the "print" output the indexes of all the letters l if "l" in user_sms: print()
[ "Check if this solves your problem\nfor i in range(len(user_sms)):\n if user_sms[i]=='l':\n print(i)\n\n", "Loop over the characters in the string using the enumerate function, the enumerate function returns an iterable (index, item).\nExample:\nuser_sms = \"Hello\"\nenumerate(user_sms) -> (0, \"H\"), (1...
[ 1, 1 ]
[]
[]
[ "indexing", "python" ]
stackoverflow_0074431432_indexing_python.txt
Q: Execute based on values of different data types in different columns of a data frame | Pandas I am trying to loop through all items in a column. If it meets the condition in the column then check to see, If another condition is met in a different column. The data types in the two columns are different, one is an i...
Execute based on values of different data types in different columns of a data frame | Pandas
I am trying to loop through all items in a column. If it meets the condition in the column then check to see, If another condition is met in a different column. The data types in the two columns are different, one is an integer & the other a string that I am checking for. I am not sure where I have gone wrong & all inf...
[ "Create mask wich chain both masks toghether by & bot bitwise AND and for count use Series.value_counts, last select True and False values:\nm = (df['login'] > 10) & df['operatingsystem'].str.contains(\"server\", case=False, na=False)\nprint (m.value_counts())\nFalse 3\nTrue 2\ndtype: int64\n\n\nout = m.valu...
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074431604_dataframe_pandas_python.txt
Q: Generating Random (Seed) Numbers in Python How can I generate a random number using Uniform distributed random number range between (Length of the string and 2000000), integer only., by using all the time constant seed(2) in random generation to get the same results in each run? x = random.uniform(len(String),200)...
Generating Random (Seed) Numbers in Python
How can I generate a random number using Uniform distributed random number range between (Length of the string and 2000000), integer only., by using all the time constant seed(2) in random generation to get the same results in each run? x = random.uniform(len(String),200) How can I use seed next?
[ "You can use a list comprehension for a more compact (and potentially faster) code:\nimport random\n\n# Fixed seed for repetitive results\nconst_seed = 200\n\n# Bounds of numbers\nn_min = 0\nn_max = 2\n\n# Final number of values \nn_numbers = 5\n\n# Seed and retrieve the values\nrandom.seed(const_seed)\n\nnumbers =...
[ 1, 0 ]
[]
[]
[ "algorithm", "list", "python", "random", "random_seed" ]
stackoverflow_0074431501_algorithm_list_python_random_random_seed.txt
Q: Why django admin is not reading the __str__ method? I'm trying to add a str method in my models.py file to my administrative page show me the objects I've register with their own name and not like a 'UserObject(1)' But when I add this method that's what is happening: AttributeError at /admin/crud_app/user/ 'User' ...
Why django admin is not reading the __str__ method?
I'm trying to add a str method in my models.py file to my administrative page show me the objects I've register with their own name and not like a 'UserObject(1)' But when I add this method that's what is happening: AttributeError at /admin/crud_app/user/ 'User' object has no attribute 'first_name' models.py -> from dj...
[ "You should define it in f-strings to take care of None values so that if it is None so it will not raise error.\nclass User(models.Model):\n \"\"\"\n A normal class that represents an User object, the attributes are those bellow:\n \"\"\"\n first_name = models.CharField(name=\"First Name\", max_length=...
[ 2, 0 ]
[]
[]
[ "django", "django_admin", "django_model_field", "django_models", "python" ]
stackoverflow_0074393962_django_django_admin_django_model_field_django_models_python.txt
Q: ANSI Color Escape Sequences Different Foreground and Background color with 256 colors I'm using the ANSI Escape Sequence codes to add color to terminal output in my program. I am mainly using this code, where COLOR can be any value between 0 and 255 to achieve great color variation. \033[38;5;COLOR;1m TEXT \u001b[...
ANSI Color Escape Sequences Different Foreground and Background color with 256 colors
I'm using the ANSI Escape Sequence codes to add color to terminal output in my program. I am mainly using this code, where COLOR can be any value between 0 and 255 to achieve great color variation. \033[38;5;COLOR;1m TEXT \u001b[0m The problem is that using the 256 color spectrum I am unable to have the "background" (...
[ "Managed to figure it out!\nI simply run the escape sequence twice before the text. Once for background color, once for foreground color.\n\\033[48;5;(ONE OF 256 COLORS)m\\033[38;5;(ONE OF 256 COLORS)m TEXTHERE \\033[0;0m\n\nThis allows me to use the whole 256-color spectrum in both BG and FG, no imports or addons ...
[ 0 ]
[]
[]
[ "ansi_escape", "colors", "python" ]
stackoverflow_0074388263_ansi_escape_colors_python.txt
Q: Python on Windows 10 - Find window name when mouse hovers Is there a way to get the name of the window that is under the mouse cursor (i.e. the window the mouse cursor is hovering)? The windows is not necessarily the active window. In my code, I have a function that runs every time the USER presses F2. I want this...
Python on Windows 10 - Find window name when mouse hovers
Is there a way to get the name of the window that is under the mouse cursor (i.e. the window the mouse cursor is hovering)? The windows is not necessarily the active window. In my code, I have a function that runs every time the USER presses F2. I want this function to run, only if the mouse hovers a chrome window. Any...
[ "using pynput and win32 api in python: (works fine for me!)\nfrom pynput import mouse\nfrom win32gui import GetWindowText, GetCursorPos, WindowFromPoint\n\ndef on_move(x, y):\n print(GetWindowText(WindowFromPoint(GetCursorPos()))) \n\n# Collect events until released\nwith mouse.Listener(on_move=on_move) as lis...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0062270854_python_python_3.x.txt
Q: Storing the previous value and reusing it in a loop I am implementing a code that after debugging for a month I found out the problem that could be translated in the present simpler case: for i in range(1,5): x=2 if i==1: y=2*x else: y=2*ypred ypred=y print(i) print(ypr...
Storing the previous value and reusing it in a loop
I am implementing a code that after debugging for a month I found out the problem that could be translated in the present simpler case: for i in range(1,5): x=2 if i==1: y=2*x else: y=2*ypred ypred=y print(i) print(ypred) print(y) I want to store only the previous...
[ "Moving prints in right places leads to this output:\nx = 2\nypred = 0\nfor i in range(1, 5):\n print(f\"{i=}\")\n print(f\"{ypred=}\")\n if i == 1:\n y = 2 * x\n else:\n y = 2 * ypred\n print(f\"{y=}\")\n ypred = y\n print(f\"===\")\n\nOutput:\ni=1\nypred=0\ny=4\n===\ni=2\nypred=...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074431568_python.txt
Q: Google Sheets API security If I set up a Google Sheets API instance and a Google Drive API instance and then connect to the Google Sheet using the credentials key from a python script (application) on my desktop. This script performs basic CRUD operations. My question: Is this connection secure? In other words doe...
Google Sheets API security
If I set up a Google Sheets API instance and a Google Drive API instance and then connect to the Google Sheet using the credentials key from a python script (application) on my desktop. This script performs basic CRUD operations. My question: Is this connection secure? In other words does the data travel over the Inter...
[ "The network calls are secure since they must be using https calls and thus are not transported in plane text. Post a link to the python script if you want someone to check here.\nYou do have to trust google with all your data.\n" ]
[ 0 ]
[]
[]
[ "google_drive_api", "google_sheets_api", "python", "security" ]
stackoverflow_0074383552_google_drive_api_google_sheets_api_python_security.txt
Q: ModuleNotFoundError on a file in a (working) package when trying to import a class on another folder Abridged: When importing a class (in the example below, c2) from another package (folder1), where the imported class (c2) imports a class (c1) from the same package (folder1), the program (file2) raises a ModuleNot...
ModuleNotFoundError on a file in a (working) package when trying to import a class on another folder
Abridged: When importing a class (in the example below, c2) from another package (folder1), where the imported class (c2) imports a class (c1) from the same package (folder1), the program (file2) raises a ModuleNotFoundError on the import of c1 on c2, even when the import already worked in the package. Extended: The ex...
[ "Add the same correct full path to file1.py in file2.py:\n from folder1.file1 import c1\n\nWhen file2.py trying to import file1.py, it trying to import from ('../') where no file1.py, only /folder1 and /folder2.\nAnd you can delete __init__.py if you are using python 3.3+.\n" ]
[ 2 ]
[]
[]
[ "python", "python_3.x", "python_import" ]
stackoverflow_0074430941_python_python_3.x_python_import.txt
Q: converting thread to multiprocess pool basically i have a thread code right now but i wish to try to convert to multiprocessing pool for testing the performance user_dict = { 'users': [ { 'username': 'test1', 'password': 'opop1', }...
converting thread to multiprocess pool
basically i have a thread code right now but i wish to try to convert to multiprocessing pool for testing the performance user_dict = { 'users': [ { 'username': 'test1', 'password': 'opop1', }, { 'use...
[ "You can create a Pool and feed it with your function and arguments in a list with starmap. With arguments reduced to usr/pwd:\nfrom multiprocessing import Pool\n\nuser_dict = {\n 'users': [\n {\n 'username': 'test1',\n 'password': 'opop1',\n ...
[ 0 ]
[]
[]
[ "multiprocessing", "multithreading", "python", "python_3.x" ]
stackoverflow_0074430232_multiprocessing_multithreading_python_python_3.x.txt
Q: how to Derivative and Integrals with steps in python? I have this piece of code to calculate the integral of the function given in the argument. I tried to search around the internet to find a solution, but i didn't find it. I want to see the step by step integral (and derivatives too) calculation. import sympy fr...
how to Derivative and Integrals with steps in python?
I have this piece of code to calculate the integral of the function given in the argument. I tried to search around the internet to find a solution, but i didn't find it. I want to see the step by step integral (and derivatives too) calculation. import sympy from sympy import sin, cos, tan, exp, log, integrate from sym...
[ "Use the integral_steps function:\nfrom sympy import log, Symbol\nfrom sympy.integrals.manualintegrate import integral_steps\n\nx = Symbol('x')\nsteps = integral_steps(log(x), x)\nprint(steps)\n\nNote that the steps are printed using the internal representation of the rules so you'll have to deduce yourself what ar...
[ 0 ]
[]
[]
[ "derivative", "integral", "math", "python" ]
stackoverflow_0074430387_derivative_integral_math_python.txt
Q: Problem subtracting datetimes python pandas I have the following code snippet: ls3['REP'] = pd.to_datetime(ls3['REP']).dt.to_period('M') ls3['month'] = pd.to_datetime(ls3['month']).dt.to_period('M') ls3['MonthsBetween'] = ls3['REP']-ls3['month'] So rep is a column of values like 2022-05 and month is a...
Problem subtracting datetimes python pandas
I have the following code snippet: ls3['REP'] = pd.to_datetime(ls3['REP']).dt.to_period('M') ls3['month'] = pd.to_datetime(ls3['month']).dt.to_period('M') ls3['MonthsBetween'] = ls3['REP']-ls3['month'] So rep is a column of values like 2022-05 and month is also in the format YYYY-MM. I want a column that g...
[ "IIUC, you don't have to overwrite your existing columns, perform the computation and assign directly:\nls3['MonthsBetween'] = (pd.to_datetime(ls3['REP']).dt.to_period('M')\n -pd.to_datetime(ls3['month']).dt.to_period('M')\n )\n\nIf you want integers:\nls3['MonthsBetw...
[ 1 ]
[]
[]
[ "dataframe", "datetime", "pandas", "python" ]
stackoverflow_0074431861_dataframe_datetime_pandas_python.txt
Q: How to run Python script with parameters and returned values in scripted Jenkins I'm very new to writing Jenkinsfile. I have 2 Python scripts which takes in an input and also returns value that I would like to execute in a Jenkins pipeline. How should I make the Python script calls in the Jenkinsfile? Here's the e...
How to run Python script with parameters and returned values in scripted Jenkins
I'm very new to writing Jenkinsfile. I have 2 Python scripts which takes in an input and also returns value that I would like to execute in a Jenkins pipeline. How should I make the Python script calls in the Jenkinsfile? Here's the expected flow of the Pipeline written in a scripted Jenkinsfile: node { stage('Code...
[ "Assuming you have Python installed in your Jenkins Agent, you can simply use the shell step to execute Python and use the returnStdout flag to capture the execution output.\n// Git committer email\nOUTPUT = sh (\n script: \"python3 some.py $SOME_ARG\",\n returnStdout: true\n).trim()\n\n" ]
[ 1 ]
[]
[]
[ "groovy", "jenkins", "jenkins_groovy", "jenkins_pipeline", "python" ]
stackoverflow_0074428561_groovy_jenkins_jenkins_groovy_jenkins_pipeline_python.txt
Q: Convert 5 minutes values to 15 minutes values I have the following data as Dataframe: As can be seen, the data is available in 5 minute steps. Now i want to convert the 5-min steps to 15-min steps. The columns "Verbrauch (kWh)" and "Leistung" should convert to the mean of the 15-min intervall. I am able to conver...
Convert 5 minutes values to 15 minutes values
I have the following data as Dataframe: As can be seen, the data is available in 5 minute steps. Now i want to convert the 5-min steps to 15-min steps. The columns "Verbrauch (kWh)" and "Leistung" should convert to the mean of the 15-min intervall. I am able to convert to hourly data with the following: df.groupby(df[...
[ "first replace \"_\" with nan:\nimport numpy as np\ndf = df.replace('_', np.nan)\n\nthen use resample and get means:\ndf['Zeitpunkt']=pd.to_datetime(df['Zeitpunkt'])\nfinal= df.set_index('Zeitpunkt').sort_index().resample('15Min').agg({'Verbrauch (kWh)':'mean','Leistung':'mean'})\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "python" ]
stackoverflow_0074429914_dataframe_python.txt
Q: Which is the single unicode value of control characters? Is there a way to access or find character controls in python, like these NUL, DEL, CR, LF, BEL which is its form as a single ASCII unicode character to use as a parameter in the ord() built-in method to get a numeric value. A: You can find their Unicode r...
Which is the single unicode value of control characters?
Is there a way to access or find character controls in python, like these NUL, DEL, CR, LF, BEL which is its form as a single ASCII unicode character to use as a parameter in the ord() built-in method to get a numeric value.
[ "You can find their Unicode representation on the ASCII page on Wikipedia.\n\n\n\n\nKey\nUnicode\nUnicode-Hex\n\n\n\n\nNUL\n␀\n\\u2400\n\n\nDEL\n␡\n\\u2421\n\n\nCR\n␍\n\\u240d\n\n\nLF\n␊\n\\u240a\n\n\nBEL\n␇\n\\u2407\n\n\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074431653_python.txt
Q: Maketrans use dict and remove list of word I passed a dictionary to maketrans to replace a symbol with multiple character (Is it possible replace one character by two using maketrans?), however i also want to pass string containing symbol to be removed by maketrans. However maketrans does not accept second argumen...
Maketrans use dict and remove list of word
I passed a dictionary to maketrans to replace a symbol with multiple character (Is it possible replace one character by two using maketrans?), however i also want to pass string containing symbol to be removed by maketrans. However maketrans does not accept second argument if the first argument was a dictionary and not...
[ "Per the documentation :\n\nThis static method returns a translation table usable for str.translate().\nIf there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or None. Character keys will then...
[ 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0074418192_python_string.txt
Q: Find all points in a radius of one point (Python) I have two datasets with a number of points. Both datasets have points with gps coordinates. the point are located in the same area. I have to find for one point out of dataset A, all points from dataset B, which are in a radius of point from dataset A. I can do it...
Find all points in a radius of one point (Python)
I have two datasets with a number of points. Both datasets have points with gps coordinates. the point are located in the same area. I have to find for one point out of dataset A, all points from dataset B, which are in a radius of point from dataset A. I can do it like an idiot and do it with to for loops, but it take...
[ "If you are currently using basic loops to perform your calculations, it is likely you can get much improved performance without changing your algorithm, just through restructuring how you are doing the calculations.\nI have run a series of benchmarks to illustrate how different approaches impact performance. For s...
[ 0 ]
[]
[]
[ "2d", "performance", "point", "python" ]
stackoverflow_0074417694_2d_performance_point_python.txt
Q: How to integrate an array of functions? I'm trying to integrate each element of an array to output an array of the same size. Below, X and Y are meshgrid arrays, and trying to integrate returns the error "only size-1 arrays can be converted to Python scalars." def integral_x(p_i, p_j): def integrand(s): ...
How to integrate an array of functions?
I'm trying to integrate each element of an array to output an array of the same size. Below, X and Y are meshgrid arrays, and trying to integrate returns the error "only size-1 arrays can be converted to Python scalars." def integral_x(p_i, p_j): def integrand(s): return ((2*(X - (p_j.xa - math.sin(p_j.beta...
[ "Just use integrate.quad_vec rather than integrate.quad. For example,\nfrom scipy.integrate import quad_vec\n\nN = 3 # Number of points in each direction\nx_start, x_end = -2.5, 2.5 # x-direction boundaries\ny_start, y_end = -3.0, 3.0 # y-direction boundaries\nx =...
[ 0 ]
[]
[]
[ "integral", "python", "vectorization" ]
stackoverflow_0074425242_integral_python_vectorization.txt
Q: ConvergenceWarning: Maximum Likelihood optimization failed to converge I am trying to use the ARIMA algorithm in statsmodels library to do forecasting on a time series dataset. It is a stock price dataset and when I feed normalized data to the model it gives the below error. Note: This is a uni-variate forecasting...
ConvergenceWarning: Maximum Likelihood optimization failed to converge
I am trying to use the ARIMA algorithm in statsmodels library to do forecasting on a time series dataset. It is a stock price dataset and when I feed normalized data to the model it gives the below error. Note: This is a uni-variate forecasting and I am trying to forecast the closing price. ConvergenceWarning: Maximum...
[ "I'm not sure whether the error is produced due to normalization or other reasons such as seasonality. In any case, the problem can be solved by increasing the maximum number of iterations used to estimate the model parameters. I.e.,\nmodel = ARIMA(time_series, order=(p, d, q))\nmodel_fit = model.fit(method_kwargs=...
[ 0 ]
[]
[]
[ "arima", "machine_learning", "python", "regression", "time_series" ]
stackoverflow_0052872724_arima_machine_learning_python_regression_time_series.txt
Q: Image clarity issue in HTML page I have Matplotlib & Seaborn visualizations that need to be saved in HTML. Since there is no direct method to do so, I first saved the images in PNG & then converted them to HTML. This decreased the quality of my images. My code: import aspose.words as aw from PIL import Image def...
Image clarity issue in HTML page
I have Matplotlib & Seaborn visualizations that need to be saved in HTML. Since there is no direct method to do so, I first saved the images in PNG & then converted them to HTML. This decreased the quality of my images. My code: import aspose.words as aw from PIL import Image def pairplot_fun(eda_file, pairplot_input...
[ "You can specify image resolution in Aspose.Words HtmlSaveOptions using HtmlSaveOptions.image_resolution property.\ndoc = aw.Document(\"in.docx\")\noptions = aw.saving.HtmlSaveOptions()\noptions.image_resolution = 1200\ndoc.save(\"out.html\", options)\n\n" ]
[ 0 ]
[]
[]
[ "aspose.words", "dpi", "html", "python", "visualization" ]
stackoverflow_0074429706_aspose.words_dpi_html_python_visualization.txt
Q: Remove characters from a string upon user input I am creating a hangman game and I am displaying the letters that have not yet been guessed so if no letters have been guessed it displays all the abc's. And what I am trying to figure out is how to get rid of the letter the user inputted from the letters remaining a...
Remove characters from a string upon user input
I am creating a hangman game and I am displaying the letters that have not yet been guessed so if no letters have been guessed it displays all the abc's. And what I am trying to figure out is how to get rid of the letter the user inputted from the letters remaining and return the string of the remaining letters. def ge...
[ "\n\n\nYou can just subtract letters_guessed from ALL_LETTERS, the available letters remains.\nThis function returns the subtracted letters by replacing letters_guessed in ALL_LETTERS to be empty. So what remains is the remaining available letters.\ndef get_available_letters(letters_guessed):\n ALL_LETTERS = 'abcd...
[ 1, 0, 0, 0 ]
[]
[]
[ "list", "loops", "python", "return", "string" ]
stackoverflow_0074431650_list_loops_python_return_string.txt
Q: django.db.utils.IntegrityError: NOT NULL constraint failed: xx_xx.author_id ** author error in python/django i'm trying to setup a databased website with Python and Django. I can not POST with my self created index-interface. It works with the django admin interface. Here's my code: views.py: from django.shortcuts...
django.db.utils.IntegrityError: NOT NULL constraint failed: xx_xx.author_id ** author error in python/django
i'm trying to setup a databased website with Python and Django. I can not POST with my self created index-interface. It works with the django admin interface. Here's my code: views.py: from django.shortcuts import render from .models import Item from django.db.models import Q from django.contrib.auth.decorators import ...
[ "Try this code snippet\nif request.method == 'POST':\n Item(\n name = request.POST['itemName'],\n beschreibung = request.POST['itemBeschreibung'],\n link = request.POST['itemTag'],\n public = request.POST['itemPublic'],\n useridnummer = request.POST['itemUserid'],\n author = request.user\n ).sav...
[ 0 ]
[]
[]
[ "django", "django_models", "django_templates", "python", "python_3.x" ]
stackoverflow_0074431654_django_django_models_django_templates_python_python_3.x.txt
Q: Search in set of sets I would like to search in a set of sets in a specific way: Example (Pseudocode): search = {{1}, {3}} search_base = {{1, 2}, {3, 4}} # search results in True because the 1 can be found in the first set and the 3 in the second. Order doesn't matter, but the number of subsets has to be identica...
Search in set of sets
I would like to search in a set of sets in a specific way: Example (Pseudocode): search = {{1}, {3}} search_base = {{1, 2}, {3, 4}} # search results in True because the 1 can be found in the first set and the 3 in the second. Order doesn't matter, but the number of subsets has to be identical, the search consists alwa...
[ "As you said the data type is not important, I will just use a list of numbers and a list of sets. You can nest all and any, with in to check set membership:\ndef search(nums, sets):\n return all(any(x in y for y in sets) for x in nums)\n\nprint(search([1, 3], [{1, 2}, {3, 4}])) # True\nprint(search([1, 2], [{1,...
[ 2, 0 ]
[]
[]
[ "frozenset", "python", "set" ]
stackoverflow_0074426012_frozenset_python_set.txt
Q: module object is not callable error with Flask and Apache on Windows I've recently set up apache server to serve my flask app on windows. Let me tell you about my setup. I've download apache through apache lounge. Have extracted it in C:\Apache24. I did install mod_wsgi in a virtual python 3.7.7 Copied mod_wsgi c...
module object is not callable error with Flask and Apache on Windows
I've recently set up apache server to serve my flask app on windows. Let me tell you about my setup. I've download apache through apache lounge. Have extracted it in C:\Apache24. I did install mod_wsgi in a virtual python 3.7.7 Copied mod_wsgi configuration in the httpd.conf file created my_app.conf in the conf direct...
[ "It's quite a very silly error. In my wsgi script I imported my main flask module as application object instead of the Flask object that's inside the module. So my flask app has a module app which contains the Flask object app. So instead of doing this\nfrom shotgrid_ami_handler import app as application\n\nI shoul...
[ 0 ]
[]
[]
[ "apache", "flask", "python", "python_3.x" ]
stackoverflow_0074403498_apache_flask_python_python_3.x.txt
Q: Tensorflow ReLU output activation returns NaN I have a yolo-like network architecture, where on the output layer I want to predict bounding boxes with coordinates such as x,y,width,height. When I use a linear activation function everything works fine, but my model sometimes predicts negative values which dont make...
Tensorflow ReLU output activation returns NaN
I have a yolo-like network architecture, where on the output layer I want to predict bounding boxes with coordinates such as x,y,width,height. When I use a linear activation function everything works fine, but my model sometimes predicts negative values which dont make sense in my case, as all values to predict are bet...
[ "It is hard to say without you giving more data to us. However, it seems to be a common problem in cases where the input data is not normalized correctly.\nHere are some links to maybe look into. If it does not help you will probably have to give more info for someone to give a usefull answer\nhttps://discuss.tenso...
[ 0 ]
[]
[]
[ "python", "regression", "tensorflow" ]
stackoverflow_0074431961_python_regression_tensorflow.txt
Q: List comprehension vs. lambda + filter I have a list that I want to filter by an attribute of the items. Which of the following is preferred (readability, performance, other reasons)? xs = [x for x in xs if x.attribute == value] xs = filter(lambda x: x.attribute == value, xs) A: It is strange how much beauty va...
List comprehension vs. lambda + filter
I have a list that I want to filter by an attribute of the items. Which of the following is preferred (readability, performance, other reasons)? xs = [x for x in xs if x.attribute == value] xs = filter(lambda x: x.attribute == value, xs)
[ "It is strange how much beauty varies for different people. I find the list comprehension much clearer than filter+lambda, but use whichever you find easier.\nThere are two things that may slow down your use of filter.\nThe first is the function call overhead: as soon as you use a Python function (whether created b...
[ 695, 281, 88, 35, 32, 17, 10, 9, 9, 7, 5, 4, 4, 2, 1, 1, 0 ]
[]
[]
[ "filter", "functional_programming", "lambda", "list", "python" ]
stackoverflow_0003013449_filter_functional_programming_lambda_list_python.txt
Q: Cannot install asammdf python package in docker I need to use asammdf as part of my app to concatenate multiple .MF4 files. If you know about other ways, I will gladly try other packages. Problem is that it runs on windows but once I try to build docker image (on linux) with asammdf (tried same version as I have o...
Cannot install asammdf python package in docker
I need to use asammdf as part of my app to concatenate multiple .MF4 files. If you know about other ways, I will gladly try other packages. Problem is that it runs on windows but once I try to build docker image (on linux) with asammdf (tried same version as I have on windows and even some other) in requirements, it fa...
[ "In error messages, it is says \"error: command 'gcc' failed: No such file or directory\".\nSo, you may need to install gcc to your container.\nTry to add this line, before pip install.\nRUN apt-get install build-essential\n", "Make sure you have numpy installed before trying to install asammdf\n" ]
[ 2, 0 ]
[]
[]
[ "asammdf", "docker", "python" ]
stackoverflow_0074406375_asammdf_docker_python.txt
Q: rename a column in dataframe I have a DF df = spark.sql("""select number,name,owner,support,user,business_unit from table""") I want to rename owner.display_value as owner_display_value and support.display_value as support_display_value owner column and support column is a struct, hence i'm obtaining only the dis...
rename a column in dataframe
I have a DF df = spark.sql("""select number,name,owner,support,user,business_unit from table""") I want to rename owner.display_value as owner_display_value and support.display_value as support_display_value owner column and support column is a struct, hence i'm obtaining only the display_value from the column. df2 = ...
[ "replace\ndf2 = df.select(\n \"number\",\n \"name\",\n \"owner.display_value\" as owner_display_value,\n \"support.display_value\" as support_display_value, \n \"user_group\",\n \"business_unit\"\n)\n\nwith\ndf2 = df.selectExpr(\n \"number\",\n \"name\",\n \"owner.display_value as owner_d...
[ 1, 0 ]
[]
[]
[ "pyspark", "python" ]
stackoverflow_0074430404_pyspark_python.txt
Q: Maya python get top most parent transforms I have a selection of transforms in maya and I want to get the top parent transforms of all hierarchies within the selection. Is this the best way to achieve that? import maya.cmds as cmds def getTopParents(transforms): ''' Returns a list of the top most parents f...
Maya python get top most parent transforms
I have a selection of transforms in maya and I want to get the top parent transforms of all hierarchies within the selection. Is this the best way to achieve that? import maya.cmds as cmds def getTopParents(transforms): ''' Returns a list of the top most parents for the given transforms ''' parents = []...
[ "How about something like this? Modify as needed to store the parents instead of just printing them.\nimport maya.cmds as cmds\n\ntargets = ['pCylinder1', 'group4', 'group10']\n\nprint('Full hierarchy: {}'.format(cmds.ls(targets[0], long=True)[0]))\n\nfor target in targets:\n parent = None\n stop = False\n ...
[ 2, 1 ]
[]
[]
[ "maya", "python" ]
stackoverflow_0067389885_maya_python.txt
Q: merge pandas dataframe with itself to add new rows (like a cross join) I would like to join my dataframe with itself in a way that it has the same amount of rows for a particular column. It sounds a bit complicated but I believe it is not when you see it. So here is an example: year brand series model version val...
merge pandas dataframe with itself to add new rows (like a cross join)
I would like to join my dataframe with itself in a way that it has the same amount of rows for a particular column. It sounds a bit complicated but I believe it is not when you see it. So here is an example: year brand series model version value value 2 2022 bmw A 1X plan 3 1 2022 bmw B 2X plan 8 1 2022 bmw...
[ "One option is with complete from pyjanitor, to expose the missing rows:\n# pip install pyjanitor\nimport pandas as pd\nimport janitor\n\ndf.complete('version', 'model') \n model version value\n0 1X plan 3.0\n1 2X plan 8.0\n2 3X plan NaN\n3 4X plan NaN\...
[ 3, 1 ]
[]
[]
[ "dataframe", "join", "merge", "pandas", "python" ]
stackoverflow_0074431901_dataframe_join_merge_pandas_python.txt