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: Grouping samples for snakemake workflow I have a data table which is formatted as following: | Read1 | Read2 | Group | SampleID | | ---------- | ---------- | ----- | -------- | | file.fq.gz | file.fq.gz | 1 | 1.1 | | file.fq.gz | file.fq.gz | 2 | 2.1 | | file.fq.gz | file.fq.gz | 3 ...
Grouping samples for snakemake workflow
I have a data table which is formatted as following: | Read1 | Read2 | Group | SampleID | | ---------- | ---------- | ----- | -------- | | file.fq.gz | file.fq.gz | 1 | 1.1 | | file.fq.gz | file.fq.gz | 2 | 2.1 | | file.fq.gz | file.fq.gz | 3 | 3.1 | | file.fq.gz | file.fq.gz | 2 ...
[ "It's hard to tell without more detail about what you need to do. Maybe something along these lines?\nrule all:\n input:\n expand('{group}.txt', group=[1, 2, 3]),\n\nrule one:\n output:\n '{group}.txt',\n run:\n subset = df[df['Group'] == wildcards.group]\n analyze_subset_etc(su...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "snakemake" ]
stackoverflow_0074147561_dataframe_pandas_python_snakemake.txt
Q: How can I add reshape layer in nn.Sequential? So I'm implementing Generator of a GAN and I need the architecture as shown as below: The problem is when I try to reshape the output of Linear layer after BatchNorm and ReLU (in fig. Dense as they have used Tensorflow) it is throwing error as :TypeError: reshape(): a...
How can I add reshape layer in nn.Sequential?
So I'm implementing Generator of a GAN and I need the architecture as shown as below: The problem is when I try to reshape the output of Linear layer after BatchNorm and ReLU (in fig. Dense as they have used Tensorflow) it is throwing error as :TypeError: reshape(): argument 'input' (position 1) must be Tensor, not in...
[ "\nIn nn.Sequential, torch.nn.Unflatten() can help you achieve reshape operation.\n\nFor nn.Linear, its input shape is (N, *, H_{in}) and output shape is (H, *, H_{out}). Note that the feature dimension is last. So unsqueeze_noise() is not useful here.\n\nBased on the network structure, the arguments passed to make...
[ 1 ]
[]
[]
[ "conv_neural_network", "deep_learning", "generative_adversarial_network", "python", "pytorch" ]
stackoverflow_0074149053_conv_neural_network_deep_learning_generative_adversarial_network_python_pytorch.txt
Q: Flask App Error while deploying to Heroku at=error code=H10 desc="App crashed" method=GET path="/". I'm using Python 3 The sample flask app is giving error at=error code=H10 desc="App crashed" method=GET path="/" while deploying in Heroku. I changed the Procfile as many times as I got an error, but there are no be...
Flask App Error while deploying to Heroku at=error code=H10 desc="App crashed" method=GET path="/". I'm using Python 3
The sample flask app is giving error at=error code=H10 desc="App crashed" method=GET path="/" while deploying in Heroku. I changed the Procfile as many times as I got an error, but there are no better results. run.py import os from flask_minify import Minify from apps import create_app app = create_app() DEBUG = ap...
[ "I think your issue is in the Procfile.\nTry changing it to:\nweb: gunicorn --bind 0.0.0.0:$PORT flaskapp:app\n\nAnother useful command would be:\nweb: gunicorn flaskapp.wsgi --log-file-\n\nLet me know if this helped. Most of the times, this error is caused by a misconfigured Procfile. I'd suggest you definitely lo...
[ 0 ]
[]
[]
[ "flask", "heroku", "python", "python_3.x" ]
stackoverflow_0074148366_flask_heroku_python_python_3.x.txt
Q: How to get non-bar SHAP plot for LightGBM I have trained a lightGBM model using this code: from flaml import AutoML #Select Hyper-Parameters automl_final = AutoML() automl_final.fit( X_train, y_train, estimator_list=["lgbm"],#,"xgboost"], task="classification", metric="roc_auc", eval_m...
How to get non-bar SHAP plot for LightGBM
I have trained a lightGBM model using this code: from flaml import AutoML #Select Hyper-Parameters automl_final = AutoML() automl_final.fit( X_train, y_train, estimator_list=["lgbm"],#,"xgboost"], task="classification", metric="roc_auc", eval_method="cv", n_splits=3, time_budget=30,...
[ "shap.plots.beeswarm(shap_values)\n\nPlease check the documentation if needed.\n" ]
[ 1 ]
[]
[]
[ "lightgbm", "plot", "python", "shap" ]
stackoverflow_0074130997_lightgbm_plot_python_shap.txt
Q: How to schedule the data pipeline to run on first Tuesday each month and then 5 days later during night time cet using cron expression I wanted to create a cron job that runs on first Tuesday every month and then 5 days later of first Tuesday at Night time cet. A: Tuesday is day_of_the_week 2, and the first week...
How to schedule the data pipeline to run on first Tuesday each month and then 5 days later during night time cet using cron expression
I wanted to create a cron job that runs on first Tuesday every month and then 5 days later of first Tuesday at Night time cet.
[ "Tuesday is day_of_the_week 2, and the first week is days 1-7 of the month. Then 5 days later is a Sunday, normally day 0 (but sometimes day 7). This will run the task at 20:00 on the local system time on those days.\n0 20 1-7 * 2 run_some_job\n0 20 6-12 * 0 run_some_job\n\n", "// Using the cron configs provid...
[ 4, 3 ]
[]
[]
[ "palantir_foundry", "python", "sql" ]
stackoverflow_0074148922_palantir_foundry_python_sql.txt
Q: How to refer to a randomised choice How do I refer to a randomised choice? I want the program to print and speak the same choice it made from the list. Code so far: speaklist = ["wassup", "hello", "how do I help?"] speak(random.choice(speaklist)) I want to add a: print(same thing it had chosen from the list) A: ...
How to refer to a randomised choice
How do I refer to a randomised choice? I want the program to print and speak the same choice it made from the list. Code so far: speaklist = ["wassup", "hello", "how do I help?"] speak(random.choice(speaklist)) I want to add a: print(same thing it had chosen from the list)
[ "You use random correctly, you just need to assign it to variable first:\nspeaklist = [\"wassup\", \"hello\", \"how do I help?\"] \nword = random.choice(speaklist)\nspeak(word)\nprint(word)\n\nAs a curiosity, you can use seed too:\nimport random\n\nspeaklist = [\"wassup\", \"hello\", \"how do I help?\"]\nrandom.see...
[ 1 ]
[]
[]
[ "python", "random" ]
stackoverflow_0074150061_python_random.txt
Q: How to correctly add type hints to a decorator? I'm currently writing and learning about decorators (with and without arguments). Here is an example of a decorator with one argument that redirects the output of a function to a log file. The code works, but my questions are the following: What is the correct way t...
How to correctly add type hints to a decorator?
I'm currently writing and learning about decorators (with and without arguments). Here is an example of a decorator with one argument that redirects the output of a function to a log file. The code works, but my questions are the following: What is the correct way to use type hints when dealing with decorators? Are de...
[ "ParamSpec is a solution to this problem.\nHere is the code example\nin its document.\nfrom typing import TypeVar, ParamSpec\nimport logging\n\nT = TypeVar('T')\nP = ParamSpec('P')\n\ndef add_logging(f: Callable[P, T]) -> Callable[P, T]:\n '''A type-safe decorator to add logging to a function.'''\n def inner(...
[ 0 ]
[]
[]
[ "python", "python_decorators", "type_hinting" ]
stackoverflow_0057890734_python_python_decorators_type_hinting.txt
Q: How to solve pylint (too-many-return-statements) elegantly? The example of too-many-return-statements is as above, but my scenario is as follows, how to make the function more beautiful? def func(): # do something1 ret1 = do_something1() if ret1 != 0: return ret1 # do something2 ret2 =...
How to solve pylint (too-many-return-statements) elegantly?
The example of too-many-return-statements is as above, but my scenario is as follows, how to make the function more beautiful? def func(): # do something1 ret1 = do_something1() if ret1 != 0: return ret1 # do something2 ret2 = do_something2() if ret2 != 0: return ret2 # ......
[ "You could try something like this:\ndef foo(x):\n nums = ['one','two','three','four','five','six','seven']\n return 'This is ' + nums[x-1]\n\nto solve your example. And you could solve your scenario like this:\ndef func():\n functions = [do_something1,do_something2,...]\n for function in functions:\n ...
[ 3, 2, 0, 0, 0 ]
[]
[]
[ "pylint", "python" ]
stackoverflow_0072024229_pylint_python.txt
Q: How to order and index the column in a dataframe? I am thinking a way to order the data frame and create a column to sort the order. For example: df = pd.DataFrame({'YYYYMM':[202206,202207,202206,202209,202206,202207]}) YYYYMM 0 202206 1 202207 2 202206 3 202209 4 202206 5 202207 Then I tried to order it...
How to order and index the column in a dataframe?
I am thinking a way to order the data frame and create a column to sort the order. For example: df = pd.DataFrame({'YYYYMM':[202206,202207,202206,202209,202206,202207]}) YYYYMM 0 202206 1 202207 2 202206 3 202209 4 202206 5 202207 Then I tried to order it by using numpy df['order'] = np.argsort(df['YYYYMM']) ...
[ "Use Series.rank with method='dense', convert to integers and subtract 1:\ndf['order'] = df['YYYYMM'].rank(method='dense').astype(int).sub(1)\nprint (df)\n YYYYMM order\n0 202206 0\n1 202207 1\n2 202206 0\n3 202209 2\n4 202206 0\n5 202207 1\n\n", "Use rank with the method='d...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074150114_pandas_python.txt
Q: Keeping user logged in after changing password (Django) custom user model I have a customized Django model. My problem is whenever I update any of the user profile information, it logged out. I know that Django logged out the user after changing their password and I have to use update_session_auth_hash() function....
Keeping user logged in after changing password (Django) custom user model
I have a customized Django model. My problem is whenever I update any of the user profile information, it logged out. I know that Django logged out the user after changing their password and I have to use update_session_auth_hash() function. However, in my case it didn't work and I don't want to use Django changePasswo...
[ "The problem is that the change of the password will make the session invalid.\nSee doc\nYou could also heredity the django change password form for your own form.\n", "You could do something like this.\nTemplate:\n<form method=\"POST\" class=\"contact-form\" action=\"{% url 'change-password' %}\"> ##make sure th...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0066965055_django_python.txt
Q: Can't install pyrealsense2 on Windows 10 using pip I tried to install pyrealsense2 using pip in VS Code with the command pip install pyrealsense2. However, VS Code prints following error: ERROR: Could not find a version that satisfies the requirement pyrealsense2 (from versions: none) ERROR: No matching distributi...
Can't install pyrealsense2 on Windows 10 using pip
I tried to install pyrealsense2 using pip in VS Code with the command pip install pyrealsense2. However, VS Code prints following error: ERROR: Could not find a version that satisfies the requirement pyrealsense2 (from versions: none) ERROR: No matching distribution found for pyrealsense2 I am using Windows 10 and Pyt...
[ "Python libraries are install through the windows powershell or CMD,\nRun CMD, then paste this command\npip install pyrealsense2\n\nthen press enter, wait for it to install. Once it is done just restart VS Code\n", "pyrealsense2 is only available up to Python version 3.9 See https://pypi.org/project/pyrealsense2/...
[ 0, 0 ]
[]
[]
[ "computer_vision", "opencv", "pip", "python" ]
stackoverflow_0073472085_computer_vision_opencv_pip_python.txt
Q: How to eliminate values in a DOB result in such a way that each part of it doesn't contain more than the required number of digits? The DOB contains three parts, for example as shown below: 11/012/1992 The desired DOB output for the above example should be as follows: 11/12/1992 So, basically the code should eli...
How to eliminate values in a DOB result in such a way that each part of it doesn't contain more than the required number of digits?
The DOB contains three parts, for example as shown below: 11/012/1992 The desired DOB output for the above example should be as follows: 11/12/1992 So, basically the code should eliminate the values in such a way that: If the first part till the '/' contains more than 2 digits, the first one has to be eliminated. If...
[ "You can use str.replace to remove the unwanted parts:\n# option 1, just remove the extra digits\ndf['DOB2'] = df['DOB'].str.replace(r'^.*?(\\d{1,2}/).*?(\\d{1,2}/).*?(\\d{4})$', r'\\1\\2\\3')\n\n# option 2, also pad the missing digits\ndf['DOB3'] = (pd.to_datetime(df['DOB'].str.replace(r'^.*?(\\d{1,2}/).*?(\\d{1,2...
[ 0 ]
[]
[]
[ "logic", "pandas", "python", "string" ]
stackoverflow_0074150018_logic_pandas_python_string.txt
Q: Display values of json returned by python file in html webpage seperately I am making a webapp for OCR on document with layoutlm using flask, website has upload system that accepts images and documents which are later processed by a python file for OCR which returns a JSON containing 'key' as field name like 'Name...
Display values of json returned by python file in html webpage seperately
I am making a webapp for OCR on document with layoutlm using flask, website has upload system that accepts images and documents which are later processed by a python file for OCR which returns a JSON containing 'key' as field name like 'Name', 'DOB' and value as corresponding answer to the field as 'Akshit', '17/02/200...
[ "It's difficult to diagnose exactly what your issue is as you didn't explain what output you're getting (error message? no content showing?), but the issue appears to be in the way you're trying to use the jinja template, in particular in the line:\n{% with messages = get_flashed_messages() %}\n\nWhat is get_flashe...
[ 0 ]
[]
[]
[ "flask", "html", "python" ]
stackoverflow_0074148661_flask_html_python.txt
Q: Appending to xml content Python I have this xml file. I just want to append another row to each country tag like below. I want the change to be modifies in existing country_data.xml file **<population>2318921212</population>** The xml file I have <?xml version="1.0"?> <data> <country name="Liechtenstein">...
Appending to xml content Python
I have this xml file. I just want to append another row to each country tag like below. I want the change to be modifies in existing country_data.xml file **<population>2318921212</population>** The xml file I have <?xml version="1.0"?> <data> <country name="Liechtenstein"> <rank>&copy;1</rank> ...
[ "You need to use ET.SubElement for each country to get the population into the right spot. \nAs a bonus, I have added some extra code to get the formatting of the XML correct. There is probably a better way to do this but, at least this method works.\nimport xml.etree.ElementTree as ET\nimport xml.dom.minidom as md...
[ 0 ]
[]
[]
[ "lxml", "python", "python_3.x", "xml", "xml_parsing" ]
stackoverflow_0074148224_lxml_python_python_3.x_xml_xml_parsing.txt
Q: How to extract number before specific text with regular expression? I try to extract the number before some specific text. So I have this long string: verdi = "['a= (>)\n\nFactuur\nVerdi Import Schoolfruit\nFactuur nr; %: 70273 Koopliedenweg 38\nDeb. nr. : 108636 2991 LN BARENDRECHT\nYour VAT nr. : NL851703884B01 ...
How to extract number before specific text with regular expression?
I try to extract the number before some specific text. So I have this long string: verdi = "['a= (>)\n\nFactuur\nVerdi Import Schoolfruit\nFactuur nr; %: 70273 Koopliedenweg 38\nDeb. nr. : 108636 2991 LN BARENDRECHT\nYour VAT nr. : NL851703884B01 Nederland\nFactuur datum : 19-11-21\nAantal Omschrijving Prijs Bedrag\nOr...
[ "You forgot the | in the regular expression.\nimport re\n\nverdi = \"['a= (>)\\n\\nFactuur\\nVerdi Import Schoolfruit\\nFactuur nr; %: 70273 Koopliedenweg 38\\nDeb. nr. : 108636 2991 LN BARENDRECHT\\nYour VAT nr. : NL851703884B01 Nederland\\nFactuur datum : 19-11-21\\nAantal Omschrijving Prijs Bedrag\\nOrder number...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074123604_python.txt
Q: How do concatenate two generator object before model fit? I want to normalize the training and validation images with one generator, and get new images from the training and validation views with the other generator. Then I want to combine and train them separately. How can I do this merge operation? I'm getting a...
How do concatenate two generator object before model fit?
I want to normalize the training and validation images with one generator, and get new images from the training and validation views with the other generator. Then I want to combine and train them separately. How can I do this merge operation? I'm getting an error. ValueError: Layer model expects 1 input(s), but it rec...
[ "I found similar question/answer on stackoverflow as below:\nHow to join two generators in Python?\nThis solution has worked for me:\n# Images generator for training set (Base without Augmented Data)\ntrain_data_generator_Base = ImageDataGenerator(preprocessing_function = preprocess_input) # data preproces...
[ 1, 0 ]
[]
[]
[ "generator", "python" ]
stackoverflow_0070167797_generator_python.txt
Q: How to access MySQL Database on a Bluehost server remotely through Python I currently have a Python connector script that I run on my Bluehost server locally. In the past, I've tried to run this script remotely, i.e. login remotely with the Python script on my own local machine, but I ended up just running it on t...
How to access MySQL Database on a Bluehost server remotely through Python
I currently have a Python connector script that I run on my Bluehost server locally. In the past, I've tried to run this script remotely, i.e. login remotely with the Python script on my own local machine, but I ended up just running it on the server. In my current situation, I need to run a script every 10 minutes on ...
[ "You have to enable access for the IP address of the computer you are trying to access the server from. By default the database server doesn't allow outside connections. You'll do this by logging into your host (Bluehost)\n\nLog into cPanel and click the Remote MySQL icon, under Databases.\nType in the connecting I...
[ 3, 1 ]
[]
[]
[ "mysql", "python", "shared_hosting" ]
stackoverflow_0034910432_mysql_python_shared_hosting.txt
Q: Iterating through a List of dictionaries in python I have a list and in that list there are multiple records of dictionaries. I want to create a new list with some of the dictionaries in my previous list. for example, s_dict = [{'cs':'10', 'ca':'11', 'cb':'12', 'cc':'same'}, {'cs':'114', 'ca':'121','cb':'132', 'cc...
Iterating through a List of dictionaries in python
I have a list and in that list there are multiple records of dictionaries. I want to create a new list with some of the dictionaries in my previous list. for example, s_dict = [{'cs':'10', 'ca':'11', 'cb':'12', 'cc':'same'}, {'cs':'114', 'ca':'121','cb':'132', 'cc':'diff'}, {'cs':'20', 'ca':'21', 'cb':'22', 'cc':'same'...
[ "new = [i for i in s_dict if ('cc','same') in i.items()]\n\n", "In your code you can change\nres = []\nfor dic in s_dict:\n for val,cal in dic.items():\n if cal == 'same':\n res.append(dic)\nprint(res)\n# [{'cs': '10', 'ca': '11', 'cb': '12', 'cc': 'same'}, {'cs': '20', 'ca': '21', 'cb': '22'...
[ 0, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074150009_dictionary_list_python.txt
Q: How to add columns with "a" in the field name This above is a simple example I want to add the data which columns with "a" df['a+abc+bca'] = df[['a', 'abc','bca']].sum(axis=1) Although this method can be counted successfully, it is not very flexible, because if I have many columns whose field names contain "A", t...
How to add columns with "a" in the field name
This above is a simple example I want to add the data which columns with "a" df['a+abc+bca'] = df[['a', 'abc','bca']].sum(axis=1) Although this method can be counted successfully, it is not very flexible, because if I have many columns whose field names contain "A", the drawbacks of this method will appear. I would l...
[ "Use DataFrame.filter(like=)\ncols = df.filter(like='a').columns\ndf['+'.join(cols)] = df[cols].sum(axis=1)\n\nprint(df)\n\n a b abc bca a+abc+bca\n0 1 2 3 4 8\n\n", "The filter solution is easier but this works too.\na_columns = [column for column in columns if 'a' in column]\ndf['all_a_su...
[ 6, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074150144_python.txt
Q: How do I return a valid response in This Case in Flask? I am new to Flask, I wanted to know few things around it, like how to create a REST api i am getting this error TypeError: The view function for 'create_employee' did not return a valid response Been checking some stuff on the internet and not been able to se...
How do I return a valid response in This Case in Flask?
I am new to Flask, I wanted to know few things around it, like how to create a REST api i am getting this error TypeError: The view function for 'create_employee' did not return a valid response Been checking some stuff on the internet and not been able to see this to solve this correctly. My source code is looking lik...
[ "In flask,you not need return a response,just need return jsonify(),maybe you need read the document carefully\n", "I fixed it :) Thanks people. had to closely look at the documentation and some quick videos again\nThe code looks like this\nmain.py\nimport pymysql\nfrom app import app\nfrom config import mysql\nf...
[ 0, 0 ]
[]
[]
[ "flask", "mysql", "python" ]
stackoverflow_0074149934_flask_mysql_python.txt
Q: Python XML Parsing without root v2 I have 100,000 XML files that look like this <?xml version="1.0" encoding="utf-8" standalone="no"?> <reiXml> <program>BB</program> <nazivStavbe>Test build</nazivStavbe> <X>101000</X> <Y>462000</Y> <QNH>24788</QNH> <QNC>9698</QNC> <Qf>255340</Qf> <Qp>597451</Qp> ...
Python XML Parsing without root v2
I have 100,000 XML files that look like this <?xml version="1.0" encoding="utf-8" standalone="no"?> <reiXml> <program>BB</program> <nazivStavbe>Test build</nazivStavbe> <X>101000</X> <Y>462000</Y> <QNH>24788</QNH> <QNC>9698</QNC> <Qf>255340</Qf> <Qp>597451</Qp> <CO2>126660</CO2> <An>1010.7</An> <V...
[ "Can you try beautifulsoup to parse the XML files?\nxml_doc = \"\"\"\\\n<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n<reiXml>\n <program>BB</program>\n <nazivStavbe>Test build</nazivStavbe>\n <X>101000</X>\n <Y>462000</Y>\n <QNH>24788</QNH>\n <QNC>9698</QNC>\n <Qf>255340</Qf>\n <Qp>597451</...
[ 1, 0, 0 ]
[]
[]
[ "multithreading", "parsing", "python", "xml", "xml_parsing" ]
stackoverflow_0074136140_multithreading_parsing_python_xml_xml_parsing.txt
Q: How to print something only if a function called is true ten times python Hi :) my question is basically what the title says. How do i create a function that calls another function ten times and only if all those times the function2 returns True function 1 prints “good job” For example: def function_one(s) #retu...
How to print something only if a function called is true ten times python
Hi :) my question is basically what the title says. How do i create a function that calls another function ten times and only if all those times the function2 returns True function 1 prints “good job” For example: def function_one(s) #returns true if string is increasing x = all(x <= y for x, y in itertools.pai...
[ "Just use all as you did in function_one.\nHere is an example with a different function_one:\nimport random\n\n# make example reproducible\nrandom.seed(0)\n\n# dummy function that returns True with p=0.9\n# and also prints an indicator ./× for True/False\ndef function_one():\n # return True with a probability of...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074150141_python.txt
Q: How to scatter plot with bubble colors depending on parameter I have the following code #the data data = pd.DataFrame({ 'label': ['Luis', 'Sara', 'Jeroen', 'Sophie', 'Florence', 'Simeon', 'Lambert', 'Rahul', 'Peter', 'John'], 'Data Culture': [0, 5, 10, 15, 20, 18, 13, 9, 4, 1], 'Data Skills': [20, 15, ...
How to scatter plot with bubble colors depending on parameter
I have the following code #the data data = pd.DataFrame({ 'label': ['Luis', 'Sara', 'Jeroen', 'Sophie', 'Florence', 'Simeon', 'Lambert', 'Rahul', 'Peter', 'John'], 'Data Culture': [0, 5, 10, 15, 20, 18, 13, 9, 4, 1], 'Data Skills': [20, 15, 10, 5, 0, 3, 7, 11, 16, 18], 'Department' :['Dept1', 'Dept2', '...
[ "I would suggest doing this with seaborn like this:\nimport seaborn as sns\n\nscatter = sns.scatterplot(data=data,x=\"Data Culture\",y=\"Data Skills\",hue=\"Department\")\n\nlabels = data[\"label\"]\nx = data[\"Data Culture\"]\ny = data[\"Data Skills\"]\n\nfor i in range(len(labels)):\n plt.annotate(labels[i], (...
[ 2 ]
[]
[]
[ "matplotlib", "pandas", "plotly", "python", "seaborn" ]
stackoverflow_0074149783_matplotlib_pandas_plotly_python_seaborn.txt
Q: Altair - how to add lines inside chart I am trying to add specific lines to a line graph in Altair, going from text to a certain point on the graph. I have added my current output here: I am trying to end up with a chart like the one below, but I can't figure out how to add the lines correctly inside the graph. ...
Altair - how to add lines inside chart
I am trying to add specific lines to a line graph in Altair, going from text to a certain point on the graph. I have added my current output here: I am trying to end up with a chart like the one below, but I can't figure out how to add the lines correctly inside the graph. Below is a df of the text and locations that...
[ "The problem is with the way you are plotting the line.\nWhen you specify the line using only x and y, it joins those lines and does not create a separate line\ns =\"\"\"date,count,note\n2017-08-27 00:15:00,4,Fight begins\n2017-08-27 00:22:00,5,McGregor does OK \\\\nin the early rounds\n2017-08-27 00:53:00,4,Maywea...
[ 1 ]
[]
[]
[ "altair", "charts", "pandas", "python", "python_3.x" ]
stackoverflow_0074147856_altair_charts_pandas_python_python_3.x.txt
Q: Running OpenFoam with Python i want to create a bigger application around OpenFoam, considering that the meshing is done with a Python api, i want to include the ./Allrun script into my Python files. First instict was to import os in python and insert the commands from the ./Allrun script. However i am only met wi...
Running OpenFoam with Python
i want to create a bigger application around OpenFoam, considering that the meshing is done with a Python api, i want to include the ./Allrun script into my Python files. First instict was to import os in python and insert the commands from the ./Allrun script. However i am only met with following error messages: ./All...
[ "After some digging i found the solution myself. The inital instict, that the path was somehow realted to the problem turned out to be true.\nAdding\nsource /opt/openfoam9/etc/bashrc\n\ndid the trick.\n" ]
[ 0 ]
[]
[]
[ "bash", "openfoam", "python" ]
stackoverflow_0074139772_bash_openfoam_python.txt
Q: Nested for loop with if in one line for creating new column in dataframe I have a dataframe "result" and want to create a new column called "type". The value in "type" will be the item value of a dict if the column "Particulars" in the dataframe contains value of the key. dict_classify={'key1': 'content1', ...
Nested for loop with if in one line for creating new column in dataframe
I have a dataframe "result" and want to create a new column called "type". The value in "type" will be the item value of a dict if the column "Particulars" in the dataframe contains value of the key. dict_classify={'key1': 'content1', 'key2':'content2' } result['type']=[dict_classify[key] if key....
[ "The most straightforward way is probably to iterate through the dictionary using loc to find cells that contain each key:\nfor key, value in dict_classify.items():\n result.loc[result[\"Particulars\"].str.contains(key), \"type\"] = value\n\nYou could also use a regex to identify the matched keys (like this answ...
[ 1, 0 ]
[]
[]
[ "nested_loops", "python" ]
stackoverflow_0074148988_nested_loops_python.txt
Q: Flask-Babel | Reloading .mo files when Flask app running | Production there is small problem with Flask web application. Right now I'm creating backend for one website and one of the task is to create translation panel in Flask-Admin. Website are using Flask-Babel for multi language support. Long story short, I ma...
Flask-Babel | Reloading .mo files when Flask app running | Production
there is small problem with Flask web application. Right now I'm creating backend for one website and one of the task is to create translation panel in Flask-Admin. Website are using Flask-Babel for multi language support. Long story short, I made BaseView in Admin panel that show all translations and give ability to e...
[ "With Flask-Babelex (0.9.4) the catalog is loaded into the cache during the first translation in the Domain class with the get_translations function.\ndef get_translations(self):\n \"\"\"Returns the correct gettext translations that should be used for\n this request. This will never fail and return a dummy t...
[ 1 ]
[]
[]
[ "flask", "flask_admin", "flask_babel", "mo", "python" ]
stackoverflow_0063190560_flask_flask_admin_flask_babel_mo_python.txt
Q: link several Popen commands with pipes I know how to run a command using cmd = subprocess.Popen and then subprocess.communicate. Most of the time I use a string tokenized with shlex.split as 'argv' argument for Popen. Example with "ls -l": import subprocess import shlex print subprocess.Popen(shlex.split(r'ls -l')...
link several Popen commands with pipes
I know how to run a command using cmd = subprocess.Popen and then subprocess.communicate. Most of the time I use a string tokenized with shlex.split as 'argv' argument for Popen. Example with "ls -l": import subprocess import shlex print subprocess.Popen(shlex.split(r'ls -l'), stdin = subprocess.PIPE, stdout = subproce...
[ "I think you want to instantiate two separate Popen objects here, one for 'ls' and the other for 'sed'. You'll want to pass the first Popen object's stdout attribute as the stdin argument to the 2nd Popen object.\nExample:\np1 = subprocess.Popen('ls ...', stdout=subprocess.PIPE)\np2 = subprocess.Popen('sed ...', st...
[ 47, 6, 4, 4, 0 ]
[]
[]
[ "command", "pipe", "popen", "python", "subprocess" ]
stackoverflow_0007389662_command_pipe_popen_python_subprocess.txt
Q: Dictionary with multiple values per key via for loop given a List in Python I want top create a dictionary that stores all possible two sums as keys and the corresponding indices as values, e.g. list = [1,0,-1, 0] Then I would to compute the dictionary {1:{0,1}, {0,3}, 0: {1,3},{0,2}, -1:{1,2}, {2,3}}. I am having...
Dictionary with multiple values per key via for loop
given a List in Python I want top create a dictionary that stores all possible two sums as keys and the corresponding indices as values, e.g. list = [1,0,-1, 0] Then I would to compute the dictionary {1:{0,1}, {0,3}, 0: {1,3},{0,2}, -1:{1,2}, {2,3}}. I am having troubles finding out how to have a dictionary where one k...
[ "IIUC, use a dictionary with setdefault to add the results and itertools.combinations to generate the combinations of indices:\nlst = [1,0,-1, 0]\n\nfrom itertools import combinations\n\nout = {}\nfor i,j in combinations(range(len(lst)), 2):\n a = lst[i] # first value\n b = lst[j] # second value\n S = a+...
[ 1, 1 ]
[]
[]
[ "dictionary", "python", "python_3.x" ]
stackoverflow_0074150236_dictionary_python_python_3.x.txt
Q: I use POST methon in Django, but my request.method == 'POST' said that it's GET method I don't know why the create function worked before, but now is not working. I see only "It's not POST, it's GET". I have tried to delete something, for example: from def index(request): email = str(request.GET.get('autorization_...
I use POST methon in Django, but my request.method == 'POST' said that it's GET method
I don't know why the create function worked before, but now is not working. I see only "It's not POST, it's GET". I have tried to delete something, for example: from def index(request): email = str(request.GET.get('autorization_email')) and from def create(request) type_values = Type.objects.all() model_values = Mode...
[ "I’m not sure but I think\nif request.method == 'POST':\n\nShould be in the first of function\ndef create(request):\n if request.method == 'POST':\n\nBecause Django by default make a function as get request and you make some operations before you specific the request type\n", "from django.shortcuts import rend...
[ 0, 0 ]
[]
[]
[ "django", "http_post", "python", "python_requests" ]
stackoverflow_0074149964_django_http_post_python_python_requests.txt
Q: Python input words and count repeated words in there hello I have this question to write a program. Write a program that can count the number of occurrences of a string as a substring of another string. Assume that the entered string only consists of lowercase letters (a - z), and string 1 is not longer than strin...
Python input words and count repeated words in there
hello I have this question to write a program. Write a program that can count the number of occurrences of a string as a substring of another string. Assume that the entered string only consists of lowercase letters (a - z), and string 1 is not longer than string 2. For input and output formats, the program can follow ...
[ "This is how you can do it:\nstring.count(substring)\n\n" ]
[ 0 ]
[]
[]
[ "arrays", "python", "python_3.x" ]
stackoverflow_0074150403_arrays_python_python_3.x.txt
Q: How to iterate through list of div at a certain level using BeautifulSoup? I'm trying to webscrape the news from the following URL: https://www.google.com/search?num=250&q=Apple+innovation%20performance&oq=Apple+innovation%20performance%3D1600&source=lnt&tbs=cdr:1,cd_min:1/1/2018,cd_max:12/31/2018&tbm=nws&hl=en-US...
How to iterate through list of div at a certain level using BeautifulSoup?
I'm trying to webscrape the news from the following URL: https://www.google.com/search?num=250&q=Apple+innovation%20performance&oq=Apple+innovation%20performance%3D1600&source=lnt&tbs=cdr:1,cd_min:1/1/2018,cd_max:12/31/2018&tbm=nws&hl=en-US However I can see that Google is changing the name of their news's div classes ...
[ "As one of the comments mentioned, you can use CSS selectors with select.\nFor the news section, this should work\nblockSel = '#search div[eid] div[data-hveid][data-ved] > div[data-hveid]'\n# blockSel = '#main > div > div > a'\nsoup.select(blockSel)\n\nThe first version should work for the tree shown in your questi...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074137966_beautifulsoup_python_web_scraping.txt
Q: Automation tool for testing python code and javascript Does anyone know any free automation testing tool for unit testing python code and javascript? A: You will likely want to compose a number of testing frameworks together. Our team uses nose http://code.google.com/p/python-nose/ as pointed out by @Arbie. We ...
Automation tool for testing python code and javascript
Does anyone know any free automation testing tool for unit testing python code and javascript?
[ "You will likely want to compose a number of testing frameworks together. Our team uses nose http://code.google.com/p/python-nose/ as pointed out by @Arbie. \nWe use nose to also run selenium http://seleniumhq.org/ tests with the python driver which is really the only way I know of to effectively test javascript th...
[ 1, 0, 0 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0005235602_javascript_python.txt
Q: Flask-Login module 'app' has no attribute 'after_request' I'm trying to use Flask-Login with Flask, but when I try to initialize the LoginManager class with the app (as shown in the documentation) I get the following error: AttributeError: module 'app' has no attribute 'after_request' Here's (a snippet of) my cod...
Flask-Login module 'app' has no attribute 'after_request'
I'm trying to use Flask-Login with Flask, but when I try to initialize the LoginManager class with the app (as shown in the documentation) I get the following error: AttributeError: module 'app' has no attribute 'after_request' Here's (a snippet of) my code: from flask_login import LoginManager login_manager = LoginMa...
[ "Okay, so I figured out what was causing the problem. Before the init_app line I imported my models (for Flask-Migrate) like this:\nimport app.models.<model-name-here>\n\nI changed it to\nfrom app.models.<model-name-here> import <model-name-here>\n\nI still don't know why that caused issues but it works now.\n", ...
[ 0, 0 ]
[]
[]
[ "flask", "flask_login", "python" ]
stackoverflow_0061851118_flask_flask_login_python.txt
Q: python suppress minus charactere On Python3, I have ome data on array: tst_val: ['', '1', '--2147483648-0', '', 0] => bad values tst_val: ['1', '0', '0'] => values OK tst_val: ['0', '0', '1'] => values OK tst_val: ['1', '-0', '-1'] => bad value...
python suppress minus charactere
On Python3, I have ome data on array: tst_val: ['', '1', '--2147483648-0', '', 0] => bad values tst_val: ['1', '0', '0'] => values OK tst_val: ['0', '0', '1'] => values OK tst_val: ['1', '-0', '-1'] => bad values Then tabVal_sub = str(tst_val).spli...
[ "If your problem truly is\n\nIn my sub_val, I only want values, properly formatted, like 0 or 1 (int format preferred). If value is not '1' or '0', replace by default with '0'.\n\nthen the solution is simply\nsub_val = [(int(val) if val in (\"1\", \"0\") else 0) for val in tst_val]\n\n" ]
[ 0 ]
[]
[]
[ "arrays", "formatted", "negative_number", "python" ]
stackoverflow_0074150508_arrays_formatted_negative_number_python.txt
Q: TemplateSyntaxError when tried to manage page on Django admin backend I am new on Django CMS and i have experience with error when try to add a page or page type trough backend site. Below is the error i got. I am using Django 4.1.1 version, Django-cms 3.11.0. Any help or suggestion will be appreciated. Templ...
TemplateSyntaxError when tried to manage page on Django admin backend
I am new on Django CMS and i have experience with error when try to add a page or page type trough backend site. Below is the error i got. I am using Django 4.1.1 version, Django-cms 3.11.0. Any help or suggestion will be appreciated. TemplateSyntaxError at /admin/cms/pagetype/add/ Invalid block tag on line 101: '...
[ "Django CMS 3.11.0 does not support Django 4.1 yet. Please downgrade to Django 4.0 (or LTS 3.2).\n" ]
[ 0 ]
[]
[]
[ "django", "django_cms", "python" ]
stackoverflow_0073767981_django_django_cms_python.txt
Q: How to concatenate Pandas dataframes built from multiple requests/JSON responses? I have a script that I use to send a request to an endpoint and receive a JSON response that looks as follows: {'SalesInfoStatus': {'next_offset': 15, 'sales': [{'saSalesID': '761S-1666031549-adhoc-0:0', 'identifier': '761', ...
How to concatenate Pandas dataframes built from multiple requests/JSON responses?
I have a script that I use to send a request to an endpoint and receive a JSON response that looks as follows: {'SalesInfoStatus': {'next_offset': 15, 'sales': [{'saSalesID': '761S-1666031549-adhoc-0:0', 'identifier': '761', 'origin': 'New York', 'destination': 'London', 'filed_time': {'epoch': 166603...
[ "Try this:\nConvert the entire structure to a data frame:\ndf = pd.json_normalize(response['SalesInfoStatus']['sales'])\n\nCheck if the structure is empty:\nif df.empty:\n print('dataframe is empty')\n\nIf the structure is not empty, extract the relevant columns to create the unified data frame and create a list...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074143441_pandas_python.txt
Q: How do I use a list or set as keys in file renaming Is something like this possible? Id like to use a dictionary or set as the key for my file renamer. I have a lot of key words that id like to filter out of the file names but the only way iv found to do it so far is to search by string such as key720 = "720" this...
How do I use a list or set as keys in file renaming
Is something like this possible? Id like to use a dictionary or set as the key for my file renamer. I have a lot of key words that id like to filter out of the file names but the only way iv found to do it so far is to search by string such as key720 = "720" this make it functions correctly but creates bloat. I have to...
[ "How about using Regular Expressions, specifically the sub function?\nfrom re import sub\n\nKEYS = [\"720p\", \"720\", \"1080p\", \"1080\"]\n\nold_filename = \"filename1080p.jpg\"\nnew_filename = sub('|'.join(KEYS),'',old_filename)\n\nprint(new_filename)\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074150605_python.txt
Q: mysql-connector-python query script not working, but only from PHP I am running a LAMP setup w/ the 64bit Raspbian OS on a Raspberry Pi4. I am having a weird issue with 'utf8' and executing python scripts from PHP that are using a connector to my database in mariadb. I have no issues running the scripts and modify...
mysql-connector-python query script not working, but only from PHP
I am running a LAMP setup w/ the 64bit Raspbian OS on a Raspberry Pi4. I am having a weird issue with 'utf8' and executing python scripts from PHP that are using a connector to my database in mariadb. I have no issues running the scripts and modifying the database through my IDE. I have no issues inserting a record int...
[ "This is a known issue introduced by MySQL Connector/Python 8.0.30 with MariaDB when using the pure Python implementation.\nIn your case you have the scenario of not having the C extension implementation of Connector/Python, since you're using Raspbian OS.\nYou have two choices, one is to downgrade to version 8.0.2...
[ 0 ]
[]
[]
[ "mariadb", "mysql_connector_python", "php", "python", "raspberry_pi4" ]
stackoverflow_0074145611_mariadb_mysql_connector_python_php_python_raspberry_pi4.txt
Q: Appending element to a dictionary python I was wondering what is the difference between this two code examples. The first one doesn't work(Key error) but the second one works perfectly. I was using the append function and somehow it didn't work for me. Can someone explain why is it. Thank you! First one (with key...
Appending element to a dictionary python
I was wondering what is the difference between this two code examples. The first one doesn't work(Key error) but the second one works perfectly. I was using the append function and somehow it didn't work for me. Can someone explain why is it. Thank you! First one (with key error) class Solution: def containsNearb...
[ "map[i].append(j) assumes that map[i] already holds a list.\nmap[i] = j just sets (or overrides) the value of map[i].\n", "The way that I remember the difference is:\nIn the first example, you're using the dot operator, which is used to access the object's data members and member functions. The first example is t...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074150485_python.txt
Q: How to escape this python eval() function? So, as part of a challenge I found the following piece of code on a template of an opensource site: @app.route("/admin", methods=['GET', 'POST']) def admin(): username = getUsernameFromSecureStorage() or "admin" passwd = getPasswordFromSecureStorage() if sessi...
How to escape this python eval() function?
So, as part of a challenge I found the following piece of code on a template of an opensource site: @app.route("/admin", methods=['GET', 'POST']) def admin(): username = getUsernameFromSecureStorage() or "admin" passwd = getPasswordFromSecureStorage() if session.get('loggedin', False): return render...
[ "Thank you so much for the help with bypassing the password field by using\n' or True or '\n\nAnother way is:\n1==1'or'2\n\nMain thing is that the statement had to evaluate to always being True.\nAs for the reverse shell, was pretty easy, especially when I found out that there's no bash on the server\nSo this is wh...
[ 1 ]
[ "Maybe take a look here. It's a pretty neat cheat sheet for Reverse Shells, and there are plenty of python examples.\nI'm sure you can find anything in there!\nEDIT:\nI dont have a working reverse shell yet, but bypassing login should be possible with \"' == '' or '\" as password.\n\nexample.py:\npasswd = \"aa\"\ne...
[ -2, -2 ]
[ "bypass", "eval", "python", "reverse_shell", "security" ]
stackoverflow_0074137715_bypass_eval_python_reverse_shell_security.txt
Q: PyYAML automatically converting certain keys to boolean values I've been working with a the PyYAML parser for a few months now to convert file types as part of a data pipeline. I've found the parser to be quite idiosyncratic at times and it seems that today I've stumbled on another strange behavior. The file I'm c...
PyYAML automatically converting certain keys to boolean values
I've been working with a the PyYAML parser for a few months now to convert file types as part of a data pipeline. I've found the parser to be quite idiosyncratic at times and it seems that today I've stumbled on another strange behavior. The file I'm currently converting contains the following section: off: yes: "F...
[ "PyYAML is YAML 1.1 conformant for parsing and emitting, and for YAML 1.1 this is at least partly documented behavior, so no idiosyncrasy at all, but conscious design.\nIn YAML 1.2 (which in 2009 superseded the 1.1 specification from 2005) this usage of Off/On/Yes/No was dropped, among other changes.\nIn ruamel.ya...
[ 15, 5, 2, 1, 0 ]
[]
[]
[ "python", "pyyaml", "yaml" ]
stackoverflow_0036463531_python_pyyaml_yaml.txt
Q: FastAPI Server is not accessible from the internet For the past few days, i've been trying to set up a FastAPI & Uvicorn server on my Windows machine (although the main idea is to set it up on an old Android device that i dont use anymore.) The server (in both my android and my pc) can be reached by any machine in...
FastAPI Server is not accessible from the internet
For the past few days, i've been trying to set up a FastAPI & Uvicorn server on my Windows machine (although the main idea is to set it up on an old Android device that i dont use anymore.) The server (in both my android and my pc) can be reached by any machine in my local network. The problem comes when I try to acces...
[ "This question is way to broad for StackOverflow, and is highly dependent on the specifics of your situation. However, to get you going here is a highlevel overview of how it would normally work.\nSituation: you have a house, in which there is a internet connection to which your computer is connected. There are two...
[ 0 ]
[]
[]
[ "android", "fastapi", "python", "uvicorn", "windows" ]
stackoverflow_0074148281_android_fastapi_python_uvicorn_windows.txt
Q: How to create features for multiple datetime columns in featuretools? Sorry to put three question in one issue. How to create features for multiple datatime columns? I got a dataframe with multiple datetime columns, and hoped to create features like TimeSinceFirst, TimeSinceLast for all of them. But with only one...
How to create features for multiple datetime columns in featuretools?
Sorry to put three question in one issue. How to create features for multiple datatime columns? I got a dataframe with multiple datetime columns, and hoped to create features like TimeSinceFirst, TimeSinceLast for all of them. But with only one of them set as time_index, I couldn't get time-related features for the ot...
[ "I asked almost the same questions on github, and have got answers to the first two there. In summary,\n\nHow to create features for multiple datatime columns?\nYou should create custom primitives to make it. To quote from here, \"For the custom primitive you could copy the code for TimeSinceLast and just remove se...
[ 1 ]
[]
[]
[ "featuretools", "python" ]
stackoverflow_0074040726_featuretools_python.txt
Q: Scrap drop down menu I am trying to scrap the size menu of this page. https://www.hayabusafightwear.co.uk/hayabusa-lightweight-jiu-jitsu-gi-blue If I copy the html and use beautiful soup it works but doesn't seem to work on the live version. I think it is because the html is dynamic? What is the best way to go for...
Scrap drop down menu
I am trying to scrap the size menu of this page. https://www.hayabusafightwear.co.uk/hayabusa-lightweight-jiu-jitsu-gi-blue If I copy the html and use beautiful soup it works but doesn't seem to work on the live version. I think it is because the html is dynamic? What is the best way to go forward? Is it even worth try...
[ "You should use the combination of selenium and bs4 to get it done:\nimport time\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\n\noptions = webdriver.ChromeOptions()\noptions.add_argument('--ignore-certificate-errors')\noptions.add_argument('--incognito')\noptions.add_argument('--headless')\ndrive...
[ 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0074143293_beautifulsoup_python.txt
Q: MWAA: Trouble installing Airflow Google Providers from requirements.txt I'm trying to set up an MWAA Airflow 2.0 environment that integrates S3 and GCP's Pub/Sub. While we have no problems with the environment being initialized, we're having trouble installing some dependencies and importing Python packages -- spe...
MWAA: Trouble installing Airflow Google Providers from requirements.txt
I'm trying to set up an MWAA Airflow 2.0 environment that integrates S3 and GCP's Pub/Sub. While we have no problems with the environment being initialized, we're having trouble installing some dependencies and importing Python packages -- specifically apache-airflow-providers-google==2.2.0. We've followed all of the i...
[ "I'm having the same problems and in the end we had to refactor a lot of things to remove the dependence. It looks like is a problem with PIP resolver and apache-airflow-providers-google if you look the official page:\nhttps://pypi.org/project/apache-airflow-providers-google/2.0.0rc1/\nIn the WORST case, you may ne...
[ 0, 0 ]
[]
[]
[ "airflow", "amazon_web_services", "etl", "mwaa", "python" ]
stackoverflow_0068435154_airflow_amazon_web_services_etl_mwaa_python.txt
Q: How do I check the name of a namedtuple? I have a list of namedtuples, for example: [Student(ID='1', name='abc'), Room(number='1', location='4th floor'), Student(ID='2', name='xyz')] While looping through this list, how do I check if an element is a Student or Room? A: You can use isinstance to check an object ...
How do I check the name of a namedtuple?
I have a list of namedtuples, for example: [Student(ID='1', name='abc'), Room(number='1', location='4th floor'), Student(ID='2', name='xyz')] While looping through this list, how do I check if an element is a Student or Room?
[ "You can use isinstance to check an object is an instance of a class.\n>>> help(isinstance)\nHelp on built-in function isinstance in module builtins:\n\nisinstance(obj, class_or_tuple, /)\n Return whether an object is an instance of a class or of a subclass thereof.\n\n A tuple, as in ``isinstance(x, (A, B, ....
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074150868_python.txt
Q: IOError: [Errno 2] No such file - Paramiko put() I'm uploading a file via SFTP using Paramiko with sftp.put(localFile, remoteFile). I make the necessary directory first if needed with makeCommand = 'mkdir -p "' + remotePath + '"' ssh.exec_command(makeCommand) this was works sometimes but I'm occasionally...
IOError: [Errno 2] No such file - Paramiko put()
I'm uploading a file via SFTP using Paramiko with sftp.put(localFile, remoteFile). I make the necessary directory first if needed with makeCommand = 'mkdir -p "' + remotePath + '"' ssh.exec_command(makeCommand) this was works sometimes but I'm occasionally getting the following error: sftp.put(localFile, ...
[ "It seems to be a remote folder permission problem. Although the remote folder was made before the file was uploaded, it appears the permissions on the folder were preventing an upload. \nThe problem is linked to this issue - if I set open permissions on the folder I'll be uploading to before I upload, the program ...
[ 12, 10, 2, 2, 1, 1 ]
[]
[]
[ "paramiko", "python", "python_2.7", "sftp" ]
stackoverflow_0015481934_paramiko_python_python_2.7_sftp.txt
Q: pivot drop Nan Values in pandas Having a pivot as below: I was trying to drop the NaN values: matrix = matrix.drop(index=None, columns=None) Its not working. ValueError: Need to specify at least one of 'labels', 'index' or 'columns' Is there any other way to do this? Expected output: A: drop is for dropping en...
pivot drop Nan Values in pandas
Having a pivot as below: I was trying to drop the NaN values: matrix = matrix.drop(index=None, columns=None) Its not working. ValueError: Need to specify at least one of 'labels', 'index' or 'columns' Is there any other way to do this? Expected output:
[ "drop is for dropping entire rows or columns (independed of their values). Use dropna to delete rows or columns where values are NAN\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074150887_pandas_python.txt
Q: Error in google colab(python) while transliterating data into Indian language I am transliterating data into India language using python in google colab, but encountered error: AttributeError: module 'emoji' has no attribute 'UNICODE_EMOJI' The error occurs to the second line in the code: for word in line_list: ...
Error in google colab(python) while transliterating data into Indian language
I am transliterating data into India language using python in google colab, but encountered error: AttributeError: module 'emoji' has no attribute 'UNICODE_EMOJI' The error occurs to the second line in the code: for word in line_list: if word in emoji.UNICODE_EMOJI: new_line_list.append(emo...
[ "You can use the function distinct_emoji_list() to extract emojis in a string and return a list of found emojis, then call emoji.demojize() on each emoji in that list to convert it into its meaning.\nso having:\nline_list = ['Hello World! ', 'Goodbye World ']\nnew_line_list = []\n\nfor word in line_list:\n emojis ...
[ 5, 0, 0 ]
[]
[]
[ "emoji", "google_colaboratory", "python", "transliteration" ]
stackoverflow_0073024976_emoji_google_colaboratory_python_transliteration.txt
Q: Passing strings in a lambda function I would like to automate the following code line: df_b = df_b.append([{'A':df_a['A'][1], 'B':df_a['B'][1], 'C':df_a['C'][1]}], ignore_index=True) and I was considering using a lambda function to do so: list = ['A', 'B', 'C'] func = lambda j: df_a[j][1] df_b = df_b.append([{(fu...
Passing strings in a lambda function
I would like to automate the following code line: df_b = df_b.append([{'A':df_a['A'][1], 'B':df_a['B'][1], 'C':df_a['C'][1]}], ignore_index=True) and I was considering using a lambda function to do so: list = ['A', 'B', 'C'] func = lambda j: df_a[j][1] df_b = df_b.append([{(func(list))}], ignore_index=True) And I got...
[ "I think what you want here is a dictionary comprehension:\nlst = ['A', 'B', 'C']\nfunc = lambda j: df_a[j][1]\nto_append = {s:func(s) for s in lst}\ndf_b = df_b.append([to_append], ignore_index=True)\n\nAs a side note, you could equally define func with a def instead of lambda in this case.\n" ]
[ 1 ]
[]
[]
[ "lambda", "pandas", "python" ]
stackoverflow_0074140931_lambda_pandas_python.txt
Q: Why does my scrapy JSON export not work when ran in Python? I've created a python scrapy script that I want to be able to start by running the python file and not using the terminal. I've been using the following - os.system("scrapy crawl preorder") However, when I add a JSON export the scrapy it runs as normal b...
Why does my scrapy JSON export not work when ran in Python?
I've created a python scrapy script that I want to be able to start by running the python file and not using the terminal. I've been using the following - os.system("scrapy crawl preorder") However, when I add a JSON export the scrapy it runs as normal but no JSON file is created. The same command works when ran in te...
[ "Thanks, guys. Because the terminal location defaults to the project directory I was looking for the file in the wrong place. Stupid, me.\n" ]
[ 0 ]
[]
[]
[ "python", "scrapy", "terminal", "web_crawler" ]
stackoverflow_0074140916_python_scrapy_terminal_web_crawler.txt
Q: How to repeat my "if" and "elif" statements after my "else" statement How do I make it so that it goes back to the previous commands after else statement Name = input("Please insert your Name = ") Male = "Male" Female = "Female" Gender = input("Are you male or female = ") if Gender == Male: print(Name) p...
How to repeat my "if" and "elif" statements after my "else" statement
How do I make it so that it goes back to the previous commands after else statement Name = input("Please insert your Name = ") Male = "Male" Female = "Female" Gender = input("Are you male or female = ") if Gender == Male: print(Name) print(Gender) print("he/him") elif Gender == Female: print(Name) ...
[ "while True:\n name = input(\"Please insert your Name = \")\n gender = input(\"Are you male or female = \")\n\n if gender == \"Male\":\n print(name, '\\n', \"Male\", \"\\n\", \"he/him\")\n elif gender == \"Female\":\n print(name, '\\n', \"Female\", \"\\n\", \"she/her\")\n else:\n ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074150331_python.txt
Q: KeyError in django when using a textarea I want to do a very simple operation : 1-taking some info form the form 2-saving the data in the database But i get this error and i don't know the reason of it! can you please help . this is the forms.py : class ContactForm(forms.Form): title = forms.CharField(max_length=5...
KeyError in django when using a textarea
I want to do a very simple operation : 1-taking some info form the form 2-saving the data in the database But i get this error and i don't know the reason of it! can you please help . this is the forms.py : class ContactForm(forms.Form): title = forms.CharField(max_length=500) phone_mail = forms.CharField(max_length=30...
[ "You got this error because you have written text instead of body.\nmodels.py:\ninstead:\ntext = models.TextField()\n\ntry this:\nbody = models.TextField()\n\nclass Contact(models.Model):\n title = models.CharField(max_length=500)\n phone_mail = models.CharField(max_length=30)\n body = models.TextFie...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074151000_django_python.txt
Q: How to run ansible module in python Here is my code: I am not able to run a ansible module using python. How to pass a inventory file for which this command is running. I am not able to run it for my inventory. Do I need to do something else ? Here is my ansible command: ansible all -i /home/ubuntu/extra -m 'debug...
How to run ansible module in python
Here is my code: I am not able to run a ansible module using python. How to pass a inventory file for which this command is running. I am not able to run it for my inventory. Do I need to do something else ? Here is my ansible command: ansible all -i /home/ubuntu/extra -m 'debug' -a 'var=hostvars' Here is my code: im...
[ "You can pass the inventory file path to ansible.runner.Runner()\nAnd for getting group-names and host-names , you should pass var=hostvars, not vars=hostvars\nYour code would look like this,\nimport json\nimport ansible.runner\nimport ansible.playbook\nimport ansible.inventory\n\nexample_inventory = ansible.invent...
[ 4, 0 ]
[]
[]
[ "ansible", "python" ]
stackoverflow_0033538483_ansible_python.txt
Q: Finding what is most commonly purchased with a specific product - PANDAS I am trying to find the most common products purchased with the product 'SWE' but am currently stuck. I have the variables 'product' and 'sales_invoice' So far I have this code: df_pairs = df_pairs = df.groupby(df['product'].str.contains('SWE...
Finding what is most commonly purchased with a specific product - PANDAS
I am trying to find the most common products purchased with the product 'SWE' but am currently stuck. I have the variables 'product' and 'sales_invoice' So far I have this code: df_pairs = df_pairs = df.groupby(df['product'].str.contains('SWE'))['sales_invoice'] print(df_pairs.head()) it results in a list of sales inv...
[ "First of all, since there may be more than one product in an order, we create a line for each product, then we group them according to sales_invoice and assign the products in each order to a list, then we show the distribution of each list as a dictionary. In addition, you can filter by SWE or see the product dis...
[ 0 ]
[]
[]
[ "associations", "combinations", "pandas", "python" ]
stackoverflow_0074148259_associations_combinations_pandas_python.txt
Q: Tkinter: "NameError: name 'event' is not defined error" when passing argument in button command I'm trying to pass the event argument in my button command function to create a toplevel, but I'm getting this error: NameError: name 'event' is not defined This is my code class MainApplication(tk.Frame): def __ini...
Tkinter: "NameError: name 'event' is not defined error" when passing argument in button command
I'm trying to pass the event argument in my button command function to create a toplevel, but I'm getting this error: NameError: name 'event' is not defined This is my code class MainApplication(tk.Frame): def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) ...
[ "Button press is not considered an event. An event is binding a function to a mouse, or keyboard action. In this example I get the cursor position upon left click, relative to the top left corner of the screen. The event is bound to the root widget.\nimport tkinter as tk\n\n\nclass MainApplication(tk.Frame):\n d...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074150546_python_tkinter.txt
Q: Failed when using the filter_query in style_data_conditional in dashtable Trying to use the filter_query in style_data_conditional to styling certain row in the dashtable. However, receive the error message. Referring to the Highlighting Text that Equals a Value Error message: DataTable filtering syntax is invali...
Failed when using the filter_query in style_data_conditional in dashtable
Trying to use the filter_query in style_data_conditional to styling certain row in the dashtable. However, receive the error message. Referring to the Highlighting Text that Equals a Value Error message: DataTable filtering syntax is invalid for query: {column1} = "Grand Total" (This error originated from the bui...
[ "Found out is the data issue. Cannot have space between the word.\n\"Grand Total\" change to \"Grand_Total\", then styling can function.\n" ]
[ 0 ]
[]
[]
[ "plotly", "python" ]
stackoverflow_0074063860_plotly_python.txt
Q: Sum two array if they have the same index, but keep the indexes afterward? lets say we have to arrays first: arr1= [1000 5.0 1270 5.0 1315 5.0 ] arr2= [578 5.0 1000 5.0 1315 5.0 ] So as you can see we have indexes and their values ...
Sum two array if they have the same index, but keep the indexes afterward?
lets say we have to arrays first: arr1= [1000 5.0 1270 5.0 1315 5.0 ] arr2= [578 5.0 1000 5.0 1315 5.0 ] So as you can see we have indexes and their values what I want to do is concat them in a way if they have the same index then add ...
[ "The use of a dict seems to be the way to go here:\nmap1={\n 1000: 5.0,\n 1270: 5.0,\n 1315: 5.0\n}\n\nmap2={\n578: 5.0,\n1000: 5.0,\n1315: 5.0\n}\n\nr = map1\nfor k, v in map2.items():\n if k not in r:\n r[k] = 0\n r[k] += v\n\n", "Those are not arrays. They aren't even python.\nIn python, arrays...
[ 2, 2, 1, 0 ]
[]
[]
[ "arrays", "python", "python_3.x" ]
stackoverflow_0074150719_arrays_python_python_3.x.txt
Q: AWS lambda read zip file perform validation and unzip to s3 bucket if validation is passed I have a requirement in which a zip files arrives on s3 bucket, I need to write a lambda using python to read the zip file perform some validation and unzip on another S3 bucket. Zip file contains below: a.csv b.csv c.csv tr...
AWS lambda read zip file perform validation and unzip to s3 bucket if validation is passed
I have a requirement in which a zip files arrives on s3 bucket, I need to write a lambda using python to read the zip file perform some validation and unzip on another S3 bucket. Zip file contains below: a.csv b.csv c.csv trigger_file.txt trigger_file.txt -- contain names of files in zip and record count (example: a.c...
[ "In the following while loop in your code, if fileName is not \"Trigger_file.txt\", it falls into infinite loop.\n\nfound = False\nwhile not found:\n if fileName == \"Trigger_file.txt\":\n with zipf.open(fileName , 'r') as thefile:\n my_list = [i.decode('utf8').split(' ') for i in thefile]\n ...
[ 1, 0 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "aws_lambda", "csv", "python" ]
stackoverflow_0062417455_amazon_s3_amazon_web_services_aws_lambda_csv_python.txt
Q: Look for 100% matches,partial matches and dismatches between python list and list column in Pandas I know how to compare lists but working with unflatten data in Pandas is beyond my skills..anyway.. I have: list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and df = pd.DataFrame({ "col1":["a", "b", "c", "d"], "col2":[[1, 2,...
Look for 100% matches,partial matches and dismatches between python list and list column in Pandas
I know how to compare lists but working with unflatten data in Pandas is beyond my skills..anyway.. I have: list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and df = pd.DataFrame({ "col1":["a", "b", "c", "d"], "col2":[[1, 2, 3, 4, 5], [20, 30, 100], [1, 3, 20], [20,30]] }) I want to compare the list with the df and print rows...
[ "Code:\n###INPUT\nlst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\ndf = pd.DataFrame({\n\"col1\": ['a', 'b', 'c', 'd'], \n\"col2\":[[1, 2, 3, 4, 5], [20, 30, 100], [1, 3, 20], [20,30]]})\n \n\n#Creating another list to define categorize\ncat = ['100% matches are in rows:', 'Partial matches are in rows:', 'Dismatches are in r...
[ 1, 1 ]
[]
[]
[ "compare", "list", "pandas", "python" ]
stackoverflow_0074150971_compare_list_pandas_python.txt
Q: Create Tempview from sql query df_sales = spark.sql( "SELECT \ s.TRANS_DT, \ s.STORE_KEY, \ s.PROD_KEY, \ s.SALES_QTY FROM sales s \ JOIN inventory i ON s.cal_dt=i.cal_dt and s.store_key=i.store_key and s.prod_key=i.prod_key;" ) I created sql query from 2 tempview (inventory and sales). How to convert df_sales sq...
Create Tempview from sql query
df_sales = spark.sql( "SELECT \ s.TRANS_DT, \ s.STORE_KEY, \ s.PROD_KEY, \ s.SALES_QTY FROM sales s \ JOIN inventory i ON s.cal_dt=i.cal_dt and s.store_key=i.store_key and s.prod_key=i.prod_key;" ) I created sql query from 2 tempview (inventory and sales). How to convert df_sales sql query to tempview again and I can ...
[ "Read this and you can write your own code as follows:\nspark.sql(\n\"\"\"\nSELECT\n s.TRANS_DT,\n s.STORE_KEY,\n s.PROD_KEY,\n s.SALES_QTY\nFROM sales s\nJOIN inventory i ON s.cal_dt=i.cal_dt and s.store_key=i.store_key and s.prod_key=i.prod_key;\n\"\"\"\n).createOrReplaceTempView(\"tmpViewName\")\n\n"...
[ 2 ]
[]
[]
[ "apache_spark", "python", "sql" ]
stackoverflow_0074148022_apache_spark_python_sql.txt
Q: How to visualize duplicated dates as lineplot? I have the following dataframe (sample): import pandas as pd import seaborn as sns data = [['A', '2022-09-01', False, 2], ['A', '2022-09-02', False, 2], ['A', '2022-09-02', False, 1], ['A', '2022-09-03', False, 1], ['A', '2022-09-03', False, 1], ['A', '2022-...
How to visualize duplicated dates as lineplot?
I have the following dataframe (sample): import pandas as pd import seaborn as sns data = [['A', '2022-09-01', False, 2], ['A', '2022-09-02', False, 2], ['A', '2022-09-02', False, 1], ['A', '2022-09-03', False, 1], ['A', '2022-09-03', False, 1], ['A', '2022-09-04', False, 1], ['A', '2022-09-04', True, 3], ['A...
[ "IIUC, you want to keep the last duplicate and use drawstyle='steps-post':\nsns.lineplot(data=df.drop_duplicates(subset=['group', 'date'], keep='last'),\n x='date', y='value', hue='group', drawstyle='steps-post')\n\noutput:\n\n" ]
[ 2 ]
[]
[]
[ "matplotlib", "pandas", "python", "seaborn" ]
stackoverflow_0074150698_matplotlib_pandas_python_seaborn.txt
Q: Replace specific lines in a list, from another list I want to replace lines that start with G0 and G1 in a list; from G0 and G1 from another list. And doing this without changing anything else in the list. List1= ['G1 F2400 X101.031 Y24512.91 E769.44645', 'G0 F2400 X48501.031 Y112.91 E769.44645', 'G1 F2400 X5801....
Replace specific lines in a list, from another list
I want to replace lines that start with G0 and G1 in a list; from G0 and G1 from another list. And doing this without changing anything else in the list. List1= ['G1 F2400 X101.031 Y24512.91 E769.44645', 'G0 F2400 X48501.031 Y112.91 E769.44645', 'G1 F2400 X5801.031 Y112.91 E769.44645','G0 F2400 X7801.031 Y112.91 E769...
[ "You can do this,\nList1 = ['G1 F2400 X101.031 Y112.91 E769.44645', 'M204 S5000', 'M205 X30 Y30', 'G0 F15000 X101.29 Y112.675',\n 'M204 S500', 'M205 X5 Y5', 'G1 F2400 X100.906 Y112.291 E769.46135', 'M204 S5000', 'M205 X30 Y30', \n 'G0 F15000 X101.163 Y112.053', 'M204 S500', 'M205 X5 Y5', 'G1 F2400 X101.545 ...
[ 1, 0 ]
[]
[]
[ "append", "for_loop", "list", "python", "replace" ]
stackoverflow_0074151106_append_for_loop_list_python_replace.txt
Q: How do I transfer data from excel into 3D array in python, with X being latitude, Y longitude and Z representing depth? I have a problem transferring data from an excel file into a 3D array. The different variables of data is latitude, longitude and depth of an area in western norway. The plan is to later have a r...
How do I transfer data from excel into 3D array in python, with X being latitude, Y longitude and Z representing depth?
I have a problem transferring data from an excel file into a 3D array. The different variables of data is latitude, longitude and depth of an area in western norway. The plan is to later have a reinforcement learning algorithm use this map of a 3D array to learn navigate the area at sea, i.e. where the depth is positiv...
[ "You are importing the columns as dataframes. In order to generate an np.array you have to convert them to list first:\ntreD_array = np.array([Lat.iloc[:,0].tolist(), long.iloc[:,0].tolist(), Depth.iloc[:,0].tolist()])\n\n", "You are receiving this warning because of your syntax for creating your numpy array.\nI ...
[ 0, 0 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0074150738_arrays_python.txt
Q: (Pymongo) connect/adding relationship with two column from different collections in MongoDB I'm practicing use python to commit rollback MongoDB (Pymongo) For example, I have two collections, one collection store all amount of money of each user and log collection is saving data of with roll or input money in bank...
(Pymongo) connect/adding relationship with two column from different collections in MongoDB
I'm practicing use python to commit rollback MongoDB (Pymongo) For example, I have two collections, one collection store all amount of money of each user and log collection is saving data of with roll or input money in bank total_money_collection {"user": "Joy" , "total_money" : 100, "ID" : 999} log_money_collection ...
[ "the same concept make ur {\"user\": \"Joy\" , \"total_money\" : 93, \"ID\" : 999},\nthe \"total_money\" become lesser by subtracting them, for sure U can't directly do that, like python (4 - 1 something)....\nhere is the code:\nimport pymongo\nimport datetime\nimport json\nfrom bson.objectid import ObjectId\nfrom ...
[ 0 ]
[]
[]
[ "mongodb", "pymongo", "pymongo_3.x", "python" ]
stackoverflow_0074139088_mongodb_pymongo_pymongo_3.x_python.txt
Q: Execute multiline code with tabs from input() Consider the following code: code = input() eval(code) If I run it and type > print(10) It will get executed and print "10" My question is when the code needs an indent, such as: > for i in range(10): > print(i) How can I receive this code with input() (notice tha...
Execute multiline code with tabs from input()
Consider the following code: code = input() eval(code) If I run it and type > print(10) It will get executed and print "10" My question is when the code needs an indent, such as: > for i in range(10): > print(i) How can I receive this code with input() (notice that I have to keep the indent) so that I can use eval...
[ "If i understand correctly you want to be able to get python code using input() with tabs included.\nthe post\nHow to read multiple lines of raw input? tells us that we can get multiline input with\ncode = '\\n'.join(iter(input, ''))\n\nBut after trying that myself I noticed that exec(code) didn't work because tabs...
[ 0 ]
[ "What's your use case here?\nIf you want to run the string in eval(), do you consider this?\nnew_string_name = \"for i in range(10):\\n eval(a)\"\n\nor\nnew_string_name = \" eval()\"\n\nBut if you don't want to follow the indentation rules (4 characters, no tabs), you can use\nnew_string_name = \"for i in ran...
[ -2 ]
[ "python", "python_3.x" ]
stackoverflow_0074150548_python_python_3.x.txt
Q: Pandas 'DataFrame' object has no attribute 'unique' I'm working in pandas doing pivot tables and when doing the groupby (to count distinct observations) aggfunc={"person":{lambda x: len(x.unique())}} gives me the following error: 'DataFrame' object has no attribute 'unique' any ideas how to fix it? A: DataFram...
Pandas 'DataFrame' object has no attribute 'unique'
I'm working in pandas doing pivot tables and when doing the groupby (to count distinct observations) aggfunc={"person":{lambda x: len(x.unique())}} gives me the following error: 'DataFrame' object has no attribute 'unique' any ideas how to fix it?
[ "DataFrames do not have that method; columns in DataFrames do: \ndf['A'].unique()\n\nOr, to get the names with the number of observations (using the DataFrame given by closedloop):\n>>> df.groupby('person').person.count()\nOut[80]: \nperson\n0 2\n1 3\nName: person, dtype: int64\n\n", "Rather than ...
[ 37, 5, 4, 2, 0 ]
[]
[]
[ "pandas", "pivot_table", "python" ]
stackoverflow_0029244549_pandas_pivot_table_python.txt
Q: When create django table dynamically, how can I set Meta class? I have a Django abstract model class and want to create it dynamically with meta class. class AccountTransaction(models.Model): class Meta: abstract = True account_num = models.ForeignKey('Account', on_delete=models.CASCADE) tran_...
When create django table dynamically, how can I set Meta class?
I have a Django abstract model class and want to create it dynamically with meta class. class AccountTransaction(models.Model): class Meta: abstract = True account_num = models.ForeignKey('Account', on_delete=models.CASCADE) tran_amt = models.PositiveBigIntegerField() tran_type = models.CharFie...
[ "I think, you have to make more of just implement an abstract base for going to your purpose, but it is possible i think. But probably not a good idea for the future maintenability of project...\nDjango has a internal mecanism for recognizing a model and you can create dynamically types whiches Django recognize as ...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074148298_django_python.txt
Q: converting a text file with tags in a pandas dataframe with tags as fields I have a text file with this structure: - ASDF : |a=1|b=1|c=1|d=1 - QWER : |b=2|e=2|f=2 - ZXCV : |a=3|c=3|e=3|f=3|g=3 - TREW : |a=4|b=4|g=4 and I'd like to create a dataframe like this: index A B C D E F G ASDF 1 1 1 1 NaN NaN NaN QWER ...
converting a text file with tags in a pandas dataframe with tags as fields
I have a text file with this structure: - ASDF : |a=1|b=1|c=1|d=1 - QWER : |b=2|e=2|f=2 - ZXCV : |a=3|c=3|e=3|f=3|g=3 - TREW : |a=4|b=4|g=4 and I'd like to create a dataframe like this: index A B C D E F G ASDF 1 1 1 1 NaN NaN NaN QWER NaN 2 NaN NaN NaN 2 NaN ZXCV 3 NaN 3 NaN 3 3 3 TREW 4 4 NaN NaN NaN N...
[ "Use read_csv first, then convert first column to index and split by | by Series.str.split, reshape by DataFrame.stack, split by =, convert index to columns and pivoting by DataFrame.pivot, last create uppercase columns names:\ndf = pd.read_csv('file', sep=':', header=None)\n\n\ndf1 = (df.set_index(0)[1]\n ...
[ 1, 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074151219_dataframe_pandas_python.txt
Q: Hackerrank doesn't accept my code. Why? So the task is to read an integer N For all non-negative integers I < N, print The output format should print N lines, one corresponding to each i. For example, the user input is 5 so the output should be... 0 1 4 9 16 Here is my solution. # The first two lines of code were...
Hackerrank doesn't accept my code. Why?
So the task is to read an integer N For all non-negative integers I < N, print The output format should print N lines, one corresponding to each i. For example, the user input is 5 so the output should be... 0 1 4 9 16 Here is my solution. # The first two lines of code were default and already there. if __name__ == '_...
[ "Firstly, You should not write in range(0,5) if you want to iterate through n numbers. \nSecondly, You do not need to write another while function. You use for loop or while loop for this question.\nChange\nfor i in range(0,5):\n while i < 5:\n print(i ** 2)\n i += 1\n break\n\nto \nfor i in...
[ 3, 1, 1, 0, 0, 0, 0 ]
[ "This should work:\nif __ name __ == ' __main __':\n n = int(input())\n\nfor i in range(n):\n while i < 10:\n print(i ** 2)\n i += 1\n break\n\n", " if __name__ == '__main__':\n n = int(input())\n\nfor i in range(0,n):\n (i*i) and 1 <=n <=20\n print(i*i)\n\n\n\n" ]
[ -1, -2 ]
[ "loops", "python", "python_3.x", "while_loop" ]
stackoverflow_0051392779_loops_python_python_3.x_while_loop.txt
Q: I created a virtual environment in macos, and my global environment fails after installing some packages in the virtual one I created a virtual environment in my macbook, and installed some packages using the following commands: python3 -m venv virtenv1 source ~/virtenv1/bin/activate pyenv install 3.9.7 pip instal...
I created a virtual environment in macos, and my global environment fails after installing some packages in the virtual one
I created a virtual environment in my macbook, and installed some packages using the following commands: python3 -m venv virtenv1 source ~/virtenv1/bin/activate pyenv install 3.9.7 pip install -r requirements.txt pip install jupyter lab pip install ipykernel python -m ipykernel install --user --name=virtenv1kernel My ...
[ "When you create a Python virtual environment with the venv module activate it using the source [virtual env]/bin/activate it effectively hardcodes the Python version to the global Python version that was invoked to create the virtual environment.\nIf you want to use a different Python version in the virtual enviro...
[ 0 ]
[]
[]
[ "jupyter_lab", "macos", "python", "virtualenv" ]
stackoverflow_0074130193_jupyter_lab_macos_python_virtualenv.txt
Q: Flask-Admin remove "Home" button How do I remove the "Home" button in Python's Flask-Admin library? from flask_admin import Admin flask_admin = Admin(app, name='Customer Admin', template_mode='bootstrap3', # endpoint refers to the blueprint [e.g. url_for('admin_cust.index')] where index() is the f...
Flask-Admin remove "Home" button
How do I remove the "Home" button in Python's Flask-Admin library? from flask_admin import Admin flask_admin = Admin(app, name='Customer Admin', template_mode='bootstrap3', # endpoint refers to the blueprint [e.g. url_for('admin_cust.index')] where index() is the function/view index_view=SecuredAdm...
[ "Flask-Admin BaseView has a method is_visible(self), the source code has a note:\nPlease note that item should be both visible and accessible to be displayed in menu.\nFor example, an index view could be along the following lines:\nfrom flask_admin import Admin\nfrom flask_admin import AdminIndexView\nfrom flask_ad...
[ 8, 0, 0 ]
[]
[]
[ "flask", "flask_admin", "python" ]
stackoverflow_0061624338_flask_flask_admin_python.txt
Q: not able to get file form the form data in flask server i am trying to upload a form data in js into my flask server but i am not getting file in the server. My code in JS is: const form = document.forms.namedItem('fileinfo') form.addEventListener('submit', async (event) => { event.preventDefa...
not able to get file form the form data in flask server
i am trying to upload a form data in js into my flask server but i am not getting file in the server. My code in JS is: const form = document.forms.namedItem('fileinfo') form.addEventListener('submit', async (event) => { event.preventDefault() let formData = new FormData(form) ...
[ "In contrast to normal form fields, which can be accessed via request.form, it is necessary to use request.files on the server side in order to receive transmitted files. Here you can request an object of type FileStorage using the name of the form field.\n@app.route(\"/stateUpload\", methods=[ \"POST\"])\ndef stat...
[ 0 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074150417_flask_python.txt
Q: Removing last words in each row in pandas dataframe A dataframe contains a column named 'full_name' and the rows look like this: full_name Peter Eli Smith Vanessa Mary Ellen Raul Gonzales Kristine S Lee How do I remove the last words and add an additional column called 'first_middle_name' which will result l...
Removing last words in each row in pandas dataframe
A dataframe contains a column named 'full_name' and the rows look like this: full_name Peter Eli Smith Vanessa Mary Ellen Raul Gonzales Kristine S Lee How do I remove the last words and add an additional column called 'first_middle_name' which will result like this?: full_name first_middle_name Peter Eli...
[ "We can try using str.replace here:\ndf[\"first_middle_name\"] = df[\"full_name\"].replace(\"\\s+\\S+$\", \"\")\n\nSee the above regex replacement working in the demo link below.\nDemo\n", "Use str\ndf[\"first_middle_name\"] = df[\"full_name\"].str.replace(\"\\s+\\S+$\", \"\")\n\n" ]
[ 1, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0063212643_pandas_python.txt
Q: TypeError: '>=' not supported between instances of 'datetime.date' and 'str' in Jupyter Notebook When I try to run this in Jupyter Notebook: isolated = diff['2012-09-28' <= diff['start_date']] isolated I get this: TypeError: '>=' not supported between instances of 'datetime.date' and 'str' What should I do? I al...
TypeError: '>=' not supported between instances of 'datetime.date' and 'str' in Jupyter Notebook
When I try to run this in Jupyter Notebook: isolated = diff['2012-09-28' <= diff['start_date']] isolated I get this: TypeError: '>=' not supported between instances of 'datetime.date' and 'str' What should I do? I already tried importing pandas and datetime but it didn't work.
[ "Convert column to datetimes:\ndiff['2012-09-28' <= pd.to_datetime(diff['start_date'])]\n\nOr convert string to date:\ndiff[pd.Timestamp('2012-09-28').date() <= diff['start_date']]\n\n" ]
[ 0 ]
[ "Strings cannot be compared directly; they need to convert to suitable data format for comparison.\nUse this sort of formatting.\nimport pandas as pd\ndf = pd.read_csv(\"dataframe.csv\")\nstartdate = pd.to_datetime(\"date\").date()\nenddate = pd.to_datetime(\"date\").date()\n\n" ]
[ -1 ]
[ "pandas", "python" ]
stackoverflow_0074151326_pandas_python.txt
Q: Is it possible to remotely upload a configuration to Twincat i.e. from a Python script? I'm working with a Beckhoff PLC running Twincat 3 and communicating to it using an Ubuntu client with Pyads. Is there any way to upload a project configuration to Twincat using Python, Bash, or something similar? My goal is to ...
Is it possible to remotely upload a configuration to Twincat i.e. from a Python script?
I'm working with a Beckhoff PLC running Twincat 3 and communicating to it using an Ubuntu client with Pyads. Is there any way to upload a project configuration to Twincat using Python, Bash, or something similar? My goal is to have multiple Python projects each with specific Twincat projects, and running one Python pro...
[ "There are a few steps to do what you want but it is theoretically possible (in that the toolchain exists, but I've not tested it)\nThe first element that you are missing with your understanding is the Automation Interface(AI) vs the Automation Device Specification(ADS).\nThe ADS is intended as a method for access...
[ 1, 0 ]
[]
[]
[ "linux", "plc", "python", "twincat" ]
stackoverflow_0073452145_linux_plc_python_twincat.txt
Q: How can I output the list of positions of the cells with specific text in Python? I am trying to find the postions of the cells which have "Pi". My dataframe is as follows. As you can see, the cells with "Pi" are in 0,2, 1,1, 1,3 in format column,row. Pi Column_B 0 F Kitten 1 L Pippy 2 Pi Lamb 3 ...
How can I output the list of positions of the cells with specific text in Python?
I am trying to find the postions of the cells which have "Pi". My dataframe is as follows. As you can see, the cells with "Pi" are in 0,2, 1,1, 1,3 in format column,row. Pi Column_B 0 F Kitten 1 L Pippy 2 Pi Lamb 3 K Pikjh 4 K Momo Therefore, the output that I want is [(0,2),(1,1),(1,3)]. M...
[ "From what I could understand you want to filter out and located the strings that contain the PI, key string and check out what indexes have it. And put it into a list?\nFor that a simple loc\nAnd a index class selections will help you out\npi_rows = df.loc[df.Pi.str.contains('Pi')]\n\npi_rows_index = df.loc[df.Co...
[ 0, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074147639_pandas_python.txt
Q: How to iterate through nested dictionaries and extract substructures and filter out certain keys? I have nested dictionaries, which are representations of XML that I have parsed using xmltodict. Now I want to give the possibility to extract certain sub-structures and remove keys which contain '@'. {'rpc': {'@xmlns...
How to iterate through nested dictionaries and extract substructures and filter out certain keys?
I have nested dictionaries, which are representations of XML that I have parsed using xmltodict. Now I want to give the possibility to extract certain sub-structures and remove keys which contain '@'. {'rpc': {'@xmlns': 'urn:1.0', '@message-id': '4', 'edit-config': {'target': {'running': None}, 'config': {'test'...
[ "This will work for you\norig_dict = {'rpc': {'@xmlns': 'urn:1.0',\n '@message-id': '4',\n 'edit-config': {'target': {'running': None},\n 'config': {'test': {'@xmlns': 'urn:2.0',\n 'common': {'abc': 'forward',\n 'bbc': {'geo-model': 'texas',\n 'remote': [{'id': '288',\n 'transport': 'tcp'...
[ 2, 0 ]
[]
[]
[ "dictionary", "nested", "python" ]
stackoverflow_0074150557_dictionary_nested_python.txt
Q: Improving python classes' methods I have come across an issue during set-up python classes. I have such classes: class ModifierType(ABC): """Represents a generic modifier type.""" ... class DefaultModifierType(ModifierType): """Represents a default modifier type.""" @staticmethod def check_mo...
Improving python classes' methods
I have come across an issue during set-up python classes. I have such classes: class ModifierType(ABC): """Represents a generic modifier type.""" ... class DefaultModifierType(ModifierType): """Represents a default modifier type.""" @staticmethod def check_modifier(modifier_id: str, item_name: st...
[ "You could add some further arguments, give them a default value, and ignore them where they are irrelevant or don't make sense.\nclass ModifierType():\n\n @staticmethod\n def check_modifier(modifier_id: str, item_name: str, default_modifiers: tuple[str] = None) -> None:\n ...\n\nclass DefaultModifierT...
[ 0 ]
[]
[]
[ "oop", "python", "python_class" ]
stackoverflow_0074151378_oop_python_python_class.txt
Q: How to make work javascript in template in django I'm trying to use js to save values in selected options. It works if js put it in my HTML template. Like this: {% load static %} {% include "header.html" %} {% block content %} <script src="{% static 'ReportingTool/js/sort_text.js' %}"></script> <script src="{% sta...
How to make work javascript in template in django
I'm trying to use js to save values in selected options. It works if js put it in my HTML template. Like this: {% load static %} {% include "header.html" %} {% block content %} <script src="{% static 'ReportingTool/js/sort_text.js' %}"></script> <script src="{% static 'ReportingTool/js/sort_number.js' %}"></script> ......
[ "change this:\n<script src=\"{% static 'ReportingTool/js/select.js' %}\"></script>\n\nTo\n<script src=\"{% static '/ReportingTool/js/select.js' %}\"></script> #You forgot to add forward slash(/) before ReportingTool.\n\nTry and see if this is works\n" ]
[ 0 ]
[]
[]
[ "django", "javascript", "python" ]
stackoverflow_0074151253_django_javascript_python.txt
Q: Memory not being released by httpx So I've been struggling to find a solution here that doesn't require me ripping out httpx and replacing it with another library, especially since the availability of http2/async libraries is slim to none. While I wait for the team at httpx to get back to me, I wanted to do a sani...
Memory not being released by httpx
So I've been struggling to find a solution here that doesn't require me ripping out httpx and replacing it with another library, especially since the availability of http2/async libraries is slim to none. While I wait for the team at httpx to get back to me, I wanted to do a sanity check here to see if what I'm seeing ...
[ "Having taken Tim Boddy's advice, I extended my test to request a URL multiple times and see if an actual OOM issue can happen. After running the function above 150 times, getting a 100kb page, I see that the memory usage levels out quite quickly and that at the end of the run there is only a ~5mb increase in usage...
[ 1 ]
[]
[]
[ "aiohttp", "httpx", "memory_leaks", "python" ]
stackoverflow_0074137279_aiohttp_httpx_memory_leaks_python.txt
Q: pylance: import could not be resolved I am using vscode with virtual environment (conda) to write python files on my mac. I keep seeing import problems from pylance for specific third party AND official libraries (for example pyproj, geopy for third party, math for preinstalled). for each file the errors/warnings ...
pylance: import could not be resolved
I am using vscode with virtual environment (conda) to write python files on my mac. I keep seeing import problems from pylance for specific third party AND official libraries (for example pyproj, geopy for third party, math for preinstalled). for each file the errors/warnings look as follows: I am sure that these pack...
[ "Add the following configuration in setting.json to remove these warnings\n \"python.analysis.diagnosticSeverityOverrides\": {\n \"reportMissingImports\": \"none\",\n \"reportUndefinedVariable\": \"none\"\n },\n\nUse ctrl + shift +p to open the command palette. Search Settings, there are two set...
[ 1 ]
[]
[]
[ "anaconda", "python", "virtualenv", "visual_studio_code" ]
stackoverflow_0074151422_anaconda_python_virtualenv_visual_studio_code.txt
Q: Python Contains in Panda DATAFRAME I am grouping in each iteration the same price, add quantity together and combine the name of the exchange like : asks_price asks_qty exchange_name_ask bids_price bids_qty exchange_name_bid 0 20156.51 0.000745 Coinbase 20153.28 0.000200 Coin...
Python Contains in Panda DATAFRAME
I am grouping in each iteration the same price, add quantity together and combine the name of the exchange like : asks_price asks_qty exchange_name_ask bids_price bids_qty exchange_name_bid 0 20156.51 0.000745 Coinbase 20153.28 0.000200 Coinbase 1 20157.52 0.050000 Co...
[ "To do that we can use astype(str)\nlike :\nself.global_orderbook = self.global_orderbook[self.global_orderbook.exchange_name_ask.astype(str).str.contains(name,regex=False)]\n\nAnd then it works we can use on column with string\n" ]
[ 1 ]
[]
[]
[ "dataframe", "python" ]
stackoverflow_0074151201_dataframe_python.txt
Q: Random model values inside list subfactory elements I cannot find an answer to my question. The thing is that I want to generate an User factory model where inside will be a subfactory List with Addresses. Each Addresses element must have different/random values (I mean that each element has non-repeatable unique ...
Random model values inside list subfactory elements
I cannot find an answer to my question. The thing is that I want to generate an User factory model where inside will be a subfactory List with Addresses. Each Addresses element must have different/random values (I mean that each element has non-repeatable unique values). In my current implementation, all of the element...
[ "In the code you provided, you have to replace fake.name() by Faker(\"name\"), where Faker is imported from factory at the beginning of your file.\nIndeed, fake.name() is called only once, when the class is defined, whereas you want it to happen each time you instantiate a factory.\nYou'll find a more detailed answ...
[ 0 ]
[]
[]
[ "factory_boy", "faker", "python" ]
stackoverflow_0071572939_factory_boy_faker_python.txt
Q: Error - cannot install Miniconda with RStudio I have written a R script where I use some python lines through the reticulate package. I need to share it with some colleagues who don't know about programming and I've created a batch file so I can run it without them even opening R. However, I tried using the instal...
Error - cannot install Miniconda with RStudio
I have written a R script where I use some python lines through the reticulate package. I need to share it with some colleagues who don't know about programming and I've created a batch file so I can run it without them even opening R. However, I tried using the install_miniconda() function to silently install python t...
[ "Try installing rminiconda from the github like this:\nremotes::install_github(\"hafen/rminiconda\")\nrminiconda::install_miniconda(name='your_name')\n\nAfter that you can specify the installation using reticulate like this:\npy <- rminiconda::find_miniconda_python(\"your_name\")\nreticulate::use_python(py, require...
[ 1 ]
[]
[]
[ "installation", "miniconda", "python", "r", "reticulate" ]
stackoverflow_0074151654_installation_miniconda_python_r_reticulate.txt
Q: Combining Sphinx Autodoc with Manual documentation I am currently working on a reference documentation that was initially documented manually with .. class:: All classes in the modules where documented this way. However, it was necessary recently to allow some automation to the documentation, such as show-inherita...
Combining Sphinx Autodoc with Manual documentation
I am currently working on a reference documentation that was initially documented manually with .. class:: All classes in the modules where documented this way. However, it was necessary recently to allow some automation to the documentation, such as show-inheritance of each class, but the problem now is how to combine...
[ "It is possible to use autodoc for some things (in this case it's just :show-inheritance:) and \"manual\" documentation (content that does not come from a docstring) for others, within the same directive.\nRemove .. class:: and ensure that all lines after the .. autoclass:: line have the same indentation. I think t...
[ 2 ]
[]
[]
[ "autodoc", "python", "python_sphinx" ]
stackoverflow_0074148639_autodoc_python_python_sphinx.txt
Q: Linked keys in dictionary I am trying to make, say foo and bar reference to the same object. This is the expected output: # note that variable d is a dictionary # d["foo"] and d["bar"] are both have a value of "hello" print(d["foo"]) print(d["bar"]) d["foo"] = "world" print(d["foo"]) print(d["bar"]) However, this...
Linked keys in dictionary
I am trying to make, say foo and bar reference to the same object. This is the expected output: # note that variable d is a dictionary # d["foo"] and d["bar"] are both have a value of "hello" print(d["foo"]) print(d["bar"]) d["foo"] = "world" print(d["foo"]) print(d["bar"]) However, this shows: hello hello world hello...
[ "What you want is not possible, you would need to use an object that it mutable (e.g. a list):\nd = {}\nd['foo'] = ['hello']\nd['bar'] = d['foo']\n\nprint(d['bar'])\n\nd['foo'][0] = 'world'\nprint(d['bar'])\n\noutput:\n['hello']\n['world']\n\n" ]
[ 2 ]
[]
[]
[ "dictionary", "python", "python_3.x" ]
stackoverflow_0074151662_dictionary_python_python_3.x.txt
Q: How do I prevent Visual Studio Code from accessing and showing global python installations on my system? I have 2 global python installations and 2 python venv. I don't use global interpreters and don't want vscode to show these 2. Is there a way to stop vscode from accessing these global python interpreters and ...
How do I prevent Visual Studio Code from accessing and showing global python installations on my system?
I have 2 global python installations and 2 python venv. I don't use global interpreters and don't want vscode to show these 2. Is there a way to stop vscode from accessing these global python interpreters and showing them? I had manually added the python interpreter paths for venvs and I am using that and not the glob...
[ "Python extension retrieves your environment variables to provide you with the choice of python interpreter.\nUnless you delete the python path in the environment variable, it will always be displayed, (but this is not recommended).\n", "Try opening VSCode as administrator. Right click VSCode and select 'Run as a...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x", "visual_studio_code" ]
stackoverflow_0074050385_python_python_3.x_visual_studio_code.txt
Q: What can I do to prevent an http 403 error in python requests in the docker container that does not occur outside the container? I am sending requests to web addresses and processing the responses. However, my program that uses requests and runs in a Docker container on my raspberry-pi only gets HTTP 403 errors no...
What can I do to prevent an http 403 error in python requests in the docker container that does not occur outside the container?
I am sending requests to web addresses and processing the responses. However, my program that uses requests and runs in a Docker container on my raspberry-pi only gets HTTP 403 errors no matter what address. If I use curl to call the address from within the Linux console of the Pi I get the normal response (http code 2...
[ "The website detects that you are using automation and won't let you access the information through script. I guess the problem is that you don't have good enough headers and thats why the website is blocking your request. My best advice is to use headless browser ( Which is slower but works for any site ) or try t...
[ 0 ]
[]
[]
[ "curl", "docker", "python", "python_requests", "raspberry_pi" ]
stackoverflow_0074151497_curl_docker_python_python_requests_raspberry_pi.txt
Q: How do I use multiple strings as keys in file renaming? Ok so I am making a file renaming program to help clean up file names. Everything seems to work how I would like it to but I have an issue that I would like to solve if possible. I want to take the cleanup section and make it more streamlined so it is not a b...
How do I use multiple strings as keys in file renaming?
Ok so I am making a file renaming program to help clean up file names. Everything seems to work how I would like it to but I have an issue that I would like to solve if possible. I want to take the cleanup section and make it more streamlined so it is not a bunch of repeated code. This is like what I am trying to accom...
[ "I was able to get this resolved in a different question. not exactly the answer but it accomplished what I was trying to do here in a different way. Here's the link to that one. How do I use a list or set as keys in file renaming\n" ]
[ 1 ]
[]
[]
[ "python", "refactoring" ]
stackoverflow_0074076969_python_refactoring.txt
Q: How to write correct executable_path of selenium webdriver I am using selenium with python and tried to run chromedriver in my Windows PC. I unpacked the zip file to several folder, listed in PATH. However, the same error always appers: "'./chromedriver.exe' executable needs to be in PATH. Please see https://chrom...
How to write correct executable_path of selenium webdriver
I am using selenium with python and tried to run chromedriver in my Windows PC. I unpacked the zip file to several folder, listed in PATH. However, the same error always appers: "'./chromedriver.exe' executable needs to be in PATH. Please see https://chromedriver.chromium.org/home". I`ve tried to put chromedriver.exe i...
[ "Try this:\ndriver = webdriver.Chrome(executable_path = r\"C:\\Users\\polikarpov\\AppData\\Local\\Microsoft\\WindowsApp\\chromedriver.exe\")\n\n", "You can try this\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\n\ndriverpath = Service('C:\\\\Users\\\\polikarpov\\\\AppData\...
[ 0, 0, 0 ]
[]
[]
[ "path", "python", "python_3.x", "selenium", "selenium_chromedriver" ]
stackoverflow_0074139294_path_python_python_3.x_selenium_selenium_chromedriver.txt
Q: How to fill missing year value with the existing one from other groups in pyton? I have a pandas dataframe like this: df= pd.DataFrame({'year':['2020','2030','2040','2030','2040','2030','2040'], 'group':['a', 'a', 'a', 'b', 'b', 'c', 'c'], 'values':[10,20,30,45,60,1...
How to fill missing year value with the existing one from other groups in pyton?
I have a pandas dataframe like this: df= pd.DataFrame({'year':['2020','2030','2040','2030','2040','2030','2040'], 'group':['a', 'a', 'a', 'b', 'b', 'c', 'c'], 'values':[10,20,30,45,60,12,36]}) year group value 2020 a 10 2030 ...
[ "Use DataFrame.pivot, forward and back filling missing values and reshape back:\ndf1 = df.pivot('group','year','values').ffill().bfill().unstack().reset_index(name='value')\nprint (df1)\n year group value\n0 2020 a 10.0\n1 2020 b 10.0\n2 2020 c 10.0\n3 2030 a 20.0\n4 2030 b 45....
[ 1, 0 ]
[]
[]
[ "group_by", "pandas", "python" ]
stackoverflow_0074151722_group_by_pandas_python.txt
Q: Finding two linear fits on different domains in the same data I'm trying to plot a 3rd-order polynomial, and two linear fits on the same set of data. My data looks like this: ,Frequency,Flux Density,log_freq,log_flux 0,1.25e+18,1.86e-07,18.096910013008056,-6.730487055782084 1,699000000000000.0,1.07e-06,14.84447717...
Finding two linear fits on different domains in the same data
I'm trying to plot a 3rd-order polynomial, and two linear fits on the same set of data. My data looks like this: ,Frequency,Flux Density,log_freq,log_flux 0,1.25e+18,1.86e-07,18.096910013008056,-6.730487055782084 1,699000000000000.0,1.07e-06,14.84447717574568,-5.97061622231479 2,541000000000000.0,1.1e-06,14.73319726510...
[]
[]
[ "I am not sure to well understand your request. If you want to fit a piecewise function made of three linear segments a method is described in https://fr.scribd.com/document/380941024/Regression-par-morceaux-Piecewise-Regression-pdf with theory and numerical examples.\nSeveral cases are considered. Among them the c...
[ -1 ]
[ "curve_fitting", "numpy", "polynomials", "python" ]
stackoverflow_0074147461_curve_fitting_numpy_polynomials_python.txt
Q: binning with multiple conditions in pandas dataframe Existing Dataframe : Id Total_amt amt_paid pending_amt A 100 0 100 B 200 20 180 C 500 500 0 D 1000 400 600 E 20...
binning with multiple conditions in pandas dataframe
Existing Dataframe : Id Total_amt amt_paid pending_amt A 100 0 100 B 200 20 180 C 500 500 0 D 1000 400 600 E 2000 100 1900 Expected Dataframe : Id ...
[ "Try use np.select\ncol = 'pending_amt'\ncol1 = 'Total_amt'\n\nconditions = [df[col] == df[col1], (df[col] < 250) & (df[col] != 0), (df[col] >= 250) & (df[col] <= 750), df[col] > 750, df[col] == 0]\n\nresult = ['No_Payment_Made','<250','250-750','>750','Payment_Completed']\n\ndf['status'] = np.select(conditions, re...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074151421_pandas_python.txt
Q: How to add verticale scatter with specific values on basic plot? I'm trying to reproduce the following plot from this paper : The plot show the mean accuracy across five runs and the vertical values shows the min and max accuracy. How can I add those verticale scatter with specific values ? My current code : def ...
How to add verticale scatter with specific values on basic plot?
I'm trying to reproduce the following plot from this paper : The plot show the mean accuracy across five runs and the vertical values shows the min and max accuracy. How can I add those verticale scatter with specific values ? My current code : def plot_losses(losses: Dict[float, Dict[float, List[float]]]) -> None: ...
[ "Prefer plt.errorbar (over plt.plot inside the for loop of plot_losses) and use the argument yerr to add the vertical bars with min and max values.\nHere is an example:\nimport numpy as np \nimport matplotlib.pyplot as plt \n\n# Generate data\nx = np.arange(10) + 1\ny1 = x/20\ny2 = x/25\n\n# Generate data for pseu...
[ 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074150240_matplotlib_python.txt
Q: List all supported codecs/fourcc tags on Raspberry Pi 4 using python, opencv This is my code for recording videos on Raspberry Pi 4 running Raspbian Buster: fourcc = cv2.VideoWriter_fourcc(*'MJPG') writer = cv2.VideoWriter(tempVideo.path, fourcc, framerate, resolution, True) writer.write(frame) However, no matter...
List all supported codecs/fourcc tags on Raspberry Pi 4 using python, opencv
This is my code for recording videos on Raspberry Pi 4 running Raspbian Buster: fourcc = cv2.VideoWriter_fourcc(*'MJPG') writer = cv2.VideoWriter(tempVideo.path, fourcc, framerate, resolution, True) writer.write(frame) However, no matter what codec I try, I keep getting errors like: OpenCV: FFMPEG: tag 0x47504a4d/'MJP...
[ "It's not an exact answer to the question, but what eventually helped me is cv2.getBuildInformation() is an answer. It shows what video formats are supported by particular build of opencv.\n", "Here is the link with all fourcc codecs.\nhttp://www.fourcc.org/codecs.php\nSome codecs don't exist there, but in your...
[ 1, 0 ]
[]
[]
[ "codec", "opencv", "python", "raspberry_pi", "video" ]
stackoverflow_0057983110_codec_opencv_python_raspberry_pi_video.txt
Q: Celery current_task.update_state not working I'm trying to add a long running async task and make it update it's progress status in intervals. I'm using a Django-rest-framework server, RabbitMQ broker, Celery worker. I'm able to add a task to celery, and even able to successfully retrieve the result upon task comp...
Celery current_task.update_state not working
I'm trying to add a long running async task and make it update it's progress status in intervals. I'm using a Django-rest-framework server, RabbitMQ broker, Celery worker. I'm able to add a task to celery, and even able to successfully retrieve the result upon task completion. However whenever trying to get the state b...
[ "checkout Asyncresult.\nalso check usages here: celery.result.AsyncResult usages\n" ]
[ 0 ]
[]
[]
[ "celery", "django", "django_celery", "python", "rabbitmq" ]
stackoverflow_0074150332_celery_django_django_celery_python_rabbitmq.txt
Q: Python function changing global variable? So I have a question that pertains to the scope of variables in functions in python, consider the following code: import numpy as np def function(data, mask): data *= mask data = np.ones(5) for x in range(2): print(data) mask = np.array([1, 0, 0, 0, 0]) f...
Python function changing global variable?
So I have a question that pertains to the scope of variables in functions in python, consider the following code: import numpy as np def function(data, mask): data *= mask data = np.ones(5) for x in range(2): print(data) mask = np.array([1, 0, 0, 0, 0]) function(data, mask) And the output is the fo...
[ "In Python, mutable objects passed to a function will mutate in-place if requested. Specifically, you are telling function to mutate data in-place by using the operator *=. If, on the other hand, you don't want data to mutate, simply do\ndata = data * mask\nwhich will simply assign the local (i.e. within the functi...
[ 2, 2, 1 ]
[]
[]
[ "python", "scope" ]
stackoverflow_0074151709_python_scope.txt
Q: tensorflow Conv2D layer input type issue I had a working PPO algorithm for the Cartpole environment from OpenAI Gym, and I wanted to tweak it to work for the CarRacing-v2 environment. I am having issues with having a wrong input type for the Conv2D layer. I am on Ubuntu 22.04LTS, in a conda env with gym==0.26.0, t...
tensorflow Conv2D layer input type issue
I had a working PPO algorithm for the Cartpole environment from OpenAI Gym, and I wanted to tweak it to work for the CarRacing-v2 environment. I am having issues with having a wrong input type for the Conv2D layer. I am on Ubuntu 22.04LTS, in a conda env with gym==0.26.0, tensorflow==2.10.0. The Observation from the Ca...
[ "It is simply a matter of when to consider it as single function scripts.\nSample: Sample is a template you add prediction Fn and scapes you create a racer.\nEasy is drive but staying on track all the time is the difficulty.\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"...
[ 0 ]
[]
[]
[ "deep_learning", "keras", "machine_learning", "python", "tensorflow" ]
stackoverflow_0074151027_deep_learning_keras_machine_learning_python_tensorflow.txt