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: Convert list of elements into list of tuples to match the structure of another list of tuples Say that I have the following lists L = [("a0","a1"),("b0",),("b1","a1","b0"),("a0","a1"),("b0",)] M = ["u0", "u1", "u2", "u3", "u4", "u5", "u6", "u7" , "u8"] and I want to group the elements of M into a list of tuples N...
Convert list of elements into list of tuples to match the structure of another list of tuples
Say that I have the following lists L = [("a0","a1"),("b0",),("b1","a1","b0"),("a0","a1"),("b0",)] M = ["u0", "u1", "u2", "u3", "u4", "u5", "u6", "u7" , "u8"] and I want to group the elements of M into a list of tuples N such that N has the same structure of L, i.e. N = [("u0", "u1"), ("u2",), ("u3", "u4", "u5"), ("u6...
[ "it = iter(M)\n\nfollowed by\nres = [tuple(itertools.islice(it, len(t))) for t in L]\n\nshould do the trick\n", "using for loop\n>>> L = [(\"a0\",\"a1\"),(\"b0\",),(\"b1\",\"a1\",\"b0\"),(\"a0\",\"a1\"),(\"b0\",)]\n>>> M = [\"u0\", \"u1\", \"u2\", \"u3\", \"u4\", \"u5\", \"u6\", \"u7\" , \"u8\"]\n>>> R =[]\n>>> i...
[ 8, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074487572_python.txt
Q: comparing keys:- list of nested dictionary I want to write a function that checks keys of dict1 (base dict) and compare it to keys of dict2 (list of nested dictionaries, can be one or multiple), such that it checks for the mandatory key and then optional keys(if and whatever are present) and returns the difference...
comparing keys:- list of nested dictionary
I want to write a function that checks keys of dict1 (base dict) and compare it to keys of dict2 (list of nested dictionaries, can be one or multiple), such that it checks for the mandatory key and then optional keys(if and whatever are present) and returns the difference as a list. dict1 = {"name": str, ...
[ "Try out this recursive check function:\ndef compare_dict_keys(d1, d2, diff: list):\n if isinstance(d2, dict):\n for key, expected_value in d2.items():\n try:\n actual_value = d1[key]\n compare_dict_keys(actual_value, expected_value, diff)\n except KeyEr...
[ 0 ]
[]
[]
[ "comparison", "dictionary", "list", "nested", "python" ]
stackoverflow_0074488014_comparison_dictionary_list_nested_python.txt
Q: Scikit-Learn Linear Regression using Datetime Values and forecasting Below is a sample of the dataset. row_id datetime energy 1 2008-03-01 00:00:00 1259.985563 2 2008-03-01 01:00:00 1095.541500 3 2008-03-01 02:00:00 1056.247500 4 2008-03-01 03:00:00 1034.742000 5 2008-03-01 04:00:00 1026.334500 The dataset ...
Scikit-Learn Linear Regression using Datetime Values and forecasting
Below is a sample of the dataset. row_id datetime energy 1 2008-03-01 00:00:00 1259.985563 2 2008-03-01 01:00:00 1095.541500 3 2008-03-01 02:00:00 1056.247500 4 2008-03-01 03:00:00 1034.742000 5 2008-03-01 04:00:00 1026.334500 The dataset has datetime values and energy consumption for that hour in o...
[ "You can not train on a datetime format. If you want the model to learn datetime features then consider splitting it into day, month, weekday, weekofyear, hour etc to learn patterns with seasonality:\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklea...
[ 1 ]
[]
[]
[ "datetime", "forecasting", "pandas", "python", "scikit_learn" ]
stackoverflow_0074485762_datetime_forecasting_pandas_python_scikit_learn.txt
Q: Pandas .min() not getting lowest value per week I have a dateframe with, for every hour for each day, the amount of gas and electricity used: elec gas day_of_week DuringBusinessHours ts 2022-04-30 01:00:00+02:00 3.6000000834465027 0.0 5 False 2022-04-30 02:00:00+02...
Pandas .min() not getting lowest value per week
I have a dateframe with, for every hour for each day, the amount of gas and electricity used: elec gas day_of_week DuringBusinessHours ts 2022-04-30 01:00:00+02:00 3.6000000834465027 0.0 5 False 2022-04-30 02:00:00+02:00 3.6000000834465027 0.0 5 False 2022-04-30 03...
[ "Try:\nlowestUsage = BusinessUsageDf.groupby(pd.Grouper(key='ts', freq='W-SAT'))['elec'].min()\nlowestUsage.head(5)\n\n" ]
[ 0 ]
[]
[]
[ "datetime", "min", "pandas", "python" ]
stackoverflow_0074487811_datetime_min_pandas_python.txt
Q: How to group at the for loop through the second condition unfortunately I'm having trouble creating a correct display of mianowiecie values. I have such a DF: Group Match Team A 1 A1 A 1 A2 A 2 A3 A 2 A4 I have this code: for group in set(world_cup['Group']): print('___Starting group {}:___'.format(group...
How to group at the for loop through the second condition
unfortunately I'm having trouble creating a correct display of mianowiecie values. I have such a DF: Group Match Team A 1 A1 A 1 A2 A 2 A3 A 2 A4 I have this code: for group in set(world_cup['Group']): print('___Starting group {}:___'.format(group)) for home, away in combinations(world_cup.que...
[ "I hope I've understood you correctly. You can .groupby() and then .agg the values:\nout = df.groupby([\"Group\", \"Match\"]).agg(\"-\".join)\nprint(out)\n\nPrints:\n Team\nGroup Match \nA 1 A1-A2\n 2 A3-A4\n\n\nout = df.groupby([\"Group\", \"Match\"]).agg(\"-\".join)\n\ntmp = ...
[ 0 ]
[]
[]
[ "for_loop", "group", "python", "python_3.x" ]
stackoverflow_0074488178_for_loop_group_python_python_3.x.txt
Q: Check a number if prime using python I want to create a procedure show if a given number prime what i have tried so far : def premier(a): isPrimary=False for i in range(2,a//2): if(a%i==0): isPrimary=True break if(isPrimary==True): print(a,'est un nbre premier') ...
Check a number if prime using python
I want to create a procedure show if a given number prime what i have tried so far : def premier(a): isPrimary=False for i in range(2,a//2): if(a%i==0): isPrimary=True break if(isPrimary==True): print(a,'est un nbre premier') else: print(a,'non premier') c...
[ "i think you're talking about prime numbers right ? - so numbers only divisable by themselfs and 1. In that case you could use:\ndef is_prime(n):\n for i in range(2,n):\n if (n % i) == 0:\n return False\n return True\n\n" ]
[ 0 ]
[ "Vous vous trompez d'état. Ce sera a%i != 0 s'il n'est pas égal à zéro alors premier si zéro alors pas premier. Ou vous pouvez définir isPrimary= False dans la condition que vous avez donnée. J'espère que cela fonctionnera.\nIn english:\nYou make a mistake in in condition. It will be a%i != 0 if it not equal zero t...
[ -1 ]
[ "algorithm", "procedure", "python" ]
stackoverflow_0074487534_algorithm_procedure_python.txt
Q: Python coding error as it canot defined after i make def i did imported self but it show NameError: name 'self' is not defined #implementation class KMeans: def __init__(self, n_cluster=8, max_iter=300): self.n_cluster = n_cluster self.max_iter = max_iter # Randomly select centroid st...
Python coding error as it canot defined after i make def
i did imported self but it show NameError: name 'self' is not defined #implementation class KMeans: def __init__(self, n_cluster=8, max_iter=300): self.n_cluster = n_cluster self.max_iter = max_iter # Randomly select centroid start points, uniformly distributed across the domain of the dat...
[ "You should learn more about OOP in Python (here for example)\nself is a reference to the current instance of the class. So it can be used only inside of instance method.\nYou are trying to reach reference of an object without object itself.\nYou should define your function as a method of your class and then initia...
[ 2 ]
[]
[]
[ "nameerror", "python" ]
stackoverflow_0074488272_nameerror_python.txt
Q: SNS mocking with moto is not working correctly In my unit test: def test_my_function_that_publishes_to_sns(): conn = boto3.client("sns", region_name="us-east-1") mock_topic = conn.create_topic(Name="mock-topic") topic_arn = mock_topic.get("TopicArn") os.environ["SNS_TOPIC"] = topic_arn # call...
SNS mocking with moto is not working correctly
In my unit test: def test_my_function_that_publishes_to_sns(): conn = boto3.client("sns", region_name="us-east-1") mock_topic = conn.create_topic(Name="mock-topic") topic_arn = mock_topic.get("TopicArn") os.environ["SNS_TOPIC"] = topic_arn # call my_function my_module.my_method() The the func...
[ "issue was my_module.my_method() wasn't setting a region just doing client = boto3.client(\"sns\")\nIt could not find it because it was defaulting to a diff region than us-east-1 which was hard coded into the unit test\n", "maybe it will help you \nkeep all modules in a single class and put a decorator @mock_sns ...
[ 3, 3, 0 ]
[]
[]
[ "amazon_web_services", "boto", "moto", "python", "unit_testing" ]
stackoverflow_0062015260_amazon_web_services_boto_moto_python_unit_testing.txt
Q: Sort label of a pie chart in a specific way I want to make a pie chart plot to display a survey result. I'll try to keep it very simple. On a question of my survey, there were several response type string, like this example : Question : "do you practice magic" Possibles responses : "yes", "not sure", "not intentio...
Sort label of a pie chart in a specific way
I want to make a pie chart plot to display a survey result. I'll try to keep it very simple. On a question of my survey, there were several response type string, like this example : Question : "do you practice magic" Possibles responses : "yes", "not sure", "not intentionnally", "no" Then I make a pie chart with the pr...
[ "Oh dear, I just find it !\njust create a list of your specific order :\nreorderindex = ['no', 'not sure', 'not intentionally', 'yes'.]\n# the old one tocompare : ['no', 'not intentionally', 'not sure', 'yes']\n\nand reindex with it :\ndf2 = df2.reindex(reorderindex)\n\nYolo !\n" ]
[ 0 ]
[]
[]
[ "dataframe", "indexing", "pie_chart", "python", "survey" ]
stackoverflow_0074487974_dataframe_indexing_pie_chart_python_survey.txt
Q: How can the code being allowed to continue from one question to another question even though the input answer had wrong for 3 attempts? import time import random #declare variables and constant guessingelement = ["Hydrogen", "Magnesium", "Cobalt", "Mercury", "Aluminium", "Uranium", "Antimony"] nicephrases = ["Nice...
How can the code being allowed to continue from one question to another question even though the input answer had wrong for 3 attempts?
import time import random #declare variables and constant guessingelement = ["Hydrogen", "Magnesium", "Cobalt", "Mercury", "Aluminium", "Uranium", "Antimony"] nicephrases = ["Nice job", "Marvellous", "Wonderful", "Bingo", "Dynamite"] guess = "" guess_count = 0 guess_limit = 3 out_of_guesses = False guess_no = 0 score...
[ "I hope this helps. I wrote this code for myself in a new way. I have used recursion to keep the guess happening and simple used a while loop that will break when max attempts go beyond 3.\nimport random\n\nelements = [\"hydrogen\", \"magnesium\", \"cobalt\", \"mercury\", \"aluminium\", \"uranium\", \"antimony\"]\n...
[ 0 ]
[]
[]
[ "python", "while_loop" ]
stackoverflow_0074487482_python_while_loop.txt
Q: How can I visualize a dataset containing 5 independent and 1 dependent variable? I have a DataFrame containing 576 rows with these variables, where the first 5 is the independent variable and the last is the dependent one. The line below shows the range of the variables. I am looking for an effective way to visual...
How can I visualize a dataset containing 5 independent and 1 dependent variable?
I have a DataFrame containing 576 rows with these variables, where the first 5 is the independent variable and the last is the dependent one. The line below shows the range of the variables. I am looking for an effective way to visualize the dataset. I want to show the optimum fitness value for the 5 variables. The ran...
[ "I can recommend parallel coordinates, plotly has a good implementation here.\nhttps://plotly.com/python/parallel-coordinates-plot/\n\n" ]
[ 0 ]
[]
[]
[ "python", "visualization" ]
stackoverflow_0074487582_python_visualization.txt
Q: How can I break out of telegram bot loop application.run_polling()? def bot_start(): application = ApplicationBuilder().token("api_key").build() async def stop(update, context): await context.bot.send_message(chat_id=update.message.chat_id, text='Terminating Bot...') await application.stop...
How can I break out of telegram bot loop application.run_polling()?
def bot_start(): application = ApplicationBuilder().token("api_key").build() async def stop(update, context): await context.bot.send_message(chat_id=update.message.chat_id, text='Terminating Bot...') await application.stop() await Updater.shutdown(application.bot) await applica...
[ "Application.run_polling is a convenience methods that starts everything and keeps the bot running until you signal the process to shut down. It's mainly intended to be used if the Application is the only long-running thing in your python process. If you want to run other things alongside your bot, you can instead ...
[ 1 ]
[]
[]
[ "python", "python_telegram_bot", "telegram" ]
stackoverflow_0074484933_python_python_telegram_bot_telegram.txt
Q: Why am I getting this matplotlib error for plotting a categorical variable? I feel stupid but I cannot seem to fix this error or find any solution online. Why do I keep getting the following error no matter how I try to plot it using matplotlib? For instance even the following code gives me the same error - names ...
Why am I getting this matplotlib error for plotting a categorical variable?
I feel stupid but I cannot seem to fix this error or find any solution online. Why do I keep getting the following error no matter how I try to plot it using matplotlib? For instance even the following code gives me the same error - names = list(fig1['day']) values = list(fig1['count']) fig, axs = plt.subplots(figsize=...
[ "Actually the right solution is this, because is more generic, applies not only to calendar objects:\nfig, ax = plt.subplots()\n\nnames = ['Monday', 'Tuesday', 'Wednesday']\n# you may try with: \n# names = ['1111', '2222', '3333']\n\n# This variable is a range (numerical values) and we pass it for number of ticks o...
[ 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0065526338_matplotlib_python.txt
Q: How to index specific elements of a linear model summary output - pandas I have the following linear model output. I want to index a particular value, printing only the R-squared value (0.028) but am not sure how to do this. Would be so grateful for a helping hand! resultmodeldistancevariation2sleepsummary OLS Re...
How to index specific elements of a linear model summary output - pandas
I have the following linear model output. I want to index a particular value, printing only the R-squared value (0.028) but am not sure how to do this. Would be so grateful for a helping hand! resultmodeldistancevariation2sleepsummary OLS Regression Results Dep. Variable: distance R-squared: 0.028 Model: OLS Adj...
[ "I have solved the issue by adding the following code:\nnewerresults = resultmodeldistancevariation2sleepsummary.tables[0]\nnewerdata = pd.DataFrame(newerresults)\nprint(newerdata.iloc[0,3])\n\nConvert to table - then to dataframe - then index\n:)\n" ]
[ 0 ]
[]
[]
[ "jupyter_notebook", "pandas", "python", "regression", "statistics" ]
stackoverflow_0074488168_jupyter_notebook_pandas_python_regression_statistics.txt
Q: How to change Azure App Service Python version from 3.9.7 to 3.9.12? I am trying to deploy an application on Azure App Service. I have created a deployment with Python 3.9.7, but my app needs Python 3.9.12. How do I upgrade python's version? In Azure App Service > Configuration > General Settings > Python minor ve...
How to change Azure App Service Python version from 3.9.7 to 3.9.12?
I am trying to deploy an application on Azure App Service. I have created a deployment with Python 3.9.7, but my app needs Python 3.9.12. How do I upgrade python's version? In Azure App Service > Configuration > General Settings > Python minor version, there is no 3.9.12 available. So I have to upgrade it by SSH. But, ...
[ "\nCreated the Python Web App from the Azure Portal with the version 3.9 and shown as 3.9.7 in the SSH Console.\nIn the Configuration, it shown me only these versions in minor and major dropdown lists:\n\nUsing this Azure CLI cmdlet az webapp config set ..., I have set the Python version from 3.9.7 to 3.9.12 but no...
[ 1, 0 ]
[]
[]
[ "azure", "azure_web_app_service", "bash", "linux", "python" ]
stackoverflow_0074478132_azure_azure_web_app_service_bash_linux_python.txt
Q: Python SDK Azure Computer Vision: 'bytes' object has no attribute 'read' I am currently developing simple demo how to capture some text over the object such as license plate, Bus number, etc using combination Azure custom vision and Azure OCR. I have issue when sending image to Azure OCR like below: 'bytes' object...
Python SDK Azure Computer Vision: 'bytes' object has no attribute 'read'
I am currently developing simple demo how to capture some text over the object such as license plate, Bus number, etc using combination Azure custom vision and Azure OCR. I have issue when sending image to Azure OCR like below: 'bytes' object has no attribute 'read' Simply by capturing frame from camera and send it to ...
[ "Computer vision libraries cannot be accessible from the root environment and we need to get the libraries to access inside the virtual environment. With respect to CV2, upgrade the version of computer vision which solves the issue. The read operation needs to have some upgrade in the form of computer vision librar...
[ 0 ]
[]
[]
[ "azure", "azure_cognitive_services", "camera", "python", "real_time" ]
stackoverflow_0074474621_azure_azure_cognitive_services_camera_python_real_time.txt
Q: BadRequestKeyError(key) werkzeug.exceptions. 400 The browser (or proxy) sent a request that this server could not understand. KeyError: 'name' I've a problem with sending from a html form to a python flask application. First the html code: <form id="signup-form" class="bg-white rounded" ...
BadRequestKeyError(key) werkzeug.exceptions. 400 The browser (or proxy) sent a request that this server could not understand. KeyError: 'name'
I've a problem with sending from a html form to a python flask application. First the html code: <form id="signup-form" class="bg-white rounded" autocomplete="no" id="signup-form" action="/signup" method="post"> <h2 class="mt-0 mb-0 text-center">Sign Up For</h2> ...
[ "!!!!Solved!!!!\nThe overgiven post message is a json-string. So I have handle it like this.\ndef signup(self, request):\n # Get data from AJAX request\n data = request.get_json(force=True)\n \n email = data['email']\n password = data['password']\n name = data['name']\n\n message, status_code =...
[ 0 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074476933_flask_python.txt
Q: Python Apache Beam error "InvalidSchema: No connection adapters were found for" when request api url with spaces Following example from Apache Beam Pipeline to read from REST API runs locally but not on Dataflow pipeline requests data from api with response = requests.get(url, auth=HTTPDigestAuth(self.USER, self.P...
Python Apache Beam error "InvalidSchema: No connection adapters were found for" when request api url with spaces
Following example from Apache Beam Pipeline to read from REST API runs locally but not on Dataflow pipeline requests data from api with response = requests.get(url, auth=HTTPDigestAuth(self.USER, self.PASSWORD), headers=headers) where url string url = "https://host:port/car('power%203')/speed" Pipeline fails with err...
[ "Remove the comma next to url in get_api_data class - it should fix the problem\nclass get_api_data(beam.DoFn):\n def __init__(self, url):\n self.url = url\n self.USER = 'user' \n self.PASSWORD = 'password'\n\n" ]
[ 1 ]
[]
[]
[ "apache_beam", "google_cloud_dataflow", "python", "python_requests" ]
stackoverflow_0074487643_apache_beam_google_cloud_dataflow_python_python_requests.txt
Q: how can I fix TypeError: can't set attributes of built-in/extension type 'cimpl.Consumer' example.py def simple(): msg = consumer.poll(timeout=int(timeout)) if msg is None: break if msg.error(): if (msg.error().code() == KafkaError.UNKNOWN_TOPIC_OR_PART): response_code = 409 ...
how can I fix TypeError: can't set attributes of built-in/extension type 'cimpl.Consumer'
example.py def simple(): msg = consumer.poll(timeout=int(timeout)) if msg is None: break if msg.error(): if (msg.error().code() == KafkaError.UNKNOWN_TOPIC_OR_PART): response_code = 409 self.logger.debug("Error reading message : {}".format(msg.error())) break ...
[ "As the error message says, you can't patch the C extension class. As a remedy, you can derive the class like this.(It shows the new style syntax for a fixture. Using an annotation is deprecated.)\nimport confluent_kafka import Consumer as _Consumer\n\nclass Consumer(_Consumer): pass\n\ndef get_cls_full_name(cls):\...
[ 0 ]
[]
[]
[ "apache_kafka", "confluent_kafka_python", "kafka_consumer_api", "pytest_mock", "python" ]
stackoverflow_0073290315_apache_kafka_confluent_kafka_python_kafka_consumer_api_pytest_mock_python.txt
Q: find all occurrences between 2 values in non default pattern I am stumbling into an issue with a regex search in python So I have: testVariable = re.findall(r'functest(.*?)1', 'functest exampleOne [2] functest exampleTwo [1] functest exampleOne throw [2] functest exampleThree [1]') Current Output is: [' exampleOn...
find all occurrences between 2 values in non default pattern
I am stumbling into an issue with a regex search in python So I have: testVariable = re.findall(r'functest(.*?)1', 'functest exampleOne [2] functest exampleTwo [1] functest exampleOne throw [2] functest exampleThree [1]') Current Output is: [' exampleOne [2] functest exampleTwo [', ' exampleOne throw [2] functest exam...
[ "If there can not be any digits in between matching the first occurrence of 1 or 3:\n\\bfunctest\\b\\s*(\\D*)[13]\\b\n\nThe pattern matches:\n\n\\bfunctest\\b\\s* Match the word functest followed by optional whitespace chars\n(\\D*) Capture Optional non digits in group 1\n[13] Match either 1 or 3\n\\b A word bounda...
[ 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074488046_python_regex.txt
Q: How to iterate over multiple list and calculate every alternate values in it? I have list where it has values of multiple persons, I want to calculate every alternate values in list of lists, how can I achieve it? list looks like below for j in persons: person_list.append(persons[int(j)][0]+persons[int(j)][2])...
How to iterate over multiple list and calculate every alternate values in it?
I have list where it has values of multiple persons, I want to calculate every alternate values in list of lists, how can I achieve it? list looks like below for j in persons: person_list.append(persons[int(j)][0]+persons[int(j)][2]) person_list.append(persons[int(j)][1]+persons[int(j)][3]) print(...
[ "You can do something like this:\n>>> x = [[222, 1, 255, 54], [105, 1, 135, 48], [397, 310, 521, 594]]\n>>> [[sum(i[::2]), sum(i[1::2])] for i in x]\n[[477, 55], [240, 49], [918, 904]]\n\nThis will go over and sum the even-indexed values together and the same with the odd-indexed values.\n" ]
[ 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074488593_list_python.txt
Q: Access google storage client using dictionary I have a service account in a form of dictionary. Below is the service account service_account = { "type": "service_account", "project_id": "project_id", "private_key_id": "private_key_id", "private_key": "PRIVATE KEY", "client_email": "email", "client_id"...
Access google storage client using dictionary
I have a service account in a form of dictionary. Below is the service account service_account = { "type": "service_account", "project_id": "project_id", "private_key_id": "private_key_id", "private_key": "PRIVATE KEY", "client_email": "email", "client_id": "111111", "auth_uri": "https://auth.com", "to...
[ "It looks like this can be done with the\nfrom_service_account_info() method instead of from_service_account_json.\n" ]
[ 0 ]
[]
[]
[ "google_cloud_platform", "google_cloud_storage", "python" ]
stackoverflow_0074488268_google_cloud_platform_google_cloud_storage_python.txt
Q: 4D Matrix operation in Python - conversion from MATLAB I'm trying to translate this MATLAB code to Python: MATLAB: V_c = delta* max(V_L, repmat(V_A_c,[N_p 1]) - NM ) where these are 4D arrays: V_c is the continuation value for in different states, (should have shape 81, 75, 15, 31) V_L is the initial value, (has ...
4D Matrix operation in Python - conversion from MATLAB
I'm trying to translate this MATLAB code to Python: MATLAB: V_c = delta* max(V_L, repmat(V_A_c,[N_p 1]) - NM ) where these are 4D arrays: V_c is the continuation value for in different states, (should have shape 81, 75, 15, 31) V_L is the initial value, (has shapes 81, 75, 15, 31) V_A_c is the value of adjustment unde...
[ "The error you mention, comes from the fact that you want to element-wise compare two tensor (matrix). use np.maximum.\nconsidering the tile operation is correct and N_p is 85 in you example:\nV_c = delta * np.maximum(V_L, np.tile(V_A_c,(N_p,1,1,1)) - NM ) \n\n" ]
[ 1 ]
[]
[]
[ "dynamic_programming", "matlab", "numpy_ndarray", "python" ]
stackoverflow_0074488411_dynamic_programming_matlab_numpy_ndarray_python.txt
Q: Selenium IDE: Export to Python when using brackets '(' & ')' in xpaths I have XPath statements in Selenium IDE that don't seem possible to export to Python due to the usage of brackets - any ideas for what to do to get around this to complete the export to Python? Its statements like: (//td[@role='presentation'])[...
Selenium IDE: Export to Python when using brackets '(' & ')' in xpaths
I have XPath statements in Selenium IDE that don't seem possible to export to Python due to the usage of brackets - any ideas for what to do to get around this to complete the export to Python? Its statements like: (//td[@role='presentation'])[3] The XPath statements seem sound from a syntax perspective since they wor...
[ "(//td[@role='presentation'])[3] expression can be enclosed with \", as following:\n\"(//td[@role='presentation'])[3]\"\n\n" ]
[ 0 ]
[]
[]
[ "python", "selenium_ide", "xpath" ]
stackoverflow_0074488631_python_selenium_ide_xpath.txt
Q: python selenium- how to get only some of the information inside a HTML element? The website bellow will she the scores of a all the soccer matches and this one is an example, im trying to get the teams that have played and the scores. photo this is the code for the one above: code I tried getting the whole and i...
python selenium- how to get only some of the information inside a HTML element?
The website bellow will she the scores of a all the soccer matches and this one is an example, im trying to get the teams that have played and the scores. photo this is the code for the one above: code I tried getting the whole and it worked, the only thing i can't figure out is how to get the score and teams out of i...
[ "First Identify the parent anchor tag and then iterate the parent element to find the specific child element.\nScores are not available for all the matches since some of them have not started yet. Use try..except block in that case.\ndriver.get('https://www.fotmob.com/?date=20221118&q=')\nelements=WebDriverWait(dri...
[ 0 ]
[]
[]
[ "css_selectors", "python", "selenium", "webdriver", "webdriverwait" ]
stackoverflow_0074488282_css_selectors_python_selenium_webdriver_webdriverwait.txt
Q: How do I get the number `(0 + infj)` in python? I'm using Python 3.9.15 and trying to get the number (0 + infj), i.e. the imaginary part is infinite and the real part is zero. However, I tried several alternatives but all of them gave (nan + infj) instead of (0 + infj). >>> float('inf') * 1j (nan+infj) >>> float('...
How do I get the number `(0 + infj)` in python?
I'm using Python 3.9.15 and trying to get the number (0 + infj), i.e. the imaginary part is infinite and the real part is zero. However, I tried several alternatives but all of them gave (nan + infj) instead of (0 + infj). >>> float('inf') * 1j (nan+infj) >>> float('inf') * 1j + 0 (nan+infj) >>> import numpy as np >>> ...
[ "You can use built-in complex function:\ncomplex(0,float('inf'))\n\n" ]
[ 2 ]
[]
[]
[ "complex_numbers", "python", "python_3.x" ]
stackoverflow_0074488694_complex_numbers_python_python_3.x.txt
Q: How do you make a 2d array from a text file in python and traverse it to get an average of the floats? I have to get input from a text file of a sector and all of it's sales, it has to be stored in a 2d array has to be able to write an average function for data I tried it in java but I want to know how in python....
How do you make a 2d array from a text file in python and traverse it to get an average of the floats?
I have to get input from a text file of a sector and all of it's sales, it has to be stored in a 2d array has to be able to write an average function for data I tried it in java but I want to know how in python.
[ "I suggest using the Pandas library in Python. It has several handy functions for example creating a DataFrame (a 2D array which allows all sorts of manipulations and calculations).\nYou can install it using PIP in your CMD with the following command:\npython3 -m pip install pandas\n\nYour code should look somethin...
[ 0 ]
[]
[]
[ "2d", "arrays", "python" ]
stackoverflow_0074488400_2d_arrays_python.txt
Q: overwriting the column rows basis the condition Existing Dataframe : Id condition1 condition2 score A attempt pass 0 A attempt fail 0 B attempt pass 0 B attempt le...
overwriting the column rows basis the condition
Existing Dataframe : Id condition1 condition2 score A attempt pass 0 A attempt fail 0 B attempt pass 0 B attempt level_1 0 B attempt fai...
[ "You can try:\nm1 = df['condition1'].eq('attempt')\nm2 = df['condition2'].eq('pass') | df['condition2'].eq('level_1')\n\ndf['score'] = (m1 & m2)\ndf['score'] = df.groupby('Id')['score'].transform(lambda x: x.any().astype(int))\n\n Id condition1 condition2 score\n0 A attempt pass 1\n1 A attempt ...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074488713_dataframe_pandas_python.txt
Q: Copy a non-empty folder in python How to copy a non-empty folder in Python ? I am want use like unix command " cp -r " Ex.. sourceFolder = /tmp/Folder1/file1.txt destinationFolder = /tmp/Folder2/ after copying sourceFolder is look like " /tmp/Folder2/Folder1/file1.txt " I am trying for copy shutil.copytree('/tmp/F...
Copy a non-empty folder in python
How to copy a non-empty folder in Python ? I am want use like unix command " cp -r " Ex.. sourceFolder = /tmp/Folder1/file1.txt destinationFolder = /tmp/Folder2/ after copying sourceFolder is look like " /tmp/Folder2/Folder1/file1.txt " I am trying for copy shutil.copytree('/tmp/Folder1/file.txt', '/tmp/Folder2/')
[]
[]
[ "import os\n# Copy Created Feature folder and file into \n\n\ncoping = os.system('cp -rf /tmp/'+folder1+' /tmp/'+folder2+'/')\n\n" ]
[ -2 ]
[ "list", "python", "shutil" ]
stackoverflow_0074488293_list_python_shutil.txt
Q: blosc.MAX_BUFFERSIZE error while trying to guess if a dask dataframe is empty I want to perform a test on the emptiness of a dask dataframe. So I have this dask dataframe ddf, a local ray cluster, and dask configured to use ray as backend. I've seen here that there is no empty property and that I have to perform t...
blosc.MAX_BUFFERSIZE error while trying to guess if a dask dataframe is empty
I want to perform a test on the emptiness of a dask dataframe. So I have this dask dataframe ddf, a local ray cluster, and dask configured to use ray as backend. I've seen here that there is no empty property and that I have to perform the following code len(ddf.index) == 0 This results in ValueError: bytesobj cannot ...
[ "The issue was that the number of partitions on the dask dataframe was 1.\nI've used ddf.repartition(npartitions=32) to solve my issue.\npartition_size=\"100MB\" is the recommended way to go.\n" ]
[ 0 ]
[]
[]
[ "blosc", "dask", "pandas", "python", "ray" ]
stackoverflow_0074319762_blosc_dask_pandas_python_ray.txt
Q: How to change ttk button background and foreground when hover it in tkinter I'm trying to change ttk.tkinter button background to black and foreground colour to white when mouse is hover it. Have tried highlightbackground and activebackground but doesn't yield the result I'm looking for. import tkinter as tk imp...
How to change ttk button background and foreground when hover it in tkinter
I'm trying to change ttk.tkinter button background to black and foreground colour to white when mouse is hover it. Have tried highlightbackground and activebackground but doesn't yield the result I'm looking for. import tkinter as tk import tkinter.ttk as ttk root = tk.Tk() style = ttk.Style(root) #style.theme_use...
[ "ttk Button appearances are driven by themes (3D/Color-alt/classic/default, Color-clam). Not setting/others leaves buttons flat/grey and settings don't change things.\nTo make a ttk TButton change colors can be achieved using map. 3D appearance requires borderwidth.Only Classic forms an outer ring using highlight.\...
[ 8, 2, 0 ]
[]
[]
[ "python", "tkinter", "ttk" ]
stackoverflow_0057186536_python_tkinter_ttk.txt
Q: Python - Tell if there is a non consecutive date in pandas dataframe I have a pandas data frame with dates. I need to know if every other date pair is consecutive. 2 1988-01-01 3 2015-01-31 4 2015-02-01 5 2015-05-31 6 2015-06-01 7 2021-11-16 11 2021-11-17 12 2022-10-05 8 2022-10-06 9 20...
Python - Tell if there is a non consecutive date in pandas dataframe
I have a pandas data frame with dates. I need to know if every other date pair is consecutive. 2 1988-01-01 3 2015-01-31 4 2015-02-01 5 2015-05-31 6 2015-06-01 7 2021-11-16 11 2021-11-17 12 2022-10-05 8 2022-10-06 9 2022-10-12 10 2022-10-13 # How to build this example dataframe df=pd.Data...
[ "here is one way to do it\nbtw, what is your expected output? the answer get you the difference b/w the consecutive dates skipping the first row and populate diff column\n# make date into datetime\ndf['date'] = pd.to_datetime(df['date'])\n\n# create two intermediate DF skipping the first and taking alternate values...
[ 1, 0 ]
[]
[]
[ "dataframe", "date", "pandas", "python" ]
stackoverflow_0074483104_dataframe_date_pandas_python.txt
Q: Solving system of nonlinear complex equations in Python I'm trying to solve a problem with 8 unknowns and 8 complex equations. I've tried to use fsolve but I get the error message: error: Result from function call is not a proper array of floats. From what I've now read fsolve doesn't support complex equations and...
Solving system of nonlinear complex equations in Python
I'm trying to solve a problem with 8 unknowns and 8 complex equations. I've tried to use fsolve but I get the error message: error: Result from function call is not a proper array of floats. From what I've now read fsolve doesn't support complex equations and hence my questions, how would I solve systems of complex non...
[ "Algorithm in which the code below was written\nalgorithm for Newton’s Method for Systems\n\n# Author : Carlos Eduardo da Silva Lima\n# Theme : Newton’s Method for Systems (real or complex)\n# Language: Python\n# IDE : Google Colab\n# Data : 18/11/2022\n\n##################################################...
[ 0 ]
[]
[]
[ "complex_numbers", "equation_solving", "nonlinear_functions", "python" ]
stackoverflow_0058302415_complex_numbers_equation_solving_nonlinear_functions_python.txt
Q: How to use Flask API to post two variables via Postman and run a function using them in that call? I have the following function : ` def file(DOCname,TABLEid): directory = DOCname parent_dir = "E:\\Tables\\Documents\\"+TABLEid path = os.path.join(parent_dir, directory) try: os.makedirs(path, exist_ok = ...
How to use Flask API to post two variables via Postman and run a function using them in that call?
I have the following function : ` def file(DOCname,TABLEid): directory = DOCname parent_dir = "E:\\Tables\\Documents\\"+TABLEid path = os.path.join(parent_dir, directory) try: os.makedirs(path, exist_ok = True) print("Directory '%s' created successfully" % directory) except OSError as error: pri...
[ "It can be done in following way. The data from the Postman should be send\nthrough the forms .\nfrom flask import Flask\nfrom flask import request\napp = Flask(__name__)\n\n@app.route(\"/\",methods=[\"POST\"])\ndef file():\n dic_data = request.form \n DOCname= dic_data[\"DOCname\"]\n TABLEid = dic_data[\"TABLEid\"...
[ 0, 0 ]
[]
[]
[ "api", "flask", "python" ]
stackoverflow_0074488581_api_flask_python.txt
Q: .xlsx and xls(Latest Versions) to pdf using python With the help of this .doc to pdf using python Link I am trying for excel (.xlsx and xls formats) Following is modified Code for Excel: import os from win32com import client folder = "C:\\Oprance\\Excel\\XlsxWriter-0.5.1" file_type = 'xlsx' out_folder = folder + ...
.xlsx and xls(Latest Versions) to pdf using python
With the help of this .doc to pdf using python Link I am trying for excel (.xlsx and xls formats) Following is modified Code for Excel: import os from win32com import client folder = "C:\\Oprance\\Excel\\XlsxWriter-0.5.1" file_type = 'xlsx' out_folder = folder + "\\PDF_excel" os.chdir(folder) if not os.path.exists(o...
[ "Link of xlsxwriter :\nhttps://xlsxwriter.readthedocs.org/en/latest/contents.html\nWith the help of this you can generate excel file with .xlsx and .xls\nfor example excel file generated name is trial.xls\nNow if you want to generate pdf of that excel file then do the following :\nfrom win32com import client\nxlApp...
[ 23, 5, 1, 0, 0 ]
[]
[]
[ "excel", "excel_2010", "pdf", "python", "win32com" ]
stackoverflow_0020854840_excel_excel_2010_pdf_python_win32com.txt
Q: How to read a env variable added in script execution from GitHub workflow Execute a script (tmp.py) with workflow that has below line: os.environ["VERSION"] = "Version 1.1.1.2.2.3" print(os.system('env')) #prints all env included above one Now I need this var in workflow: - name: Run script run: python3 t...
How to read a env variable added in script execution from GitHub workflow
Execute a script (tmp.py) with workflow that has below line: os.environ["VERSION"] = "Version 1.1.1.2.2.3" print(os.system('env')) #prints all env included above one Now I need this var in workflow: - name: Run script run: python3 tmp.py - name: print env var if: always() run: | echo ${{ env.VERSION ...
[ "To save an environment variable in a step (to use it in another one), you would generally use the following syntax:\necho \"foo=bar\" >> $GITHUB_ENV\n\nIn a Python script, that would be done similarly. I'm personally using the following syntax which directly write the variable to the env file:\nimport os\n\nenv_fi...
[ 0 ]
[]
[]
[ "github", "github_actions", "python" ]
stackoverflow_0074486495_github_github_actions_python.txt
Q: Extract a JSON string from a Text File using pyspark I have a TEXT file with 4 fields and 3rd field is JSON string which I want to extract and create a separate column in dataframe. pk,line,json,date DBG,CDL,{"line":"CDL","stn":"DBG","latitude":"12.298915","longitude":"143.846263","isInterchange":true,"isIncidentS...
Extract a JSON string from a Text File using pyspark
I have a TEXT file with 4 fields and 3rd field is JSON string which I want to extract and create a separate column in dataframe. pk,line,json,date DBG,CDL,{"line":"CDL","stn":"DBG","latitude":"12.298915","longitude":"143.846263","isInterchange":true,"isIncidentStn":false,"stnKpis":[{"code":"PCD_PCT","value":0.1,"valueC...
[ "You can read the csv file using pyspark into a dataframe.\ndf = spark.read.csv(\"/tmp/resources/zipcodes.csv\")\nThen\njson_string = json.loads(df.iloc[\"json\"])\n", "Data\ndf =spark.createDataFrame([('DBG','CDL',{\"line\":\"CDL\",\"stn\":\"DBG\",\"latitude\":\"12.298915\",\"longitude\":\"143.846263\",\"isInter...
[ 0, 0 ]
[]
[]
[ "apache_spark", "json", "pyspark", "python" ]
stackoverflow_0074488160_apache_spark_json_pyspark_python.txt
Q: path in FileField django I prepared my model to create PDF filled by all the fields it includes and I try to to link generated file to the pdf = models.FileField(). However the path to the file seems to be ok I can't reach the file through the view. models.py: class Lesson(models.Model): # fields # ... ...
path in FileField django
I prepared my model to create PDF filled by all the fields it includes and I try to to link generated file to the pdf = models.FileField(). However the path to the file seems to be ok I can't reach the file through the view. models.py: class Lesson(models.Model): # fields # ... pdf = models.FileField(upload...
[ "Just use it like this:\n<a href=\"/media/{{ lesson.pdf }}\">CLICK TO VIEW FILE</a>\n\nAfter using the above code, you will be redirected to this path media/pdf/myfile.pdf\n" ]
[ 3 ]
[]
[]
[ "django", "filefield", "python" ]
stackoverflow_0074488939_django_filefield_python.txt
Q: Using Regex to combine two lines I would like to use regex to combine two lines. If the first line has only one word and is followed by one \n , then combine it with next line. The first line sometimes may have a word and a comma , or a word with hyphen - My text looks like this: import re text = ''' Critical Acc...
Using Regex to combine two lines
I would like to use regex to combine two lines. If the first line has only one word and is followed by one \n , then combine it with next line. The first line sometimes may have a word and a comma , or a word with hyphen - My text looks like this: import re text = ''' Critical Accounting Policies and Estimates Review...
[ "Thanks for Wiktor's comment! The code should be\ncombine = re.sub(r'((?<=[A-Za-z,-])\\n(?=[a-zA-Z]))', ' ', text) \n\n" ]
[ 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074488689_python_regex.txt
Q: How to slice output of a neuronal network I constructed a generator CNN which has the output (1, 3328, 1), but I would need (1, 3326, 1) so just 2 neurons/outputs less. I don't think that I can achieve it by changing parameter of the existing net. But I thought, it would be great just to cut out the last 2 neurons...
How to slice output of a neuronal network
I constructed a generator CNN which has the output (1, 3328, 1), but I would need (1, 3326, 1) so just 2 neurons/outputs less. I don't think that I can achieve it by changing parameter of the existing net. But I thought, it would be great just to cut out the last 2 neurons of the last layer. But does someone know how t...
[ "Do this\nmodel = tf.keras.models.Model(model.input , model.layers[-1].output[:,:-2,:])\n\nSimply do this\nmodel.layers[-1].output[:,:-2,:]\n\n#This will simply return \n[None, 3326, None] \n\n\n" ]
[ 1 ]
[]
[]
[ "deep_learning", "keras", "neural_network", "python", "python_3.x" ]
stackoverflow_0074488736_deep_learning_keras_neural_network_python_python_3.x.txt
Q: to print name with a pattern in python I ask the user to enter it's name and I print the pattern eg: W WO WOR WORL WORLD s=input("Enter your name") l=s.split() i=len(l) for m in range(0,i): for s in range(0,m): print(s) print() I have written this program where am I wrong please help. A beginner h...
to print name with a pattern in python
I ask the user to enter it's name and I print the pattern eg: W WO WOR WORL WORLD s=input("Enter your name") l=s.split() i=len(l) for m in range(0,i): for s in range(0,m): print(s) print() I have written this program where am I wrong please help. A beginner here
[ "Others have given you code that does what you want it to do; I'll try to explain why your code doesn't do what you think it would do.\n#s=input(\"Enter your name\")\n# Let's pretend that the given word from the user was 'WORLD' as in your example.\ns = \"WORLD\"\nl=s.split()\n\nThe above line s.split() uses the de...
[ 1, 0, 0 ]
[]
[]
[ "debugging", "design_patterns", "python" ]
stackoverflow_0074488803_debugging_design_patterns_python.txt
Q: How do I plot this piecewise function into Python with matplotlib? This is the function I need to plot: This is my code: pi = np.pi sin = np.sin e = np.e x1 = np.linspace(-10*pi, -pi) y1 = (4*pi*(e**0.1*x1)) * sin(2*pi*x1) plt.plot(x1, y1) x2 = np.linspace(-pi, -pi/2) y2 = 0 plt.plot(x2, y2) x3 = np.linspace(-...
How do I plot this piecewise function into Python with matplotlib?
This is the function I need to plot: This is my code: pi = np.pi sin = np.sin e = np.e x1 = np.linspace(-10*pi, -pi) y1 = (4*pi*(e**0.1*x1)) * sin(2*pi*x1) plt.plot(x1, y1) x2 = np.linspace(-pi, -pi/2) y2 = 0 plt.plot(x2, y2) x3 = np.linspace(-pi/2, pi/2) y3 = 4/pi * x3**2 - pi plt.plot(x3, y3) x4 = np.linspace(pi...
[ "\nTo define a piecewise function, I usually use a chained sequence of numpy.where.\nFirst, the domain for the independent variable, then the conditions and the analytical expression, with a difference for the last where, as explained in the docs.\nNB: are you sure that the circular frequency of the sines is 2π? wh...
[ 1, 0, 0 ]
[]
[]
[ "matplotlib", "numpy", "piecewise", "python", "valueerror" ]
stackoverflow_0074488361_matplotlib_numpy_piecewise_python_valueerror.txt
Q: Why does gunicorn need to restart so often in my gcloud appengine app? I am using Flask to run an application. The application will be deployed on gcloud appengine. Currently, when I run it on my local dev machine, there is no issue. But when I run it on gcloud appengine, it appears that the gunicorn thread is ...
Why does gunicorn need to restart so often in my gcloud appengine app?
I am using Flask to run an application. The application will be deployed on gcloud appengine. Currently, when I run it on my local dev machine, there is no issue. But when I run it on gcloud appengine, it appears that the gunicorn thread is being restarted quite often. 2022-11-13 08:54:13 default[20221113t165059] O...
[ "Many apologies. I found that the reason why my session (run off MongoDB) was so unstable. The reason is because for the\nsecretKey = os.urandom(21) # your own secret key\n\nSo every time gunicorn reinitialized itself (I don't know the reason why though), all the code infront of that which required to have the s...
[ 0 ]
[]
[]
[ "flask", "gcloud", "google_app_engine", "gunicorn", "python" ]
stackoverflow_0074420230_flask_gcloud_google_app_engine_gunicorn_python.txt
Q: How to unnest JSON with levels upon levels I'm trying to unnest a json file. The JSON has multiple lists of dictionaries inside a list of dictionaries. I'm trying to flatten everything in it and turn it into a dataframe. it looks something like this: { "Result": [ { "OptionalColumns": { "optionalCo...
How to unnest JSON with levels upon levels
I'm trying to unnest a json file. The JSON has multiple lists of dictionaries inside a list of dictionaries. I'm trying to flatten everything in it and turn it into a dataframe. it looks something like this: { "Result": [ { "OptionalColumns": { "optionalColumnName": "Joe Blogs" }, "fieldOne": ...
[ "It would be how you posted it before with another dict. Quite simple really.\npd.json_normalize(data, “thirdList”, [“OptionalColumns”, “optionalColumnName”],”fieldOne”, “fieldTwo”, “fieldThree”, [“secondList”, “secondListDictOneFieldOne”,”secondListDictTwoFieldOne”], “anotherField”, “someNumberValue”)\n\n" ]
[ 0 ]
[]
[]
[ "arrays", "json", "nested_lists", "python", "unnest" ]
stackoverflow_0074488995_arrays_json_nested_lists_python_unnest.txt
Q: How can I hide "" (NaN) values with st.dataframe() or st.table() in Streamlit? When I display a Pandas DataFrame in Streamlit, using st.dataframe() or st.table(), NaN values show up as the text <NA>. I would like to hide them. Code: # table.py import pandas as pd import streamlit as st df = pd.read_csv("nlp_metri...
How can I hide "" (NaN) values with st.dataframe() or st.table() in Streamlit?
When I display a Pandas DataFrame in Streamlit, using st.dataframe() or st.table(), NaN values show up as the text <NA>. I would like to hide them. Code: # table.py import pandas as pd import streamlit as st df = pd.read_csv("nlp_metrics_v2.csv", header=0) st.dataframe(df) # nlp_metrics_v2.csv Model,NLP Model,NLP Pri...
[ "I tried using pandas.io.formats.style.Styler.highlight_null to set \"opacity: 0\" or \"visibility: hidden\", but Streamlit seemed to ignore these CSS properties.\nI found this solution by playing around with WebStorm and PyCharm:\n# table.py\nimport pandas as pd\nimport streamlit as st\n\ndf = pd.read_csv(\"nlp_me...
[ 1, 1 ]
[]
[]
[ "dataframe", "nan", "pandas", "python", "streamlit" ]
stackoverflow_0073339413_dataframe_nan_pandas_python_streamlit.txt
Q: Implement HTTP methods in different APIView class in django I have an API with 2 routes some_resource/ and some_resource/<id> and I would like to implement the normal CRUD actions (list, retrieve, create, update, delete). However, I don't want to use ViewSet because I want to have 1 class for each view. Thus I ne...
Implement HTTP methods in different APIView class in django
I have an API with 2 routes some_resource/ and some_resource/<id> and I would like to implement the normal CRUD actions (list, retrieve, create, update, delete). However, I don't want to use ViewSet because I want to have 1 class for each view. Thus I need to set up the route manually for clarity. : class SomeResource...
[ "You can make use of ViewSets\ngive this a try:\nfrom rest_framework import viewsets\nfrom rest_framework.response import Response\n\nclass InvitationTeamAccessViewSet(viewsets.ViewSet):\n \"\"\"\n Example empty viewset demonstrating the standard\n actions that will be handled by a router class.\n\n If ...
[ 0 ]
[]
[]
[ "django", "django_rest_framework", "python" ]
stackoverflow_0074487483_django_django_rest_framework_python.txt
Q: add shell script to lambda function on EC2 I have a lambda function that boots a machine on EC2 triggered by a file uploaded on S3 bucket. I would like to run a shell command that is in that machine after the boot, but I failed to do so. Any thoughts of what I can do? import boto3 region = 'us-east-1' instances =...
add shell script to lambda function on EC2
I have a lambda function that boots a machine on EC2 triggered by a file uploaded on S3 bucket. I would like to run a shell command that is in that machine after the boot, but I failed to do so. Any thoughts of what I can do? import boto3 region = 'us-east-1' instances = ['i-079e6065f959e151a'] def lambda_handler(eve...
[ "On the Amazon EC2 instance, store your script in:\n/var/lib/cloud/scripts/per-boot/\n\nAny scripts in that directory will be automatically run each time that the instance boots (or 'Starts').\nWhen the instance has finished its work, it should perform a shutdown with:\nsudo shutdown now -h\n\nThis will return the ...
[ 0 ]
[]
[]
[ "amazon_ec2", "amazon_web_services", "aws_lambda", "python", "shell" ]
stackoverflow_0074488971_amazon_ec2_amazon_web_services_aws_lambda_python_shell.txt
Q: Why won't my grouped box plot work in Python? I have a data set (my_data) that looks something like this: Gender Time Money Score Female 23 14 26.74 Male 12 98 56.76 Male 11 34 53.98 Female 18 58 25.98 etc. I want to make a grouped b...
Why won't my grouped box plot work in Python?
I have a data set (my_data) that looks something like this: Gender Time Money Score Female 23 14 26.74 Male 12 98 56.76 Male 11 34 53.98 Female 18 58 25.98 etc. I want to make a grouped box plot of gender against score, so that there wil...
[ "When you extracted your source data, you put them unnecessary in square brackets.\nGenerate them instead as:\nMales = my_data.loc[my_data['Gender']=='Male', 'Score']\nFemales = my_data.loc[my_data['Gender']=='Female', 'Score']\n\nThen, to generate your box plot, you can run e.g.:\nfig, ax = plt.subplots(1, 1)\nax....
[ 0 ]
[]
[]
[ "boxplot", "graph", "matplotlib", "numpy", "python" ]
stackoverflow_0074488153_boxplot_graph_matplotlib_numpy_python.txt
Q: run an external script and print the output in real-time in a text widget I want to run an external script (demo_print.py) and print the output in real-time in a text widget. I got error: What's my mistake and how to reach my goal ? You can suggest more simple solution if you have. Exception in thread Thread-1: Tr...
run an external script and print the output in real-time in a text widget
I want to run an external script (demo_print.py) and print the output in real-time in a text widget. I got error: What's my mistake and how to reach my goal ? You can suggest more simple solution if you have. Exception in thread Thread-1: Traceback (most recent call last): File "/usr/bin/python3/3.7.4/lib/python3.7/thr...
[ "Okay so first of all make sure demo_print.py is in the same space as your main.py not in a folder or anything then you can just do this:\nfrom demo_print import *\nprint(whatever u named your output variable in demo_print)\n\nFrom the looks of it you know how to do the rest.\n", "Since you execute \"demo_print.p...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x", "tkinter" ]
stackoverflow_0074487766_python_python_3.x_tkinter.txt
Q: I am getting a type error when I am trying to replace I am trying to do a conditional replacing of values in one column(age_cat) by values in another column(stillbirth) but it's giving me a type error TypeError: '<' not supported between instances of 'str' and 'float' basically, I need it to say age_cat is "SB" if...
I am getting a type error when I am trying to replace
I am trying to do a conditional replacing of values in one column(age_cat) by values in another column(stillbirth) but it's giving me a type error TypeError: '<' not supported between instances of 'str' and 'float' basically, I need it to say age_cat is "SB" if report_stillbirth is Yes 'report_stillbirth' 'age_cat'...
[ "Try this:\n\nimport numpy as np\nimport pandas as pd\n\ndf['age_cat'] = np.where(df['report_stillbirth'] == 'Yes', 'SB', df['age_cat'])\n\nExample:\n\nimport numpy as np\nimport pandas as pd\n\n\nchoices = ['Yes', 'No']\n\ndf = pd.DataFrame(\n {\n 'report_stillbirth': np.random.choice(choices, 10),\n ...
[ 1 ]
[]
[]
[ "numpy", "pandas", "python" ]
stackoverflow_0074489050_numpy_pandas_python.txt
Q: What regex can I use to "clean" a sentence from its first characters like 1), or #1, or I'm trying in Python to "clean up" a string and remove some characters that were added like : "1. bla bla" => i want "bla bla" "#. bla bla" => same "3) bla bla" => same "I. bla bla" => same I tried to use (\W)(\w.*) but doesn'...
What regex can I use to "clean" a sentence from its first characters like 1), or #1, or
I'm trying in Python to "clean up" a string and remove some characters that were added like : "1. bla bla" => i want "bla bla" "#. bla bla" => same "3) bla bla" => same "I. bla bla" => same I tried to use (\W)(\w.*) but doesn't work. Thanks !
[ "You can try:\n^.[.)]\\s+(.*)\n\nRegex demo.\n\nimport re\n\ntext = \"\"\"\\\n1. bla bla\n#. bla bla\n3) bla bla\nI. bla bla\"\"\"\n\npat = re.compile(r\"^.[.)]\\s+(.*)\", flags=re.M)\n\nfor cleaned in pat.findall(text):\n print(cleaned)\n\nPrints:\nbla bla\nbla bla\nbla bla\nbla bla\n\n", "You can try this de...
[ 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074489160_python_regex.txt
Q: File - read and write? Im new to this so i don't quite understand question fully. It says: It is necessary to load output.txt file in program. Structure of file is that every line is new expression in format: 10-1 6-3. So format is number-operator-number It is necessary to write a program that reads that file, l...
File - read and write?
Im new to this so i don't quite understand question fully. It says: It is necessary to load output.txt file in program. Structure of file is that every line is new expression in format: 10-1 6-3. So format is number-operator-number It is necessary to write a program that reads that file, line by line, applies the giv...
[ "so i maganed to do it, just to post it so if some1 else might need. Cheers.\nf = open(\"your file location /input.txt\")\ncontent = f.read()\nsplitRows = content.split('\\n')\nresult = \"\"\nfor x in splitRows:\na, b = x.split('-') \n\nc = int(a) - int(b) \n\nc = str(c) \n\nres = (a + \"-\" + b + \"=\" + c + \"\\n...
[ 0 ]
[]
[]
[ "file", "file_read", "input", "python", "read_write" ]
stackoverflow_0074466037_file_file_read_input_python_read_write.txt
Q: How to fetch data analyzed in python to node.js and pass it to angular? I am new to angular and i want to display JSON data from python to angular with the help of node.js and I used child process to connect python and node.js but I dont know how to pass it to angular service node.js file const express = require('...
How to fetch data analyzed in python to node.js and pass it to angular?
I am new to angular and i want to display JSON data from python to angular with the help of node.js and I used child process to connect python and node.js but I dont know how to pass it to angular service node.js file const express = require('express') const { spawn } = require('child_process') const app = express() co...
[ "Technically you just have to send a Http GET request from your service.\nI suggest that you should read and follow this offical http client guide to set it up correctly.\nHere is a simple service snippet. This should be enough.\n @Injectable({\n providedIn: 'root',\n })\n export class MyService {\n ...
[ 0 ]
[]
[]
[ "angular", "node.js", "python" ]
stackoverflow_0074488744_angular_node.js_python.txt
Q: how to pass python script variables to a csh script? I have a python script which asks user to selct one of many options, I would like to use the selected variable in a csh script to proceed further. I am getting undefined variable when I am trying to use the python variable from the shell script. Here is some ref...
how to pass python script variables to a csh script?
I have a python script which asks user to selct one of many options, I would like to use the selected variable in a csh script to proceed further. I am getting undefined variable when I am trying to use the python variable from the shell script. Here is some reference: There is a python script choices.py whose output i...
[ "Csh has no way to know what variables existed in a Python process which has now ceased to exist, just like you have no way to know what C variables exist internally in the C compiler.\nA common arrangement is to have your script output a value on standard output, and have the shell capture that:\nset choice=`pytho...
[ 0 ]
[]
[]
[ "csh", "python", "shell" ]
stackoverflow_0074488906_csh_python_shell.txt
Q: Why threading doesn't work in my Python script? I try to launch this code on my computer and threading doesn't work: import threading def infinite_loop(): while 1 == 1: pass def myname(): print("chralabya") t1 = threading.Thread(target=infinite_loop()) t2 = threading.Thread(target=myname()) t1....
Why threading doesn't work in my Python script?
I try to launch this code on my computer and threading doesn't work: import threading def infinite_loop(): while 1 == 1: pass def myname(): print("chralabya") t1 = threading.Thread(target=infinite_loop()) t2 = threading.Thread(target=myname()) t1.start() t2.start() When I execute this program myn...
[ "target=inifinite_loop() calls your function (note the ()) and assigns the result (which never comes) to the target parameter. That's not what you want!\nInstead, you want to pass the function itself to the Thread constructor:\nt1 = threading.Thread(target=infinite_loop)\nt2 = threading.Thread(target=myname)\n\n" ]
[ 1 ]
[]
[]
[ "multithreading", "python", "python_3.x", "python_multithreading" ]
stackoverflow_0074489241_multithreading_python_python_3.x_python_multithreading.txt
Q: Want to display only specific value in graph's x-axis , but its showing repeated values of columns of csv-file I need to display only unique values on x-axis, but it is showing all the values in a specific column of the csv-file. Any suggestions please to fix this out? df=pd.read_csv('//media//HOTEL MANAGEMENT.csv...
Want to display only specific value in graph's x-axis , but its showing repeated values of columns of csv-file
I need to display only unique values on x-axis, but it is showing all the values in a specific column of the csv-file. Any suggestions please to fix this out? df=pd.read_csv('//media//HOTEL MANAGEMENT.csv') df.plot('Room_Type','Charges',color='g') plt.show()
[]
[]
[ "My assumption is that you are looking to plot the result of some aggregated data. e.g. Either:\n\nThe total charges per room type, or\nThe average charge per room type, or\nThe minimum/maximum charge per room type.\n\nIf so, you could so like:\ndf=pd.read_csv('//media//HOTEL MANAGEMENT.csv')\n\n# And use any of th...
[ -1 ]
[ "csv", "matplotlib", "python" ]
stackoverflow_0074489133_csv_matplotlib_python.txt
Q: Passing variable to href django template I have some problem and maybe I can give an example of two views below what I want to achieve. class SomeViewOne(TemplateView): model = None template_name = 'app/template1.html' def get_context_data(self, **kwargs): context = super().get_context_data(**...
Passing variable to href django template
I have some problem and maybe I can give an example of two views below what I want to achieve. class SomeViewOne(TemplateView): model = None template_name = 'app/template1.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # The downloads view contains ...
[ "If Manoj's solution doesn't work, try removing the single quotes AND {{ }}. In my program, my integer doesnt need to be wrapped with {{ }}, so maybe neither does your string.\nI have this in my code:\n{% for item in items %}\n\n <div class=\"item-title\">\n {{ item }}<br>\n </div>\n <...
[ 1, 1, 0 ]
[]
[]
[ "django", "django_templates", "django_urls", "django_views", "python" ]
stackoverflow_0074488338_django_django_templates_django_urls_django_views_python.txt
Q: PyCharm warns for unresolved reference builtin datetime module I just installed the latest version of PyCharm (4.5). Now I am experiencing unresolved reference errors. On the top of my code I have: from datetime import datetime OS is Ubuntu 15.04. Already did the Invalidate Cache/Restart several times. No differe...
PyCharm warns for unresolved reference builtin datetime module
I just installed the latest version of PyCharm (4.5). Now I am experiencing unresolved reference errors. On the top of my code I have: from datetime import datetime OS is Ubuntu 15.04. Already did the Invalidate Cache/Restart several times. No difference. The Project interpreter of my project is set to Python 2.7.6. A...
[ "As mentioned here try to delete the content of the skeleton folder. It reside inside of the settingsfolder (~/.PyCharmxxxx.xx/system/python_stubs)\nRemoving/adding the python environment was not necessary for me. Simply restart PyCharm after removing the content (or the whole python_stubs folder)\nThis does the tr...
[ 9, 4, 0 ]
[]
[]
[ "pycharm", "python" ]
stackoverflow_0030311954_pycharm_python.txt
Q: Reverse certain elements in a 2d array to produce a matrix in the specified format, Python 3 I have the following code for a list of lists with the intention of creating a matrix of numbers: grid=[[1,2,3,4,5,6,7],[8,9,10,11,12],[13,14,15,16,17],[18,19,20,21,22]] On using the following code which i figured out wou...
Reverse certain elements in a 2d array to produce a matrix in the specified format, Python 3
I have the following code for a list of lists with the intention of creating a matrix of numbers: grid=[[1,2,3,4,5,6,7],[8,9,10,11,12],[13,14,15,16,17],[18,19,20,21,22]] On using the following code which i figured out would reverse the list, it produces a matrix ... for i in reversed(grid): print(i) The output is...
[ "You need to reverse the list and also the sub-lists:\n[lst[::-1] for lst in grid[::-1]]\n\nNote that lst[::-1] reverses the list via list slicing, see here. \nYou can visualize the resulting nested lists across multiples lines with pprint:\n>>> from pprint import pprint\n>>> pprint([lst[::-1] for lst in grid[::-1]...
[ 1, 0, 0 ]
[]
[]
[ "list", "matrix", "python", "reverse" ]
stackoverflow_0041983087_list_matrix_python_reverse.txt
Q: VSCode not recognizing python import and functions Can someone let me know what the squiggly lines represent in the image? The actual error the flags up when I hover my mouse over the squiggly line is: Import "pyspark.sql.functions" could not be resolvedPylance I'm not sure what that means, but I'm getting the err...
VSCode not recognizing python import and functions
Can someone let me know what the squiggly lines represent in the image? The actual error the flags up when I hover my mouse over the squiggly line is: Import "pyspark.sql.functions" could not be resolvedPylance I'm not sure what that means, but I'm getting the error for almost all functions in VSCode. Can someone let m...
[ "I was with the same error as yours. VSCode usually has a \"recommended\" interpreter, but sometimes it won't help you out with what you need. So,\n\nI changed the Interpeter (ctrl + shift + p in VSCODE).\nLook for \"Python: Select Interpreter.\nChoose the one who contains the name \"Conda\"\n\nAnd that's how the m...
[ 2, 0 ]
[]
[]
[ "python", "visual_studio_code" ]
stackoverflow_0070362595_python_visual_studio_code.txt
Q: _tkinter.TclError: can't delete Tcl command - customtkinter - custom prompt What do I need I am trying to implement a custom Yes / No prompt box with help of tkinter. However I don't want to use the default messagebox, because I require the following two functionalites: a default value a countdown after which the...
_tkinter.TclError: can't delete Tcl command - customtkinter - custom prompt
What do I need I am trying to implement a custom Yes / No prompt box with help of tkinter. However I don't want to use the default messagebox, because I require the following two functionalites: a default value a countdown after which the widget destroys itself and takes the default value as answer What are the unpre...
[ "While I don't have Ctk to give you the exact code. I can tell you exactly what is wrong and how you need to solve it.\nYou have self repeating function via after here:\ndef countdown(self):\n \"\"\"Sets the timer for the question.\"\"\"\n if self.answer is not None:\n self.terminate()\n ...
[ 2 ]
[]
[]
[ "customtkinter", "python", "tkinter" ]
stackoverflow_0074488759_customtkinter_python_tkinter.txt
Q: Faster numpy array indexing when using condition (numpy.where)? I have a huge numpy array with shape (50000000, 3) and I'm using: x = array[np.where((array[:,0] == value) | (array[:,1] == value))] to get the part of the array that I want. But this way seems to be quite slow. Is there a more efficient way of perfo...
Faster numpy array indexing when using condition (numpy.where)?
I have a huge numpy array with shape (50000000, 3) and I'm using: x = array[np.where((array[:,0] == value) | (array[:,1] == value))] to get the part of the array that I want. But this way seems to be quite slow. Is there a more efficient way of performing the same task with numpy?
[ "np.where is highly optimized and I doubt someone can write a faster code than the one implemented in the last Numpy version (disclaimer: I was one who optimized it). That being said, the main issue here is not much np.where but the conditional which create a temporary boolean array. This is unfortunately the way t...
[ 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074482961_numpy_python.txt
Q: How to replicate SHAP Summary plot Instead of the traditional approach using train/test split or cross-validation, I've done 100 repeats of cross-validation, taken SHAP values on each repeat, then averaged them out. I'd now like to plot these averages in the same way that a summary_plot would look. Is this possibl...
How to replicate SHAP Summary plot
Instead of the traditional approach using train/test split or cross-validation, I've done 100 repeats of cross-validation, taken SHAP values on each repeat, then averaged them out. I'd now like to plot these averages in the same way that a summary_plot would look. Is this possible at all, either by hacking the summary_...
[ "I almost got there with the following code:\n## Obtain range of each var to rank variables by importance \nranges = mean_shap_values.apply(np.ptp, axis=0) .sort_values(ascending=False)\n\n## Re-order df for plotting purposes\nordered_mean_shap = mean_shap_values[ranges.index]\n\n## Transpose dataframe to long form...
[ 1 ]
[]
[]
[ "matplotlib", "plot", "python", "shap", "visualization" ]
stackoverflow_0074488664_matplotlib_plot_python_shap_visualization.txt
Q: What is the best way to return a boolean when a negative value exists in a list? I have the following funciton telling us that a series has at least one negative value: def has_negative(series): v=False for i in range(len(series)): if series[i]<0: v=True break return v ...
What is the best way to return a boolean when a negative value exists in a list?
I have the following funciton telling us that a series has at least one negative value: def has_negative(series): v=False for i in range(len(series)): if series[i]<0: v=True break return v When we use this function on an example we get : y=[1,2,3,4,5,6,7,8,9] z=[1,-2,3,4,5,6...
[ "You can utilise the built-in any function as follows:\ndef has_negative(lst):\n return any(e < 0 for e in lst)\n\nprint(has_negative([1,2,3,4,5,6,7,8,9]))\nprint(has_negative([1,-2,3,4,5,6,7,8,9]))\n\nOutput:\nFalse\nTrue\n\nEDIT:\nDid some timing tests based around this and other suggested answers. Whilst this...
[ 3, 2, 1, 1 ]
[]
[]
[ "boolean", "function", "list", "python" ]
stackoverflow_0074488705_boolean_function_list_python.txt
Q: Loop through list of text I'm trying to write a code in Python that iterates through a list of text (events) as following: ln pid description 1 23 failure in node 5 2 23 restart node 5 3 26 check node 5 4 30 fault alarm in node 10 5 23 finish .. .. .. I want the algorithm to check first if the l...
Loop through list of text
I'm trying to write a code in Python that iterates through a list of text (events) as following: ln pid description 1 23 failure in node 5 2 23 restart node 5 3 26 check node 5 4 30 fault alarm in node 10 5 23 finish .. .. .. I want the algorithm to check first if the line has the word 'failure' in a...
[ "This code\nwith open('events.txt') as f:\n failed_node = None\n while True:\n try:\n pid, *msg, node = next(f).split()\n if 'finish' in msg:\n failed_node = None\n continue\n if failed_node is not None:\n if node == failed_n...
[ 0 ]
[]
[]
[ "enumerate", "list", "loops", "python" ]
stackoverflow_0074488644_enumerate_list_loops_python.txt
Q: Turtle not moving, screen events Heello! My turtle is not moving and I don't really know why... May anyone help? import turtle chocolate = turtle.Turtle() def move_forward(): chocolate.forward(10) screen = turtle.Screen() screen.exitonclick() screen.listen() screen.onkey(fun=move_forward, key="space") scr...
Turtle not moving, screen events
Heello! My turtle is not moving and I don't really know why... May anyone help? import turtle chocolate = turtle.Turtle() def move_forward(): chocolate.forward(10) screen = turtle.Screen() screen.exitonclick() screen.listen() screen.onkey(fun=move_forward, key="space") screen.mainloop() I expect my turtle m...
[ "Try this. It's working. Tested here.\nimport turtle\n\nchocolate = turtle.Turtle()\nchocolate.shape(\"turtle\")\nchocolate.speed(500)\n\ndef move_forward():\n chocolate.forward(1)\n\nscreen = turtle.Screen()\nscreen.onkey(move_forward, \"space\")\nscreen.listen()\nscreen.exitonclick()\n\nPerhaps this can give y...
[ 0, 0 ]
[]
[]
[ "python", "python_turtle", "turtle_graphics" ]
stackoverflow_0074489269_python_python_turtle_turtle_graphics.txt
Q: Python pandas check if dataframe is not empty I have an if statement where it checks if the data frame is not empty. The way I do it is the following: if dataframe.empty: pass else: #do something But really I need: if dataframe is not empty: #do something My question is - is there a method .not_empty...
Python pandas check if dataframe is not empty
I have an if statement where it checks if the data frame is not empty. The way I do it is the following: if dataframe.empty: pass else: #do something But really I need: if dataframe is not empty: #do something My question is - is there a method .not_empty() to achieve this? I also wanted to ask if the sec...
[ "Just do\nif not dataframe.empty:\n # insert code here\n\nThe reason this works is because dataframe.empty returns True if dataframe is empty. To invert this, we can use the negation operator not, which flips True to False and vice-versa. \n", ".empty returns a boolean value\n>>> df_empty.empty\nTrue\n\nSo if...
[ 149, 17, 15, 0, 0 ]
[ "Another way:\nif dataframe.empty == False:\n #do something`\n\n" ]
[ -3 ]
[ "pandas", "python", "python_3.x" ]
stackoverflow_0036543606_pandas_python_python_3.x.txt
Q: Django: How to add created_at with nulls for old records? I'm trying to add created_at field to a table with millions of records, and I don't want to add value to the previous records. I have tried the following: created_at = models.DateTimeField(auto_now_add=True) OR created_at = models.DateTimeField(auto_now_add...
Django: How to add created_at with nulls for old records?
I'm trying to add created_at field to a table with millions of records, and I don't want to add value to the previous records. I have tried the following: created_at = models.DateTimeField(auto_now_add=True) OR created_at = models.DateTimeField(auto_now_add=True, null=True) Still, it set the value to all records, not ...
[ "auto_now_add=True automatically sets the fields value and it is not editable.\nYou need to remove the auto_now_add and set a default value. Best approach for that is:\nfrom django.utils.timezone import now\n\ncreated = models.DateTimeField(blank=True, null=True, default=now)\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "postgresql", "python" ]
stackoverflow_0074488917_django_django_models_postgresql_python.txt
Q: How to plot complex numbers (Argand Diagram) using matplotlib I'd like to create an Argand Diagram from a set of complex numbers using matplotlib. Are there any pre-built functions to help me do this? Can anyone recommend an approach? Image by LeonardoG, CC-SA-3.0 A: I'm not sure exactly what you're after here...
How to plot complex numbers (Argand Diagram) using matplotlib
I'd like to create an Argand Diagram from a set of complex numbers using matplotlib. Are there any pre-built functions to help me do this? Can anyone recommend an approach? Image by LeonardoG, CC-SA-3.0
[ "I'm not sure exactly what you're after here...you have a set of complex numbers, and want to map them to the plane by using their real part as the x coordinate and the imaginary part as y? \nIf so you can get the real part of any python imaginary number with number.real and the imaginary part with number.imag. If ...
[ 21, 13, 2, 1, 0 ]
[]
[]
[ "complex_numbers", "matplotlib", "numpy", "plot", "python" ]
stackoverflow_0017445720_complex_numbers_matplotlib_numpy_plot_python.txt
Q: Adding data to the dictionary I have a function that loops through a database. And it writes the result to a dictionary. But it doesn't work. Each loop doesn't write new data into the dictionary, but overwrites the previous ones. How may I fix the error in my code? A fragment of my code: if x is not None: for ...
Adding data to the dictionary
I have a function that loops through a database. And it writes the result to a dictionary. But it doesn't work. Each loop doesn't write new data into the dictionary, but overwrites the previous ones. How may I fix the error in my code? A fragment of my code: if x is not None: for key, value in qur_list.items(): ...
[ "just move result = {} outside of for loop. Also fnc[0] should be unique. Think how to define unique key in dictionary\n" ]
[ 0 ]
[]
[]
[ "function", "loops", "python" ]
stackoverflow_0074489464_function_loops_python.txt
Q: Kivymd MDLabel padding or margin I hope you are doing great. I would like to keep space between the text in MDLabel and the edges of the screen any help ideas? this is my code for the first page .kv MDScreen: name:"splash" MDFloatLayout: md_bg_color: (255/255, 250/255, 245/255, 1) Image: source:"assets/1.png" size...
Kivymd MDLabel padding or margin
I hope you are doing great. I would like to keep space between the text in MDLabel and the edges of the screen any help ideas? this is my code for the first page .kv MDScreen: name:"splash" MDFloatLayout: md_bg_color: (255/255, 250/255, 245/255, 1) Image: source:"assets/1.png" size_hint:.50,.50 pos_hint:{"center_x":.5,...
[ "I got the answer:\nMDLabel:\n text:\"Recognizing the Type of the vine based on the image of list leaves\"\n pos_hint:{\"center_x\":.5,\"center_y\":.4}\n halign:\"center\"\n theme_text_color:\"Custom\"\n text_color: (5/255, 215/255, 80/255, 1)\n font...
[ 0 ]
[]
[]
[ "design_patterns", "kivy", "kivy_language", "kivymd", "python" ]
stackoverflow_0074489003_design_patterns_kivy_kivy_language_kivymd_python.txt
Q: Is there a way to order Wagtail Blocks in the Admin Panel Currently I have all blocks split out into different groups for the page editors to easily navigate through the different block options. However, from reading the documentation I cannot see any way to specifically order the groups. It would be great to be ...
Is there a way to order Wagtail Blocks in the Admin Panel
Currently I have all blocks split out into different groups for the page editors to easily navigate through the different block options. However, from reading the documentation I cannot see any way to specifically order the groups. It would be great to be able to customise this so that I could have the text editor gro...
[ "This isn't currently supported - as of Wagtail 4.1, groups of blocks are always listed alphabetically by group name. Here's where this is implemented.\nYou could probably override this behaviour by subclassing StreamField and defining your own grouped_child_blocks method, but be aware that this isn't an officially...
[ 0 ]
[]
[]
[ "admin", "content_management_system", "django", "python", "wagtail" ]
stackoverflow_0074488997_admin_content_management_system_django_python_wagtail.txt
Q: updating the column basis checking the condition Id condition2 score A pass 0 A fail 0 B pass 0 B level_1 0 B fail 0 C ...
updating the column basis checking the condition
Id condition2 score A pass 0 A fail 0 B pass 0 B level_1 0 B fail 0 C fail 0 D ...
[ "Lets use isin to find the ids which have pass or level_1:\nm = df['condition2'].isin(['pass', 'level_1'])\ndf['score'] = df['Id'].isin(df.loc[m, 'Id']).astype(int)\n\nIf you still want to use groupby and transform..here is the fix to your existing approach:\nm = df['condition2'].isin(['pass', 'level_1'])\ndf['scor...
[ 1, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074489447_dataframe_pandas_python.txt
Q: comparing lists in python, with a twist So I have two lists I want to compare, listA and listB. If an item from listA appears in listB, I want to remove it from listB. I can do this with: listA = ["config", "\n", "config checkpoint"] listB = ["config exclusive", "config checkpoint test", "config", "config", "con...
comparing lists in python, with a twist
So I have two lists I want to compare, listA and listB. If an item from listA appears in listB, I want to remove it from listB. I can do this with: listA = ["config", "\n", "config checkpoint"] listB = ["config exclusive", "config checkpoint test", "config", "config", "config", "\n", "hello"] listB = [line for l...
[ "If, listA is a list of regex patterns (as you wrote in comments), you can do:\nimport re\n\nlistA = [\"^config$\", \"^\\n$\", \"^config checkpoint\"]\nlistB = [\"config exclusive\", \"config checkpoint test\", \"config\", \"config\", \"config\", \"\\n\", \"hello\"]\n\nlistB = [line for line in listB if not any(re....
[ 1, 0 ]
[]
[]
[ "list", "python", "string" ]
stackoverflow_0074489212_list_python_string.txt
Q: convert tuple to dict and accessing its values inputTuple = ({'mobile': '91245555555', 'email': 'xyz@gmail.com', 'name': 'xyz', 'app_registration': 1},) print(type(inputTuple)) # <class 'tuple'> my_dict = dict(inputTuple) print(my_dict) #ValueError: dictionary update sequence element #0 has length 4; 2 is requi...
convert tuple to dict and accessing its values
inputTuple = ({'mobile': '91245555555', 'email': 'xyz@gmail.com', 'name': 'xyz', 'app_registration': 1},) print(type(inputTuple)) # <class 'tuple'> my_dict = dict(inputTuple) print(my_dict) #ValueError: dictionary update sequence element #0 has length 4; 2 is required mobile = my_dict.get("mobile") email = my_dict.g...
[ "Do you just want\nmy_dict = inputTuple[0]\ndata = my_dict['mobile']\nprint(data) \n\n", "inputTuple = ({'mobile': '91245555555', 'email': 'xyz@gmail.com', 'name': 'xyz', 'app_registration': 1})\n\nIn the question the inputTuple value ended with 'comma' which will make it as tuple and if we remove that it will be...
[ 1, -1 ]
[]
[]
[ "dictionary", "key", "python", "tuples" ]
stackoverflow_0074472214_dictionary_key_python_tuples.txt
Q: Python Selenium `execute_cdp_cmd` only works at the first run I am trying to change device geolocation using Selenium Python (with Selenium wire to catch http requests) by: from seleniumwire import webdriver options = webdriver.EdgeOptions() options.accept_insecure_certs = True options.add_argument('--disable-bli...
Python Selenium `execute_cdp_cmd` only works at the first run
I am trying to change device geolocation using Selenium Python (with Selenium wire to catch http requests) by: from seleniumwire import webdriver options = webdriver.EdgeOptions() options.accept_insecure_certs = True options.add_argument('--disable-blink-features=AutomationControlled') driver = webdriver.Edge(selenium...
[ "Have you tried using Emulation.clearGeolocationOverride prior to calling Emulation.setGeolocationOverride?\nfrom seleniumwire import webdriver\n\noptions = webdriver.EdgeOptions()\noptions.accept_insecure_certs = True\noptions.add_argument('--disable-blink-features=AutomationControlled')\ndriver = webdriver.Edge(s...
[ 1 ]
[]
[]
[ "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074483259_python_selenium_selenium_webdriver.txt
Q: os.pipe() forcing me to write an input I have code in python which I modify the stdin and stderr, it work succesfuly but at the end of the program it asks for input (for the shell) python code: import os import subprocess stdin_read, stdin_write = os.pipe() stderr_read, stderr_write = os.pipe() os.write(stdin_wr...
os.pipe() forcing me to write an input
I have code in python which I modify the stdin and stderr, it work succesfuly but at the end of the program it asks for input (for the shell) python code: import os import subprocess stdin_read, stdin_write = os.pipe() stderr_read, stderr_write = os.pipe() os.write(stdin_write, b'\x00\x0a\x00\xff') os.write(stderr_wr...
[ "Notice the Python program ended before printing success -A and success -B. Apparently ./prog started, then Python ended, then ./prog printed its thing. The pipe still exists until all programs that have access to it close it (or end) so ./prog can still read the data from both pipes.\nYou typed the echo command in...
[ 1 ]
[]
[]
[ "c", "file_descriptor", "linux", "python" ]
stackoverflow_0074489387_c_file_descriptor_linux_python.txt
Q: How to access `ApplyResult` and `Event` types in the multiprocessing library I've written a working wrapper around the python multiprocessing code so I can easily start, clean up, and catch errors in my processes. I've recently decided to go back and add proper type hints to this code, however I can't figure out h...
How to access `ApplyResult` and `Event` types in the multiprocessing library
I've written a working wrapper around the python multiprocessing code so I can easily start, clean up, and catch errors in my processes. I've recently decided to go back and add proper type hints to this code, however I can't figure out how to use the types defined in multiprocessing correctly. I have a function which ...
[ "To resolve such issues with standard library, usually typeshed repo is useful enough. In mp __init__.py Event is defined as some attribute of context. Going to mp context.py, we find out that Event is defined as synchronize.Event, and in mp synchronize.py we finally find the class definition.\nThe issue with mp.po...
[ 1 ]
[]
[]
[ "multiprocessing", "mypy", "python", "python_typing" ]
stackoverflow_0074488948_multiprocessing_mypy_python_python_typing.txt
Q: I have a numpy array with the shape of 480x600, numpy complex numbers, there is a way to append it in a empty array which has more of these inside? Ok, so in this loop in a function of a class for oo in range(norient): ... for ss in range(nscale): filt=logGabor[ss]*spread This filt numpy array contains nu...
I have a numpy array with the shape of 480x600, numpy complex numbers, there is a way to append it in a empty array which has more of these inside?
Ok, so in this loop in a function of a class for oo in range(norient): ... for ss in range(nscale): filt=logGabor[ss]*spread This filt numpy array contains numpy complex numbers. So this filt numpy array has a shape of 480x600 and it would do it like 12 times, so I would like to have a numpy array with 12 valu...
[ "Numpy arrays aren't very good if the size constantly changes, instead collect into a list and convert to an array at the end:\nspecial = []\nfor oo in range(norient):\n …\n for ss in range(nscale):\n filt=logGabor[ss]*spread\n special.append(filt)\n\nspecial = np.array(special)\n\n" ]
[ 1 ]
[]
[]
[ "append", "arrays", "complex_numbers", "numpy", "python" ]
stackoverflow_0074489552_append_arrays_complex_numbers_numpy_python.txt
Q: Skulpt vs Trinket.io Python Version I'm confused. On http://skulpt.org/ it says, under "what's new?": Python 3 Grammar. The master branch is now building and running using the grammar for Python 3.7.3. There are still lots of things to implement under the hood, but we have made a huge leap forward in Python 3 com...
Skulpt vs Trinket.io Python Version
I'm confused. On http://skulpt.org/ it says, under "what's new?": Python 3 Grammar. The master branch is now building and running using the grammar for Python 3.7.3. There are still lots of things to implement under the hood, but we have made a huge leap forward in Python 3 compatibility. We will still support Python ...
[ "It looks like Trinket.io doesn't use Skulpt for Python 3 anymore. When you run a Python 3 code on Trinket.io it says \"Connecting to server\" which wouldn't be necessary with Skulpt.\n" ]
[ 0 ]
[]
[]
[ "embed", "python", "python_3.x", "skulpt" ]
stackoverflow_0074478932_embed_python_python_3.x_skulpt.txt
Q: Cartopy not able to Identify GEOS for PROJ install on Windows I am trying to install Cartopy on Windows. I have installed all the dependencies from their website, however when I go to run pip install Cartopy I get: Complete output (5 lines): setup.py:117: UserWarning: Unable to determine GEOS version. Ensure y...
Cartopy not able to Identify GEOS for PROJ install on Windows
I am trying to install Cartopy on Windows. I have installed all the dependencies from their website, however when I go to run pip install Cartopy I get: Complete output (5 lines): setup.py:117: UserWarning: Unable to determine GEOS version. Ensure you have 3.7.2 or later installed, or installation may fail. war...
[ "Installing Cartopy on Windows using pip is not trivial. Nevertheless, here is a cartopy installation overview using the method that worked for me, specifically for Windows and without using conda.\n\nStart by uninstalling proj, geos, and shapely if they are already installed, otherwise skip to step 2. This will fa...
[ 14, 0 ]
[ "Do yourself a favour and use conda (or even better mamba) to manage your package-dependencies!\n1 line and it will work out of the box in Windows, MacOS and Linux.\nconda install -c conda-forge cartopy\n\nManaging dependencies yourself is tedious and error-prone, especially when it comes to c or c++ dependencies (...
[ -4 ]
[ "cartopy", "geos", "pip", "proj", "python" ]
stackoverflow_0070177062_cartopy_geos_pip_proj_python.txt
Q: LibreOffice, Python, get-pip, pip imports ok but then? module is in LibreOffice sitelib folder Related questions: How update Libre Office Python on windows? Pyuno on Python 3.6 installation issue I have downloaded get-pip.py to my LibreOffice program folder, and used it to install pip. Using pip in that folder, I ...
LibreOffice, Python, get-pip, pip imports ok but then? module is in LibreOffice sitelib folder
Related questions: How update Libre Office Python on windows? Pyuno on Python 3.6 installation issue I have downloaded get-pip.py to my LibreOffice program folder, and used it to install pip. Using pip in that folder, I have installed pymodbus. pip list shows that pymodbus is installed for that version of python, in th...
[ "It turns out that, due to breaking changes in version 3.0 of pymodbus, the documentation at https://pymodbus-n.readthedocs.io/en/latest/readme.html#summary (Docs » PyModbus - A Python Modbus Stack, Summary) is not actually correct.\nAnd, of course, my reference implementation using Anaconda somehow got out of sync...
[ 0 ]
[]
[]
[ "pip", "python" ]
stackoverflow_0074484853_pip_python.txt
Q: Automated Messages in discord.py (discord bot) I'm programming a discord bot which should start some comands including a timer and two surveys every tuesday and thursday at 11.30 am. Unfortunately the documentary is outdated and older articles in stack overflow do not work anymore. How do I do that in Python or is...
Automated Messages in discord.py (discord bot)
I'm programming a discord bot which should start some comands including a timer and two surveys every tuesday and thursday at 11.30 am. Unfortunately the documentary is outdated and older articles in stack overflow do not work anymore. How do I do that in Python or is this impossible? The single commands are already pr...
[ "Actually , This Option Can't Be Added With Discord.py .\nYou Should Use Time Or Datetime Modules . \nTo Manage Scripts At The Correct Times .\nCheck This Article !\n", "I got my soultion. I worked with apscheduler and now I can time it for days and times.\nThis can be closed.\n" ]
[ 0, 0 ]
[]
[]
[ "automation", "bots", "discord", "discord.py", "python" ]
stackoverflow_0074430312_automation_bots_discord_discord.py_python.txt
Q: Get tables from AWS Glue using boto3 I need to harvest tables and column names from AWS Glue crawler metadata catalogue. I used boto3 but constantly getting number of 100 tables even though there are more. Setting up NextToken doesn't help. Please help if possible. Desired results is list as follows: lst = [table_...
Get tables from AWS Glue using boto3
I need to harvest tables and column names from AWS Glue crawler metadata catalogue. I used boto3 but constantly getting number of 100 tables even though there are more. Setting up NextToken doesn't help. Please help if possible. Desired results is list as follows: lst = [table_one.col_one, table_one.col_two, table_two....
[ "You can try the below approach by using the paginator option:\ndef get_tables_for_database(database):\n starting_token = None\n next_page = True\n tables = []\n while next_page:\n paginator = glue_client.get_paginator(operation_name=\"get_tables\")\n response_iterator = paginator.paginate...
[ 2, 1, 0, 0 ]
[]
[]
[ "amazon_web_services", "aws_glue", "boto3", "pyspark", "python" ]
stackoverflow_0066545190_amazon_web_services_aws_glue_boto3_pyspark_python.txt
Q: Is there a workaround to prevent Gmail API for python from asking for a new token each time I run my python script? I have a python script that sends emails with attachments using GMAIL's API. Each time(mostly after a day) I run the script, I get an error that the token's invalid. The only solution I have identifi...
Is there a workaround to prevent Gmail API for python from asking for a new token each time I run my python script?
I have a python script that sends emails with attachments using GMAIL's API. Each time(mostly after a day) I run the script, I get an error that the token's invalid. The only solution I have identified so far is to download the json file each time I run the script but I was expecting this to be done only once as I inte...
[ "Google sends you an authToken and a RefreshToken, who need to be stored to refresh your token when he is no longer valid.\nCheck that :\nhttps://developers.google.com/identity/protocols/oauth2\n", "There are two types of tokens access tokens and refresh tokens.\nAccess tokens are only good for an hour. Refresh ...
[ 0, 0 ]
[]
[]
[ "api", "gmail", "python" ]
stackoverflow_0074488359_api_gmail_python.txt
Q: Client get message from server using asyncio in python We are trying to use asyncio to run a straightforward client/server. The server is an echo server with two possible commands sent by the client, "quit" and "timer". The timer command starts a timer that will print a message in the console every second (at the ...
Client get message from server using asyncio in python
We are trying to use asyncio to run a straightforward client/server. The server is an echo server with two possible commands sent by the client, "quit" and "timer". The timer command starts a timer that will print a message in the console every second (at the server and client), and the quit command closes the connecti...
[ "The client blocks on the input() function. This question is similar to server stop receiving msg after 1 msg receive\n", "Finally, I found a possible solution, by separating the thread.\nimport asyncio\nimport websockets\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nasync def send_msg(websocket):\n ...
[ 2, 1, 0 ]
[]
[]
[ "python", "python_asyncio" ]
stackoverflow_0074468560_python_python_asyncio.txt
Q: TypeError: list indices must be integers or slices, not str - dealing with dataframes I'm having the error below with a project and looked for some explanation (like this page) and I get the cause of the error. But I couldn't figure out what might be the problem in this case. Traceback (most recent call last): F...
TypeError: list indices must be integers or slices, not str - dealing with dataframes
I'm having the error below with a project and looked for some explanation (like this page) and I get the cause of the error. But I couldn't figure out what might be the problem in this case. Traceback (most recent call last): File "c:\Users\luisa.oliveira\Programs\VScode\dashboard-ecg-atualizado\app\views\dashboard.p...
[ "Global variables can be accessed inside of functions as long as they are on the right side of an assignment:\n# Global variable\nx = 3\n\ndef fun():\n # assign value of global variable x to local variable y\n y = x\n\nIf, however you have a variable with the same name of a global variable on the left side of a...
[ 0 ]
[]
[]
[ "callback", "list", "pandas", "plotly_dash", "python" ]
stackoverflow_0074478000_callback_list_pandas_plotly_dash_python.txt
Q: Set two colors for a point of a matplotlib-scatter plot So Realising that this may not possible. What I want to do, looks something like this: point_x = [1] point_y = [1] col1 = ['blue'] col2 = ['red'] plt.scatter(point_x,point_y, c=col1,marker='o') plt.scatter(point_x,point_y, c=col2,marker=donut?) This ...
Set two colors for a point of a matplotlib-scatter plot
So Realising that this may not possible. What I want to do, looks something like this: point_x = [1] point_y = [1] col1 = ['blue'] col2 = ['red'] plt.scatter(point_x,point_y, c=col1,marker='o') plt.scatter(point_x,point_y, c=col2,marker=donut?) This would represent one point, where a portion of the (let's say)...
[ "maybe specifiying the point size s would help\nfrom matplotlib import pyplot as plt\n\npoint_x = 1\npoint_y = 1\n\ncol1 = ['blue']\ncol2 = ['red']\n\nplt.scatter(point_x, point_y, c=col1, marker='o', s=1000)\nplt.scatter(point_x, point_y, c=col2, marker='o', s=500)\nplt.show()\n\noutput\n\n" ]
[ 1 ]
[]
[]
[ "matplotlib", "python", "scatter_plot" ]
stackoverflow_0074489736_matplotlib_python_scatter_plot.txt
Q: best way to subtract mean monthly values for each grid in Python xarray A toy dataset from here: import numpy as np import pandas as pd import seaborn as sns import xarray as xr np.random.seed(123) xr.set_options(display_style="html") times = pd.date_range("2000-01-01", "2001-12-31", name="time") annual_cycle ...
best way to subtract mean monthly values for each grid in Python xarray
A toy dataset from here: import numpy as np import pandas as pd import seaborn as sns import xarray as xr np.random.seed(123) xr.set_options(display_style="html") times = pd.date_range("2000-01-01", "2001-12-31", name="time") annual_cycle = np.sin(2 * np.pi * (times.dayofyear.values / 365.25 - 0.28)) base = 10 + 1...
[ "I think that you might be looking for is this:\nanomalies = xr.apply_ufunc(\n lambda x, mean: x - mean, \n ds.tmax.groupby('time.month'),\n ds.tmax.groupby('time.month').mean()\n).drop('month')\n\nfor just the tmax variable (a DataArray) or\nanomalies = xr.apply_ufunc(\n lambda x, means: x - means, \n ...
[ 1 ]
[]
[]
[ "python", "python_xarray" ]
stackoverflow_0066903278_python_python_xarray.txt
Q: subprocess problem with PyDub: Python 3.63 v Python 3.10 Until recently I've been using python 3.63. When I need to use Pydub's audio_segment I do it like this to avoid a flash of the console when the app is frozen in a pyinstaller exe: subprocess.STARTUPINFO.dwFlags |= subprocess.STARTF_USESHOWWINDOW audio = Audi...
subprocess problem with PyDub: Python 3.63 v Python 3.10
Until recently I've been using python 3.63. When I need to use Pydub's audio_segment I do it like this to avoid a flash of the console when the app is frozen in a pyinstaller exe: subprocess.STARTUPINFO.dwFlags |= subprocess.STARTF_USESHOWWINDOW audio = AudioSegment.from_file('path_to_file') Since moving to Python 3.1...
[ "I finally got to the bottom of this.\nA module of pydub called utils.py contains a couple of subprocess calls. I changed the calls from:\ncommand = [prober] + command_args\noutput = Popen(command, stdout=PIPE).communicate([0].decode(\"utf-8\")\n\nTo:\ncommand = [prober] + command_args\nstartupinfo = subprocess.STA...
[ 1 ]
[]
[]
[ "pydub", "python", "subprocess" ]
stackoverflow_0074448497_pydub_python_subprocess.txt
Q: How to get ALL (or multiple) pair's historical klines from Binance API in ONE request? I have a trading bot that trades multiple pairs (30-40). It uses the previous 5m candle for the price input. Therefore, I get 5m history for ALL pairs one by one. Currently, the full cycle takes about 10 minutes, so the 5m candl...
How to get ALL (or multiple) pair's historical klines from Binance API in ONE request?
I have a trading bot that trades multiple pairs (30-40). It uses the previous 5m candle for the price input. Therefore, I get 5m history for ALL pairs one by one. Currently, the full cycle takes about 10 minutes, so the 5m candles get updated once in 10m, which is no good. Any ideas on how to speed things up?
[ "I think the best option for you will be websocket connection. You cannot recieve kline data once per eg. 5 minutes, but you can recieve every change in candle like you see it in graph. Binance API provide only this, but in compound with websocket connection it will by realy fast, not 10 minutes.\nAfter recieve dat...
[ 10, 1, 0 ]
[]
[]
[ "algorithmic_trading", "api", "binance", "python", "trading" ]
stackoverflow_0063515267_algorithmic_trading_api_binance_python_trading.txt
Q: Error while targeting a Julia function into multiprocessing.Process of Python I am trying to parallelize a code in python by using multiprocessing.Process which targets a Julia function. The function works fine when I call it directly, i.e. when I execute: if __name__ == "__main__": import julia julia.Jul...
Error while targeting a Julia function into multiprocessing.Process of Python
I am trying to parallelize a code in python by using multiprocessing.Process which targets a Julia function. The function works fine when I call it directly, i.e. when I execute: if __name__ == "__main__": import julia julia.Julia(compiled_modules=False) julia.Pkg_jl.func_jl(*args) However, I have an err...
[ "I finally solved the error.\nThe syntaxis is not the problem, but the instance on which Julia packages are precompiled.\nIn the first code, the error is in the call [Jl]:\njulia.Julia(compiled_modules=False)\n\njust before Julia is imported.\nThe second code works fine since the expression [Jl] is precompiled in t...
[ 0 ]
[]
[]
[ "julia", "multiprocessing", "pycall", "python" ]
stackoverflow_0074438358_julia_multiprocessing_pycall_python.txt
Q: How to use pytest-custom_exit_code plugin Need help! I have a job on Gitlab ci, that runs tests and reruns failed ones. If there are no failed tests, job fails with exit code 5, that means that there are no tests for running. I found out that there is plugin "pytest-custom_exit_code", but I don't know how to corr...
How to use pytest-custom_exit_code plugin
Need help! I have a job on Gitlab ci, that runs tests and reruns failed ones. If there are no failed tests, job fails with exit code 5, that means that there are no tests for running. I found out that there is plugin "pytest-custom_exit_code", but I don't know how to correctly use it. I need just to add command 'pytes...
[ "Assumption here is that plugin is installed first using\npip install pytest-custom_exit_code\n\ncommand like option pytest --suppress-no-test-exit-code should work after that.\nIf configuration file like .pytest.ini is used , following lines should be added in it\n[pytest]\naddopts = --suppress-no-test-exit-code\n...
[ 0 ]
[]
[]
[ "pytest", "python" ]
stackoverflow_0073091711_pytest_python.txt
Q: Seaborn Boxplot with jittered outliers I want a Boxplot with jittered outliers. But only the outliers not the non-outliers. Searching the web you often find a workaround combining sns.boxplot() and sns.swarmplot(). The problem with that figure is that the outliers are drawn twice. I don't need the red ones I only...
Seaborn Boxplot with jittered outliers
I want a Boxplot with jittered outliers. But only the outliers not the non-outliers. Searching the web you often find a workaround combining sns.boxplot() and sns.swarmplot(). The problem with that figure is that the outliers are drawn twice. I don't need the red ones I only need the jittered (green) ones. Also the no...
[ "Here is an approach to have jittered outliers. The jitter is similar to sns.stripplot(), not to sns.swarmplot() which uses a rather elaborate spreading algorithm. Basically, all the \"line\" objects of the subplot are checked whether they have a marker. The x-positions of the \"lines\" with a marker are moved a b...
[ 3 ]
[]
[]
[ "python", "seaborn" ]
stackoverflow_0074488328_python_seaborn.txt
Q: Remove white space plot matplotlib I'm trying to get something like this: with this code x = np.arange(l, r, s) y = np.arange(b, t, s) X, Y = np.meshgrid(x, y) Z = f(X,Y) plt.axis('equal') plt.pcolormesh(X, Y, Z) plt.savefig("image.png",dpi=300) But I get this: How could I remove the white regions? I really ap...
Remove white space plot matplotlib
I'm trying to get something like this: with this code x = np.arange(l, r, s) y = np.arange(b, t, s) X, Y = np.meshgrid(x, y) Z = f(X,Y) plt.axis('equal') plt.pcolormesh(X, Y, Z) plt.savefig("image.png",dpi=300) But I get this: How could I remove the white regions? I really appreciate any kind of help.
[ "i would use the pyplot subplots to define the figures size and therefor aspect like this\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\ndef f(x,y):\n return x + y\n\nx = np.arange(1, 10, .1)\ny = np.arange(1, 10, .1)\nX, Y = np.meshgrid(x, y)\nZ = f(X,Y)\n\n\nf, ax = plt.subplots(figsize=(4, 4))\n...
[ 1 ]
[ "Anwered here You can remove the margins at the edges of the plot.\nplt.margins(x=0)\n\n" ]
[ -1 ]
[ "matplotlib", "plot", "python" ]
stackoverflow_0074489519_matplotlib_plot_python.txt
Q: for loop append in a list, but the input is a data frame I have a bit python code below. Just an example to show the problem: I would like to select some lines in a data frame basing on some values. Somehow this needs to be in a for loop, and I used .append() to add each selection of rows into a final file. But th...
for loop append in a list, but the input is a data frame
I have a bit python code below. Just an example to show the problem: I would like to select some lines in a data frame basing on some values. Somehow this needs to be in a for loop, and I used .append() to add each selection of rows into a final file. But the result is not the same as what I expected. I learned by read...
[ "Your code just recreates the same list you had before, you can just use pd.concat instead, to write it to a frame you have to convert it to a str first:\nimport pandas as pd\n\ndf = pd.DataFrame({'a': [4, 5, 6, 7], 'b': [10, 20, 30, 40], 'c': [100, 50, -30, -50]})\ndf['diff'] = (df['b'] - df['c']).abs()\n# print(d...
[ 0 ]
[]
[]
[ "loops", "pandas", "python" ]
stackoverflow_0074490019_loops_pandas_python.txt
Q: UpdateOrAdd() changes to Pandas DataFrame Hi I'm wondering what is the fastest, most easy way to AddOrUpdate data in a Pandas DataFrame import pandas as pd # Original DataFrame pd.DataFrame([ {'A':'a1','B':'b1','C':'c1'}, {'A':'a3','B':'b2','C':'c2'}, {'A':'a3','B':'b3','C':'c3'}, ]) ...
UpdateOrAdd() changes to Pandas DataFrame
Hi I'm wondering what is the fastest, most easy way to AddOrUpdate data in a Pandas DataFrame import pandas as pd # Original DataFrame pd.DataFrame([ {'A':'a1','B':'b1','C':'c1'}, {'A':'a3','B':'b2','C':'c2'}, {'A':'a3','B':'b3','C':'c3'}, ]) Original DataFrame : A B C 0 a1 b...
[ "You can use craft a DataFrame from the dictionary, then align the indices with reindex and combine_first:\ndf2 = pd.DataFrame(changes).set_index('id')\n\nout = (df2.reindex(df.index.union(df2.index))\n .combine_first(df)\n )\n\nOutput:\n A B C\n0 aNEW b1 cNEW\n1 a3 b2 c2\n2...
[ 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074490151_pandas_python.txt
Q: How to prevent pandas datafram columns from moving to new line in colab? I'm working in colab and created a dataframe using this code: def daily_sma(): symbol = 'BTCUSDT' num_bars = 70 timeframe = '1d' bars = exchange.fetch_ohlcv(symbol, timeframe = timeframe, limit = num_bars) df_d = pd.DataFrame(ba...
How to prevent pandas datafram columns from moving to new line in colab?
I'm working in colab and created a dataframe using this code: def daily_sma(): symbol = 'BTCUSDT' num_bars = 70 timeframe = '1d' bars = exchange.fetch_ohlcv(symbol, timeframe = timeframe, limit = num_bars) df_d = pd.DataFrame(bars, columns = ['timestamp', 'open', 'high', 'low', 'close', 'volume']) df_d[...
[ "You can print with to_string:\nprint(df.to_string())\n\n# to set a larger, yet not unlimited width\n# print(df.to_string(line_width=200))\n\nIf you want a permanent change, defined in terms of number of characters:\npd.set_option('display.width', 200)\nprint(df)\n\nExample:\ndf = pd.DataFrame(columns=[f'column_{x}...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074490203_dataframe_pandas_python.txt
Q: Calculating height and width of a bounding box in Yolov5 Currently I am working with Yolov5 and I have done training and validation on custom dataset and the results are quite impressive. Now I want to calculate the height and width of the object(bounding box) and present it on screen just like confidence score. I...
Calculating height and width of a bounding box in Yolov5
Currently I am working with Yolov5 and I have done training and validation on custom dataset and the results are quite impressive. Now I want to calculate the height and width of the object(bounding box) and present it on screen just like confidence score. In Yolov5 there's one option to save the cordinates of a boundi...
[ "You have to first understand how the bounding boxes are encoded by the YOLOv7 framework. There are several ways coordinates could be stored.\nFirst, bounding box coordinates are usually expressed in the image coordinate system. The most common one has its origin in the top-left image corner and the axes (X, Y) are...
[ 1 ]
[]
[]
[ "object_detection", "python", "yolo" ]
stackoverflow_0074489223_object_detection_python_yolo.txt
Q: Get the YouTube video title by its url using python I want to get the title of a youtube video by url. I have been searching for several days but I did not get the result I have been searching for several days but I did not get the result A: By using requests and Beautiful Soup libraries you can achieve that: im...
Get the YouTube video title by its url using python
I want to get the title of a youtube video by url. I have been searching for several days but I did not get the result I have been searching for several days but I did not get the result
[ "By using requests and Beautiful Soup libraries you can achieve that:\nimport requests\nfrom bs4 import BeautifulSoup\n\nr = requests.get(\"https://www.youtube.com/watch?v=9sg-A-eS6Ig&list=RDBAkqJT_sMKQ&index=5\")\nsoup = BeautifulSoup(r.text)\n\nlink = soup.find_all(name=\"title\")[0]\ntitle = str(link)\ntitle = t...
[ 1 ]
[]
[]
[ "extract", "python", "search", "url", "youtube" ]
stackoverflow_0074490036_extract_python_search_url_youtube.txt