content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: python code dont delete all same entries in the array over an regex search function i read an txt file with syslog stuff Oct 3 12:09:01 webv2 CRON[1903]: (root) CMD (sudo /usr/bin/python3 /var/www/security/py_scripts/security_stuff.py 01_report_connections 0 &) Oct 3 12:09:01 webv2 CRON[1906]: (root) CMD ( [ -x...
python code dont delete all same entries in the array over an regex search function
i read an txt file with syslog stuff Oct 3 12:09:01 webv2 CRON[1903]: (root) CMD (sudo /usr/bin/python3 /var/www/security/py_scripts/security_stuff.py 01_report_connections 0 &) Oct 3 12:09:01 webv2 CRON[1906]: (root) CMD ( [ -x /usr/lib/php/sessionclean ] && if [ ! -d /run/systemd/system ]; then /usr/lib/php/sessio...
[ "You're making a classic mistake: You remove items from a list while iterating over it. That tends to go south. Also, modifying a list with del is usually not very efficient.\nExample: A list numbers from which you want to remove the even numbers. Your method\nnumbers = [1, 2, 3, 4, 5]\nn = -1\nfor a in numbers:\n ...
[ 0 ]
[]
[]
[ "arrays", "python", "sorting" ]
stackoverflow_0074152144_arrays_python_sorting.txt
Q: How do I forecast data using ARIMA? I wanted to forecast stock prices using the ARIMA model (Autoregressive Moving Average) and wanted to plot the forecasted data over the actual and training data. I'm following this tutorial and have browsed others too. But they all follow the same code. Here is the link to their...
How do I forecast data using ARIMA?
I wanted to forecast stock prices using the ARIMA model (Autoregressive Moving Average) and wanted to plot the forecasted data over the actual and training data. I'm following this tutorial and have browsed others too. But they all follow the same code. Here is the link to their tutorial for your reference:(https://www...
[ "It seems, that the forecast function is not returning three return values anymore. This may happen if you don’t use the same version as in the tutorial.\nPlease try something like:\n\nresult = fitted.forecast(216, alpha=0.05)\n\nAnd then inspect the result if it does contain all the data you need.\n", "import li...
[ 1, 0 ]
[]
[]
[ "arima", "forecast", "forecasting", "python", "sarimax" ]
stackoverflow_0071640665_arima_forecast_forecasting_python_sarimax.txt
Q: Removing all rows that are not a number in a certain column I have a problem. I want to remove all rows that are not a number in the column ['a','b']. I have tried this but my approach does not work very well. Dataframe a b c 0 0.1 10 x 1 0.5 5 y 2 10 / 5 60 z 3 9.0 12 w 4 125 ...
Removing all rows that are not a number in a certain column
I have a problem. I want to remove all rows that are not a number in the column ['a','b']. I have tried this but my approach does not work very well. Dataframe a b c 0 0.1 10 x 1 0.5 5 y 2 10 / 5 60 z 3 9.0 12 w 4 125 a w Code import uuid import pandas as pd df = pd.DataFrame( ...
[ "You could just do\nout = df[~df[['a', 'b', 'id']].apply(lambda x: pd.to_numeric(x, errors='coerce')).isna().any(1)]\n\n", "what about that\nnew_df = df[list(df.a.str.isnumeric() != False) and list(df.a.str.isnumeric() != False)]\n\n\n a b c\n0 0.1 10 x\n1 0.5 5 y\n3 9.0 12 w\n4 125 a w\n\nI ...
[ 3, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074157876_dataframe_pandas_python.txt
Q: Methods for observing RA/Dec location in the sky I am new to Skyfield and have been trying to automate the creation of full-sky star charts, given a location on earth and a time. I have attempted to create a point that corresponds to a given location's zenith and then observe that point, as in the comet example fo...
Methods for observing RA/Dec location in the sky
I am new to Skyfield and have been trying to automate the creation of full-sky star charts, given a location on earth and a time. I have attempted to create a point that corresponds to a given location's zenith and then observe that point, as in the comet example found in the documentation: https://rhodesmill.org/skyfi...
[ "Try using the Zenith position directly as the center of your plot:\nprojection = build_stereographic_projection(zenith)\n\nSee whether that puts the right stars at the center of the resulting diagram. If not, try pasting in the result as an image, and we can explore further!\n" ]
[ 0 ]
[]
[]
[ "python", "skyfield" ]
stackoverflow_0074128863_python_skyfield.txt
Q: Generating all letter combinations of a set of letters in Python Which code best generates all 3-letter combinations of a given set of letters in Python? I want to output something like this: 'AAA', 'AAB', 'AAC', 'AAD', 'AAE', 'AAF', 'AAG', 'AAH', 'AAI', 'AAJ', 'AAK', 'AAL', 'AAM'...'ZZX', 'ZZY', 'ZZZ' A: iterto...
Generating all letter combinations of a set of letters in Python
Which code best generates all 3-letter combinations of a given set of letters in Python? I want to output something like this: 'AAA', 'AAB', 'AAC', 'AAD', 'AAE', 'AAF', 'AAG', 'AAH', 'AAI', 'AAJ', 'AAK', 'AAL', 'AAM'...'ZZX', 'ZZY', 'ZZZ'
[ "itertools is a natural choice since these are essentially products drawn from a set of letters.\nimport string,itertools\n\nwords = [''.join(letters) for letters in itertools.product(string.ascii_uppercase,repeat = 3)]\n\nprint(words[:5]) #['AAA', 'AAB', 'AAC', 'AAD', 'AAE']\nprint(words[-5:]) #['ZZV', 'ZZW', 'ZZX...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074157987_python.txt
Q: Combining 4 sets of data in python I have four separate sets of data for each of the 4 quarters in the year, the columns are identical within all. What is a python function I can use to combine them into one master data set? Thank you! A: You want to use the pandas concat funtion for this since the dataframes ar...
Combining 4 sets of data in python
I have four separate sets of data for each of the 4 quarters in the year, the columns are identical within all. What is a python function I can use to combine them into one master data set? Thank you!
[ "You want to use the pandas concat funtion for this since the dataframes are identical. See this example:\ndf1 = pd.DataFrame(\n {\n \"A\": [\"A0\", \"A1\", \"A2\", \"A3\"],\n \"B\": [\"B0\", \"B1\", \"B2\", \"B3\"],\n \"C\": [\"C0\", \"C1\", \"C2\", \"C3\"],\n \"D\": [\"D0\", \"D1\",...
[ 1, 0 ]
[]
[]
[ "data_analysis", "pandas", "python" ]
stackoverflow_0074158020_data_analysis_pandas_python.txt
Q: Why does choosemove() allow you to hit endlessly and not run lose() when the total value is greater then 21? Is the code generating a new card every time choosemove() and then creating a new card again and adding on top if you hit again like its supposed to? Basically, I need lose() to run when newtotalplayercardv...
Why does choosemove() allow you to hit endlessly and not run lose() when the total value is greater then 21?
Is the code generating a new card every time choosemove() and then creating a new card again and adding on top if you hit again like its supposed to? Basically, I need lose() to run when newtotalplayercardvalue > 21 so it shows the player lost, but it just lets you "hit" endlessly for some reason. Thanks in advance! im...
[ "First things first, your program isnt well formatted, there is no seperation between the way that global variables and local variables are defined. It's standard practice to define global variables in Uppercase. Will make life easier for you. \nAs to what the endless hitting is, you aren't updating the totalplayer...
[ 0 ]
[]
[]
[ "function", "python" ]
stackoverflow_0074158001_function_python.txt
Q: Python Pandas Choosing Random Sample of Groups from Groupby What is the best way to get a random sample of the elements of a groupby? As I understand it, a groupby is just an iterable over groups. The standard way I would do this for an iterable, if I wanted to select N = 200 elements is: rand = random.sample(dat...
Python Pandas Choosing Random Sample of Groups from Groupby
What is the best way to get a random sample of the elements of a groupby? As I understand it, a groupby is just an iterable over groups. The standard way I would do this for an iterable, if I wanted to select N = 200 elements is: rand = random.sample(data, N) If you attempt the above where data is a 'grouped' the e...
[ "You can take a randoms sample of the unique values of df.some_key.unique(), use that to slice the df and finally groupby on the resultant:\nIn [337]:\n\ndf = pd.DataFrame({'some_key': [0,1,2,3,0,1,2,3,0,1,2,3],\n 'val': [1,2,3,4,1,5,1,5,1,6,7,8]})\nIn [338]:\n\nprint df[df.some_key.isin(rand...
[ 15, 3, 1 ]
[]
[]
[ "group_by", "pandas", "python", "random" ]
stackoverflow_0032340604_group_by_pandas_python_random.txt
Q: How to Automate repeated tasks in SAP Logon I am given a task to automate few boring tasks that people in office do everyday using SAP Logon 640. There are like 30-40 transactions that are required to be automated. I searched a lot on SAP Automation and found SAP GUI Scripting but failed to find any starting point...
How to Automate repeated tasks in SAP Logon
I am given a task to automate few boring tasks that people in office do everyday using SAP Logon 640. There are like 30-40 transactions that are required to be automated. I searched a lot on SAP Automation and found SAP GUI Scripting but failed to find any starting point for python, php or java. How should i start to ...
[ "We use either VBScript or C# to automate tasks. Using VBSCript is the easiest. Have the SAP GUI record a task then it will produce a vbscript that can serve as a starting point for your coding. When you have this vbscript file then you can translate it into other languages.\n", "You can use Sikuli to automate a ...
[ 1, 1, 0, 0, 0 ]
[]
[]
[ "automation", "java", "php", "python", "sap" ]
stackoverflow_0023846012_automation_java_php_python_sap.txt
Q: How to create an infinite while loop? I need to change the code below to make it so that the while loop will never stop. What do I change? count = 0 while (count < 9): print ('The droid count is:', count) count = count + 1 print ("That's all the droids we have!") A: while (8<9): while (True): Any c...
How to create an infinite while loop?
I need to change the code below to make it so that the while loop will never stop. What do I change? count = 0 while (count < 9): print ('The droid count is:', count) count = count + 1 print ("That's all the droids we have!")
[ "while (8<9):\n\nwhile (True):\n\nAny condition that always evaluates to True.\n", "count = 0\n\nwhile True:\n print ('The droid count is:', count)\n count = count + 1\n\n" ]
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074158161_python.txt
Q: IPython widgets not displaying properly within jupyter lab I am attempting to display a IPython widget in jupyter lab by calling display(mywidget) but all I get is a log printout (the log printout is just a description of the object.) In jupyter notebook, the code all works fine. The problem in jupyter lab also on...
IPython widgets not displaying properly within jupyter lab
I am attempting to display a IPython widget in jupyter lab by calling display(mywidget) but all I get is a log printout (the log printout is just a description of the object.) In jupyter notebook, the code all works fine. The problem in jupyter lab also only happens when I try to call the display function from within m...
[ "I'm not sure what you are trying to do after the button gets displayed.\nHere's something closer that runs in JupyterLab in line with what I discuss in this other stackoverflow answer about updating without relying on ipywidgets interactive function:\nimport IPython\nfrom IPython.display import display, clear_outp...
[ 0 ]
[]
[]
[ "jupyter_lab", "jupyter_notebook", "python" ]
stackoverflow_0074157807_jupyter_lab_jupyter_notebook_python.txt
Q: dictionary where key is first letter of element in list and values are element Given a list of lowercase strings named mystrings, create and return a dictionary whose keys are the unique first characters of the strings and whose values are lists of words beginning with those characters, in the same order that they...
dictionary where key is first letter of element in list and values are element
Given a list of lowercase strings named mystrings, create and return a dictionary whose keys are the unique first characters of the strings and whose values are lists of words beginning with those characters, in the same order that they appear in the list of strings. Ignore case: you can assume that all words are lower...
[ "Use a loop and dict's setdefault:\nmystrings = [\"banana\", \"xylophone\", \"duck\", \"carriage\", \"bandana\", \"diamond\", \"cardinal\"]\n\nout = {}\nfor word in mystrings:\n out.setdefault(word[0], []).append(word)\n\nOutput:\n{'b': ['banana', 'bandana'],\n 'x': ['xylophone'],\n 'd': ['duck', 'diamond'],\n '...
[ 1, 0, 0 ]
[]
[]
[ "dictionary", "loops", "python" ]
stackoverflow_0074158140_dictionary_loops_python.txt
Q: is there a way to turn [0, -2, 1, -3, 2, -4, 3, -5, 4, -6] into [0, 1, -2, 2, -3, 3, -4, 4, -5, -6] In short, I had an assignment problem where my final output should be a list of numbers, However in some cases, I have the good numbers in my list but just in the wrong order. I don't want to change my entire code...
is there a way to turn [0, -2, 1, -3, 2, -4, 3, -5, 4, -6] into [0, 1, -2, 2, -3, 3, -4, 4, -5, -6]
In short, I had an assignment problem where my final output should be a list of numbers, However in some cases, I have the good numbers in my list but just in the wrong order. I don't want to change my entire code since it is quite long. Thus, I was wondering if there is a trick, function or something that I can use ...
[ "You can use the key parameter of sorted with a tuple of the absolute value and the value itself. This will thus sort by the absolute and in case of tie, put the negative number first.\nout = sorted(your_lst, key=lambda x: (abs(x), x))\n\nOutput on the first example:\n[0, 1, -2, 2, -3, 3, -4, 4, -5, -6]\n\nIf you w...
[ 3, 3 ]
[]
[]
[ "for_loop", "list", "primes", "python", "sorting" ]
stackoverflow_0074158256_for_loop_list_primes_python_sorting.txt
Q: How do you do natural ordering for strings with negative numbers and characters? I have a list of file names that I need to open, however, the file names contain a hyphen "-" which neither os or Windows 10 naturally recognizes as a negative number. As an example, the list itself gets imported as ['-001.000ps.csv',...
How do you do natural ordering for strings with negative numbers and characters?
I have a list of file names that I need to open, however, the file names contain a hyphen "-" which neither os or Windows 10 naturally recognizes as a negative number. As an example, the list itself gets imported as ['-001.000ps.csv', '-100.000ps.csv', '0000.000ps.csv', '0001.000ps.csv', '0002.000ps.csv', '0003.00...
[ "natsort can be used to sort signed numbers like so:\nfnames = [\n '-001.000ps.csv',\n '-100.000ps.csv',\n '0000.000ps.csv',\n '0001.000ps.csv',\n '0002.000ps.csv',\n '0003.000ps.csv',\n '0003.500ps.csv',\n]\n\nnatsort.realsorted(fnames)\nnatsort.natsorted(fnames, alg=natsort.ns.REAL)\n\nBoth o...
[ 2, 1, 0 ]
[]
[]
[ "list", "natural_sort", "python", "sorting", "string" ]
stackoverflow_0074158071_list_natural_sort_python_sorting_string.txt
Q: It is impossible to add a non-nullable field Error when extending Abstract User I want to extend the Base Abstract User Model and this is the extended model: class Student(AbstractUser): birth = models.DateField(default=datetime.date.today) street = models.CharField(max_length=25) street_number = model...
It is impossible to add a non-nullable field Error when extending Abstract User
I want to extend the Base Abstract User Model and this is the extended model: class Student(AbstractUser): birth = models.DateField(default=datetime.date.today) street = models.CharField(max_length=25) street_number = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(99)]) city = m...
[ "You don't want to do that. You want a User model (you already have one that Django provides, no need to extend it for now), and a Student model that has a OneToOne relationship with the User model.\nConceptually:\n\nUser: models a user of your application and its authentication and permissions\nStudent: the repres...
[ 2 ]
[]
[]
[ "database", "django", "model", "python" ]
stackoverflow_0074158150_database_django_model_python.txt
Q: Password protected site Flask/Dash I built a website following https://dev.to/hackersandslackers/integrate-plotly-dash-into-your-flask-app-5gbo which basically embeds dashboards into flask so you have access to all the flask goodies. Problem is that now, when I try to pwd protect the website, I can still go to the...
Password protected site Flask/Dash
I built a website following https://dev.to/hackersandslackers/integrate-plotly-dash-into-your-flask-app-5gbo which basically embeds dashboards into flask so you have access to all the flask goodies. Problem is that now, when I try to pwd protect the website, I can still go to the other pages (i.e the first one is not a...
[]
[]
[ "Each app.route function needs its own @flask_login.login_required decorator to prevent a non-authorized user from accessing it.\nIt also looks like your /home route redirects to itself in a loop, without ever returning a rendered template.\n" ]
[ -1 ]
[ "flask", "plotly_dash", "python" ]
stackoverflow_0074156510_flask_plotly_dash_python.txt
Q: How do I install pip for python 3.8 on Ubuntu without changing any defaults? I'm trying to install pip for Python 3.8 on an Ubuntu 18.04 LTS. I know this has been asked way too many times. But those questions do not concern keeping Ubuntu's defaults specifically. And the answers on those questions either don't w...
How do I install pip for python 3.8 on Ubuntu without changing any defaults?
I'm trying to install pip for Python 3.8 on an Ubuntu 18.04 LTS. I know this has been asked way too many times. But those questions do not concern keeping Ubuntu's defaults specifically. And the answers on those questions either don't work or go on to suggest something so drastic that it would break the system - e.g....
[ "While we can use pip directly as a Python module (the recommended way):\npython -m pip --version\n\nThis is how I installed it (so it can be called directly): \nFirstly, make sure that command pip is available and it isn't being used by pip for Python 2.7\nsudo apt remove python-pip\n\nNow if you write pip in the ...
[ 30, 8, 3, 3, 0, 0 ]
[]
[]
[ "pip", "python", "python_3.x", "ubuntu", "ubuntu_18.04" ]
stackoverflow_0063207385_pip_python_python_3.x_ubuntu_ubuntu_18.04.txt
Q: matplotlib 'plt.tight_layout()' function not working I have the following code: listofmodels = [resultmodeldistancearlylife,resultmodeldurationearlylife,resultmodeldistancenavigate,resultmodeldurationnavigate,resultmodeldistancetravel,resultmodeldurationtravel,resultmodeldistancevideo,resultmodeldurationvideo,resu...
matplotlib 'plt.tight_layout()' function not working
I have the following code: listofmodels = [resultmodeldistancearlylife,resultmodeldurationearlylife,resultmodeldistancenavigate,resultmodeldurationnavigate,resultmodeldistancetravel,resultmodeldurationtravel,resultmodeldistancevideo,resultmodeldurationvideo,resultmodeldistancelifestyle,resultmodeldurationlifestyle,resu...
[ "The title and labels, and maybe axes numbers, are placed in the space between the grids.\nThe default space is just enough for one text.\nYou have to increase the spacing with figure.add_gridspec()\nYou can also move the titles and labels outside the for loop.\nlistofmodels = [resultmodeldistancearlylife,resultmod...
[ 1, 0 ]
[]
[]
[ "matplotlib", "pandas", "plot", "python", "visual_studio_code" ]
stackoverflow_0074157765_matplotlib_pandas_plot_python_visual_studio_code.txt
Q: Python save data in variable this script get data from CSV file and then finds the correct mac address, and then prints the wifi channel. bssid = "AB:CD:CC:AA:33:AA" wifichannel = [] file = open("file-01.csv") next(file) reader = csv.reader(file) header = next(reader, None) for row in reader: if row: if r...
Python save data in variable
this script get data from CSV file and then finds the correct mac address, and then prints the wifi channel. bssid = "AB:CD:CC:AA:33:AA" wifichannel = [] file = open("file-01.csv") next(file) reader = csv.reader(file) header = next(reader, None) for row in reader: if row: if row[header.index("BSSID")] == bssid...
[ "if row[header.index(\"BSSID\")] == bssid:\n wifichannel.append(row[header.index(\" channel\")])\n\nwill add the item to the wifichannel list rather than just print the item - thus collecting your results into a single variable for later.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074158458_python.txt
Q: How can I create a dictionary showing which entries in column a are associated with which entries in column b in a pandas dataframe? I want to understand the relationships between the variables in columns A and B. They are string variables. For example df = pd.DataFrame({'First_Name': ['Agatha', 'Agatha','Hercule'...
How can I create a dictionary showing which entries in column a are associated with which entries in column b in a pandas dataframe?
I want to understand the relationships between the variables in columns A and B. They are string variables. For example df = pd.DataFrame({'First_Name': ['Agatha', 'Agatha','Hercule', 'Hercule'],... 'Last Name': ['Christie', 'Raisin', 'Poirot', 'Holmes']}) I want some kind of dat...
[ "df.groupby('First_Name',as_index=False)['Last Name'].agg(list)\n\n First_Name Last Name\n0 Agatha [Christie, Raisin]\n1 Hercule [Poirot, Holmes]\n\nwith removing duplicates\ndf.drop_duplicates().groupby('First_Name',as_index=False)['Last Name'].agg(list)\n\nChecking duplicates on First_Name and Last N...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074158530_pandas_python.txt
Q: What is making this Python code so slow? How can I modify it to run faster? I am writing a program in Python for a data analytics project involving advertisement performance data matched to advertisement characteristics aimed at identifying high performing groups of ads that share n similar characteristics. The da...
What is making this Python code so slow? How can I modify it to run faster?
I am writing a program in Python for a data analytics project involving advertisement performance data matched to advertisement characteristics aimed at identifying high performing groups of ads that share n similar characteristics. The dataset I am using has individual ads as rows, and characteristic, summary, and per...
[ "I think your biggest issue is the lines:\ntemp_df = df\nfor i in range(len(group[0])):\n temp_df = temp_df[(temp_df[group[0][i]] == vals_lst[i])]\n\nYou're filtering the entire dataframe while I think you're only actually interested in the KPI and ad_id columns. You could instead create a rolling mask, somethin...
[ 1 ]
[]
[]
[ "data_analysis", "loops", "pandas", "performance", "python" ]
stackoverflow_0074158253_data_analysis_loops_pandas_performance_python.txt
Q: Mocking a formatted datetime.datetime.now() I have this below function and tried pytesting it using mock as per the examples I found here. But unfortunately I am getting an AssertionError. def get_print_date(): now = datetime.datetime.now() return now.strftime("%d/%m/%Y %H:%M:%S") This is my pytest code: ...
Mocking a formatted datetime.datetime.now()
I have this below function and tried pytesting it using mock as per the examples I found here. But unfortunately I am getting an AssertionError. def get_print_date(): now = datetime.datetime.now() return now.strftime("%d/%m/%Y %H:%M:%S") This is my pytest code: import datetime from unittest.mock import MagicMo...
[ "From a quick look, you're asserting a function to a datetime object, i.e. assert get_print_date == FAKE_NOW, without calling the function. Doing the latter, in addition to changing the return type of the function from string to datetime, passes the test:\nimport datetime\nfrom unittest.mock import MagicMock\nimpor...
[ 1 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0074158430_python_unit_testing.txt
Q: Leetcode 4 binary search while loop I'm trying to solve leetcode problem 4 which needs you to do binary search. Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). This is my code: class Solution: ...
Leetcode 4 binary search while loop
I'm trying to solve leetcode problem 4 which needs you to do binary search. Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). This is my code: class Solution: def findMedianSortedArrays(self, nums1, ...
[ "The error you see is a little obscure because LeetCode is taking your solution code and wrapping it up for execution - but 1 hint you can tell from the error is that something is returning None when it's expecting a double.\nThe thing that's different is that if l >= r, none of the code in the while block will exe...
[ 1 ]
[]
[]
[ "binary_search", "python" ]
stackoverflow_0074158473_binary_search_python.txt
Q: Trying to get pixel data from a set of images and store in one single array Y = np.zeros((1,m)) X = np.zeros((ROWS*COLS*CHANNELS, m)) for i,image_file in enumerate(train_images): if 'cat' in image_file.lower(): Y[0,i] = 1 else: Y[0,i] = 0 img = cv2.imread(image_file, cv2.IMREAD_CO...
Trying to get pixel data from a set of images and store in one single array
Y = np.zeros((1,m)) X = np.zeros((ROWS*COLS*CHANNELS, m)) for i,image_file in enumerate(train_images): if 'cat' in image_file.lower(): Y[0,i] = 1 else: Y[0,i] = 0 img = cv2.imread(image_file, cv2.IMREAD_COLOR) img_resized = cv2.resize(img, (ROWS, COLS),interpolation=cv2.INTER_CUBIC...
[ "X[:, i] = np.squeeze(img_resized.reshape((ROWS*COLS*CHANNELS,1)))\n\nUsing the : operator, we are able to replace all values in that column.\n" ]
[ 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074158113_numpy_python.txt
Q: Set tkinter radio button to already selected button by default I am creating a SOS game board game using tkinter. I have a class createBoard(tk.Tk) that handles the gui for the game. My function playerChoice(self,game_window) is used to create two sets of radio buttons with the choice 'S' or 'O' for each player, ...
Set tkinter radio button to already selected button by default
I am creating a SOS game board game using tkinter. I have a class createBoard(tk.Tk) that handles the gui for the game. My function playerChoice(self,game_window) is used to create two sets of radio buttons with the choice 'S' or 'O' for each player, red and blue. I am trying to make it so each button defaults to an a...
[ "You can initialize a variable when you define it.\nblue_var = tk.StringVar(value='S')\n\nYou also need to make sure you keep a reference to the variables. You're using local variables when you should be using instance variables (eg: self.blue_var)\n" ]
[ 2 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074158328_python_tkinter.txt
Q: how to compare each elements in two array and find out which element is not equal without using loop There are two array ,i want to compare each elements in two array and find out which element is not equal without using loop for example ,in the following array , a=np.array ([1,2,5,0,1,2]) b=np.array ([1,3,5,...
how to compare each elements in two array and find out which element is not equal without using loop
There are two array ,i want to compare each elements in two array and find out which element is not equal without using loop for example ,in the following array , a=np.array ([1,2,5,0,1,2]) b=np.array ([1,3,5,1,0,0]) the correct result should be [False True False True True True] What I want is something like th...
[ "Simply use !=\na = np.array([1, 2, 5, 0, 1, 2])\nb = np.array([1, 3, 5, 1, 0, 0])\nc = a != b\n\nc:\narray([False, True, False, True, True, True])\n\n" ]
[ 2 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074158601_arrays_numpy_python.txt
Q: How to web scrape a list using beautifulsoup? I need help with scraping data from this website using beautifulsoup in python can anybody help me with it Please. I ve been juggling between documenation for hrs. All i need is to store all the names to a single array from these two links https://angelsname.com/Twin-B...
How to web scrape a list using beautifulsoup?
I need help with scraping data from this website using beautifulsoup in python can anybody help me with it Please. I ve been juggling between documenation for hrs. All i need is to store all the names to a single array from these two links https://angelsname.com/Twin-Boy-Names https://angelsname.com/Modern-Hindu-Baby-N...
[ "Select your elements and iterate the ResultSet:\n[e.td.get_text(strip=True) for e in soup.select('table tr:has(td)')]\n\nExample\nfrom bs4 import BeautifulSoup\nimport requests\n\nurl = 'https://angelsname.com/Twin-Boy-Names'\nresponse = requests.get(url)\n\nsoup = BeautifulSoup(response.text)\n[e.td.get_text(stri...
[ 0 ]
[]
[]
[ "beautifulsoup", "list", "python", "web_scraping" ]
stackoverflow_0074158543_beautifulsoup_list_python_web_scraping.txt
Q: Is there a way to make this algorithm faster I have a assignment for one of my algorithms class that requires us to create an algorithm that takes an array of positive integer values and splits them into 3 separate groups with highest sum of the 3 groups being as low as possible. i.e: input: [5,3,3,2,2,2,1] output...
Is there a way to make this algorithm faster
I have a assignment for one of my algorithms class that requires us to create an algorithm that takes an array of positive integer values and splits them into 3 separate groups with highest sum of the 3 groups being as low as possible. i.e: input: [5,3,3,2,2,2,1] output: 6. The groups would be [[5,1],[3,3],[2,2,2]] whe...
[ "def func(List):\n List = [List[i:i+3] for i in range(0,len(List),3)]\n while 1:\n ma , mi = max(List,key=sum),min(List,key=sum)\n if ma == mi:\n return List\n v = min(ma)\n mi.append(v)\n ma.remove(v)\nprint(func([5,3,3,2,2,2,1]))\n\n" ]
[ 0 ]
[]
[]
[ "algorithm", "performance", "python", "recursion", "runtime" ]
stackoverflow_0074157918_algorithm_performance_python_recursion_runtime.txt
Q: KivyMD: Automatic resizing of MDBoxLayout and MDLabel based on text length I'm trying to make a simple chat that auto-sizes the message box to fit text of different lengths. For some reason, when the text is not very long, everything works well. But with increasing text length in the field and its transition to th...
KivyMD: Automatic resizing of MDBoxLayout and MDLabel based on text length
I'm trying to make a simple chat that auto-sizes the message box to fit text of different lengths. For some reason, when the text is not very long, everything works well. But with increasing text length in the field and its transition to the second line, the program doesn't work correctly. I know that the problem is in...
[ "There seems to be an interaction between the MDBoxLayout and the MDLabels within it causing an endless loop. You can eliminate the adaptive_height from the Chat rule with a simple calculation of its height. Here is a modified version of that <Chat> rule:\n<Chat>:\n size_hint_y: None\n height: lab1.height + l...
[ 0 ]
[]
[]
[ "kivy", "kivymd", "python" ]
stackoverflow_0074157481_kivy_kivymd_python.txt
Q: Assign the max value of a group to all rows in the next group Given the following dataframe: col_A col_B 1 1 1 2 1 3 2 4 2 5 2 6 3 7 3 8 3 9 How would I assign the max value of col_B from a group in col_A to all rows in the next (in ascending order) group in col_A? Output desired is as follows: col_A c...
Assign the max value of a group to all rows in the next group
Given the following dataframe: col_A col_B 1 1 1 2 1 3 2 4 2 5 2 6 3 7 3 8 3 9 How would I assign the max value of col_B from a group in col_A to all rows in the next (in ascending order) group in col_A? Output desired is as follows: col_A col_B max_col_B_ from_prev_col_A_group 1 1 ...
[ "Combine merge with groupby+shift:\n(df.merge(df.groupby(\"col_A\").col_B.max().shift(1),\n on=\"col_A\", how=\"left\")\n .rename(columns={\"col_B_y\": \"max_col_B_ from_prev_col_A_group\"}))\n\n" ]
[ 1 ]
[]
[]
[ "group_by", "pandas", "python" ]
stackoverflow_0074158640_group_by_pandas_python.txt
Q: Creating a quiz using TCP socket programming I am trying to make a quiz game that runs over a TCP server/client. Can anyone help me get the server to send the second question after the user enters the answer on the client side? Right now when I enter my first answer, whether its right or wrong the second question ...
Creating a quiz using TCP socket programming
I am trying to make a quiz game that runs over a TCP server/client. Can anyone help me get the server to send the second question after the user enters the answer on the client side? Right now when I enter my first answer, whether its right or wrong the second question is never sent. I included my code below for refere...
[ "There are some other potential problems with your current code, but I just want to address your specific issue.\nlook what your server does:\n\nIt accepts a connection\nWaits for receiving bytes\nSends some bytes to the client socket\n\nthen ? It again stops at the line connectionSocket, addr = serverSocket.accept...
[ 0, 0 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0074157272_python_sockets.txt
Q: django-import-export: cannot exclude id field during import : KeyError: u'id' On Django-1.9.6, django-import-export-0.5 When I try to upload CSV without "id" field throws this error. Line number: 1 - u'id' 13173474, Harry McDade, 10.harry.asas@asasasas.com Traceback (most recent call last): File "/Users/isanka/de...
django-import-export: cannot exclude id field during import : KeyError: u'id'
On Django-1.9.6, django-import-export-0.5 When I try to upload CSV without "id" field throws this error. Line number: 1 - u'id' 13173474, Harry McDade, 10.harry.asas@asasasas.com Traceback (most recent call last): File "/Users/isanka/dev/venv/edxubase/lib/python2.7/site-packages/import_export/resources.py", line 434, ...
[ "Seems \"django-import-export\" still using the default one 'id'. for the time been, included a column 'id' in the header in CSV file and excluded importing in resources.py\nclass edxUserResource(resources.ModelResource):\n\n class Meta:\n model = edxUser\n skip_unchanged = True\n report_ski...
[ 8, 1, 0, 0 ]
[]
[]
[ "django", "django_import_export", "python" ]
stackoverflow_0045028975_django_django_import_export_python.txt
Q: Creating a network-like figure a truss in Python I would like to create the graphic of a truss. I have two lists of lists; one gives the bar number and the nodes that make them, it looks like this: elements = [[1, 1, 2], [2, 2, 3], [3, 3, 4], [4, 4, 5], [5, 5, 1], [6, 1, 4], [7, 2, 4], [8, 4, 6], [9, 6, 5]] For e...
Creating a network-like figure a truss in Python
I would like to create the graphic of a truss. I have two lists of lists; one gives the bar number and the nodes that make them, it looks like this: elements = [[1, 1, 2], [2, 2, 3], [3, 3, 4], [4, 4, 5], [5, 5, 1], [6, 1, 4], [7, 2, 4], [8, 4, 6], [9, 6, 5]] For example, element one is composed by node 1 and node 2. ...
[ "\nYour question is too wide, I provide an answer only to the first part of it, given a list of nodal coordinates and a list of connectivities, how to draw a truss?\nFirst, if you are implementing a program for truss analysis, you will probably use a dataclass and store much more info about each one of the bars, bu...
[ 5, 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074155713_matplotlib_python.txt
Q: pandas - Assigning loc of dataframe to loc of other dataframe doesn't work I am trying to use loc to selectively copy column values from one dataframe to a slice of another dataframe. However, assigning to the loc of the target dataframe leaves it completely unchanged. This is my code, everything other than the la...
pandas - Assigning loc of dataframe to loc of other dataframe doesn't work
I am trying to use loc to selectively copy column values from one dataframe to a slice of another dataframe. However, assigning to the loc of the target dataframe leaves it completely unchanged. This is my code, everything other than the last line is just context, (probably?) unrelated to the problem: def insert_gps_di...
[ "When you call df.iloc[0] you get a Series, but if you call df.iloc[df.idxmin()] (where df.idxmin() = 0) you get a Dataframe.\nSo do gps_start_idx = int(gps_start_idx) and gps_stop_idx = int(gps_stop_idx) and then run it through the df.loc[].\n(putting this as an answer instead of comment since it did work for me i...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074158652_dataframe_pandas_python.txt
Q: TypeError: sqlrunner.run_query() missing 1 required positional argument: 'sql_string' Iam getting in error while error executing I coulf not find out the issue can anyone help me with this TypeError: sqlrunner.run_query() missing 1 required positional argument: 'sql_string' ''' import psycopg2 class sqlrunner(): ...
TypeError: sqlrunner.run_query() missing 1 required positional argument: 'sql_string'
Iam getting in error while error executing I coulf not find out the issue can anyone help me with this TypeError: sqlrunner.run_query() missing 1 required positional argument: 'sql_string' ''' import psycopg2 class sqlrunner(): hostname = 'localhost' database = 'postgres' username = 'postgres' pwd = 'N...
[ "You have the query string in the method.\nTwo options:\n\nPass the query string as variable to the method and remove it from the method:\n\n...\ndb.run_query(\"drop table if EXISTS my_table\")\n\n\nOr don't add a parameter to the signature of the method:\n\n...\ndef run_query(self):\n...\n\n" ]
[ 0 ]
[]
[]
[ "java", "postgresql", "python" ]
stackoverflow_0074128783_java_postgresql_python.txt
Q: Using regex to find email address and other values in Python String so I have a string that possesses data I need to extract for my main program. It looks something like this: string = "[email:first.last@gmail.com][days:90]" From this string I want to extract the data within the brackets and be able to split emai...
Using regex to find email address and other values in Python String
so I have a string that possesses data I need to extract for my main program. It looks something like this: string = "[email:first.last@gmail.com][days:90]" From this string I want to extract the data within the brackets and be able to split email and the email address by the colon so that I can store the word email a...
[ "So, in this case, you can just use a regex to extract what is between the brackets, then split on a colon character to get the param type and param, something like:\n[s.split(\":\") for s in re.findall(r\"\\[(.+?)\\]\", string)]\n\nSo your code would be something like:\nimport re\n\nstring = \"[email:first.last@gm...
[ 1, 1 ]
[]
[]
[ "parsing", "python", "regex", "string" ]
stackoverflow_0074158707_parsing_python_regex_string.txt
Q: Extrating Json response PYTHON I need help my friends, it's my first project with Api, and I'm not able to pull the data from the Api, it returns the following error. Script: response = data.json() for number in response['mobile_phones']: dd = resposta['ddd'] num = resposta['number'] whatsapp = respos...
Extrating Json response PYTHON
I need help my friends, it's my first project with Api, and I'm not able to pull the data from the Api, it returns the following error. Script: response = data.json() for number in response['mobile_phones']: dd = resposta['ddd'] num = resposta['number'] whatsapp = resposta['whatsapp_datetime'] print(dd...
[ "You can do this,\nfor number in response[0]['mobile_phones']:\n dd = number['ddd']\n num = number['number']\n whatsapp = number['whatsapp_datetime']\n print(dd, num, whatsapp)\n\nresponse is a list, which has dictionary of values.\nThe list you are looking its need to access like this, response[0]['mob...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074158757_python.txt
Q: Huggingface datasets ValueError I am trying to load a dataset from huggingface organization, but I am getting the following error: ValueError: Couldn't cast string -- schema metadata -- pandas: '{"index_columns": [{"kind": "range", "name": null, "start": 0, "' + 686 to {'text': Value(dtype='string', id=None)} beca...
Huggingface datasets ValueError
I am trying to load a dataset from huggingface organization, but I am getting the following error: ValueError: Couldn't cast string -- schema metadata -- pandas: '{"index_columns": [{"kind": "range", "name": null, "start": 0, "' + 686 to {'text': Value(dtype='string', id=None)} because column names don't match I used ...
[ "I solved this error by streaming the dataset.\nfrom datasets import load_dataset\ndataset = load_dataset(\"datasetFile\", use_auth_token=True, streaming= True)\n\n\n", "According to https://github.com/huggingface/datasets/issues/3700#issuecomment-1035400186, you actually want to use load_from_disk:\nfrom dataset...
[ 1, 0 ]
[]
[]
[ "huggingface", "huggingface_datasets", "nlp", "python" ]
stackoverflow_0071646831_huggingface_huggingface_datasets_nlp_python.txt
Q: How to execute the For n times using a specific column of an excel table in python? I want to repeat a process by a number from a column of my data. How can I do it using For? It's something like column_repetition 2 2 3 each line of the column_repetition the automation repeats. for i, range(column_repeti...
How to execute the For n times using a specific column of an excel table in python?
I want to repeat a process by a number from a column of my data. How can I do it using For? It's something like column_repetition 2 2 3 each line of the column_repetition the automation repeats. for i, range(column_repetion): recebimento=data.iloc[i, data.columns.get_loc('recebimento')] ite...
[ "With the information given I assume you want to use two loops. The first, to iterate over all rows and the second to repeat your code n times.\nfor row in df.column_repetition:\n for i in range(row):\n print(i)\n\nIf you give us more information, we can probably come up with a better solution to your pro...
[ 0 ]
[]
[]
[ "for_loop", "python", "selenium" ]
stackoverflow_0074101783_for_loop_python_selenium.txt
Q: Im new to coding and am trying to make myself a calculator in pyton idle 3.10 64 bit and it isnt working I've written this code so far: OPR = input(''' which functions do you wish to use? a for arithmetic g for graphic ''') CON = "yes" while CON == "yes" and OPR == "a": OPR = input(''' Please type i...
Im new to coding and am trying to make myself a calculator in pyton idle 3.10 64 bit and it isnt working
I've written this code so far: OPR = input(''' which functions do you wish to use? a for arithmetic g for graphic ''') CON = "yes" while CON == "yes" and OPR == "a": OPR = input(''' Please type in the math operation you would like to complete: + for addition - for subtraction * for multiplica...
[ "I've reorganized your code so that it works the way I think you are expecting. I don't do anything with the first question's answer; that's an exercise left for the reader.\nopr = input('''\nwhich functions do you wish to use?\na for arithmetic\ng for graphic\n ''')\n\niteration = 0\nwhile True:\n\n opr = i...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074158782_python.txt
Q: pandas conditional with .loc to combine rows by concatenating strings I have a dataframe in which some of the data spills in to the next row, for example with 2-(Acetyloxy)-1-phenylethanone, the 'none' goes to the next row, also the solubility is in three rows, so ends up looking like this: x = pd.DataFrame([ ...
pandas conditional with .loc to combine rows by concatenating strings
I have a dataframe in which some of the data spills in to the next row, for example with 2-(Acetyloxy)-1-phenylethanone, the 'none' goes to the next row, also the solubility is in three rows, so ends up looking like this: x = pd.DataFrame([ ['90', '2-(Acetyloxy)-1-phenyletha-', 'i H2O; vs EtOH,'], [np.nan, 'ne...
[ "IIUC\n# use number to group together the rows\ndf['number'].ffill(inplace=True)\n\n# make the null value as empty\ndf.fillna('', inplace=True)\n\n# groupby on number and combine the name and solubility as a single row\ndf.groupby(['number'], as_index=False)[['name','solubility']].agg({'name': ''.join, 'solubility'...
[ 2 ]
[]
[]
[ "group_by", "pandas", "python" ]
stackoverflow_0074158590_group_by_pandas_python.txt
Q: Issues understanding custom iterators in Python Good afternoon, I've been stumped with this for a while now. I have a doubly linked list with sentinel nodes created, and I'm trying to create a custom iterator to loop through said doubly linked list. My implementation of this is as follows: def __iter__(self): ...
Issues understanding custom iterators in Python
Good afternoon, I've been stumped with this for a while now. I have a doubly linked list with sentinel nodes created, and I'm trying to create a custom iterator to loop through said doubly linked list. My implementation of this is as follows: def __iter__(self): self.cur = self.__header return self...
[ "The loop in your __next__ is ostensibly being used to determine the index of the list node, but this doesn't work because it's starting at the current node, not the beginning of the list. The current node is of course always the 0th node relative to itself, but the node you're returning is the 0th node relative t...
[ 0 ]
[]
[]
[ "iterator", "python", "python_3.x" ]
stackoverflow_0074158752_iterator_python_python_3.x.txt
Q: django filter: How to filter results with multiple values I am working on Django and I need to filter records eg: table: Person name age David Abraham Benj 18 so, if I run this, Person.objects.filter(name__icontains="David Abraham") it is working but if I run this, Person.objects.filter(name__icontains="David B...
django filter: How to filter results with multiple values
I am working on Django and I need to filter records eg: table: Person name age David Abraham Benj 18 so, if I run this, Person.objects.filter(name__icontains="David Abraham") it is working but if I run this, Person.objects.filter(name__icontains="David Benj") it is not working any idea how it works? framewo...
[ "You need to use Q objects in order to chain multiple SQL ILIKE operations, which is what the __icontains operator produces in the backgroud.\nTry this:\nfrom django.db.models import Q\n\nPerson.objects.filter(\n Q(name__icontains=\"David\") &\n Q(name__icontains=\"Benj\")\n)\n\n\n", "Person.objects.filter(...
[ 3, 1 ]
[]
[]
[ "django", "django_filter", "postgresql", "python", "python_3.x" ]
stackoverflow_0074158781_django_django_filter_postgresql_python_python_3.x.txt
Q: AttributeError: 'Bot' object has no attribute 'db' I a bot using discord.py and using aiosqlite for a leveling database. Sometimes when I start up my bot, I get this error, and Im not sure what is causing it. It doesn't happen every time I start my bot. I think it happens when my bot is in the middle of starting u...
AttributeError: 'Bot' object has no attribute 'db'
I a bot using discord.py and using aiosqlite for a leveling database. Sometimes when I start up my bot, I get this error, and Im not sure what is causing it. It doesn't happen every time I start my bot. I think it happens when my bot is in the middle of starting up and someone sends a message in the server? Im not sure...
[ "As said in the comment, you should use setup_hook if you want to setup something before the bot starts.\nYou will need to subclass your bot though:\n# First you need to subclass your bot\nclass MyBot(commands.Bot):\n # Use the init function to attach a variable to your bot\n def __init__(self, *args, **kwarg...
[ 0 ]
[]
[]
[ "aiosqlite", "discord", "discord.py", "python", "sqlite" ]
stackoverflow_0074143738_aiosqlite_discord_discord.py_python_sqlite.txt
Q: Django doesn't redirect to the same page I'm working on a django project website. When submitting a form I need to save the data and show a message with from django.contrib import messagesmodule. It works perfectly with saving data but it never shows the message and redirecting to the same page. Views.py class. de...
Django doesn't redirect to the same page
I'm working on a django project website. When submitting a form I need to save the data and show a message with from django.contrib import messagesmodule. It works perfectly with saving data but it never shows the message and redirecting to the same page. Views.py class. def showIndex(request): if request.method ==...
[ "You have to pass the messages variable to the render method:\nrender(request,'index.html', {'messages': messages})\n\n" ]
[ 3 ]
[]
[]
[ "django", "django_forms", "django_models", "django_views", "python" ]
stackoverflow_0074158925_django_django_forms_django_models_django_views_python.txt
Q: Error: no such table when extending Abstract User Model I wanted to extend the Base Abstract User Model within Django to have some other Fields: class Student(AbstractUser): birth = models.DateField(default=datetime.date.today) street = models.CharField(max_length=20) street_number = models.IntegerFiel...
Error: no such table when extending Abstract User Model
I wanted to extend the Base Abstract User Model within Django to have some other Fields: class Student(AbstractUser): birth = models.DateField(default=datetime.date.today) street = models.CharField(max_length=20) street_number = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(99)]) ...
[ "Try in first time to run:\npython manage.py makemigrations\npython manage.py migrate\n\nWithout put the app name to migration process\n", "You cannot define \"address\" like this. Database column is not for string concatenation of other columns, nor any calculation. It can cause error.\n" ]
[ 0, 0 ]
[]
[]
[ "database", "django", "model", "python" ]
stackoverflow_0074157218_database_django_model_python.txt
Q: Invalid Python interpreter selected for the project I use Pycharm, and whenever I move a project to another folder, it says "invalid python interpreter selected for the project". I think it happens because the path to venv has changed. I tried Configure Python Interpreter > Add Interpreter > Select "Existing Envir...
Invalid Python interpreter selected for the project
I use Pycharm, and whenever I move a project to another folder, it says "invalid python interpreter selected for the project". I think it happens because the path to venv has changed. I tried Configure Python Interpreter > Add Interpreter > Select "Existing Environment" with the new path to venv. I was expecting this t...
[ "Virtualenv has hardcoded path inside the bin/activate file, which will fail when you move the virtualenv.\nOne way is to recreate your virtualenv. Another way is to open the file bin/activate and find this line VIRTUAL_ENV='/private/tmp/test2/.venv' and replace it with your new virtualenv path.\nMy virtualenv is c...
[ 3, 0 ]
[]
[]
[ "interpreter", "pycharm", "python", "python_venv" ]
stackoverflow_0068222454_interpreter_pycharm_python_python_venv.txt
Q: Happy Numbers doesn't update variable I've been coding for about 3 months. Could someone help me understand why my code isn't working? I could look up the answer, but I'd really like to figure out what is going wrong. It runs perfectly the first time through the code, but while it is While-Looping, x always stays ...
Happy Numbers doesn't update variable
I've been coding for about 3 months. Could someone help me understand why my code isn't working? I could look up the answer, but I'd really like to figure out what is going wrong. It runs perfectly the first time through the code, but while it is While-Looping, x always stays as the number inserted into the function. T...
[ "The PROBLEM is that you are not resetting digit_list and squared_list in every loop, so they just keep getting bigger and bigger. Move their initialization into the while loop, or use a list comprehension instead of a loop.\nConsider this for your loop:\n while True:\n digit_list = [int(digit) for digit ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074158938_python.txt
Q: Http Post data from Python to net core app I am trying to send a file from a Python script to my .net core webserver. In Python I am doing this using the requests library, and my code looks like so. filePath = "run-1.csv" with open(filePath, "rb") as postFile: file_dict = {filePath: postFil...
Http Post data from Python to net core app
I am trying to send a file from a Python script to my .net core webserver. In Python I am doing this using the requests library, and my code looks like so. filePath = "run-1.csv" with open(filePath, "rb") as postFile: file_dict = {filePath: postFile} response = requests.post(serv...
[ "Solved my issue - the problem was that in Python I was assigning my file to my upload dictionary with the actual file name \"./run1.csv\" rather than a literal string \"file\"\nUpdating this fixed my issue.\nfile_dict = {\"file\": postFile}\n\nThis is what I believe @nalnpir mentioned above.\nI figured this out by...
[ 1, 0 ]
[]
[]
[ ".net_core", "asp.net_core", "asp.net_mvc", "c#", "python" ]
stackoverflow_0064779410_.net_core_asp.net_core_asp.net_mvc_c#_python.txt
Q: How can we Check if something other than a value in a list in Python? I want to know if there is a value other than a specific value in a list in python, for example: given a list lst = [0,0,0,0,0,0,0] How can I check if there is a value other than 0 in it like 1 or 2 or 3 or any number other than 0 and its posi...
How can we Check if something other than a value in a list in Python?
I want to know if there is a value other than a specific value in a list in python, for example: given a list lst = [0,0,0,0,0,0,0] How can I check if there is a value other than 0 in it like 1 or 2 or 3 or any number other than 0 and its position? Example : lst = [0,0,0,0,1,0,0,0] The check operation should bring a...
[ "to get the positions and values of nonzero elements you can do this:\nlst = [0,0,0,0,1,0,0,0,2]\nlist(filter(lambda x: x[1]!=0, enumerate(lst))) # [(4, 1), (8, 2)]\n\n", "You can use enumerate to get values plus their index in the list.\nlst = [0,0,0,0,1,0,0,0]\nbaddies = [i for i,val in enumerate(lst)]\nhas_ba...
[ 2, 1, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074157557_python_python_3.x.txt
Q: Scrapy Increase robustness when scraping I am trying my best to search for a setting on the Scrapy spider when the following condition occurs. In the middle of my scraping activity If I have a power failure my ISP goes down and the behavior i am expecting is Scrapy should not give up. rather wait infinitely for ...
Scrapy Increase robustness when scraping
I am trying my best to search for a setting on the Scrapy spider when the following condition occurs. In the middle of my scraping activity If I have a power failure my ISP goes down and the behavior i am expecting is Scrapy should not give up. rather wait infinitely for power to be restored and continue scraping by ...
[ "There is no built in setting that will do this, however this can still be implemented rather easily.\nThe way that seems the most straight forward to me would be to catch the response_received signal in your spider and check for the specific error code you receive when your ISP goes down. When this happens you ca...
[ 2 ]
[]
[]
[ "python", "scrapy" ]
stackoverflow_0074155257_python_scrapy.txt
Q: ROS2 ImportError: cannot import name 'generate_py' from 'rosidl_generator_py' I got an ImportError while trying to create a custom interface following the ros2 tutorial Creating custom msg and srv files. The project looks like this: src/tutorial_interfaces/ ├── CMakeLists.txt ├── include │   └── tutorial_interfac...
ROS2 ImportError: cannot import name 'generate_py' from 'rosidl_generator_py'
I got an ImportError while trying to create a custom interface following the ros2 tutorial Creating custom msg and srv files. The project looks like this: src/tutorial_interfaces/ ├── CMakeLists.txt ├── include │   └── tutorial_interfaces ├── msg │   └── Num.msg ├── package.xml ├── src └── srv └── AddThreeInts.srv...
[ "I'm Facing the same issue (same system)\nSystem: Ubuntu 22.04 + ROS2 Humble\ncolcon build ─╯\n[0.370s] WARNING:colcon.colcon_core.package_selection:Some selected packages are already built in one or more underlay workspaces:\n...
[ 3, 2, 0, 0 ]
[]
[]
[ "python", "ros", "ros2" ]
stackoverflow_0072752937_python_ros_ros2.txt
Q: What else besides grid and weights are needed to make widgets proportionally sized? A Frame that has 2 rows and 1 column can be weighted. From my understanding, this will set the growth from some arbitrary position to be proportional. So something like: self.grid_columnconfigure(0, weight=1) self.grid_rowc...
What else besides grid and weights are needed to make widgets proportionally sized?
A Frame that has 2 rows and 1 column can be weighted. From my understanding, this will set the growth from some arbitrary position to be proportional. So something like: self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) self.grid_rowconfigure(1, weight=10) # # ============ fram...
[ "\nFrom my understanding, this will set the growth from some arbitrary position to be proportional\n\nNot so much arbitrary, but rather initial. Grid will compute the layout based on the requested size of the widgets. If there is any unallocated space left over, the space will be allocated to each row or column pro...
[ 1 ]
[]
[]
[ "python", "tkinter", "tkinter_layout" ]
stackoverflow_0074158975_python_tkinter_tkinter_layout.txt
Q: Python: Multiple controlled while loops inside while loop Please help me to solve this issue! Python 3 code: x=True while x: a=input('Enter an num:') y=a.isdigit() while y: b=input('Enter an alphabet:') z=b.isalpha while z: print('This is a nested while loop')...
Python: Multiple controlled while loops inside while loop
Please help me to solve this issue! Python 3 code: x=True while x: a=input('Enter an num:') y=a.isdigit() while y: b=input('Enter an alphabet:') z=b.isalpha while z: print('This is a nested while loop') z=False y=False x=False...
[ "In evaluating your code I did some simplification to the code along with changing out some of the \"while\" statements with \"if\" statements. Following is a revised code snippet.\nwhile True:\n a=input('Enter an number: ')\n if a.isdigit(): # Instead of storing a boolean value, plus it works with the e...
[ 1 ]
[]
[]
[ "exit", "loops", "nested_loops", "python", "while_loop" ]
stackoverflow_0074157984_exit_loops_nested_loops_python_while_loop.txt
Q: Matplotlib aspect ratio of subplots with shared axes I have three matplotlib subplots with some shared axes, and I would like to set the axis ratio for one of them. I have tried the solution proposed here https://stackoverflow.com/a/66793156/6843348 and it only affects one of the subplots while messing the others...
Matplotlib aspect ratio of subplots with shared axes
I have three matplotlib subplots with some shared axes, and I would like to set the axis ratio for one of them. I have tried the solution proposed here https://stackoverflow.com/a/66793156/6843348 and it only affects one of the subplots while messing the others up. Any suggestions? My code is below. import matplotli...
[ "Since adjustable='box-forced' was apparently removed in recent matplotlib versions, you could use the following work-around and plot the main plot with some aspect ratio first and add the additional axes thereafter.\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import make_axes...
[ 1 ]
[]
[]
[ "matplotlib", "python", "subplot" ]
stackoverflow_0074134073_matplotlib_python_subplot.txt
Q: How do I fix TypeError: cannot convert the series to when column in df has nan? I have a dataframe dfooc Name AddressId XYZ nan ABC <memory at 0x7f145136ca10> HIJ nan How do I convert this AddressId column to float type? it is currently - Name: AddressId, Length: 346498, dtype: object I tried dfooc['AddressI...
How do I fix TypeError: cannot convert the series to when column in df has nan?
I have a dataframe dfooc Name AddressId XYZ nan ABC <memory at 0x7f145136ca10> HIJ nan How do I convert this AddressId column to float type? it is currently - Name: AddressId, Length: 346498, dtype: object I tried dfooc['AddressId'] = int(float(dfooc['AddressId'])) raise TypeError(f"cannot convert the series to {c...
[ "You can do :\ndfooc['AddressId'] = dfooc['AddressId'].astype('float', errors = 'ignore')\n\nerrors control raising of exceptions on invalid data for provided dtype according to the documentation, set to ignore, it will ssuppress exceptions and on error return original object (i.e. nan).\nOr you can fillna first an...
[ 1 ]
[]
[]
[ "pandas", "precision", "python", "typeerror" ]
stackoverflow_0074158860_pandas_precision_python_typeerror.txt
Q: What is the easiest way to convert a binned feature to a numeric categorical feature? Converting a numeric feature into a categorical binned feature is pretty simple when using pandas.cut(). However, say you want to do the opposite by converting a binned object feature into a numeric categorical feature (1, 2, 3, ...
What is the easiest way to convert a binned feature to a numeric categorical feature?
Converting a numeric feature into a categorical binned feature is pretty simple when using pandas.cut(). However, say you want to do the opposite by converting a binned object feature into a numeric categorical feature (1, 2, 3, 4... etc.), what would be the easiest way to do so? Distinct binned categories: ["0-9%", "1...
[ "Create a dictionary showing the current bin and the number you want to convert it to and then you the replace function\nconversion={\"0-9%\":1, \"10-19%\":2, \"20-29%\":2,.....etc }\ndf.replace(conversion)\n\n", "There is already a numerical information in a Categorical.\nUse cat.codes to access it:\ndf = pd.Dat...
[ 2, 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074158985_pandas_python.txt
Q: python: How concatenate pandas dataframes with VAEX I would like to join thousands of dataframes into one VAEX dataframe Following the documentation I have: https://vaex.readthedocs.io/en/latest/api.html?highlight=concat#vaex.concat I do: df_vaex = vaex.DataFrame() for i,file in enumerate(files): df = pd.read_...
python: How concatenate pandas dataframes with VAEX
I would like to join thousands of dataframes into one VAEX dataframe Following the documentation I have: https://vaex.readthedocs.io/en/latest/api.html?highlight=concat#vaex.concat I do: df_vaex = vaex.DataFrame() for i,file in enumerate(files): df = pd.read_pickle(file) df_vx = vaex.from_pandas(df=df, copy_ind...
[ "If you want to use vaex to concat dataframes you need to do it in the following way:\n\nread in all dataframes first\ncreate a list of dataframes\nuse df_final = vaex.concat(list_of_dataframes)\n\nSo your code would look something like this:\nlist_of_dataframes = []\n\nfor i, file in enumerate(files)\n pdf = pd...
[ 0 ]
[]
[]
[ "concatenation", "pandas", "python", "vaex" ]
stackoverflow_0074152913_concatenation_pandas_python_vaex.txt
Q: Error with referencing a variable before assignment python I have a for loop as part of a larger function: for table in tables_list: if table["file"] == file: table_name = table["table_name"] break log.info(f"table: {table_name}") I am getting an error saying the variable is being referenced before...
Error with referencing a variable before assignment python
I have a for loop as part of a larger function: for table in tables_list: if table["file"] == file: table_name = table["table_name"] break log.info(f"table: {table_name}") I am getting an error saying the variable is being referenced before assignment UnboundLocalError: local variable 'table_name' refer...
[ "You need to declare the table_name before the loop there might be a chance for unsatisfied this condition table[\"file\"] == file so table_name will be undeclared at that moment.\ntable_name = None # declare here\nfor table in tables_list:\n if table[\"file\"] == file:\n table_name = table[\"table_name\"]\n...
[ 0 ]
[]
[]
[ "python", "reference", "variable_assignment" ]
stackoverflow_0074159095_python_reference_variable_assignment.txt
Q: Failed processing format-parameters; Python 'member' cannot be converted to a MySQL type Unable to convert discord.Member to a acceptable mysql type: @app_commands.checks.cooldown(1, 3.0, key=lambda i: (i.guild_id, i.user.id)) @app_commands.command(name = "warn", description = "hi") async def warn(self, i...
Failed processing format-parameters; Python 'member' cannot be converted to a MySQL type
Unable to convert discord.Member to a acceptable mysql type: @app_commands.checks.cooldown(1, 3.0, key=lambda i: (i.guild_id, i.user.id)) @app_commands.command(name = "warn", description = "hi") async def warn(self, interaction: discord.Interaction, user: discord.Member, reason: str, amount: str) -> None: ...
[ "Your column is named ID which suggests you want to store an ID in there, but the value you're passing is a discord.Member instance. You can't insert that into a database. MYSQL has no idea how to take a discord.Member object and store it in a db.\nIf you want to store the ID, access the attribute using user.id and...
[ 0 ]
[]
[]
[ "discord.py", "mysql", "python" ]
stackoverflow_0074158703_discord.py_mysql_python.txt
Q: VSCode doesn't show poetry virtualenvs in select interpreter option I need help. VSCode will NEVER find poetry virtualenv interpreter no matter what I try. Installed poetry Python package manager using a standard $ curl method as explained in the official documentation. Started a project by $ poetry new finance-...
VSCode doesn't show poetry virtualenvs in select interpreter option
I need help. VSCode will NEVER find poetry virtualenv interpreter no matter what I try. Installed poetry Python package manager using a standard $ curl method as explained in the official documentation. Started a project by $ poetry new finance-essentials_37-64, installed poetry environment with $ poetry install. So...
[ "You just need to type in your shell:\npoetry config virtualenvs.in-project true\n\nThe virtualenv will be created inside the project path and vscode will recognize.\n\nIf you already have created your project, you need to re-create the virtualenv to make it appear in the correct place:\npoetry env list # shows th...
[ 213, 52, 5, 3 ]
[]
[]
[ "python", "python_poetry", "visual_studio_code" ]
stackoverflow_0059882884_python_python_poetry_visual_studio_code.txt
Q: How do you check if all the values in a column in a dataframe exist in another column in another dataframe using Vaex? I have a dataframe with 160,000 rows and I need to know if these values exist in another column in another different dataframe that has over 7 million rows using Vaex. I have tried doing this in p...
How do you check if all the values in a column in a dataframe exist in another column in another dataframe using Vaex?
I have a dataframe with 160,000 rows and I need to know if these values exist in another column in another different dataframe that has over 7 million rows using Vaex. I have tried doing this in pandas but it takes way too long to run. Once I run this code I would like a list or a column that says either "True" or "Fal...
[ "There are few tricks you can do.\nSome ideas:\n\nyou can try inner join, and then get the list of unique values, which appear in both dataframes. Then you can use the isin method in the smaller dataframe and that list to get your answer.\n\nDunno if this will work out of the box, but it would be something like:\nd...
[ 0 ]
[]
[]
[ "python", "vaex" ]
stackoverflow_0074100495_python_vaex.txt
Q: Bioformats python module The following python code: import javabridge import bioformats javabridge.start_vm(class_path=bioformats.JARS) gives this error: Traceback (most recent call last): File "C:\Users\Joshua\Documents\test.py", line 3, in javabridge.start_vm(class_path=bioformats.JARS) AttributeError: ...
Bioformats python module
The following python code: import javabridge import bioformats javabridge.start_vm(class_path=bioformats.JARS) gives this error: Traceback (most recent call last): File "C:\Users\Joshua\Documents\test.py", line 3, in javabridge.start_vm(class_path=bioformats.JARS) AttributeError: module 'bioformats' has no att...
[ "Exactly same problem, and I tried many ways including:\n\npip install python-bioformats in python3\n\nconda install python-bioformats in python2\n\n\nand none of them works.\nFinally, the github version saved me: https://github.com/CellProfiler/python-bioformats. Download all of them, unzip, cd to your folder, and...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0056934631_python.txt
Q: Pandas - How to Create Month and Year Column from DateTime Column I have the following data (I purposely created a DateTime column from the string column of dates because that's how I am receiving the data): import numpy as np import pandas as pd data = pd.DataFrame({"String_Date" : ['10/12/2021', '9/...
Pandas - How to Create Month and Year Column from DateTime Column
I have the following data (I purposely created a DateTime column from the string column of dates because that's how I am receiving the data): import numpy as np import pandas as pd data = pd.DataFrame({"String_Date" : ['10/12/2021', '9/21/2021', '2/12/2010', '3/25/2009']}) #Create DateTime columns ...
[ "You can do:\ndata[\"Month & Year Date\"] = (\n data[\"Date\"].dt.month_name() + \"-\" + data[\"Date\"].dt.year.astype(str)\n)\n\nprint(data)\n\nPrints:\n String_Date Date Month & Year Date\n0 10/12/2021 2021-10-12 October-2021\n1 9/21/2021 2021-09-21 September-2021\n2 2/12/2010 2010-02-12 ...
[ 0, 0, 0, 0 ]
[]
[]
[ "group_by", "pandas", "python" ]
stackoverflow_0074159098_group_by_pandas_python.txt
Q: How to make a tiff z-stack conserving or adding metadata? I have a number of tiff files that I would like to combine to a z-stack using python. The individual files have metadata that I would like to conserve (OME in my case), in particular the information on which z slice it is. Alternatively, I would like to ins...
How to make a tiff z-stack conserving or adding metadata?
I have a number of tiff files that I would like to combine to a z-stack using python. The individual files have metadata that I would like to conserve (OME in my case), in particular the information on which z slice it is. Alternatively, I would like to insert somewhere in the z-stack's metadata that it is a z-stack (a...
[ "Try this:\nimport numpy as np\nimport bioformats.omexml as ome\nimport tifffile\nimport sys\n \ndef writeplanes(pixel, SizeT=1, SizeZ=1, SizeC=1, order='TZCYX', verbose=False):\n\n if order == 'TZCYX':\n\n p.DimensionOrder = ome.DO_XYCZT\n counter = 0\n for t in range(SizeT):\n ...
[ 0 ]
[]
[]
[ "python", "tiff" ]
stackoverflow_0031978698_python_tiff.txt
Q: Django ._meta and adding to ManyToMany fields I haven't had much luck finding other questions that helped with this, but apologies if I missed something and this is a duplicate. I'm trying to add to some ManyToMany fields, without having to explicitly type out the names of the fields in the code (because the funct...
Django ._meta and adding to ManyToMany fields
I haven't had much luck finding other questions that helped with this, but apologies if I missed something and this is a duplicate. I'm trying to add to some ManyToMany fields, without having to explicitly type out the names of the fields in the code (because the function I'm working on will be used to add to multiple ...
[ "Why do you want to do\nfield = blt._meta.get_field(field_name) \nfield.add(bacon)\n\ninstead of\nblt.meats.add(bacon)\n\nin the first place?\nIf what you want is to access the attribute meats on the blt instance of the Sandwich class because you have the string 'meats' somewhere, then it's plain python you're aft...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074159113_django_python.txt
Q: How to Display Colored Y Cb Cr Channels in Python OpenCV? I understand how to convert a BGR image to YCrCb format using cvtColor() and separate different channels using split() in OpenCV. However, these channels are displayed as grayscale images: imgYCrCB = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb) Y, Cr, Cb = cv2.sp...
How to Display Colored Y Cb Cr Channels in Python OpenCV?
I understand how to convert a BGR image to YCrCb format using cvtColor() and separate different channels using split() in OpenCV. However, these channels are displayed as grayscale images: imgYCrCB = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb) Y, Cr, Cb = cv2.split(imgYCrCB) cv2.imshow("Y", Y) cv2.imshow("Cr", Cr) cv2.imsho...
[ "The trick for getting the false colors effect for displaying Cb and Cr is relatively simple:\n\nFor Cb false colors:\nFill Y and Cr with value 128, and convert back to BGR.\nFor Cr false colors:\nFill Y and Cb with value 128, and convert back to BGR.\nY is kept in Grayscale format.\n\nValue 128 applies middle gray...
[ 1, 0 ]
[]
[]
[ "image_processing", "opencv", "python" ]
stackoverflow_0074158097_image_processing_opencv_python.txt
Q: Dynamically appending one list into another I have following very simple implementation in python m = [] l = [] l.append('A') l.append('B') l.append('C') m.append(l) l.clear() print(m) --> this gives empty list. i tried m = [] l = [] n = [] l.append('A') l.append('B') l.append('C') n = l m.append(...
Dynamically appending one list into another
I have following very simple implementation in python m = [] l = [] l.append('A') l.append('B') l.append('C') m.append(l) l.clear() print(m) --> this gives empty list. i tried m = [] l = [] n = [] l.append('A') l.append('B') l.append('C') n = l m.append(n) l.clear() print(m) --> this gives empty list...
[ "When you are passing a list to another list then it is taking its reference there\nSo when you cleared that list your original list's element is also cleared\nTry this\nm = []\nl = []\nl.append('A')\nl.append('B')\nl.append('C')\nm.append(l.copy()) -> use list.copy()\nl.clear()\nprint(m) \n\n", "Both variables ...
[ 3, 2, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074157230_list_python.txt
Q: Beautiful Soup Scraping returns empty brackets html = 'https://en.wikipedia.org/wiki/List_of_largest_banks' html_data = requests.get('https://en.wikipedia.org/wiki/List_of_largest_banks') html_data_text = html_data.text soup = bs(html_data_text, 'html.parser') table = soup.find_all('table', {id : "By_market_ca...
Beautiful Soup Scraping returns empty brackets
html = 'https://en.wikipedia.org/wiki/List_of_largest_banks' html_data = requests.get('https://en.wikipedia.org/wiki/List_of_largest_banks') html_data_text = html_data.text soup = bs(html_data_text, 'html.parser') table = soup.find_all('table', {id : "By_market_capitalization"}) print(table) returns empty bracket...
[ "You're looking for a table with that id. However, the links shows that ID in a\nspan.\n\nChange the first selector to find a span, then use findNext() to get the table.\nThere you can find the tr and td and print the .text:\nimport json\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport req...
[ 1, 1, 0 ]
[]
[]
[ "beautifulsoup", "python", "web", "web_scraping" ]
stackoverflow_0074154477_beautifulsoup_python_web_web_scraping.txt
Q: How can i embed javascript code to pdf and get it to execute? i am talking a malware analysis class in uni and in the previous lesson we talked about malicious pdf documents and embeded executables, as well as embeded javascript that runs once the pdf is opened. After class, i tried creating one such pdf myself, b...
How can i embed javascript code to pdf and get it to execute?
i am talking a malware analysis class in uni and in the previous lesson we talked about malicious pdf documents and embeded executables, as well as embeded javascript that runs once the pdf is opened. After class, i tried creating one such pdf myself, but with no luck. I tried doing it manually by loading the pdf in no...
[ "It is not trivial to inject JS using Python, for this example I used a GUI and other editors like MS Notepad as easier to cut and paste. Note it is a very simple proof of concept to test if a browser will respond to scripting.\n\nIt could be much cleaner that this but you can compare with one that is not working s...
[ 1 ]
[]
[]
[ "embed", "javascript", "pdf", "python", "security" ]
stackoverflow_0074113542_embed_javascript_pdf_python_security.txt
Q: In Python is there a way to substitute part of the instruction by a string variable? I want display the data of the items listed in the show_list array. Obviously this code won't work. Any easy way to make it work? import panda as pd show_list=['Apple', 'Orange'] data = { "Apple": [1,2,3], "Banana": [4,5,6],...
In Python is there a way to substitute part of the instruction by a string variable?
I want display the data of the items listed in the show_list array. Obviously this code won't work. Any easy way to make it work? import panda as pd show_list=['Apple', 'Orange'] data = { "Apple": [1,2,3], "Banana": [4,5,6], "Orange": [7,8,9] } df=pd.DataFrame(data) for item in show_list: print(df.item)
[ "If you just do df[show_list] it'll display it.\nIn [1]: df[show_list]\nOut[1]:\n Apple Orange\n0 1 7\n1 2 8\n2 3 9\n\n", "You can print the columns you want by passing their names to df\nprint(df[show_list])\n\nThe output will be\n Apple Orange\n 0 1 7\n 1...
[ 0, 0 ]
[]
[]
[ "dataframe", "python" ]
stackoverflow_0074159033_dataframe_python.txt
Q: Convert a relative path (mp3) from a master file path (playlist) using python pathlib I have three files My python file running in an unimportant different folder: C:\DD\CC\BB\AA\code.py A playlist file "C:\ZZ\XX\Playlist.pls" which points to ....\mp3\song.mp3 The C:\mp3\song.mp3 file. What I want is to get the ...
Convert a relative path (mp3) from a master file path (playlist) using python pathlib
I have three files My python file running in an unimportant different folder: C:\DD\CC\BB\AA\code.py A playlist file "C:\ZZ\XX\Playlist.pls" which points to ....\mp3\song.mp3 The C:\mp3\song.mp3 file. What I want is to get the location of the mp3 as an absolute path. But every attemp I try I get everything related to...
[ "If you're using a Windows version of Python, this is fairly easy. You can join the directory of plMaster (plMaster.parent) with the relative path of plSlave, then resolve the path using resolve(). You can use strict=False to force the resolve even if the path components aren't found.\nThis worked for me:\n>>> plMa...
[ 2, 1, 0 ]
[]
[]
[ "pathlib", "python" ]
stackoverflow_0074159000_pathlib_python.txt
Q: How to use list I am trying to write a program that retrieves user input for sales for every weekday and then calculates the total. What I have got so far looks like this. days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] index = 0 def sales_by_days(days): while index < len(days) sales1 = float(inp...
How to use list
I am trying to write a program that retrieves user input for sales for every weekday and then calculates the total. What I have got so far looks like this. days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] index = 0 def sales_by_days(days): while index < len(days) sales1 = float(input("Enter sales for",...
[ "You can use for loop instead of while loop here,\ndays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']\n\ndef sales_by_days(days):\n totalsales = 0\n for day in days:\n sales = float(input(f\"Enter sales for {day} here. \"))\n totalsales += sales\n print(f\"Your total sales for th...
[ 0, 0, 0 ]
[]
[]
[ "arrays", "list", "python" ]
stackoverflow_0074159273_arrays_list_python.txt
Q: How to convert a pandas dataframe with non unique indexes into a one with unique indexes? I created a dataframe with some previous operations but when I query a column name with an index (for example, df['order_number][0] ), multiple rows/records come as output. The screenshot shows the unique and total indexes o...
How to convert a pandas dataframe with non unique indexes into a one with unique indexes?
I created a dataframe with some previous operations but when I query a column name with an index (for example, df['order_number][0] ), multiple rows/records come as output. The screenshot shows the unique and total indexes of the dataframe. image shows the difference in lengths of uniques indexes and all indexes
[ "It looks like the data kept their index when you merged/joined df. Try:\ndf.reset_index()\n\n", "Could you should a df.head() for example, usually when you consume a data source, if you sent the arg indexto True each row will be assigned a unique numerical index\n" ]
[ 2, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074159436_pandas_python.txt
Q: How can i extract only tuples that have the value 3 and above? lst = [(2),('hello',3),(4),('world',5)] I want extract only the tuples that have the value 3 and above how can i do that ? A: [n for n in lst if type(n) is tuple and n[1] >= 3] [n for n in lst if isinstance(n, tuple) and n[1] >= 3 or isinstance(n, ...
How can i extract only tuples that have the value 3 and above?
lst = [(2),('hello',3),(4),('world',5)] I want extract only the tuples that have the value 3 and above how can i do that ?
[ "[n for n in lst if type(n) is tuple and n[1] >= 3]\n\n\n[n for n in lst if isinstance(n, tuple) and n[1] >= 3 or isinstance(n, int) and n >= 3]\n\n", "Try this:\nlst = [(2),('hello',3),(4),('world',5)]\n\nres = []\nfor tpl in lst:\n # check type(tpl)==tuple \n # and all elements in tpl not in range(3) -> [...
[ 2, 0, 0 ]
[ "This will handle the cases you need. I made it so that you get the tuples first. It's more object oriented than other answers.\nfrom typing import List\n\n\nclass More:\n def __init__(self):\n self.value = 0\n\n def be(self, value: int):\n self.value = value\n return self\n\n def than...
[ -1 ]
[ "list", "python" ]
stackoverflow_0074159295_list_python.txt
Q: How do I subtract from every second[i][1] element in a 2d array? Here is my 2d array: [['P1', 27], ['P2', 44], ['P3', 65], ['P4', 51], ['P5', 31], ['P6', 18], ['P7', 33]] I have created a loop to attach each appropriate label to its corresponding value within this 2d array. At the end of the loop I would like to ...
How do I subtract from every second[i][1] element in a 2d array?
Here is my 2d array: [['P1', 27], ['P2', 44], ['P3', 65], ['P4', 51], ['P5', 31], ['P6', 18], ['P7', 33]] I have created a loop to attach each appropriate label to its corresponding value within this 2d array. At the end of the loop I would like to subtract every value by a different number. For example: if I wanted t...
[ "This is a simple job for a list comprehension:\n>>> L = [['P1', 27], ['P2', 44], ['P3', 65], ['P4', 51], ['P5', 31], ['P6', 18], ['P7', 33]]\n>>> [[s, n - 5] for s, n in L]\n[['P1', 22], ['P2', 39], ['P3', 60], ['P4', 46], ['P5', 26], ['P6', 13], ['P7', 28]]\n\nNote that using a comprehension creates a new list an...
[ 5, 5, 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0074159352_python.txt
Q: how to pack into frame class python tkinter Here I pack a Label into a frame class but it doesn't pack inside the frame it packs in the other side the window class. Here is a screenshot of the results in a . Code: from PIL import Image,ImageTk import tkinter as tk class Window(tk.Tk): def __init__(self): ...
how to pack into frame class python tkinter
Here I pack a Label into a frame class but it doesn't pack inside the frame it packs in the other side the window class. Here is a screenshot of the results in a . Code: from PIL import Image,ImageTk import tkinter as tk class Window(tk.Tk): def __init__(self): super().__init__() def AddImage(path, siz...
[ "Just add self as the first argument of your testLabel. This sets the parent for the label so it knows where to pack itself.\n def widgets(self):\n self.test = Window.AddImage(r\"assets\\images\\add-word.png\",size=(20,20))\n self.testLabel = tk.Label(self, image = self.test)\n # self.pack_p...
[ 1 ]
[]
[]
[ "class", "python", "python_imaging_library", "tkinter" ]
stackoverflow_0074159243_class_python_python_imaging_library_tkinter.txt
Q: I get "SyntaxError: invalid syntax" for no reason (I think) this is the code print(f"{DataBase.Count()} Users\n") and this is the error print(f"{DataBase.Count()} Users\n") ^ SyntaxError: invalid syntax and i dont know how to fix it please help me A: If you want to use ...
I get "SyntaxError: invalid syntax" for no reason (I think)
this is the code print(f"{DataBase.Count()} Users\n") and this is the error print(f"{DataBase.Count()} Users\n") ^ SyntaxError: invalid syntax and i dont know how to fix it please help me
[ "If you want to use fstring in python 2.7, you could use this lib: https://github.com/asottile-archive/future-fstrings\nfstring is added after python 3.6.\n" ]
[ 1 ]
[]
[]
[ "python", "python_2.7" ]
stackoverflow_0074159452_python_python_2.7.txt
Q: Pandas: how to split or extract multiple values from column This is my first Stack post and I'm new in the worlds of Python and Pandas. I'm trying to get 3 separate values from a column. I tried both .str.split and .str.extract but can't get the result. The df I have: wow 0 1000100011-DT000111-1111 Hellost...
Pandas: how to split or extract multiple values from column
This is my first Stack post and I'm new in the worlds of Python and Pandas. I'm trying to get 3 separate values from a column. I tried both .str.split and .str.extract but can't get the result. The df I have: wow 0 1000100011-DT000111-1111 Hellostreet 45 Town 1 1000100012 DT000122-1222-Hellostrasse 56 Plac...
[ "To solve it, you can use the .str.extract method, splitting the string into three groups using regular expressions.\nimport pandas as pd\n\n\ndf = pd.DataFrame({'wow': ['1000100011-DT000111-1111 Hellostreet 45 Town',\n '1000100012 DT000122-1222-Hellostrasse 56 Place',\n ...
[ 1 ]
[]
[]
[ "extract", "pandas", "python", "split" ]
stackoverflow_0074154314_extract_pandas_python_split.txt
Q: I need to "Copy" the return of a Label in tkinter Python I have a question where I have a python code where I make a request in an API, as well as request data via tkinter Entry, however I need the result it generates for the user to "Copy". My code: from cgitb import text from os import link from tokenize import ...
I need to "Copy" the return of a Label in tkinter Python
I have a question where I have a python code where I make a request in an API, as well as request data via tkinter Entry, however I need the result it generates for the user to "Copy". My code: from cgitb import text from os import link from tokenize import String from turtle import back import requests from tkinter im...
[ "Try this:\ndef copy():\n janela.clipboard_clear()\n janela.clipboard_append(resposta[\"text\"])\n janela.update()\n \nButton(janela, text=\"Copiar o link\", command=copy).place(x=10, y=220, width=100, height=20)\n\n" ]
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074148393_python_tkinter.txt
Q: Iterate over an array of lists without Itertools I have an array of lists array_of_lists, of which I need every combination of elements. The number of elements of array_of_lists should not be predefined. The usual way would be to use itertools.product(*array_of_lists). However, I don't need to actually save all it...
Iterate over an array of lists without Itertools
I have an array of lists array_of_lists, of which I need every combination of elements. The number of elements of array_of_lists should not be predefined. The usual way would be to use itertools.product(*array_of_lists). However, I don't need to actually save all iterations* and itertools breaks my memory. I could do n...
[ "I hope I understand the problem.\nLet's suppose your array of lists is name aol.\nfor i in range( len( aol)):\n for j in range( len( aol[i])):\n ... do data handling ...\n\nthen you can iterate your un-predefined arrays\n" ]
[ 0 ]
[]
[]
[ "for_loop", "python", "python_itertools" ]
stackoverflow_0074156618_for_loop_python_python_itertools.txt
Q: How to convert list to int I am trying to write a code to calculate the average of the height of the student that is my code height = input("what is your higth\n").split() for n in range(0, len(height)): height[n] = int(height[n]) print(height) t = 0 for i in height: t += height print(height) and ...
How to convert list to int
I am trying to write a code to calculate the average of the height of the student that is my code height = input("what is your higth\n").split() for n in range(0, len(height)): height[n] = int(height[n]) print(height) t = 0 for i in height: t += height print(height) and I have error t += higths Typ...
[ "Use enumerate on the for loop to access to the list indexes and convert it to int.\nThen calculate the sum divided by the len of the list.\nheight = input(\"what is your higth\\n\").split()\n\nfor i, element in enumerate(height) : \n height[i] = int(element)\n\n# Average\nprint(sum(height)/len(height))\n\n", ...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074159214_python.txt
Q: Autoencoders for figuring the underlying data distribution in python I have the following randomly generated data import numpy as np from keras import models,layers from keras import applications from sklearn.model_selection import train_test_split data = np.random.normal(100, 10, 100) # generate 100 numbers Whi...
Autoencoders for figuring the underlying data distribution in python
I have the following randomly generated data import numpy as np from keras import models,layers from keras import applications from sklearn.model_selection import train_test_split data = np.random.normal(100, 10, 100) # generate 100 numbers Which I split into train and test data_train, data_test = train_test_split(da...
[ "Variational Autoencoder\nInitial thoughts and problems\nSupposed the model has learned the distribution, we can draw samples from the latent space L. dim(L)=embedding_dim\nEvery point in L will result in a prediction and here we meet our first problems.\n\na) The latent space is infinitely large\nb) and there are ...
[ 3, 1 ]
[]
[]
[ "autoencoder", "deep_learning", "machine_learning", "neural_network", "python" ]
stackoverflow_0074068269_autoencoder_deep_learning_machine_learning_neural_network_python.txt
Q: Pass python list to ajax select 2 I´m querying data from my db and save it in a list. On my .html template i have 2 select2 fields, which are both in a form. In one i want to add the data in the select2 field using flask and ajax. Any help is appreciated!! Here is my code i´ve done so far. app.py @application.rout...
Pass python list to ajax select 2
I´m querying data from my db and save it in a list. On my .html template i have 2 select2 fields, which are both in a form. In one i want to add the data in the select2 field using flask and ajax. Any help is appreciated!! Here is my code i´ve done so far. app.py @application.route("/autocomplete",methods=["POST","GET"...
[ "The following example shows you how to add data to your select2 field using neo4j.\nTo provide the data for the select field using AJAX, you need a list of objects that have the properties id and text. This list is a property called results within a parent object. Later, the ids are assigned to the respective valu...
[ 1 ]
[]
[]
[ "ajax", "flask", "python" ]
stackoverflow_0074027592_ajax_flask_python.txt
Q: I have problem scraping a 'title' attribut from an html class using python I need to take out the 'title': NAPAPIJRI Дуксер Burgee. Here is my code. html=BeautifulSoup(raw_html,"html.parser") cardtitles=html.select(".product-link") HTML: </a>, <a class="product-link" href="https://www.buzzsneakers.mk/dukser/2119...
I have problem scraping a 'title' attribut from an html class using python
I need to take out the 'title': NAPAPIJRI Дуксер Burgee. Here is my code. html=BeautifulSoup(raw_html,"html.parser") cardtitles=html.select(".product-link") HTML: </a>, <a class="product-link" href="https://www.buzzsneakers.mk/dukser/211933-napapijri-dukser-burgee" title="NAPAPIJRI Дуксер Burgee "> <span>подетално</...
[ "You can access the tags' attributes\ncardtitles=html.select(\".product-link\")[0]['title']\n\n" ]
[ 0 ]
[]
[]
[ "html", "python", "web_scraping" ]
stackoverflow_0074159497_html_python_web_scraping.txt
Q: python, matplotlib.pyplot, draw graph without the curve I am trying to draw a curve without a line (skeleton). I want the axis and grid lines only. Here is the code. ++++++++++ import matplotlib.pyplot as plt import numpy as np plt.rcParams["figure.figsize"] = [10.00, 7.00] plt.rcParams["figure.autolayout"] = Tr...
python, matplotlib.pyplot, draw graph without the curve
I am trying to draw a curve without a line (skeleton). I want the axis and grid lines only. Here is the code. ++++++++++ import matplotlib.pyplot as plt import numpy as np plt.rcParams["figure.figsize"] = [10.00, 7.00] plt.rcParams["figure.autolayout"] = True x = [1.6,2,2.5,3.2,4,5,6.3,8,10,13,16,20,25,32,40,50,63,8...
[ "By adding\nprint(plt.xlim())\nprint(plt.ylim())\n\nto your code you get the exact axis limits.\nThese can be used in a second run to create the plot without actually plotting anything:\nimport matplotlib.pyplot as plt\n\nimport numpy as np\n\nplt.rcParams[\"figure.figsize\"] = [10.00, 7.00]\nplt.rcParams[\"figure....
[ 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0074120805_matplotlib_python.txt
Q: I am trying to allow the user input to select specified options from a list I have only been learning Python for about two weeks and need a bit of help with an assignment. Below is the code I have written so far, import random colour_list = ["red","blue","white","yellow","pink","orange","black","green","grey","pu...
I am trying to allow the user input to select specified options from a list
I have only been learning Python for about two weeks and need a bit of help with an assignment. Below is the code I have written so far, import random colour_list = ["red","blue","white","yellow","pink","orange","black","green","grey","purple"] start_num = int(input("enter a starting number between 0 and 4\n")) end_nu...
[ "You don't need to use random here. You can do simple list slicing,\ncolour_list = [\"red\",\"blue\",\"white\",\"yellow\",\"pink\",\"orange\",\"black\",\"green\",\"grey\",\"purple\"]\nstart_num = int(input(\"enter a starting number between 0 and 4\\n\"))\nend_num = int(input(\"enter a end number between 5 and 9\\n\...
[ 0 ]
[]
[]
[ "input", "list", "python" ]
stackoverflow_0074159657_input_list_python.txt
Q: How to remove "None" from output of function related question def function1(): print("Aww im sorry to hear") def function2(): print("Thats fantastic") def function3(): print("Invalid response") ansr = input(print("Did you have a good day at school? Answer 'Y' or 'N'!!")...
How to remove "None" from output of function related question
def function1(): print("Aww im sorry to hear") def function2(): print("Thats fantastic") def function3(): print("Invalid response") ansr = input(print("Did you have a good day at school? Answer 'Y' or 'N'!!")) if ansr == "Y": function2() elif ansr == "N": function1(...
[ "Don't print inside input. The prompt message is automatic.\nansr = input(\"Did you have a good day at school? Answer 'Y' or 'N'!!\")\n\n\nprint returns None here a similar example\nprint(print('Hallo'))\n\nOutput\nHallo\nNone\n\n" ]
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0074159674_python.txt
Q: Optimize XML parsing to use lesser memory I am currently doing a parsing of a bunch of large XML files using: import xml.etree.ElementTree as ET and this is my function: def xmlfilter(input_file): print('Processing file: ' + input_file) tree = ET.ElementTree(file = input_file) root = tree.getroot() ...
Optimize XML parsing to use lesser memory
I am currently doing a parsing of a bunch of large XML files using: import xml.etree.ElementTree as ET and this is my function: def xmlfilter(input_file): print('Processing file: ' + input_file) tree = ET.ElementTree(file = input_file) root = tree.getroot() packagebody = root.find('./PackageBody') ...
[ "lxml is usually more space efficient than ElementTree because it backends to the C based libxml2. You should be able to write a single XPATH to select the nodes you want. That will remove the need to reverse your delete list. I wasn't sure how to deal with in IDs so I wrote an XPATH extension function that checks ...
[ 1 ]
[]
[]
[ "large_data", "optimization", "python", "xml", "xml_parsing" ]
stackoverflow_0074159240_large_data_optimization_python_xml_xml_parsing.txt
Q: How can I rename an uploaded file on Django before sending it to amazon s3 bucket? I have a Django App which allows a user to upload a file and save it to an s3 bucket. My question is how could I rename the file before uploading to the bucket? This is my models.py class: from converter.storage_backends import Cs...
How can I rename an uploaded file on Django before sending it to amazon s3 bucket?
I have a Django App which allows a user to upload a file and save it to an s3 bucket. My question is how could I rename the file before uploading to the bucket? This is my models.py class: from converter.storage_backends import CsvStorage from django.db import models from django.utils import timezone class CSVUploa...
[ "Django provides API for that - it is upload_to parameter of the FileField object\nhttps://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FileField.upload_to\n\nupload_to may also be a callable, such as a function. This will be called to obtain the upload path, including the filename. This callab...
[ 0 ]
[ "You would need to override the save function. I did it something like this:\nclass Documents(AuditFields):\ndocument_file = models.FileField(max_length=10000)\n\ndef save(self, *args, **kwargs):\n self.document_file.name = 'some_prefix' + self.document_file.name\n super(PlantDocument, self).save(*args, **kwa...
[ -1 ]
[ "amazon_s3", "django", "file_upload", "python" ]
stackoverflow_0056888583_amazon_s3_django_file_upload_python.txt
Q: creating a recursive function to show the depth of numbers of list in dictionary Design a function depth_map which returns a dictionary whose keys are the depths of the items in and the value for a given key is a list of the items at that depth. The depth of an object in a nested list is the number of nested l...
creating a recursive function to show the depth of numbers of list in dictionary
Design a function depth_map which returns a dictionary whose keys are the depths of the items in and the value for a given key is a list of the items at that depth. The depth of an object in a nested list is the number of nested lists,enclosing the object. The depth of a single int is 0. If no items occur at a give...
[ "You need to use recursion. First create a function that checks the type. If the type is a list call the function again until it is not a list. Once that happens append the value to the list of whatever depth it is.\ndef depth_map(array: list, depth=1, result={}) -> dict:\n for element in array:\n if type...
[ 0 ]
[]
[]
[ "depth", "function", "python", "recursion" ]
stackoverflow_0074159745_depth_function_python_recursion.txt
Q: Flask- these two inputs are doing the same function I want the de request.form.get('Stay') to keep me in the same index and I want request.form.get("Deal") to send me to the deal route and they both send me to the deal route @app.route('/', methods=['POST', "GET"]) def home(): if request.method == "POST": ...
Flask- these two inputs are doing the same function
I want the de request.form.get('Stay') to keep me in the same index and I want request.form.get("Deal") to send me to the deal route and they both send me to the deal route @app.route('/', methods=['POST', "GET"]) def home(): if request.method == "POST": if request.form.get("Stay"): return redir...
[ "I figured it out ! =)\n <form action=\"/\" method=\"Post\" >\n <input class=\"deal_button\" type=\"submit\" value=\"{{ button }}\" name=\"Deal\"/>\n<input class=\"hit_button\" type=\"submit\" value=\"Hit\" name=\"Hit_home\"/>\n<input class=\"stay_button\" type=\"submit\" value=\"Stay\" name=\"Stay_home\"/>\n\nthe ...
[ 0 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074145524_flask_python.txt
Q: got empty result in scraping a record i made a progam to scrap attributes from single record from web but i am getting nothing in my variables below is what i tried. I am unable to understand where my logic is wrong from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver....
got empty result in scraping a record
i made a progam to scrap attributes from single record from web but i am getting nothing in my variables below is what i tried. I am unable to understand where my logic is wrong from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from seleni...
[ "There is nothing in page_source you have saved. you have to wait for some time\n#iterate the the list of elements if there are more than one elements\n\n", "I there are more than one elements with same class then be sure you are locating the right element.\nFind the elements list\niterate the list\nlocate your r...
[ 2, 2, 1, 1, 1 ]
[]
[]
[ "css_selectors", "python", "selenium", "selenium_webdriver", "xpath" ]
stackoverflow_0074039001_css_selectors_python_selenium_selenium_webdriver_xpath.txt
Q: python count of the recursive calls to function The amount of recursive calls to the following function need to be counted: def fb(n, d): if n in d: return d[n] else: ans = fb(n-1, d) + fb(n-2, d) d[n] = ans return ans d = {1:1, 2:2} print(fb(8, d)) print(d) Now i understan...
python count of the recursive calls to function
The amount of recursive calls to the following function need to be counted: def fb(n, d): if n in d: return d[n] else: ans = fb(n-1, d) + fb(n-2, d) d[n] = ans return ans d = {1:1, 2:2} print(fb(8, d)) print(d) Now i understand the function, and what essentially happens, i just ...
[ "This might help you to understand it:\ndef fb(n, d, indent):\n if n in d:\n print(indent, n, \"old\")\n return d[n]\n else:\n print(indent, n, \"new\")\n indent2 = indent + \" \"\n ans = fb(n-1, d, indent2) + fb(n-2, d, indent2)\n d[n] = ans\n return ans\nd =...
[ 3, 1, 0 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0074159596_python_recursion.txt
Q: How to import one Excel file sheet to another Excel file in new sheet programmatically I have two excel files with multiple sheets in it, I want to import one sheet from the second excel file to first excel file as new sheet programmatically. While importing I want to retain formatting of the sheet Looking soluti...
How to import one Excel file sheet to another Excel file in new sheet programmatically
I have two excel files with multiple sheets in it, I want to import one sheet from the second excel file to first excel file as new sheet programmatically. While importing I want to retain formatting of the sheet Looking solution in Python or PowerShell. Didn’t find anything in the search, hence posting this question....
[ "Very basic boilerplate Powershell script ...\n$excelApplication = New-Object -comobject Excel.Application\n\n$sourceWorkbook = $excelApplication.Workbooks.Open(\"C:\\temp\\Source.xlsx\")\n$sourceWorksheet = $sourceWorkbook.Worksheets(\"Sheet1\")\n\n$destinationWorkbook = $excelApplication.Workbooks.Open(\"C:\\temp...
[ 1 ]
[]
[]
[ "excel", "powershell", "python" ]
stackoverflow_0074147354_excel_powershell_python.txt
Q: How to create a File using json data from postman in python from aiohttp import web import os import json i want to create a file with input parameters in post request server async http python get request async def handle(request): path = "C://Users/berto/Desktop/MEGSI - ESI 1/ITI/Servidor/Ficheiros" dir_...
How to create a File using json data from postman in python
from aiohttp import web import os import json i want to create a file with input parameters in post request server async http python get request async def handle(request): path = "C://Users/berto/Desktop/MEGSI - ESI 1/ITI/Servidor/Ficheiros" dir_list = os.listdir(path) text = str(dir_list) return web.R...
[ "You have wrong indentation and you have writeToJSONFile(\"C...\") inside def writeToJSONFile() so it can't execute it.\nasync def handler(requests):\n def writeToJSONFile(path, fileName, data):\n filePathNameWExt = path + '/' + fileName + '.json'\n with open(filePathNameWExt, 'a') as fp:\n ...
[ 0 ]
[]
[]
[ "json", "post", "postman", "python" ]
stackoverflow_0074143957_json_post_postman_python.txt
Q: Recursive function in python returns None I have the following simple code to compute the sum of values until the indicated number. The total is stored inside result. def ComputeMath(number, result): if number > 0: result = number + result print('if', result) ComputeMath(number-1, result) ...
Recursive function in python returns None
I have the following simple code to compute the sum of values until the indicated number. The total is stored inside result. def ComputeMath(number, result): if number > 0: result = number + result print('if', result) ComputeMath(number-1, result) else: print("else", result) ret...
[ "The conditional split the code flow/execution among two paths but only one of them has a return, hence the other one will implicitly return None\ndef ComputeMath(number, result):\n if number > 0:\n result = number + result\n print('if', result)\n return ComputeMath(number-1, result)\n else:\n...
[ 1 ]
[]
[]
[ "function", "python", "recursion", "return" ]
stackoverflow_0074159890_function_python_recursion_return.txt
Q: Snowflake - invoking Python code without creating UDF/Stored Procedure How to run Python code without defining pernament/temporary User Defined Function or stored procedure? The use case is to run the code one time inside a script and it should avoid creating/dropping additional database objects. I am searching fo...
Snowflake - invoking Python code without creating UDF/Stored Procedure
How to run Python code without defining pernament/temporary User Defined Function or stored procedure? The use case is to run the code one time inside a script and it should avoid creating/dropping additional database objects. I am searching for an equivalent of anonymous block (SQL) known from Snowflake Scripting but ...
[ "It is possible to define inline stored procedure using WITH <stored_procedure> AS ... CALL <stored_procedure> syntax.\nCALL (with Anonymous Procedure)\n\nCreates and calls an anonymous procedure that is like a stored procedure but is not stored for later use.\nWith this command, you both create an anonymous proced...
[ 2 ]
[]
[]
[ "python", "snowflake_cloud_data_platform", "stored_procedures" ]
stackoverflow_0074159933_python_snowflake_cloud_data_platform_stored_procedures.txt
Q: how to implement random choice how to implement random choice on both url? I had tired when send request i get response from both api not from any one @app.route('/v1.1/userRegistor', methods=['POST','GET']) def job(): data = request.get_json() numbers=data['number'] api_url =f'https://app.simplywhat...
how to implement random choice
how to implement random choice on both url? I had tired when send request i get response from both api not from any one @app.route('/v1.1/userRegistor', methods=['POST','GET']) def job(): data = request.get_json() numbers=data['number'] api_url =f'https://app.simplywhatsapp.com/api/send.php?number={number...
[ "Choosing the random from both API responses it's a bad approach. You can randomly choose the URL and fetch the API response from the selected URL.\n@app.route('/v1.1/userRegistor', methods=['POST','GET'])\ndef job():\n data = request.get_json()\n numbers=data['number']\n api_url =f'https://app.simplywhats...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074159912_python.txt
Q: Python list index not in order I'm trying to make it so that my text alternates between upper and lower case like the question ask. It seems to skip 3 in the indexing and I can't figure out why. sentence = input("Write a sentence") newList = [] for i in range(len(sentence)): if sentence[i] != " ": new...
Python list index not in order
I'm trying to make it so that my text alternates between upper and lower case like the question ask. It seems to skip 3 in the indexing and I can't figure out why. sentence = input("Write a sentence") newList = [] for i in range(len(sentence)): if sentence[i] != " ": newList.append(sentence[i]) listJoint...
[ "The function .index() finds the first occurrence of that letter. 'L' occurs at index 2 and 3 so it would return 2 for both L's.\n", "Iterate through each character of the string and alternate upper/lower methods.\nsentence = \"Hello\"\n\nalternated_sentence = ''\nfor i, char in enumerate(sentence):\n if i % 2...
[ 1, 0, 0, 0 ]
[]
[]
[ "indexing", "list", "python" ]
stackoverflow_0074159679_indexing_list_python.txt