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: ZODB broken instance I am trying to persist an object reference using only ZODB in a FileStorage database. I made a test to analyze its performance, but the object when it is loaded it appears to be broken. The test consists on: create an object in one script and write it to database. In another script read that ...
ZODB broken instance
I am trying to persist an object reference using only ZODB in a FileStorage database. I made a test to analyze its performance, but the object when it is loaded it appears to be broken. The test consists on: create an object in one script and write it to database. In another script read that object from the same datab...
[ "I think that the problem you see is because zodb2.py has no knowledge of the Instrument class defined in zodb1.py.\nI guess that if you moved your class to a separate module and imported it in both zodb1 and zodb2, you would not see a broken object.\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x", "zodb" ]
stackoverflow_0072899290_python_python_3.x_zodb.txt
Q: Getting App Performance Data from Appium in iOS Im curious if there is any way to get app performance data during an appium iOS test? I understand that if I were using appium testing an android app, I would be able to get app performance. Appium does not support the iOS version of this. I've tried running my tests...
Getting App Performance Data from Appium in iOS
Im curious if there is any way to get app performance data during an appium iOS test? I understand that if I were using appium testing an android app, I would be able to get app performance. Appium does not support the iOS version of this. I've tried running my tests with an xctrace recording, which works, but not well...
[ "There are several options you can go with. All up to the point where you have automated frameworks including time-series tools for trend analysis.\nDisclaimer: I have no experience with profiling and XCode - my understandig is that this is more towards unit-testing rather than UI-testing/user experience level\nOpt...
[ 1 ]
[]
[]
[ "appium", "ios", "python", "selenium", "xcrun" ]
stackoverflow_0074297518_appium_ios_python_selenium_xcrun.txt
Q: Automatically generate list for @pytest.mark.parametrize? I am writing a test, using @pytest.mark.parametrize. The test looks like this: @pytest.mark.parametrize( "device_type,first_command,second_command", [ pytest.param( <device_type>, <first_command>, <second_...
Automatically generate list for @pytest.mark.parametrize?
I am writing a test, using @pytest.mark.parametrize. The test looks like this: @pytest.mark.parametrize( "device_type,first_command,second_command", [ pytest.param( <device_type>, <first_command>, <second_command>, id=str(<first_command>) + "," + str(<seco...
[ "This can be achived by creating a method for generating the test cases and call it in the @pytest.mark.parametrize decorator.\nfrom typing import List\n\nimport pytest\n\n\ndevice_types = ['cpu', 'gpu']\nfirst_commands = ['ls', 'pwd']\nsecond_commands = ['ls', 'pwd']\n\n\ndef generate_test_cases() -> List[pytest.p...
[ 1, 1, 0 ]
[]
[]
[ "parametrized_testing", "pytest", "python" ]
stackoverflow_0074422305_parametrized_testing_pytest_python.txt
Q: Is there any way match two different csv files with similar columns in python? I am a beginner in numpy and I have two csv files that look like this: csv1: ID item_size Cost 0010 4.4 0010 5.5 0012 8 0012 10.1 csv2: ID item_size Cost 0010 6.1 5 0010 7.2 2 0010 5.3 1 0010 3.1 3 0010 4.7 2 0012 7.6 5 00...
Is there any way match two different csv files with similar columns in python?
I am a beginner in numpy and I have two csv files that look like this: csv1: ID item_size Cost 0010 4.4 0010 5.5 0012 8 0012 10.1 csv2: ID item_size Cost 0010 6.1 5 0010 7.2 2 0010 5.3 1 0010 3.1 3 0010 4.7 2 0012 7.6 5 0012 22 4 0012 13.1 2 0012 9.2 3 0012 11.1 3 The...
[ "You can use a merge_asof:\n# save the index to restore it later\n# sort the data for the merge_asof (required)\n(pd.merge_asof(df1.reset_index().sort_values(by='item_size').drop(columns='Cost'),\n df2.sort_values(by='item_size'),\n by='ID', on='item_size', direction='nearest'\n ...
[ 1 ]
[]
[]
[ "csv", "numpy", "pandas", "python" ]
stackoverflow_0074434601_csv_numpy_pandas_python.txt
Q: I can't run even simple code of python in my PyCharm IDE. Do need support Screenshot of which when i tried to create a new project2I can't run my python files with pycharm. It says "Error running 'main': Cannot run program "C:\Users\pbrah\AppData\Local\Microsoft\WindowsApps\python3.10.exe" (in directory "C:\Users\...
I can't run even simple code of python in my PyCharm IDE. Do need support
Screenshot of which when i tried to create a new project2I can't run my python files with pycharm. It says "Error running 'main': Cannot run program "C:\Users\pbrah\AppData\Local\Microsoft\WindowsApps\python3.10.exe" (in directory "C:\Users\pbrah\PycharmProjects\pythonProject9"): CreateProcess error=1920, The file cann...
[ "First of all, you should make sure that Python is properly installed in you system.\nIn CommandPrompt or PowerShell:\npython -V\n\nwill print your python version, and if the command is working, means that your system can find Python.\nThen, get into PyCharm:\n\nOpen Settings: File > Settings (or just ctrl + alt +...
[ 0 ]
[]
[]
[ "django", "pycharm", "python", "python_3.x" ]
stackoverflow_0074434441_django_pycharm_python_python_3.x.txt
Q: Twitter Scraper newbie Okay, I am new to coding so please bear with me. I appreciate all the help. I want to create my own Twitter Scraper using Edge as my browser. My fist problem is that some words arent coloured. For example .webdriver.common.keys should be blue like in the video. (I put a link to the video in ...
Twitter Scraper newbie
Okay, I am new to coding so please bear with me. I appreciate all the help. I want to create my own Twitter Scraper using Edge as my browser. My fist problem is that some words arent coloured. For example .webdriver.common.keys should be blue like in the video. (I put a link to the video in the file at the bottom I was...
[ "All the methods like find_element_by_name, find_element_by_xpath, find_element_by_id etc. are deprecated now.\nYou should use find_element(By. instead.\nSo, instead of\nusername = driver.find_element_by_xpath('//input[@name=\"text\"]')\n\nit should be now\nusername = driver.find_element(By.XPATH, '//input[@name=\"...
[ 0, 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver", "web_scraping" ]
stackoverflow_0074434603_python_selenium_selenium_webdriver_web_scraping.txt
Q: instagram graph api posting carousel error Trying to upload a carousel post to instagram. using this official guide. it consists of 3 steps, but i can't seem to get through the second step. def carouselcontainer(item_ids,caption): #Post the Image post_url = 'https://graph.facebook.com/v15.0/{}/media'.format(ac...
instagram graph api posting carousel error
Trying to upload a carousel post to instagram. using this official guide. it consists of 3 steps, but i can't seem to get through the second step. def carouselcontainer(item_ids,caption): #Post the Image post_url = 'https://graph.facebook.com/v15.0/{}/media'.format(account_id) payload = { 'caption' : ca...
[ "Hi your code looks perfect. Just need to change\nr = requests. Post(post_url, data=payload)\n\nto\nr = requests.Post(post_url, json=payload)\n\nsince you are passing as data so instead of arrays it was going single element of arrays thats why getting that error\n" ]
[ 0 ]
[]
[]
[ "instagram_api", "python" ]
stackoverflow_0074163557_instagram_api_python.txt
Q: loading data in GPU before starting training in Google Colab I am using a subset of the PlantVillage (image) dataset on my Google drive and trying to train CNN models on that data from Google Colab (and of course, I use GPU). The problem is, the first epoch of training goes very slowly because the data is being lo...
loading data in GPU before starting training in Google Colab
I am using a subset of the PlantVillage (image) dataset on my Google drive and trying to train CNN models on that data from Google Colab (and of course, I use GPU). The problem is, the first epoch of training goes very slowly because the data is being loaded into the GPU for the first time. the later rounds move much f...
[ "You can use Dataset.cache() and Dataset.prefetch() which will keep the data in memory after loading from disk and will increase the model training speed comparatively.\nCheck the below code:\nAUTOTUNE = tf.data.AUTOTUNE\n\ntrain_ds = train_ds.cache().prefetch(buffer_size=AUTOTUNE)\nval_ds = val_ds.cache().prefetch...
[ 1 ]
[]
[]
[ "dataset", "keras", "python", "tensorflow" ]
stackoverflow_0074315137_dataset_keras_python_tensorflow.txt
Q: Regex to find comments with a word inside them I have the next regex: comment_pattern = "(/\*[\w\W]*\*/)" With it I am able to search match strings like bellow: /* blablabla example blabla */ Basically I would also like to search in those comments for the variable Compiler_Warning -> in case its inside a multil...
Regex to find comments with a word inside them
I have the next regex: comment_pattern = "(/\*[\w\W]*\*/)" With it I am able to search match strings like bellow: /* blablabla example blabla */ Basically I would also like to search in those comments for the variable Compiler_Warning -> in case its inside a multiline comment to get all the expression-> Can some one...
[ "Try (regex demo):\nimport re\n\ntext = \"\"\"\\\n/*\nblablabla example \nblabla\n*/\n\nNot comment\n\n/* blabla\nCompiler_Warning blablalba\n*/\"\"\"\n\npat = re.compile(r\"/\\*(?=(?:(?!\\*/).)*?Compiler_Warning).*?\\*/\", flags=re.S)\n\nfor comment in pat.findall(text):\n print(comment)\n\nPrints:\n/* blabla\n...
[ 3, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0074433786_python_regex.txt
Q: How to set the background color of the entire sheet? I want to set the same background color and the cell border color for the whole worksheet. I could not find a solution anywhere that applies to the whole sheet. A: As @Gino Mempin states, Openpyxl works with cells so you would need to set the background for al...
How to set the background color of the entire sheet?
I want to set the same background color and the cell border color for the whole worksheet. I could not find a solution anywhere that applies to the whole sheet.
[ "As @Gino Mempin states, Openpyxl works with cells so you would need to set the background for all cells in the sheet. You may then prefer to then just change a range of cells rather than the whole sheet.\nIt may be best to use iter_rows for memory use.\nThe example fills 1000 rows and columns. The max size of a sh...
[ 0, 0 ]
[]
[]
[ "openpyxl", "python", "python_3.x" ]
stackoverflow_0073759729_openpyxl_python_python_3.x.txt
Q: How to import data into specific column of an existing dataset and save as new dataset? As i continue my project on python web scraping to excel, I manage to extract the information I wanted and put it in a fresh excel file. For the next step, instead of generating on a new sheet, I would like to put each of my d...
How to import data into specific column of an existing dataset and save as new dataset?
As i continue my project on python web scraping to excel, I manage to extract the information I wanted and put it in a fresh excel file. For the next step, instead of generating on a new sheet, I would like to put each of my data lists into a different column of an existing dataset. Here's my code for the first step o...
[ "Instead of using .insert, you can try with .loc :\nexample = pd.DataFrame({0: [1, 2, 3],\n 2: [\"a\", \"b\", \"c\"]})\n\nservice_tag_list = [\"ab\", \"cd\", \"ef\"]\nexample.loc[:, 'service_tag'] = service_tag_list\nprint(example)\n\n0 2 service_tag\n0 1 a ab\n1 2 b cd...
[ 0 ]
[]
[]
[ "excel", "openpyxl", "pandas", "python", "selenium" ]
stackoverflow_0074434767_excel_openpyxl_pandas_python_selenium.txt
Q: How to fix the datetime in python? I am getting an error message that says time data 2017-01-02 13:42:05.378582 does not match format %y-%m-%d %H:%M:%S.%f start_time = datetime.datetime.strptime(df['timestamp'].min(),'%y-%m-%d %H:%M:%S.%f') end_time = datetime.datetime.strptime(df['timestamp'].max(),'%y-%m-%d %H:%...
How to fix the datetime in python?
I am getting an error message that says time data 2017-01-02 13:42:05.378582 does not match format %y-%m-%d %H:%M:%S.%f start_time = datetime.datetime.strptime(df['timestamp'].min(),'%y-%m-%d %H:%M:%S.%f') end_time = datetime.datetime.strptime(df['timestamp'].max(),'%y-%m-%d %H:%M:%S.%f') data_duration = (end_time - st...
[ "%y is year without century as a zero-padded decimal number (17)\n%Y is year with century as a decimal number (2017)\nYou need: '%Y-%m-%d %H:%M:%S.%f'\n" ]
[ 1 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0074434896_datetime_python.txt
Q: How is UltimateListTextCtrl in wxPython used I'm trying to create a list control which should contain check boxes, list boxes and text entry fields. The way to go seems to be wx.lib.agw.ultimatelistctrl.UltimateListCtrl The check boxes and list boxes are straight forward enough, but in order to create a text entry...
How is UltimateListTextCtrl in wxPython used
I'm trying to create a list control which should contain check boxes, list boxes and text entry fields. The way to go seems to be wx.lib.agw.ultimatelistctrl.UltimateListCtrl The check boxes and list boxes are straight forward enough, but in order to create a text entry field i gather that i need to use UltimateListTex...
[ "Solved, sort of.\nNo need to use UltimateListTextCtrl, a normal wx.TextCtrl works fine. Something like this:\n index = self.ultimateList.InsertStringItem(sys.maxsize, \"Item\")\n textctrl = wx.TextCtrl(self.ultimateList, -1, \"default\")\n self.ultimateList.SetItemWindow(index, 1, textctrl, expand=True)\n...
[ 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0074416791_python_wxpython.txt
Q: How to debug patched method with unittest.mock I have the following (simplified) FBV: def check_existing_contacts(request): if request.is_ajax and request.method == "GET": print('Function called') return mailgun_validate_email(request) return JsonResponse({"error": "Incorrect AJAX / GET req...
How to debug patched method with unittest.mock
I have the following (simplified) FBV: def check_existing_contacts(request): if request.is_ajax and request.method == "GET": print('Function called') return mailgun_validate_email(request) return JsonResponse({"error": "Incorrect AJAX / GET request."}, status=400) I want to test that the mailgu...
[ "\nIf you did from myapp import mailgun_validate_email for check_existing_contacts, then you need to patch the reference in that module instead of myapp.\nE.g. if the import is in myapp/views.py, then patch myapp.views.mailgun_validate_email.\nThe view needs to return an instance of HttpResponse or one of its subcl...
[ 5 ]
[]
[]
[ "django", "django_testing", "python", "python_mock", "python_unittest" ]
stackoverflow_0063073501_django_django_testing_python_python_mock_python_unittest.txt
Q: How to import data from a url to pandas dataframe? I'm trying to import data from the following url into pandas dataframe: https://www.asx.com.au/data/shortsell.txt I tried the following: url = 'https://www.asx.com.au/data/shortsell.txt' reader = pd.read_table(url, sep='\t', skiprows=lambda x:...
How to import data from a url to pandas dataframe?
I'm trying to import data from the following url into pandas dataframe: https://www.asx.com.au/data/shortsell.txt I tried the following: url = 'https://www.asx.com.au/data/shortsell.txt' reader = pd.read_table(url, sep='\t', skiprows=lambda x: x in [0, 1, 2, 3, 4, 5, 6, 7], header=None, names=[ ...
[ "try pd.read_fwf()\ni.e. reader = pd.read_fwf(url, sep='\\t',\nskiprows=8, header=None, names=[\n'ASX', 'Company Name', 'Product/', 'Reported Gross', 'Issued', '% of issued capital'])\n" ]
[ 1 ]
[]
[]
[ "pandas", "python", "url" ]
stackoverflow_0074434897_pandas_python_url.txt
Q: Python get output of a multiprocess subprocess I have a Python function that runs a given terminal command. If the command takes more than 20 seconds, it terminates. It uses subprocess.getoutput to run the command, and multiprocessing.Process to define a timeout and terminate it if needed. def run_command_with_tim...
Python get output of a multiprocess subprocess
I have a Python function that runs a given terminal command. If the command takes more than 20 seconds, it terminates. It uses subprocess.getoutput to run the command, and multiprocessing.Process to define a timeout and terminate it if needed. def run_command_with_timeout(command_to_run): timeout = 20 mp = mult...
[ "Append to a list within the function and return the list.\n" ]
[ 0 ]
[]
[]
[ "python", "python_multiprocessing", "subprocess" ]
stackoverflow_0074434975_python_python_multiprocessing_subprocess.txt
Q: How to transfer the following Java methods to Python def() public static double readNumber(String prompt,double min, double max){ Scanner scanner = new Scanner(System.in); double value; while (true){ System.out.print(prompt); value = scanner.nextFloat(); if (value >= min && val...
How to transfer the following Java methods to Python def()
public static double readNumber(String prompt,double min, double max){ Scanner scanner = new Scanner(System.in); double value; while (true){ System.out.print(prompt); value = scanner.nextFloat(); if (value >= min && value <= max) { break; } else Syste...
[ "You have the break in the wrong case. in the java method you break when the value is > minimum and < than maximum, but in the python code you break the loop in the other case\n", "For me it works perfectly fine. To use the function just put it somewhere and make sure to make the prompt a string like for example ...
[ 1, 0, 0 ]
[]
[]
[ "java", "python" ]
stackoverflow_0074434557_java_python.txt
Q: TensorFlow Stopped Working | Update Needed (?) Updated to Python 11.0, and Tensorflow stopped working when running import tensorflow on all my programs. I looked for other solutions online and none of them worked. After doing some research, I noticed TF seems to only work for Python 10.0+ apparently? However, sho...
TensorFlow Stopped Working | Update Needed (?)
Updated to Python 11.0, and Tensorflow stopped working when running import tensorflow on all my programs. I looked for other solutions online and none of them worked. After doing some research, I noticed TF seems to only work for Python 10.0+ apparently? However, shouldn't that mean it should still work, somewhat, wit...
[ "According to pyreadiness, Tensorflow has not released a build for Python 3.11.\nhttps://pyreadiness.org/3.11/\nIf you want, you may be able to build Tensorflow from source: https://www.tensorflow.org/install/source\n" ]
[ 1 ]
[]
[]
[ "importerror", "python", "python_import", "tensorflow", "visual_studio_code" ]
stackoverflow_0074434563_importerror_python_python_import_tensorflow_visual_studio_code.txt
Q: I would like to do a loop through every row of a multi-index table and only show columns that are not blank in that particular row I would like to do a loop through every row of a multi-index table and only show columns that are not blank in that particular row. The idea is to produce a list of changes for each em...
I would like to do a loop through every row of a multi-index table and only show columns that are not blank in that particular row
I would like to do a loop through every row of a multi-index table and only show columns that are not blank in that particular row. The idea is to produce a list of changes for each employee that I can cross reference against the list of changes sent by HR. If the column shows nothing, nothing has changed between last ...
[ "I do agree with the commenter itprorh66\n# only Salary is different... make a df for only salary\ndf_sal = df[df['Salary (diff)'].notna()]\n# only Pension is different... make a df for only Pension\ndf_pen = df[df['Pension (diff)'].notna()]\n# both are different\ndf_both = df.dropna(axis=0, how='any')\nprint(df_sa...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074434607_pandas_python.txt
Q: split character into small set of character list split dataframe character into small set of character list in dataframe? This is a dataframe, I need to split into as 10 10 character in a list of dataframe. | contact_num | | -------------------------------| | 01111784885788634878 | | ...
split character into small set of character list
split dataframe character into small set of character list in dataframe? This is a dataframe, I need to split into as 10 10 character in a list of dataframe. | contact_num | | -------------------------------| | 01111784885788634878 | | 247782788869775178889785427889 | | not available ...
[ "Try:\nmask = df[\"contact_num\"].str.contains(r\"^\\d{10,}$\", regex=True)\n\ndf.loc[mask, \"contact_num\"] = df.loc[mask, \"contact_num\"].str.findall(r\"\\d{10}\")\nprint(df)\n\nPrints:\n contact_num\n0 [0111178488, 5788634878]\n1 [2477827888, 6977517888, 9785427889]\n2 ...
[ 1, 1 ]
[]
[]
[ "dataframe", "list", "pandas", "python", "split" ]
stackoverflow_0074434927_dataframe_list_pandas_python_split.txt
Q: PyCharm does not recognize the interpreter it just created Problem Statement My PyCharm project does not recognize any Virtualenv project interpreter, including ones it successfully creates. Steps Taken to Produce Error I opened PyCharm to the Welcome to PyCharm window. I clicked Get from Version Control. I clon...
PyCharm does not recognize the interpreter it just created
Problem Statement My PyCharm project does not recognize any Virtualenv project interpreter, including ones it successfully creates. Steps Taken to Produce Error I opened PyCharm to the Welcome to PyCharm window. I clicked Get from Version Control. I cloned a private repo from my GitHub into my local system. I confirm...
[ "The solution suggested in this answer to a related question—where the error message \"Please specify a different SDK name\" is being raised—about PyCharm interpreters may be what you are looking for.\nI also had an issue with interpreters not loading, and it turned out to be an underlying conflict, which PyCharm w...
[ 0 ]
[]
[]
[ "pycharm", "python", "virtualenv" ]
stackoverflow_0065909088_pycharm_python_virtualenv.txt
Q: Why does else function run even the elif statement is true? I'm working on a take home exam and I completed it but only for one sample test it doesn't work. Here is my code: h = 'abcdefgh' v = '12345678' h_knight = (input('Please enter horizontal position of the knight (a,b,c,d,e,f,g,h): ')).lower() if len(h_knigh...
Why does else function run even the elif statement is true?
I'm working on a take home exam and I completed it but only for one sample test it doesn't work. Here is my code: h = 'abcdefgh' v = '12345678' h_knight = (input('Please enter horizontal position of the knight (a,b,c,d,e,f,g,h): ')).lower() if len(h_knight) != 1 or h_knight.isalpha() is False: print('Horizontal input...
[ "You never check if the bishops postition is in v\nThis\nelif v_bishop.isdigit() == True and v_knight not in v:\n print('Vertical input for bishop is not a proper number')\n\nShould be this:\nelif v_bishop.isdigit() == True and v_bishop not in v:\n print('Vertical input for bishop is n...
[ 0 ]
[]
[]
[ "if_statement", "python", "python_3.x" ]
stackoverflow_0074434971_if_statement_python_python_3.x.txt
Q: SELENIUM PYTHON: How to pass automatic security validation? I am trying to get in this website: "https://core.cro.ie/". I can get in using normal web search, but I can't get in using selenium. My code looks like this: site= "https://core.cro.ie/" driver = webdriver.Edge(service=Service(EdgeChromiumDriverManager()...
SELENIUM PYTHON: How to pass automatic security validation?
I am trying to get in this website: "https://core.cro.ie/". I can get in using normal web search, but I can't get in using selenium. My code looks like this: site= "https://core.cro.ie/" driver = webdriver.Edge(service=Service(EdgeChromiumDriverManager().install())) driver.get(site) driver.maximize_window() Any idea...
[ "This code works fine for navigation ( I dont have Edge browser):\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\n\nsite= \"https://core.cro.ie/\"\n\ndriver = webdriver.Firefox()\ndriver.get(site)\ndriver.maximize_window() \n\nI have ins...
[ 0 ]
[]
[]
[ "python", "selenium", "selenium4", "selenium_webdriver" ]
stackoverflow_0074434919_python_selenium_selenium4_selenium_webdriver.txt
Q: Python Script to run a basic scan throws print error I am familiar with python although it's been years since I've used it since I have taken more senior roles where my scripting skills have diminished from non-use. I have received the following error and supplied the code in use below. Grateful for any insight sh...
Python Script to run a basic scan throws print error
I am familiar with python although it's been years since I've used it since I have taken more senior roles where my scripting skills have diminished from non-use. I have received the following error and supplied the code in use below. Grateful for any insight shared. ./portscan1.py File "/home/kali/pythonprograms/scann...
[ "You must add parenthesis like this (for python 3):\nprint(\"Port %d is opened\" % (port))\n\nOr you can try this:\nprint(\"Port {} is opened\".format(port))\n\nOr you can also try f string:\nprint(f\"Port {port} is opened\")\n\n" ]
[ 1 ]
[]
[]
[ "nmap", "python" ]
stackoverflow_0074435100_nmap_python.txt
Q: How to visualize a Tensorflow Model from its summary? I am working with a custom Tensorflow model (not a Keras object) with a mostly unknown structure, and I printed the summary with this (taken from Is there an easy way to get something like Keras model.summary in Tensorflow?): def model_summary(): model_vars...
How to visualize a Tensorflow Model from its summary?
I am working with a custom Tensorflow model (not a Keras object) with a mostly unknown structure, and I printed the summary with this (taken from Is there an easy way to get something like Keras model.summary in Tensorflow?): def model_summary(): model_vars = tf.trainable_variables() slim.model_analyzer.analyze...
[ "This diagram was most likely made by a human.\nLabels like \"copy and crop\" are not typically derived from your raw model, maybe you could train a model for it ;D\nThere are many frameworks which can visualize your Tensorflow Model, Tensorflow has it's own suite Tensorboard.\nSee this example:\n\nIf you want anyt...
[ 1 ]
[]
[]
[ "modelsummary", "python", "tensorflow" ]
stackoverflow_0074434928_modelsummary_python_tensorflow.txt
Q: How to a Python custom function to raised value with inner function This is the current code, tried to print but it return None..can some1 enlightened me how to do it? def calculate(Amount1, Amount2): def inner(square,cube): square=Amount1**2 cube=Amount2**3 return (inner(Amount1,Amount2)) p...
How to a Python custom function to raised value with inner function
This is the current code, tried to print but it return None..can some1 enlightened me how to do it? def calculate(Amount1, Amount2): def inner(square,cube): square=Amount1**2 cube=Amount2**3 return (inner(Amount1,Amount2)) print(calculate(2,4)) Expected result (4,64)
[ "def calculate(Amount1, Amount2):\ndef inner(square,cube):\n square=Amount1**2\n cube=Amount2**3\n return((square, cube))\nreturn (inner(Amount1,Amount2))\n\nprint(calculate(2,4))\nyou forgot to return the values from your inner function\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074434961_python.txt
Q: How to check if a classifier belongs to sklearn.tree? Suppose, I have a trained model, and I would like to check whether the model is a tree-based classifier. What is the best way to determine it? e.g. I'm looking for something following: import sklearn from imaginarypackage import listmodules if type(clf).__name_...
How to check if a classifier belongs to sklearn.tree?
Suppose, I have a trained model, and I would like to check whether the model is a tree-based classifier. What is the best way to determine it? e.g. I'm looking for something following: import sklearn from imaginarypackage import listmodules if type(clf).__name__ in listmodules(sklearn.tree) I have tried: >>> import pk...
[ "Check type of tree model\nAs @Alexander Santos suggests, you can use the method from this answer to check which module your class belongs to. As far as I can tell, the tree based models are either a part of sklearn.tree or sklearn.ensemble._tree modules.\n# Method 1: check if object type has __module__ attribute\n...
[ 1 ]
[]
[]
[ "python", "scikit_learn" ]
stackoverflow_0074434505_python_scikit_learn.txt
Q: How to separate column in dataframe pandas I have DataFrame containing values about shops and categories in one column. Date Spent ... Category/Shop 2022-08-04 126.98 ... Supermarkets 2022-08-04 NaN ... ShopName 2022-08-04 119.70 ... Supermarkets 2022-08-04 NaN ... ShopName ... I need to separate last column...
How to separate column in dataframe pandas
I have DataFrame containing values about shops and categories in one column. Date Spent ... Category/Shop 2022-08-04 126.98 ... Supermarkets 2022-08-04 NaN ... ShopName 2022-08-04 119.70 ... Supermarkets 2022-08-04 NaN ... ShopName ... I need to separate last column into to columns: Date Spent ......
[ "Based on the sample and expecting future similar behavior I would do it with groupby\ndf = df.fillna(method='ffill').groupby(['Date','Spent'])['Category/Shop'].apply(list).reset_index()\ndf['Category'],df['Shop'] = df['Category/Shop'].str[0],df['Category/Shop'].str[1]\ndf = df.drop(columns='Category/Shop')\n\nOutp...
[ 3, 0, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0073288227_pandas_python.txt
Q: How to play audio in Jupyter notebook with VSCode? Using a jupyter notebook in VSCode, I'm trying to run the following code from this documentation: import numpy as np from IPython.display import Audio framerate = 44100 t = np.linspace(0,5,framerate*5) data = np.sin(2*np.pi*220*t) + np.sin(2*np.pi*224*t) Audio(dat...
How to play audio in Jupyter notebook with VSCode?
Using a jupyter notebook in VSCode, I'm trying to run the following code from this documentation: import numpy as np from IPython.display import Audio framerate = 44100 t = np.linspace(0,5,framerate*5) data = np.sin(2*np.pi*220*t) + np.sin(2*np.pi*224*t) Audio(data, rate=framerate) However, I only get this If I press...
[ "As of today, it seems VSCode Jupyter extension does not support audio. You can track the issue here on their Github.\nOne solution can be merging this pull request and rebuilding VSCode, which is not suggested.\nThe preferred alternate solution is using jupyter lab instead of VSCode for such use cases.\n", "As o...
[ 3, 0 ]
[]
[]
[ "audio", "jupyter_notebook", "python", "visual_studio_code" ]
stackoverflow_0071366566_audio_jupyter_notebook_python_visual_studio_code.txt
Q: Know what is happening inside functios or methods I've been working with Python for a while, but now I got curious if there is a way to see the code inside the built-in functions or methods of Python. I know that is not really necessary to know this, but some time I'm a curious person. Thanks for your help. A: P...
Know what is happening inside functios or methods
I've been working with Python for a while, but now I got curious if there is a way to see the code inside the built-in functions or methods of Python. I know that is not really necessary to know this, but some time I'm a curious person. Thanks for your help.
[ "Python is a open-source language. You can find the whole source code from github.\n", "All of the cPython source code is publicly available here. There is a book on the way it all works by Anthony Shaw. Details here\n" ]
[ 0, 0 ]
[]
[]
[ "built_in", "python" ]
stackoverflow_0074435161_built_in_python.txt
Q: Why are there different outputs for 'while' loop depending on postion of 'print' statement? I am new to Python and I encountered this problem using while loops. Depending on where the print statement is located (after 'while' or at end of loop) I get 2 different outputs. # 'While' loop example with 'print' after '...
Why are there different outputs for 'while' loop depending on postion of 'print' statement?
I am new to Python and I encountered this problem using while loops. Depending on where the print statement is located (after 'while' or at end of loop) I get 2 different outputs. # 'While' loop example with 'print' after 'while' statement i = 2 x = 10 while i < x: # Perform loop until this condition no longer true: i ...
[ "Try to reproduce it by yourself, with a pencil on a blank paper. \nFirst case: \n\nAt first i is equal to 2, so print(i) will print 2, then increment it by 2, now i is equal to 4\nThen printing i will print 4, then you add 2, so now i is equal to 6...\nWhen i = i+2 changes the value of i to 10, at the next iterati...
[ 1 ]
[]
[]
[ "python", "while_loop" ]
stackoverflow_0074434870_python_while_loop.txt
Q: Django/React CSRF Failed: Origin checking failed - http://localhost:8000/ does not match any trusted origins I am building a web application using Django for the backend, RestApi for information transfer, and ReactJs for the frontend. When I run a POST request, in which I send data from a form, I get an error: "CS...
Django/React CSRF Failed: Origin checking failed - http://localhost:8000/ does not match any trusted origins
I am building a web application using Django for the backend, RestApi for information transfer, and ReactJs for the frontend. When I run a POST request, in which I send data from a form, I get an error: "CSRF Failed: Origin checking failed - http://localhost:8000/ does not match any trusted origins."This means that Dja...
[ "It helped me to add the authentication_classes = [] variable to the body of the class. Now my ArticleList class looks like this:\nclass ArticleList(generics.GenericAPIView):\n authentication_classes = []\n def post(self, request, format=None):\n serializer = ArticleSerializer(data=request.data)\n ...
[ 0 ]
[]
[]
[ "django", "python", "reactjs", "rest" ]
stackoverflow_0074430567_django_python_reactjs_rest.txt
Q: Ray Tune scheduler hyperparam_mutations vs. param_space I am having a hard time understanding the need for what seems like two search space definitions in the same program flow. The tune.Tuner() object takes in a param_space argument, where we can set up the hyperparameter space to look into, however, it can also ...
Ray Tune scheduler hyperparam_mutations vs. param_space
I am having a hard time understanding the need for what seems like two search space definitions in the same program flow. The tune.Tuner() object takes in a param_space argument, where we can set up the hyperparameter space to look into, however, it can also take in a scheduler. As an example, I have a HuggingFace tran...
[ "This section in one of the PBT user guides touches on both questions.\n\nIn particular, the param_space is used to get the initial samples, and the hyperparam_mutations specifies the resample distributions (resampling being one of the possible mutation operations) and determines which parameters actually get mutat...
[ 1 ]
[]
[]
[ "huggingface_transformers", "python", "ray" ]
stackoverflow_0074408892_huggingface_transformers_python_ray.txt
Q: Invoke vs Argparse for multi-task scripts Invoke and Argparse are both python libraries for managing and executing python scripts. They both allow to deal with the case when the same script should be used in different ways (Argparse via add_subparsers, and Invoke via task). Eventually it comes down to just specify...
Invoke vs Argparse for multi-task scripts
Invoke and Argparse are both python libraries for managing and executing python scripts. They both allow to deal with the case when the same script should be used in different ways (Argparse via add_subparsers, and Invoke via task). Eventually it comes down to just specifying the name of a task and the task's specific ...
[ "One thing which immediately comes to my mind when thinking about Invoke vs Argparse is that the former makes it somewhat trivial to respond to program output.\nLet's suppose that you want to run a sudo command, then Invoke can capture the terminal output and set a rule for example to respond to the prompt with a p...
[ 0 ]
[]
[]
[ "argparse", "pyinvoke", "python" ]
stackoverflow_0032583877_argparse_pyinvoke_python.txt
Q: Motion Builder 2019 Python setting custom framerate for plot options I believe when setting plot options you set the fps using plot period with FBTime and an FBTimeMode. This seems to work for all preset time modes, but when setting to custom I can't figure out how to set the fps of the custom time mode. lOptions ...
Motion Builder 2019 Python setting custom framerate for plot options
I believe when setting plot options you set the fps using plot period with FBTime and an FBTimeMode. This seems to work for all preset time modes, but when setting to custom I can't figure out how to set the fps of the custom time mode. lOptions = FBPlotOptions () lOptions.PlotPeriod = FBTime(0,0,0,0,0,FBTimeMode.kFBTi...
[ "Couldn't figure out a nice way to do it, but I was able to use a popup window, enter desired settings and then print the plot period from the popup and found that the plot period I wanted was FBTime(588000).\nfrom pyfbsdk import *\n\nlPopup = FBPlotPopup()\nlPopup.Popup(\"Options\")\nlOptions = lPopup.GetPlotOptio...
[ 1 ]
[]
[]
[ "frame_rate", "motionbuilder", "python", "time" ]
stackoverflow_0074396096_frame_rate_motionbuilder_python_time.txt
Q: Why do I get "object has no attribute 'exclude'" error? Trying to get a one to many query with filters I get an error: def user_profile(request,pk): profileObj = Profile.objects.get(id = pk) topSkill = Profile.skill_set.exclude(description__isnull=True) otherSkill = Profile.skill_set(description = "") ...
Why do I get "object has no attribute 'exclude'" error?
Trying to get a one to many query with filters I get an error: def user_profile(request,pk): profileObj = Profile.objects.get(id = pk) topSkill = Profile.skill_set.exclude(description__isnull=True) otherSkill = Profile.skill_set(description = "") context = {"profile":profileObj,'topSkills':topSkills,"ot...
[ "I have following suggestions including one already stated by @AbdulAzizBarkat in the above comment:\n\nBetter to use get_object_or_404().\n\nDirectly exclude items from model rather than using reverse relations.\n\n\nSo the view should be:\nfrom django.shortcuts import get_object_or_404\n\ndef user_profile(request...
[ 0 ]
[]
[]
[ "django", "django_models", "django_queryset", "django_views", "python" ]
stackoverflow_0074434432_django_django_models_django_queryset_django_views_python.txt
Q: Webscraping: No any Data Shown in scrapy I am trying to crawl this website but I am getting empty response I am using scrapy and I tried printing xpath but I am getting empty array I though this was straight forward task but now I am unable to get data from the table. here is my code. import scrapy from scrapy imp...
Webscraping: No any Data Shown in scrapy
I am trying to crawl this website but I am getting empty response I am using scrapy and I tried printing xpath but I am getting empty array I though this was straight forward task but now I am unable to get data from the table. here is my code. import scrapy from scrapy import Request class ShareInfoSpider(scrapy.Spi...
[ "Implementation using Scrapy\nExample:\nfrom scrapy.crawler import CrawlerProcess\nimport scrapy\nimport json\nfrom bs4 import BeautifulSoup\nfrom urllib.parse import urlencode\n \nclass ShareSpider(scrapy.Spider):\n name = \"market\"\n \n custom_settings = {\n 'USER_AGENT' : 'Mozilla/5.0 (Windows NT...
[ 3, 1 ]
[]
[]
[ "beautifulsoup", "python", "scrapy", "web_scraping" ]
stackoverflow_0074434125_beautifulsoup_python_scrapy_web_scraping.txt
Q: Python: How to use methods from another file I am kind of a beginner in python and stuck with the part where I have to access methods from a class which reside in a different file. Here, in File1 i am trying to access find_method from file2 to and do some operation and return values. But somehow its not accessing ...
Python: How to use methods from another file
I am kind of a beginner in python and stuck with the part where I have to access methods from a class which reside in a different file. Here, in File1 i am trying to access find_method from file2 to and do some operation and return values. But somehow its not accessing "find_method" from file2. id_1.py (File1): from ba...
[ "You will need to import using from base_file import basefile. Make sure to use above import statement, your both files 1 & 2 are in same directory.\nIn base_file.py, check if for your given input satisfies the condition -\nif start < end and start < store_time < end or \\\n end < start and not (...
[ 1, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074434862_python_python_3.x.txt
Q: File download problem in chrome using ir.actions.act_url I have requirement to download uploaded binary files in one zip file. For this i have searched out and found like Download from Attachments files in zip format odoo 15 I have followed these steps and used res_field to fetch data from ir.attachment model. I h...
File download problem in chrome using ir.actions.act_url
I have requirement to download uploaded binary files in one zip file. For this i have searched out and found like Download from Attachments files in zip format odoo 15 I have followed these steps and used res_field to fetch data from ir.attachment model. I have successfully done the task.Its working on mozilla but not ...
[ "You should use browser's native download feature instead of Odoo action.\n<a href=\"/download_attachments\" download=\"Filename.zip\">Download</a>\nIn case you are not using Qweb Templates, and your need is to customize more server-side your link, use a computed field using widget=\"html\"\ndownload_btn = fields.C...
[ 0 ]
[]
[]
[ "odoo_14", "python" ]
stackoverflow_0074434828_odoo_14_python.txt
Q: How to get rid of superfluous x-axis date tick marks with pandas plot? Using pandas' plot method, I am trying to plot the columns in a pandas DataFrame whose index consists of dates with regular spacing except the last one. For some reason, superfluous tick marks appear on the x-axes of the plots. How can I get ri...
How to get rid of superfluous x-axis date tick marks with pandas plot?
Using pandas' plot method, I am trying to plot the columns in a pandas DataFrame whose index consists of dates with regular spacing except the last one. For some reason, superfluous tick marks appear on the x-axes of the plots. How can I get rid of these superfluous tick marks while continuing to use pandas' plot metho...
[ "Modify the for loop as\nfor ax in axes:\n ax.minorticks_off()\n for label in ax.xaxis.get_ticklabels():\n label.set_ha('center')\n\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "pandas", "python" ]
stackoverflow_0074435296_matplotlib_pandas_python.txt
Q: how can i find the most frequent character for each position in a file full of strings and return the highest frequent characters for each position I can't seem to understand the part where you have to do it for each position of the string and return the highest frequent character for example if i have like multip...
how can i find the most frequent character for each position in a file full of strings and return the highest frequent characters for each position
I can't seem to understand the part where you have to do it for each position of the string and return the highest frequent character for example if i have like multiple strings in the file:'house', 'garden', 'kitchen','balloon','home','park','affair','kite','hello','portrait','angel','surfing' and the return value sho...
[ "One line solution:\nimport itertools\nfrom statistics import mode\n\nwords = ['house', 'garden', 'kitchen', 'balloon', 'home', 'park', 'affair', 'kite', 'hello', 'portrait', 'angel', 'surfing']\n\nlist(map(lambda x: mode(sorted(filter(lambda v: v != None, x))), (itertools.zip_longest(*words))))\n\nIn a slightly mo...
[ 0 ]
[]
[]
[ "character", "python", "string" ]
stackoverflow_0074434414_character_python_string.txt
Q: Iterating over a file with re.search() and incrementing dictionary value with each match I am trying to iterate over a file that is written in multiple languages and each time I get a match for a sentence, I want to increment the value of the corresponding dictionary key. Each sentence has a language marker at the...
Iterating over a file with re.search() and incrementing dictionary value with each match
I am trying to iterate over a file that is written in multiple languages and each time I get a match for a sentence, I want to increment the value of the corresponding dictionary key. Each sentence has a language marker at the beginning (something like lang="de"). import re import sys lang_freq = {'de':0, 'fr':0, 'it...
[ "The re.search function returns a match object, and when you check for equality with if matches == 'lang=\"de\"':, you always get False.\nYou need to compare the match object group() property, or, better, just capture the data in between the double quotes, and then check if it is present in the lang_freq dictionary...
[ 0 ]
[]
[]
[ "dictionary", "python", "regex" ]
stackoverflow_0074435357_dictionary_python_regex.txt
Q: How can I fix Thirdweb Goerli Testnet HTTP Error 429? I'm minting the NFT with the Python SDK of Thirdweb using Goerli TestNet. Code : sdk = ThirdwebSDK.from_private_key(PRIVATE_KEY, NETWORK) NFT_COLLECTION_ADDRESS = contratonft nft_collection = sdk.get_nft_collection(NFT_COLLECTION_ADDRESS) urlarchivoarr=imagence...
How can I fix Thirdweb Goerli Testnet HTTP Error 429?
I'm minting the NFT with the Python SDK of Thirdweb using Goerli TestNet. Code : sdk = ThirdwebSDK.from_private_key(PRIVATE_KEY, NETWORK) NFT_COLLECTION_ADDRESS = contratonft nft_collection = sdk.get_nft_collection(NFT_COLLECTION_ADDRESS) urlarchivoarr=imagencert.split("/") urlarchivostr=str(urlarchivoarr[1]); urlarchi...
[ "What version of the Python SDK are you using? I would suggest upgrading to the latest version (2.1.0).\nThis issue looks like its coming up because your SDK is still using the old public alchemy RPC endpoint, which has since been shut down/blocked.\nWe updated our SDK to use different RPC endpoints in later versio...
[ 2 ]
[]
[]
[ "blockchain", "nft", "python", "thirdweb", "web3py" ]
stackoverflow_0074434445_blockchain_nft_python_thirdweb_web3py.txt
Q: get a character select if its int or str or a symbol hi im having this problem this is my code rn but it wont do anything or just say its a int or a str b=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] c=['&','!','@','#','$','%'] ...
get a character select if its int or str or a symbol
hi im having this problem this is my code rn but it wont do anything or just say its a int or a str b=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] c=['&','!','@','#','$','%'] a = input("Enter here :") if type(a) ==int: print("nu...
[ "The question is worded a little strangely but i'll give it a go. B is a list, so saying a==b will not be true if it is a word. you may be looking to see if the charater passed in (a) is IN list b. for that you will want to do if a in b. Also i believe all of the inputs a will come in as a string, so the first line...
[ 1, 1 ]
[]
[]
[ "python", "python_2.7", "python_3.x" ]
stackoverflow_0074435414_python_python_2.7_python_3.x.txt
Q: Python pandas: Why does df.iloc[:, :-1].values for my training data select till only the second last column? Very simply put, For the same training data frame df, when I use X = df.iloc[:, :-1].values, it will select till the second last column of the data frame instead of the last column (which is what I want B...
Python pandas: Why does df.iloc[:, :-1].values for my training data select till only the second last column?
Very simply put, For the same training data frame df, when I use X = df.iloc[:, :-1].values, it will select till the second last column of the data frame instead of the last column (which is what I want BUT it's a strange behavior I've never seen before), and I know this as the second last column's value and the last...
[ "I think you have only two columns in df, because if there is more columns, iloc select all columns without last:\ndf = pd.DataFrame({'A':[1,2,3],\n 'B':[4,5,6],\n 'C':[7,8,9],\n 'D':[1,3,5],\n 'E':[5,3,6],\n 'F':[7,4,3]})\n\n...
[ 21, 4, 2, 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0037512079_pandas_python.txt
Q: Set dataframe value based on condition of another dataframe Table 1: ID Name Column C Column D 1234hj Bob 1 1 nkj234 Joe 2 2 ji3251 Schmoe 3 3 Table 2: ID Name Bob Joe Sam I currently have 2 dataframes like so. How do i extract the ID from table 1 and set it as ID in table 2 IF the name matches? I've tri...
Set dataframe value based on condition of another dataframe
Table 1: ID Name Column C Column D 1234hj Bob 1 1 nkj234 Joe 2 2 ji3251 Schmoe 3 3 Table 2: ID Name Bob Joe Sam I currently have 2 dataframes like so. How do i extract the ID from table 1 and set it as ID in table 2 IF the name matches? I've tried this code but requires same labelling...
[ "You can try this:\ndf2['ID'] = df2['Name'].map(df.set_index('Name')['ID'])\n\npd.merge is also an option here.\n", "table2 = pd.merge(table1[['ID','Name']], table2[['Name']], how='right', on='Name')\n\n" ]
[ 0, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074435435_dataframe_pandas_python.txt
Q: How to query blob storage data using python Assuming I set up my blob_client correctly (with the right storage account key, url, container name, and blob name) why is my python query code failing? The file in blob is a JSON. query_expression = "SELECT COUNT(*) from blobdata" input_format = DelimitedJsonDialect(del...
How to query blob storage data using python
Assuming I set up my blob_client correctly (with the right storage account key, url, container name, and blob name) why is my python query code failing? The file in blob is a JSON. query_expression = "SELECT COUNT(*) from blobdata" input_format = DelimitedJsonDialect(delimiter=',') reader = blob_client.query_blob(query...
[ "I was able to dig this up from the Azure documentation\nhttps://learn.microsoft.com/en-us/python/api/azure-storage-blob/azure.storage.blob.blobclient?view=azure-python#azure-storage-blob-blobclient-query-blob\nquery_expression = \"SELECT _2 from BlobStorage\"\ninput_format = DelimitedTextDialect(delimiter=',', quo...
[ 2 ]
[]
[]
[ "azure_blob_storage", "python", "sql" ]
stackoverflow_0074435068_azure_blob_storage_python_sql.txt
Q: How to create a multi-index pivot table that sums the max values within a sub-group I have a somewhat large dataframe of customers assigned to a hub and each hub is in a specific location. The hubs get flagged whenever there's an issue and I'd like to know the number of customers affected each time this happens. S...
How to create a multi-index pivot table that sums the max values within a sub-group
I have a somewhat large dataframe of customers assigned to a hub and each hub is in a specific location. The hubs get flagged whenever there's an issue and I'd like to know the number of customers affected each time this happens. So I'd like to find the max number of customers assigned to each hub (this would then excl...
[ "You're on the right start! pivot_table is the right way to group the table with columns by type. You also identified that you can perform the max aggregation at pivot-time:\ndf = pd.pivot_table(\n out,\n values='Customers',\n index=['Location','Hub'],\n columns=['Type','Month'],\n aggfunc='max'\n)\n...
[ 0 ]
[]
[]
[ "pandas", "pivot_table", "python" ]
stackoverflow_0074435535_pandas_pivot_table_python.txt
Q: Is there a function in python that executes two different commands receiving different specific inputs? I am quite new to programming so if this question is really silly please don't laugh at me :( I am looking for a function to ask for (yes or no) questions, just like the below: if input("Question (y/n)") == "y":...
Is there a function in python that executes two different commands receiving different specific inputs?
I am quite new to programming so if this question is really silly please don't laugh at me :( I am looking for a function to ask for (yes or no) questions, just like the below: if input("Question (y/n)") == "y": print("y") if input("Question (y/n)") == "n": print("n") If the input equals "y" it would execute line 2,...
[ "\nIs there a function that can be used in such situation or is there a specific method\n\nYes, the function is called input(). In fact, you almost have it correct. The one piece you are missing is that you need to store the result in a variable. Then you can reuse that result as many times as you wish without call...
[ 2, 0 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0074435488_if_statement_python.txt
Q: How to overwrite a file in azure cosmos DB using azure functions(python) HTTP trigger I am able to write a file to cosmos DB with the help of output binding, but what I need is to know how to overwrite the existing file that is already in cosmos DB My code looks like this import azure.functions as func def main(r...
How to overwrite a file in azure cosmos DB using azure functions(python) HTTP trigger
I am able to write a file to cosmos DB with the help of output binding, but what I need is to know how to overwrite the existing file that is already in cosmos DB My code looks like this import azure.functions as func def main(req: func.HttpRequest, doc: func.Out[func.Document]) -> func.HttpResponse: request_body...
[ "\nI am able to write a file to cosmos DB with the help of output binding, but what I need is to know how to overwrite the existing file that is already in cosmos DB\n\n\nAs far as I know, currently there is no possible way to overwrite the existing file in a cosmos DB.\nIf you want to update existing document in c...
[ 0 ]
[]
[]
[ "azure_cosmosdb", "azure_functions", "azure_http_trigger", "python" ]
stackoverflow_0074413780_azure_cosmosdb_azure_functions_azure_http_trigger_python.txt
Q: Switch GUI icon from light to dark "theme" with PyQt5 I am developing a GUI based on PyQt5 (I'm using Qt creator 8.0.0 based on Qt6.3) and I want to update the icons when the user switches the application to "dark" or "light" mode (ie, icon is black png for light mode and white png for dark mode). The problem is t...
Switch GUI icon from light to dark "theme" with PyQt5
I am developing a GUI based on PyQt5 (I'm using Qt creator 8.0.0 based on Qt6.3) and I want to update the icons when the user switches the application to "dark" or "light" mode (ie, icon is black png for light mode and white png for dark mode). The problem is that I can't access to buttons icon name, and so I can't red...
[ "As @musicamante suggested, I solved the problem by generating theme files and calling the QIcon.setThemeName(\"selected_theme_name\") method to actually update the paths of the icons used in the application.\nHere the light index.theme file (very simplified for the test, and just change the name for the dark theme...
[ 1 ]
[]
[]
[ "darkmode", "pyqt5", "python", "user_interface" ]
stackoverflow_0074432913_darkmode_pyqt5_python_user_interface.txt
Q: How to apply featuretools to output of featuretools? I want to create complex features like [(a-b)/c or (a-b)/a] This can be achieved by running feature tools multiple times so that first one creates features like a-b or a+b or a/b and then next run would create more complex features. As I try to do this using the...
How to apply featuretools to output of featuretools?
I want to create complex features like [(a-b)/c or (a-b)/a] This can be achieved by running feature tools multiple times so that first one creates features like a-b or a+b or a/b and then next run would create more complex features. As I try to do this using the following code samples: import featuretools as ft def mu...
[ "Thank you for your question.\nIt sounds like the desired goal is to create complex features. The desired features can be generated in a single run of dfs. Stacking TransformPrimitives on top of each other is not permitted in Featuretools. However, seed features can be used to generate the desired features. Click h...
[ 1 ]
[]
[]
[ "feature_engineering", "featuretools", "pandas", "python" ]
stackoverflow_0074372332_feature_engineering_featuretools_pandas_python.txt
Q: Write a program to replace the following list of key phrases with underscore in between them in given text: list_of_keyphrases = ['Prince Charles', 'Prince William', 'Meghan Markle', 'United Kingdom', 'North America', 'Duke and Duchess of Sussex', 'Queen Elizabeth II'] text = 'On January 8, Prince Harry and Megha...
Write a program to replace the following list of key phrases with underscore in between them in given text:
list_of_keyphrases = ['Prince Charles', 'Prince William', 'Meghan Markle', 'United Kingdom', 'North America', 'Duke and Duchess of Sussex', 'Queen Elizabeth II'] text = 'On January 8, Prince Harry and Meghan Markle, the Duke and Duchess of Sussex, unveiled their controversial plan to walk away from royal roles. We int...
[ "You imported regular expressions library but never used.\nre.sub() function lets you change strings the way you want in this question.\nre.sub(substringYouAreWannaChange,ConvertedTo,OriginalText)\nYou can use regular expressions for the first parameter but in this case you can use this.\nfor i in list_of_keyphrase...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074435649_python.txt
Q: Importing modules from parent folder I am running Python 2.5. This is my folder tree: ptdraft/ nib.py simulations/ life/ life.py (I also have __init__.py in each folder, omitted here for readability) How do I import the nib module from inside the life module? I am hoping it is possible to do without...
Importing modules from parent folder
I am running Python 2.5. This is my folder tree: ptdraft/ nib.py simulations/ life/ life.py (I also have __init__.py in each folder, omitted here for readability) How do I import the nib module from inside the life module? I am hoping it is possible to do without tinkering with sys.path. Note: The main m...
[ "You could use relative imports (python >= 2.5):\nfrom ... import nib\n\n(What’s New in Python 2.5) PEP 328: Absolute and Relative Imports\nEDIT: added another dot '.' to go up two packages\n", "I posted a similar answer also to the question regarding imports from sibling packages. You can see it here.\nSolution ...
[ 729, 453, 448, 152, 125, 86, 65, 35, 33, 33, 29, 25, 18, 15, 11, 11, 11, 10, 6, 5, 5, 2, 1, 1, 1, 0, 0, 0 ]
[ "Although it is against all rules, I still want to mention this possibility:\nYou can first copy the file from the parent directory to the child directory. Next import it and subsequently remove the copied file:\nfor example in life.py:\nimport os\nimport shutil\n\nshutil.copy('../nib.py', '.')\nimport nib\nos.remo...
[ -1, -4 ]
[ "directory", "module", "path", "python", "python_import" ]
stackoverflow_0000714063_directory_module_path_python_python_import.txt
Q: How to add an animated horizontal line in a python animated scatter plotly graph? Let's take a sample example of animated scatter graph from plotly site : import plotly.express as px df = px.data.gapminder() fig = px.scatter(df, x="gdpPercap", y="lifeExp", animation_frame="year", animation_group="country", ...
How to add an animated horizontal line in a python animated scatter plotly graph?
Let's take a sample example of animated scatter graph from plotly site : import plotly.express as px df = px.data.gapminder() fig = px.scatter(df, x="gdpPercap", y="lifeExp", animation_frame="year", animation_group="country", size="pop", color="continent", hover_name="country", log_x=True, size_ma...
[ "I found a non-optimal solution, which consists in adding scatters having the form line-ew :\nimport plotly.express as px\nimport pandas as pd\nimport numpy as np\n\ndef weighted_average(df, values, weights):\n return sum(df[weights] * df[values]) / df[weights].sum()\n\ndf = px.data.gapminder()\n\ndf[\"Point cat...
[ 0 ]
[]
[]
[ "animation", "graph", "plotly", "plotly_python", "python" ]
stackoverflow_0074359047_animation_graph_plotly_plotly_python_python.txt
Q: Python list maze Hi I am a beginner in python, I keep having "AttributeError: 'int' object has no attribute 'maze'" in my problem I cannot find the problem on my own so please someone help me. Here is the code. def valid(n,maze,x,y): if maze[x][y] == 1 and x < n and y < n: return True else : ...
Python list maze
Hi I am a beginner in python, I keep having "AttributeError: 'int' object has no attribute 'maze'" in my problem I cannot find the problem on my own so please someone help me. Here is the code. def valid(n,maze,x,y): if maze[x][y] == 1 and x < n and y < n: return True else : return False def...
[ "Your problem is a typo in this block:\n if valid(n,maze,x,y) == True:\n move(n,maze,x,y)\n elif valid(n,maze,x,y) == False:\n marked(n.maze,x,y) \n\nSpecifically:\nmarked(n.maze,x,y) \n\nNeeds to be\nmarked(n, maze,x,y) \n\nIt needs to be a coma otherwise it is interpreted as:\nobj...
[ 0 ]
[]
[]
[ "list", "maze", "python" ]
stackoverflow_0074435647_list_maze_python.txt
Q: Python pandas - writing groupby output to file I used the following to get proportion information on my data: >>>testfile = pd.read_csv('CCCC_output_all_FINAL.txt', delimiter="\t", header=0) >>> testdf = pd.DataFrame({'Proportion': testfile.groupby(('Name','Chr','Position','State')).size() / 39}) >>> testdf.head(5...
Python pandas - writing groupby output to file
I used the following to get proportion information on my data: >>>testfile = pd.read_csv('CCCC_output_all_FINAL.txt', delimiter="\t", header=0) >>> testdf = pd.DataFrame({'Proportion': testfile.groupby(('Name','Chr','Position','State')).size() / 39}) >>> testdf.head(5) Proportion...
[ "Use reset_index():\ntestdf.reset_index().to_csv('CCCC_output_summary.txt', sep='\\t', header=True, index=False)\n\n", "I had the same problem. reset_index() as explained above did not work for me. I used an answer from another Stackoverflow and it worked wonderfully. Details are below.\nInput csv has data under ...
[ 5, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0035025917_pandas_python.txt
Q: How to compare values in a list created with *map() function? This is my Python code: class Holiday: def __init__(self, month, day, hours): self.month = month self.day = day self.hours = hours def __str__(self): return f'Month = {self.month}, Day = {self.day}, Hours = {self...
How to compare values in a list created with *map() function?
This is my Python code: class Holiday: def __init__(self, month, day, hours): self.month = month self.day = day self.hours = hours def __str__(self): return f'Month = {self.month}, Day = {self.day}, Hours = {self.hours}' list_of_holidays = [] with open("Holidays.txt") as afil...
[ "How you define each instance of Holiday isn't really relevant, so the solution is the same whether or not you used *map(...) to provide the arguments to Holiday.\nYou just need to check the given month and day against each holiday.\nfor holiday in list_of_holidays:\n if month_input == holiday.month and day_inpu...
[ 1 ]
[]
[]
[ "if_statement", "list", "python" ]
stackoverflow_0074435683_if_statement_list_python.txt
Q: Numpy - odd number operations Write a program that generates a one-dimensional Numpy array consisting of integer random numbers between 1 and 100. The dimension of the array should be queried by the user. After the array is generated, calculate and print the sum of all odd numbers. Then replace all odd numbers by ...
Numpy - odd number operations
Write a program that generates a one-dimensional Numpy array consisting of integer random numbers between 1 and 100. The dimension of the array should be queried by the user. After the array is generated, calculate and print the sum of all odd numbers. Then replace all odd numbers by -1. Finally calculate and print the...
[ "For any array:\nIn [396]: x=np.arange(10) \nIn [397]: x\nOut[397]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n\nThe even/odd test:\nIn [398]: x%2\nOut[398]: array([0, 1, 0, 1, 0, 1, 0, 1, 0, 1], dtype=int32)\n\nSelecting the even ones:\nIn [399]: even = x[x%2==0] \nIn [400]: even\nOut[400]: array([0, 2, 4, 6, 8]...
[ 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074435055_numpy_python.txt
Q: only integer scalar arrays can be converted to a scalar index numpy I found keras tutorial and when was following it got error. train_df = pd.read_csv("train.csv") test_df = pd.read_csv("test.csv") print(f"Total videos for training: {len(train_df)}") print(f"Total videos for testing: {len(test_df)}") center_crop...
only integer scalar arrays can be converted to a scalar index numpy
I found keras tutorial and when was following it got error. train_df = pd.read_csv("train.csv") test_df = pd.read_csv("test.csv") print(f"Total videos for training: {len(train_df)}") print(f"Total videos for testing: {len(test_df)}") center_crop_layer = layers.CenterCrop(IMG_SIZE, IMG_SIZE) def crop_center(frame): ...
[ "Most probably it's because frame is returning an empty array, so concat is failing. So add a condition to check the length of the frame,\nframes = load_video(os.path.join(root_dir, path))\n\nif len(frames) == 0:\n continue\n\n# Pad shorter videos.\nif len(frames) < MAX_SEQ_LENGTH:\n diff = MAX_SEQ_LENGTH - len...
[ 1 ]
[]
[]
[ "keras", "numpy", "pandas", "python", "tensorflow" ]
stackoverflow_0074435359_keras_numpy_pandas_python_tensorflow.txt
Q: Plot multiple image error num must be 1 <= num <= 9, not 10 I'm trying to plot multiple images (9) with the file name it plot the images but it doesn't plot it randomly plus it keep throwing this error "ValueError: num must be 1 <= num <= 9, not 10" no_col = 3 no_row = 3 temp_ls = [] for dirpath, dirnames, filen...
Plot multiple image error num must be 1 <= num <= 9, not 10
I'm trying to plot multiple images (9) with the file name it plot the images but it doesn't plot it randomly plus it keep throwing this error "ValueError: num must be 1 <= num <= 9, not 10" no_col = 3 no_row = 3 temp_ls = [] for dirpath, dirnames, filenames in os.walk("/content/drive/MyDrive/data/"): for filename...
[ "Alternative pattern using plt.subplots:\nno_row, no_col = 3, 3 \n\n# Load your fnames into list\n\nfig,axs = plt.subplots(no_row, no_col)\n\nfor idx,ax in enumerate(axs.flatten()):\n ax.imshow(cv2.imread(temp_ls[idx]))\n ax.set_title(os.path.basename(os.path.normpath(temp_ls[idx])))\n \n# e.g. accessing p...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074407251_python.txt
Q: How to use the result of one function as a parameter of a new function in python? For example: def title(a,b): ... def movie( c = title, d): ... But I get : NameError: name 'title' is not defined How can I use function 'title' in function 'movie' ? I have try: def movie(title(a, b), c): But SyntaxError...
How to use the result of one function as a parameter of a new function in python?
For example: def title(a,b): ... def movie( c = title, d): ... But I get : NameError: name 'title' is not defined How can I use function 'title' in function 'movie' ? I have try: def movie(title(a, b), c): But SyntaxError: invalid syntax now.
[ "def add(a, b):\n return a + b\n\ndef mult(c, d):\n return c * d\n\nprint(mult(add(2, 2), 3))\n# ^ ^ ^ ^\n# | | | |\n#function \"c\"=(a +b),*d\n\n# (2 + 2) x 3 = 12\n# ^ ^ ^\n# | | |\n# a b d\n\n" ]
[ 0 ]
[ "When you call the function in movie, also give it parameters (your a and b)\nLike:\nmovie(title(a, b), c)\n" ]
[ -1 ]
[ "function", "parameters", "python" ]
stackoverflow_0074435734_function_parameters_python.txt
Q: discord.py how to add required text/attachment on a slash command I am in the process of updating a discord bot and i want to make it so it has slash commands instead of using the message content route now that discord.py has slash commands, the following is the code i have and this works for making the command an...
discord.py how to add required text/attachment on a slash command
I am in the process of updating a discord bot and i want to make it so it has slash commands instead of using the message content route now that discord.py has slash commands, the following is the code i have and this works for making the command and having the user be able to run it but i have had a look at the api re...
[ "The syntax for slash command arguments is the same as regular commands. Just add a parameter to your callback & give it a type annotation.\n...\nasync def first_command(interaction, arg1: str, arg2: discord.Attachment):\n ...\n\nFor more examples refer to the official app commands examples: https://github.com/R...
[ 0 ]
[]
[]
[ "bots", "discord", "discord.py", "python" ]
stackoverflow_0074435536_bots_discord_discord.py_python.txt
Q: While installing pyinstaller, this occured : ERROR: Could not install packages due to an OSError: [WinError 2] This is what occurs when installing the pyinstaller, please help me solve this. pip install pyinstaller Collecting pyinstaller Using cached pyinstaller-4.8-py3-none-win_amd64.whl (2.0 MB) Installing coll...
While installing pyinstaller, this occured : ERROR: Could not install packages due to an OSError: [WinError 2]
This is what occurs when installing the pyinstaller, please help me solve this. pip install pyinstaller Collecting pyinstaller Using cached pyinstaller-4.8-py3-none-win_amd64.whl (2.0 MB) Installing collected packages: pyinstaller WARNING: Failed to write executable - trying to use .deleteme logic ERROR: Could not in...
[ "I had a similar problem \"Requirement already satisfied\" with the Pillow module. I saw it in IDE, but it was broken. So I deleted the package folder in C:\\Python310\\Lib\\site-packages and reinstalled it. You could try to do the same.\n" ]
[ 0 ]
[ "I had the same issue. I solved it by uninstallation of partially installed pyinstaller. Then I installed it as Administrator.\n" ]
[ -2 ]
[ "pyinstaller", "python", "python_3.x", "windows" ]
stackoverflow_0070844918_pyinstaller_python_python_3.x_windows.txt
Q: How to add to the pythonpath in jupyter lab I am trying to work with jupyterlab on a remote server that I don't manage, and I want to add my custom libraries to the path so that I can import and use them. Normally, I would go into .bashrc and add to PYTHONPATH there using export PYTHONPATH="/home/username/path/to/...
How to add to the pythonpath in jupyter lab
I am trying to work with jupyterlab on a remote server that I don't manage, and I want to add my custom libraries to the path so that I can import and use them. Normally, I would go into .bashrc and add to PYTHONPATH there using export PYTHONPATH="/home/username/path/to/module:$PYTHONPATH" but this hasn't worked. I ha...
[ "In a Specific Notebook\nManually append the path to sys.path in the first cell of the notebook\nimport sys\nextra_path = ... # whatever it is\nif extra_path not in sys.path:\n sys.path.append(extra_path)\n\nAs a System Configuration\nModify ~/.ipython/profile_default/ipython_config.py using the shell functional...
[ 1 ]
[]
[]
[ "import", "jupyter_lab", "path", "python", "pythonpath" ]
stackoverflow_0071755156_import_jupyter_lab_path_python_pythonpath.txt
Q: Extract Coordinates from KML BatchGeo File with Python I've uploaded some addresses to BatchGeo and downloaded the resulting KML file from which I want to extract the coordinates. I managed to prettify the jumbled text file online here, but I don't know how to parse it to extract the co-ordinates. <?xml version="...
Extract Coordinates from KML BatchGeo File with Python
I've uploaded some addresses to BatchGeo and downloaded the resulting KML file from which I want to extract the coordinates. I managed to prettify the jumbled text file online here, but I don't know how to parse it to extract the co-ordinates. <?xml version="1.0" ?> <kml xmlns="http://earth.google.com/kml/2.0"> <D...
[ "from pykml import parser\n\nroot = parser.fromstring(open('BatchGeo.kml', 'r').read())\nprint root.Document.Placemark.Point.coordinates\n\nsee the pykml docs\nhope that helps!\n", "For some reason, I didn't have a Point element in the KML, it was a LineString element instead. Furthermore, the text string value o...
[ 15, 0 ]
[]
[]
[ "geocoding", "kml", "lxml", "pykml", "python" ]
stackoverflow_0013712132_geocoding_kml_lxml_pykml_python.txt
Q: use pyautogui in a certain open program in windows I would like to use image search in a certain open application, for example, I want it to search the image only in the windows "Calculator" application, how could I do that? Today pyautogui searches the whole screen, is it possible to limit only one open applicati...
use pyautogui in a certain open program in windows
I would like to use image search in a certain open application, for example, I want it to search the image only in the windows "Calculator" application, how could I do that? Today pyautogui searches the whole screen, is it possible to limit only one open application? def main(): try: while True: ...
[ "You can program PyAutoGui to look only at the region of your Windows Taskbar. Below an example:\npyautogui.locateOnScreen('someButton.png', region=(0,0, 300, 400))\n\nPass a region argument (a 4-integer tuple of (left, top, width, height))\nSee more in the documentation\n" ]
[ 0 ]
[]
[]
[ "pyautogui", "python" ]
stackoverflow_0072138990_pyautogui_python.txt
Q: Add title to Networkx plot? I want my code to create a plot with a title. With the code below the plot gets created but no title. Can someone clue me in on what I am doing wrong? import pandas as pd import networkx as nx from networkx.algorithms import community import matplotlib.pyplot as plt from datetime imp...
Add title to Networkx plot?
I want my code to create a plot with a title. With the code below the plot gets created but no title. Can someone clue me in on what I am doing wrong? import pandas as pd import networkx as nx from networkx.algorithms import community import matplotlib.pyplot as plt from datetime import datetime ... G = nx.from_pa...
[ "I can only think of some intermediate step triggering a call to plt.show before your call to plt.title (though it doesn't look like that should be the case with the shared code). Try setting the title beforehand, and setting an ax, here's an example:\nplt.figure(figsize=(10,5))\nax = plt.gca()\nax.set_title('Rando...
[ 9, 6, 0 ]
[]
[]
[ "matplotlib", "networkx", "python" ]
stackoverflow_0063038379_matplotlib_networkx_python.txt
Q: ValueError: Filename must be a string while uploading file to s3 bucket I am sending an excel file as a request in postman and need to upload this to s3 . I access the file from request and send it to s3. @api_view(['POST']) def excel_upload(request): print("request", request) excel_file = request.FILES['f...
ValueError: Filename must be a string while uploading file to s3 bucket
I am sending an excel file as a request in postman and need to upload this to s3 . I access the file from request and send it to s3. @api_view(['POST']) def excel_upload(request): print("request", request) excel_file = request.FILES['file'] print("excel_file", excel_file) // this prints the name of the exc...
[ "I made my configuration with AWSCLI\nS3_BUCKET_NAME = 'YOUR_BUCKET'\n\ns3 = boto3.client('s3')\nwith open(file, 'rb') as f:\n s3.upload_fileobj(f, S3_BUCKET_NAME, file)\n\nI have been getting the same error so I just used upload_fileobj instead of upload_file. This worked fine for me, you can try it.\n", "Sav...
[ 5, 0 ]
[]
[]
[ "amazon_s3", "boto3", "django", "python" ]
stackoverflow_0059891320_amazon_s3_boto3_django_python.txt
Q: Base64 Conversion issue between Python and JAVA Good Morning I'm having an issue converting a Base64 string back to a byte stream when using a compressed file. There appears to be a difference in the byte arrays between a pre converted string from python vs a byte conversion in Java. UPDATED: Apologies, I think my...
Base64 Conversion issue between Python and JAVA
Good Morning I'm having an issue converting a Base64 string back to a byte stream when using a compressed file. There appears to be a difference in the byte arrays between a pre converted string from python vs a byte conversion in Java. UPDATED: Apologies, I think my explanation left something to desire. I've attempted...
[ "You didn't show Python code so I don't know where you went wrong, but you definitely shouldn't get negative numbers. I suspect the decoding steps are applied in the wrong order.\nThis decodes your BASE64 string:\nimport base64\nimport gzip\n\ns = b'H4sIAAAAAAAA/3WSzW7sIAyF9zyFd7PJS0xX7aaq1JG6ZsAJdAiOwBlu3v4eyGwrR...
[ 0, 0 ]
[]
[]
[ "base64", "java", "python", "utf_8" ]
stackoverflow_0074430743_base64_java_python_utf_8.txt
Q: Stream RAW8 video from camera using openCV and Python [Windows] We have a camera that streams RAW8 video at 1920x1080. The GUID used is GREY. We are able to stream video from this camera using ffmpeg on Windows with the below command: ffmpeg -f dshow -pix_fmt gray -video_size 1920x1080 -i video="CAM0" -f nut - | f...
Stream RAW8 video from camera using openCV and Python [Windows]
We have a camera that streams RAW8 video at 1920x1080. The GUID used is GREY. We are able to stream video from this camera using ffmpeg on Windows with the below command: ffmpeg -f dshow -pix_fmt gray -video_size 1920x1080 -i video="CAM0" -f nut - | ffplay - We are now trying to grab images from this camera using Open...
[ "I don't know why reading the frames using OpenCV is not working, but we may use FFmpeg CLI instead.\n\nExecute FFmpeg as sub-process, and set the output to stdout pipe.\nRead the raw video frames from stdout pipe, and convert each frame to 1920x1080 uint8 NumPy array.\n\n\nCode sample:\nimport cv2\nimport numpy as...
[ 1, 0 ]
[]
[]
[ "ffmpeg", "opencv", "python", "video", "windows" ]
stackoverflow_0074433052_ffmpeg_opencv_python_video_windows.txt
Q: How to share and print class attributes with multi thread? I have the program, which does stuff. And it counts how many times it has done some things by day and by hour. So I created a class and assigned it to hourly and daily. And besides that, I have a multi thread function (let's call it background) which is us...
How to share and print class attributes with multi thread?
I have the program, which does stuff. And it counts how many times it has done some things by day and by hour. So I created a class and assigned it to hourly and daily. And besides that, I have a multi thread function (let's call it background) which is used for the menu in the console. It is used to see/print or even ...
[ "your concepts are correct: instance attributes changed in one thread should be visible in another thread. What I think might be wrong in your setup has to do with module naming and importing: some of the imports are ending internally as \"myproject.a\" and others just as \"a\": internally Python will create separ...
[ 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0074435933_multithreading_python.txt
Q: python - create dynamic URL for api call Im trying to send a list of variables to another variable so i can send all items in the list to an api call, so curently I have I have: module = "a" BASE_URL = "https://api-call.io/api" API_KEY = "abcxyz" url = BASE_URL + f"?module={module}&apikey={API_KEY}" But I have 3...
python - create dynamic URL for api call
Im trying to send a list of variables to another variable so i can send all items in the list to an api call, so curently I have I have: module = "a" BASE_URL = "https://api-call.io/api" API_KEY = "abcxyz" url = BASE_URL + f"?module={module}&apikey={API_KEY}" But I have 3 modules to send to api the api call and curr...
[ "Loop over module_list like this:\nmodule_list = [\"a\",\"b\",\"c\"]\nBASE_URL = \"https://api-call.io/api\"\nAPI_KEY = \"abcxyz\"\n\nfor module in module_list:\n url = BASE_URL + f\"?module={module}&apikey={API_KEY}\"\n # now call the url\n\n" ]
[ 0 ]
[]
[]
[ "api", "python" ]
stackoverflow_0074435785_api_python.txt
Q: Maximal set of string-covering substring terms I want to calculate the largest covering of a string from many sets of substrings. All strings in this problem are lowercased, and contain no whitespace or unicode strangeness. So, given a string: abcdef, and two groups of strings: ['abc', 'bc'], ['abc', 'd'], the sec...
Maximal set of string-covering substring terms
I want to calculate the largest covering of a string from many sets of substrings. All strings in this problem are lowercased, and contain no whitespace or unicode strangeness. So, given a string: abcdef, and two groups of strings: ['abc', 'bc'], ['abc', 'd'], the second group (['abc', 'd']) covers more of the original...
[ "Ok, this is not optimized but let's start fixing the results. I believe you have two issues: one is the over-counting in apple; the other is the under-counting in foofoobar0.\nSolving the second issue when the term set is composed of two non-overlapping terms (or just one term), is easy:\nsum([s.count(t)*len(t) fo...
[ 0 ]
[]
[]
[ "numpy", "pandas", "python", "string" ]
stackoverflow_0074423066_numpy_pandas_python_string.txt
Q: Visual Studio Code (VSC) not able to recognize Conda command I am new to VSC and have some experience in Anaconda. Recently, I started learning VSC and found an interesting case. Method 1: When I start VSC from Windows CMD prompt and run any Conda command (i.e. conda list) it throws a big error. I tried to solve i...
Visual Studio Code (VSC) not able to recognize Conda command
I am new to VSC and have some experience in Anaconda. Recently, I started learning VSC and found an interesting case. Method 1: When I start VSC from Windows CMD prompt and run any Conda command (i.e. conda list) it throws a big error. I tried to solve it by following many Google answers without success. Method 2: Then...
[ "Conda has its own environment path where all its dependencies installed in it including python.\nSo if you launch vs code from conda navigator, vs code will run conda's python path, but if you launch vs code from your desktop it will use the path of python installed in your AppData/temp folder.\nYou can still laun...
[ 4, 0, 0 ]
[]
[]
[ "anaconda", "conda", "python", "visual_studio_code" ]
stackoverflow_0064170551_anaconda_conda_python_visual_studio_code.txt
Q: Why I can't increment my variable in this tkinter program I try to make a programme to improve mental calculation with an gui with tkinter. And I apologies in advance if I my errors are really stupid, but it's the first time I use tkinter. So I have the function addition which gives me two numbers (a,b) and the su...
Why I can't increment my variable in this tkinter program
I try to make a programme to improve mental calculation with an gui with tkinter. And I apologies in advance if I my errors are really stupid, but it's the first time I use tkinter. So I have the function addition which gives me two numbers (a,b) and the sum of these two number (c). The user enters the result in the en...
[ "score=0 is a local variable in __init__. You need to add global score to __init__ as well:\nclass PageAdd1(tk.Frame):\n def __init__(self, parent, controller):\n # ...\n global score\n score=0\n\n def getEntry():\n global score\n res=int(entryRes.get())\n ...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074436069_python_tkinter.txt
Q: How can I get a coordinate grid for certain coordinates on the X,Y and Z axis? coordinates = [] repeats = 2 grid_size = 4 for c in itertools.product(range(grid_size), range(grid_size), range(grid_size)): for _ in range(repeats): coordinates.append(list(c)) until now I used this code because I h...
How can I get a coordinate grid for certain coordinates on the X,Y and Z axis?
coordinates = [] repeats = 2 grid_size = 4 for c in itertools.product(range(grid_size), range(grid_size), range(grid_size)): for _ in range(repeats): coordinates.append(list(c)) until now I used this code because I had the same points on all the axis (0,1,2,3) Now it has changed and I have 0,1,2,3 o...
[ "Use itertools.product(range(4), range(7), [0.1, 0.6, 1.3])\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074436139_python.txt
Q: sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 3, and there are 1082 supplied import sqlite3 database = r"files/users.db" textfile = r"files/AlphaVList.txt" class List: def getusers(f): return f c = sqlite3.connect(database) with open(textfile, "r") as ...
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 3, and there are 1082 supplied
import sqlite3 database = r"files/users.db" textfile = r"files/AlphaVList.txt" class List: def getusers(f): return f c = sqlite3.connect(database) with open(textfile, "r") as openfile: file = openfile.read() # print(file) nameList = [] addressList = [] fullAddress = file.split("\n") fullAd...
[ "When you use executemany() the second argument should be a list of rows. So it should be\n[(fullAddress, name, mailAddress), (fullAddress, name, mailAddress), (fullAddress, name, mailAddress), ...]\n\nbut you're creating\n((fullAddress, fullAddress, fullAddress, ...), (name, name, name, ...), (mailAddress, mailAdd...
[ 1 ]
[]
[]
[ "python", "sql" ]
stackoverflow_0074436122_python_sql.txt
Q: Django unittest function with redirect based on mock return_value I have a view function similar to def my_function(request): session = create_something('some_random_string') return redirect(session.url, code=303) To test it import unittest from django.test import TestCase from unittest.mock import patch ...
Django unittest function with redirect based on mock return_value
I have a view function similar to def my_function(request): session = create_something('some_random_string') return redirect(session.url, code=303) To test it import unittest from django.test import TestCase from unittest.mock import patch from my_app.views import my_function class TestMyFunction(TestCase): ...
[ "I had to substitute the return_value in patch to use MagicMock\n@patch('my_app.views.create_something', return_value=MagicMock(url=\"https://tiagoperes.eu\"))\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_tests", "mocking", "python", "python_unittest" ]
stackoverflow_0074436200_django_django_tests_mocking_python_python_unittest.txt
Q: How to remove part of a string by condition - Python->Pandas? I have the next DataFrame: a = [{'name': 'AAA|YYY'},{ 'name': 'BBB|LLL'}] df = pd.DataFrame(a) print(df) name 0 AAA|YYY 1 BBB|LLL and I'm trying to remove the part of the string from the right up to the character |: df['name'] = [i.split('|')[...
How to remove part of a string by condition - Python->Pandas?
I have the next DataFrame: a = [{'name': 'AAA|YYY'},{ 'name': 'BBB|LLL'}] df = pd.DataFrame(a) print(df) name 0 AAA|YYY 1 BBB|LLL and I'm trying to remove the part of the string from the right up to the character |: df['name'] = [i.split('|')[:-1] for i in df['name']] but I get the following result: name...
[ "You're selecting a range of items from the result of your split operation, because you're passing a slice object (:-1).\nActually, to get your result, you just have to select the first part of the split, which will correspond to the index 0:\ndf['name'] = [i.split('|')[0] for i in df['name']]\n\nOr if you have mul...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074435742_dataframe_pandas_python.txt
Q: Can tqdm be used with Database Reads? While reading large relations from a SQL database to a pandas dataframe, it would be nice to have a progress bar, because the number of tuples is known statically and the I/O rate could be estimated. It looks like the tqdm module has a function tqdm_pandas which will report pr...
Can tqdm be used with Database Reads?
While reading large relations from a SQL database to a pandas dataframe, it would be nice to have a progress bar, because the number of tuples is known statically and the I/O rate could be estimated. It looks like the tqdm module has a function tqdm_pandas which will report progress on mapping functions over columns, b...
[ "Edit: Answer is misleading - chunksize has no effect on database side of the operation. See comments below.\nYou could use the chunksize parameter to do something like this:\nchunks = pd.read_sql('SELECT * FROM table', con=conn, chunksize=100)\n\ndf = pd.DataFrame()\nfor chunk in tqdm(chunks):\n df = pd.concat(...
[ 9, 0 ]
[]
[]
[ "pandas", "python", "tqdm" ]
stackoverflow_0040282478_pandas_python_tqdm.txt
Q: How to guarantee Supervisor-launched script gets killed when daemon stopped? How do you ensure that running sudo supervisorctl stop myservice actually stops my service? I have a Supervisor config like: [program:myprogram] command=/usr/local/bin/run_script.sh directory=/usr/local/bin user=myuser numprocs=1 process_...
How to guarantee Supervisor-launched script gets killed when daemon stopped?
How do you ensure that running sudo supervisorctl stop myservice actually stops my service? I have a Supervisor config like: [program:myprogram] command=/usr/local/bin/run_script.sh directory=/usr/local/bin user=myuser numprocs=1 process_name=%(program_name)s stdout_logfile=/var/log/run_script.log stderr_logfile=/var/l...
[ "There's two things happening here.\n\nSupervisord knows PID of its immediate children, but not all descendents.\nWe're sending uncatchable KILL (9) rather than TERM (15).\n\nThose two won't get along with one another.\n\nCurrent hierarchy is: bash --> python --> python workers\nNow, if it was just \"bash --> pytho...
[ 0 ]
[]
[]
[ "python", "supervisord" ]
stackoverflow_0074436214_python_supervisord.txt
Q: Multiple Iterations - Self joining the file/table The problem I am facing is quite tricky(may be for me!) I have a csv file which has 2 columns which are NEW_ID and OLD_ID. The NEW_ID will have its corresponding OLD_ID. The output should be, if the OLD_ID value is alos available as one of the values in NEW_ID the...
Multiple Iterations - Self joining the file/table
The problem I am facing is quite tricky(may be for me!) I have a csv file which has 2 columns which are NEW_ID and OLD_ID. The NEW_ID will have its corresponding OLD_ID. The output should be, if the OLD_ID value is alos available as one of the values in NEW_ID then it needs to be appended with "--". The process needs ...
[ "Two solutions\n#[First]\nimport csv\n\nwith open(path+iteration_file, 'r', encoding=\"utf-8\") as f_in:\n P = set()\n c_in = csv.reader(f_in)\n _, mx = max(\n c_in, \n key=lambda x:(P.add(x[0]), int(x[1]))[1]\n )\n f_in.seek(0)\n with open('output.csv', 'w', newline='', encoding=\"u...
[ 0 ]
[]
[]
[ "iteration", "pandas", "python" ]
stackoverflow_0074435542_iteration_pandas_python.txt
Q: Create new dictionaries based on names of keys of another dictionary I have a dictionary "A": A = { "Industry1": 1, "Industry2": 1, "Industry3": 1, "Customer1": 1, "Customer2": 1, "LocalShop1": 1, "LocalShop2": 1, } I want to group by key names and create new dictionaries for each "cat...
Create new dictionaries based on names of keys of another dictionary
I have a dictionary "A": A = { "Industry1": 1, "Industry2": 1, "Industry3": 1, "Customer1": 1, "Customer2": 1, "LocalShop1": 1, "LocalShop2": 1, } I want to group by key names and create new dictionaries for each "category", the names should be generated automatically. Expected Output: Indu...
[ "Assuming your keys are in (KEYNAME)(NUM), you can do the following:\nimport re\nfrom collections import defaultdict\nfrom pprint import pprint\n\nA = {\n \"Industry1\": 1,\n \"Industry2\": 1,\n \"Industry3\": 1,\n \"Customer1\": 1,\n \"Customer2\": 1,\n \"LocalShop1\": 1,\n \"LocalShop2\": 1,\...
[ 1, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074435636_dictionary_python.txt
Q: ModuleNotFoundError: No Module name 'pandasql' I am trying to import pandasql. I am running the following code in a jupyter notebook running python: !pip install pandasql from pandasql import sqldf import pandas as pd This logs an error saying ModuleNotFoundError: No Module name 'pandasql' I understand this is a...
ModuleNotFoundError: No Module name 'pandasql'
I am trying to import pandasql. I am running the following code in a jupyter notebook running python: !pip install pandasql from pandasql import sqldf import pandas as pd This logs an error saying ModuleNotFoundError: No Module name 'pandasql' I understand this is a common problem and have tried using the following S...
[ "I know I am quite late in responding this but try this, but as you are working on Jupyter notebook, you can try pip install pandasql in Anaconda prompt\n", "I think either your python you are using is wrong/doesn't have the code, or you haven't installed or printed it right.\n", "I encountered the same issue a...
[ 3, 0, 0 ]
[]
[]
[ "pandas", "pandasql", "python" ]
stackoverflow_0058944642_pandas_pandasql_python.txt
Q: show several curve fit output in one diagram python I have 4 float arrays with sizes (5,10) and I need to show each row of these arrays in one diagram. I fit a curve to each row of these arrays. the output is as follows. for the first row, I have 4 graphs as follows. but I need to show all of them in one graph to ...
show several curve fit output in one diagram python
I have 4 float arrays with sizes (5,10) and I need to show each row of these arrays in one diagram. I fit a curve to each row of these arrays. the output is as follows. for the first row, I have 4 graphs as follows. but I need to show all of them in one graph to find the intersection points. I used the following code t...
[ "You can pass a multi-dimensional array to plot and each column will be created as a separate plot object. We transpose both inputs so that it will plot each row separately.\nAssuming your (5,10) array looks like this.\n#d= [[16 18 29 22 24 26 28 30]\n [17 19 20 24 27 29 29 29]\n [10 18 19 28 29 32 33 36...
[ 0 ]
[]
[]
[ "plot", "python" ]
stackoverflow_0074435942_plot_python.txt
Q: Identical matrices give different results based on how they're created I want to create a matrix with 1 column and n rows, to use in a calculation for a PageRank algorithm. If I make it like this, and then use the matrix in a calculation, it gives this result: A = [[0.0375,0.4625,0.0375,0.32083333], [0.0375, ...
Identical matrices give different results based on how they're created
I want to create a matrix with 1 column and n rows, to use in a calculation for a PageRank algorithm. If I make it like this, and then use the matrix in a calculation, it gives this result: A = [[0.0375,0.4625,0.0375,0.32083333], [0.0375, 0.0375,0.0375,0.32083333], [0.8875, 0.0375, 0.0375, 0.32083333], [...
[ "It isn't clearly visible, but there IS a difference between the two examples.\nThe difference is that the first r is an np.matrix, and the second r is an np.array. One of the few differences between the two is the multiply operator. Using * on a matrix does a matrix multiply. Using * on an array does an element...
[ 1 ]
[]
[]
[ "matrix", "pagerank", "python" ]
stackoverflow_0074431041_matrix_pagerank_python.txt
Q: The image is not displayed in the html layout of letters I am trying to send an email with html code. In it I place my image. But when receiving a letter in the mail, the image is not displayed. <div class="header__container "> <img src="mysite/logo.svg" alt="logo" class="header_img"> </div> However, it does n...
The image is not displayed in the html layout of letters
I am trying to send an email with html code. In it I place my image. But when receiving a letter in the mail, the image is not displayed. <div class="header__container "> <img src="mysite/logo.svg" alt="logo" class="header_img"> </div> However, it does not appear in the email. <img src="https://ci6.googleuserc...
[ "SVG is not supported in many email clients (Outlook as well). If you try to insert SVG files in Outlook manually you may find that they are converted to JPEG images.\nAnother aspect is that internet based images (hosted on the server anywhere) are blocked by default in most emails clients. To avoid that you need t...
[ 2, 0 ]
[]
[]
[ "css", "email", "html", "image", "python" ]
stackoverflow_0074434240_css_email_html_image_python.txt
Q: Removing certain elements from a list that start with a specific character and adding them to new list in Python I have a list that I want to edit. For all the elements that start with '[x]', I want the list to remove those elements and place them into new list. But for the new list, in doing so, it should remove ...
Removing certain elements from a list that start with a specific character and adding them to new list in Python
I have a list that I want to edit. For all the elements that start with '[x]', I want the list to remove those elements and place them into new list. But for the new list, in doing so, it should remove the '[x]' from the front of the elements. list1 = ['[x]final', '[x]gym', 'midterm', '[x]class', 'school'] list1 becom...
[ "Since you are a beginner, the verbose way to do this is the following\nlist1 = ['[x]final', '[x]gym', 'midterm', '[x]class', 'school']\n\nnew_list = []\nfor s in list1:\n if s.startswith(\"[x]\"):\n new_list.append(s[3:])\n\nprint(new_list)\n\nHowever, you can take advantage of Python's list comprehensio...
[ 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074436421_list_python.txt
Q: How i can make multiline label in KivyMD? I want make multiline label in KV string: MDLabel: text: ' MultilineText' But i receive this error: text: ' 8: >> 9: MultilineText' 10: 11: pos_hint: {'cent...
How i can make multiline label in KivyMD?
I want make multiline label in KV string: MDLabel: text: ' MultilineText' But i receive this error: text: ' 8: >> 9: MultilineText' 10: 11: pos_hint: {'center_x':.5,'center_y':.5} ... Invalid indentatio...
[ "Tricky topic. Try this:\n'''\n<Code>\n size_hint_y: None\n height: 60\n FloatLayout:\n MDLabel:\n text: '\\\\n' +\\\n '\\\\n' +\\\n 'MultilineText'\n \n pos_hint: {'center_x':.5,'center_y':.5}\n'''\n\n" ]
[ 1 ]
[ "I tried it ou and it Works nicely !!\nMDLabel:\nmarkup : True\nmultiline : True\nfont_size :'12sp'\ntext: '[b][color=#007acc] Derived Cust Bullet Rates (%) [/color][/b]'+'\\n' +' Rate convention linked'\npos_hint: {'center_x': 1,'center_y': 0.75}\n" ]
[ -1 ]
[ "kivy", "kivymd", "label", "python", "python_3.x" ]
stackoverflow_0066220880_kivy_kivymd_label_python_python_3.x.txt
Q: Python Logging - Disable logging from imported modules I'm using the Python logging module, and would like to disable log messages printed by the third party modules that I import. For example, I'm using something like the following: logger = logging.getLogger() logger.setLevel(level=logging.DEBUG) fh = logging.S...
Python Logging - Disable logging from imported modules
I'm using the Python logging module, and would like to disable log messages printed by the third party modules that I import. For example, I'm using something like the following: logger = logging.getLogger() logger.setLevel(level=logging.DEBUG) fh = logging.StreamHandler() fh_formatter = logging.Formatter('%(asctime)s...
[ "The problem is that calling getLogger without arguments returns the root logger so when you set the level to logging.DEBUG you are also setting the level for other modules that use that logger.\nYou can solve this by simply not using the root logger. To do this just pass a name as argument, for example the name of...
[ 129, 62, 61, 27, 11, 10, 9, 3, 3, 2, 1, 1, 0 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0035325042_logging_python.txt
Q: How to Fix Images Being Written to Video in Random Order I am attempting to write 271 images of a simulation that are already in numerical order ('0.jpg','1.jpg', ..., '271.jpg') into a video. cv2.videoWriter appears to be writing all of these images in random order, producing a video that doesn't align with what ...
How to Fix Images Being Written to Video in Random Order
I am attempting to write 271 images of a simulation that are already in numerical order ('0.jpg','1.jpg', ..., '271.jpg') into a video. cv2.videoWriter appears to be writing all of these images in random order, producing a video that doesn't align with what is supposed to happen in the simulation. I have already tried...
[ "There are two problems with\nfiles.sort(key = lambda x: x[5:-4])\nfiles.sort()\n\nFirst, '0.jpg'[5:-4] produces an empty string. I think you want something like\nfile.sort(key = lambda x: int(x[:-4]))\n\nSecond, you're throwing away the result by sorting again. Drop the second sort.\n", "I was facing the same pr...
[ 0, 0 ]
[]
[]
[ "cv2", "python" ]
stackoverflow_0056300792_cv2_python.txt
Q: Getting 'HttpError 401' when attempting to use Google Drive API with delegated credentials I'm attempting to look at the files for all the users in my org using the Google API in Python. I have a service account with domain-wide delegation. I'm attempting to create delegated credentials for each user so that I can...
Getting 'HttpError 401' when attempting to use Google Drive API with delegated credentials
I'm attempting to look at the files for all the users in my org using the Google API in Python. I have a service account with domain-wide delegation. I'm attempting to create delegated credentials for each user so that I can look at their files. However, when I run the code below, on this line in the for loop: results ...
[ "I figured it out. It turns out the first user in the list is suspended, and therefore does not have access to their Google drive files. Other users work just fine.\nThat begs the question, though, of how I'm supposed to look at the files of suspended users (as I'm pretty sure those files still exist).\n" ]
[ 0 ]
[]
[]
[ "google_admin_sdk", "google_drive_api", "python" ]
stackoverflow_0074436399_google_admin_sdk_google_drive_api_python.txt
Q: How do I map over individual regions, over a several year timespan, in Google Earth Engine? I'm new to GEE and am trying to get the average precipitation over a time period 1981-2019 for geometries along a transect. Here is my code: def yearlyRainfall(year): startDate = ee.Date.fromYMD(year, 1, 1) endDate ...
How do I map over individual regions, over a several year timespan, in Google Earth Engine?
I'm new to GEE and am trying to get the average precipitation over a time period 1981-2019 for geometries along a transect. Here is my code: def yearlyRainfall(year): startDate = ee.Date.fromYMD(year, 1, 1) endDate = startDate.advance(1, 'year') filtered = chirps.filter(ee.Filter.date(startDate, endDate)) ...
[ "Use reduceRegions instead. Also, create an image with bands for all years instead of mapping over the years so you only do the reduce call once.\ndef yearlyRainfall(year):\n startDate = ee.Date.fromYMD(year, 1, 1)\n endDate = startDate.advance(1, 'year')\n filtered = chirps.filter(ee.Filter.date(startDate...
[ 0 ]
[]
[]
[ "google_earth_engine", "libgee", "python" ]
stackoverflow_0074426258_google_earth_engine_libgee_python.txt
Q: Return a list of values that match a minimum condition [Pandas] I have a dataframe that I'm hoping to return a list of all the values that match the minimum cost per segment. The dataframe looks like this: Segment Part ID Cost 1 1 $0.5 - - - 1 2 $0.6 1 3 $0.5 1 4 $0.7 2 5 $0.4 2 6 $0.5 2 7 $0.6 Etc. Wha...
Return a list of values that match a minimum condition [Pandas]
I have a dataframe that I'm hoping to return a list of all the values that match the minimum cost per segment. The dataframe looks like this: Segment Part ID Cost 1 1 $0.5 - - - 1 2 $0.6 1 3 $0.5 1 4 $0.7 2 5 $0.4 2 6 $0.5 2 7 $0.6 Etc. What I am hoping to end up with is a new dataframe like ...
[ "You can use a double groupby, one to filter, the other to aggregate:\ns = pd.to_numeric(df['Cost'].str.strip('$'))\n\nout = (df[s.eq(s.groupby(df['Segment']).transform('min'))]\n .groupby('Segment', as_index=False)\n .agg({'Part ID': list, 'Cost': 'first'})\n )\n\nOutput:\n Segment Part ID Cos...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074436134_pandas_python.txt
Q: WebSocket Get Futures Realtime Price Binance This is how I established a real-time price WebSocket price for Spot Market, but how do I get the real-time price for Futures BTCUSDT? socket = f"wss://stream.binance.com:9443/ws/dotusdt@kline_1m" def on_message(ws, message): print(message) def on_close(ws): p...
WebSocket Get Futures Realtime Price Binance
This is how I established a real-time price WebSocket price for Spot Market, but how do I get the real-time price for Futures BTCUSDT? socket = f"wss://stream.binance.com:9443/ws/dotusdt@kline_1m" def on_message(ws, message): print(message) def on_close(ws): print("Connection closed") ws = websocket.WebSocke...
[ "socket = f\"wss://fstream.binance.com:9443/ws/dotusdt@kline_1m\"\nyou need to add \"f\" before \"stream\"\n", "Add 'f' before 'stream' and remove the ':9443\n" ]
[ 0, 0 ]
[]
[]
[ "binance", "binance_api_client", "python" ]
stackoverflow_0071200303_binance_binance_api_client_python.txt
Q: How to create an array with arrays in one function I am trying to create an output that will be an array that contains 5 "sub-arrays". Every array should include 10 random numbers between 0 and 10. I have this code: def count_tweets(): big_array = [] for i in range(5): array = [] for p in r...
How to create an array with arrays in one function
I am trying to create an output that will be an array that contains 5 "sub-arrays". Every array should include 10 random numbers between 0 and 10. I have this code: def count_tweets(): big_array = [] for i in range(5): array = [] for p in range(10): array.append(random.randint(0,10))...
[ "You got it right, just slide the print out of the for loop.(delete four spaces before print())\n", "So what you did was put the print() statement inside a loop, which will print each time it runs.\n import random\n\n def count_tweets():\n big_array = []\n for i in range(5):\n array...
[ 0, 0 ]
[]
[]
[ "append", "arrays", "python", "random", "range" ]
stackoverflow_0074436483_append_arrays_python_random_range.txt
Q: Config variable 'Py_DEBUG' is unset I tried installing matplotlib whl file in python 3.6 on windows but I all I got was this error: C:\Python36\lib\site-packages\wheel\pep425tags.py:77: RuntimeWarning: Config variable 'Py_DEBUG' is unset, Python ABI tag may be incorrect warn=(impl == 'cp')): I tried debugging it b...
Config variable 'Py_DEBUG' is unset
I tried installing matplotlib whl file in python 3.6 on windows but I all I got was this error: C:\Python36\lib\site-packages\wheel\pep425tags.py:77: RuntimeWarning: Config variable 'Py_DEBUG' is unset, Python ABI tag may be incorrect warn=(impl == 'cp')): I tried debugging it but it seems to be a real issue here: http...
[ "Although this answer is irrelevant (and outdated) to the original question, people come here after Googling for this very error.\nAt the end of the day, it usually turn out to be some kind of package compilation error when using pip install . and build related installs. Most likely because the build config was mad...
[ 0 ]
[]
[]
[ "matplotlib", "pip", "python" ]
stackoverflow_0042840905_matplotlib_pip_python.txt
Q: Python - Sampling imbalanced dataset I have a dataset with 3 classes and below are the value_counts(). Class 0 - 2000 Class 1 - 10000 Class 2 - 10000 I want to sample this dataset with the distribution as below. Class 0 - 2000 (i.e., all rows from Class 0) Class 1 - 4000 (i.e., twice as many rows as Class 0) Clas...
Python - Sampling imbalanced dataset
I have a dataset with 3 classes and below are the value_counts(). Class 0 - 2000 Class 1 - 10000 Class 2 - 10000 I want to sample this dataset with the distribution as below. Class 0 - 2000 (i.e., all rows from Class 0) Class 1 - 4000 (i.e., twice as many rows as Class 0) Class 2 - 4000 (i.e., twice as many rows as Cl...
[ "If I understand you correctly:\n# Create sample data\ndf = pd.DataFrame({\"class\": np.repeat([0, 1, 2], [2_000, 10_000, 10_000])})\n\n# The distribution matrix\ndistribution = {0: 2000, 1: 4000, 2: 4000}\n\n# Take samples based on the distribution matrix\nsample = pd.concat(\n [group.sample(distribution[class_...
[ 1 ]
[]
[]
[ "machine_learning", "pandas", "python", "random", "sample" ]
stackoverflow_0074436311_machine_learning_pandas_python_random_sample.txt
Q: Setting only global level seed gives same output in consecutive iterations of loop in Tensorflow I am testing out the tf.random.set_seed according to the rules given at - https://www.tensorflow.org/api_docs/python/tf/random/set_seed In particular I am testing the second rule - where we set only global level seed a...
Setting only global level seed gives same output in consecutive iterations of loop in Tensorflow
I am testing out the tf.random.set_seed according to the rules given at - https://www.tensorflow.org/api_docs/python/tf/random/set_seed In particular I am testing the second rule - where we set only global level seed and no operation level seed. According to the documentation (the link is mentioned above), the second r...
[ "Two different operation seed can generate the same sequence. I don't think there is any guarantee that no two consecutive tensors are repeated. For example,\ntf.random.set_seed(1234)\nprint(tf.random.shuffle(constant_tensor, seed=6))\nprint(tf.random.shuffle(constant_tensor, seed=7))\n\n#ouputs are same even thoug...
[ 0 ]
[]
[]
[ "machine_learning", "python", "tensorflow", "tensorflow2.0" ]
stackoverflow_0074434308_machine_learning_python_tensorflow_tensorflow2.0.txt