content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Python C++ API function with multiple arguments I'm trying to create a python module using my C++ code and I want to declare a function with multiple arguments. (3 in this case) I've read the docs and it says that I must declare METH_VARARGS which I did, but I think I also must change something inside my function ...
Python C++ API function with multiple arguments
I'm trying to create a python module using my C++ code and I want to declare a function with multiple arguments. (3 in this case) I've read the docs and it says that I must declare METH_VARARGS which I did, but I think I also must change something inside my function to actually receive the arguments. Otherwise it gives...
[ "You are still expecting one argument.\nif (!PyArg_ParseTuple(args, \"s\", &command))\n\nthe documentation defines how you can expect optional or additional arguments, for example \"s|dd\" will expect a string and two optional numbers, you still have to pass two doubles to the function for when the numbers are avai...
[ 2 ]
[]
[]
[ "c++", "python", "python_3.x" ]
stackoverflow_0074597442_c++_python_python_3.x.txt
Q: BeautifulSoup Data Scraping : Unable to fetch correct information from the page I am trying to scrape data from:- https://www.canadapharmacy.com/ below are a few pages that I need to scrape:- https://www.canadapharmacy.com/products/abilify-tablet https://www.canadapharmacy.com/products/accolate https://www.cana...
BeautifulSoup Data Scraping : Unable to fetch correct information from the page
I am trying to scrape data from:- https://www.canadapharmacy.com/ below are a few pages that I need to scrape:- https://www.canadapharmacy.com/products/abilify-tablet https://www.canadapharmacy.com/products/accolate https://www.canadapharmacy.com/products/abilify-mt I need all the information from the page. I wrot...
[ "You can try the next working example:\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\n\ndata = []\nr = requests.get('https://www.canadapharmacy.com/products/abilify-tablet')\n\nsoup = BeautifulSoup(r.text,\"lxml\")\ntry:\n card = ''.join([x.get_text(' ',strip=True) for x in soup.select('di...
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0074596440_beautifulsoup_python_web_scraping.txt
Q: Remove duplicated elements (not lists) from 2D list, Python I would like to delete all the elements from list of lists that appear more than once and am looking for a smoother solution than this: Removing Duplicate Elements from List of Lists in Prolog I am not trying to remove duplicated lists inside of the paren...
Remove duplicated elements (not lists) from 2D list, Python
I would like to delete all the elements from list of lists that appear more than once and am looking for a smoother solution than this: Removing Duplicate Elements from List of Lists in Prolog I am not trying to remove duplicated lists inside of the parent list like here: How to remove duplicates from nested lists Cons...
[ "There may be sleeker ways, but this works:\nfrom collections import Counter\n\nmylist = [\n[1, 3, 4, 5, 77],\n[1, 5, 10, 3, 4],\n[1, 5, 100, 3, 4], \n[1, 3, 4, 5, 89], \n[1, 3, 5, 47, 48]]\n\n\nflat = [y for x in mylist for y in x] \ncount = Counter(flat)\nuniq = [x for x,y in count.items() if y == 1]\nnew_list...
[ 2, 1, 0 ]
[]
[]
[ "list", "pandas", "python" ]
stackoverflow_0074583876_list_pandas_python.txt
Q: How can I prove that a value from input is a number in Python? For a task I had to write a programm the programm functions nicely so I dont have a problem there. But I have to use input() and than I have to prove if the type is correct. I only needs integer but the type of input(5) is a str. Althought I need a int...
How can I prove that a value from input is a number in Python?
For a task I had to write a programm the programm functions nicely so I dont have a problem there. But I have to use input() and than I have to prove if the type is correct. I only needs integer but the type of input(5) is a str. Althought I need a int. But if use int(input()) thats also dont work because I want that m...
[ "s = input()\n\n\ntry:\n print(int(s))\n\nexcept:\n print(\"not int\")\n\n", "We can achieve this by using eval only.\ne.g:\nval = input()\ntry:\n val = eval(val)\nexcept NameError:\n pass\n\nIn try it will try to return the exact data type, like int, float, bool, dict, and list will works fine but if...
[ 0, -1 ]
[]
[]
[ "integer", "python", "string" ]
stackoverflow_0074597394_integer_python_string.txt
Q: How would I reference an external .py file containing an array, in another .py file, and use the array to retrieve information I am trying to retrive the data from an external array, to use in this program, but it gave me the error IndexError: list index out of range. This is the example data I used: [["James", 23...
How would I reference an external .py file containing an array, in another .py file, and use the array to retrieve information
I am trying to retrive the data from an external array, to use in this program, but it gave me the error IndexError: list index out of range. This is the example data I used: [["James", 23], ["Jack", 27], ["Jimothy", 21],["Jillian", 22]] And my example code: import random data = open('array.py', 'r').readlines() ran...
[ "You reading a python file as a text file & splitting accordingly. You don't even need to do that. Consider this example.\narray.py\narr_from_file_one = [[\"James\", 23], [\"Jack\", 27], [\"Jimothy\", 21],[\"Jillian\", 22]]\n\nMain.py\nfrom array import arr_from_file_one\n\nfor x in arr_from_file_one:\n print(x)...
[ 0 ]
[]
[]
[ "multidimensional_array", "python" ]
stackoverflow_0074597493_multidimensional_array_python.txt
Q: Two different Python max() function articles in GeeksForGeeks? I was reading about the key argument in max() in Python and came across two articles in GeeksForGeeks. First article: Python – max() function Second article: Python String | max(). In the first article, Example 2 reads: "By default, max() will retur...
Two different Python max() function articles in GeeksForGeeks?
I was reading about the key argument in max() in Python and came across two articles in GeeksForGeeks. First article: Python – max() function Second article: Python String | max(). In the first article, Example 2 reads: "By default, max() will return the string with the maximum lexicographic value" and gave the fol...
[]
[]
[ "The article is incorrect in one place and correct in another - you've typed the data incorrectly. It has Geeks: not geeks. Geeks has a lower lexicographical value than for, geeks has a higher one.\n" ]
[ -2 ]
[ "python" ]
stackoverflow_0074597526_python.txt
Q: Delete similar values in an array python numpy Is there an easy possibility to delete similar values in an array (with condition) without using a for loop? For example lets say I have an array np.array([1.2, 3.4, 3.5, 8.9, 10.9]) In this case, i would set the condition for example difference < 0.3 and get as an o...
Delete similar values in an array python numpy
Is there an easy possibility to delete similar values in an array (with condition) without using a for loop? For example lets say I have an array np.array([1.2, 3.4, 3.5, 8.9, 10.9]) In this case, i would set the condition for example difference < 0.3 and get as an output np.array([1.2, 3.4, 8.9, 10.9]) I haven't see...
[ "If you want to delete the successive values, you can compute the successive differences and perform boolean indexing:\na = np.array([1.2, 3.4, 3.5, 8.9, 10.9])\n\nout = a[np.r_[True, np.diff(a)>=0.3]]\n\nOr, if you want the absolute difference:\nout = a[np.r_[True, np.abs(np.diff(a))>=0.3]]\n\nOutput:\narray([ 1.2...
[ 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074597543_numpy_python.txt
Q: How to make vscode refer to a .py file when I click on a python method? When I press ctrl+click on a built-in or library function method, it redirects me not to the source file of that method, but to a stub .pyi file, which is wildly annoying. For example, if I go to print() function, the IDE will open builtins.py...
How to make vscode refer to a .py file when I click on a python method?
When I press ctrl+click on a built-in or library function method, it redirects me not to the source file of that method, but to a stub .pyi file, which is wildly annoying. For example, if I go to print() function, the IDE will open builtins.pyi file instead of builtins.py. I know this problem doesn't exist in PyCharm, ...
[ "Just create a .env file in root of your project and put path to python there, like that:\nPYTHONPATH=~/.venv/bin/python3\nIf needed, use : as a separator in case of multiple paths.\n" ]
[ 0 ]
[]
[]
[ "pylance", "python", "visual_studio_code" ]
stackoverflow_0071209751_pylance_python_visual_studio_code.txt
Q: Multiple conditions for string variable I am trying to add a new column "profile_type" to a dataframe "df_new" which contains the string "Decision Maker" if the "job_title" has any one of the following words: (Head or VP or COO or CEO or CMO or CLO or Chief or Partner or Founder or Owner or CIO or CTO or President...
Multiple conditions for string variable
I am trying to add a new column "profile_type" to a dataframe "df_new" which contains the string "Decision Maker" if the "job_title" has any one of the following words: (Head or VP or COO or CEO or CMO or CLO or Chief or Partner or Founder or Owner or CIO or CTO or President or Leaders), "Key Influencer" if the "job_ti...
[ "I would try something like this:\nimport numpy as np\n\ndm_titles = ['Head', 'VP', 'COO', ...]\nki_titles = ['Senior ', 'Consultant', 'Manager', ...]\n\n\nconditions = [\n(any([word in new_df['job_title'] for word in dm_titles])),\n(any([word in new_df['job_title'] for word in ki_titles])),\n(all([word not in n...
[ 0, 0 ]
[ "First, define a function that acts on a row of the dataframe, and returns what you want: in your case, 'Decision Maker' if the job_title contains any words in your list.\ndef is_key_worker(row):\n if (row[\"job_title\"] == \"CTO\" or row[\"job_title\"]==\"Founder\") # add more here.\n\nNext, apply the function ...
[ -1 ]
[ "multiple_conditions", "pandas", "python" ]
stackoverflow_0074570681_multiple_conditions_pandas_python.txt
Q: How do you convert a Dictionary to a List? For example, if the Dictionary is {0:0, 1:0, 2:0} making a list: [0, 0, 0]. If this isn't possible, how do you take the minimum of a dictionary, meaning the dictionary: {0:3, 1:2, 2:1} returning 1? A: convert a dictionary to a list is pretty simple, you have 3 flavors f...
How do you convert a Dictionary to a List?
For example, if the Dictionary is {0:0, 1:0, 2:0} making a list: [0, 0, 0]. If this isn't possible, how do you take the minimum of a dictionary, meaning the dictionary: {0:3, 1:2, 2:1} returning 1?
[ "convert a dictionary to a list is pretty simple, you have 3 flavors for that .keys(), .values() and .items()\n>>> test = {1:30,2:20,3:10}\n>>> test.keys() # you get the same result with list(test)\n[1, 2, 3]\n>>> test.values()\n[30, 20, 10]\n>>> test.items()\n[(1, 30), (2, 20), (3, 10)]\n>>> \n\n(in python 3 you w...
[ 5, 2, 1, 0 ]
[ "A dictionary is defined as the following:\ndict{[Any]:[Any]} = {[Key]:[Value]}\n\nThe problem with your question is that you haven't clarified what the keys are. \n1: Assuming the keys are just numbers and in ascending order without gaps, dict.values() will suffice, as other authors have already pointed out.\n2: ...
[ -1 ]
[ "dictionary", "list", "python", "python_2.7" ]
stackoverflow_0041915545_dictionary_list_python_python_2.7.txt
Q: Creating a Function to Count Unique Values Based on Another Column I have data that look like this. company_name new_company_status A Co.,Ltd Yes B. Inc No PT XYZ No PT DFE, Tbk. Yes A Co.,Ltd Yes PT DFE, Tbk. Yes I want to create a function in python to check every unique company name from 'company_name' ...
Creating a Function to Count Unique Values Based on Another Column
I have data that look like this. company_name new_company_status A Co.,Ltd Yes B. Inc No PT XYZ No PT DFE, Tbk. Yes A Co.,Ltd Yes PT DFE, Tbk. Yes I want to create a function in python to check every unique company name from 'company_name' column and compare the 'new_company_status', if the 'new_c...
[ "You can use masks and boolean addition to count the matches:\n# keep one company of each\nm1 = ~df['company_name'].duplicated()\n# is this a yes?\nm2 = df['new_company_status'].eq('Yes')\n\n# count cases for which both conditions are True\nout = (m1&m2).sum()\n\nOutput: 2\nIf a given company can have both Yes and ...
[ 1, 0 ]
[]
[]
[ "function", "pandas", "python", "unique_values" ]
stackoverflow_0074597716_function_pandas_python_unique_values.txt
Q: Auto fill a field in model via function django I was searching to find a way to fill a field of a model via a function. example: def myfunction(): return a_file class SomeModel(models.Model): a_field_name=models.FileField(value=my_function()) I some how was thinking to rewrite the save().share with me y...
Auto fill a field in model via function django
I was searching to find a way to fill a field of a model via a function. example: def myfunction(): return a_file class SomeModel(models.Model): a_field_name=models.FileField(value=my_function()) I some how was thinking to rewrite the save().share with me your idea
[ "Well as per my understanding your question you can try it like this:\n def Function(self, parameter: int):\n return Models.objects.update_or_create(\n variable=parameter\n )\n\nPlease reply to this message If the issue still persist.\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "django_rest_framework", "python" ]
stackoverflow_0074597633_django_django_models_django_rest_framework_python.txt
Q: How do I skip some value when I'm using pandas df.transform I want to convert the names of items that occur less than two times to None But I don't want some items to be changed. The original df | Column A | Column B | | -------- | -------- | | Cat | Fish | | Cat | Bone | | Camel | Fish | ...
How do I skip some value when I'm using pandas df.transform
I want to convert the names of items that occur less than two times to None But I don't want some items to be changed. The original df | Column A | Column B | | -------- | -------- | | Cat | Fish | | Cat | Bone | | Camel | Fish | | Dog | Bone | | Dog | Bone | | Tiger | Bone...
[ "Use several conditions for your boolean indexing:\n# is the count <= 2?\nm1 = df.groupby('Column A')['Column A'].transform('count').lt(2)\n# is the name NOT Tiger?\nm2 = df['Column A'].ne('Tiger')\n\n# if both conditions are True, change to \"None\"\ndf.loc[m1&m2, 'Column A'] = \"None\"\n\n" ]
[ 3 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074597748_pandas_python.txt
Q: How to catch an element from a for loop in Django template? I'm looping through to different categories and rendering results (of its name and its associated pages). This code is rendering correctly. {% for category in categories %} <div class="row"> <div class="col-lg-4"> <h3><a href="{{category.get_a...
How to catch an element from a for loop in Django template?
I'm looping through to different categories and rendering results (of its name and its associated pages). This code is rendering correctly. {% for category in categories %} <div class="row"> <div class="col-lg-4"> <h3><a href="{{category.get_absolute_url}}"></a>{{category.category_name}}</h3> {% for...
[ "As per my understanding of your question. You can try it soo:\nYou can place this inside your for loop so that whenever you it iterates and by that you can use your if value to do some operations for specific value.\n{% if some_variable == some_value %}\n {{ do_something }}\n{% endif %}\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_templates", "for_loop", "python" ]
stackoverflow_0074597538_django_django_templates_for_loop_python.txt
Q: I want to make a Guess the number code without input import random number = random.randint(1, 10) player_name = "doo" number_of_guesses = 0 print('I\'m glad to meet you! {} \nLet\'s play a game with you, I will think a number between 1 and 10 then you will guess, alright? \nDon\'t forget! You have only 3 chances ...
I want to make a Guess the number code without input
import random number = random.randint(1, 10) player_name = "doo" number_of_guesses = 0 print('I\'m glad to meet you! {} \nLet\'s play a game with you, I will think a number between 1 and 10 then you will guess, alright? \nDon\'t forget! You have only 3 chances so guess:'.format(player_name)) while number_of_guesses <...
[ "As i understand, you want to \"test\" your program and therefore use a list of inputs instead of real user inputs?\nHowever, you made a mistake in line 6\nfor number in lis: -> for number in list:\nIf I change this line it gives me this output. Is that what you wanted?\nI am Guessing a number between 1 and 10:\n\n...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074596571_python.txt
Q: How to split number into combination to make the same number when sum I have bit stuck trying to implement a combination for example : inp = 3 Need combination which could make again the same value like below `(1,1,1) -> sum -> 3 (2,1) -> sum -> 3 (1,2) -> sum -> 3 (0,3) -> sum -> 3 (3,0) -> sum -> 3` Not ...
How to split number into combination to make the same number when sum
I have bit stuck trying to implement a combination for example : inp = 3 Need combination which could make again the same value like below `(1,1,1) -> sum -> 3 (2,1) -> sum -> 3 (1,2) -> sum -> 3 (0,3) -> sum -> 3 (3,0) -> sum -> 3` Not sure how to achieve this. Any idea to start with the approach
[ "I remember this question. My teacher told me to solve this.\nThis is the solution:\n\n# arr - array to store the combination\n# index - next location in array\n# num - given number\n# reducedNum - reduced number \n\n\ndef findCombinationsUtil(arr, index, num,\n\n reducedNum):\n \n\n ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074597578_python.txt
Q: Numba: No implementation of function Function() found for signature: I was able to use Numba to solve a slow itertuples iteration issue with code provided in the answer of this question however when I try it on a new function with a similar loop format i run into this error No implementation of function Function(<...
Numba: No implementation of function Function() found for signature:
I was able to use Numba to solve a slow itertuples iteration issue with code provided in the answer of this question however when I try it on a new function with a similar loop format i run into this error No implementation of function Function(<built-in function setitem>) found for signature: >>> setitem(array(floa...
[ "It would help if you simplified the question and added a reproducible example.\nBut based on the Exception, it looks like you're trying to set the item with a different incompatible type:\nsetitem(array(float64, 1d, C), int64, datetime64[ns])\nstart_dtm = float64\ni = int64\nstart_idx = datetime64[ns...
[ 1 ]
[]
[]
[ "numba", "numpy", "python" ]
stackoverflow_0074595975_numba_numpy_python.txt
Q: PLY reduce/reduce conflict I am encountering a reduce / reduce conflict that I am unsure how to tackle. I have the following grammar : Type -> int | bool | void | string | char | Identifier Expression -> ... ... | Expression Ind...
PLY reduce/reduce conflict
I am encountering a reduce / reduce conflict that I am unsure how to tackle. I have the following grammar : Type -> int | bool | void | string | char | Identifier Expression -> ... ... | Expression Index | Identifier ...
[ "Either you need to use some mechanism outside of the parser (such as a symbol table) to distinguish between Types and other Identifiers, or you need to avoid forcing the parser to immediately reduce identifier. That's a bit of a pain, because it requires a bit of duplication of grammar rules.\nHere's one possibili...
[ 1 ]
[]
[]
[ "compiler_construction", "ply", "python" ]
stackoverflow_0074596969_compiler_construction_ply_python.txt
Q: MySQL Deadlock when using DataFrame.to_sql in multithreaded environment I have a multithreaded ETL process inside a docker container that looks like this simplified code: class Query(abc.ABC): def __init__(self): self.connection = sqlalchemy.create_engine(MYSQL_CONNECTION_STR) def load(self, df: p...
MySQL Deadlock when using DataFrame.to_sql in multithreaded environment
I have a multithreaded ETL process inside a docker container that looks like this simplified code: class Query(abc.ABC): def __init__(self): self.connection = sqlalchemy.create_engine(MYSQL_CONNECTION_STR) def load(self, df: pd.DataFrame) -> None: df.to_sql( name=self.table, con=sel...
[ "If multiple connections try to INSERT or UPDATE to the same table concurrently, you can get deadlocks from contention in the tables' indexes.\nYour question says you perform your INSERTs from multiple threads. Performing INSERTs requires checking constraints such primary key uniqueness and foreign key validity, a...
[ 1, 0 ]
[]
[]
[ "deadlock", "multithreading", "mysql", "python", "sqlalchemy" ]
stackoverflow_0063940226_deadlock_multithreading_mysql_python_sqlalchemy.txt
Q: Python progress bar and downloads I have a Python script that launches a URL that is a downloadable file. Is there some way to have Python display the download progress as oppose to launching the browser? A: I've just written a super simple (slightly hacky) approach to this for scraping PDFs off a certain site. ...
Python progress bar and downloads
I have a Python script that launches a URL that is a downloadable file. Is there some way to have Python display the download progress as oppose to launching the browser?
[ "I've just written a super simple (slightly hacky) approach to this for scraping PDFs off a certain site. Note, it only works correctly on Unix based systems (Linux, mac os) as PowerShell does not handle \"\\r\":\nimport sys\nimport requests\n\nlink = \"http://indy/abcde1245\"\nfile_name = \"download.data\"\nwith o...
[ 147, 79, 55, 27, 10, 7, 6, 4, 4, 0, 0 ]
[ "You can stream a downloads as it is here -> Stream a Download.\nAlso you can Stream Uploads.\nThe most important streaming a request is done unless you try to access the response.content\nwith just 2 lines\nfor line in r.iter_lines(): \n if line:\n print(line)\n\nStream Requests\n" ]
[ -1 ]
[ "download", "progress_bar", "python" ]
stackoverflow_0015644964_download_progress_bar_python.txt
Q: ImportError: cannot import name 'docevents' from 'botocore.docs.bcdoc' in AWS CodeBuild ImportError: cannot import name 'docevents' from 'botocore.docs.bcdoc' (/python3.7/site-packages/botocore/docs/bcdoc/init.py) Traceback (most recent call last): File "/root/.pyenv/versions/3.7.6/bin/aws", line 19, in <module>...
ImportError: cannot import name 'docevents' from 'botocore.docs.bcdoc' in AWS CodeBuild
ImportError: cannot import name 'docevents' from 'botocore.docs.bcdoc' (/python3.7/site-packages/botocore/docs/bcdoc/init.py) Traceback (most recent call last): File "/root/.pyenv/versions/3.7.6/bin/aws", line 19, in <module> import awscli.clidriver File "/root/.pyenv/versions/3.7.6/lib/python3.7/site-packages...
[ "Reading this GitHub issue #2596. i fixed my error.\nJust before the PRE_BUILD section, I added this line to my buildspec-cd.yml file:\npip3 install --upgrade awscli\ninstall:\n commands:\n - pip3 install awsebcli --upgrade\n - eb --version\n - pip3 install --upgrade awscli\n\n pre_build:\n ...
[ 146, 14, 7, 3, 1, 0, 0 ]
[]
[]
[ "amazon_web_services", "aws_codebuild", "docker", "python" ]
stackoverflow_0064596394_amazon_web_services_aws_codebuild_docker_python.txt
Q: Save the loop output into csv file I want to save the loop result into a csv file or dataframe; the below code just writes the tweets to the console. j =1 sortedDF = tweets_df.sort_values(by = ['Polarity']) for i in range (0, sortedDF.shape[0]): if(sortedDF['Analysis'][i] == 'Positive'): print(str(j)+...
Save the loop output into csv file
I want to save the loop result into a csv file or dataframe; the below code just writes the tweets to the console. j =1 sortedDF = tweets_df.sort_values(by = ['Polarity']) for i in range (0, sortedDF.shape[0]): if(sortedDF['Analysis'][i] == 'Positive'): print(str(j)+')'+ sortedDF['transalted'][i]) ...
[ "with open(\"some.csv\", \"w\") as f:\n j = 1\n sortedDF = tweets_df.sort_values(by=['Polarity'])\n for i in range(0, sortedDF.shape[0]):\n if (sortedDF['Analysis'][i] == 'Positive'):\n f.write(str(j) + ')' + sortedDF['transalted'][i])\n print()\n j = j + 1\n\n", "...
[ 0, 0 ]
[]
[]
[ "export_to_csv", "python" ]
stackoverflow_0074597750_export_to_csv_python.txt
Q: Confused by convention in paho-mqtt for asigning a built in method as a function that i create (but without arguments) I am trying to get my head around the paho-MQTT library. I am struggling to understand what is clearly a convention in the coding of the library, but which doesn't make sense to me. I am happy to ...
Confused by convention in paho-mqtt for asigning a built in method as a function that i create (but without arguments)
I am trying to get my head around the paho-MQTT library. I am struggling to understand what is clearly a convention in the coding of the library, but which doesn't make sense to me. I am happy to look this up, if someone can give me the topic I should be looking for. A lot of paho-mqtt tutorials and PAHO Foundation pag...
[ "You will never explicitly call any of the callback functions. The client will call them from it's event loop at the appropriate time.\nclient.on_message = on_message is how yo tell the client which function to call (in the future) when a message arrives. Passing a function name with no arguments passes a handle to...
[ 0 ]
[]
[]
[ "mqtt", "paho", "python" ]
stackoverflow_0074595606_mqtt_paho_python.txt
Q: How to add a requirement.txt in my project python In fact When I do pip freeze > requirements.txt to put all the packages that I use in my project in a requirements.txt, it puts all python packages that I have in my pc and this despite I have activated my visual environment. In my project path I activated my venv ...
How to add a requirement.txt in my project python
In fact When I do pip freeze > requirements.txt to put all the packages that I use in my project in a requirements.txt, it puts all python packages that I have in my pc and this despite I have activated my visual environment. In my project path I activated my venv then I did pip freeze > requirements.txt I had a requir...
[ "You may have inherited some global site packages when you created the venv. Likely ones you had pip installed while not in any venv. Try creating the venv using\nWindows:\npython -m venv (venv name here) --no-site-packages\nLinux:\npython3 -m venv (venv name here) --no-site-packages\nThe no site packages argument ...
[ 1, 1, 0 ]
[]
[]
[ "pip", "python", "python_venv", "requirements.txt" ]
stackoverflow_0074592548_pip_python_python_venv_requirements.txt.txt
Q: AttributeError: module 'h11' has no attribute 'Event' ` Already up to date. venv "C:\StableDiffusion\stable-diffusion-webui\venv\Scripts\Python.exe" Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] Commit hash: 828438b4a190759807f9054932cae3a8b880ddf1 Installing requirements fo...
AttributeError: module 'h11' has no attribute 'Event'
` Already up to date. venv "C:\StableDiffusion\stable-diffusion-webui\venv\Scripts\Python.exe" Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] Commit hash: 828438b4a190759807f9054932cae3a8b880ddf1 Installing requirements for Web UI Launching Web UI with arguments: Traceback (most r...
[ "Seems you have to reinstall httpcore in version 0.15\n\npip install --force-reinstall httpcore==0.15\nworks as a temporary workaround until some other fix is found.\nThat or just append it to your requirement.txt\nThis comes from a recent update in httpcore and nothing related to this repository.\n\nSource: https:...
[ 0, 0, 0 ]
[]
[]
[ "attributeerror", "events", "python" ]
stackoverflow_0074578145_attributeerror_events_python.txt
Q: Looking to create a string that is joint by commas to parse a json array I have the below code, however I need the output to return with commas between the pair of curly brackets. i.e., {},{}. ` for i in range (0,Eqpt_List.shape[0]): EquipmentCode = Eqpt_List['assetitemindex'].iloc[i] TotalRate = Eqpt_List...
Looking to create a string that is joint by commas to parse a json array
I have the below code, however I need the output to return with commas between the pair of curly brackets. i.e., {},{}. ` for i in range (0,Eqpt_List.shape[0]): EquipmentCode = Eqpt_List['assetitemindex'].iloc[i] TotalRate = Eqpt_List['hourlycostprice'].iloc[i] test1 = { "equipmentCode": str(Equipme...
[]
[]
[ "Why not just print comma then new line char after print?\nIn python print() we have end argument that print() prints after the message. By default it’s = new line. So we just need to change it to either comma & new line or just comma.\nI’m putting both the comma & new line but if you just need comma then delete \\...
[ -1 ]
[ "arrays", "for_loop", "json", "python" ]
stackoverflow_0074597868_arrays_for_loop_json_python.txt
Q: Regular expression to make non-greedy I have a text like this EXPRESS blood| muscle| testis| normal| tumor| fetus| adult RESTR_EXPR soft tissue/muscle tissue tumor Right now I want to only extract the last item in EXPRESS line, which is adult. My pattern is: [|](.*?)\n The code goes greedy to muscle| test...
Regular expression to make non-greedy
I have a text like this EXPRESS blood| muscle| testis| normal| tumor| fetus| adult RESTR_EXPR soft tissue/muscle tissue tumor Right now I want to only extract the last item in EXPRESS line, which is adult. My pattern is: [|](.*?)\n The code goes greedy to muscle| testis| normal| tumor| fetus| adult. Can I know...
[ "You can take the capture group value exclude matching pipe chars after matching a pipe char followed by optional spaces.\nIf there has to be a newline at the end of the string:\n\\|[^\\S\\n]*([^|\\n]*)\\n\n\nExplanation\n\n\\| Match |\n[^\\S\\n]* Match optional whitespace chars without newlines\n( Capture group 1\...
[ 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074596624_python_regex.txt
Q: How to speed up calculation to get the minimum value of row by row a calculation over 2 dataframes in pandas I have 2 (for presentation simplified) Dataframes: table1_id lat long table2_id 1 5.5 45.5 2 5.2 50.2 3 8.9 49.7 table2_id lat long 1 5.0 47.2 2 8.5 22.5 3 2.1 33.3 Table1 has >40000 rows. Table2 ...
How to speed up calculation to get the minimum value of row by row a calculation over 2 dataframes in pandas
I have 2 (for presentation simplified) Dataframes: table1_id lat long table2_id 1 5.5 45.5 2 5.2 50.2 3 8.9 49.7 table2_id lat long 1 5.0 47.2 2 8.5 22.5 3 2.1 33.3 Table1 has >40000 rows. Table2 has 3000 rows. What I want is to find the table2_id for each item in table 1 which has th...
[ "As far as I understand, the geodesic function does not support vectorization. Therefore, you need to implement the distance calculation function for coordinate vectors yourself. Fortunately, there are many such implementations.\nHere is a very simple implementation. Here is a complete example of the solution to yo...
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python", "vectorization" ]
stackoverflow_0074594718_dataframe_pandas_python_vectorization.txt
Q: Call Dlang function in struct with Python ctypes I have a .so (written in Dlang) which has a struct as below struct A { static A* load(string folder) { } } I am trying to consume the .so in Python. I am not sure how can i call the function which is present inside the structure. My python code is below fr...
Call Dlang function in struct with Python ctypes
I have a .so (written in Dlang) which has a struct as below struct A { static A* load(string folder) { } } I am trying to consume the .so in Python. I am not sure how can i call the function which is present inside the structure. My python code is below from ctypes import * class A(Structure): _fields_...
[ "The ctypes module is designed to access a C module. So, you should define a C compatible structure and implement a C compatible function that calls your A.load() and converts arguments and return value.\nThis is an example for that, assuming the A has a string member.\nimport std.string;\nimport std.conv;\nimport ...
[ 0 ]
[]
[]
[ "ctypes", "d", "python" ]
stackoverflow_0074595383_ctypes_d_python.txt
Q: Pulling files from real devices in appium iOS Im having a difficult time trying to pull files and folders in one of my automated tests using appium. We use real devices for testing and I would like to use driver.pull_file() to accomplish this task. The files I want exist in the On My iPad folder, and I cannot figu...
Pulling files from real devices in appium iOS
Im having a difficult time trying to pull files and folders in one of my automated tests using appium. We use real devices for testing and I would like to use driver.pull_file() to accomplish this task. The files I want exist in the On My iPad folder, and I cannot figure out how to get the file path of the actual file ...
[ "How to get the file path of a file on iOS.\n" ]
[ 0 ]
[]
[]
[ "appium", "ios", "python" ]
stackoverflow_0074594979_appium_ios_python.txt
Q: FastAPI: Internal server error when accessing through OpenAPI docs I am exposing API using OpenAPI which is developed using FastAPI. Here is my pydantic model: class ComponentListResponse(BaseModel): """ This model is to list the component """ tag_info = ComponentSummaryTagInfoResp heath...
FastAPI: Internal server error when accessing through OpenAPI docs
I am exposing API using OpenAPI which is developed using FastAPI. Here is my pydantic model: class ComponentListResponse(BaseModel): """ This model is to list the component """ tag_info = ComponentSummaryTagInfoResp heath_status : Optional[str] = Field(alias="healthStatus") stage : Option...
[ "Your models are wrongly defined. The \"=\" sign should be use to provide default values not type definitions.\nTherefore your models should be define as follows:\nclass ComponentListResponse(BaseModel):\n \"\"\"\n This model is to list the component\n\n \"\"\"\n \n tag_info = ComponentSummaryTagInf...
[ 0 ]
[]
[]
[ "fastapi", "openapi", "python", "swagger" ]
stackoverflow_0074596711_fastapi_openapi_python_swagger.txt
Q: Django - How can view function see difference of the endpoint being hit , without any value stated in the url? I'm fairly new to Django and here's my case. If i have 3 endpoints that i can't modify, and i need to point them to one same View function such as : urls.py urlpatterns = [ ... url(r'^a/', views.funct...
Django - How can view function see difference of the endpoint being hit , without any value stated in the url?
I'm fairly new to Django and here's my case. If i have 3 endpoints that i can't modify, and i need to point them to one same View function such as : urls.py urlpatterns = [ ... url(r'^a/', views.functionz.as_view(), name='a'), url(r'^b/', views.functionz.as_view(), name='b'), url(r'^c/', views.functionz.as_...
[ "I don't know if mapping diffrent url patterns to same view is a good idea, but if you want to do that logic with in the post you probably can use the get_full_path to get the current path and parse the last the item.\nClass XYZ(API View):\n def post(self, request, format=None):\n current_path = request....
[ 0 ]
[]
[]
[ "backend", "django", "django_rest_framework", "django_views", "python" ]
stackoverflow_0074598040_backend_django_django_rest_framework_django_views_python.txt
Q: Python check if values of a dataframe are present in another dataframe index I have two dataframes. I want to drop the values in first dataframe (default) after comparing with second dataframe (provided by user) def_df = pd.DataFrame([['alpha','beta'],['gamma','delta']],index=['ab_plot',gd_plot]) 0...
Python check if values of a dataframe are present in another dataframe index
I have two dataframes. I want to drop the values in first dataframe (default) after comparing with second dataframe (provided by user) def_df = pd.DataFrame([['alpha','beta'],['gamma','delta']],index=['ab_plot',gd_plot]) 0 1 ab_plot alpha beta gd_plot gamma delta rk_plot ray kite ...
[ "If need test all values if match at least one value by index from user_df use DataFrame.isin with DataFrame.any and filter def_df.index:\n#changed data\ndef_df = pd.DataFrame([['alpha','beta'],['gamma','beta']],index=['ab_plot','gd_plot'])\n\nuser_df = pd.DataFrame([10,20],index=['alpha','beta'])\n\nposble_plots_w...
[ 2 ]
[]
[]
[ "dataframe", "numpy", "numpy_ndarray", "pandas", "python" ]
stackoverflow_0074598122_dataframe_numpy_numpy_ndarray_pandas_python.txt
Q: Trying to execute a `ddb_to_es.py` file in order to backfill OpenSearch index on my DynamoDB table (for @searchable Amplify directive) TLDR: I'm trying to execute a ddb_to_es.py file in order to backfill OpenSearch index on my DynamoDB table. But when I run the command in the terminal nothing happens. I've made an...
Trying to execute a `ddb_to_es.py` file in order to backfill OpenSearch index on my DynamoDB table (for @searchable Amplify directive)
TLDR: I'm trying to execute a ddb_to_es.py file in order to backfill OpenSearch index on my DynamoDB table. But when I run the command in the terminal nothing happens. I've made an update to my Amplify/GraphQL schema and added a @searchable directive. I need to backfill OpenSearch index on my DynamoDB table, as per the...
[ "I have got it working. It seemed to respond this morning where it didn't on Friday. This is what I did today:\nInstall file dependencies:\npip3 install boto3\n\nExecute file in cli (I changed the file name to the pathname):\npython3 /Users/myName/myPythonExecution/ddb_to_es.py \\\n --rn 'eu-west-2' \\\n --tn '<D...
[ 0 ]
[]
[]
[ "amazon_dynamodb", "amazon_web_services", "aws_appsync", "graphql", "python" ]
stackoverflow_0074565212_amazon_dynamodb_amazon_web_services_aws_appsync_graphql_python.txt
Q: Python- list of lists with values.tolist() I need to read a single column from db table as a list of values. I tried to do that with following line of code: ids_list = (pd.read_sql_query(q, db_internal.connection)).values.tolist() when I use the values.tolist() it does what documentation says, that is turns the d...
Python- list of lists with values.tolist()
I need to read a single column from db table as a list of values. I tried to do that with following line of code: ids_list = (pd.read_sql_query(q, db_internal.connection)).values.tolist() when I use the values.tolist() it does what documentation says, that is turns the df into list of lists: [['0x0043Fcb34e7470130fDe2...
[ "You can simply iterate through the list with:\n[i for i in ids_list[0]]\n\nI hope this helps.\n", "Just convert tolist() generated list into list with the first element only.\nids_list = list(i[0] for i in (pd.read_sql_query(q, db_internal.connection)).values.tolist())\n\n" ]
[ 2, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074598156_pandas_python.txt
Q: Hypothesis create column with pd.datetime dtype in given test-dataframe I want to test whether a certain method can handle different dates in a pandas dataframe, which it takes as an argument. The following example should clarify what kind of setup I want. In the example column('Date', dtype=pd.datetime) does not ...
Hypothesis create column with pd.datetime dtype in given test-dataframe
I want to test whether a certain method can handle different dates in a pandas dataframe, which it takes as an argument. The following example should clarify what kind of setup I want. In the example column('Date', dtype=pd.datetime) does not work for creating a date column in the test dataframe: from hypothesis import...
[ "Use dtype=\"datetime64[ns]\" instead of dtype=pd.datetime.\n\nI've opened an issue to look into this in more detail and give helpful error messages when passed pd.datetime, datetime, or a unitless datetime dtype; this kind of confusion isn't the user experience we want to offer!\n" ]
[ 1 ]
[]
[]
[ "pandas", "python", "python_hypothesis", "unit_testing" ]
stackoverflow_0074591552_pandas_python_python_hypothesis_unit_testing.txt
Q: Error when writting image from python to Excel I am trying to run this code: wb=openpyxl.load_workbook('Output_Report_v16.xlsm',read_only=False,keep_vba=True) sheets=wb.sheetnames sheet_InputData_Overview=wb [sheets[7]] img=openpyxl.drawing.image.Image('Eink_Liq.png') sheet_InputData_Overview.add_image(ws.cell(2,...
Error when writting image from python to Excel
I am trying to run this code: wb=openpyxl.load_workbook('Output_Report_v16.xlsm',read_only=False,keep_vba=True) sheets=wb.sheetnames sheet_InputData_Overview=wb [sheets[7]] img=openpyxl.drawing.image.Image('Eink_Liq.png') sheet_InputData_Overview.add_image(ws.cell(2,28)) wb.save('Output_Report_v16.xlsm') When python...
[ "Seem to be a few issues with your code but the problem is appying the image.\nYou created the img object but never use it.\nws.cell references an object not defined\n...\nwb=openpyxl.load_workbook('Output_Report_v16.xlsm',read_only=False,keep_vba=True)\nsheets=wb.sheetnames\nsheet_InputData_Overview=wb [sheets[7]]...
[ 1 ]
[ "Simple fix after looking at the attributes of Cell. Try this:\nws[cell].style = Style(font=Font(color=Color(colors.RED))) \n\n" ]
[ -1 ]
[ "excel", "image", "numpy", "openpyxl", "python" ]
stackoverflow_0074597600_excel_image_numpy_openpyxl_python.txt
Q: check if string exists on a json (python) i only need to print something if a certain condition was met, not all of the data data = json.loads(r.text) for value in data: if value['username'] == 'GDjkhp': print(value['content'], '\n') the following code gives me a keyerror
check if string exists on a json (python)
i only need to print something if a certain condition was met, not all of the data data = json.loads(r.text) for value in data: if value['username'] == 'GDjkhp': print(value['content'], '\n') the following code gives me a keyerror
[]
[]
[ "try using the get() method:\nif value.get('username','no_username') == 'GDjkhp':\n print(value.get('content',''), '\\n')\n\n\nif you need to check if a key is in there:\nif 'content' not in value:\n print('content not in json')\n\n" ]
[ -1 ]
[ "json", "python" ]
stackoverflow_0074598184_json_python.txt
Q: Retrieve Azure IoT connection string using Python I have the following code conn_str = "HostName=my_host.azure-devices.net;DeviceId=MY_DEVICE;SharedAccessKey=MY_KEY" device_conn = IoTHubDeviceClient.create_from_connection_string(conn_str) await device_conn.connect() This works fine, but only because I've manually...
Retrieve Azure IoT connection string using Python
I have the following code conn_str = "HostName=my_host.azure-devices.net;DeviceId=MY_DEVICE;SharedAccessKey=MY_KEY" device_conn = IoTHubDeviceClient.create_from_connection_string(conn_str) await device_conn.connect() This works fine, but only because I've manually retrieved this from the IoT hub and pasted it into the...
[ "The device id and key are you give to the each device and you choose where to store/how to load it. The connection string is just a concept for easy to get started but it has no meaning in the actual technical level.\nYou can use create_from_symmetric_key(symmetric_key, hostname, device_id, **kwargs) to direct pas...
[ 1, 0, 0 ]
[]
[]
[ "azure_iot_hub", "python" ]
stackoverflow_0074563593_azure_iot_hub_python.txt
Q: I want to create a wordlist of incrementing decimal numbers by 1 using python I know i can create a wordlist using programms like 'crunch' but i wanted to use python in hopes of learning something new. so I'm doing this CTF where i need a wordlist of numbers from 1 to maybe 10,000 or more. all the wordlists in Sec...
I want to create a wordlist of incrementing decimal numbers by 1 using python
I know i can create a wordlist using programms like 'crunch' but i wanted to use python in hopes of learning something new. so I'm doing this CTF where i need a wordlist of numbers from 1 to maybe 10,000 or more. all the wordlists in Seclists have at least 3 zeroes in front of them, i dont want to use those files becau...
[ "this works better, then pipe the results into a file.\n#!/usr/bin/python3\n\ndef generate():\n\n n = 10000\n print(\"\\n\".join(str(v) for v in range(1, n + 1)))\ngenerate()\n\n\n", "Here is how you can create a wordlist of such numbers and get it into a .csv file:\ndef generate(min=0,max=10000):\n...
[ 1, 0 ]
[]
[]
[ "ctf", "python" ]
stackoverflow_0074597397_ctf_python.txt
Q: A regex pattern that matches all words starting from a word with an s and stopping before a word that starts with an s I'm trying to capture words in a string such that the first word starts with an s, and the regex stops matching if the next word also starts with an s. For example. I have the string " Stack, Code...
A regex pattern that matches all words starting from a word with an s and stopping before a word that starts with an s
I'm trying to capture words in a string such that the first word starts with an s, and the regex stops matching if the next word also starts with an s. For example. I have the string " Stack, Code and StackOverflow". I want to capture only " Stack, Code and " and not include "StackOverflow" in the match. This is what I...
[ "I think this should work. I adapted the regex from this thread. You can also test it out here. I have also included a non-regex solution. I basically track the first occurrence of a word starting with an 's' and the next word starting with an 's' and get the words in that range.\nimport re\n\nteststring = \" Stac...
[ 0, 0 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0074595679_python_regex_string.txt
Q: Can't find ADP login page password box by webdriver I want to download report from ADP platform through webdriver, but I can't locate the login page password box. Can anyone help me, thanks a lot! Blow is my part code: print("start to login") chrome.get('https://online.adp.com/signin/v1/?APPID=WFNPortal&productId=...
Can't find ADP login page password box by webdriver
I want to download report from ADP platform through webdriver, but I can't locate the login page password box. Can anyone help me, thanks a lot! Blow is my part code: print("start to login") chrome.get('https://online.adp.com/signin/v1/?APPID=WFNPortal&productId=80e309c3-7085-bae1-e053-3505430b5495&returnURL=https://wo...
[ "The selector seems ok. I think the problem is in the application. When running the test the application shows an error when next button is clicked.\n(By.ID, \"login-form_password\")\n\nYou can try with this as well:\nWebDriverWait(driver, 10).until(\n EC.presence_of_element_located((By.ID, \"login-form_pass...
[ 0 ]
[]
[]
[ "adp", "python", "selenium", "webdriver" ]
stackoverflow_0074597372_adp_python_selenium_webdriver.txt
Q: How to join lists inside two or more different lists in arranged order? I have three lists as follows. A = [1, 2, 3]; B = [[3, 4, 5], [4, 5, 6], [4, 5, 7], [7, 4, 3]]; C = [[2, 3, 1], [2, 3, 3], [2, 4, 5], [4, 5, 6], [7, 3, 1]] I want to create another list containing all the above inner lists starting from A to C...
How to join lists inside two or more different lists in arranged order?
I have three lists as follows. A = [1, 2, 3]; B = [[3, 4, 5], [4, 5, 6], [4, 5, 7], [7, 4, 3]]; C = [[2, 3, 1], [2, 3, 3], [2, 4, 5], [4, 5, 6], [7, 3, 1]] I want to create another list containing all the above inner lists starting from A to C. Desired = [elements of A, elements of B, elements of C] just like this. Des...
[ "The method I use below is to see if the inner_list contents are infact a list of themselves.\n\nIf they are, then append the inner list.\nIf they are not, then append the outer_list.\n\nA = [1, 2, 3]; \nB = [[3, 4, 5], [4, 5, 6], [4, 5, 7], [7, 4, 3]]; \nC = [[2, 3, 1], [2, 3, 3], [2, 4, 5], [4, 5, 6], [7, 3, 1]]\...
[ 2, 2, 1 ]
[]
[]
[ "arrays", "list", "python" ]
stackoverflow_0074580747_arrays_list_python.txt
Q: Why PyTorch BatchNorm1D gives "batch_norm" not implemented for 'Long'" error while normalizing Integer type tensor? I am trying to learn some functions in Pytorch framework and was stuck due to below error while normalizing a simple integer tensor. Could someone please help me with this. Here is the sample code to...
Why PyTorch BatchNorm1D gives "batch_norm" not implemented for 'Long'" error while normalizing Integer type tensor?
I am trying to learn some functions in Pytorch framework and was stuck due to below error while normalizing a simple integer tensor. Could someone please help me with this. Here is the sample code to reproduce the error - import torch import torch.nn as nn #Integer type tensor test_int_input = torch.randint(size = [3,...
[ "Your input tensor should be a floating point:\n>>> batchnorm1D(test_int_input.float())\ntensor([[-5.9605e-08, -1.3887e+00, -9.8058e-01, 2.6726e-01, 1.4142e+00],\n [-1.2247e+00, 4.6291e-01, 1.3728e+00, -1.3363e+00, -7.0711e-01],\n [ 1.2247e+00, 9.2582e-01, -3.9223e-01, 1.0690e+00, -7.0711e-01]],...
[ 1 ]
[]
[]
[ "deep_learning", "machine_learning", "normalization", "python", "pytorch" ]
stackoverflow_0074598178_deep_learning_machine_learning_normalization_python_pytorch.txt
Q: Custom huggingface Tokenizer with custom model I am working on molecule data with representation called SMILES. an example molecule string looks like Cc1ccccc1N1C(=O)NC(=O)C(=Cc2cc(Br)c(N3CCOCC3)o2)C1=O. Now, I want a custom Tokenizer which can be used with Huggingface transformer APIs. I also donot want to use th...
Custom huggingface Tokenizer with custom model
I am working on molecule data with representation called SMILES. an example molecule string looks like Cc1ccccc1N1C(=O)NC(=O)C(=Cc2cc(Br)c(N3CCOCC3)o2)C1=O. Now, I want a custom Tokenizer which can be used with Huggingface transformer APIs. I also donot want to use the existing tokenizer models like BPE etc. I want the...
[ "This code snippet provides a tokenizer that can be used with Hugging Face transformers. It uses a simple Word Level (= mapping) \"algorithm\".\nfrom tokenizers import Regex, Tokenizer\nfrom tokenizers.models import WordLevel\nfrom tokenizers.pre_tokenizers import Split\nfrom tokenizers.processors import TemplatePr...
[ 1 ]
[]
[]
[ "huggingface_tokenizers", "huggingface_transformers", "nlp", "python" ]
stackoverflow_0067513831_huggingface_tokenizers_huggingface_transformers_nlp_python.txt
Q: If/Else or One Line Say I've got a class who has a property called MyClass.name. I'm looping through some data where I want to arrange names to either be MyClass.name or other. I've got a method: def return_name(self, the_name): if the_name == self.name: return the_name else: return 'other'...
If/Else or One Line
Say I've got a class who has a property called MyClass.name. I'm looping through some data where I want to arrange names to either be MyClass.name or other. I've got a method: def return_name(self, the_name): if the_name == self.name: return the_name else: return 'other' Would it make sense to ...
[ "The first one is better due to readability. As you mansion performance is not an issue. You could test it with a timer.\nThe branchless argument is decent, however '*' is often a slow operation.\nPython also allows you to use the if else in a single line.\ndef return_name(self, the_name):\n return the_name if s...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074598418_python.txt
Q: Merge PDF files Is it possible, using Python, to merge separate PDF files? Assuming so, I need to extend this a little further. I am hoping to loop through folders in a directory and repeat this procedure. And I may be pushing my luck, but is it possible to exclude a page that is contained in each of the PDFs (my...
Merge PDF files
Is it possible, using Python, to merge separate PDF files? Assuming so, I need to extend this a little further. I am hoping to loop through folders in a directory and repeat this procedure. And I may be pushing my luck, but is it possible to exclude a page that is contained in each of the PDFs (my report generation al...
[ "You can use PyPdf2s PdfMerger class.\nFile Concatenation\nYou can simply concatenate files by using the append method.\nfrom PyPDF2 import PdfMerger\n\npdfs = ['file1.pdf', 'file2.pdf', 'file3.pdf', 'file4.pdf']\n\nmerger = PdfMerger()\n\nfor pdf in pdfs:\n merger.append(pdf)\n\nmerger.write(\"result.pdf\")\nme...
[ 414, 153, 37, 15, 9, 3, 3, 3, 2, 1, 1, 1, 0, 0 ]
[ "def pdf_merger(path):\n\"\"\"Merge the pdfs into one pdf\"\"\"\nimport logging\nlogging.basicConfig(filename = 'output.log', level = logging.DEBUG, format = '%(asctime)s %(levelname)s %(message)s' )\n\ntry:\n import glob, os\n import PyPDF2\n \n os.chdir(path)\n \n pdfs = []\n \n for file i...
[ -1 ]
[ "file_io", "pdf", "pypdf", "pypdf2", "python" ]
stackoverflow_0003444645_file_io_pdf_pypdf_pypdf2_python.txt
Q: extract number of ranking position in pandas dataframe I have a pandas dataframe with a column named ranking_pos. All the rows of this column look like this: #123 of 12,216. The output I need is only the number of the ranking, so for this example: 123 (as an integer). How do I extract the number after the # and ge...
extract number of ranking position in pandas dataframe
I have a pandas dataframe with a column named ranking_pos. All the rows of this column look like this: #123 of 12,216. The output I need is only the number of the ranking, so for this example: 123 (as an integer). How do I extract the number after the # and get rid of the of 12,216? Currently the type of the column is ...
[ "You can use .str.extract:\ndf['ranking_pos'].str.extract(r'#(\\d+)').astype(int)\n\nor you can use .str.split():\ndf['ranking_pos'].str.split(' of ').str[0].str.replace('#', '').astype(int)\n\n", "df.loc[:,\"ranking_pos\"] =df.loc[:,\"ranking_pos\"].str.replace(\"#\",\"\").astype(int)\n\n" ]
[ 1, 0 ]
[]
[]
[ "dataframe", "integer", "pandas", "python", "type_conversion" ]
stackoverflow_0074598438_dataframe_integer_pandas_python_type_conversion.txt
Q: How to check whether the Html value is 1 in Django? home.html {% if stud.scrapper_status == 1 %} <td>{{stud.scrapper_status}} --> Started</td> {% else %} <td>{{stud.scrapper_status}} --> Completed</td> {% endif %} Output Image If my value is 1 I should get started but...
How to check whether the Html value is 1 in Django?
home.html {% if stud.scrapper_status == 1 %} <td>{{stud.scrapper_status}} --> Started</td> {% else %} <td>{{stud.scrapper_status}} --> Completed</td> {% endif %} Output Image If my value is 1 I should get started but for all the value its getting Completed, How to check th...
[ "It should be \"1\" not 1 so:\nhome.html\n\n {% if stud.scrapper_status == \"1\" %}\n <td>{{stud.scrapper_status}} --> Started</td>\n {% else %}\n <td>{{stud.scrapper_status}} --> Completed</td>\n {% endif %}\n\n" ]
[ 3 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0074598520_django_django_templates_python.txt
Q: Trying to wrap the header of data frame /excel but gives me error Final_Inv = Inv_report2[["Product ID","Product","Net Activations","Books(at warehouse)","Books(Received by Retailer)","In Transit","Activated","Lost/Stolen (After Activation)","Lost/Stolen(Before Activation)","Total stock at Retailer","Activations(B...
Trying to wrap the header of data frame /excel but gives me error
Final_Inv = Inv_report2[["Product ID","Product","Net Activations","Books(at warehouse)","Books(Received by Retailer)","In Transit","Activated","Lost/Stolen (After Activation)","Lost/Stolen(Before Activation)","Total stock at Retailer","Activations(Books)","Stock in Network(Weeks)","Sell Through(%)","Stock at warehouse(...
[ "Because format is a built-in function.\nCan you try this:\ncell_format = workbook.add_format()\ncell_format.set_text_wrap()\n\nFull code:\nFinal_Inv = Inv_report2[[\"Product ID\",\"Product\",\"Net Activations\",\"Books(at warehouse)\",\"Books(Received by Retailer)\",\"In Transit\",\"Activated\",\"Lost/Stolen (Afte...
[ 0 ]
[]
[]
[ "dataframe", "excel", "python", "word_wrap" ]
stackoverflow_0074596233_dataframe_excel_python_word_wrap.txt
Q: Pandas: faster string operations in dataframes I am working on a python script that read data from a database and save this data into a .csv file. In order to save it correctly I need to escape different characters such as \r\n or \n. Here is how I am currently doing it: Firstly, I use the read_sql pandas function...
Pandas: faster string operations in dataframes
I am working on a python script that read data from a database and save this data into a .csv file. In order to save it correctly I need to escape different characters such as \r\n or \n. Here is how I am currently doing it: Firstly, I use the read_sql pandas function in order to read the data from the database. import...
[ "It should be faster to use applymap if really you have mixed types:\ndf = df.applymap(lambda x: repr(x) if isinstance(x, str) else x)\n\nHowever, if you can identify string columns, then you can slice them, (maybe in combination with re.escape?).:\nimport re\nstr_cols = ['col1', 'col2']\ndf[str_cols] = df[str_cols...
[ 3 ]
[]
[]
[ "csv", "pandas", "performance", "python" ]
stackoverflow_0074598581_csv_pandas_performance_python.txt
Q: Unable to import module 'app': No module named '_tkinter'", "errorType": "Runtime.ImportModuleError" I am trying to create a docker container to deploy on AWS lambda but I continuously keep getting the error: "Unable to import module 'app': No module named '_tkinter'", "errorType": "Runtime.ImportModuleError", "st...
Unable to import module 'app': No module named '_tkinter'", "errorType": "Runtime.ImportModuleError"
I am trying to create a docker container to deploy on AWS lambda but I continuously keep getting the error: "Unable to import module 'app': No module named '_tkinter'", "errorType": "Runtime.ImportModuleError", "stackTrace": []} The docker file I have created is as below: FROM public.ecr.aws/lambda/python:3.8 RUN yum ...
[ "Commented out the below code to resolve the issue:\nfrom turtle import back\n\n" ]
[ 0 ]
[]
[]
[ "aws_lambda", "docker", "python", "pytorch", "tkinter" ]
stackoverflow_0074473315_aws_lambda_docker_python_pytorch_tkinter.txt
Q: Python | Create combination of dictionary based on conditions I'm trying to create combination of dictionary based on some condition below is the main dictionary: payload = { "type": ["sedan","suv"], "name": ["car1","car2"], "color": ["black","white","green"], "version": ["mid","top"], "model":...
Python | Create combination of dictionary based on conditions
I'm trying to create combination of dictionary based on some condition below is the main dictionary: payload = { "type": ["sedan","suv"], "name": ["car1","car2"], "color": ["black","white","green"], "version": ["mid","top"], "model": ["2","5","13"], } below are the conditions: color = { "car1":...
[ "You can try to create a dataframe with the outputs and the filter it for each condition like below\nimport itertools\nimport pandas as pd\npayload = {\n \"type\": [\"sedan\",\"suv\"],\n \"name\": [\"car1\",\"car2\"],\n \"color\": [\"black\",\"white\",\"green\"],\n \"version\": [\"mid\",\"top\"],\n \...
[ 0 ]
[]
[]
[ "combinations", "dictionary", "python", "python_3.x" ]
stackoverflow_0074595956_combinations_dictionary_python_python_3.x.txt
Q: Getting a list of months between two dates I need to implement the code which will help me to get the list of months between two dates. I already have the code which will give the month delta , That is the number of months. Actually, I need the way to achieve getting the list of months between two dates. Here it i...
Getting a list of months between two dates
I need to implement the code which will help me to get the list of months between two dates. I already have the code which will give the month delta , That is the number of months. Actually, I need the way to achieve getting the list of months between two dates. Here it is code for getting month delta. import calendar ...
[ "try this\nimport datetime\nimport time\nfrom dateutil.rrule import rrule, MONTHLY\nmonths = [dt.strftime(\"%m\") for dt in rrule(MONTHLY, dtstart=date1, until=date2)]\nprint months\n\n", "You can use the datae_range function in pandas library. \nimport pandas as pd\n\nmonths = pd.date_range(data1, date2, freq=\"...
[ 13, 0 ]
[ "Change your print statement to:\nprint calendar.month_name[:monthdelta]\n", "Because I don't know your desired output I can't format mine, but this returns an integer of the total number of months between two dates.\ndef calculate_monthdelta(date1, date2):\n print abs(date1.year - date2.year) * 12 + abs(date1...
[ -1, -1 ]
[ "calendar", "datetime", "python" ]
stackoverflow_0037456421_calendar_datetime_python.txt
Q: CDK: How to get L2 construct instance from L1 (CFN)? In my CDK code there is a low-lavel ecs.CfnTaskDefinition task definition. my_task_definition = aws_cdk.ecs.CfnTaskDefinition( scope=self, id="my_task_definition", # rest of the parameters... ) I want to use this task definition to a create a Ecs se...
CDK: How to get L2 construct instance from L1 (CFN)?
In my CDK code there is a low-lavel ecs.CfnTaskDefinition task definition. my_task_definition = aws_cdk.ecs.CfnTaskDefinition( scope=self, id="my_task_definition", # rest of the parameters... ) I want to use this task definition to a create a Ecs service, like this. my_service = aws_cdk.ecs.Ec2Service( ...
[ "\nIs it possible to get aws_cdk.aws_ecs.TaskDefinition object from aws_cdk.aws_ecs.CfnTaskDefinition instance?\n\n❌ No. You cannot get a L2 Something construct from a L1 CfnSomething. You can get a L2 ISomething interface construct with from_task_definition_arn (see below). But the task_definition prop won't ac...
[ 2 ]
[]
[]
[ "amazon_ecs", "amazon_web_services", "aws_cdk", "aws_cdk_python", "python" ]
stackoverflow_0074592569_amazon_ecs_amazon_web_services_aws_cdk_aws_cdk_python_python.txt
Q: Python loop through rows and then calculate doesn't wok What I wanted to do, is to loop through each row. If the category is "HR contacts" and it's number is smaller than 500 then keep it. Otherwise only keep 500 as part of it. My code is: cntByUserNm['keep #'] = np.nan cntByUserNm['rest #'] = np.nan for index, ro...
Python loop through rows and then calculate doesn't wok
What I wanted to do, is to loop through each row. If the category is "HR contacts" and it's number is smaller than 500 then keep it. Otherwise only keep 500 as part of it. My code is: cntByUserNm['keep #'] = np.nan cntByUserNm['rest #'] = np.nan for index, row in cntByUserNm.iterrows(): print(row['Owner Name'], row...
[ "You are updating the copy of row of the dataframe, instead of the dataframe itself. Assuming that your row index is continuous (from 0 to len(dataframe)), you can use .loc to modify directly on the dataframe.\nfor index, row in cntByUserNm.iterrows():\n print(row['Owner Name'], row['source'])\n if row['sourc...
[ 2, 2, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074598297_pandas_python.txt
Q: How to assign value to variable in list [PYTHON] How can I do something like this on python : class Game: def __init__(self, size: int): self.settings = { 'timeout_turn' = 0 'timeout_match' = 0 'max_memory' = 0 'time_left' = 2147483647 '...
How to assign value to variable in list [PYTHON]
How can I do something like this on python : class Game: def __init__(self, size: int): self.settings = { 'timeout_turn' = 0 'timeout_match' = 0 'max_memory' = 0 'time_left' = 2147483647 'game_type' = 0 'rule' = 0 'eva...
[ "To make it work you need to replace the = by and : and add a , after every entry.\nclass Game:\n def __init__(self, size: int):\n self.settings = { \n 'timeout_turn': 0,\n 'timeout_match': 0,\n 'max_memory': 0,\n 'time_left': 2147483647,\n 'game_typ...
[ 3, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074598563_python.txt
Q: Can I use pymysql.connect() with "with" statement? The following is listed as example in pymysql: conn = pymysql.connect(...) with conn.cursor() as cursor: cursor.execute(...) ... conn.close() Can I use the following instead, or will this leave a lingering connection? (it executes successfully) import pym...
Can I use pymysql.connect() with "with" statement?
The following is listed as example in pymysql: conn = pymysql.connect(...) with conn.cursor() as cursor: cursor.execute(...) ... conn.close() Can I use the following instead, or will this leave a lingering connection? (it executes successfully) import pymysql with pymysql.connect(...) as cursor: cursor.exe...
[ "This does not look safe, if you look here, the __enter__ and __exit__ functions are what are called in a with clause. For the pymysql connection they look like this:\ndef __enter__(self):\n \"\"\"Context manager that returns a Cursor\"\"\"\n return self.cursor()\n\ndef __exit__(self, exc, value, traceback):\...
[ 18, 7, 1, 0 ]
[]
[]
[ "pymysql", "python", "with_statement" ]
stackoverflow_0031214658_pymysql_python_with_statement.txt
Q: Linkedin LogIn with Selenium I am creating a short program in Python - Selenium to login to my Linkedin Profile, it opens the new windows but I get an error on line 13 during the debug: Exception has occurred: AttributeError 'WebDriver' object has no attribute 'find_element_by_xpath' File "C:\Users\viale\Desktop...
Linkedin LogIn with Selenium
I am creating a short program in Python - Selenium to login to my Linkedin Profile, it opens the new windows but I get an error on line 13 during the debug: Exception has occurred: AttributeError 'WebDriver' object has no attribute 'find_element_by_xpath' File "C:\Users\viale\Desktop\Automation\linkedin_selenium_auto...
[ "You have to mention like this:\ndriver.find_element(By.XPATH,\"//input[@name='session_key']\")\n\n" ]
[ 0 ]
[]
[]
[ "authentication", "linkedin", "python", "selenium" ]
stackoverflow_0074598558_authentication_linkedin_python_selenium.txt
Q: What is the shortcut key to comment multiple lines using PyCharm IDE? In Corey Schafer's Programming Terms: Mutable vs Immutable, at 3:06, he selected multiple lines and commented them out in PyCharm all in one action. What is this action? Is it a built-in shortcut in PyCharm that I can use or configure myself? A...
What is the shortcut key to comment multiple lines using PyCharm IDE?
In Corey Schafer's Programming Terms: Mutable vs Immutable, at 3:06, he selected multiple lines and commented them out in PyCharm all in one action. What is this action? Is it a built-in shortcut in PyCharm that I can use or configure myself?
[ "This is a setting you can change and define in \"Settings\".\nThe default is with Ctrl+/ for Windows, or Cmd+/ for Mac.\n", "Is depends on you're text editor , but probably all text editor use (ctrl + /) just highlight all the code you need to comments and use the shortcut , to know what shortcut using in you're...
[ 40, 4, 1, 0 ]
[]
[]
[ "comments", "pycharm", "python" ]
stackoverflow_0053426322_comments_pycharm_python.txt
Q: Django formsubmission gives me a 405 error I am trying to display a form and and take the submission in post of my class-based view. I am not using Django's form as it breaks my design. Code for my form: <form action="." method="POST" > <input type='hidden' name='pf_id' value='{{pf.id}}' /> <input type='...
Django formsubmission gives me a 405 error
I am trying to display a form and and take the submission in post of my class-based view. I am not using Django's form as it breaks my design. Code for my form: <form action="." method="POST" > <input type='hidden' name='pf_id' value='{{pf.id}}' /> <input type='hidden' name='content_type' value='portfolio' />...
[ "I guess the problem is with your view. As you have inherited the FormMixin and DetailView neither does implement the POST method and hence django returns 405 error code. Try inheriting an updateview or createview to support post functionality.\n", "For those who don't want to use CreateView because they are not ...
[ 1, 0, 0 ]
[]
[]
[ "django", "forms", "python" ]
stackoverflow_0022477586_django_forms_python.txt
Q: Cygwin: (python) ERROR: Failed building wheel for cryptography I'm using cygwin to develop a django application. And I'm stuck at a package install call digikey-api. It requires a cryptography package to be installed and it fails with the following error messages: generating cffi module 'build/temp.cygwin-3.2.0-x8...
Cygwin: (python) ERROR: Failed building wheel for cryptography
I'm using cygwin to develop a django application. And I'm stuck at a package install call digikey-api. It requires a cryptography package to be installed and it fails with the following error messages: generating cffi module 'build/temp.cygwin-3.2.0-x86_64-3.8/_openssl.c' running build_rust =======================...
[ "The message is very clear\nerror: can't find Rust compiler\n\nAs Cygwin has NO rust compiler, you can not build it\nhttps://cygwin.com/packages/package_list.html\n", "FYI,\nThe current workaround is to force installation of cryptography at 3.2.1 and pyopenssl at 21.0.0.\n(or cryptography==3.3.2)\n" ]
[ 1, 0 ]
[]
[]
[ "cygwin", "pip", "python" ]
stackoverflow_0068438667_cygwin_pip_python.txt
Q: Can't install python packages on my ubuntu virtual machine This is the full script: (venv) ubuntu@ubuntu:~$ pip install wxPython Collecting wxPython Using cached wxPython-4.2.0.tar.gz (71.0 MB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not...
Can't install python packages on my ubuntu virtual machine
This is the full script: (venv) ubuntu@ubuntu:~$ pip install wxPython Collecting wxPython Using cached wxPython-4.2.0.tar.gz (71.0 MB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [12 lines of output] ...
[ "You need to use an older version of Python (I am guessing 3.9). The best option is probably to set it up in virtualenv like this:\nsudo apt update\nsudo apt install python3.9\nsudo apt-get install python3.9-dev python3.9-venv\npython3.9 -m venv myenv\nsource venv/bin/activate\npip install wxPython\n\n", "Try to ...
[ 0, 0 ]
[]
[]
[ "python", "ubuntu" ]
stackoverflow_0074598555_python_ubuntu.txt
Q: The Fastest way to convert bytes to int32_t list in Python I need to convert bytes data to signed int32_t format and put it in to a list. (It is about recieveing ADC data from external ADC converter via Ethernet). For me the fastest method so far: tempADC = np.ndarray(256,np.intc,rawADC).tolist() 256 - I will hav...
The Fastest way to convert bytes to int32_t list in Python
I need to convert bytes data to signed int32_t format and put it in to a list. (It is about recieveing ADC data from external ADC converter via Ethernet). For me the fastest method so far: tempADC = np.ndarray(256,np.intc,rawADC).tolist() 256 - I will have 256 int32_t values rawADC - are raw bytes: b'T\x08\x00\x00W\xf...
[ "I presume your input data from the ADC can be simulated with:\nimport numpy as np\ninput = np.arange(256,dtype=np.uint32).tobytes()\n\nSo, I would try this to unpack:\nimport struct\n%timeit struct.unpack('<256I',input)\n735 ns ± 1.57 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n\n" ]
[ 2 ]
[]
[]
[ "list", "numpy", "python" ]
stackoverflow_0074598518_list_numpy_python.txt
Q: Selecting dataframe columns with boolen, rest have to be false I try to filter a dataframe with a specific condition, but don't now how to get safe that all other columns have to be false. A | B | C | D | E | F True True False False False False True False True False False True True True True False False False giv...
Selecting dataframe columns with boolen, rest have to be false
I try to filter a dataframe with a specific condition, but don't now how to get safe that all other columns have to be false. A | B | C | D | E | F True True False False False False True False True False False True True True True False False False given this df i want to select every row where A is tru and B or C is T...
[ "You can use another mask with columns.difference and any:\nm1 = df['A'] & (df['B'] | df['C'])\nm2 = ~df[df.columns.difference(['A', 'B', 'C'])].any(axis=1)\ndf.loc[m1 & m2]\n\nOutput:\n A B C D E F\n0 True True False False False False\n2 True True True False False False\n...
[ 1 ]
[]
[]
[ "boolean_logic", "dataframe", "lines_of_code", "pandas", "python" ]
stackoverflow_0074598811_boolean_logic_dataframe_lines_of_code_pandas_python.txt
Q: How to update values of python 2D array using loop and animate changing the colors I am looking for a way to update the values of the array numphy array created by creating an update function to update the values of the previous array and change the colors of the new values updated below is my code though it only ...
How to update values of python 2D array using loop and animate changing the colors
I am looking for a way to update the values of the array numphy array created by creating an update function to update the values of the previous array and change the colors of the new values updated below is my code though it only display the final frame. My Question is how do i display the entire process to show how ...
[ "Does it need to be a movie file format?\nYou can probably use the Plotly animation feature, where you create a new heatmap for each frame:\nhttps://plotly.com/python/animations/\nhttps://plotly.com/python/visualizing-mri-volume-slices/\nhttps://plotly.com/python/heatmaps/\nedit: someone did something similar alrea...
[ 0 ]
[]
[]
[ "2d", "animation", "arrays", "python" ]
stackoverflow_0074598238_2d_animation_arrays_python.txt
Q: Drop function removes more indices in pandas than it should I am trying to concatinate an older df(main_df) with a newer (ellicom_df) and then drop all the rows where i have the same manufacturer but a different date from the one making the update. However the code drops far too many lines than it should. In the e...
Drop function removes more indices in pandas than it should
I am trying to concatinate an older df(main_df) with a newer (ellicom_df) and then drop all the rows where i have the same manufacturer but a different date from the one making the update. However the code drops far too many lines than it should. In the example below old the main_df has 6269 lines the new (ellicom_df)...
[ "Why not simply filter this way:\nmain_df = main_df[(main_df['MANUFACTURER']!='ELLICOM') | (main_df['UPDATED']==date_)]\n\n" ]
[ 1 ]
[]
[]
[ "concatenation", "drop", "pandas", "python" ]
stackoverflow_0074598819_concatenation_drop_pandas_python.txt
Q: How to cache pip packages within Azure Pipelines Although this source provides a lot of information on caching within Azure pipelines, it is not clear how to cache Python pip packages for a Python project. How to proceed if one is willing to cache Pip packages on an Azure pipelines build? According to this, it may...
How to cache pip packages within Azure Pipelines
Although this source provides a lot of information on caching within Azure pipelines, it is not clear how to cache Python pip packages for a Python project. How to proceed if one is willing to cache Pip packages on an Azure pipelines build? According to this, it may be so that pip cache will be enabled by default in th...
[ "I used the pre-commit documentation as inspiration:\n\nhttps://pre-commit.com/#azure-pipelines-example\nhttps://github.com/asottile/azure-pipeline-templates/blob/master/job--pre-commit.yml\n\nand configured the following Python pipeline with Anaconda:\npool:\n vmImage: 'ubuntu-latest'\n\nvariables:\n CONDA_ENV: ...
[ 4, 3, 0 ]
[]
[]
[ "azure_pipelines", "caching", "pip", "python" ]
stackoverflow_0062420695_azure_pipelines_caching_pip_python.txt
Q: How to store the positions of an element in string in a dictionary (Python)? I want to get all the positions (indexes) of an element in a string and store them in a dictionary. This is what I've tried: string = "This is an example" test = {letter: pos for pos, letter in enumerate(string)} But this only giv...
How to store the positions of an element in string in a dictionary (Python)?
I want to get all the positions (indexes) of an element in a string and store them in a dictionary. This is what I've tried: string = "This is an example" test = {letter: pos for pos, letter in enumerate(string)} But this only gives the last position of the letter. I'd like all positions, desired output: test["...
[ "At the moment you are overwriting the dictionary values. For example,\n>>> my_dict = {}\n>>> my_dict['my_val'] = 1 # creating new value\n>>> my_dict\n{'my_val': 1}\n>>> my_dict['my_val'] = 2 # overwriting the value for `my_val`\n>>> my_dict\n{'my_val': 2}\n\nIf you want to keep all values for a key you can use a l...
[ 3, 1 ]
[]
[]
[ "dictionary", "python", "string" ]
stackoverflow_0074598636_dictionary_python_string.txt
Q: Python - Pandas - DROPNA(subset) deleting value for no apparent reasons? I'm cleaning some data and I've been struggling with one thing. I have a dataframe with 7740 rows and 68 columns. Most of the columns contains Nan values. What i'm interested in, is to remove NaN values when it is NaN in those two columns : [...
Python - Pandas - DROPNA(subset) deleting value for no apparent reasons?
I'm cleaning some data and I've been struggling with one thing. I have a dataframe with 7740 rows and 68 columns. Most of the columns contains Nan values. What i'm interested in, is to remove NaN values when it is NaN in those two columns : [SERIAL_ID],[NUMBER_ID] Example : SERIAL_ID NUMBER_ID 8RY68U4R NaN 87...
[ "I don't know why it only works for 3 columns and not for 68 originals.\nHowever, we can obtain desired output in other way.\nuse boolean indexing:\ndf[df[['SERIAL_ID', 'NUMBER_ID']].notnull().any(axis=1)]\n\n", "You can use boolean logic or simple do something like this for any given column:\nimport numpy as np\...
[ 1, 0 ]
[]
[]
[ "data_cleaning", "dataframe", "pandas", "python" ]
stackoverflow_0074596404_data_cleaning_dataframe_pandas_python.txt
Q: Recursively find and replace string in text files I want to recursively search through a directory with subdirectories of text files and replace every occurrence of {$replace} within the files with the contents of a multi line string. How can this be achieved with Python? So far all I have is the recursive code us...
Recursively find and replace string in text files
I want to recursively search through a directory with subdirectories of text files and replace every occurrence of {$replace} within the files with the contents of a multi line string. How can this be achieved with Python? So far all I have is the recursive code using os.walk to get a list of files that are required to...
[ "os.walk is great. However, it looks like you need to filer file types (which I would suggest if you are going to walk some directory). To do this, you should add import fnmatch.\nimport os, fnmatch\ndef findReplace(directory, find, replace, filePattern):\n for path, dirs, files in os.walk(os.path.abspath(direct...
[ 67, 35, 15, 7, 2, 0, 0, 0, 0 ]
[ "How about just using:\nclean = ''.join([e for e in text if e != 'string'])\n\n", "Multiple files string change\nimport glob\nfor allfiles in glob.glob('*.txt'):\nfor line in open(allfiles,'r'):\n change=line.replace(\"old_string\",\"new_string\")\n output=open(allfiles,'w')\n output.write(change) \n\...
[ -1, -4 ]
[ "python" ]
stackoverflow_0004205854_python.txt
Q: MongoDB extract specific value python I want to extract value of name : x = col.find({},{'_id': 0, 'country.name': 1}) for data in x: #if data == 'India': print(data['country']) This above code generate this output: {'name': 'India'} {'name': 'Colombia'} {'name': 'Iran (Islamic Republic of)'} {'name...
MongoDB extract specific value python
I want to extract value of name : x = col.find({},{'_id': 0, 'country.name': 1}) for data in x: #if data == 'India': print(data['country']) This above code generate this output: {'name': 'India'} {'name': 'Colombia'} {'name': 'Iran (Islamic Republic of)'} {'name': 'Germany'} Desire output: India Colombi...
[ "We need to create a list and append country name in that, and use join outside the for loop, It will print the expected output.\ncountries = []\nfor data in x:\n countries.append(data.get(\"country\", {}).get(\"name\"))\nprint(\"Output: \", \" \".join(countries))\n\n" ]
[ 1 ]
[]
[]
[ "bash", "mongodb", "python" ]
stackoverflow_0074598861_bash_mongodb_python.txt
Q: get value from tuple keys dictionary and sequential I have a dictionary d = {(1,100) : 0.5 , (1,150): 0.7 ,(1,190) : 0.8, (2,100) : 0.5 , (2,120): 0.7 ,(2,150) : 0.8, (3,100) : 0.5 , (3,110): 0.7 ,(4,100) : 0.5 , (4,150): 0.7 ,(4,190) : 0.8,(5,100) : 0.5 , (5,150): 0.7} list = [4,2,1,3,5] for (k1,k2),k3 in d.item...
get value from tuple keys dictionary and sequential
I have a dictionary d = {(1,100) : 0.5 , (1,150): 0.7 ,(1,190) : 0.8, (2,100) : 0.5 , (2,120): 0.7 ,(2,150) : 0.8, (3,100) : 0.5 , (3,110): 0.7 ,(4,100) : 0.5 , (4,150): 0.7 ,(4,190) : 0.8,(5,100) : 0.5 , (5,150): 0.7} list = [4,2,1,3,5] for (k1,k2),k3 in d.items(): for k1 in list : print(k1,k2 : ,k3) I want get ...
[ "You can use sorted() with the the values from the tuple as index in the list\nd = dict(sorted(d.items(), key=lambda x: lst.index(x[0][0])))\nprint(d)\n\nOutput\n{(4, 100): 0.5, (4, 150): 0.7, (4, 190): 0.8, (2, 100): 0.5, (2, 120): 0.7, (2, 150): 0.8, (1, 100): 0.5, (1, 150): 0.7, (1, 190): 0.8, (3, 100): 0.5, (3,...
[ 1, 0 ]
[]
[]
[ "dictionary", "python", "tuples" ]
stackoverflow_0074598712_dictionary_python_tuples.txt
Q: Can't display SVG pictures with IPython.HTML I Tried to plot out SVG images with IPython using this from from IPython.display import HTML, display if '.svg' in link: #img_data = bunch of tags display(HTML(img_data))) continue image = io.imread(link) ratio = image.shape[1]/image.shape[0] print(ratio...
Can't display SVG pictures with IPython.HTML
I Tried to plot out SVG images with IPython using this from from IPython.display import HTML, display if '.svg' in link: #img_data = bunch of tags display(HTML(img_data))) continue image = io.imread(link) ratio = image.shape[1]/image.shape[0] print(ratio) print(image.shape) resized = cv.cvtColo...
[ "You can display SVG images in IPython with:\nfrom from IPython import display\nsvg = '<svg ...' # Replace with your SVG content.\ndisplay.SVG(svg)\n\n" ]
[ 1 ]
[]
[]
[ "html", "python", "svg" ]
stackoverflow_0071004245_html_python_svg.txt
Q: May I ask there are any algorithms(in python) could filter "deep valley" data points on a sloping straight line? I have a group of datasets, each of them containing 251 points, which will be fitted as a sloping straight line. However there are around 30 outliers forming a lot "deep valleys" as shown below in every...
May I ask there are any algorithms(in python) could filter "deep valley" data points on a sloping straight line?
I have a group of datasets, each of them containing 251 points, which will be fitted as a sloping straight line. However there are around 30 outliers forming a lot "deep valleys" as shown below in every dataset.enter image description here My task is to remove these deep valleys for future data processing and my initia...
[ "What an outlier is can be very dependent on the dataset. Here is a similar question that was answered that might help: Is there a numpy builtin to reject outliers from a list\nIn your case it comes done to keeping track of a running average, and checking if values are further out then you would prefer.\nLast but n...
[ 0 ]
[]
[]
[ "curve_fitting", "data_fitting", "filter", "outliers", "python" ]
stackoverflow_0074598916_curve_fitting_data_fitting_filter_outliers_python.txt
Q: Access Tools from .venv What is the best way to access python tools from within a script? For my example I want to use msgfmt.py and pygettext from the Tools/i18n package(?). On a Linux system probably no issue, since they are already on the PATH, but under Windows I have to call them with python as interpreter, s...
Access Tools from .venv
What is the best way to access python tools from within a script? For my example I want to use msgfmt.py and pygettext from the Tools/i18n package(?). On a Linux system probably no issue, since they are already on the PATH, but under Windows I have to call them with python as interpreter, so setting the directory on th...
[ "Researching a bit further into the topic, I got really mind gobbled:\nMaybe I am doing this totally wrong under windows, but my line ratio (linux/windows) to call a python tool from inside a venv: 1/34. I did not fully tested the final call under linux yet, but this ratio is only for getting the subprocess command...
[ 0 ]
[]
[]
[ "gettext", "python" ]
stackoverflow_0074572814_gettext_python.txt
Q: Detect Changes In Two Or More CSVs Using Pandas I am trying to use Pandas to detect changes across two CSVs. I would like it ideally to highlight which UIDs have been changed. I've attached an example of the ideal output here. CSV 1 (imported as DataFrame): | UID | Email | | -------- | ------------...
Detect Changes In Two Or More CSVs Using Pandas
I am trying to use Pandas to detect changes across two CSVs. I would like it ideally to highlight which UIDs have been changed. I've attached an example of the ideal output here. CSV 1 (imported as DataFrame): | UID | Email | | -------- | --------------- | | U01 | u01@email.com | | U02 | u02...
[ "The strategy here is to merge the two dataframes on UID, then compare the email columns, and finally see if the new UIDs are in the UID list.\ndf_compare = pd.merge(left=df, right=df_new, how='outer', on='UID')\n\ndf_compare['Change Status'] = df_compare.apply(lambda x: 'No Change' if x.Email_x == x.Email_y else '...
[ 0 ]
[]
[]
[ "csv", "dataframe", "pandas", "python", "validation" ]
stackoverflow_0074595978_csv_dataframe_pandas_python_validation.txt
Q: Does anyone know how to break this loop in python if the correct password has been entered? I'm new to Python and programming in general so I decided to set myself a bit of a challenge to code a password storage system. It basically writes and reads from a text file with passwords stored inside it. At the end, the...
Does anyone know how to break this loop in python if the correct password has been entered?
I'm new to Python and programming in general so I decided to set myself a bit of a challenge to code a password storage system. It basically writes and reads from a text file with passwords stored inside it. At the end, the user needs to put in the password that matches in the text file. All of it works but I can't see...
[ "while True: is creating an \"infinite\" loop, which you probably tried to break with the break statement, but it breaks an internal for loop only.\nI think a good solution is to put \"not found\" into the while condition, so it will run the input sequence only if found is False\nfound: bool = False\nwhile not foun...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074599082_python_python_3.x.txt
Q: How do i get my bars in my df.plot() to be one column and the rest of the columns to be on the x axis? i have this dataframe: Week Income Fuel ... Extras Total costs Remainder 18-18-218 2000.0 1200.0 ... 122.0 1842.0 158.0 12-12-2012 1750.0 100.0 ... 100.0 820.0 ...
How do i get my bars in my df.plot() to be one column and the rest of the columns to be on the x axis?
i have this dataframe: Week Income Fuel ... Extras Total costs Remainder 18-18-218 2000.0 1200.0 ... 122.0 1842.0 158.0 12-12-2012 1750.0 100.0 ... 100.0 820.0 930.0 nan 1786.0 289.0 ... 109.0 1060.0 726.0 What i have now is: chartdf = pd...
[ "you need to change your data so you set the Week as an index and drop it from the columns then you create the plot from the transpose of the data and it will give you your expected output:\nchartdf=chartdf.set_index('Week', drop=True)\n \nchartdf.T.plot.bar(rot=0)\n\nas an example of results:\n\...
[ 1 ]
[]
[]
[ "matplotlib", "pandas", "python" ]
stackoverflow_0074598829_matplotlib_pandas_python.txt
Q: Plugin or Settings for Python/Pycharms for Code Editor is there a plugin or way that if i press the run button pycharms starts to highlight the code that is currently running step by step so i can see what pycharms is doing I looked into the pycharms editor settings but didnt really find anything that would help m...
Plugin or Settings for Python/Pycharms for Code Editor
is there a plugin or way that if i press the run button pycharms starts to highlight the code that is currently running step by step so i can see what pycharms is doing I looked into the pycharms editor settings but didnt really find anything that would help me
[ "I think that what you are referring if the debugger tool running the script line by line or just putting breakpoints to check specific values. check this\n", "for me there is two possibility :\n-use thonny IDE (i dont like it but the debug mod is interresting for that)\n-use the tutor module (https://pythontutor...
[ 0, 0 ]
[]
[]
[ "pycharm", "python" ]
stackoverflow_0074599017_pycharm_python.txt
Q: How to normalize-scale data in attribute in range <-1;1> Hello i have used many options for normalize data in my dataframe attribute elnino_1["air_temp"] ,but it always shows me an error like "Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contai...
How to normalize-scale data in attribute in range <-1;1>
Hello i have used many options for normalize data in my dataframe attribute elnino_1["air_temp"] ,but it always shows me an error like "Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample." or "'int' object is not callable" . I try...
[ "As I do not have access to your dataset, here I'm using make_classification to generate some synthetic data. Please run through in a notebook to gain understanding. (Do note as well there may be slight differences as I'm using a numpy array as dataset, yours is a DataFrame.)\nimport pandas as pd\nimport numpy as n...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "scikit_learn", "sklearn_pandas" ]
stackoverflow_0074560125_dataframe_pandas_python_scikit_learn_sklearn_pandas.txt
Q: Python Solution for Project Euler Question 8 I am trying to solve the question about the largest product in a series from Project Euler website. https://projecteuler.net/problem=8 I basically, saved the 1000 digits as a text file converted it to string created an array called window that stores the values this ar...
Python Solution for Project Euler Question 8
I am trying to solve the question about the largest product in a series from Project Euler website. https://projecteuler.net/problem=8 I basically, saved the 1000 digits as a text file converted it to string created an array called window that stores the values this array goes through the 1000 digit array and stores t...
[ "You compute intWin and mult inside the b loop, giving you a mix of old window and new window, and as a result you get a product that's sometimes too high. Instead, you should only compute intWin and mult once you've populated the current window.\nBut really, your code is over-complicated, and doesn't need reduce o...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074598986_python_python_3.x.txt
Q: pandas.DataFrame.assign: how to refer to newly created columns? I'm trying to use pandas.DataFrame.assign in Pandas 1.5.2. Let's consider this code, for instance: df = pd.DataFrame({"col1":[1,2,3], "col2": [4,5,6]}) df.assign( test1="hello", test2=df.test1 + " world" ) I'm facing this error: AttributeErr...
pandas.DataFrame.assign: how to refer to newly created columns?
I'm trying to use pandas.DataFrame.assign in Pandas 1.5.2. Let's consider this code, for instance: df = pd.DataFrame({"col1":[1,2,3], "col2": [4,5,6]}) df.assign( test1="hello", test2=df.test1 + " world" ) I'm facing this error: AttributeError: 'DataFrame' object has no attribute 'test1' However, it's explic...
[ "You can pass a callable to assign. Here use a lambda to reference the DataFrame.\n\nParameters\n**kwargsdict of {str: callable or Series}\nThe column names are keywords. If the values are callable, they are computed on the DataFrame and\nassigned to the new columns. The callable must not change input\nDataFrame (t...
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0074599116_dataframe_pandas_python_python_3.x.txt
Q: How to return data type with input? I'm brand new to python and am using the "Job Ready for Python" as a first text and ran across this chapter 4 problem that I can't get my head around: Create a program that prompts the user to a number and then displays the type of number entered(e.g., complex, integer, or a flo...
How to return data type with input?
I'm brand new to python and am using the "Job Ready for Python" as a first text and ran across this chapter 4 problem that I can't get my head around: Create a program that prompts the user to a number and then displays the type of number entered(e.g., complex, integer, or a float). I'm having a hard time understanding...
[ "In Python, whenever you take input from user. It is always a string.\nage = input(\"Enter your age :\")\nprint(type(age))\n\nThis will print str.\nTo convert this, you can do this,\nage = int(input(\"Enter your age :\"))\nprint(type(age))\n\nThis will print int.\n", "This basic code seems to work for me; not sur...
[ 1, 0 ]
[]
[]
[ "floating_point", "input", "integer", "python" ]
stackoverflow_0074595996_floating_point_input_integer_python.txt
Q: Get Values from CSV to pass as Arguments in Array/List (Python) I would like to find values from one CSV in another and modify/remove the rows accordingly. Removing already works quite well, but I would like to automate this process as much as possible. So my question is how can I put all values from the serachfor...
Get Values from CSV to pass as Arguments in Array/List (Python)
I would like to find values from one CSV in another and modify/remove the rows accordingly. Removing already works quite well, but I would like to automate this process as much as possible. So my question is how can I put all values from the serachforthat.csv (column [0]) into a kind of array or list and use it to run ...
[ "import csv\n\nwith open('searchforthat.csv', 'r') as inp:\n args = [row[0] for row in csv.reader(inp)]\n\nwith open('all.csv', 'r') as inp, open('final.csv', 'w') as out:\n writer = csv.writer(out)\n for row in csv.reader(inp):\n if row[3] not in args:\n writer.writerow(row)\n\n", "You have to g...
[ 1, 0 ]
[]
[]
[ "arrays", "csv", "list", "python", "writer" ]
stackoverflow_0074599103_arrays_csv_list_python_writer.txt
Q: Pandas to_csv() checking for overwrite When I am analyzing data, I save my dataframes into a csv-file and use pd.to_csv() for that. However, the function (over)writes the new file, without checking whether there exists one with the same name. Is there a way to check whether the file already exists, and if so, ask ...
Pandas to_csv() checking for overwrite
When I am analyzing data, I save my dataframes into a csv-file and use pd.to_csv() for that. However, the function (over)writes the new file, without checking whether there exists one with the same name. Is there a way to check whether the file already exists, and if so, ask for a new filename? I know I can add the sys...
[ "Try the following:\nimport glob\nimport pandas as pd\n\n# Give the filename you wish to save the file to\nfilename = 'Your_filename.csv'\n\n# Use this function to search for any files which match your filename\nfiles_present = glob.glob(filename)\n\n\n# if no matching files, write to csv, if there are matching fil...
[ 13, 5, 0 ]
[ " # if you already has a file with the name \"out\"\n # nothing will happen as pass gets excuted\ntry:\n df.to_csv('out.csv')\nexcept:\n pass\n\n" ]
[ -1 ]
[ "export_to_csv", "file_management", "pandas", "python", "python_2.7" ]
stackoverflow_0040375366_export_to_csv_file_management_pandas_python_python_2.7.txt
Q: AUTH_USER_MODEL refers to model that has not been installed I am getting an error ImproperlyConfigured at /admin/ AUTH_USER_MODEL refers to model 'ledger.User' that has not been installed I am only getting it on my production server. Not when I run things via localhost. First it was only when I was making a certa...
AUTH_USER_MODEL refers to model that has not been installed
I am getting an error ImproperlyConfigured at /admin/ AUTH_USER_MODEL refers to model 'ledger.User' that has not been installed I am only getting it on my production server. Not when I run things via localhost. First it was only when I was making a certain request. Then I thought my database must be out of sync so I d...
[ "I had this problem and it was solved by properly understanding how the Django filed are structured.\nThe instructions in tutorials are often different and confusing.\nYou need to understand that when you install Django, there are two key steps:\n1: creating a project\n2: creating an app (application)\nLet's illust...
[ 8, 3, 3, 2, 2, 1, 0, 0, 0, 0, 0 ]
[ "I've had the same problem, but no answer here worked for me.\nMy issue was that my custom UserAdmin was in models.py but not in admin.py. Hope that helps!\nI found the solution here : Django LookupError: App 'accounts' doesn't have a 'User' model\nLink to the original answer: https://groups.google.com/g/django-use...
[ -1 ]
[ "django", "django_authentication", "django_settings", "python" ]
stackoverflow_0026914022_django_django_authentication_django_settings_python.txt
Q: how to use Wait in Print standment in for loop python without appending into LISTs? I am wondering if its possible to execute first print statement and then others. For example in below code. It can print the prod_val then c. code: l = [2,3,4] pro_val = 1 c = 0 for i in range(len(l)): pro_val = pro_val * l[c] ...
how to use Wait in Print standment in for loop python without appending into LISTs?
I am wondering if its possible to execute first print statement and then others. For example in below code. It can print the prod_val then c. code: l = [2,3,4] pro_val = 1 c = 0 for i in range(len(l)): pro_val = pro_val * l[c] c = c+1 print(pro_val) await #looking something here and it print c after ...
[ "You get your desired output, if you simply do two loops.\nl = [2, 3, 4]\npro_val = 1\n\nfor num in l:\n pro_val *= num\n print(pro_val)\n\nfor num in l:\n print(num)\n\nOutput:\n\n2\n6\n24\n2\n3\n4\n\nIf you want the second to print the indices shifted by one instead, you would do this instead:\n...\nfor ...
[ 1 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0074599097_for_loop_python.txt
Q: Import modules in package in ROS2 I have created a package for ROS2 and I have added a Python repository I downloaded. The problem I am having is that in the original repository the modules from the own repo were imported directly while in mine I have to import them adding the ROS2 package name before the module, ...
Import modules in package in ROS2
I have created a package for ROS2 and I have added a Python repository I downloaded. The problem I am having is that in the original repository the modules from the own repo were imported directly while in mine I have to import them adding the ROS2 package name before the module, even though I am importing a module fro...
[ "First, according to the Module Search Path docs, when you do import something, Python looks for that something in the following places:\n\nFrom the built-in modules\nsys.path, which is a list containing:\n\nThe directory of the input script\nPYTHONPATH, which is an environment variable containing a list of directo...
[ 9, 0 ]
[ "For CMAKE packages with cpp and python code you can add the following lines to your CMakeLists.txt.\nThis will copy your python_pkg folder into your install environment to \"lib/python{version}/site-packages\" which is per default included in your python path.\n# for python code\nfind_package(ament_cmake_python RE...
[ -1 ]
[ "import", "python", "python_3.x", "ros2" ]
stackoverflow_0057426715_import_python_python_3.x_ros2.txt
Q: StyleGAN image generation doesn't work, TensorFlow doesn't see GPU After reinstalling Ubuntu 18.04, I cannot generate images anymore using a StyleGAN agent. The error message I get is InvalidArgumentError: Cannot assign a device for operation Gs_1/_Run/Gs/latents_in: {{node Gs_1/_Run/Gs/latents_in}}was explicitly ...
StyleGAN image generation doesn't work, TensorFlow doesn't see GPU
After reinstalling Ubuntu 18.04, I cannot generate images anymore using a StyleGAN agent. The error message I get is InvalidArgumentError: Cannot assign a device for operation Gs_1/_Run/Gs/latents_in: {{node Gs_1/_Run/Gs/latents_in}}was explicitly assigned to /device:GPU:0 but available devices are [ /job:localhost/rep...
[ "Might be because TensorFlow is looking for GPU:0 to assign a device for operation when the name of your graphical unit is actually XLA_GPU:0.\nWhat you could try to do is using soft placement when opening your session, so that TensorFlow uses any existing GPU (or any other supported devices if unavailable) when ru...
[ 1, 0 ]
[]
[]
[ "gpu", "machine_learning", "python", "tensorflow" ]
stackoverflow_0059199502_gpu_machine_learning_python_tensorflow.txt
Q: Typechecking with conditional parameters I'm trying to use typing with a function that has conditional parameters, that works like this: from typing import Optional, Union class Foo: some_param_to_check: str = 'foo_name' one_param_exclusive_to_foo: int class Bar: some_param_to_check: str = 'bar_name'...
Typechecking with conditional parameters
I'm trying to use typing with a function that has conditional parameters, that works like this: from typing import Optional, Union class Foo: some_param_to_check: str = 'foo_name' one_param_exclusive_to_foo: int class Bar: some_param_to_check: str = 'bar_name' another_param_exclusive_to_bar: str d...
[ "I'm pretty sure this is just a mypy issue. Its type inference system is not clever enough to recognize that your if not foo and not bar block that raises an exception excludes the double None case later on (since it can't conclusively infer anything about either type in isolation). There doesn't seem to be a good ...
[ 3, 1, 1 ]
[]
[]
[ "mypy", "python", "python_typing", "type_hinting" ]
stackoverflow_0074596129_mypy_python_python_typing_type_hinting.txt
Q: write the python program for this? Write a Python program that takes the user's name as input and displays and welcomes them. Expected behaviour: Enter your name: Nimal Welcome Nimal The Python code for taking the input and displaying the output is already provided. answer for this code! A: name = input("Enter y...
write the python program for this?
Write a Python program that takes the user's name as input and displays and welcomes them. Expected behaviour: Enter your name: Nimal Welcome Nimal The Python code for taking the input and displaying the output is already provided. answer for this code!
[ "name = input(\"Enter your name: \")\nprint(\"Welcome\", name)\n\n" ]
[ -2 ]
[]
[]
[ "python" ]
stackoverflow_0074599303_python.txt
Q: i want to make a loop, for every x actions do y I want to make a loop, to run x times, and when it has run x times, then do y and start again to run x time like first time. This is what Itried, but run only 1 time (x), and then did (y) but I need to run 20 times (x) and only after 20 times do y and start again to ...
i want to make a loop, for every x actions do y
I want to make a loop, to run x times, and when it has run x times, then do y and start again to run x time like first time. This is what Itried, but run only 1 time (x), and then did (y) but I need to run 20 times (x) and only after 20 times do y and start again to do (x) for user in usernames: ...
[ "Try if this works:\ndef generator(usernames):\n for user in usernames:\n yield user\n\ndef my_func(usernames):\n generator_obj = generator(usernames)\n try:\n while True:\n for _ in range(20):\n user = next(generator_obj)\n # do something with user\n ...
[ 0 ]
[]
[]
[ "loops", "python", "python_3.x", "while_loop" ]
stackoverflow_0074598809_loops_python_python_3.x_while_loop.txt
Q: How to create reports with Python SDK Api I am trying to create reports with Python on dailymotion but I have error,According to my received error, renponse is empty. I don't get it. I guess, My user coudln't login to dailymotion. Please check error. {'data': {'askPartnerReportFile': None}, 'errors': [{'message':...
How to create reports with Python SDK Api
I am trying to create reports with Python on dailymotion but I have error,According to my received error, renponse is empty. I don't get it. I guess, My user coudln't login to dailymotion. Please check error. {'data': {'askPartnerReportFile': None}, 'errors': [{'message': 'Not authorized to access `askPartnerReportFil...
[ "This feature requires a specific API access, which is missing on your API Key, that's why you get the message Not authorized to access askPartnerReportFile field.\nAs it's a feature restricted to verified-partners, you should reach out to your content manager to ask him this kind of access, or you can try to conta...
[ 0 ]
[]
[]
[ "dailymotion_api", "python", "report" ]
stackoverflow_0074571992_dailymotion_api_python_report.txt
Q: How to set a style for a particular cell in a multiindex dataframe I'm iterating over a multi-index dataframe, and I trying to set the color for particular cells to the style in the two variables points_color and stat_color. How to apply the style to the cells? for metric, new_df in df3.groupby(level=0): idx =...
How to set a style for a particular cell in a multiindex dataframe
I'm iterating over a multi-index dataframe, and I trying to set the color for particular cells to the style in the two variables points_color and stat_color. How to apply the style to the cells? for metric, new_df in df3.groupby(level=0): idx = pd.IndexSlice row = new_df.loc[(metric),:] for geo in ['US', 'U...
[ "You can select geo columns by list, compare stat and difference and set values in slices:\ndef color(x):\n \n idx = pd.IndexSlice\n geo = ['US', 'UK']\n \n m1 = x.loc[:, idx[geo, :, 'stat']].isin(('below', 'above'))\n diff = x.loc[:, idx[geo, :, 'difference']]\n \n df1 = pd.DataFrame('', in...
[ 1 ]
[]
[]
[ "dataframe", "multi_index", "pandas", "python" ]
stackoverflow_0074599211_dataframe_multi_index_pandas_python.txt
Q: How to create this kind of crosstab by Python? The data looks like: bad score1 score2 1 80-90 70-80 0 90-100 80-90 1 70-80 90-100 1 70-80 70-80 0 70-80 70-80 1 80-90 70-80 The result should be like the total number of 'the bad flag is 1 when it is in the corresponding range of socre1 and scor...
How to create this kind of crosstab by Python?
The data looks like: bad score1 score2 1 80-90 70-80 0 90-100 80-90 1 70-80 90-100 1 70-80 70-80 0 70-80 70-80 1 80-90 70-80 The result should be like the total number of 'the bad flag is 1 when it is in the corresponding range of socre1 and score2'. For example: 70-80 80-90 90-100 (score2)...
[ "Use values andaggfunc, combined with fillna:\nout = (pd.crosstab(df.score1, df.score2, values=df['bad'], aggfunc='sum')\n .fillna(0, downcast='infer')\n)\n\nOutput:\nscore2 70-80 80-90 90-100\nscore1 \n70-80 1 0 1\n80-90 2 0 0\n90-100 0 0 ...
[ 0 ]
[]
[]
[ "numpy", "pandas", "python", "scikit_learn" ]
stackoverflow_0074599436_numpy_pandas_python_scikit_learn.txt
Q: Custom button in Django Admin page, that when clicked, will change the field of the model to True I have a sample model in my Django App: class CustomerInformation(models.Model): # CustomerInformation Schema name=models.CharField(max_length=200, verbose_name="Name",default="Default Name") login_url=mod...
Custom button in Django Admin page, that when clicked, will change the field of the model to True
I have a sample model in my Django App: class CustomerInformation(models.Model): # CustomerInformation Schema name=models.CharField(max_length=200, verbose_name="Name",default="Default Name") login_url=models.URLField(max_length=200, verbose_name="Login URL",default="") is_test=models.BooleanField(defau...
[ "in your process_action function do a setattr(self, 'is_test_result', True) then override get_form like so\ndef get_form(self, *arg, **kwargs):\n form = super().get_form(*arg, **kwargs)\n if arg[1] and hasattr(self, 'is_test_result'):\n if self.is_test_result is not None:\n arg[1].is_test = ...
[ 0 ]
[]
[]
[ "django", "django_admin", "django_admin_actions", "django_models", "python" ]
stackoverflow_0073040960_django_django_admin_django_admin_actions_django_models_python.txt
Q: How to use multiprocessing pool.map with multiple arguments In the Python multiprocessing library, is there a variant of pool.map which supports multiple arguments? import multiprocessing text = "test" def harvester(text, case): X = case[0] text + str(X) if __name__ == '__main__': pool = multiproces...
How to use multiprocessing pool.map with multiple arguments
In the Python multiprocessing library, is there a variant of pool.map which supports multiple arguments? import multiprocessing text = "test" def harvester(text, case): X = case[0] text + str(X) if __name__ == '__main__': pool = multiprocessing.Pool(processes=6) case = RAW_DATASET pool.map(harves...
[ "\nis there a variant of pool.map which support multiple arguments?\n\nPython 3.3 includes pool.starmap() method:\n#!/usr/bin/env python3\nfrom functools import partial\nfrom itertools import repeat\nfrom multiprocessing import Pool, freeze_support\n\ndef func(a, b):\n return a + b\n\ndef main():\n a_args = [...
[ 736, 492, 177, 116, 81, 31, 19, 10, 10, 10, 9, 9, 7, 5, 3, 3, 2, 2, 2, 2, 0, 0 ]
[ "For Python 2, you can use this trick\ndef fun(a, b):\n return a + b\n\npool = multiprocessing.Pool(processes=6)\nb = 233\npool.map(lambda x:fun(x, b), range(1000))\n\n" ]
[ -2 ]
[ "multiprocessing", "python", "python_multiprocessing" ]
stackoverflow_0005442910_multiprocessing_python_python_multiprocessing.txt
Q: Extracting data for a specific location from netCDF by python I am new to using Python and also new to NetCDF, so apologies if I'm unclear. I have an nc file that has several variables and I need to extract data from those nc files in a new order. My nc file has 8 variables (longitude, latitude, time, u10, v10, sw...
Extracting data for a specific location from netCDF by python
I am new to using Python and also new to NetCDF, so apologies if I'm unclear. I have an nc file that has several variables and I need to extract data from those nc files in a new order. My nc file has 8 variables (longitude, latitude, time, u10, v10, swh, mwd, mwp) and the logic I'm trying is "If I input longitude and ...
[ "2022 edit: this is now much easier with xarray, as shown in Adrian's answer: https://stackoverflow.com/a/74599597/3581217\n\nYou first need to know the order of the dimensions in the time/space varying variables like e.g. u10, which you can obtain with:\nu10 = jan.variables['u10']\nprint(u10.dimensions)\n\nNext it...
[ 8, 1 ]
[ "I used this on netCDF files that are generated with the WRF model.\nimport numpy as np\nfrom netCDF4 import Dataset # http://code.google.com/p/netcdf4-python/\nimport pandas as pd\nimport os\n\nos.chdir('.../netcdf') # Select your dir\nf = Dataset('wrfout_d01_2007-01-01_10_00_00', 'r') #Charge your file\n\nlatbou...
[ -1 ]
[ "netcdf", "netcdf4", "python" ]
stackoverflow_0045582344_netcdf_netcdf4_python.txt
Q: Emojis in Pycharm Windows 7 I am making a program in Python using Pycharm IDE and I need Emoji packages in it. I have seen some guys do it in Mac using Ctrl + Space, How I can do this in windows ? A: It's a new feature in Windows 10. You can access the emoji keyboard shortcut using the keys: "Windows key + ." o...
Emojis in Pycharm Windows 7
I am making a program in Python using Pycharm IDE and I need Emoji packages in it. I have seen some guys do it in Mac using Ctrl + Space, How I can do this in windows ?
[ "It's a new feature in Windows 10. You can access the emoji keyboard shortcut using the keys:\n\"Windows key + .\" or, \"Windows key + >\"\nThe \".\" is the period or, the full stop key, not the point or the decimal key.\n", "In windows 10 you can use windows key + .(dot) or windows key + ; \n", "Use either of ...
[ 10, 3, 3, 1, 0, 0, 0 ]
[ "It is include in Mac OS, I do not think you can do that in Windows.\n", "You can use the Windows + ; key combination to open that box, however the emojis won't appear as bright as they do in mac. \n" ]
[ -2, -3 ]
[ "pycharm", "python" ]
stackoverflow_0054909711_pycharm_python.txt