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: PYFPDF: Adjust cell height with a multicell i have a problem for adjust the height of cell depending on height of multicell, this multicell changes its height by the number of words and width.My code that I am testing is the following. datos = ["hola","Esto es el texto que determina el tamaño"] pdf = FPDF() pdf.a...
PYFPDF: Adjust cell height with a multicell
i have a problem for adjust the height of cell depending on height of multicell, this multicell changes its height by the number of words and width.My code that I am testing is the following. datos = ["hola","Esto es el texto que determina el tamaño"] pdf = FPDF() pdf.add_page() pdf.set_font('Arial', 'B', 8) line_heig...
[ "You use the split_only argument of multi_cell to calculate the needed lines per cell for the text. With this information you can properly calculate the exact position of each cell. Be aware that the max_line_height argument has to be understand as line height of each line of a cell. Meaning that a value of 3 will ...
[ 0 ]
[]
[]
[ "pyfpdf", "python" ]
stackoverflow_0071476543_pyfpdf_python.txt
Q: Load Form recognizer data into a dataframe I am reading a pdf file using Form recognizer. Storing it in a "result" variable/object. As per the syntax given for the Azure Databricks/pyspark in the documentation for the Formrecognizer my output is coming out like below. Instead I need to put the output into a datafr...
Load Form recognizer data into a dataframe
I am reading a pdf file using Form recognizer. Storing it in a "result" variable/object. As per the syntax given for the Azure Databricks/pyspark in the documentation for the Formrecognizer my output is coming out like below. Instead I need to put the output into a dataframe. Each table into a separate dataframe. Pleas...
[ "I tried to read PDF doc using azure form recognizer and used azure databricks for converting it to dataframe following are the detailed steps\n->login to the subscribed Azur account in Form Recognizer Studio - Microsoft Azure and select layout from document analysis\n\n->Browse required Invoice pdf file and click...
[ 1 ]
[]
[]
[ "azure_databricks", "azure_form_recognizer", "pyspark", "python", "python_3.x" ]
stackoverflow_0074307525_azure_databricks_azure_form_recognizer_pyspark_python_python_3.x.txt
Q: Push python data to SQL I am trying to push my data into SQL but it keeps telling me that one of my columns is an invalid data type float. sqlalchemy.exc.ProgrammingError: (pyodbc.ProgrammingError) ('42000', '[42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]The incoming tabular data stream (TDS) remot...
Push python data to SQL
I am trying to push my data into SQL but it keeps telling me that one of my columns is an invalid data type float. sqlalchemy.exc.ProgrammingError: (pyodbc.ProgrammingError) ('42000', '[42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]The incoming tabular data stream (TDS) remote procedure call (RPC) protoc...
[ "I figure out what it was. My data had some nan cells and for some reason it was not accepting it. Once I addressed the Nan cells using the below line of code it worked.\nEnergyFwdOutright_CM101 = EnergyFwdOutright_CM101.where(pd.notnull(EnergyFwdOutright_CM101), None) \n\n", "The SQL Standard doesn't allow NaN v...
[ 0, 0 ]
[]
[]
[ "python", "sql_server" ]
stackoverflow_0074345840_python_sql_server.txt
Q: Python Selenium webdriver doesn't open chrome, and if it does - it keeps refreshing it without any result I am trying to enter web.whatsapp.com while using Selenium through Python, it opens Chrome web browser but doesn't enter the site but shows "data.;" blank page instead. import pandas as pd import webbrowser fr...
Python Selenium webdriver doesn't open chrome, and if it does - it keeps refreshing it without any result
I am trying to enter web.whatsapp.com while using Selenium through Python, it opens Chrome web browser but doesn't enter the site but shows "data.;" blank page instead. import pandas as pd import webbrowser from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chro...
[ "You have to remove the ' in front of 'https://ynet.co.il. It should be https://ynet.co.il i.e.\ndriver.get(\"https://ynet.co.il\")\n\nSo simple\n" ]
[ 0 ]
[]
[]
[ "automation", "python", "selenium", "selenium_chromedriver", "selenium_webdriver" ]
stackoverflow_0074361995_automation_python_selenium_selenium_chromedriver_selenium_webdriver.txt
Q: How can you calculate where the middle of the screen is using math in python I must've skipped school that day because I cannot remember how to calculate the middle of a square. A: There are a few different ways to calculate the middle of a square using Python. One way is to find the average of the x and y coord...
How can you calculate where the middle of the screen is using math in python
I must've skipped school that day because I cannot remember how to calculate the middle of a square.
[ "There are a few different ways to calculate the middle of a square using Python. One way is to find the average of the x and y coordinates of the square's four corners. Another way is to find the point that is equidistant from all four corners of the square.\n# method-1\ndef square_middle(square):\n x1, y1, x2,...
[ 2, 1 ]
[]
[]
[ "math", "python" ]
stackoverflow_0074361781_math_python.txt
Q: How can I drop rows in a time series dataframe based on conditioning the time in the timestamp. i.e dropping rows for a particular time of the day I have data of 7 months on an hourly and minutes basis. I want to drop night time data (7:30pm to 5:10am) from everyday. A: If you are using a datetime as index, you ...
How can I drop rows in a time series dataframe based on conditioning the time in the timestamp. i.e dropping rows for a particular time of the day
I have data of 7 months on an hourly and minutes basis. I want to drop night time data (7:30pm to 5:10am) from everyday.
[ "If you are using a datetime as index, you don't need to use dt. Also, dt.hour returns an integer value. But you are using an integer value with a string expression. You can use like this:\ndf2=df.loc[(df.index.hour >= 5) & (df.index.hour <= 19)]\n\nbut there is simple way. Use between_time():\ndf=df.between_time('...
[ 0 ]
[]
[]
[ "datetime", "filter", "python", "time_series", "timestamp" ]
stackoverflow_0074360631_datetime_filter_python_time_series_timestamp.txt
Q: How to plot a graph with own data created by a (for) loop? Before I worked with predefined data sets, this time I decided to create my own. This led me to a problem with plotting a graph with variable n and S_T. Based on a defined S_T which is a strike price and n number of observations I created a for loop with t...
How to plot a graph with own data created by a (for) loop?
Before I worked with predefined data sets, this time I decided to create my own. This led me to a problem with plotting a graph with variable n and S_T. Based on a defined S_T which is a strike price and n number of observations I created a for loop with the following conditions. I want my loop to work in the range (0,...
[ "i don't really understand what you want to do in your for loop but you can just use 2 lists for your desired x and y values like so:\nimport plotly.graph_objects as go\nx = []\ny = []\nfor i in range(start, end):\n if i > some value:\n x.append(do something with i)\n y.append(do something with i)\...
[ 1 ]
[]
[]
[ "plot", "python", "python_3.x" ]
stackoverflow_0074362044_plot_python_python_3.x.txt
Q: Make lists from pdf file in python I'm going to read a pdf file in python and make a data frame. DataFrame = (Locality, Reference, Price...) There are so many pages like this picture. How can I do that? I tried to solve this problem by using regular expression but I haven't done it. A: disclaimer: I am the auth...
Make lists from pdf file in python
I'm going to read a pdf file in python and make a data frame. DataFrame = (Locality, Reference, Price...) There are so many pages like this picture. How can I do that? I tried to solve this problem by using regular expression but I haven't done it.
[ "disclaimer: I am the author of borb, the library used in this answer\nUsing borb you can extract text from a PDF.\nThere are plenty of options:\n\nextract all text (left to right, top to bottom)\nextract text at a given location (using LocationFilter)\nextract text in a given Color (using FontColorFilter)\nextract...
[ 0 ]
[]
[]
[ "paragraph", "pdf", "python" ]
stackoverflow_0074267029_paragraph_pdf_python.txt
Q: Python - How to properly access class members if the instance itself is not None Coming from c++ this implementation looks similar to accessing pointers, in python is there more elegant way to do this? if something is not None: return something.x else: return None if the in...
Python - How to properly access class members if the instance itself is not None
Coming from c++ this implementation looks similar to accessing pointers, in python is there more elegant way to do this? if something is not None: return something.x else: return None if the instance itself is not null, then allow accessing its members. any ideas? thanks
[ "For best clarity and easier for newcomers to understand, I believe you can use a single line if-else statment in Python:\nval = something.x if something else None\n\nAs mentioned in comments, the above will go the else part even if something is a falsy value, such as 0.\nIn that case, you could also add an explici...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074362047_python.txt
Q: Pycharm 2022 cannot connect to the docker service. It does not find it I have Pycharm 2022 and when configuring a docker Python interpreter, Pycharm is not able to find the remote docker service, it seems that it cannot find it although the service is running (and I have the pro license): Loaded: loaded (/lib/sys...
Pycharm 2022 cannot connect to the docker service. It does not find it
I have Pycharm 2022 and when configuring a docker Python interpreter, Pycharm is not able to find the remote docker service, it seems that it cannot find it although the service is running (and I have the pro license): Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled) Active: active...
[ "Appart from the official \"solution\" from Intelillj I find it easier with this workaround:\n\nHelp -> Find Action -> Registry\nDisable python.use.targets.api\nTry to configure the interpreter again\n\nThere is an official solution from Intelillj that you can check here:\nhttps://intellij-support.jetbrains.com/hc/...
[ 2 ]
[]
[]
[ "docker", "pycharm", "python", "sockets" ]
stackoverflow_0074362149_docker_pycharm_python_sockets.txt
Q: Python change lowercase to uppercase I need help with python program. I don't know how to make python change at least 1 lowercase letter to uppercase. from random import * import random pin="" lenght=random.randrange(8,15) for i in range(lenght): pin=pin+chr(randint(97,122)) print(pin) A: You want a passw...
Python change lowercase to uppercase
I need help with python program. I don't know how to make python change at least 1 lowercase letter to uppercase. from random import * import random pin="" lenght=random.randrange(8,15) for i in range(lenght): pin=pin+chr(randint(97,122)) print(pin)
[ "You want a password with at least one uppercase letter but it shouldn't be every character. First get length random lowercase letters. Then get some random indexes (min. 1, max. length-1) that should be transposed to uppercase.\nimport random\nimport string\n\n# randomize length of password\nlength = random.randra...
[ 2, 0, 0 ]
[ "I give it a shot with the little info I got. You can change a lower to upper char with lower(), and vise versa with upper().\npin=\"asd\"\n\nprint(pin.upper())\n>>>ASD\n\nThis applies of course to single characters as well. Since idk what the exact goal is, I gave above example. If you want to be sure some charact...
[ -1 ]
[ "letter", "lowercase", "python", "uppercase" ]
stackoverflow_0074361951_letter_lowercase_python_uppercase.txt
Q: Printing the number of different numbers in python I would like to ask a question please regarding printing the number of different numbers in python. for example: Let us say that I have the following list: X = [5, 5, 5] Since here we have only one number, I want to build a code that can recognize that we have o...
Printing the number of different numbers in python
I would like to ask a question please regarding printing the number of different numbers in python. for example: Let us say that I have the following list: X = [5, 5, 5] Since here we have only one number, I want to build a code that can recognize that we have only one number here so the output must be: 1 The number ...
[ "You could keep track of unique numbers with a set object:\nX = [1,2,3,3,3]\nS = set(X)\nn = len(S)\nprint(n, S) # 3 {1,2,3}\n\nBear in mind sets are unordered, so you would need to convert back to a list and sort them if needed.\n", "you can change this list into set, it will remove duplicate, then you can chan...
[ 1, 1, 0, 0 ]
[]
[]
[ "numbers", "printing", "python" ]
stackoverflow_0074360583_numbers_printing_python.txt
Q: Group By and ILOC Errors I'm getting the following error when trying to groupby and sum by dataframe by specific columns. ValueError: Grouper for '<class 'pandas.core.frame.DataFrame'>' not 1-dimensional I've checked other solutions and it's not a double column name header issue. See df3 below which I want to gro...
Group By and ILOC Errors
I'm getting the following error when trying to groupby and sum by dataframe by specific columns. ValueError: Grouper for '<class 'pandas.core.frame.DataFrame'>' not 1-dimensional I've checked other solutions and it's not a double column name header issue. See df3 below which I want to group by on all columns except la...
[ "df.iloc[:,0:3] returns a dataframe. So you are trying to group dataframe with another dataframe.\nBut you just need a column list.\ncan you try this:\ndfs = df3.groupby(list(df3.iloc[:,0:3].columns))['Churn_Alive_1','Churn_Alive_0'].sum()\n\n" ]
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074358975_pandas_python.txt
Q: How to properly transform a sync function to an async one? I'm writing a telegram bot and I need the bot to be available to users even when it is processing some previous request. My bot downloads some videos and compresses them if it exceeds the size limit, so it takes some time to process the request. I want to ...
How to properly transform a sync function to an async one?
I'm writing a telegram bot and I need the bot to be available to users even when it is processing some previous request. My bot downloads some videos and compresses them if it exceeds the size limit, so it takes some time to process the request. I want to turn my sync functions to async ones and handle them within anot...
[ "The article runs a nice experiment, but it really is just meant to work with a threaded-pool exercutor - not a multi-processing one.\nIf you see its code, at some point it passes executor=None to the .run_in_executor call, and asyncio creates a default executor which is a ThreadPoolExecutor.\nThe main difference...
[ 1 ]
[]
[]
[ "process_pool", "python", "python_3.x", "python_asyncio", "python_decorators" ]
stackoverflow_0074359811_process_pool_python_python_3.x_python_asyncio_python_decorators.txt
Q: Loop through either Pandas dataframe or Excel Sheet with Python I want to preface this that I am VERY new to Python so I am very much learning as I go. Project: Scrape data from an HTML table, clean the data up and append to a copied template in Excel for a shipping report. Current Code: In my first step I get the...
Loop through either Pandas dataframe or Excel Sheet with Python
I want to preface this that I am VERY new to Python so I am very much learning as I go. Project: Scrape data from an HTML table, clean the data up and append to a copied template in Excel for a shipping report. Current Code: In my first step I get the data via: import xlwings as xw import pandas as pd import openpyxl ...
[ "So basically you are trying to do two things:\n\nYou want to delete rows in the table, based on the \"Progress Point\" column:\ndf = df[df['Progress Point] != 'Cancelled']\n\n(Get only columns where the value of 'Progress Point' is not 'Cancelled')\n\nYou want to drop columns you don't need:\ncolumns_to_drop = ['L...
[ 0 ]
[]
[]
[ "excel", "python" ]
stackoverflow_0074361610_excel_python.txt
Q: Plot according to data value I am new with the library mathplotlib on python. I have a dataset containing french city with latitude and longitude and a mark between 0 and 10 for each of them. The higher the mark is, the better I want to plot this coordinates on a map, and change the plotting color according to the...
Plot according to data value
I am new with the library mathplotlib on python. I have a dataset containing french city with latitude and longitude and a mark between 0 and 10 for each of them. The higher the mark is, the better I want to plot this coordinates on a map, and change the plotting color according to the mark (0 = red, 10 = green). I man...
[ "You can add that column as a color marker like so:\ntmp_geo.plot(ax = axis, c=tmp_geo.COM_MARK)\nNOTE: be sure to remove the color argument first\n", "The parameter you are looking for is column, that specifies which column should be use as value.\nPlus, since I don't think there is a red to green colormap, you ...
[ 0, 0 ]
[]
[]
[ "geopandas", "matplotlib", "pandas", "python" ]
stackoverflow_0074361146_geopandas_matplotlib_pandas_python.txt
Q: is there any rest api url for get all virtual machine compliance status? I am using this api url for getting virtual machine compliance status, however its giving me 202 Accepted response. I have attached image for reference, I wanted to get these information through api. A: I tried to reproduce the same in my e...
is there any rest api url for get all virtual machine compliance status?
I am using this api url for getting virtual machine compliance status, however its giving me 202 Accepted response. I have attached image for reference, I wanted to get these information through api.
[ "I tried to reproduce the same in my environment and got below results:\nI created one Azure AD application named WebApp and granted API permission like below:\n\nI generated access token via Postman with below parameters:\nPOST https://login.microsoftonline.com/<tenantID>/oauth2/v2.0/token\n\nclient_id: appID\ngra...
[ 0 ]
[]
[]
[ "azure", "azure_automation", "azure_management_api", "azure_vm", "python" ]
stackoverflow_0074349668_azure_azure_automation_azure_management_api_azure_vm_python.txt
Q: Python threading not waiting - could be related to OO design issue To my mind, I have a fairly simple long-IO operation that could be refined using threading. I've built a DearPyGui GUI interface (not explicitly related to the problem - just background info). A user can load a file via the package's file loader. ...
Python threading not waiting - could be related to OO design issue
To my mind, I have a fairly simple long-IO operation that could be refined using threading. I've built a DearPyGui GUI interface (not explicitly related to the problem - just background info). A user can load a file via the package's file loader. Some of these files can be quite large (3 GB). Therefore, I'm adding a p...
[ "I solved it. In the threading.Thread() do not call the method using self. Instead, pass self in as an argument to the thread method e.g.,\nthread = threading.Thread(target=threadMethod, args=(self, fileName))\n\nThe target function doesn't change i.e. it remains as so:\ndef threadMethod(self, fileName):\n #expe...
[ 0 ]
[]
[]
[ "multithreading", "python", "python_multithreading" ]
stackoverflow_0074346077_multithreading_python_python_multithreading.txt
Q: Oracle 19c connection with python Listener refused connection I'm using oracledb library as the cx_oracle is not working now, using the command oracledb.connect(), and it always gives error here is my code: connection = oracledb.connect( user='myusername', password='mypassword', dsn='xx.xx.xxx.xxx:p...
Oracle 19c connection with python Listener refused connection
I'm using oracledb library as the cx_oracle is not working now, using the command oracledb.connect(), and it always gives error here is my code: connection = oracledb.connect( user='myusername', password='mypassword', dsn='xx.xx.xxx.xxx:portnumber/dsnname') print("Successfully connected to Oracle Databas...
[ "The error (ORA-12660) indicates that you have encryption or checksumming parameters set on the database. These are set up in the server side sqlnet.ora and look something like this:\nSQLNET.ENCRYPTION_SERVER=REQUIRED\nSQLNET.CRYPTO_CHECKSUM_SERVER=REQUIRED\nSQLNET.ENCRYPTION_TYPES_SERVER=(AES256,AES192,AES128)\nSQ...
[ 1 ]
[]
[]
[ "oracle19c", "python", "python_3.x", "python_oracledb" ]
stackoverflow_0074356755_oracle19c_python_python_3.x_python_oracledb.txt
Q: How to stop a nested forloop after a condition is met in python so I have been trying to stop a forloop after a condition is met. Here is the code DATA_t = pd.read_excel('C:/Users/yo4226ka/Work Folders/Desktop/Teaching/IKER STUFF/iker1.xlsx',index_col=0, header = 0) DATA_1 = DATA_t[["Código de Provincia","Código ...
How to stop a nested forloop after a condition is met in python
so I have been trying to stop a forloop after a condition is met. Here is the code DATA_t = pd.read_excel('C:/Users/yo4226ka/Work Folders/Desktop/Teaching/IKER STUFF/iker1.xlsx',index_col=0, header = 0) DATA_1 = DATA_t[["Código de Provincia","Código de Municipio","Papeletas a candidaturas"]] cols_i= ["Código de Prov...
[ "You can use break.\nWherever you use break statement, the current loop itself exists or let's say the execution line continues after the for-loop block. Your current for-loop is the nested one so after exiting(by break) you end up running the next iteration of the \"outer\" for loop(since you don't have any statem...
[ 1 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0074362148_for_loop_python.txt
Q: Python: Adding multiple lines on a map between sets of coordinates I have the following code which works well: import plotly.graph_objects as go fig = go.Figure(go.Scattermapbox( mode = "markers+lines", lon = [-74.164556, -73.214697], lat = [41.515941, 41.474395], marker = {'size':...
Python: Adding multiple lines on a map between sets of coordinates
I have the following code which works well: import plotly.graph_objects as go fig = go.Figure(go.Scattermapbox( mode = "markers+lines", lon = [-74.164556, -73.214697], lat = [41.515941, 41.474395], marker = {'size': 10})) fig.update_layout( margin ={'l':0,'t':0,'b':0,'r':0}, ...
[ "With your data format, it's best to loop over the start and end coordinate pairs. Otherwise I think it should be a list with alternating start and end coordinates.\nimport plotly.graph_objects as go\n\nfig = go.Figure()\n\nfor row in data.itertuples():\n fig.add_trace(go.Scattermapbox(\n mode = \"markers...
[ 2 ]
[]
[]
[ "maps", "plotly", "python" ]
stackoverflow_0074358612_maps_plotly_python.txt
Q: Filtering nested lists with python conditions how are you? I have a distance matrix and need to perform a filter based on another list before applying some functions. The matrix has 10 elements that represent machines and the distances between them, I need to filter this list by getting only the distances between ...
Filtering nested lists with python conditions
how are you? I have a distance matrix and need to perform a filter based on another list before applying some functions. The matrix has 10 elements that represent machines and the distances between them, I need to filter this list by getting only the distances between some chosen machines. matrix = [[0, 1, 3, 17, 24, 1...
[ "You forgot to filter by column ids. You can do this using nested list comprehensions.\nfinal_matrix = [[matrix[row-1][col-1] for col in filter_list] for row in filter_list]\n\n", "final_matrix = []\n\nfor i in filter_list:\n to_append = []\n for j in filter_list:\n to_append.append(matrix[i-1][j-1])...
[ 2, 1 ]
[]
[]
[ "nested_lists", "python" ]
stackoverflow_0074362386_nested_lists_python.txt
Q: How to filter dictionary values according to a given list of values? I have a list and a dictionary: my_list = ['white', 'grey', 'black'] my_dict = {'name1': ['green', 'yellow', 'orange', 'black'], 'name2': ['red', 'yellow', 'orange', 'purple', 'white', 'black'], 'name3': ['blue', 'red', 'gr...
How to filter dictionary values according to a given list of values?
I have a list and a dictionary: my_list = ['white', 'grey', 'black'] my_dict = {'name1': ['green', 'yellow', 'orange', 'black'], 'name2': ['red', 'yellow', 'orange', 'purple', 'white', 'black'], 'name3': ['blue', 'red', 'grey', 'orange', 'black']} I want to get a filtered dictionary according to...
[ "I would use a dictionary comprehension here.\n>>> my_list = [\"white\", \"grey\", \"black\"]\n>>>\n>>> my_dict = {\n... \"name1\": [\"green\", \"yellow\", \"orange\", \"black\"],\n... \"name2\": [\"red\", \"yellow\", \"orange\", \"purple\", \"white\", \"black\"],\n... \"name3\": [\"blue\", \"red\", \"g...
[ 5 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074362471_dictionary_list_python.txt
Q: How can I get features names when there is a preprocessor before feature selection? I tried checking some posts like this, this and this but I still couldn't find what I need. These are the transformations I'm doing: cat_transformer = Pipeline(steps=[("encoder", TargetEncoder())]) num_transformer = Pipeline( ...
How can I get features names when there is a preprocessor before feature selection?
I tried checking some posts like this, this and this but I still couldn't find what I need. These are the transformations I'm doing: cat_transformer = Pipeline(steps=[("encoder", TargetEncoder())]) num_transformer = Pipeline( steps=[ ("scaler", MinMaxScaler()), ("poly", PolynomialFeatures(2, intera...
[ "Use model[:-1].get_feature_names_out().\nThe problem is that your preprocessor outputs a numpy array, so the feature selection step never sees feature names. But the pipeline's get_feature_names_out method steps the feature names forward through each transformer, so taking the pipeline excluding the logistic regr...
[ 0 ]
[]
[]
[ "feature_selection", "machine_learning", "pipeline", "python", "scikit_learn" ]
stackoverflow_0074361372_feature_selection_machine_learning_pipeline_python_scikit_learn.txt
Q: Why is a python variable, which is declared(assigned a value),of type class? I declare a variable and assign it an integer value, its type is <class 'int>. Shouldn't that be an object? If I define a class and instantiate its object, the type of the object is again class. If I assign a variable to object, the varia...
Why is a python variable, which is declared(assigned a value),of type class?
I declare a variable and assign it an integer value, its type is <class 'int>. Shouldn't that be an object? If I define a class and instantiate its object, the type of the object is again class. If I assign a variable to object, the variable is <class 'object> and its type is <class 'type'> (refer the corresponding sh...
[ "All values in Python are objects, in the sense that each value has a type associated with it. (Variables themselves to not have types; type(a) simply reports the inherent type of whatever value as assigned to the name a.)\nFurther, classes themselves are first-class values with their own type. Just as the type of ...
[ 3, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0074362110_oop_python.txt
Q: Python 3 - Finding single number within a non-empty array I am trying to solve a leetcode problem, in which I have to find the number in a list that does not repeat. I have written this code, but it fails in this test case. I cannot seem to understand why it fails in this case. Can someone give me an explanation? ...
Python 3 - Finding single number within a non-empty array
I am trying to solve a leetcode problem, in which I have to find the number in a list that does not repeat. I have written this code, but it fails in this test case. I cannot seem to understand why it fails in this case. Can someone give me an explanation? this is the code: class Solution: def singleNumber(self, nu...
[ "I'm surprised that this code passed 28 test cases without triggering the bug. The way that you use remove is buggy, and also not needed. I don't see any good reason to mutate the list.\nThe core problem is that you seem to think that remove removes all occurrences on an item. It doesn't -- it only removes the firs...
[ 0 ]
[]
[]
[ "arrays", "python", "python_3.x" ]
stackoverflow_0074359039_arrays_python_python_3.x.txt
Q: How to disable cookie handling with the Python requests library? When I use requests to access an URL cookies are automatically sent back to the server (in the following example the requested URL set some cookie values and then redirect to another URL that display the stored cookie) >>> import requests >>> respons...
How to disable cookie handling with the Python requests library?
When I use requests to access an URL cookies are automatically sent back to the server (in the following example the requested URL set some cookie values and then redirect to another URL that display the stored cookie) >>> import requests >>> response = requests.get("http://httpbin.org/cookies/set?k1=v1&k2=v2") >>> res...
[ "You can do this by defining a cookie policy to reject all cookies:\nfrom http import cookiejar # Python 2: import cookielib as cookiejar\nclass BlockAll(cookiejar.CookiePolicy):\n return_ok = set_ok = domain_return_ok = path_return_ok = lambda self, *args, **kwargs: False\n netscape = True\n rfc2965 = hi...
[ 31, 0, 0, 0 ]
[ "class BlockAll(CookiePolicy):\n def set_ok(self, cookie, request):\n return False\nsession.cookies.policy = BlockAll()\n\n" ]
[ -1 ]
[ "cookies", "python", "python_requests" ]
stackoverflow_0017037668_cookies_python_python_requests.txt
Q: Python 3 Unit tests with user input I'm absolutely brand new to Python unit test. I need to use it for a project I have to submit. I sort of have an idea of where to begin, it looks like we basically put in test parameters to functions we have defined in our program and we enter the expected result. If the expecte...
Python 3 Unit tests with user input
I'm absolutely brand new to Python unit test. I need to use it for a project I have to submit. I sort of have an idea of where to begin, it looks like we basically put in test parameters to functions we have defined in our program and we enter the expected result. If the expected result is output, we get OK, otherwise ...
[ "You can use mocking, where you replace a function or class with a test-supplied version. You can do this with the unittest.mock() module.\nIn this case, you can patch the input() name in your module; instead of the built-in function, the mock object will be called:\nfrom unittest import mock\nfrom unittest import ...
[ 27, 0 ]
[]
[]
[ "python", "python_3.x", "unit_testing" ]
stackoverflow_0047690020_python_python_3.x_unit_testing.txt
Q: How can I retrieve the first N items from a TensorFlow batch dataset, and not an iterator that reevaluates to different items? I would like to retrieve the first N items from a BatchDataSet. I have tried a number of different ways to do this, and they all retrieve different items when reevaluated. However I woul...
How can I retrieve the first N items from a TensorFlow batch dataset, and not an iterator that reevaluates to different items?
I would like to retrieve the first N items from a BatchDataSet. I have tried a number of different ways to do this, and they all retrieve different items when reevaluated. However I would like to retrieve N actual items, not an iterator that will continue to retrieve new items. import tensorflow as tf import numpy as...
[ "Iterating over a tf.data.Dataset will trigger shuffling every time. You could set shuffle to False to get deterministic results:\nimport tensorflow as tf\nimport pathlib\nimport matplotlib.pyplot as plt\n\ndataset_url = \"https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz\"\nda...
[ 1 ]
[]
[]
[ "keras", "python", "tensorflow", "tensorflow_datasets" ]
stackoverflow_0074362414_keras_python_tensorflow_tensorflow_datasets.txt
Q: How to set connection timeout in SQLAlchemy I'm trying to figure out how to set the connection timeout in create_engine(), so far I've tried: create_engine(url, timeout=10) TypeError: Invalid argument(s) 'timeout' sent to create_engine(), using configuration PGDialect_psycopg2/QueuePool/Engine. Please check th...
How to set connection timeout in SQLAlchemy
I'm trying to figure out how to set the connection timeout in create_engine(), so far I've tried: create_engine(url, timeout=10) TypeError: Invalid argument(s) 'timeout' sent to create_engine(), using configuration PGDialect_psycopg2/QueuePool/Engine. Please check that the keyword arguments are appropriate for thi...
[ "The right way is this one (connect_timeout instead of connection_timeout):\ncreate_engine(db_url, connect_args={'connect_timeout': 10})\n\n...and it works with both Postgres and MySQL\ndocs sqlalchemy connect-args\nps: (the timeout is defined in seconds)\n", "For whoever is using Flask-SQLAlchemy instead of plai...
[ 87, 16, 7, 4, 2, 2, 1, 0, 0 ]
[]
[]
[ "postgresql", "psycopg2", "python", "sqlalchemy" ]
stackoverflow_0035640726_postgresql_psycopg2_python_sqlalchemy.txt
Q: TensorFlow reshape after text_dataset_from_directory After the data is loaded with tf.keras.preprocessing.text_dataset_from_directory, the shape is (10, 1). However, the shape needs to be (10,). How could the shape be changed? train_data = tf.keras.preprocessing.text_dataset_from_directory( "data/text", ba...
TensorFlow reshape after text_dataset_from_directory
After the data is loaded with tf.keras.preprocessing.text_dataset_from_directory, the shape is (10, 1). However, the shape needs to be (10,). How could the shape be changed? train_data = tf.keras.preprocessing.text_dataset_from_directory( "data/text", batch_size=1) train_features_batch, train_labels_batch = ne...
[ "For the benefit of the community posting the comments of @Frightera and @RishabhGupta in the Answer section.\nYou can use tf.squeeze(), which removes dimensions of size 1 from the shape of a tensor like below\ntrain_data.map(lambda x: tf.squeeze(x))\n\nOR\nYou can use tf.reshape(), which reshapes a tensor like be...
[ 0 ]
[]
[]
[ "python", "tensorflow" ]
stackoverflow_0068782423_python_tensorflow.txt
Q: Hashing message using CryptoJS output is different from python hashlib that includes Unicode characters What I'm trying to do is hash a message but it contains a Unicode charset. What I've done so far in NodeJS :- const CryptoJS = require('crypto-js'); let message = '\x1aSmartCash Signed Message:\n\xabCTxIn(COutP...
Hashing message using CryptoJS output is different from python hashlib that includes Unicode characters
What I'm trying to do is hash a message but it contains a Unicode charset. What I've done so far in NodeJS :- const CryptoJS = require('crypto-js'); let message = '\x1aSmartCash Signed Message:\n\xabCTxIn(COutPoint(7bb8ad134928a003752beb098471af5a66fc5475ff96b5ba4c2e1c4cbac3aa13, 0), scriptSig=)000000000002c5c2ef4afc5...
[ "message in the Python code is a byte string, i.e. a sequence of bytes. In particular, \\xab in the message corresponds to the byte 0xab.\nIn the CryptoJS code, message is a string that is implicitly UTF-8 encoded in CryptoJS.SHA256(message). Here all characters beyond U+007f are represented by more than one byte. ...
[ 1 ]
[]
[]
[ "cryptojs", "hashlib", "node.js", "python" ]
stackoverflow_0074361783_cryptojs_hashlib_node.js_python.txt
Q: Seaborn set_style() is changing the axes background color and the figure background color I am trying to use different colors for axes background color and figure background color using the matplotlib and seaborn. I got the following graph. sns.set(rc = {'axes.facecolor': 'yellow', 'figure.facecolor': 'red'}) plt....
Seaborn set_style() is changing the axes background color and the figure background color
I am trying to use different colors for axes background color and figure background color using the matplotlib and seaborn. I got the following graph. sns.set(rc = {'axes.facecolor': 'yellow', 'figure.facecolor': 'red'}) plt.figure(figsize = (6,6)) sns.scatterplot(x = x, y = y, data = df) plt.show() But I don't want ...
[ "The axes.facecolor is part of the style definition, so if you want to use a seaborn style but also override some of its parameters, you need to do both at the same time:\nsns.set_theme(style='ticks', rc={'axes.facecolor': 'yellow', 'figure.facecolor': 'red'})\nplt.figure(figsize=(6,6))\nsns.scatterplot(x=x, y=y, d...
[ 2 ]
[]
[]
[ "matplotlib", "python", "seaborn", "visualization" ]
stackoverflow_0074361734_matplotlib_python_seaborn_visualization.txt
Q: Replace one Column in a Multidimensional Array in a For Loop Current state: 1 Multi Array np.ndarray (2000 Rows and 7 Columns) Then I have a function (for loop) which only looks at one (2000 Rows and 1 Column) at a time -> So the For Loop is going to run 7 Times The Calculations will be stored in another array cal...
Replace one Column in a Multidimensional Array in a For Loop
Current state: 1 Multi Array np.ndarray (2000 Rows and 7 Columns) Then I have a function (for loop) which only looks at one (2000 Rows and 1 Column) at a time -> So the For Loop is going to run 7 Times The Calculations will be stored in another array called out (2000 Rows and 1 Column) Problem: I want to store the Resu...
[ "You can use array slicing to access subarrays of a np.ndarray:\n# Assuming 'Row-Major' storage\ncolumn = arr[:,columnIdx]\n\n# Assigning an array of zeros to column\narr[:,columnIdx] = np.zeros_like(column)\n\nEdit: Here is a working example\nimport numpy as np\narr = np.arange(700).reshape(100,7)\n\n# compute val...
[ 0 ]
[]
[]
[ "arrays", "multidimensional_array", "numpy", "python" ]
stackoverflow_0074362036_arrays_multidimensional_array_numpy_python.txt
Q: Beginner question: returning a boolean value from a function in Python I'm trying to get this rock paper scissors game to either return a Boolean value, as in set player_wins to True or False, depending on if the player wins, or to refactor this code entirely so that it doesn't use a while loop. I'm coming from t...
Beginner question: returning a boolean value from a function in Python
I'm trying to get this rock paper scissors game to either return a Boolean value, as in set player_wins to True or False, depending on if the player wins, or to refactor this code entirely so that it doesn't use a while loop. I'm coming from the sysadmin side of the world, so please be gentle if this is written in the...
[ "Ignoring the refactoring issues, you need to understand functions and return values. You don't need a global at all. Ever. You can do this:\ndef rps():\n # Code to determine if player wins\n if player_wins:\n return True\n\n return False\n\nThen, just assign a value to the variable outside this ...
[ 37, 2, 0 ]
[]
[]
[ "boolean", "function", "python" ]
stackoverflow_0004165933_boolean_function_python.txt
Q: How to better visualize Networkx self loop plot? How can I plot the self-loop larger, it is small and does not look good. G = nx.DiGraph() G.add_nodes_from(my_graph.vertex_list) G.add_weighted_edges_from(my_graph.edges_list) weight = nx.get_edge_attributes(G, 'weight') nx.draw_networkx(G, with_labels=True, pos=my...
How to better visualize Networkx self loop plot?
How can I plot the self-loop larger, it is small and does not look good. G = nx.DiGraph() G.add_nodes_from(my_graph.vertex_list) G.add_weighted_edges_from(my_graph.edges_list) weight = nx.get_edge_attributes(G, 'weight') nx.draw_networkx(G, with_labels=True, pos=my_graph.position, node_size= 200, node_color='r', ...
[ "This is an interesting question. The easy (but unreliable) fix imo is to change the figure size:\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nG = nx.DiGraph()\n\nG.add_edge('A','A')\nG.add_edge('A','B')\nG.add_edge('C','B')\nG.add_edge('D','B')\n\npos = {'A':(0,1),'B':(1,1),'C':(0...
[ 0 ]
[]
[]
[ "graph", "matplotlib", "networkx", "python" ]
stackoverflow_0074350464_graph_matplotlib_networkx_python.txt
Q: Running seperate python scripts in same window I have build a game in python, which uses OpenCV to fingerspell letters. Through the first iteration of the program I have stumbled upon a problem regarding creating a GUI interface. The problem is that I am using two python script one for recognition and one for disp...
Running seperate python scripts in same window
I have build a game in python, which uses OpenCV to fingerspell letters. Through the first iteration of the program I have stumbled upon a problem regarding creating a GUI interface. The problem is that I am using two python script one for recognition and one for displaying what the user currently fingerspelled. I woul...
[ "Why do you need this to be multithreaded?\nInside your game simply take a picture of the person on each draw loop and get the letter from that image.\nIf you need to display it you can always blit it to your pygame surface.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074362613_python.txt
Q: I tried to make a calculator but everytime i try subtraction it still makes addition I tried to make a basic calculator by myself. I am complately new and that is why ı don't really know where did ı made the mistake. I can make an addition but still when ı try to make subtraction ıt makes addition again. It ıs my...
I tried to make a calculator but everytime i try subtraction it still makes addition
I tried to make a basic calculator by myself. I am complately new and that is why ı don't really know where did ı made the mistake. I can make an addition but still when ı try to make subtraction ıt makes addition again. It ıs my first project and ı need help. I am waiting for your responds :) mathematical_operation=i...
[ "That's because you used := (walrus) instead of == operator.\nWhen you want to compare values, use == so replace all your:\nif mathematical_operation:='subtraction':\n\nby:\nif mathematical_operation == 'subtraction':\n\n(same goes for \"addition\")\n" ]
[ 1 ]
[ "you need to change input types to integers for calculation.\nfirst=int(input(\"first: \")) # converting str to int\nprint(\"first\")\nsecond=int(input(\"second: \")) # converting str to int\nprint(\"second\")\nsum=float(first) + float(second)\nprint(\"sum\" +str(sum))\n\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0074362063_python.txt
Q: How do I remove substrings from a string if repeated more than once? I am writing a program where the user enters certain substrings, and the code will concatenate them based on overlapping characters. The program works perfectly fine for two strings, however, when I enter three strings, it overlaps two substrings...
How do I remove substrings from a string if repeated more than once?
I am writing a program where the user enters certain substrings, and the code will concatenate them based on overlapping characters. The program works perfectly fine for two strings, however, when I enter three strings, it overlaps two substrings in the string. Here is my code: ` y = int(input("How many strings do you ...
[ "Your code is so much complex to understand... I understand your goal you can solve this solution even with simpler solution.\nimport re\nn= input(\"how many \")\nfs = ''\nfor i in range(int(n)):\n s= input(f\"enter string{i+1} : \")\n fs += s\n \n\nprint(re.sub(r\"(.+?)\\1+\", r\"\\1\", fs))\n\nObsorvatio...
[ 2, 2 ]
[]
[]
[ "python", "string" ]
stackoverflow_0074362072_python_string.txt
Q: Im able to find the quantile but am confused about how to then find the greater values Using df, count the number of rows where car width is greater than the 49th percentile for car width. print("This is the 49th percentile for car Width:") df['car_width'].quantile([.84]) (df['car_width']>"the percentile value") ...
Im able to find the quantile but am confused about how to then find the greater values
Using df, count the number of rows where car width is greater than the 49th percentile for car width. print("This is the 49th percentile for car Width:") df['car_width'].quantile([.84]) (df['car_width']>"the percentile value") I am expecting a list but am getting true/false statements.
[ "Well, yes, that is what a boolean expression (such as ==, isin(...), or in your case >) means on series: a series of boolean.\nIf you want to get the lines matching true values in this series (which is obviously what you want: rows such as (df['car_width']>\"the percentile value\"), get it by using indexing with t...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074349784_pandas_python.txt
Q: Dynamically create columns from string with delimiter in Spark I have a table like this: a | a_vector | 1 | 710.83;-776.98;-10.86;2013.02;-896.28; | 2 | 3 ; 2 ; 1 | Using PySpark/pandas, how do I dynamically create columns so that first values in ...
Dynamically create columns from string with delimiter in Spark
I have a table like this: a | a_vector | 1 | 710.83;-776.98;-10.86;2013.02;-896.28; | 2 | 3 ; 2 ; 1 | Using PySpark/pandas, how do I dynamically create columns so that first values in vector go to "col1" and second values go to "col2" etc. + calculate ...
[ "with names\ndfs = df['a_vector'].str.split(';', expand=True).rename(columns = lambda x: \"col\"+str(x+1))\ndf =pd.concat([df, dfs], axis=1)\nprint(df)\n\ninputs\n a a_vector\n0 1 300;-200;2022\n1 2 3;2;1\n\nOutput\n a a_vector col1 col2 col3\n0 1 300;-200;2022 300 -200 2022\n1 2...
[ 1, 1 ]
[]
[]
[ "dataframe", "multiple_columns", "pandas", "pyspark", "python" ]
stackoverflow_0074361797_dataframe_multiple_columns_pandas_pyspark_python.txt
Q: extract colors of rubiks cube using opencv and python I am trying to write a python program to extract colors of rubiks cube, i am stuck at recognizing / masking stage ( so as to separate the rubiks cube from background ). What i do is: canny edge detection dilate contours countour approximation But i still end ...
extract colors of rubiks cube using opencv and python
I am trying to write a python program to extract colors of rubiks cube, i am stuck at recognizing / masking stage ( so as to separate the rubiks cube from background ). What i do is: canny edge detection dilate contours countour approximation But i still end up with too many contours, cause of background objects etc....
[ "The code described below is over on github in main.py here simbo1905/CubieMoves. Note that link points to the first commit that has a working solve that is detailed below.\nMy approach will be to get the user to hold the cube face close and centre until it is the correct size. This is what apps do to have you scan...
[ 1, 0 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0069350874_opencv_python.txt
Q: Analyzing dataframe with hourly data I would like to analyze a dataframe with hourly data for several days, e.g. df: DATE TIME Threshold Value 2022-11-04 02:00:00 10 9 2022-11-04 03:00:00 11 10 2022-11-04 04:00:00 10 11 2022-11-04 06:00:00 12 11...
Analyzing dataframe with hourly data
I would like to analyze a dataframe with hourly data for several days, e.g. df: DATE TIME Threshold Value 2022-11-04 02:00:00 10 9 2022-11-04 03:00:00 11 10 2022-11-04 04:00:00 10 11 2022-11-04 06:00:00 12 11 2022-11-04 05:00:00 12 12 ...
[ "at first make DatetimeInex:\ndate_idx=df.iloc[:, :2].astype('str').apply(lambda x: pd.to_datetime(' '.join(x)), axis=1)\n\nand make new column that have Threshold before 4H\nand make result to df1\ndf1 = (df.set_index(date_idx)\n .drop(['DATE', 'TIME'], axis=1)\n .sort_index()\n .assign(new=df1.s...
[ 1, 0 ]
[]
[]
[ "pandas", "python", "time_series" ]
stackoverflow_0074359356_pandas_python_time_series.txt
Q: How to check the username in text file or not and then ask for the password? loginUsername = input("Enter Username: ") loginPassword = input("Enter PASSWORD: ") data=open('database.txt', 'r') accounts = data.readlines() for line in data: accounts = line.split(",") if (loginUsername == accounts[0] and log...
How to check the username in text file or not and then ask for the password?
loginUsername = input("Enter Username: ") loginPassword = input("Enter PASSWORD: ") data=open('database.txt', 'r') accounts = data.readlines() for line in data: accounts = line.split(",") if (loginUsername == accounts[0] and loginPassword == accounts[1]): print("LOGGED IN") else: print("Lo...
[ "# You should always use CamelCase for class names and snake_case\n# for everything else in Python as recommended in PEP8.\nusername = input(\"Enter Username: \")\npassword = input(\"Enter Password: \")\n\n# You can use a list to store the database's credentials.\ncredentials = []\n\n# You can use context manager t...
[ 3, 1 ]
[]
[]
[ "jupyter_notebook", "python" ]
stackoverflow_0074361127_jupyter_notebook_python.txt
Q: Python get domain name and associated IP scapy I am a new beginner in scapy. I would like to know how could I get the domain name in each trace. When I try to print(packet[DNS].qd.qname), it will always show b'f1tata-b.pc.bitgravity.com.'. How do I remove all the b''? When doing [2:] it will always remove the cont...
Python get domain name and associated IP scapy
I am a new beginner in scapy. I would like to know how could I get the domain name in each trace. When I try to print(packet[DNS].qd.qname), it will always show b'f1tata-b.pc.bitgravity.com.'. How do I remove all the b''? When doing [2:] it will always remove the content inside but not outside.
[ "the b means bytes, explanation here\nyour address is just not a string, you can do to decode it using utf-8:\naddr = addr.decode(\"utf-8\") \n\nI didn't get the second part of your question:\n\nI would like to know how do you get a domain that has a id associated?\n\n" ]
[ 0 ]
[]
[]
[ "dns", "python", "scapy" ]
stackoverflow_0074362746_dns_python_scapy.txt
Q: Apache Spark regexp_replace, replace "\n" for the actual representation? I have a DataFrame from Spark, I'm trying to remove any newlines and leave the unprocessed \n symbol instead. Input: "Hello world" Expected Result: Hello\nWorld My code snippet is as follows: df.withColumn('discount_description', regexp_r...
Apache Spark regexp_replace, replace "\n" for the actual representation?
I have a DataFrame from Spark, I'm trying to remove any newlines and leave the unprocessed \n symbol instead. Input: "Hello world" Expected Result: Hello\nWorld My code snippet is as follows: df.withColumn('discount_description', regexp_replace('discount_description', '\n', r'\n')) Unfortunately this doesn't work ...
[ "Try using two backslashes to escape the \\ preceding \\n:\ndf.withColumn('discount_description', regexp_replace('discount_description', '\\n', '\\\\n'))\n\n", "I ended up doing:\ndf.withColumn('discount_description', regexp_replace('discount_description', '\\n', r'\\\\n'))\n\nAnd it worked!\n", "If anybody is ...
[ 0, 0, 0 ]
[]
[]
[ "apache_spark", "pyspark", "python" ]
stackoverflow_0068296482_apache_spark_pyspark_python.txt
Q: not able to replace \n using regex_replace in pyspark I am trying to replace all "\n" characters present in a string column in pyspark. I tried the following which seems not to work df1 = df.withColumn("old_trial_text_clean", f.regexp_replace(f.col("old_trial_text"), "[\\n]", "")) The current dataframe has the ex...
not able to replace \n using regex_replace in pyspark
I am trying to replace all "\n" characters present in a string column in pyspark. I tried the following which seems not to work df1 = df.withColumn("old_trial_text_clean", f.regexp_replace(f.col("old_trial_text"), "[\\n]", "")) The current dataframe has the exact same text in both column old_trial_text_clean '', 'Drug...
[ "You don't need to escape the backslash in a literal newline \\n. Use this version:\ndf1 = df.withColumn(\"old_trial_text_clean\", f.regexp_replace(f.col(\"old_trial_text\"), \"\\n\", \"\"))\n\n", "To fix the above issue I had to use the following regex\ndf1 = df.withColumn(\"old_trial_text_clean\", f.regexp_rep...
[ 0, 0, 0 ]
[]
[]
[ "pyspark", "python", "regex", "regexp_replace" ]
stackoverflow_0070936091_pyspark_python_regex_regexp_replace.txt
Q: Sentence Transformers in Python: "[E1002] Span index out of range" As a programming noob, I am trying to find similar sentences in several hundreds of newspaper articles. I have tried my code with a smaller text sample which has worked brilliantly. Now, with a larger text file (using the same code), I get the erro...
Sentence Transformers in Python: "[E1002] Span index out of range"
As a programming noob, I am trying to find similar sentences in several hundreds of newspaper articles. I have tried my code with a smaller text sample which has worked brilliantly. Now, with a larger text file (using the same code), I get the error code "[E1002] Span index out of range.". This is my code so far: !pip ...
[ "I had a similar problem with the same mistake, and for me it was solved after changing sentences from a list[Span] to list[str] as this is what .encode() requires. Instead of sentences = list(about_doc.sents), write sentences = list(sent.text for sent in about_doc.sents)\n" ]
[ 0 ]
[]
[]
[ "nlp", "python", "sentence_similarity", "sentence_transformers", "spacy" ]
stackoverflow_0073253018_nlp_python_sentence_similarity_sentence_transformers_spacy.txt
Q: Random filter a python list of dictionary to get a new list of dictionary based on same key name I want to form a new list of dictionaries by random choosing dictionary from existing list of dictionary based on same key name. existing_list = [{'topic1': 'question1'}, {'topic2': 'question2'}, {'topic3': 'question3'...
Random filter a python list of dictionary to get a new list of dictionary based on same key name
I want to form a new list of dictionaries by random choosing dictionary from existing list of dictionary based on same key name. existing_list = [{'topic1': 'question1'}, {'topic2': 'question2'}, {'topic3': 'question3'}, {'topic2': 'question4'}, {'topic2': 'question5'}, {'topic1': 'question2'}, {'topic1': 'question3'},...
[ "i think your main problem is how you store your data. having a list of dictionaries with a single key-value pair is not that easy to work with.\na better approach might be to store the different questions in a list for each topic so kind of like this:\nd = {'topic1': [question1, question2, question3], 'topic2': [q...
[ 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074362408_list_python.txt
Q: Attribute Error: 'RandomNumberGenerator._generator_ctor' in gym.utils.seeding I´m trying to run a reinforcement learning algorithm for a production line optimization. As an engineering student I am not very familiar with coding so I´m looking for help from you guys. I get this error when trying to train the agent:...
Attribute Error: 'RandomNumberGenerator._generator_ctor' in gym.utils.seeding
I´m trying to run a reinforcement learning algorithm for a production line optimization. As an engineering student I am not very familiar with coding so I´m looking for help from you guys. I get this error when trying to train the agent: AttributeError: Can't get attribute 'RandomNumberGenerator._generator_ctor' on <mo...
[ "According to my experience, you should try to use gym version 0.25.2 or below (just use pip install gym==0.25.2) because some modules might be deprecated such as mentioned in this page.\nOr, you can use version 0.25.1, as mentioned here.\n" ]
[ 0 ]
[]
[]
[ "openai_gym", "python", "reinforcement_learning", "rllib" ]
stackoverflow_0074302629_openai_gym_python_reinforcement_learning_rllib.txt
Q: Discord.py read json data print and if statement My admins.json { "admins": [ { "admin_name": "admin#5123", "admin_id": "1024561820381491231" } ] } f = open('admins.json') data = json.load(f) for i in data['admins']: print(i) how to check if the memberid from message author in admins...
Discord.py read json data print and if statement
My admins.json { "admins": [ { "admin_name": "admin#5123", "admin_id": "1024561820381491231" } ] } f = open('admins.json') data = json.load(f) for i in data['admins']: print(i) how to check if the memberid from message author in admins.json? i was trying to do if ctx.author.id in admins.j...
[ "Try something like the below\nadmins = {\n \"admins\": [\n {\n \"admin_name\": \"admin#5123\",\n \"admin_id\": \"1024561820381491231\"\n },\n {\n \"admin_name\": \"admin#5123\",\n \"admin_id\": \"102456182038184633\"\n }\n ]\n}\n\n\ndef ...
[ 0 ]
[]
[]
[ "discord.py", "if_statement", "json", "python" ]
stackoverflow_0074362790_discord.py_if_statement_json_python.txt
Q: Compute mean of a groupbby pandas I have a very large dataset about twitter. I want to be able to compute the mean tweets per hour published by the user. I was able to groupby the tweets per hour per user but now how can I compute the mean per hour? I'm not able to write all the code since the dataset has been hea...
Compute mean of a groupbby pandas
I have a very large dataset about twitter. I want to be able to compute the mean tweets per hour published by the user. I was able to groupby the tweets per hour per user but now how can I compute the mean per hour? I'm not able to write all the code since the dataset has been heavily preprocessed. In the dataset I hav...
[ "I'm not sure what the name of your columns are anymore, but it would be something like this:\ngrouped_df.reset_index().groupby(\"user_id\").agg(avgTweetsPerHour = ('created_at','mean'))\n\nAs was commented above, I can't test this without enough information to reproduce it, but the .agg() goes beautifully with .gr...
[ 1, 1, 0, 0 ]
[]
[]
[ "group_by", "pandas", "python" ]
stackoverflow_0074321259_group_by_pandas_python.txt
Q: using set() with pandas May I ask you please if we can use set() to read the data in a specific column in pandas? For example, I have the following output from a DataFrame df1: df1= [ 0 -10 2 5 1 24 5 10 2 30 3 6 3 30 2 1 4 30 4 5 ...
using set() with pandas
May I ask you please if we can use set() to read the data in a specific column in pandas? For example, I have the following output from a DataFrame df1: df1= [ 0 -10 2 5 1 24 5 10 2 30 3 6 3 30 2 1 4 30 4 5 ] where the first co...
[ "set() takes an itterable.\nusing a pandas dataframe as an itterable yields the column names in turn.\nSince you've transposed the dataframe, your index values are now column names, so when you use the transposed dataframe as an itterable you get those index values.\nIf you want to use set to get the values in the ...
[ 0 ]
[]
[]
[ "pandas", "python", "set" ]
stackoverflow_0074362719_pandas_python_set.txt
Q: PyFPDF: Align columns in row I want to align cell and multi-cell in the same row. i = 0 for col in row: if i == 0: self.multi_cell(col_widths[i], 6, col, 1, new_x=XPos.LMARGIN, new_y=YPos.NEXT, align=alignments[i], fill=True) else: self.cell(col_widths[i], 6, col, 1, new_x=XPos.LMARGIN, new...
PyFPDF: Align columns in row
I want to align cell and multi-cell in the same row. i = 0 for col in row: if i == 0: self.multi_cell(col_widths[i], 6, col, 1, new_x=XPos.LMARGIN, new_y=YPos.NEXT, align=alignments[i], fill=True) else: self.cell(col_widths[i], 6, col, 1, new_x=XPos.LMARGIN, new_y=YPos.NEXT, align=alignments[i],...
[ "Why not using multi_cell in both cases? Maybe just have a look to my answer I gave in another thread.\nIn short, build a table with multi_cell and make sure you align them central in vertical direction.\n" ]
[ 0 ]
[]
[]
[ "pyfpdf", "python" ]
stackoverflow_0073633228_pyfpdf_python.txt
Q: replace value in x randomly selected columns in pandas row How do I replace the value in x randomly selected columns in the last two rows of a pandas df? I find this for columns but not for rows. A: You can use random.sample and iloc: import random x = 4 df.iloc[-2:, random.sample(list(range(df.shape[1])), x)]...
replace value in x randomly selected columns in pandas row
How do I replace the value in x randomly selected columns in the last two rows of a pandas df? I find this for columns but not for rows.
[ "You can use random.sample and iloc:\nimport random\n\nx = 4\ndf.iloc[-2:, random.sample(list(range(df.shape[1])), x)] = 'X'\n\nOutput:\n 0 1 2 3 4 5 6 7 8 9\n0 0 1 2 3 4 5 6 7 8 9\n1 10 11 12 13 14 15 16 17 18 19\n2 20 21 22 23 24 25 26 27 28 29\n3 30 ...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074362946_pandas_python.txt
Q: How to return object when using `append` in Python i have a function to append a list, something like this: def append_func(element): if xxxx: new_list.append(element) else: [] I have another function that uses append_func(): def second_func(item): for i in item: append_func(i) if ...
How to return object when using `append` in Python
i have a function to append a list, something like this: def append_func(element): if xxxx: new_list.append(element) else: [] I have another function that uses append_func(): def second_func(item): for i in item: append_func(i) if i run : new_list = [] second _func(item) new_list This ...
[ "According to the clarification you did in the comments you might want something like this. (I changed some of your placeholders so we have running code and a reproducible example)\nThe list is created by second_func so we get rid of the global list.\ndef append_func(data, element):\n if 2 < element < 7:\n ...
[ 2, 1, 0 ]
[]
[]
[ "append", "list", "nonetype", "python", "python_3.x" ]
stackoverflow_0074362513_append_list_nonetype_python_python_3.x.txt
Q: I am getting the Path has no attribute join error Here is the code: from pathlib import Path import sys # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent PROJECT_DIR = Path.join(BASE_DIR, "online_auction") # Quick-start development settings - unsui...
I am getting the Path has no attribute join error
Here is the code: from pathlib import Path import sys # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent PROJECT_DIR = Path.join(BASE_DIR, "online_auction") # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.c...
[ "The BASE_DIR is a pathlib.Path object. This objects provide an easy way to join them by just using the / operator\nfrom pathlib import Path\n\nBASE_DIR = Path(__file__).resolve().parent.parent\nPROJECT_DIR = BASE_DIR / \"online_auction\"\n\n" ]
[ 0 ]
[]
[]
[ "pathlib", "python" ]
stackoverflow_0074362942_pathlib_python.txt
Q: How to send a Direct Message on twitter using Tweppy Client? I am trying to a send a basic direct message on Twitter, but it isn't recognizing 'create_direct_message'. This is the code I am using: Client.create_direct_message(participant_id = '129593148134547046', text = 'Hello') This is the error message: Attrib...
How to send a Direct Message on twitter using Tweppy Client?
I am trying to a send a basic direct message on Twitter, but it isn't recognizing 'create_direct_message'. This is the code I am using: Client.create_direct_message(participant_id = '129593148134547046', text = 'Hello') This is the error message: AttributeError: 'Client' object has no attribute 'create_direct_message'...
[ "The following is steps to send a direct message using Tweepy.\n\nOn the Twitter developer portal you will need to upgrade your account to elevated.\n\nOnce elevated access is approved and create your app, then got user authentication settings.\n\nSet it to the following:\n\nRead and write and Direct message\nNativ...
[ 0 ]
[]
[]
[ "api", "python", "tweepy", "twitter" ]
stackoverflow_0074309089_api_python_tweepy_twitter.txt
Q: Plotting CDF of a pandas series in python Is there a way to do this? I cannot seem an easy way to interface pandas series with plotting a CDF. A: I believe the functionality you're looking for is in the hist method of a Series object which wraps the hist() function in matplotlib Here's the relevant documentat...
Plotting CDF of a pandas series in python
Is there a way to do this? I cannot seem an easy way to interface pandas series with plotting a CDF.
[ "I believe the functionality you're looking for is in the hist method of a Series object which wraps the hist() function in matplotlib\nHere's the relevant documentation\nIn [10]: import matplotlib.pyplot as plt\n\nIn [11]: plt.hist?\n...\nPlot a histogram.\n\nCompute and draw the histogram of *x*. The return value...
[ 93, 45, 15, 14, 11, 6, 2, 1, 1, 0 ]
[]
[]
[ "cdf", "pandas", "python", "series" ]
stackoverflow_0025577352_cdf_pandas_python_series.txt
Q: 'column "survey_data.start_date" must appear in the GROUP BY clause or be used in an aggregate function' when using agg_json I'm trying to run the following PostgreSQL query: sql = """SELECT json_agg(survey_data) FROM survey_data.survey_data WHERE codigo_do_projeto LIKE '%%%s%%' ...
'column "survey_data.start_date" must appear in the GROUP BY clause or be used in an aggregate function' when using agg_json
I'm trying to run the following PostgreSQL query: sql = """SELECT json_agg(survey_data) FROM survey_data.survey_data WHERE codigo_do_projeto LIKE '%%%s%%' ORDER BY data_de_inicio_da_coleta desc LIMIT %s OFFSET %s*%s""" % (survey_name,items_per_page, items_pe...
[ "As the error says data_de_inicio_da_coleta desc needs to be used in a GROUP BY or used in the aggregate function.\nSo your choices are, throw a GROUP BY in the query:\nSELECT json_agg(survey_data)\nFROM survey_data.survey_data \nWHERE codigo_do_projeto LIKE '%%%s%%'\nGROUP BY data_de_inicio_da_coleta desc\nORDER B...
[ 1 ]
[]
[]
[ "postgresql", "python" ]
stackoverflow_0074362322_postgresql_python.txt
Q: How to requests all sizes in stock - Python I'm trying to request all the sizes in stock from Zalando. I can not quite figure out how to do it since the video I'm watching showing how to request sizes look different than min. The video that I watch was this. Video - 5.30 Does anyone know how to request the sizes i...
How to requests all sizes in stock - Python
I'm trying to request all the sizes in stock from Zalando. I can not quite figure out how to do it since the video I'm watching showing how to request sizes look different than min. The video that I watch was this. Video - 5.30 Does anyone know how to request the sizes in stock and print the sizes that in stock? The si...
[ "The sizes are in the page\nI found them in the html, in a javascript tag, in the format\n{\n \"sku\": \"NI112O0BT-A110090000\",\n \"size\": \"42.5\",\n \"deliveryOptions\": [\n {\n \"deliveryTenderType\": \"FASTER\"\n }\n ],\n \"offer\": {\n \"price\": {\n ...
[ 2, 1, 0 ]
[]
[]
[ "beautifulsoup", "html", "python", "python_requests", "web_scraping" ]
stackoverflow_0072319238_beautifulsoup_html_python_python_requests_web_scraping.txt
Q: Export multiple pandas dataframes in one csv I'm trying to export two separate pandas dataframes into one csv file. To merge the dataframes is not an option because they describe different things. If possible I would also like to display one (or more) sentences between the tables. Here as an example: [] [] And thi...
Export multiple pandas dataframes in one csv
I'm trying to export two separate pandas dataframes into one csv file. To merge the dataframes is not an option because they describe different things. If possible I would also like to display one (or more) sentences between the tables. Here as an example: [] [] And this is the result I would like to somehow get to: []...
[ "A great thing to look at would be XLWings: https://www.xlwings.org/\nAlthough XLWings does not work with saving as \".csv\" format, creating the Excel file is pretty simple here and then you can just save the Excel workbook as CSV in Excel.\nYou can then open a workbook and sheet and assign different cells to spec...
[ 0 ]
[]
[]
[ "csv", "dataframe", "export", "pandas", "python" ]
stackoverflow_0074362830_csv_dataframe_export_pandas_python.txt
Q: How to retry in python we know the standard Exception Handling in python: def fun(): a = 1 x = 5 ...... ...... try: print(x) except: print("An exception occurred %d", a) ...... ...... return x+a I want to achieve that if try fails, we will retry again immediately; ...
How to retry in python
we know the standard Exception Handling in python: def fun(): a = 1 x = 5 ...... ...... try: print(x) except: print("An exception occurred %d", a) ...... ...... return x+a I want to achieve that if try fails, we will retry again immediately; if try fails second time, we...
[ "try the retry decorator from package retry\nhttps://pypi.org/project/retry/\npip install retry\n\nthen\nfrom retry import retry\n\n@retry(ZeroDivisionError, tries=4, delay=2, backoff=2)\ndef make_trouble():\n '''Retry on ZeroDivisionError, raise error after 3 attempts, sleep 2 seconds between attempts.'''\n ...
[ 2, 0, 0 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0074362983_exception_python.txt
Q: Django - getting properly formatted decimals in forms (+crispy)? I have the following model: class Probe(models.Model): name = models.CharField("Probe name", max_length=200, blank=True, null=True) order = models.IntegerField("ordering", default=1) digits = models.IntegerField("trailing zeroes", null=Tr...
Django - getting properly formatted decimals in forms (+crispy)?
I have the following model: class Probe(models.Model): name = models.CharField("Probe name", max_length=200, blank=True, null=True) order = models.IntegerField("ordering", default=1) digits = models.IntegerField("trailing zeroes", null=True, blank=True, default=5) class ProbeInst(models.Model): probe =...
[ "OK, i found the solution - adding the deciaml quantize and 'lang':'en' to attributes solved the issue!\nclass ProbeEntryForm(ModelForm):\n# Переопределяем форму\ndef __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n if 'instance' in kwargs:\n # Значение теста цифровое?\n if...
[ 0 ]
[]
[]
[ "django", "django_crispy_forms", "python" ]
stackoverflow_0074343559_django_django_crispy_forms_python.txt
Q: Delete items of a dictionary using a list as condition I have a dictionary like this: features_id = { id1: [a, b, c, d], id2: [c, d], id3: [a, e, f, d, g, k], ... } I have also a list of values I want to create a new dictionary. Something like this: list_of_values = [a, c] Goal to achieve: I ...
Delete items of a dictionary using a list as condition
I have a dictionary like this: features_id = { id1: [a, b, c, d], id2: [c, d], id3: [a, e, f, d, g, k], ... } I have also a list of values I want to create a new dictionary. Something like this: list_of_values = [a, c] Goal to achieve: I want a new dictionary like this: new_dict = { id1: [a, c...
[ "for such a large dataset (1M) it might have sence to use pandas and numpy. i'm not sure about the speed in this case but you can try the following:\nimport pandas as pd\nimport numpy as np\n\nfeatures_id = {\n 'id1': ['a', 'b', 'c', 'd'],\n 'id2': ['c', 'd'],\n 'id3': ['a', 'e', 'f', 'd', 'g', 'k'],\n ...
[ 0, 0, 0 ]
[]
[]
[ "dictionary", "key_value", "list", "python", "python_3.x" ]
stackoverflow_0074353592_dictionary_key_value_list_python_python_3.x.txt
Q: List of CSVs written inside Byte strings to be saved with individual Filenames I have a list of data as byte strings and another list that consists of file names for that data. This data needs to be saved as individual CSV files based on the list of names. I don't know why, but Pandas to_csv isn't working for this...
List of CSVs written inside Byte strings to be saved with individual Filenames
I have a list of data as byte strings and another list that consists of file names for that data. This data needs to be saved as individual CSV files based on the list of names. I don't know why, but Pandas to_csv isn't working for this particular task (probably has to do with the data inside the byte strings). Basical...
[ "You are using a nested loop. The inner loop is iterating over the reports and is writing each report in the file from the outer loop. I.e. your code should write the last report in every available file (it does here). You could fix that by doing something like:\nvalid_reports = (\n report for report in All_repo...
[ 0 ]
[]
[]
[ "csv", "list", "python" ]
stackoverflow_0074356317_csv_list_python.txt
Q: How to find possible permutation of a list that contains images? I am trying to load an image using opencv and then splitting that image into 4 parts. I have saved all the images in a list and now i want to find out all the possible permutation combination. This is my current code. #Importing Libraries import cv2 ...
How to find possible permutation of a list that contains images?
I am trying to load an image using opencv and then splitting that image into 4 parts. I have saved all the images in a list and now i want to find out all the possible permutation combination. This is my current code. #Importing Libraries import cv2 as cv import numpy as np import glob import itertools #Importing Imag...
[ "I expaneded you code a little bit, ran this and it worked for me:\n#Importing Libraries\nimport cv2 as cv\nimport glob\nimport os\nfrom itertools import permutations\n\n#Importing Image\npath = 'cat.jpg'\nimg = cv.imread(path)\n\n#Seperating the height and width from the image data\n(h, w) = img.shape[:2] \n\n#Fin...
[ 1 ]
[]
[]
[ "image_processing", "opencv", "python" ]
stackoverflow_0074362114_image_processing_opencv_python.txt
Q: Python: API request nested dictionaries to dataframe with datetime indexed values I run a query on python to get hourly price data from an API, using the get function: result = (requests.get(url_prices, headers=headers, params={'SpotKey':'1','Fields':'hours','FromDate':'2016-05-05','ToDate':'2016-12-05','Currency'...
Python: API request nested dictionaries to dataframe with datetime indexed values
I run a query on python to get hourly price data from an API, using the get function: result = (requests.get(url_prices, headers=headers, params={'SpotKey':'1','Fields':'hours','FromDate':'2016-05-05','ToDate':'2016-12-05','Currency':'eur','SortType':'ascending'}).json()) where 'SpotKey' identifies the item I want to ...
[ "You did not give examples of the dts, so I cannot verify. But in principle, trating the Date as timestamp and TimeSpan as as timedeltas should give you both the ability to ignore granularity changes and potentialy include additional \"dts\" parsing.\ndef parse_time(x):\n if \"dst\" not in x:\n return x[:...
[ 4, 3 ]
[]
[]
[ "api", "dataframe", "datetime", "pandas", "python" ]
stackoverflow_0074318512_api_dataframe_datetime_pandas_python.txt
Q: Exit a loop from terminal I would like to know how to leave a loop from the terminal, otherwise when closing it... Thanks! I tried 'exit', 'leave' and others keywords like that A: In Mac and Windows: control + C. In general it terminate a process. A: try adding keyboard Interrupt exception try: while True:...
Exit a loop from terminal
I would like to know how to leave a loop from the terminal, otherwise when closing it... Thanks! I tried 'exit', 'leave' and others keywords like that
[ "In Mac and Windows: control + C. In general it terminate a process.\n", "try adding keyboard Interrupt exception\ntry:\n while True:\n pass\nexcept KeyboardInterrupt, e:\n print \"Stopped\"\n raise\n\n" ]
[ 0, 0 ]
[]
[]
[ "object", "python" ]
stackoverflow_0074363167_object_python.txt
Q: bind enter key to run a command in tkinter label I am trying to make a simple find and replace widget in tkinter. I can press the button "RegexReplace" and it works good without any problems. In this widget, we first type if label1, then label2, what I want is when I type text to be replaced in label called "To" a...
bind enter key to run a command in tkinter label
I am trying to make a simple find and replace widget in tkinter. I can press the button "RegexReplace" and it works good without any problems. In this widget, we first type if label1, then label2, what I want is when I type text to be replaced in label called "To" and press Return Key, I want the app to do the find and...
[ "Bind to the appropriate widget\ne_from = tk.Entry(lf00);e_to = tk.Entry(lf00)\n# add '_event' param to the lambda to absorb the unused event\ne_from.bind(\"<Return>\", lambda _event, x=[e_from,e_to]: find_and_replace(x[0],x[1]) )\n\n" ]
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0074363139_python_tkinter.txt
Q: load and show images from dog and cat dataset with keras and python how can i return and display images from dataset using keras and python, this is my code to download and unzip the dataset _URL = 'https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip' data_dir = tf.keras.utils.get_file('cats_a...
load and show images from dog and cat dataset with keras and python
how can i return and display images from dataset using keras and python, this is my code to download and unzip the dataset _URL = 'https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip' data_dir = tf.keras.utils.get_file('cats_and_dogs_filterted', origin=_URL, extract=True) data_dir = pathlib.Path(da...
[ "I was able to replicate the issue in colab. A workaround is to set the cache_subdir, which is an absolute path, and the file will be saved at that location.\n# Set \"cache_subdir\" to path-to-folder\ndata_dir = tf.keras.utils.get_file('cats_and_dogs_filterted', cache_subdir='/content/cats_and_dogs_filterted', ori...
[ 0 ]
[]
[]
[ "keras", "matplotlib", "python", "tensorflow" ]
stackoverflow_0073293342_keras_matplotlib_python_tensorflow.txt
Q: How can you make it so that only a certain role can use a command on a discord bot? It's so that if this person in the server has a certain role, eg. "giveaway person" they are alloud to make a giveaway, but not anyone else I didnt really try much, since I only learned to use the Nextcord library and not Discord l...
How can you make it so that only a certain role can use a command on a discord bot?
It's so that if this person in the server has a certain role, eg. "giveaway person" they are alloud to make a giveaway, but not anyone else I didnt really try much, since I only learned to use the Nextcord library and not Discord library
[ "Going through the nextcord documentation a bit I found this: has_role(item)\n\nA check() that is added that checks if the member invoking the command has the role specified via the name or ID specified.\nIf a string is specified, you must give the exact name of the role, including caps and spelling. \nIf an intege...
[ 1 ]
[]
[]
[ "bots", "discord.py", "nextcord", "python" ]
stackoverflow_0074362873_bots_discord.py_nextcord_python.txt
Q: Allocate total amount to a column using cumulative sum, up to another column's limit Background: I am having a list of several hundred departments that I would like to allocate budget as follow: Each DEPT has an AMT_TOTAL budget within given number of months. They also have a monthly limit LIMIT_MONTH that they c...
Allocate total amount to a column using cumulative sum, up to another column's limit
Background: I am having a list of several hundred departments that I would like to allocate budget as follow: Each DEPT has an AMT_TOTAL budget within given number of months. They also have a monthly limit LIMIT_MONTH that they cannot exceed. As each DEPT plans to spend their budget as fast as possible, we assume they...
[ "Try this:\nfor department in table['DEPT'].unique():\n subset = table[table['DEPT'] == department]\n for index, row in subset.iterrows():\n subset = table[table['DEPT'] == department]\n cumsum = subset.loc[:index-1, 'AMT_ALLOC_MONTH'].sum()\n limit = row['LIMIT_MONTH']\n remaining...
[ 0 ]
[]
[]
[ "conditional_statements", "cumsum", "python" ]
stackoverflow_0074362512_conditional_statements_cumsum_python.txt
Q: OSError: [Errno 28] inotify watch limit reached I am making a python-based web app using Streamlit. After deploying it in Heroku, the build succeeds but there is an application error. I don't have any idea where in the source code this error is being generated. Please help me! The error : 2022-07-18T18:55:37.98542...
OSError: [Errno 28] inotify watch limit reached
I am making a python-based web app using Streamlit. After deploying it in Heroku, the build succeeds but there is an application error. I don't have any idea where in the source code this error is being generated. Please help me! The error : 2022-07-18T18:55:37.985429+00:00 app[web.1]: Inotify._raise_error() 2022-0...
[ "Adding option --server.fileWatcherType none at the command line helped me to resolve similar issue. A full example would look like this:\nstreamlit run app.py --server.fileWatcherType none\n\nMore solutions here\n" ]
[ 0 ]
[]
[]
[ "heroku", "heroku_api", "python", "streamlit" ]
stackoverflow_0073027461_heroku_heroku_api_python_streamlit.txt
Q: Python folium - ValueError: Location values cannot contain NANs I have a problem. After fetching my .csv file in Python I keep getting the following error: ValueError: Location values cannot contain NANs. My code looks like this: df = pd.read_csv("surveyed.csv") fc=folium.FeatureGroup(name="Tbs",overlay=True) c...
Python folium - ValueError: Location values cannot contain NANs
I have a problem. After fetching my .csv file in Python I keep getting the following error: ValueError: Location values cannot contain NANs. My code looks like this: df = pd.read_csv("surveyed.csv") fc=folium.FeatureGroup(name="Tbs",overlay=True) cf_survey_cluster = MarkerCluster(name="Tbs").add_to(map) for i,row i...
[ "You can use the dropna() function to remove nan values from columns.\ndf.dropna(axis='columns')\n\nExample:\ndf = df.dropna(subset=['Longitude','Latitude'])\n\ndf = pd.read_csv(\"surveyed.csv\")\ndf = df.dropna(subset=['Longitude','Latitude'])\n\nfc=folium.FeatureGroup(name=\"To be surveyed\",overlay=True)\ncf_sur...
[ 1 ]
[]
[]
[ "folium", "python" ]
stackoverflow_0074363315_folium_python.txt
Q: How to execute a postgres query with multiple dynamic parameters using python I'm trying to execute a postgres select query using cursor.execute. How can I write the query if the number of parameters change dynamically. E.g One instance the query can be cursor.execute('SELECT name FROM personal_details WHERE id IN...
How to execute a postgres query with multiple dynamic parameters using python
I'm trying to execute a postgres select query using cursor.execute. How can I write the query if the number of parameters change dynamically. E.g One instance the query can be cursor.execute('SELECT name FROM personal_details WHERE id IN (%s, %s)', (3, 4)) an in some other instance the query can be cursor.execute('SEL...
[ "You need to use ANY and psycopg2 list adaption:\n\ncursor.execute(\"SELECT name FROM personal_details WHERE id IN param = ANY(%s)\", [ids])\n\n", "You will need to build your statement dynamically:\nparams = (1, 2, 3, 4, 5)\nsql = f\"SELECT x FROM tbl WHERE id IN ({', '.join(['%s']*len(params))})\"\nprint(sql)\n...
[ 3, 2 ]
[]
[]
[ "postgresql", "python" ]
stackoverflow_0074358591_postgresql_python.txt
Q: How do you write a new text file (and also an excel file) to your default directory or a specific directory using python? I used the code below from Starting Out WIth Python 5th edition and I do not see a text file in the directory I specified. I used Jupyter notebook to run the code: def main(): # Open a f...
How do you write a new text file (and also an excel file) to your default directory or a specific directory using python?
I used the code below from Starting Out WIth Python 5th edition and I do not see a text file in the directory I specified. I used Jupyter notebook to run the code: def main(): # Open a file named philosophers.txt. outfile = open(r'C:\Users\ME\philosophers.txt', 'w') # Write the names of three phi...
[ "Welcome to SO!\nYou should use os module to avoid trouble in cross-platform and do this:\nimport os\nfilename = \"philosophers.txt\"\n\nx = os.path.join(\"C:/Users/ME\", \"filename\")\n\nwith open(x, \"w\") as outfile:\n outfile.write(\"John Locke\\n\")\n outfile.write(\"David Hume\\n\")\n outfile.write(\...
[ 1 ]
[]
[]
[ "jupyter_notebook", "python" ]
stackoverflow_0074363188_jupyter_notebook_python.txt
Q: Is there a semantic error in my code that I'm missing? I made a code to try and compute the partial sum of a series, but it keeps producing a result that's about 0.01 off. It looks pretty straightforward to me and I haven't been able to spot what my mistake might've been, but there's definitely something off. impo...
Is there a semantic error in my code that I'm missing?
I made a code to try and compute the partial sum of a series, but it keeps producing a result that's about 0.01 off. It looks pretty straightforward to me and I haven't been able to spot what my mistake might've been, but there's definitely something off. import math def f(n): s = 0 for x in range(1,n+1): ...
[ "As written, your function computes a good approximation of - (√√e - 1) ~ -0.28402541668774148407342056806244.\nBy applying the fix suggested by jason, the constant is 1/√√e - 1 ~ -0.22119921692859513175482973302168.\nThe discrepancy is larger than 0.01. Given the abnormal assignment to y, we can suspect that you d...
[ 1 ]
[]
[]
[ "calculus", "math", "python" ]
stackoverflow_0074362971_calculus_math_python.txt
Q: (python) subtract value in a list from value in the same list in a for loop / list comprehension suppose i have list1 = [3, 4, 6, 8, 13] in a for loop I want to subtract the value i from the value that comes right after. In the above example: 4-3, 6-4, 8-6, 13-8. (and i want to skip the first value) desired resul...
(python) subtract value in a list from value in the same list in a for loop / list comprehension
suppose i have list1 = [3, 4, 6, 8, 13] in a for loop I want to subtract the value i from the value that comes right after. In the above example: 4-3, 6-4, 8-6, 13-8. (and i want to skip the first value) desired result list2 = [3, 1, 2, 2, 5] can i do this in a for loop / list comprehension? more specifically do I wa...
[ "The dataframe solution has already been posted. This is an implementation for lists:\nlist1 = [3, 4, 6, 8, 13]\n\nlist2 = []\nfor i, v in enumerate(list1):\n list2.append(list1[i] - list1[i-1])\nlist2[0] = list1[0]\n\nprint(list2) # [3, 1, 2, 2, 5]\n\nAnd lastly, in list comprehension:\nlist2 = [list1[i] - lis...
[ 1, 0, 0, 0 ]
[]
[]
[ "dataframe", "list_comprehension", "pandas", "python" ]
stackoverflow_0074363238_dataframe_list_comprehension_pandas_python.txt
Q: Python printing an Else statement when not supposed to I'm having trouble trying to get a game creation exercise to stop printing the else statement (at the bottom of the code block). the idea is, you can navigate from room to room, but if you go in a direction you're not supposed it should tell you. However, it s...
Python printing an Else statement when not supposed to
I'm having trouble trying to get a game creation exercise to stop printing the else statement (at the bottom of the code block). the idea is, you can navigate from room to room, but if you go in a direction you're not supposed it should tell you. However, it seems to be doing that even when you CAN go somewhere. I'd gr...
[ "If you add the following test code to the end of your class (assuming that it is inside a module Room.py):\nif __name__ == \"__main__\":\n print(\"Testing\")\n\n # rooms\n room1 = Room(\"Floor\")\n room2 = Room(\"Kitchen\")\n room3 = Room(\"Living Room\")\n\n # link the rooms\n room2.link_room...
[ 0 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0074363207_if_statement_python.txt
Q: how to represent mp3 file to binary number python I have a project where the user will enter a song and password. the password will be inserted into the song with spread spectrum steganography. This project is made using the django model, where the location of the data is stored in the database while the files tha...
how to represent mp3 file to binary number python
I have a project where the user will enter a song and password. the password will be inserted into the song with spread spectrum steganography. This project is made using the django model, where the location of the data is stored in the database while the files that have been entered will be on the laptop's local stora...
[ "This works uisng bitstring\nimport os\nfrom bitstring import BitArray\n\nb=BitArray(bytes=open(r\"file_example_MP3_700KB.mp3\",'rb').read())\n\n# Store result\nwith open('binary_mp3.txt', 'w') as file1: \n file1.write(b.bin)\n\nSample output I got\n\n" ]
[ 0 ]
[]
[]
[ "audio", "binaryfiles", "converters", "mp3", "python" ]
stackoverflow_0074363257_audio_binaryfiles_converters_mp3_python.txt
Q: matplotlib fill_between leaving gaps between regions I'm trying to use fill_between to fill different regions of a plot, but I get gaps between the regions I'm trying to fill. I've tried using interpolate=True, but this results in non rectangular shapes... ` import matplotlib.pyplot as plt import numpy as np fig,...
matplotlib fill_between leaving gaps between regions
I'm trying to use fill_between to fill different regions of a plot, but I get gaps between the regions I'm trying to fill. I've tried using interpolate=True, but this results in non rectangular shapes... ` import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots() x = np.arange(0, 4 * np.pi, 0.01) y =...
[ "You could do one or both of the following:\n\nuse finer-grainded x values, e.g.x = np.arange(0, 4 * np.pi, 0.0001). This will remove the white stripes at full view, but if you zoom in they will re-appear at a certain zoom level.\n\nfirst draw the green background without a where condition over the full x range and...
[ 0, 0 ]
[]
[]
[ "matplotlib", "maven_shade_plugin", "python" ]
stackoverflow_0074359624_matplotlib_maven_shade_plugin_python.txt
Q: how to make allied vision camera object a global variable? I use allied vision camera, I need to get single frame very frequently, but I found it needs more than 1 sec to find the camera and get single frame. Please look at this code (edited from pymba) from pymba import Vimba, VimbaException from examples.camera....
how to make allied vision camera object a global variable?
I use allied vision camera, I need to get single frame very frequently, but I found it needs more than 1 sec to find the camera and get single frame. Please look at this code (edited from pymba) from pymba import Vimba, VimbaException from examples.camera._display_frame import display_frame def capture_single(): wi...
[ "Depending on your use case, you could either declare the variable outside of the method or create a class that wraps this behavior (the latter is usually preferred).\nIf this is just a one-off script that doesn't really have many components outside of taking the single shot, you could simply use\nwith Vimba() as v...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0073009291_python.txt
Q: Getting error in Visual code studio "ImportError: cannot import name 'DummyOperator' from 'airflow.operators' Getting error while running the airflow DAG code in visual studio code. Error ImportError: cannot import name 'DummyOperator' from 'airflow.operators' (c:\Users\10679196\AppData\Local\Programs\Python\Pytho...
Getting error in Visual code studio "ImportError: cannot import name 'DummyOperator' from 'airflow.operators'
Getting error while running the airflow DAG code in visual studio code. Error ImportError: cannot import name 'DummyOperator' from 'airflow.operators' (c:\Users\10679196\AppData\Local\Programs\Python\Python38\lib\site-packages\airflow\operators\__init__.py) Import Statement from airflow import DAG from airflow.operato...
[ "As per documentation the DummyOperator is deprecated and beginning with the version 2.4.0 is not supported any more.\nYou should use\nfrom airflow.operators.empty import EmptyOperator\n\nBTW your old import seems also incorrect. For airflow < 2.4.0 this should work:\nfrom airflow.operators.dummy import DummyOperat...
[ 2 ]
[]
[]
[ "airflow", "airflow_2.x", "python" ]
stackoverflow_0074345802_airflow_airflow_2.x_python.txt
Q: Pandas: if column names are the same, I want to stack them on top of each other I have a table as following: id a b a b c color 123 1 6 7 3 4 blue 456 2 8 9 7 5 yellow As you can see, some of the columns have the same. What I want to do is to stack the columns with the same names on top of each other (make the...
Pandas: if column names are the same, I want to stack them on top of each other
I have a table as following: id a b a b c color 123 1 6 7 3 4 blue 456 2 8 9 7 5 yellow As you can see, some of the columns have the same. What I want to do is to stack the columns with the same names on top of each other (make the table longer than wider). I have looked into documentations of stack, melt...
[ "You can deduplicate with groupby.cumcount, then stack and groupby.ffill the missing values:\n(df.set_axis(pd.MultiIndex.from_arrays([df.columns,\n df.groupby(level=0, axis=1).cumcount()\n ]), axis=1)\n .stack().groupby(level=0).ffill()\...
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074363466_dataframe_pandas_python.txt
Q: Selenium webdriver click in more than one button at same page I'm trying to use selenium webdriver in python to click in all the thanks button on a page, but the problem is that my script is only clicking on the first button. Below is the part of code that I´m using: counter = 0 while counter < 10: wd.find_ele...
Selenium webdriver click in more than one button at same page
I'm trying to use selenium webdriver in python to click in all the thanks button on a page, but the problem is that my script is only clicking on the first button. Below is the part of code that I´m using: counter = 0 while counter < 10: wd.find_element_by_xpath('//*[contains(@href,"post_thanks.php?do=")]').click()...
[ "Try:\nwd.find_element_by_xpath('(//*[contains(@href,\"post_thanks.php?do=\")])[1]').click()\ntime.sleep(2)\nwd.find_element_by_xpath('(//*[contains(@href,\"post_thanks.php?do=\")])[2]').click()\n\nI do not know why you have the for loop, but as you can see with those xpath we identify the 2 different buttons\nWith...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x", "selenium", "selenium_webdriver" ]
stackoverflow_0074352453_python_python_3.x_selenium_selenium_webdriver.txt
Q: Installation error of scikit-image in python-3.11.0 Getting errors when installing scikit-image with python-3.11.0. The package is simply installed via pip install scikit-image or python -m pip install -U scikit-image. The error messages showed that the problem occur on the wheel building process, and therefore hi...
Installation error of scikit-image in python-3.11.0
Getting errors when installing scikit-image with python-3.11.0. The package is simply installed via pip install scikit-image or python -m pip install -U scikit-image. The error messages showed that the problem occur on the wheel building process, and therefore hinder the scikit-image installation. How could I fix this ...
[ "In my case, this problem was solved via installing a wheel file from:\nhttps://www.lfd.uci.edu/~gohlke/pythonlibs/#scikit-image\nIn my case, I download the cp311 windows amd64 version.\n\nThen, install the .whl file to the virtual environment\n(env) D:\\env>python -m pip install D:\\Download\\scikit_image-0.19.3-c...
[ 1 ]
[]
[]
[ "pip", "python", "scikit_image" ]
stackoverflow_0074356504_pip_python_scikit_image.txt
Q: pytest - combine fixtures into one fixture I would like to have three fixtures. They are used to setup configurations for tests, and specify which tests use which configurations. The three fixtures should be: release_configs dev_configs all_configs If a test uses the fixture "all_configs", it will be tested for ea...
pytest - combine fixtures into one fixture
I would like to have three fixtures. They are used to setup configurations for tests, and specify which tests use which configurations. The three fixtures should be: release_configs dev_configs all_configs If a test uses the fixture "all_configs", it will be tested for each config session run. If a test uses the fixtur...
[ "Pytest fixtures can \"request\" other fixtures, which can be used to combine, filter, or otherwise process.\nhttps://docs.pytest.org/en/7.1.x/how-to/fixtures.html#fixtures-can-request-other-fixtures\n# Arrange\n@pytest.fixture\ndef first_entry():\n return \"a\"\n\n\n# Arrange\n@pytest.fixture\ndef order(first_e...
[ 0 ]
[]
[]
[ "fixtures", "pytest", "python" ]
stackoverflow_0060423342_fixtures_pytest_python.txt
Q: Passing PipelineParameter DataPath in Azure ML The problem with below code is that currently it does not run because of error in line 27: raise ValueError("Unexpected input type: %s" % type(input)) ValueError: Unexpected input type: <class 'azureml.pipeline.core.graph.PipelineParameter'> If I uncomment second data...
Passing PipelineParameter DataPath in Azure ML
The problem with below code is that currently it does not run because of error in line 27: raise ValueError("Unexpected input type: %s" % type(input)) ValueError: Unexpected input type: <class 'azureml.pipeline.core.graph.PipelineParameter'> If I uncomment second data_path_pipeline_param, everything runs as it should. ...
[ "The \"inputs\" parameter is only taking in these types of data:\n :param inputs: A list of input port bindings.\n :type inputs: list[typing.Union[azureml.pipeline.core.graph.InputPortBinding,\n azureml.data.data_reference.DataReference,\n azureml.pipeline.core.P...
[ 0 ]
[]
[]
[ "azure_machine_learning_service", "azureml_python_sdk", "mlops", "python" ]
stackoverflow_0073046894_azure_machine_learning_service_azureml_python_sdk_mlops_python.txt
Q: Python : BeautifulSoup - Find the elements (meta) that doesnt contain specific tag (itemprop) How do i find the elements (meta) that doesn't contain specific attribute (itemprop) HTML: <html><body><meta content="Hello data world" /><meta content="$3500" itemprop="price" /><meta content="9876543210" itemprop="tele...
Python : BeautifulSoup - Find the elements (meta) that doesnt contain specific tag (itemprop)
How do i find the elements (meta) that doesn't contain specific attribute (itemprop) HTML: <html><body><meta content="Hello data world" /><meta content="$3500" itemprop="price" /><meta content="9876543210" itemprop="telephone" /><meta content="DOLLAR" itemprop="unitCode"/></body></html> Beautifulsoup selection : sou...
[ "Just filter with attr.get(\"itemprop\") is None:\nsoup = [\n m for m\n in BeautifulSoup(sampel_html, \"html.parser\").select(\"meta\")\n if m.get(\"itemprop\") is None\n]\nprint(soup)\n\nOutput:\n[<meta content=\"Hello data world\"/>]\n\nOr, how about using select_one()?\nFor example:\nfrom bs4 import Bea...
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "python_3.x" ]
stackoverflow_0074363441_beautifulsoup_python_python_3.x.txt
Q: pywinauto Backend "uia" is not registered! problem I am using pywinauto to control remote desktop. "app = pywinauto.Application(backend="uia").start('mstsc')" When I complier with original python 32-37, it have error: "File "../main.py", line 8, in <module> app = pywinauto.Application(backend="uia").start('mstsc'...
pywinauto Backend "uia" is not registered! problem
I am using pywinauto to control remote desktop. "app = pywinauto.Application(backend="uia").start('mstsc')" When I complier with original python 32-37, it have error: "File "../main.py", line 8, in <module> app = pywinauto.Application(backend="uia").start('mstsc') File "..\pywinauto\application.py", line 905, in __in...
[ "It is typically happened when comtypes is not installed. Do pip install comtypes==1.1.7 for your Python distribution and \"uia\" backend will be available. Maybe use full path to pip.exe to use correct pip. Like <path-to-python>\\Scripts\\pip.exe. <path-to-python> can be obtained this way in the interpreter: impor...
[ 1, 0 ]
[]
[]
[ "python", "pywinauto" ]
stackoverflow_0066470081_python_pywinauto.txt
Q: Pandas dataframe with int8 column showing inconsistent arithmetic (sum and product) I have a dataframe with an int8 column to ensure lower memory. In [1]: df = pd.DataFrame({'a': [100, 50]}, dtype='int8') df Out[1]: a 0 100 1 50 In [2]: df.dtypes Out[2]: a int8 dtype: object sum autom...
Pandas dataframe with int8 column showing inconsistent arithmetic (sum and product)
I have a dataframe with an int8 column to ensure lower memory. In [1]: df = pd.DataFrame({'a': [100, 50]}, dtype='int8') df Out[1]: a 0 100 1 50 In [2]: df.dtypes Out[2]: a int8 dtype: object sum automatically promotes the result to int64 and gives the correct result. In [3]: df.sum() Out[...
[ "numpy is doing that as well:\nnp.array([100, 50], dtype=np.int8).sum()\n\nOutput: 150\nIf you must have an int8, perform an explicit conversion:\ndf.sum().astype(np.int8)\n\noutput:\na -106\ndtype: int8\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "integer", "pandas", "python", "sum" ]
stackoverflow_0074363323_dataframe_integer_pandas_python_sum.txt
Q: How to split a nested list into multiple nested lists? I have a nested list shaped like mylist = [[a, b, c, d], [e, f, g, h], [i, j, k, l]] And i need to split the nested lists so that every two items are grouped together like this: Nested_list = [[[a, b], [c, d], [[e, f], [g, h]], [[i, j], [k, l]] I tried splitti...
How to split a nested list into multiple nested lists?
I have a nested list shaped like mylist = [[a, b, c, d], [e, f, g, h], [i, j, k, l]] And i need to split the nested lists so that every two items are grouped together like this: Nested_list = [[[a, b], [c, d], [[e, f], [g, h]], [[i, j], [k, l]] I tried splitting them by them by usinga for loop that appended them but th...
[ "mylist = [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l']]\n\nnested_list = [ [i[:2], i[2:]] for i in mylist ] \n\nprint(nested_list)\n\nOutput:\n[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']], [['i', 'j'], ['k', 'l']]]\n\n", "mylist = [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j',...
[ 3, 0, 0, 0 ]
[]
[]
[ "group", "list", "nested", "python", "split" ]
stackoverflow_0074363491_group_list_nested_python_split.txt
Q: How to downgrade Python version from 3.9 to 3.7? I'm working on a RaspberryPi. These are my OS informations: pi@raspberrypi:~ $ uname -m armv7l pi@raspberrypi:~ $ cat /etc/os-release PRETTY_NAME="Raspbian GNU/Linux 11 (bullseye)" NAME="Raspbian GNU/Linux" VERSION_ID="11" VERSION="11 (bullseye)" VERSION_CODENAME=b...
How to downgrade Python version from 3.9 to 3.7?
I'm working on a RaspberryPi. These are my OS informations: pi@raspberrypi:~ $ uname -m armv7l pi@raspberrypi:~ $ cat /etc/os-release PRETTY_NAME="Raspbian GNU/Linux 11 (bullseye)" NAME="Raspbian GNU/Linux" VERSION_ID="11" VERSION="11 (bullseye)" VERSION_CODENAME=bullseye ID=raspbian ID_LIKE=debian HOME_URL="http://ww...
[ "Use pyenv for multiple python versions management.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074362860_python.txt
Q: Trivial GUI "update" question with Gtk4 and Python First of all - sorry. I know that this is very trivial, but I just can't wrap my head around this. Total newbie at GUI department. But to the point: My very simple program calls another program that generates a jpeg file. My program then shows that picture. And by...
Trivial GUI "update" question with Gtk4 and Python
First of all - sorry. I know that this is very trivial, but I just can't wrap my head around this. Total newbie at GUI department. But to the point: My very simple program calls another program that generates a jpeg file. My program then shows that picture. And by a push of a button I'd like to generate a new one and s...
[ "OK, I think I'm getting the gist of it:\n\nMy change_picture function is outside of the class\nI was not using \"self\".\n\nThis works:\n#!/usr/bin/env python3\n\nimport gi\nimport sys\nimport os\nimport subprocess\nimport time\ngi.require_version('Gtk', '4.0')\nfrom gi.repository import Gtk\n\nclass AppWindow(Gtk...
[ 0 ]
[]
[]
[ "gtk4", "python" ]
stackoverflow_0074334685_gtk4_python.txt
Q: Get a value from instance of a class class Jokes: def __init__(self, *joke): self.joke_list = [] self.used_joke_list = [] self.joke = joke if self.joke not in self.joke_list and self.joke not in self.used_joke_list: self.add_Joke(joke) def __str__(self): ...
Get a value from instance of a class
class Jokes: def __init__(self, *joke): self.joke_list = [] self.used_joke_list = [] self.joke = joke if self.joke not in self.joke_list and self.joke not in self.used_joke_list: self.add_Joke(joke) def __str__(self): return "{} \n {}".format(self.joke.sp...
[ "It looks like you're confused about whether an instance of the Jokes class represents a single joke or a collection of jokes. I suggest making it be a collection of jokes, meaning that you'd create\na single Jokes object and add a bunch of jokes to it, rather than creating one Jokes object per joke:\nimport rando...
[ 1 ]
[]
[]
[ "class", "methods", "python", "return" ]
stackoverflow_0074363668_class_methods_python_return.txt
Q: Sum of subset of binary variables == 1 in Gurobipy I am writing a very simple optimization model in Gurobipy but am struggling with the binary variable constraints. I have 5 materials in 3 groups. The decision variables are whether or not to use one of the materials and are binary. Each decision variable has a cos...
Sum of subset of binary variables == 1 in Gurobipy
I am writing a very simple optimization model in Gurobipy but am struggling with the binary variable constraints. I have 5 materials in 3 groups. The decision variables are whether or not to use one of the materials and are binary. Each decision variable has a cost coefficient and I am minimizing total cost in the obje...
[ "You certainly can use subsets to form constraints, and here it is the best idea. As long as you provide a valid list or set of indices within the larger set, you should be fine.\nHere is an example in gurobipy. CAUTION: My gurobi license is not current so I cannot execute this code, but I think it is correct an...
[ 1 ]
[]
[]
[ "gurobi", "linear_optimization", "linear_programming", "optimization", "python" ]
stackoverflow_0074353836_gurobi_linear_optimization_linear_programming_optimization_python.txt
Q: My code says The array returned by a function changed size between calls I am trying to draw a graph of f(Pr) IN PYTHON i enred all the needed commands but it still shows the next errors, ..................................................................................................................................
My code says The array returned by a function changed size between calls
I am trying to draw a graph of f(Pr) IN PYTHON i enred all the needed commands but it still shows the next errors, ................................................................................................................................................................................................................
[ "The problem is that you are trying to solve a non-linear equation. The function fsolve is not able to find a solution for all values of Pr.\nYou can see this by plotting the function F for different values of Pr.\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import fsolve\nimport pandas...
[ 0 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0074361480_arrays_python.txt
Q: Python Inventory Allocation Optimization using PuLP I trying to optimize stock allocation using PuLP while maximizing service rate. material_items is a list of part number. material_price is a list of prices. material_demand is a dataframe with material_items as index and quantities per month as columns. from pulp...
Python Inventory Allocation Optimization using PuLP
I trying to optimize stock allocation using PuLP while maximizing service rate. material_items is a list of part number. material_price is a list of prices. material_demand is a dataframe with material_items as index and quantities per month as columns. from pulp import * def otif(part_demand, stocks): """ Ret...
[ "It is impossible to troubleshoot this well because the problem is not reproducible without data. However a couple things to help you:\n\nGet all of your data squared away (and look at it) before you start the model. Get out of pandas and just put the material, costs, demands, etc. into dictionaries. You have ma...
[ 0 ]
[]
[]
[ "inventory", "optimization", "pulp", "python" ]
stackoverflow_0074363675_inventory_optimization_pulp_python.txt
Q: python reduce print statement line how to reduce print statement line to below 80 characters. still want all to be printed on a single line in console print("Adding model: {0} with average giveaway of {1} created at {2}, which is {3} days ago" .format(m.name, m....
python reduce print statement line
how to reduce print statement line to below 80 characters. still want all to be printed on a single line in console print("Adding model: {0} with average giveaway of {1} created at {2}, which is {3} days ago" .format(m.name, m.tags["Mean Giveaway(g)"], ...
[ "Implicit string concatenation:\nprint(\"Adding model: {0} with average \"\n \"giveaway of {1} created at {2}, \"\n \"which is {3} days ago\"\n .format(m.name,\n m.tags[\"Mean Giveaway(g)\"],\n m.created_time,\n (tmzUTC.localize(datetime.utcnow()) -\n ...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0074363872_python.txt