content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Pandas query not working in some versions I have the following code: import numpy as np import pandas as pd df = pd.DataFrame({ 'name':['john','david','anna'], 'country':['USA','UK',np.nan] }) df.query('country.isnull()') This runs for me in pandas, it doesn't run for some of my teammates (whose instal...
Pandas query not working in some versions
I have the following code: import numpy as np import pandas as pd df = pd.DataFrame({ 'name':['john','david','anna'], 'country':['USA','UK',np.nan] }) df.query('country.isnull()') This runs for me in pandas, it doesn't run for some of my teammates (whose installation process I don't control), but we have th...
[ "Apparently, the reason is having numexpr installed or not:\nhttps://github.com/pandas-dev/pandas/issues/34251#issuecomment-732769686\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074287316_pandas_python.txt
Q: Is there a way to simplify bloc of if statements? Is there a way to simplify this block of if statements? if ro<=1: F=1.23 elif 1<ro<=1.05: F=1.24 elif 1.05<ro<=1.1: F=1.25 elif 1.1<ro<=1.12: F=1.26 elif 1.12<ro<=1.16: F=1.27 elif 1.16<ro<=1.19: ...
Is there a way to simplify bloc of if statements?
Is there a way to simplify this block of if statements? if ro<=1: F=1.23 elif 1<ro<=1.05: F=1.24 elif 1.05<ro<=1.1: F=1.25 elif 1.1<ro<=1.12: F=1.26 elif 1.12<ro<=1.16: F=1.27 elif 1.16<ro<=1.19: F=1.28 elif 1.19<ro<=1.21: F=1.29 el...
[ "First, you don't need < operator since it is already filtered by elif(else).\nSo,\n if ro <= 1:\n F = 1.23\n elif ro <= 1.05:\n F = 1.24\n elif ro <= 1.1:\n F = 1.25\n elif ro <= 1.12:\n F = 1.26\n elif ro <= 1.16:\n F = 1.27\n elif ro <= 1.19:\n F = 1.28...
[ 2, 0 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0074287812_if_statement_python.txt
Q: Matplotlib labels: greek letter + italic + black font I am trying to add a greek letter that is in black font and italic font at the same time. In this case is just bold. I am not sure if its possible the combination of the three. import matplotlib.pyplot as plt plt.figure() plt.plot() plt.xlabel(r'$ \it{\bf{\mu_{...
Matplotlib labels: greek letter + italic + black font
I am trying to add a greek letter that is in black font and italic font at the same time. In this case is just bold. I am not sure if its possible the combination of the three. import matplotlib.pyplot as plt plt.figure() plt.plot() plt.xlabel(r'$ \it{\bf{\mu_{0}}}$ H (mT)',fontsize = 12, fontweight='bold') plt.show()...
[ "According to the Matplotlib Documentation may use a combination of \\mathbf for italic bold math font and a definition of the font directly.\nimport matplotlib.pyplot as plt\n\nplt.rcParams['mathtext.fontset'] = 'custom'\nplt.rcParams['mathtext.bf'] = 'cm:italic:bold'\n\nplt.xlabel(r'$\\mathbf{\\mu_{0}}$ H (mT)',...
[ 1 ]
[]
[]
[ "fonts", "matplotlib", "python", "visualization" ]
stackoverflow_0071319945_fonts_matplotlib_python_visualization.txt
Q: When I access the page, nothing appears I want to use the following code to filter the data in models.py in views.py and output the Today_list to today.html, but when I open this url, nothing is displayed. What is the problem? class Post(models.Model): created =models.DateTimeField(auto_now_add=True,editable=...
When I access the page, nothing appears
I want to use the following code to filter the data in models.py in views.py and output the Today_list to today.html, but when I open this url, nothing is displayed. What is the problem? class Post(models.Model): created =models.DateTimeField(auto_now_add=True,editable=False,blank=False,null=False) title =mode...
[ "use get_context_data to add Today_list to context\nref : https://docs.djangoproject.com/en/4.1/ref/class-based-views/generic-display/\ndef get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['Today_list'] = self.get_queryset()\n return context\n\nor you can simply us...
[ 0, 0 ]
[]
[]
[ "django", "django_views", "python", "python_3.x" ]
stackoverflow_0074284598_django_django_views_python_python_3.x.txt
Q: Activity log for specific azure resource I am trying to query the activity logs of a specific azure resource. However, I am not sure how to do it. I only found base code on the internet that can only filter up to resource group level. from azure.mgmt.monitor import MonitorManagementClient import datetime ...
Activity log for specific azure resource
I am trying to query the activity logs of a specific azure resource. However, I am not sure how to do it. I only found base code on the internet that can only filter up to resource group level. from azure.mgmt.monitor import MonitorManagementClient import datetime # Get a client for Monitor credentials...
[ "\nCode: BadRequest\nMessage: The filter property: resource_id is not supported.\n\nThe error shows that ResourceID is not supported in the $filter argument.\nThe $filter has restrictions refer MS-Doc for detailed information.\nThe $filter argument is very restricted and allows only the following patterns.\n\nList ...
[ 0 ]
[]
[]
[ "activitylog", "azure", "python" ]
stackoverflow_0073931011_activitylog_azure_python.txt
Q: Build a Hierarchy table (id to parent relation) in Python spark (PySpark). (Not using GraphFrame) My input table looks like below From this table, I have to take each base_id and find out the parent hierarchy. My output table should be like below Here, for each base_id, the parent (parent_1), grand parent (paren...
Build a Hierarchy table (id to parent relation) in Python spark (PySpark). (Not using GraphFrame)
My input table looks like below From this table, I have to take each base_id and find out the parent hierarchy. My output table should be like below Here, for each base_id, the parent (parent_1), grand parent (parent_2)...(parent_n) Has to be calculated. Note that different base_id can have different hierarchy depth ...
[ "I am no PySpark expert, so please feel free to criticize my\nsuggestion.\nThe join part should be fine, but not sure how the stacking step will perform with high number of ids.\n# Data from original post\ndf0 = base_df.alias(\"df0\")\n\n# Keep tracks of joins number\ni = 1\n# Performs join as many times as necessa...
[ 1, 0 ]
[]
[]
[ "apache_spark", "apache_spark_sql", "pyspark", "python" ]
stackoverflow_0074285095_apache_spark_apache_spark_sql_pyspark_python.txt
Q: Selenium file upload url "path is not absolute" I'm trying to upload a file to a facebook group with selenium chromedriver. driver.find_element_by_xpath("//input[@type='file']").send_keys("http://www.peta.org/wp-content/uploads/2013/10/goat_2D00_list_2D00_1.jpg") But It throws an Exception Like this: selenium.co...
Selenium file upload url "path is not absolute"
I'm trying to upload a file to a facebook group with selenium chromedriver. driver.find_element_by_xpath("//input[@type='file']").send_keys("http://www.peta.org/wp-content/uploads/2013/10/goat_2D00_list_2D00_1.jpg") But It throws an Exception Like this: selenium.common.exceptions.WebDriverException: Message: unknown ...
[ "Nope, this way you can only upload files from a local machine:\ndriver.find_element_by_xpath(\"//input[@type='file']\").send_keys(\"/Path/to/the/file\")\n\nDownload the image first, then upload. For instance:\nWith urllib \nimport os\nimport urllib\n\nbase_dir = \"/Path/to/dir/\"\npath_to_image = os.path.join(base...
[ 4, 0 ]
[ "Use the full path like \"C:\\\\Users\\\\Casper\\\\Desktop\\\\hello.jpg\" instead of \"hello.jpg\".\n" ]
[ -1 ]
[ "python", "selenium", "selenium_chromedriver", "webdriver" ]
stackoverflow_0031884652_python_selenium_selenium_chromedriver_webdriver.txt
Q: Python - constrain values within interquartile range I am able to get this to run piecemeal, but when I tried a for loop to run it across all the models I am getting an error. It looks like I am giving a list of 1 rather than the item. How do I get it to provide the item? Or is there a better way to do this? my_li...
Python - constrain values within interquartile range
I am able to get this to run piecemeal, but when I tried a for loop to run it across all the models I am getting an error. It looks like I am giving a list of 1 rather than the item. How do I get it to provide the item? Or is there a better way to do this? my_list = [LogisticRegression(max_iter=1000, random_state=1),Li...
[ "You are putting i in a list, so instead of passing [i] to the fit function just pass i:\nmy_list = [LogisticRegression(max_iter=1000, random_state=1),LinearDiscriminantAnalysis(), SVC(probability = True,random_state=1)]\n\nfor i in my_list:\n rfecv = RFECV(estimator=i,step=1)\n rfecv.fit(x,y)\n print(\" \...
[ 1 ]
[]
[]
[ "python", "rfe", "scikit_learn" ]
stackoverflow_0074288055_python_rfe_scikit_learn.txt
Q: Looping through a pandas dataframe - how to make code run faster? I have a dataframe, df, with 43244 rows, and a txt file, text with 1107957 lines. The purpose of the following code is to evaluate entries in df, and return a word_id value if they are present in the text. with open('text.txt') as f: text = f.re...
Looping through a pandas dataframe - how to make code run faster?
I have a dataframe, df, with 43244 rows, and a txt file, text with 1107957 lines. The purpose of the following code is to evaluate entries in df, and return a word_id value if they are present in the text. with open('text.txt') as f: text = f.readlines() for index, row in df.iterrows(): lemma_id = 0 for li...
[ "Have you tried using pandas.merge?\nYour for loop would be replaced by the following (assuming that text is a DataFrame)\nnew_df = pd.merge(df, text_df, left_on='WORD', right_on='Word')\nnew_df.dropna(subset=['ID'], inplace=True)\n\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074287221_pandas_python.txt
Q: how to pass parameter in a function which is a value of dictionary in python i have two dictionary dict1 = { "abc": sm.xyz.cdd(), "def": sm.acf.fdr(), "ghi": sm.rty.qsd(), } I need to create a function that takes 2 parameters 1st is the key of dict1 and 2nd parameter would be a string and i want the o...
how to pass parameter in a function which is a value of dictionary in python
i have two dictionary dict1 = { "abc": sm.xyz.cdd(), "def": sm.acf.fdr(), "ghi": sm.rty.qsd(), } I need to create a function that takes 2 parameters 1st is the key of dict1 and 2nd parameter would be a string and i want the output fun("abc", "log") # then this must be my output sm.xyz.cdd("log")
[ "As was mentioned in a comment, you can remove the parentheses when defining the dictionary to store the functions as a value associated with a key. Then you can write a simple function that accesses the function in the dictionary and returns the output with the given input:\n\ndef fun(dictKey, funInput):\n \n ...
[ 1, 0 ]
[]
[]
[ "dictionary", "python", "python_3.x" ]
stackoverflow_0074288023_dictionary_python_python_3.x.txt
Q: QCompleter only works every 2nd time in a QGraphicsView I have a QLineEdit with a QCompleter inside a QGraphicsScene. For some reason, the auto-completions repeatedly appear and disappear every time you press a button. Here are some screenshots: Code: from PySide6 import QtWidgets app = QtWidgets.QApplication([]...
QCompleter only works every 2nd time in a QGraphicsView
I have a QLineEdit with a QCompleter inside a QGraphicsScene. For some reason, the auto-completions repeatedly appear and disappear every time you press a button. Here are some screenshots: Code: from PySide6 import QtWidgets app = QtWidgets.QApplication([]) scene = QtWidgets.QGraphicsScene() view = QtWidgets.QGrap...
[ "Apparently the problem is that the dropdown list yoinks the keyboard focus from the QLineEdit, and then pressing another key closes the dropdown. As a workaround, we can intercept the keyPressEvent and move the keyboard focus back to the QLineEdit:\nclass LineEditProxy(QtWidgets.QGraphicsProxyWidget):\n \"\"\"\...
[ 0 ]
[]
[]
[ "pyside", "python", "qgraphicsview", "qt" ]
stackoverflow_0074287917_pyside_python_qgraphicsview_qt.txt
Q: How to write an image attribute file in django (The 'image' attribute has no file associated with it) I am building a django blog website and I am trying to upload an image on the website. I can access the photos on the admin page but whenever I try to access it on the page I get an enroll. The trace back says " T...
How to write an image attribute file in django (The 'image' attribute has no file associated with it)
I am building a django blog website and I am trying to upload an image on the website. I can access the photos on the admin page but whenever I try to access it on the page I get an enroll. The trace back says " The 'image' attribute has no file associated with it. This my code for the model class article(models.Model...
[ "check the image with if condition like this...\n<div class=\"media-body\">\n<div style=\"text-decoration:none; display: inline-block;\" class=\"article-metadata\">\n \n {% if user.profile.image.url %}\n <img class=\"rounded-circle article-img\" src=\"{{user.profile.image.url}}\">\n {% endif %}\n <a style=\"...
[ 0 ]
[]
[]
[ "django", "django_forms", "django_templates", "django_views", "python" ]
stackoverflow_0074287286_django_django_forms_django_templates_django_views_python.txt
Q: Found keys with the same values, combine them in tuple and return updated dictionary I'm trying to sort the following dictionary: test_dict = { 'a': [1,3,5], 'b': [9,3,4], 'c': [4,5,6], 'd': [1,3,6], 'e': [1,3,5], 'f': [1,3,5], 'g': [4,5,6], 'h': [6,5...
Found keys with the same values, combine them in tuple and return updated dictionary
I'm trying to sort the following dictionary: test_dict = { 'a': [1,3,5], 'b': [9,3,4], 'c': [4,5,6], 'd': [1,3,6], 'e': [1,3,5], 'f': [1,3,5], 'g': [4,5,6], 'h': [6,5,9] } I have to combine all keys with duplicated values in the tuple as the dicti...
[ "Try:\nout = {}\nfor k, v in test_dict.items():\n out.setdefault(tuple(v), []).append(k)\n\n\nout = {v[0] if len(v) == 1 else tuple(v): list(k) for k, v in out.items()}\nprint(out)\n\nPrints:\n{\n (\"a\", \"e\", \"f\"): [1, 3, 5],\n \"b\": [9, 3, 4],\n (\"c\", \"g\"): [4, 5, 6],\n \"d\": [1, 3, 6],\n...
[ 2 ]
[]
[]
[ "dictionary", "python", "sorting" ]
stackoverflow_0074288209_dictionary_python_sorting.txt
Q: Python: Depth First Search 'maximum recursion depth exceeded' I have a recursive depth first search algorithm which takes in a black/white mask image, e.g.: And outputs the x largest clusters of white pixels in that mask, e.g. (for x = 2): The function is below: def split_mask_into_x_biggest_clusters(input_mask,...
Python: Depth First Search 'maximum recursion depth exceeded'
I have a recursive depth first search algorithm which takes in a black/white mask image, e.g.: And outputs the x largest clusters of white pixels in that mask, e.g. (for x = 2): The function is below: def split_mask_into_x_biggest_clusters(input_mask, x): def generate_neighbours(point): neighbours = [ ...
[ "For big images you will always end up with this error.\nYou can either change you implementation to iterative DFS (which doesn't use recursion), or use BFS.\nUPD\nImplementation can be found here (for iterative DFS)\nBFS implementation\n" ]
[ 2 ]
[]
[]
[ "depth_first_search", "numpy", "python", "python_3.x", "recursion" ]
stackoverflow_0074288271_depth_first_search_numpy_python_python_3.x_recursion.txt
Q: Call "WindowSummarizer" (from sktime) recursively to the forecasting target Y in future periods I need help on how to use the WindowSummarizer function from the SKTIME library recursively in the future. Because in the training and test data it is easy to generate the variables of moving averages and moving standar...
Call "WindowSummarizer" (from sktime) recursively to the forecasting target Y in future periods
I need help on how to use the WindowSummarizer function from the SKTIME library recursively in the future. Because in the training and test data it is easy to generate the variables of moving averages and moving standard deviations. But for future predictions, the WindowSummarizer function has to work interactively, wi...
[ "The issue here is that you are using ForecastingPipeline instead of TransformedTargetForecaster. According to the documents...\"Pipeline for forecasting with exogenous data.ForecastingPipeline is only applying the given transformers to X. The forecaster can also be a TransformedTargetForecaster containing transfor...
[ 0 ]
[]
[]
[ "forecasting", "python", "scikit_learn", "sktime", "time_series" ]
stackoverflow_0073325333_forecasting_python_scikit_learn_sktime_time_series.txt
Q: Writing a bootloader in Python Is it possible to write the entirety of a bootloader for an embedded device in Python? ‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎ A: Unfortunately, this is, to my knowledge, not possible. python cannot be compiled to assembl...
Writing a bootloader in Python
Is it possible to write the entirety of a bootloader for an embedded device in Python? ‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎‏‏‎ ‎
[ "Unfortunately, this is, to my knowledge, not possible. python cannot be compiled to assembly or to machine code and as such cannot be used to control the system without an interpreter. This means that you cant use python to make the boot loader without having some sort of kernel and system to handle the interprete...
[ 1 ]
[]
[]
[ "bootloader", "operating_system", "python" ]
stackoverflow_0074269386_bootloader_operating_system_python.txt
Q: How to pass arguments to another .py I'm newbie with python programming and I'm facing an issue with Windows Memory, so I want to understand if the way I'm calling the other "subprogram" ic causing this problem. Basically I've done a main program from which I call the other .py (called second_py.py) like this: fro...
How to pass arguments to another .py
I'm newbie with python programming and I'm facing an issue with Windows Memory, so I want to understand if the way I'm calling the other "subprogram" ic causing this problem. Basically I've done a main program from which I call the other .py (called second_py.py) like this: from second_py import second_py variable_1, ...
[ "Here is a working example:\n\nsecond_py.py\n\ndef my_function(a,b,c):\n print (\"I am a function from 'second_py' file!\")\n return(a+b+c, a*b*c)\n\n\nfirst_py.py\n\nfrom second_py import my_function\n\n#Call the second_py function here\nv1,v2=my_function(3,5,4)\n\nprint(v1,v2)\n\nOutput:\n\n" ]
[ 1 ]
[]
[]
[ "function", "memory_leaks", "memory_management", "python", "subprocess" ]
stackoverflow_0074288075_function_memory_leaks_memory_management_python_subprocess.txt
Q: PyCharm stops at a breakpoint where it shouldn't I'm experiencing this behavior in PyCharm Build #PY-222.4345.23 on macOS Monterey 12.6.1, which happens in both python 3.10 and 3.11. def example(i): match i % 4: case 0: if i > 10: return 0 case 1: if i > ...
PyCharm stops at a breakpoint where it shouldn't
I'm experiencing this behavior in PyCharm Build #PY-222.4345.23 on macOS Monterey 12.6.1, which happens in both python 3.10 and 3.11. def example(i): match i % 4: case 0: if i > 10: return 0 case 1: if i > 10: return 1 case 2: ...
[ "IDE bug. I've filed a ticket in PyCharm's issue tracker - https://youtrack.jetbrains.com/issue/PY-57125/PyCharm-stops-on-non-hit-breakpoint-inside-pattern-matching-block\n" ]
[ 1 ]
[]
[]
[ "breakpoints", "debugging", "pycharm", "python" ]
stackoverflow_0074261550_breakpoints_debugging_pycharm_python.txt
Q: rounding up time to last 30 mins interval I have a dataframe with a column 'queue_ist_dt'. This column contains pandas._libs.tslibs.timestamps.Timestamp values. My requirement is : if time = 10:13:00 then round_off_time = 10:00:00 if time = 23:29:00 then round_off_time = 23:00:00 and so on. if time = 10:31:00 then...
rounding up time to last 30 mins interval
I have a dataframe with a column 'queue_ist_dt'. This column contains pandas._libs.tslibs.timestamps.Timestamp values. My requirement is : if time = 10:13:00 then round_off_time = 10:00:00 if time = 23:29:00 then round_off_time = 23:00:00 and so on. if time = 10:31:00 then round_off_time = 10:30:00 if time = 23:53:00 t...
[ "Use Series.dt.floor:\n#if necessary convert to datetimes\ndf['queue_ist_dt'] = pd.to_datetime(df['queue_ist_dt'].astype(str)) \n \ndf['queue_ist_dt1'] = df['queue_ist_dt'].dt.floor('30Min').dt.time\nprint (df)\n\n", "Logic is subtract 30 minute from timedelta\ncode is as below:\nfor r in range(df.shape[0]):\n...
[ 3, 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074288159_pandas_python.txt
Q: How to mock function for call multiple time I want to mock functions to using in unit test. for example: def b(): return False def a(): b1 = b() b2 = b() ..... I want to see at first b() calling see "False" and at the second b() calling see "True" or in other examples call "find_one" function twi...
How to mock function for call multiple time
I want to mock functions to using in unit test. for example: def b(): return False def a(): b1 = b() b2 = b() ..... I want to see at first b() calling see "False" and at the second b() calling see "True" or in other examples call "find_one" function twice def check_item(user_id:str,item_id): # at...
[ "For handel this problem I use \"patch\" function from \"unittest.mock\" package and use Mock.side_effect.\nwhen we use side_effect can define at first calling of some function return this mock data and at second function call return something else.\nfor see more about side_effect can see this url.\nfrom unittest....
[ 1 ]
[]
[]
[ "mocking", "python", "python_unittest" ]
stackoverflow_0074288223_mocking_python_python_unittest.txt
Q: TeamCity: Number of tests 0 is less then the provided threshold I have a TeamCity build configuration And one build step. Runner type -- Command Line Step name -- test Run -- Custom Script Script: conda create -n my_env python=3.8 pytest source activate my_env pytest my_file.py The script is working (I can see re...
TeamCity: Number of tests 0 is less then the provided threshold
I have a TeamCity build configuration And one build step. Runner type -- Command Line Step name -- test Run -- Custom Script Script: conda create -n my_env python=3.8 pytest source activate my_env pytest my_file.py The script is working (I can see results in log PASSED [100%]) But in the "Status" I see TeamCity: Numbe...
[ "Found solution\nI have to install special package teamcity-messages\nconda create -n my_env python=3.8 pytest teamcity-messages\n\n" ]
[ 1 ]
[]
[]
[ "pytest", "python", "teamcity" ]
stackoverflow_0074287234_pytest_python_teamcity.txt
Q: Replace ip partially with x in python I have several ip addresses like 162.1.10.15 160.15.20.222 145.155.222.1 I am trying to replace the ip's like below. 162.x.xx.xx 160.xx.xx.xxx 145.xxx.xxx.x How to achieve this in python. A: We can use re.sub with a callback function here: def repl(m): return m.group(1...
Replace ip partially with x in python
I have several ip addresses like 162.1.10.15 160.15.20.222 145.155.222.1 I am trying to replace the ip's like below. 162.x.xx.xx 160.xx.xx.xxx 145.xxx.xxx.x How to achieve this in python.
[ "We can use re.sub with a callback function here:\ndef repl(m):\n return m.group(1) + '.' + re.sub(r'.', 'x', m.group(2)) + '.' + re.sub(r'.', 'x', m.group(3)) + '.' + re.sub(r'.', 'x', m.group(4))\n\ninp = \"160.15.20.222\"\noutput = re.sub(r'\\b(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)\\b', repl, inp)\nprint(output) ...
[ 3, 3, 1, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074287047_python.txt
Q: Python Dataframe Extract Colum Data Based cell value From the dataframe, unique values are taken in "Region" and would like to extract the "Name" However, when one Name is in Region, it spells out the name (l-i-n-d-a instead of linda) import pandas as pd data = { 'Region': ['South','West', 'North','W...
Python Dataframe Extract Colum Data Based cell value
From the dataframe, unique values are taken in "Region" and would like to extract the "Name" However, when one Name is in Region, it spells out the name (l-i-n-d-a instead of linda) import pandas as pd data = { 'Region': ['South','West', 'North','West', 'North', 'South','West', 'North', 'East'], ...
[ "you can try this:\ndf = pd.DataFrame(data)\nlist_region = df['Region'].unique().tolist()\nfor region in list_region:\n list_person = df.set_index('Region').loc[region, 'Name']\n if type(list_person) == str:\n list_person = [list_person]\n for person in list_person:\n print(region + ' >> ' + p...
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074287606_dataframe_pandas_python.txt
Q: I want to use a decremental range function inside zip function I want to parse two decremental range to zip function for comparison This is my code: data=[('85','51','56','35','33','73','24','90','71','50'), ('47','58','13','65','59','16','89','73','85','56'), ('25','50','63','56','32','72','16','04','46','33'), (...
I want to use a decremental range function inside zip function
I want to parse two decremental range to zip function for comparison This is my code: data=[('85','51','56','35','33','73','24','90','71','50'), ('47','58','13','65','59','16','89','73','85','56'), ('25','50','63','56','32','72','16','04','46','33'), ('70','71','44','28','06','17','01','76','38','66'), ('21','86','16',...
[]
[]
[ "I guess you want this code\nfor i in [(m,n) for m, n in zip([k for k in range(len(data),0,-1)], [l for l in range(len(data),0,-2)])]:\n print(set(i))\n\n" ]
[ -1 ]
[ "python", "python_zip" ]
stackoverflow_0074287774_python_python_zip.txt
Q: UART communication Raspberry Pi Pico to Raspberry Pi I am trying to communicate with a raspberry pi pico with my raspberry pi 4 over uart. The below code does transmit data, but I am only receiving data from the print statement. import os import utime from machine import ADC temp_sensor = ADC(4) ...
UART communication Raspberry Pi Pico to Raspberry Pi
I am trying to communicate with a raspberry pi pico with my raspberry pi 4 over uart. The below code does transmit data, but I am only receiving data from the print statement. import os import utime from machine import ADC temp_sensor = ADC(4) # Default connection of temperature sensor def temperatu...
[ "\nextra new line: this problem is just because the print ends with new line you can change print(str(temp)) to print(str(temp), end=\"\") in raspberry pi pico code\n\nwith respect to your second problem I don't think that uart.write(str(temp))is doing something useful. print statement is the way to send data to ra...
[ 0 ]
[]
[]
[ "micropython", "python", "raspberry_pi", "raspberry_pi_pico" ]
stackoverflow_0069397785_micropython_python_raspberry_pi_raspberry_pi_pico.txt
Q: Show how much there is of a certain value in each column in pandas My pandas data frame contains several columns, some of them have missing values which show up as a ? sign. I want to run a for loop to print how much ? there is in each columns of the data. I'm doing something like this: colnames = ['col_1','col_2'...
Show how much there is of a certain value in each column in pandas
My pandas data frame contains several columns, some of them have missing values which show up as a ? sign. I want to run a for loop to print how much ? there is in each columns of the data. I'm doing something like this: colnames = ['col_1','col_2','col_3'] for i in colnames: print(f'In the {i} feature, the value ...
[ "For count values avoid value_counts, because failed selecting ? if value not exist in column. Simplier is compare values by ? and count Trues by sum:\nfor i in colnames:\n print(f'In the {i} feature, the value - ? - occurs {data[i].eq(\"?\").sum()} times')\n\n", "Considering that the dataframe is data, if OP ...
[ 2, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074288383_pandas_python.txt
Q: How to remove all first articles from a string? I have a list where i want to remove all first articles: ["the house", "the beautiful garten", "the beautiful garten of the house"] and i want the list to only contain: ["house", "beautiful garten", "beautiful garten of the house"] If the first word is an article, th...
How to remove all first articles from a string?
I have a list where i want to remove all first articles: ["the house", "the beautiful garten", "the beautiful garten of the house"] and i want the list to only contain: ["house", "beautiful garten", "beautiful garten of the house"] If the first word is an article, then remove. In case the articles appears in the senten...
[ "If you're working with python try\nnew_list = [s[4:] if s.startswith('the ') else s for s in old_list]\n\n", "Another option is using re (this example will also ignore whitespaces around the first the:\nimport re\n\nlst = [\"the house\", \"the beautiful garten\", \"the beautiful garten of the house\"]\n\npat = r...
[ 1, 1, 0 ]
[]
[]
[ "article", "list", "python" ]
stackoverflow_0074287240_article_list_python.txt
Q: Forward imputation in tensorflow As a minimal example, say I have a tensor of the form: [[ 1. 0. 3. ] [ 7. 5. 6. ] [ 0. 0. 0. ] [ 0. 11. 1. ] [ 0. 0. 0. ] [ 0. 0. 0. ] [13. 14. 16.5]] Is there a way (natively in tensorflow) to impute the fully zeroed rows such their values are assig...
Forward imputation in tensorflow
As a minimal example, say I have a tensor of the form: [[ 1. 0. 3. ] [ 7. 5. 6. ] [ 0. 0. 0. ] [ 0. 11. 1. ] [ 0. 0. 0. ] [ 0. 0. 0. ] [13. 14. 16.5]] Is there a way (natively in tensorflow) to impute the fully zeroed rows such their values are assigned to be equal to the last non-fully ...
[ "We can use tf.gather(a, indices) to get the above output.\nThe indices needs to be [0, 1, 1, 3, 3, 3, 6] which can be be obtained with the following code:\nmask = tf.cast(tf.cast(tf.reduce_sum(a, axis=1), dtype=tf.bool), tf.float32)\n#[1., 1., 0., 1., 0., 0., 1.] where non-zero sum\nmask_range = (mask*tf.range(a.s...
[ 2, 1 ]
[]
[]
[ "keras", "python", "tensorflow" ]
stackoverflow_0074286259_keras_python_tensorflow.txt
Q: Pattern matching of filename between underscores and compare included date string to current datetime Similarly to the Topic to Open only files containing dates of past seven days in filename I want to open only those files which follow a very rigid rule with respect to their naming and extract part of the filenam...
Pattern matching of filename between underscores and compare included date string to current datetime
Similarly to the Topic to Open only files containing dates of past seven days in filename I want to open only those files which follow a very rigid rule with respect to their naming and extract part of the filename to do a date comparison. My filename is build like this {Custom-prefix}_{SupplierName}_{8 digtit_date}.cs...
[ "You can use\npattern = re.compile(fr\"{prefix}_(\\w*)_(\\d{{4}})(\\d{{2}})(\\d{{2}})\\.csv\")\n\nNote the double escaped literal braces in the f-string literal.\nSee the Python demo:\nimport re\nfilename = \"Custom-prefix_Shop_no24_20221009.csv\"\nprefix = \"Custom-prefix\"\npattern = re.compile(fr\"{prefix}_(\\w*...
[ 1 ]
[]
[]
[ "date", "filenames", "python", "python_re", "regex" ]
stackoverflow_0074288308_date_filenames_python_python_re_regex.txt
Q: How to os.walk a mapped network drive I'm trying to use os.walk to check all cbz files inside a folder (and sub-folders). I've tested this on a folder on my C: drive and everything works fine. However, when running it on a mapped network drive (Q:), it ends immediately with no results. I've tried using r"Q:/Mult...
How to os.walk a mapped network drive
I'm trying to use os.walk to check all cbz files inside a folder (and sub-folders). I've tested this on a folder on my C: drive and everything works fine. However, when running it on a mapped network drive (Q:), it ends immediately with no results. I've tried using r"Q:/Multimedia/Comics" as well as Q:\\Multimedia\\C...
[ "I had the same problem and found no other solution than mount the drive and access it through the directory I mounted it to.\nHope it helps. Regards.\n" ]
[ 0 ]
[]
[]
[ "python", "python_2.7" ]
stackoverflow_0055604786_python_python_2.7.txt
Q: Is it possible to calculate real-time distance of an object in a image w/o reference objects? I have a picture of human eye taken roughly 10cm away using a mobile phone(no specifications regarding the camera). After some detection and contouring, I got 113px as the Euclidean distance between the center of the dete...
Is it possible to calculate real-time distance of an object in a image w/o reference objects?
I have a picture of human eye taken roughly 10cm away using a mobile phone(no specifications regarding the camera). After some detection and contouring, I got 113px as the Euclidean distance between the center of the detected iris and the outermost edge of iris on the taken image. Dimensions of the image: 483x578px. I ...
[ "After months I was able to come up with the result after ton of research and lots of trials and errors. This is not the most ideal answer but it gave me expected results with decent precision.\nSimply, In order to measure object size/distance from the image we need multiple parameters. In my case, I was trying to ...
[ 0 ]
[]
[]
[ "euclidean_distance", "geometry", "image_processing", "opencv", "python" ]
stackoverflow_0073247175_euclidean_distance_geometry_image_processing_opencv_python.txt
Q: Is there simple way to transfer string values from one colomn to numerical values in another colomn? I'm new to python and have task to solve. I got large a .csv file and I was wondering is there simple way to transfer string values from one column to numerical values in another colomn. For example, in one column ...
Is there simple way to transfer string values from one colomn to numerical values in another colomn?
I'm new to python and have task to solve. I got large a .csv file and I was wondering is there simple way to transfer string values from one column to numerical values in another colomn. For example, in one column I have a bunch of different factory names and in the new colum should be numerical value for every factory...
[ "you can use ngroup() . Basically, group by factories and give an id for every factory. Does this give the output you want?\ndf['NumValues']=df.groupby('Factories').ngroup() + 1\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074288412_pandas_python.txt
Q: python selenium how to handle webpage randomly generates popups I am learning how to scrap webpages and I got this issue with this website: https://www.centris.ca/en/properties~for-sale~brossard?view=Thumbnail During the script execution, it would randomly give me a popup to subscribe: https://imgur.com/a/tzCVvg4 ...
python selenium how to handle webpage randomly generates popups
I am learning how to scrap webpages and I got this issue with this website: https://www.centris.ca/en/properties~for-sale~brossard?view=Thumbnail During the script execution, it would randomly give me a popup to subscribe: https://imgur.com/a/tzCVvg4 I already got the code to handle it, but it pops up at completely ran...
[ "There are some ways to disable pop-ups in chrome but they are rarely work. You can search for disabling pop-ups with chrome options but i doubt anything will help.\nI can just suggest more elegant solution:\nscrap_pages(driver)\ndriver.find_element(By.CSS_SELECTOR,'li.next> a').click()\ntime.sleep(3)\ntry:\n dr...
[ 1 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074271205_python_selenium.txt
Q: TypeError: cannot subtract DatetimeArray from ndarray when using time stamp data I am trying to calculate the number of days between two columns where each column stored as a TimeStamp object and contain NaN values. When I try to make the calculation, I am receiving TypeError: cannot subtract DatetimeArray from nd...
TypeError: cannot subtract DatetimeArray from ndarray when using time stamp data
I am trying to calculate the number of days between two columns where each column stored as a TimeStamp object and contain NaN values. When I try to make the calculation, I am receiving TypeError: cannot subtract DatetimeArray from ndarray error. My question is that how I can achieve what I'd like when having NaN value...
[ "Convert the columns to the correct format: pd.to_datetime.\nUse 'Int64' instead of 'int64'.\nIn general, if you print out the type np.nan, then it will be a float. And if this type suits you, then put the float type.\nimport pandas as pd\nimport numpy as np\n\nd1 = {'col1': [pd.Timestamp(2017, 1, 1, 12)], 'col2' ...
[ 0 ]
[]
[]
[ "missing_data", "nan", "pandas", "python" ]
stackoverflow_0074281541_missing_data_nan_pandas_python.txt
Q: Python webscraping from NCBI For a project i will need a list of all the virusnames in the family of a certain virus. Now there are many viruses in the family so i wanted to build a script for it. I have no experiance with Beautifulsoup or any other webscraping techniques but i gave it a go. def souptime(): im...
Python webscraping from NCBI
For a project i will need a list of all the virusnames in the family of a certain virus. Now there are many viruses in the family so i wanted to build a script for it. I have no experiance with Beautifulsoup or any other webscraping techniques but i gave it a go. def souptime(): import requests from bs4 import ...
[ "Select more specific to get all the virus:\nsoup.select('a[title=\"species\"] + ul a')\n\nExample\nTo get your information structured.\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\n\nurl = \"https://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?name=Orthomyxoviridae\"\nresponse = request...
[ 0 ]
[]
[]
[ "ncbi", "python", "taxonomy", "web_scraping" ]
stackoverflow_0074288454_ncbi_python_taxonomy_web_scraping.txt
Q: Regex matching a line and some lines before if line starts with a specific char I am processing an electronic circuit netlist in python and I am attempting to match all of a certain type of cell. Cell instantiations in a spice file can span multiple lines by using "+". For example... (example 1): instance_name_her...
Regex matching a line and some lines before if line starts with a specific char
I am processing an electronic circuit netlist in python and I am attempting to match all of a certain type of cell. Cell instantiations in a spice file can span multiple lines by using "+". For example... (example 1): instance_name_here pin1 pin2 pin3 + pin4 pin5 my_cell_name_here is equivalent to (example 2): instanc...
[ "Here's my code, which produces the desired result as far as I can tell. It doesn't use regex though, so it might not be the answer you seek.\ntext = '''\ninstance_name_here pin1 pin2 pin3\n+ pin4 pin5 my_cell_name_here\ninstance_name_here pin11 pin12 pin13 pin14 pin15 my_cell_name_here\ninstance_name_here pin21\n+...
[ 0 ]
[]
[]
[ "python", "python_re" ]
stackoverflow_0074284469_python_python_re.txt
Q: How do I end my program using while in python with the ff code import sys finish = True lst = [] while finish: num = int(input('How many numbers will be in the list?: ')) for n in range(num): numbers = int(input('Please enter a number: ')) lst.append(numbers) print('The l...
How do I end my program using while in python with the ff code
import sys finish = True lst = [] while finish: num = int(input('How many numbers will be in the list?: ')) for n in range(num): numbers = int(input('Please enter a number: ')) lst.append(numbers) print('The largest number is: ', max(lst), '\n The smallest number is: ', min(ls...
[ "Just replace the \"q.lower\" with \"q.lower()\" since lower() is a built-in method\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074288207_python.txt
Q: sort list in alphabetical order (with numbers preceding lowercase letters preceding uppercase letters I want to order string list strating from l = ['AAAA.html', 'aaa.html', 'index.html', 'diem', '1zz.html'] I want to have this output ['1zz.html', 'aaa.html', 'diem', 'index.html', 'AAAA.html'] How to implement s...
sort list in alphabetical order (with numbers preceding lowercase letters preceding uppercase letters
I want to order string list strating from l = ['AAAA.html', 'aaa.html', 'index.html', 'diem', '1zz.html'] I want to have this output ['1zz.html', 'aaa.html', 'diem', 'index.html', 'AAAA.html'] How to implement soluzion in python?
[ "Usual sort in python is:\n\nnumber, uppercase, lowercase.\n\nYou want\n\nnumber, lowercase, uppercase\n\nYou just need to use, as sorting key, the case-swapped input value:\n>>> l = ['AAAA.html', 'aaa.html', 'index.html', 'diem', '1zz.html']\n>>> sorted(l, key=str.swapcase)\n['1zz.html', 'aaa.html', 'diem', 'index...
[ 2 ]
[]
[]
[ "compare", "list", "python", "reorderlist", "sorting" ]
stackoverflow_0074288503_compare_list_python_reorderlist_sorting.txt
Q: How to access the values of a pandas DataFrame with multiple headers by column name when iterating over its rows? With a basic DataFrame with one header, one can iterate over the rows and access the values by column names: import pandas as pd df = pd.DataFrame(columns=['header1_column1', 'header1_column2']) df['...
How to access the values of a pandas DataFrame with multiple headers by column name when iterating over its rows?
With a basic DataFrame with one header, one can iterate over the rows and access the values by column names: import pandas as pd df = pd.DataFrame(columns=['header1_column1', 'header1_column2']) df['header1_column1'] = range(2) df['header1_column2'] = range(2) print(df) header1_column1 header1_column2 0 ...
[ "I think you need select by tuple for MultiIndex columns:\nfor index, row in df.iterrows():\n print(row[('header1_column1','header2_column1')])\n0\n1\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074288609_dataframe_pandas_python.txt
Q: using pytest-variables in a test module to get public variables I created a json file with "create_url":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxurl" then create a python test file that contain the method that I use for test @pytest.mark.regression @pytest.mark.smoke def test_create_tenant(): accounts = ...
using pytest-variables in a test module to get public variables
I created a json file with "create_url":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxurl" then create a python test file that contain the method that I use for test @pytest.mark.regression @pytest.mark.smoke def test_create_tenant(): accounts = Accounts() accounts.create_tenant() then create a method in clas...
[ "thanks\nI solved it , and here is the solution\ndef test_create_tenant(variables):\naccounts = Accounts()\naccounts.create_tenant(variables['create_tenant'])\n" ]
[ 0 ]
[]
[]
[ "pytest", "python", "testing" ]
stackoverflow_0074288409_pytest_python_testing.txt
Q: System.DllNotFoundExecption Error - PythonNet C# and Python3.8 I am interested to call my existing python 3.8 modules from an developed WPF Application(Net Core3.1). I did the following: I installed pythonnet with: pip install pythonnet Set environment paths in C# (in VS2019) : string pyInstallDir = @"C:\Python3...
System.DllNotFoundExecption Error - PythonNet C# and Python3.8
I am interested to call my existing python 3.8 modules from an developed WPF Application(Net Core3.1). I did the following: I installed pythonnet with: pip install pythonnet Set environment paths in C# (in VS2019) : string pyInstallDir = @"C:\Python38"; Environment.SetEnvironmentVariable("PATH", pyInstallDir, Environ...
[ "If your Python modules are a dll file you can use AddDllDirectory\nAddDllDirectory adds a directory for your program to search dll files for. By default dlls are only searched in the System32 folder and working directory (the location of your executable)\n[DllImport(\"kernel32.dll\", CharSet = CharSet.Unicode, Set...
[ 0 ]
[]
[]
[ "c#", "python", "python.net" ]
stackoverflow_0074288570_c#_python_python.net.txt
Q: Python3 program to swap elements def swapPositions(list, pos1, pos2): list[pos1], list[pos2] = list[pos2], list[pos1] return list List = [23, 65, 19, 90] pos1, pos2 = 1, 3 print(swapPositions(List, pos1-1, pos2-1)) i dont understand why "pos2-1" is used here why did they use minus one why doesn't i...
Python3 program to swap elements
def swapPositions(list, pos1, pos2): list[pos1], list[pos2] = list[pos2], list[pos1] return list List = [23, 65, 19, 90] pos1, pos2 = 1, 3 print(swapPositions(List, pos1-1, pos2-1)) i dont understand why "pos2-1" is used here why did they use minus one why doesn't it work without minus one??
[ "The reason why it takes \"Pos2-1\" is, the list index starts with 0(zero)\nSo\nindex List\n0 23\n1 65\n2 19\n3 90\n\nSo if you don't give the \"-1\", then the function will take the index values of 1 and 3, which is 65 and 90.\nIf you find the explanation useful, accept it and vo...
[ -2 ]
[]
[]
[ "python", "swap" ]
stackoverflow_0074288680_python_swap.txt
Q: TypeError: hash must be unicode or bytes, not None I am working on Flask project works with mongoengine. Register code hashed to password with passlib.hash when user registered. When I try to read password in login authentication I've got this error. TypeError: hash must be unicode or bytes, not None Traceback: ...
TypeError: hash must be unicode or bytes, not None
I am working on Flask project works with mongoengine. Register code hashed to password with passlib.hash when user registered. When I try to read password in login authentication I've got this error. TypeError: hash must be unicode or bytes, not None Traceback: TypeError TypeError: hash must be unicode or bytes, not ...
[ "I guess the problem is here:\nuser = User.objects(email=form.email.data, password=str(passW)).first()\n\nIf your database can't find any match user, user will be none. So you'd better use if else to tell if the user exist first.\nEDIT\nFrom the doc in Passlib,\n>>> # import the hash algorithm\n>>> from passlib.ha...
[ 1, 0, 0 ]
[]
[]
[ "flask", "hash", "python", "typeerror", "unicode" ]
stackoverflow_0039316867_flask_hash_python_typeerror_unicode.txt
Q: Find a state (on/off) from comparing two dfs with consecutive periods I have two dataframes with events logged in a system, I have sorted them by the hour. I want to count consecutive hours in both df’s and then look at either the hours or the consecutive hours to decide ‘state’ on the system based on both datafra...
Find a state (on/off) from comparing two dfs with consecutive periods
I have two dataframes with events logged in a system, I have sorted them by the hour. I want to count consecutive hours in both df’s and then look at either the hours or the consecutive hours to decide ‘state’ on the system based on both dataframes. Like this: if an event is logged in dataframe 1, state = 0, the state ...
[ "# First add a column to each df with its identity and concat them together, sorted\ndf_A['frame']='df_A'\ndf_B['frame']='df_B'\ndf_C=pd.concat([df_A, df_B]).sort_values('col_0')\n# Now, if I understand the problem correctly df_B triggers on state and df_A triggers off\ndf_C.loc[df_C['frame']=='df_B', 'state']=1\nd...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074288419_pandas_python.txt
Q: Finding subgraphs K3_3 in a given undirected graph in Python I'm trying to solve the following problem - I have an undirected graph and trying to calculate the amount of subgraphs K3_3 (complete bipartite graph) that are inside of this graph. There are some checks that one can do with networkx library for example ...
Finding subgraphs K3_3 in a given undirected graph in Python
I'm trying to solve the following problem - I have an undirected graph and trying to calculate the amount of subgraphs K3_3 (complete bipartite graph) that are inside of this graph. There are some checks that one can do with networkx library for example - Graph.subgraph class, but I'm not sure how one can use it. Are t...
[ "The biggest issue is that you are computing the bipartite sets on the full graph each time, rather than using a subgraph induced using the nodes in i.\nHere is my implementation:\n#!/usr/bin/env python\n\"\"\"\nCompute the number of complete, bipartite subgraphs with (3, 3) nodes.\n\"\"\"\nimport networkx as nx\n\...
[ 1 ]
[]
[]
[ "graph_theory", "networkx", "python" ]
stackoverflow_0074249413_graph_theory_networkx_python.txt
Q: Failing to get websocket response in python I'm trying to create a really simple websocket server with native socket package (this is mostly for a microcontoller but that's not relevant). If I understand correctly, websocket is simply an extension of HTTP protocol with an upgrade request from client which then ser...
Failing to get websocket response in python
I'm trying to create a really simple websocket server with native socket package (this is mostly for a microcontoller but that's not relevant). If I understand correctly, websocket is simply an extension of HTTP protocol with an upgrade request from client which then server responds back with right headers including th...
[ "As I mentioned this in the comment section - there was a bug in my code. Mainly map(lambda x: x.strip().lower(), header) which was converting Sec-WebSocket-Key value to lowercase causing the key to be invalid. Here's the working code that actually responds with OK status now.\nimport socket\nfrom base64 import b64...
[ 0 ]
[]
[]
[ "python", "websocket" ]
stackoverflow_0074267045_python_websocket.txt
Q: Django Override the Default success_url in contrib.auth.views I made an app with app_name = 'accounts' in urls.py of the django and created signup/login pages there using the built-in signup function. Now I need to change all the class details of the success_url, for instance from: reverse_lazy('login') to: reve...
Django Override the Default success_url in contrib.auth.views
I made an app with app_name = 'accounts' in urls.py of the django and created signup/login pages there using the built-in signup function. Now I need to change all the class details of the success_url, for instance from: reverse_lazy('login') to: reverse_lazy('accounts:login') but overwriting the original urls.py...
[ "I think there is no other solution that override django.contrib.auth classes for make your custom urls if you are using the default.\nOverriding the default urls.py does not work because auth code use the original urls.\nWith package like django-allauth, you can make custom urls, but with Django-auth, it is not po...
[ 1, 0 ]
[]
[]
[ "django", "html", "overriding", "python", "url" ]
stackoverflow_0074287632_django_html_overriding_python_url.txt
Q: Target to the mean encoding based on groups I have a data set that has some categorical values, also it has an item_id and target: import pandas as pd data = [['Salt Lake City','a', 1, 120], ['Seattle','b', 2, 120], ['San Franscisco','a', 3, 140], ['Seattle','a', 3, 100], ['Seattle', 'a', 2, 70], ['Sa...
Target to the mean encoding based on groups
I have a data set that has some categorical values, also it has an item_id and target: import pandas as pd data = [['Salt Lake City','a', 1, 120], ['Seattle','b', 2, 120], ['San Franscisco','a', 3, 140], ['Seattle','a', 3, 100], ['Seattle', 'a', 2, 70], ['San Franscisco','a', 1, 100],['Salt Lake City','a',...
[ "You can store values of the mean into a member variable like this.\nclass FeatureEngineeringCategoryToTargetMean:\n def __init__(self, features):\n self.features = features\n self.mean_by_feature = {}\n\n def fit(self, X):\n for feature in self.features:\n mean = ...\n ...
[ 0 ]
[]
[]
[ "encoding", "group_by", "mean", "python" ]
stackoverflow_0074269917_encoding_group_by_mean_python.txt
Q: Django: Retrieving IDs of manyToMany fields quickly I have the following model schema in Django (with Postgres). class A(Models.model): related = models.ManyToManyField("self", null=True) Given a QuerySet of A, I would like to return a dictionary mapping each instance of A in the QuerySet to a list of ids of...
Django: Retrieving IDs of manyToMany fields quickly
I have the following model schema in Django (with Postgres). class A(Models.model): related = models.ManyToManyField("self", null=True) Given a QuerySet of A, I would like to return a dictionary mapping each instance of A in the QuerySet to a list of ids of its related instances as quickly as possible. I can sure...
[ "According you have Three instances. You can use the values_list method to retrieve just the results and from this result get just the ID's of their related instances.\nI use the pk field to be my filter because i don't know your scheme, but you can use anything, just must be a QuerySet.\n>>> result = A.objects.fil...
[ 21, 1, 0 ]
[]
[]
[ "database", "django", "m2m", "postgresql", "python" ]
stackoverflow_0017388254_database_django_m2m_postgresql_python.txt
Q: How to loop on value in a data frame and insert zeros in the middle I have a value in a column 'ACCOUNT_N0', it consists of 14 digits I want them to be 16 digits by inserting 2 zeros in the middle, one in the 4th position and the other in the 8th position example: This is the value: 33322288888888 The output: 3330...
How to loop on value in a data frame and insert zeros in the middle
I have a value in a column 'ACCOUNT_N0', it consists of 14 digits I want them to be 16 digits by inserting 2 zeros in the middle, one in the 4th position and the other in the 8th position example: This is the value: 33322288888888 The output: 3330222088888888 What i have found is inserting zeros at the beginning of the...
[ "Strings are immutable (you cannot change a string's value). So you can use slicing to add the 0s in the right position as so:\nmy_str[:4] + \"0\" + my_str[4:8] + \"0\" + my_str[8:]\n\nIn your pandas dataframe, you could apply this concept like this:\ndf['ACCOUNT_NO'] = df['ACCOUNT_NO'].astype(str)\ndf['ACCOUNT_NO'...
[ 1, 0 ]
[]
[]
[ "data_analysis", "data_cleaning", "data_science", "python", "validation" ]
stackoverflow_0074288691_data_analysis_data_cleaning_data_science_python_validation.txt
Q: matplotlib pyplot error in jupyter notebook Within Jupyter notebook I can import matplotlib but not the pyplot module: import matplotlib % works import matplotlib.pyplot as plt % The kernel appears to have died. It will restart automatically. An alternative test also fails: import matplotlib matplotlib.pyplot ...
matplotlib pyplot error in jupyter notebook
Within Jupyter notebook I can import matplotlib but not the pyplot module: import matplotlib % works import matplotlib.pyplot as plt % The kernel appears to have died. It will restart automatically. An alternative test also fails: import matplotlib matplotlib.pyplot % AttributeError: module 'matplotlib' has no a...
[ "This imports matplotlib module/library and then you are trying looks for an attribute or variable defined in matplotlib library named as pyplot; which does not exist. pyplot is just an interface for you to call other relevant interactive state-based functions to plot.\nimport matplotlib\nmatplotlib.pyplot \n\nIn ...
[ 3, 0, 0 ]
[]
[]
[ "jupyter_notebook", "matplotlib", "python" ]
stackoverflow_0071181990_jupyter_notebook_matplotlib_python.txt
Q: Fastest way for axis-wise matrix multiplication in python? I want to multiply the same matrix axis-wise, where a matrix A has the shape (n, d): e.g. (3, 5): A = array([[ 0, 3, 6, 9, 12], [ 1, 4, 7, 10, 13], [ 2, 5, 8, 11, 14]]) I don't know whether this multiplication or product has a...
Fastest way for axis-wise matrix multiplication in python?
I want to multiply the same matrix axis-wise, where a matrix A has the shape (n, d): e.g. (3, 5): A = array([[ 0, 3, 6, 9, 12], [ 1, 4, 7, 10, 13], [ 2, 5, 8, 11, 14]]) I don't know whether this multiplication or product has a name, because I didn't find anything common. But my goal is, to...
[ "import numpy as np\n\nA = np.array([[ 0, 3, 6, 9, 12],\n [ 1, 4, 7, 10, 13],\n [ 2, 5, 8, 11, 14]])\n\nmul = A[None, :, :] * A[:, None, :]\n\nnp.median(mul, axis=2)\n\n# array([[36., 42., 48.],\n# [42., 49., 56.],\n# [48., 56., 64.]])\n\n" ]
[ 2 ]
[]
[]
[ "matrix", "median", "numpy", "python" ]
stackoverflow_0074288808_matrix_median_numpy_python.txt
Q: path error when running Pytest tests from cmd I have this issue with Pytest where unit tests run fine from PyCharm but doesn't when I run through pipeline "python -m pytest". Below is my project structure: Common |_____configuration.py | Services | |-----ServiceA | | | |___src | ...
path error when running Pytest tests from cmd
I have this issue with Pytest where unit tests run fine from PyCharm but doesn't when I run through pipeline "python -m pytest". Below is my project structure: Common |_____configuration.py | Services | |-----ServiceA | | | |___src | | |___utils | | |__ _...
[ "In pytest >= 7.0.0 you can register extra path using Pytest's pythonpath config option. The path value should be relative to the rootdir. So it might be Common or ../Common or even prefixed with more parent levels.\nIf you use pyproject.toml:\n[tool.pytest.ini_options]\npythonpath = [\"Common\"]\n\nIf you use pyte...
[ 1, 0 ]
[]
[]
[ "pytest", "python", "unit_testing" ]
stackoverflow_0074286776_pytest_python_unit_testing.txt
Q: Extract specific segment from m3u8 playlist using I wish to extract parts from an m3u8 hls playlist given 'start time' and 'end unix time' Assuming, start unix time = 1667112116900 end unix time = 1667112133040 Example input file = #EXTINF:5.9610000000, /home/aanisnoor/Videos/DVR/segments_test_push/166711209444...
Extract specific segment from m3u8 playlist using
I wish to extract parts from an m3u8 hls playlist given 'start time' and 'end unix time' Assuming, start unix time = 1667112116900 end unix time = 1667112133040 Example input file = #EXTINF:5.9610000000, /home/aanisnoor/Videos/DVR/segments_test_push/1667112094442.ts #EXTINF:5.3340000000, /home/aanisnoor/Videos/DVR/...
[ "You don't show the complete playlist but if you have one or more EXT-X-PROGRAM-DATE-TIME tag in your playlist then you can easily relate the start of each segment to a wall clock time. Then you could convert that to a Unix time and easily make the comparison.\nThe implied time of each segment is the sum of the PRO...
[ 0 ]
[]
[]
[ "c++", "http_live_streaming", "m3u8", "python", "transport_stream" ]
stackoverflow_0074262388_c++_http_live_streaming_m3u8_python_transport_stream.txt
Q: Python Start ThreadPoolExecutors in multiprocesses, for a performance increase I am just doing simple I/O tasks and want to improve the performance of my program, using 1000 threads (which is important cause I want to run a high number of tasks in the same time, and MultiProcessingPool isn't doing the job obv if I...
Python Start ThreadPoolExecutors in multiprocesses, for a performance increase
I am just doing simple I/O tasks and want to improve the performance of my program, using 1000 threads (which is important cause I want to run a high number of tasks in the same time, and MultiProcessingPool isn't doing the job obv if I only have 8 cores I can only run 8 tasks) just takes too long to start them up, the...
[ "you can obviously create a function that each process will run that will create the threadpool and submit work to it, you just need to split the work into equal parts using a custom function.\nfrom concurrent.futures import ThreadPoolExecutor, as_completed, ProcessPoolExecutor\n\n\ndef runTask(index, profile):\n ...
[ 0 ]
[]
[]
[ "multiprocessing", "multithreading", "python" ]
stackoverflow_0074287648_multiprocessing_multithreading_python.txt
Q: Pandas - Replace cell values using a conditional (normalising string input for gender) Example data id Gender Age 1 F 22 2 Fem 18 3 male 45 4 She/Her 30 5 Male 25 6 Non-bianary 26 7 M 18 8 female 20 9 Male 56 I want to be able to standardise this somewhat by replacing all cells with an 'F' in them with ...
Pandas - Replace cell values using a conditional (normalising string input for gender)
Example data id Gender Age 1 F 22 2 Fem 18 3 male 45 4 She/Her 30 5 Male 25 6 Non-bianary 26 7 M 18 8 female 20 9 Male 56 I want to be able to standardise this somewhat by replacing all cells with an 'F' in them with 'Female', and all cells with 'M' in them with 'Male'. I know the first step...
[ "Try using regex:\nimport re\n\ndf[\"Gender\"] = df[\"Gender\"].str.replace(\n r\"^F\\S*$\", \"Female\", flags=re.I, regex=True\n)\nprint(df)\n\nPrints:\n id Gender Age\n0 1 Female 22\n1 2 Female 18\n2 3 male 45\n3 4 She/Her 30\n4 5 Male 25\n5 6 No...
[ 2, 1, 1 ]
[]
[]
[ "conditional_statements", "pandas", "python", "string" ]
stackoverflow_0074287677_conditional_statements_pandas_python_string.txt
Q: Merging two list of dicts with different keys effectively I've got two lists: lst1 = [{"name": "Hanna", "age":3}, {"name": "Kris", "age": 18}, {"name":"Dom", "age": 15}, {"name":"Tom", "age": 5}] and the second one contains a few of above key name values under different key: lst2 = [{"user...
Merging two list of dicts with different keys effectively
I've got two lists: lst1 = [{"name": "Hanna", "age":3}, {"name": "Kris", "age": 18}, {"name":"Dom", "age": 15}, {"name":"Tom", "age": 5}] and the second one contains a few of above key name values under different key: lst2 = [{"username": "Kris", "Town": "Big City"}, {"username":"Dom", ...
[ "To avoid iterating over another list again and again, you can build a name index first.\nlst1 = [{\"name\": \"Hanna\", \"age\":3},\n {\"name\": \"Kris\", \"age\": 18},\n {\"name\":\"Dom\", \"age\": 15},\n {\"name\":\"Tom\", \"age\": 5}]\nlst2 = [{\"username\": \"Kris\", \"Town\": \"Big City\"}...
[ 1, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074288431_dictionary_python.txt
Q: How do I define a variable with 2 outputs in Python? I have this problem that I can´t solve. I have this function: def ex2(tex_ori): let = ("a" or "A") text_troc = tex_ori.replace(let, "x") return text_troc And the execution for this is: text_ori = input("Write a sentence: ") text_1 = ex2(text_or...
How do I define a variable with 2 outputs in Python?
I have this problem that I can´t solve. I have this function: def ex2(tex_ori): let = ("a" or "A") text_troc = tex_ori.replace(let, "x") return text_troc And the execution for this is: text_ori = input("Write a sentence: ") text_1 = ex2(text_ori) print(text_1) But the only letter being replaced ...
[ "When you write let = (\"a\" or \"A\") the let variable will store only the first true statement from the two (in this case \"a\"). In order to replace both letters you can write it for example this way:\ndef ex2(tex_ori):\n text_troc = tex_ori.replace(\"a\", \"x\")\n text_troc = text_troc.replace(\"A\", \"x\...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074289063_python.txt
Q: outputLimits Matlab equivalent for python I am trying to convert a matlab code to python, unfortunately I am facing the problem that I don't find an equivalent of the matlab function outputLimits. The function is suppose to : Estimate the output spatial limits corresponding to a set of input spatial limits, xLimit...
outputLimits Matlab equivalent for python
I am trying to convert a matlab code to python, unfortunately I am facing the problem that I don't find an equivalent of the matlab function outputLimits. The function is suppose to : Estimate the output spatial limits corresponding to a set of input spatial limits, xLimitsIn and yLimitsIn, given 2-D geometric transfor...
[ "If you take the corner points of the original image, and transform them using the tform matrix, you will get their new location. These new locations will be the output limits of the new image.\n" ]
[ 0 ]
[]
[]
[ "matlab", "python" ]
stackoverflow_0073960877_matlab_python.txt
Q: Convert json to Query I am trying to build a query builder to be processed by Pandas query. So below is the structure. { ["AND", ["OR", ["AND", { "Property": "ColumnA", "Operand": ">", "Value": "56" }, { "Property": "ColumnA", "Operand": "<", ...
Convert json to Query
I am trying to build a query builder to be processed by Pandas query. So below is the structure. { ["AND", ["OR", ["AND", { "Property": "ColumnA", "Operand": ">", "Value": "56" }, { "Property": "ColumnA", "Operand": "<", "Value": "78" ...
[ "As per @Andrew's suggestion, created a dictionary using a while loop rather than recusing which helped me with the position of joins.\n" ]
[ 0 ]
[]
[]
[ "logic", "nested_loops", "python" ]
stackoverflow_0074106284_logic_nested_loops_python.txt
Q: select.select() arguments file descriptor cannot be a negative integer error I am working on a simple chat app in python 3.6.1 for personal use. I get this error with select.select: Traceback (most recent call last): File "C:\Users\Nathan Glover\Google Drive\MAGENTA Chat\chat_server.py", line 27, in <module> ...
select.select() arguments file descriptor cannot be a negative integer error
I am working on a simple chat app in python 3.6.1 for personal use. I get this error with select.select: Traceback (most recent call last): File "C:\Users\Nathan Glover\Google Drive\MAGENTA Chat\chat_server.py", line 27, in <module> ready_to_read,ready_to_write,in_error = select.select(SOCKET_LIST,[],[],0) Value...
[ "I know it's been a long time since this question was asked. But I wanted to let OP and others know about the problem here.\nThe problem here is that the SOCKET_LIST must be containing a non-existing socket connection which may have been disconnected earlier. If you pass such connection to select it gives this erro...
[ 6, 1, 0, 0 ]
[]
[]
[ "python", "select", "server", "sockets" ]
stackoverflow_0046647167_python_select_server_sockets.txt
Q: How to connect to MySQL over `TCP/IP` and `TCP/IP over ssh` from python code? I am able to connect to my database with sql workbench. But when I am trying to connect with python code, I am getting confused. I have found some similar codes on internet and stack over flow but I am not able to connect with code. How ...
How to connect to MySQL over `TCP/IP` and `TCP/IP over ssh` from python code?
I am able to connect to my database with sql workbench. But when I am trying to connect with python code, I am getting confused. I have found some similar codes on internet and stack over flow but I am not able to connect with code. How can I connect to the DB with the following details? Using python code. EDIT:: I al...
[ "You can use the python-mysql driver\nimport mysql.connector\n\nmydb = mysql.connector.connect(\n host=\"localhost\",\n port=\"2121\",\n user=\"yourusername\",\n password=\"yourpassword\"\n)\n\nprint(mydb)\n\nThis doc explains it in details.\nConnecting VIA SSH is descibed here - Enable Python to Connect to MyS...
[ 1 ]
[]
[]
[ "mysql_connector_python", "python" ]
stackoverflow_0074289097_mysql_connector_python_python.txt
Q: QWebEngineView.page().runJavaScript() does not run a JavaScript code correctly I am making a Python program using PyQt5 GUI library. I found out that using runJavaScript() method does not work for executing JavaScript code on my HTML document. Here is my HTML document - a Mapbox GL JS component. It can also be fou...
QWebEngineView.page().runJavaScript() does not run a JavaScript code correctly
I am making a Python program using PyQt5 GUI library. I found out that using runJavaScript() method does not work for executing JavaScript code on my HTML document. Here is my HTML document - a Mapbox GL JS component. It can also be found here: https://docs.mapbox.com/mapbox-gl-js/example/simple-map/ . <!DOCTYPE html> ...
[ "My suggestion was right - it happened because the JS function in page.runJavaScript() was executed before the .js script in HEAD section of the HTML file has completed it's execution.\nSo, to solve the issue I delayed page().runJavascript() execution until the HTML file finishes loading completely (including .js f...
[ 0 ]
[]
[]
[ "pyqt", "pyqt5", "python", "qwebengineview", "qwidget" ]
stackoverflow_0074257725_pyqt_pyqt5_python_qwebengineview_qwidget.txt
Q: Tiingo Data Reader I was developing a price prediction model that requires Tiingo but there seems to be problem in the API authentification. I used the OS access the Tiingo API. ` api_key =os.environ.get('TIINGO_API_KEY') df=pdr.get_data_tiingo('AAPL',api_key) df=pd.read_csv('AAPL.csv') print(df.tail(...
Tiingo Data Reader
I was developing a price prediction model that requires Tiingo but there seems to be problem in the API authentification. I used the OS access the Tiingo API. ` api_key =os.environ.get('TIINGO_API_KEY') df=pdr.get_data_tiingo('AAPL',api_key) df=pd.read_csv('AAPL.csv') print(df.tail()) The error I got look...
[ "It seems api_key is coming as None. You should check that.\n" ]
[ 0 ]
[]
[]
[ "python", "tiingo" ]
stackoverflow_0072067279_python_tiingo.txt
Q: Passing Arguments to Threading in Python 2.7 through "target =" vs through "args = " I am using threading for the first time, in python 2.7. I am looking for guidance on which of the two techniques below is preferable, and why. Technique 2 is given on most online tutorials. But i tried technique 1 by mistake, and ...
Passing Arguments to Threading in Python 2.7 through "target =" vs through "args = "
I am using threading for the first time, in python 2.7. I am looking for guidance on which of the two techniques below is preferable, and why. Technique 2 is given on most online tutorials. But i tried technique 1 by mistake, and it also worked. Technique 1: import threading def worker(number): print ('I am thread...
[ "This code below does not call worker() in a new thread:\nthread = threading.Thread(target=worker(i))\n\nHere's how Python interprets this code above:\n\nMain thread calls worker(i).\nworker(i) returns None.\n\nSo actually, None is assigned to target as shown below:\nthread = threading.Thread(target=None)\n\nSo, st...
[ 0 ]
[]
[]
[ "arguments", "multithreading", "python" ]
stackoverflow_0051684169_arguments_multithreading_python.txt
Q: Save dataframe to file so that it can be reimported I'm quite new to Python and I'm wondering what would be the best way to save a dataframe in a way so that it can be easily reimported. I'm running a code that checks for newly added files and imports them. In case it is stopped for any reason, I would like to rei...
Save dataframe to file so that it can be reimported
I'm quite new to Python and I'm wondering what would be the best way to save a dataframe in a way so that it can be easily reimported. I'm running a code that checks for newly added files and imports them. In case it is stopped for any reason, I would like to reimport the last data that was saved before it stopped. So,...
[ "Simply save it to csv with pandas.DataFrame.to_csv and then you can easily import it with pandas.read_csv.\n" ]
[ 1 ]
[]
[]
[ "csv", "dataframe", "pandas", "python" ]
stackoverflow_0074289210_csv_dataframe_pandas_python.txt
Q: Finding the Time when a Specific Point in a Time Series is Reached I have a set of time series data where I am trying to find at what point they reach a specific value. I tried this, that gets me the answer but produces the whole column as opposed to the specific value in the time column and I am unsure how to ite...
Finding the Time when a Specific Point in a Time Series is Reached
I have a set of time series data where I am trying to find at what point they reach a specific value. I tried this, that gets me the answer but produces the whole column as opposed to the specific value in the time column and I am unsure how to iterate over several columns. num = df['Time column'].where(df['Data Column...
[ "With DataFrame.loc you can find the rows that satisfy your condition. Check the example below:\nmock_time_series.csv\n\ntime,v1,v2 \n100,10,20\n200,20,22\n300,14,12\n400,33,22\n500,43,62\n\ndf = pd.read_csv('mock_time_series.csv')\n\nBy using .loc:\ndf.loc[df['v1'] >= 20]['time'].values\n\nYou will get as a re...
[ 0, 0 ]
[]
[]
[ "dataframe", "python", "time_series" ]
stackoverflow_0074128763_dataframe_python_time_series.txt
Q: How to use smartphone camera with OpenCV (via USB) - Python I am trying to use my iPhone camera with OpenCV. However, Python doesn't recognize the camera. Some months ago I did it simply writing: cap = cv2.VideoCapture(1) Does anyone know how to solve this? I know that there are other solutions like using IP addr...
How to use smartphone camera with OpenCV (via USB) - Python
I am trying to use my iPhone camera with OpenCV. However, Python doesn't recognize the camera. Some months ago I did it simply writing: cap = cv2.VideoCapture(1) Does anyone know how to solve this? I know that there are other solutions like using IP address to use the camera with OpenCV, but I want to use the camera v...
[ "As of now, your way of accessing the camera of your iPhone is not supported by OpenCV, but there are other ways to implement OpenCV on iOS.\nOpenCV Documentation tells you to\nadd a camera controller to the view controller and initialize it when the view has loaded.\nThis is done using an XCode project utilizing t...
[ 0 ]
[]
[]
[ "iphone", "opencv", "python" ]
stackoverflow_0074289157_iphone_opencv_python.txt
Q: py_function: Replace convolution operation but keep gradient I am trying to train a LeNet-5 model in TensorFlow 2 while replacing all Dense's matrix multiplications and Conv2D's convolutions with custom ones written in C. More precisely, I would like to keep those gradients as they are by default, but use my imple...
py_function: Replace convolution operation but keep gradient
I am trying to train a LeNet-5 model in TensorFlow 2 while replacing all Dense's matrix multiplications and Conv2D's convolutions with custom ones written in C. More precisely, I would like to keep those gradients as they are by default, but use my implementation of these operations instead of TensorFlow's default ones...
[ "I actually figured it out thanks to this answer: https://stackoverflow.com/a/43952168/9675442\nThe idea was to do this:\ny = tf.matmul(a, b) + tf.stop_gradient(compute(a, b) - tf.matmul(a, b))\n\nI hope this will help others\n" ]
[ 1 ]
[]
[]
[ "python", "tensorflow", "tensorflow2.0" ]
stackoverflow_0074285505_python_tensorflow_tensorflow2.0.txt
Q: Resampled series with timedeltas does not start at zero I would like to resample a pandas series with timedelta starting with the zero interval (timedelta(seconds=0)) instead of the first occurrence. For example, for from datetime import timedelta from random import sample s = pd.Series(1, index=[timedelta(minutes...
Resampled series with timedeltas does not start at zero
I would like to resample a pandas series with timedelta starting with the zero interval (timedelta(seconds=0)) instead of the first occurrence. For example, for from datetime import timedelta from random import sample s = pd.Series(1, index=[timedelta(minutes=m) for m in sample(range(1, 100), 10)]) s.resample('1h').cou...
[ "You should use to_offset.\nfrom pandas.tseries.frequencies import to_offset\ns_res = s.resample('1h').count()\n\nWe compute the current minute index start\nminute_start = (s.index.seconds%3600//60).min()\n\nThen modify the index\ns_res.index = s_res.index - to_offset(f'{minute_start}min')\n\n", "You need to have...
[ 1, 1 ]
[]
[]
[ "pandas", "pandas_resample", "python", "timedelta" ]
stackoverflow_0074287007_pandas_pandas_resample_python_timedelta.txt
Q: Placeholder Input Value I'm very new to Python and I'm trying to set a value in the input() text. This value comes as an argument (sys.argv[1]) and I want this value to be able to be modified. An example of the input: myvar = int(input("Next input is modifiable: " , sys.argv[1])) So that the output is something l...
Placeholder Input Value
I'm very new to Python and I'm trying to set a value in the input() text. This value comes as an argument (sys.argv[1]) and I want this value to be able to be modified. An example of the input: myvar = int(input("Next input is modifiable: " , sys.argv[1])) So that the output is something like this: Next input is modif...
[ "Could this work?\nmyvar = int(input(\"Next input is modifiable: \" , sys.argv[1]))\nif myvar == \"\":\n myvar = sys.argv[1]\n\n" ]
[ 0 ]
[]
[]
[ "input", "python" ]
stackoverflow_0074289194_input_python.txt
Q: Set specific colors in a line plot in matplotlib I have 6 different columns in my dataset (cum_return_pf) which are plotted in a graph (see below). The resulting 6 lines all have a random color. How can I set the colors of each line by my own? I need that, because I want to have always the same colors in different...
Set specific colors in a line plot in matplotlib
I have 6 different columns in my dataset (cum_return_pf) which are plotted in a graph (see below). The resulting 6 lines all have a random color. How can I set the colors of each line by my own? I need that, because I want to have always the same colors in different plots import matplotlib.pyplot as plt ax = cum_retur...
[ "Similar as the suggestion to use the cycler, you could also define a list with colors (e.g. from a Colormap), where each row corresponds to the color for each plot.\nUsing a qualitative colormap\n#list with 5 colors, e.g. from colormap 'tab10'\nc = [plt.cm.tab10(i) for i in range(5)]\n\nUsing a non-qualitative col...
[ 0 ]
[]
[]
[ "colors", "matplotlib", "plot", "python" ]
stackoverflow_0074286275_colors_matplotlib_plot_python.txt
Q: How map numerical values in pandas dataframe into a discrete set? I have a dataframe with a column distances with integer values between 1 and 3500. I want to assign a weight in (0.25, 0.5, 1, 2) to each sample based on the distance value. | Distances | weights | | --------- | ------- | | >= ...
How map numerical values in pandas dataframe into a discrete set?
I have a dataframe with a column distances with integer values between 1 and 3500. I want to assign a weight in (0.25, 0.5, 1, 2) to each sample based on the distance value. | Distances | weights | | --------- | ------- | | >= 3000 | 0.25 | | >= 2000 and < 3000 | 0.5 | | >= 1...
[ "How about creating a mapping using a Series with an IntervalIndex? You can then cut your distances into appropriate bins as defined by the intervals, and map those to the respective weights:\ndf = pd.DataFrame({\n \"sample\": [\"First\", \"Second\", \"Third\"],\n \"distances\": [3234, 465, 1200]\n})\n\nmappi...
[ 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074288762_pandas_python.txt
Q: Need autentication for urllib.request with Stripe in Python I am trying to make a request to the Stripe API (which is a payment API) to get a json response which the API gives. I tried the following code I found in a Python course, but as the API needs to authenticate to get the response, I don't know how can I ad...
Need autentication for urllib.request with Stripe in Python
I am trying to make a request to the Stripe API (which is a payment API) to get a json response which the API gives. I tried the following code I found in a Python course, but as the API needs to authenticate to get the response, I don't know how can I add that data in the request. Making it in a curl request will be l...
[ "Try this code:\nfrom requests import post\n\n\nresponse = post(url='https://api.stripe.com/v1/checkout/sessions', headers={\n 'Authorization': 'bearer pk_test_51LoUz3BgfM0E8ZiCV8UO79gw8zw7fhSgHUEAVj4wS7igs5D4kKiNsxXGeKQEUhorImNUiCxCNNtidwNkhFPUHP4i0060lsvsbw',\n}, data={\n 'success_url': 'http://127.0.0.1:55...
[ 2, 0, 0 ]
[]
[]
[ "curl", "json", "python", "stripe_payments", "urllib" ]
stackoverflow_0074274081_curl_json_python_stripe_payments_urllib.txt
Q: How to navigate to the next page of a site using css selectors I'm extracting property information from a website (Find Properties For Sale). I've been able to scrape the first page. But when I tried to scrape data from the next page, my code duplicated the data from the first page. How do I correct this? Here is ...
How to navigate to the next page of a site using css selectors
I'm extracting property information from a website (Find Properties For Sale). I've been able to scrape the first page. But when I tried to scrape data from the next page, my code duplicated the data from the first page. How do I correct this? Here is my approach: next_page = response.css("ul.pagination li.page-item a....
[ "You can use this xpath expression:\nnext_page = response.xpath(\"//a[@alt='view next property page']\").css(\"::attr(href)\").get()\n\n" ]
[ 0 ]
[]
[]
[ "css", "html", "python", "scrapy" ]
stackoverflow_0074288883_css_html_python_scrapy.txt
Q: how do I get a particular text using Python I need a text after a keyword My text file like this. I am trying to extract the car info, car model, and append in to the python dict. # car name BMW suzuki # car model X1 TT # color red blue My code: keywords = [car_name,car_model,color] parsed_content = {} def...
how do I get a particular text using Python
I need a text after a keyword My text file like this. I am trying to extract the car info, car model, and append in to the python dict. # car name BMW suzuki # car model X1 TT # color red blue My code: keywords = [car_name,car_model,color] parsed_content = {} def car_info(text): content = {} indices = [...
[ "Your attempt seems extraordinarily overcomplicated. Aren't you simply looking for something like this?\nfrom collections import defaultdict\n\ndef car_info(filename):\n with open(filename) as lines:\n values = defaultdict(list)\n for line in lines:\n line = line.strip()\n if ...
[ 2, 0 ]
[]
[]
[ "python", "text_extraction" ]
stackoverflow_0074287837_python_text_extraction.txt
Q: BaseException when trying to import azureml-train-automl-runtime in windows 10 I am trying import azureml-train-automl-runtime to do explanations from azure automl pipeline. But I am getting the below error Exception ignored in: <function _Win32Helper.del at 0x0000021ECA3AD430> Traceback (most recent call last): ...
BaseException when trying to import azureml-train-automl-runtime in windows 10
I am trying import azureml-train-automl-runtime to do explanations from azure automl pipeline. But I am getting the below error Exception ignored in: <function _Win32Helper.del at 0x0000021ECA3AD430> Traceback (most recent call last): File "C:\Anaconda3\envs\check_win32_error\lib\site-packages\azureml\automl\runtime\s...
[ "Inheritance is the issue that happened. The library which needs to be imported need to be inherited to use. Run the pipeline with the inherited pattern in the code block.\nclass automl_setup_model_explanations (AutoMLExplainerSetupClass):\n pass \n\nreturn AutoMLExplainerSetupClass\n\nThe implementation will be...
[ 0 ]
[]
[]
[ "azure", "azure_machine_learning_service", "azure_sdk_python", "python", "windows" ]
stackoverflow_0074160617_azure_azure_machine_learning_service_azure_sdk_python_python_windows.txt
Q: Change values in df column based on condition using another df I have a dataframe df1 like below - |email_id | date |role |abc@gmail.com | '2022-09-08' |1 |abc@gmail.com | '2022-07-01' |1 |abc@gmail.com | nan |1 |xyz@gmail.com | '2022-04-01' |1 |gmh@gmail.com | nan |1 |ytr@gmail.com | '2022-09-08' |1 |ytr@gmail.co...
Change values in df column based on condition using another df
I have a dataframe df1 like below - |email_id | date |role |abc@gmail.com | '2022-09-08' |1 |abc@gmail.com | '2022-07-01' |1 |abc@gmail.com | nan |1 |xyz@gmail.com | '2022-04-01' |1 |gmh@gmail.com | nan |1 |ytr@gmail.com | '2022-09-08' |1 |ytr@gmail.com | '2022-09-02' |1 and df2 - |email_id | status |role |abc@gmail.c...
[ "One can use a list comprehension as follows\ndf2['status'] = [1 if df1[(df1['email_id'] == email_id) & (df1['date'].isna())].shape[0] > 0 else 0 if df1[(df1['email_id'] == email_id) & (df1['date'].notna())].shape[0] > 0 else 1 for email_id in df2['email_id']]\n\n[Out]:\n\n email_id status role\n0 abc@gma...
[ 0 ]
[]
[]
[ "aggregate", "dataframe", "pandas", "python" ]
stackoverflow_0074289117_aggregate_dataframe_pandas_python.txt
Q: How to specify $top in Python Azure Tables query_entities? I want to filter on the PartitionKey, and get the top 1 record from the matches (using the default ordering specified by the RowKey values). For filtering entities in a table, I'm using TableClient.query_entities. How can I add the $top parameter to the ex...
How to specify $top in Python Azure Tables query_entities?
I want to filter on the PartitionKey, and get the top 1 record from the matches (using the default ordering specified by the RowKey values). For filtering entities in a table, I'm using TableClient.query_entities. How can I add the $top parameter to the executed HTTP request? results_per_page = 1 does not limit the res...
[ "Created two table entities to query the top entity that is BlueMarker in myTable.\n\nYou can get the Top row by http URL, via filtering your table with top parameter:\n\nWe can assign read/write permissions to the table and try accessing it via below given Url's:\nhttps://siliconstrg4.table.core.windows.net/myTabl...
[ 0 ]
[]
[]
[ "azure_python_sdk", "azure_table_storage", "python" ]
stackoverflow_0074056471_azure_python_sdk_azure_table_storage_python.txt
Q: How to find value in a column based on min value from another column per group pandas I have a dataframe like this I need to generate a new column which hold the quota of min scale_qty of each group created by plant, material. This is the expected result: All that I can do so far is just to get the rows which co...
How to find value in a column based on min value from another column per group pandas
I have a dataframe like this I need to generate a new column which hold the quota of min scale_qty of each group created by plant, material. This is the expected result: All that I can do so far is just to get the rows which contain the min scale_qty or find the minimum of scale_qty itself, I'm stucking at how the ge...
[ "Use pandas.Series.idxmin combined with transform to get the new column.\ndf['quota_of_min_scale_qty'] = (\n df.loc[\n df\n .groupby(['plant', 'material'])['scale_qty']\n .transform(lambda x: x.idxmin()), 'quota']\n .values\n)\n\n" ]
[ 3 ]
[]
[]
[ "dataframe", "group_by", "pandas", "python" ]
stackoverflow_0074289146_dataframe_group_by_pandas_python.txt
Q: Problem with multiprocessing Python Selenium I want to open the same sites in multiprocessing (and use specific chrome profiles). But after running the code, it opens chrome profiles but open link only on one. Code: from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium....
Problem with multiprocessing Python Selenium
I want to open the same sites in multiprocessing (and use specific chrome profiles). But after running the code, it opens chrome profiles but open link only on one. Code: from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from multi...
[ "Back when I tried to implement multiprocessing I had a very rough time as well, I solved it using seleniumbase and would recommend you to check it out, you can specify how many threads you want to run the script in from the CLI and it has a ton of other great features that will speed up your workflow.\n" ]
[ 0 ]
[]
[]
[ "multiprocessing", "python", "selenium" ]
stackoverflow_0074283373_multiprocessing_python_selenium.txt
Q: How to make the database giving me two datas Hello my Database (Sqlite3) is giving me just one data from all the database, I want it to give me all datas but I don't know why It didn't, here's what I tried c.execute("SELECT type FROM accounts") acctype = c.fetchmany() It gave me just One for Some reasons ...
How to make the database giving me two datas
Hello my Database (Sqlite3) is giving me just one data from all the database, I want it to give me all datas but I don't know why It didn't, here's what I tried c.execute("SELECT type FROM accounts") acctype = c.fetchmany() It gave me just One for Some reasons !
[ "By default, 1 is considered \"many\"! Use fetchmany(size=2) if you want to fetch the next 2 rows.\nIf you want all the rows, just use fetchall() instead.\n" ]
[ 1 ]
[]
[]
[ "database", "python", "sqlite" ]
stackoverflow_0074289522_database_python_sqlite.txt
Q: Map the multiple value dictionary with a dataframe column I have a dictionary with multiple values for 1 key. Now, I need to map them with the dataframe column. Any idea how can I solve this? Dictionary Keys_nd_Values = {'ABCD' : [223, 343, 432], 'ZXS' : ['S23', 'GT4','98J']} Data A ...
Map the multiple value dictionary with a dataframe column
I have a dictionary with multiple values for 1 key. Now, I need to map them with the dataframe column. Any idea how can I solve this? Dictionary Keys_nd_Values = {'ABCD' : [223, 343, 432], 'ZXS' : ['S23', 'GT4','98J']} Data A B C 12525 1FWE23 223 14654 14654 S23 24798 ...
[ "First we convert the Keys_nd_Values to a df and convert the rows to columns. The function we wrote later does this: get the value of the column if the row value exists as a column in the df named control.\ndfx=pd.DataFrame(Keys_nd_Values)\ncontrol = dfx.melt(ignore_index = False).set_index('value').T\n\n ...
[ 1 ]
[]
[]
[ "dataframe", "dictionary", "python" ]
stackoverflow_0074288661_dataframe_dictionary_python.txt
Q: Failing: Replace a single value with a new value for an individual DataFrame column I am trying to replace some IDs in a column. I am reading an excel file using pd.read_excel and storing it in a data frame: df_A2C = pd.read_excel(file_loc1, index_col=None, na_values=['NA']) This can be reproduced with df_A2C = p...
Failing: Replace a single value with a new value for an individual DataFrame column
I am trying to replace some IDs in a column. I am reading an excel file using pd.read_excel and storing it in a data frame: df_A2C = pd.read_excel(file_loc1, index_col=None, na_values=['NA']) This can be reproduced with df_A2C = pd.DataFrame({'FROM_ID': [1, 1, 1, 1, 1], 'TO_ID': [7, 26, 71, 83, 98], 'DURATION_H': [0...
[ "Have you tried\ndf_A2C['FROM_ID'] = df_A2C['FROM_ID'].apply(lambda x: 8 if x==9 else x)\n\nthat is if your values are int\nif your values are strings use this\ndf_A2C['FROM_ID'] = df_A2C['FROM_ID'].apply(lambda x: '8' if x=='9' else x)\n\n", "Your solution based on replace works, I guess the problem is somewhere...
[ 4, 0 ]
[]
[]
[ "dataframe", "jupyter_notebook", "pandas", "python", "python_3.x" ]
stackoverflow_0074244996_dataframe_jupyter_notebook_pandas_python_python_3.x.txt
Q: dyld[3169]: Library not loaded: @rpath/libtbb.dylib I am trying to use prophet on python to forecast stock data. I could download the package fine through pip install prophet but when i run: m = Prophet() m.fit(mydataframe) It gives me this error: RuntimeError: Error during optimization: console log output: dyld...
dyld[3169]: Library not loaded: @rpath/libtbb.dylib
I am trying to use prophet on python to forecast stock data. I could download the package fine through pip install prophet but when i run: m = Prophet() m.fit(mydataframe) It gives me this error: RuntimeError: Error during optimization: console log output: dyld[3169]: Library not loaded: @rpath/libtbb.dylib Referen...
[ "For what it's worth, installing tdd with brew: brew install tdd solved the issue for me.\nThis is on an ARM (M1) mac and I've seen a few other threads not specific to prophet but that did require this library also suggesting installing tdd with brew\n", "There is an issue with Prophet 1.1 and Mac M1. Use Version...
[ 0, 0 ]
[]
[]
[ "facebook_prophet", "prophet", "pycharm", "python" ]
stackoverflow_0073408919_facebook_prophet_prophet_pycharm_python.txt
Q: Is there an efficient way to find minimum xor value between a key and elements of a list? Assume that I have a list of 10 thousand random numbers chosen in this way: random_num = list(np.random.choice(2**16, 10000, replace=False)) Now, I have a key in the same range (e.g., 1024), and I need to find 10 numbers from...
Is there an efficient way to find minimum xor value between a key and elements of a list?
Assume that I have a list of 10 thousand random numbers chosen in this way: random_num = list(np.random.choice(2**16, 10000, replace=False)) Now, I have a key in the same range (e.g., 1024), and I need to find 10 numbers from the sorted list that have minimum value with the key based on the xor distance: xor_dist = key...
[ "Sorting is overkill, because it sorts all the numbers in O(n lg n) time, but you don't care about the ordering of 9,990 of the elements.\nInstead, use the heapq module to build a heap (in O(n) time) from which you can extract the 10 smallest in O(lg n) time.\nimport numpy as np\nimport heapq\n\nrandom_num = np.ran...
[ 1, 0 ]
[]
[]
[ "binary_search", "python", "xor" ]
stackoverflow_0074289611_binary_search_python_xor.txt
Q: How to make a scatter plot of based on the value of 'type' column? I have a dataframe that looks like this: type date count CLASS A jan 456 0 A feb 121 1 A mar 333 1 B apr 123 1 B may 123 1 C jun 189 1 C j...
How to make a scatter plot of based on the value of 'type' column?
I have a dataframe that looks like this: type date count CLASS A jan 456 0 A feb 121 1 A mar 333 1 B apr 123 1 B may 123 1 C jun 189 1 C jul 789 1 I would like to create a scatter plot of the counts of ...
[ "Try this:\ndf[df['type']=='A'].plot.scatter('date', 'count')\n\nSince you only want the data where type is A you don't need a groupby here.\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "scatter_plot" ]
stackoverflow_0074289572_dataframe_pandas_python_scatter_plot.txt
Q: Tensorboard just show the graph a second and the graph disappear Generally, my problem is the graph doesn't show in tensorboard. My device is ubuntu16.04, tensorflow-gpu 1.12.0, and tensorboard 1.12.0. However, it not totally doesn't show the graph, it shows up a flash and disappears. The picture when it just star...
Tensorboard just show the graph a second and the graph disappear
Generally, my problem is the graph doesn't show in tensorboard. My device is ubuntu16.04, tensorflow-gpu 1.12.0, and tensorboard 1.12.0. However, it not totally doesn't show the graph, it shows up a flash and disappears. The picture when it just started After a second My code is here(just need to check constructed func...
[ "In my case, the reason was due to sess.graph having so many sub-graphs that Tensorboard had to zoom out to such a degree that the entire viz had disappeared from the screen.\nMy current solution (at the lack of a more systematic solution) is to double-click whatever node that you can click on during that brief per...
[ 2, 0 ]
[]
[]
[ "python", "tensorboard" ]
stackoverflow_0054004747_python_tensorboard.txt
Q: How to access data in an iteration when reading a csv with pandas I have a problem that I cannot solve. I would like to be able to do the following when reading a csv At each iteration, I can access a column by its name from the csv I tried the following code but was unsuccessful products = pandas.read_csv(f'./sto...
How to access data in an iteration when reading a csv with pandas
I have a problem that I cannot solve. I would like to be able to do the following when reading a csv At each iteration, I can access a column by its name from the csv I tried the following code but was unsuccessful products = pandas.read_csv(f'./storage/temp/{file_name}', delimiter=',', on_bad_lines='skip').to_dict() ...
[ "It's easier to use pandas for this purpose.\nimport pandas as pd\n\nproducts = pd.read_csv('dffile.txt', header=0)\n\n\nprint(products['product_url'])\n\nfor i in products.columns:\n print('name column', i)\n print(products[i])\n\nBut, if you still need it, as you tried, then you need to apply items ().\nfil...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074276663_pandas_python.txt
Q: Converting a cisco wildcard mask to list of IPNetworks in Python So, cisco routers allow one to specify ACLs using what are called wildcard masks. Wildcard masks specify a group of hosts using a 32-bit long integer, but they differ from the typical netmask in that when a bit is 0 in wildcard mask, it represents a ...
Converting a cisco wildcard mask to list of IPNetworks in Python
So, cisco routers allow one to specify ACLs using what are called wildcard masks. Wildcard masks specify a group of hosts using a 32-bit long integer, but they differ from the typical netmask in that when a bit is 0 in wildcard mask, it represents a compulsory match and when it is 1, then it is a wildcard. Some folks (...
[ "in Python 2.7:\nimport ipaddress\n\nmask = u\"0.1.2.7\"\naddress = u\"172.18.161.2\"\n\ndef wildcard_mask_test (test_octet, acl_octet, acl_wildcard_octet):\n #Test one number against acl address and mask\n #Bitwise OR of test_octet and acl_octet against the octet of the wildcard mask\n test_result = test_...
[ 3, 0, 0, 0, 0, 0 ]
[]
[]
[ "cisco", "ip", "mask", "python", "wildcard" ]
stackoverflow_0019944607_cisco_ip_mask_python_wildcard.txt
Q: Celery tasks received but not executing I have Celery tasks that are received but will not execute. I am using Python 2.7 and Celery 4.0.2. My message broker is Amazon SQS. This the output of celery worker: $ celery worker -A myapp.celeryapp --loglevel=INFO [tasks] . myapp.tasks.trigger_build [2017-01-12 23:34:...
Celery tasks received but not executing
I have Celery tasks that are received but will not execute. I am using Python 2.7 and Celery 4.0.2. My message broker is Amazon SQS. This the output of celery worker: $ celery worker -A myapp.celeryapp --loglevel=INFO [tasks] . myapp.tasks.trigger_build [2017-01-12 23:34:25,206: INFO/MainProcess] Connected to sqs://...
[ "First install eventlet,\n\n> pip install eventlet\n\n\nand then run\n\n> celery -A myapp.celeryapp worker --loglevel=info -P eventlet\n\n\n", "I was also getting same issue. After little bit for searching i found solution to add --without-gossip --without-mingle --without-heartbeat -Ofair to the Celery worker co...
[ 14, 8, 4, 3, 2 ]
[ "celery -A core worker --loglevel=INFO --without-gossip --without-mingle --without-heartbeat -Ofair --pool=solo\n" ]
[ -1 ]
[ "amazon_ec2", "amazon_elastic_beanstalk", "amazon_web_services", "celery", "python" ]
stackoverflow_0041636273_amazon_ec2_amazon_elastic_beanstalk_amazon_web_services_celery_python.txt
Q: Why am I getting a Value error and negative dimension size on my python code (cnn_model) Error : File "C:\Users\Ayeh\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler raise e.with_traceback(filtered_tb) from None File "C:\Users\Ayeh\AppData\L...
Why am I getting a Value error and negative dimension size on my python code (cnn_model)
Error : File "C:\Users\Ayeh\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler raise e.with_traceback(filtered_tb) from None File "C:\Users\Ayeh\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\framework\ops.py", line 196...
[ "If the padding argument is not specified, it will default to valid, which means that the automatic dimensionality reduction that occurs during convolution will be present. If you use this model to calculate that for a 64x64 image with automatic dimensionality reduction, you'll get negative dimensions. To ensure th...
[ 0 ]
[]
[]
[ "keras", "python", "tensorflow" ]
stackoverflow_0074162746_keras_python_tensorflow.txt
Q: How to make output from web scraping python selenium in div class to output text This is my Code ` from attr import attr import requests from bs4 import BeautifulSoup import csv datas = [] key = 'sepatu' jenis = 'teplek' url = 'https://website.com/search/?term={}+{}'.format(key,jenis) headers = { 'user-agent'...
How to make output from web scraping python selenium in div class to output text
This is my Code ` from attr import attr import requests from bs4 import BeautifulSoup import csv datas = [] key = 'sepatu' jenis = 'teplek' url = 'https://website.com/search/?term={}+{}'.format(key,jenis) headers = { 'user-agent' : 'Mozilla/5.0 (X11; Linux x86_64; rv:106.0) Gecko/20100101 Firefox/106.0' } req = re...
[ "You can add .text in this line\nharga = soup.find(\"div\", {\"class\": \"db gM ei b hE be f16-360-o ff vb uT ellipsis-1\"}).text\n\nThen you will get an output like this\n\n\n\n\nNama Sepatu\nHarga\n\n\n\n\nSepatu A\nRp.24.000\n\n\n\n", "Looks like the problem is with the commands you use to locate the elements....
[ 1, 0 ]
[]
[]
[ "python", "selenium", "web", "web_scraping" ]
stackoverflow_0074285167_python_selenium_web_web_scraping.txt
Q: How to check if an image is pressed pygame I'm trying to make a cookie clicker clone, but my code can't detect when the grandma button is pressed. Here is my code: import pygame pygame.init() display_width = 800 display_height = 600 gameDisplay = pygame.display.set_mode((display_width,display_height)) pygame.di...
How to check if an image is pressed pygame
I'm trying to make a cookie clicker clone, but my code can't detect when the grandma button is pressed. Here is my code: import pygame pygame.init() display_width = 800 display_height = 600 gameDisplay = pygame.display.set_mode((display_width,display_height)) pygame.display.set_caption('Cookie Clicker') black = (...
[ "Change appropriate lines in your code to:\nif cookie.get_rect(topleft=(x,y)).collidepoint(mouse_pos):\n\nand\nif grandma.get_rect(topleft=(xx,yy)).collidepoint(mouse_pos):\n\nThe .get_rect() method called without parameter gives you the rectangle of the loaded image with the left upper corner set to (0, 0) and not...
[ 2 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074289422_pygame_python.txt
Q: Python program to convert wildcard mask to netmask I need help with writing a python program to achieve this task. I am trying to convert wildcard mask to netmask. Input: 192.168.0.1 0.0.0.15 Expected output: 192.168.0.1 255.255.255.240 A: What have you tried? I think it is just xor operator on the bits. Let me...
Python program to convert wildcard mask to netmask
I need help with writing a python program to achieve this task. I am trying to convert wildcard mask to netmask. Input: 192.168.0.1 0.0.0.15 Expected output: 192.168.0.1 255.255.255.240
[ "What have you tried? I think it is just xor operator on the bits. Let me know if I'm correct please.\n\n\nmy inputs: 192.168.0.1 0.0.0.15\r\n\r\nexpected output: 192.168.0.1 255.255.255.240\r\n\r\n\r\nip, wcmask = input.split()\r\nnetmask='.'.join([str(255^int(i)) for i in wcmask.split('.')])\r\nreturn '{} {}'.for...
[ 2, 0, 0 ]
[]
[]
[ "python", "python_2.7", "python_3.x", "python_requests", "scripting" ]
stackoverflow_0051773707_python_python_2.7_python_3.x_python_requests_scripting.txt
Q: Computing Arctan2 with 1 argument in Pandas DataFrame I have a DF whereby I need to compute the arctan of two north/south wind components. However, it seems that the arctan2 function only takes 2 arguments x,y such according to the documentation: numpy.arctan2(x1, x2, /, out=None, *, where=True, casting='same_kind...
Computing Arctan2 with 1 argument in Pandas DataFrame
I have a DF whereby I need to compute the arctan of two north/south wind components. However, it seems that the arctan2 function only takes 2 arguments x,y such according to the documentation: numpy.arctan2(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) ...
[ "The function that takes 1 argument is called np.arctan. But I am not sure you really need it.\nnp.arctan(-100.812/126.002)\n# -0.6747912684731013\nnp.arctan2(-100.812, 126.002)\n# -0.6747912684731013\n\nSo, you see... why would you want to do the division yourself, rather than letting np.arctan2 do it?\nPlus, np.a...
[ 1, 0 ]
[]
[]
[ "math", "pandas", "python", "trigonometry" ]
stackoverflow_0074289691_math_pandas_python_trigonometry.txt
Q: Tkinter integrated with sockets not working! Python, Sockets, Tkinter, threading I am having this problem, I have a socket server in which I am receiving some info sent by a client, in this part of my implementation I want to display(with Label, tkinter) the info I have just received from the client by clicking on...
Tkinter integrated with sockets not working! Python, Sockets, Tkinter, threading
I am having this problem, I have a socket server in which I am receiving some info sent by a client, in this part of my implementation I want to display(with Label, tkinter) the info I have just received from the client by clicking on myButton(Tkinter button), but, when I clicked on myButton the tkinter GUI gets frozen...
[ "You should try running your server's myClick() function in a separate thread so as not to block tkinter\n# some code has been omitted for brevity\nfrom threading import Thread\n\n\ndef myClick():\n communication_socket, address = server.accept()\n while True:\n counter=communication_socket.recv(1024)\...
[ 0 ]
[]
[]
[ "multithreading", "python", "sockets", "tkinter" ]
stackoverflow_0074285920_multithreading_python_sockets_tkinter.txt
Q: How to unify all the "-" signs? I have a simple program that takes data from the user. Here is an abbreviated version of it: a = "0-1" b = "0‑1" print(a in b) # prints False Problem: ord('-') for a = 45 ord('‑') for b = 8209 How can I make sure that the "-" sign is always the same and checking a in b returns...
How to unify all the "-" signs?
I have a simple program that takes data from the user. Here is an abbreviated version of it: a = "0-1" b = "0‑1" print(a in b) # prints False Problem: ord('-') for a = 45 ord('‑') for b = 8209 How can I make sure that the "-" sign is always the same and checking a in b returns True?
[ "It's not clear if your example is part of a more general, but for the example provided you can handle this using replace:\na = \"0-1\"\nb = \"0‑1\"\n\nprint(a.replace(\"‑\", \"-\") in b.replace(\"‑\", \"-\")) # True\n\nI've called replace on both sides, because it's not clear which side is your input and which is...
[ 3, 3 ]
[]
[]
[ "python" ]
stackoverflow_0074289796_python.txt
Q: list index out of range for knapsack problem without repetition Problem introduction: You are given a set of bars of gold and your goal is to take as much gold as possible into your bag. There is just one copy of each bar and for each bar you can either take it or not (hence you cannot take a fraction of a bar). ...
list index out of range for knapsack problem without repetition
Problem introduction: You are given a set of bars of gold and your goal is to take as much gold as possible into your bag. There is just one copy of each bar and for each bar you can either take it or not (hence you cannot take a fraction of a bar). Problem Description: Task. Given gold bars, find the maximum weigh...
[ "The only possible cause in my opinion is this statement:\nv = w[i-1] + value[i-1][j-w[i-1]]\n\nThere aren't any constraints which dictate that j-w[i-1] will be a valid index. Just replace it with\nif j-w[i-1] >= 0:\n v = w[i-1] + value[i-1][j-w[i-1]]\n\n", "I found the same question as you.But now I figure it...
[ 1, 0 ]
[]
[]
[ "algorithm", "arrays", "dynamic_programming", "knapsack_problem", "python" ]
stackoverflow_0072195640_algorithm_arrays_dynamic_programming_knapsack_problem_python.txt
Q: How do I embed a Bokeh Interactive Plot in a Flask application? I am currently trying to create a very simple app that displays a recipe and a network diagram. I have gotten most of the way there, but I am receiving the following error: Uncaught ReferenceError: Bokeh is not defined at HTMLDocument.fn (?description...
How do I embed a Bokeh Interactive Plot in a Flask application?
I am currently trying to create a very simple app that displays a recipe and a network diagram. I have gotten most of the way there, but I am receiving the following error: Uncaught ReferenceError: Bokeh is not defined at HTMLDocument.fn (?description=blueberry+pancakes:29:5) I have tried implementing the solutions at ...
[ "You are already passing the div with the plot,\nbut cannot tell how, try using bokeh.plotting.Figure and bokeh.embed.components;\nimport bokeh\n# ...\nempty_boxplot = bokeh.plotting.Figure(\n plot_width=500,\n plot_height=450\n )\nscript, div = bokeh.embed.components(empty_boxplot)\n\n...
[ 0, 0 ]
[]
[]
[ "bokeh", "flask", "python" ]
stackoverflow_0074286136_bokeh_flask_python.txt