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: Node.js: ECONNRESET when making multipart/form-data post request? I am getting the following error: (node:12268) [https://github.com/node-fetch/node-fetch/issues/1167] DeprecationWarning: form-data doesn't follow the spec and requires special treatment. Use alternative package (Use `node --trace-deprecation ...` t...
Node.js: ECONNRESET when making multipart/form-data post request?
I am getting the following error: (node:12268) [https://github.com/node-fetch/node-fetch/issues/1167] DeprecationWarning: form-data doesn't follow the spec and requires special treatment. Use alternative package (Use `node --trace-deprecation ...` to show where the warning was created) FetchError: request to https://ap...
[ "Adding the following solved the issues.\ndata.append(\n'input',\nfs.createReadStream(`./data/transactions_${process.env.GEBRUIKER}.json`)\n)\n\n", "replace:\nconst data = new FormData();\n\nwith:\nconst data = new URLSearchParams();\n\n" ]
[ 0, 0 ]
[]
[]
[ "fetch", "http", "javascript", "node.js", "python" ]
stackoverflow_0071709706_fetch_http_javascript_node.js_python.txt
Q: how do I find a curve fit model is good for the data? I have a 2D array and I am trying to fit a curve on the data. my objective function is a polynomial function: def objective(x, a, b, c): return a * x + b * x**2 + c I used curve_fit from scipy.optimize to find the suitable curve for the data. But, I need t...
how do I find a curve fit model is good for the data?
I have a 2D array and I am trying to fit a curve on the data. my objective function is a polynomial function: def objective(x, a, b, c): return a * x + b * x**2 + c I used curve_fit from scipy.optimize to find the suitable curve for the data. But, I need to know how much this model is good. what is the difference ...
[ "You are better off using np.polynomial.polynomial.polyfit` to do polynomial fits.\n", "According to the documentation of curve_fit, setting the input argument full_output to True, the function returns some additional information about the optimization; in particular, the function returns a dictionary (infodict) ...
[ 0, 0 ]
[]
[]
[ "curve_fitting", "optimization", "python", "python_3.x", "scipy" ]
stackoverflow_0074483555_curve_fitting_optimization_python_python_3.x_scipy.txt
Q: Python library to convert between SI unit prefixes I'm looking for a python library which comes with support to convert numbers between various SI prefixes, for example, kilo to pico, nano to giga and so on.What would you recommend? A: I ported a simple function (original C version written by Jukka “Yucca” Korpe...
Python library to convert between SI unit prefixes
I'm looking for a python library which comes with support to convert numbers between various SI prefixes, for example, kilo to pico, nano to giga and so on.What would you recommend?
[ "I ported a simple function (original C version written by\nJukka “Yucca” Korpela) to Python for formatting numbers according to SI standards. I use it often, for example, to set tick labels on plots, etc.\nYou can install it with:\npip install si-prefix\n\nThe source is available on GitHub.\nExample usage:\nfrom ...
[ 17, 6, 6, 4, 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0010969759_python.txt
Q: Type Hinting: Use type of a class member as function return type (for inheritance) What is the correct way to reuse the type of a class member to type hint other items in the class? As an example: from typing import Type class Model: pass class ChildModel: childvar = "Child Model" class Base: var: T...
Type Hinting: Use type of a class member as function return type (for inheritance)
What is the correct way to reuse the type of a class member to type hint other items in the class? As an example: from typing import Type class Model: pass class ChildModel: childvar = "Child Model" class Base: var: Type[Model] def fn(self) -> ??: return self.var class Child(Base): var ...
[ "This can be accomplished with Generics.\nfrom typing import Generic, TypeVar\n\nT = TypeVar(\"T\", bound=\"Model\")\n\n\nclass Model:\n pass\n\n\nclass ChildModel(Model):\n childvar = \"Child Model\"\n\n\nclass Base(Generic[T]):\n var: type[T]\n\n def fn(self) -> type[T]:\n return self.var\n\n\n...
[ 2, 0 ]
[]
[]
[ "mypy", "python", "python_3.x", "python_typing", "type_hinting" ]
stackoverflow_0072581534_mypy_python_python_3.x_python_typing_type_hinting.txt
Q: Not able to access all results in notion DB (via python) I have a DB with 106 entries and I can't seem to access the first 6 entries. I tried adding start_cursor and page_size keys to my request but they don't seem to have any effect. If I add them as ints the request gets rejected so I'm adding them as strings - ...
Not able to access all results in notion DB (via python)
I have a DB with 106 entries and I can't seem to access the first 6 entries. I tried adding start_cursor and page_size keys to my request but they don't seem to have any effect. If I add them as ints the request gets rejected so I'm adding them as strings - not sure if this is the issue (I also tried converting to byte...
[ "As it said in the documentation, you can retrieve no more than 100 items per one request, but you can send many consecutive requests. You need to grab the property next_cursor from the response to the previous request and then pass it as a parameter start_cursor in your next request. While the has_more property is...
[ 0, 0 ]
[]
[]
[ "notion_api", "python" ]
stackoverflow_0074493865_notion_api_python.txt
Q: how to replace the comma in numbers in dataframe by dot? I have this dataframe that I wish to replace all the comma by dot, for example it would be 50.5 and 81.5. Unnamed: 0 NB Ppt Resale 5 yrs 10 yrs 15 yrs 20 yrs 1 VLCC 120 114 87 64 50,5 37 3 SUEZMAX 81,5 80 ...
how to replace the comma in numbers in dataframe by dot?
I have this dataframe that I wish to replace all the comma by dot, for example it would be 50.5 and 81.5. Unnamed: 0 NB Ppt Resale 5 yrs 10 yrs 15 yrs 20 yrs 1 VLCC 120 114 87 64 50,5 37 3 SUEZMAX 81,5 80 62 45 36 24 5 LR 2 69 72 57...
[ "A simple way:\nout = df.replace(',', '.', regex=True)\n\nOutput:\n Unnamed: 0 NB Ppt Resale 5 yrs 10 yrs 15 yrs 20 yrs\n1 VLCC 120 114 87 64 50.5 37\n3 SUEZMAX 81.5 80 62 45 36 24\n5 LR 2 69 72 57 42 32 20\n7 AFR...
[ 2, 2 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074493938_dataframe_pandas_python.txt
Q: How does one invert an area of an image with python? I was prompted to modify one of our filters so that we can specify which portion of the image should be modified. row1 and col1 : the top left coordinates the rectangle to modify row2 and col2: the bottom right coordinates of the rectangle to modify I have attme...
How does one invert an area of an image with python?
I was prompted to modify one of our filters so that we can specify which portion of the image should be modified. row1 and col1 : the top left coordinates the rectangle to modify row2 and col2: the bottom right coordinates of the rectangle to modify I have attmepted this but it has not worked. This is what I have attem...
[ "I would do this in numpy. Easier and runs faster.\nfrom PIL import Image\nimport numpy as np\n\nimg = Image.open(\"test186_img.jpg\")\n\ndef invertspot(pic, row1, col1, row2, col2):\n array = np.array(img)\n subset = array[row1:row2, col1:col2]\n subset = 255 - subset\n array[row1:row2, col1:col2] = su...
[ 2, 2 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0074493191_python_python_imaging_library.txt
Q: mongodb find returns json object with keys that start with unwanted dollar sign ($date, $binary..) I am using python 3.9.12 to query mongodb, I then read the values into variables and continue with my logic. Problem is, some of my values have keys that start with dollar sign. Here is an example of a json I get: [ ...
mongodb find returns json object with keys that start with unwanted dollar sign ($date, $binary..)
I am using python 3.9.12 to query mongodb, I then read the values into variables and continue with my logic. Problem is, some of my values have keys that start with dollar sign. Here is an example of a json I get: [ { "_id": { "$oid": "234876234875236752309823" }, "createdAt": { ...
[ "If your data is in a string format (say, from a file), use loads from the bson.json_util module. https://pymongo.readthedocs.io/en/stable/api/bson/json_util.html\nFor the second part, that is just formatting; but beware, this just creates another string output. Chances are the data you are interested in is actuall...
[ 0 ]
[]
[]
[ "bson", "dollar_sign", "mongodb", "pymongo", "python" ]
stackoverflow_0074486368_bson_dollar_sign_mongodb_pymongo_python.txt
Q: Unable to write a code to read table from word document in python I am a newbie and I started learning Python on my own by seeing videos. I have a task to read table from word document using python and populate it to database. I can able to write the code to read the paragraphs by using the below code. Can anyone ...
Unable to write a code to read table from word document in python
I am a newbie and I started learning Python on my own by seeing videos. I have a task to read table from word document using python and populate it to database. I can able to write the code to read the paragraphs by using the below code. Can anyone please guide me how to write the code for reading the table form word d...
[ "You can use the docx library:\nfrom docx import Document\n\ndoc = Document('Text.docx')\n\nfor table in doc.tables:\n for row in table.rows:\n for cell in row.cells:\n print cell.text\n\nSimilar question can be found here: How to read contents of an Table in MS-Word file Using Python?\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074494045_python.txt
Q: Adding a absolute path that has a \f in it While adding an absolute path to my script because it has a \f in it the code won't run properly. C:\Users\showoi\Desktop\website\repository\fileAdder\softwarelisting.xlsx The file is in the same directory as the script but using a relative path won't work. No misspellin...
Adding a absolute path that has a \f in it
While adding an absolute path to my script because it has a \f in it the code won't run properly. C:\Users\showoi\Desktop\website\repository\fileAdder\softwarelisting.xlsx The file is in the same directory as the script but using a relative path won't work. No misspellings or anything.
[ "Use python r string\npath=r'C:\\Users\\showoi\\Desktop\\website\\repository\\fileAdder\\softwarelisting.xlsx'\n\n", "Use one of the following ways:\n\nr\"C:\\Users\\showoi\\Desktop\\website\\repository\\fileAdder\\softwarelisting.xlsx\"\n\n\"C:\\\\Users\\\\showoi\\\\Desktop\\\\website\\\\repository\\\\fileAdder\...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074494202_python.txt
Q: Find mean grouped by column in Spark I have a dataframe such as: Col1 Value 0 20 1 30 1 20 1 10 0 10 2 30 I want to calculate mean and group by Col1, so that the result is: Col1 Value2 0 15 1 20 2 30 I don't know how to get the result (the aggregated mean). One additional problem is that when I try df...
Find mean grouped by column in Spark
I have a dataframe such as: Col1 Value 0 20 1 30 1 20 1 10 0 10 2 30 I want to calculate mean and group by Col1, so that the result is: Col1 Value2 0 15 1 20 2 30 I don't know how to get the result (the aggregated mean). One additional problem is that when I try df.groupBy("Col1") ...
[ "In PySpark version 3, the following code accomplishes exactly what you have pictured above.\nWelcome to\n ____ __\n / __/__ ___ _____/ /__\n _\\ \\/ _ \\/ _ `/ __/ '_/\n /__ / .__/\\_,_/_/ /_/\\_\\ version 3.1.1-amzn-0\n /_/\n\nUsing Python version 3.7.10 (default, Jun 3 2021 0...
[ 0 ]
[]
[]
[ "apache_spark", "python" ]
stackoverflow_0074494082_apache_spark_python.txt
Q: Sorting list of strings based on both sides of a delimiter ("|") in Python 3 I'm looking to sort a list of of strings which illustrate dependencies (the structure of a Bayesian Networks determined through the PC Algorithm). e.g. verbose_struct = ['A', 'C|A,E', 'E', 'B|C,D', 'D'] sorted_struct = ['A', 'E', 'D', 'C...
Sorting list of strings based on both sides of a delimiter ("|") in Python 3
I'm looking to sort a list of of strings which illustrate dependencies (the structure of a Bayesian Networks determined through the PC Algorithm). e.g. verbose_struct = ['A', 'C|A,E', 'E', 'B|C,D', 'D'] sorted_struct = ['A', 'E', 'D', 'C|A,E', 'B|C,D'] The order of the strings is determined by whether or not the depe...
[ "I would just \"make the jump\" here to making a class to hold these objects. by doing so, you can implement your own __lt__ method, which is all that is needed for all of the default sorting methods to sort the objects.\nNote: This example class just deals with \"labels\" so when you are adding dependencies, you...
[ 1, 0 ]
[]
[]
[ "bayesian_networks", "python", "python_3.x", "sorting" ]
stackoverflow_0074491679_bayesian_networks_python_python_3.x_sorting.txt
Q: fixing date shape in pandas dataset in question Hello, I have been trying to standardize the date in the year column to get rid of the decimals and and the random format and keep only the years. Is there an efficient way to do this in Pandas? A: Setup import pandas as pd # 1.5.1 so = pd.DataFrame({ "Countr...
fixing date shape in pandas
dataset in question Hello, I have been trying to standardize the date in the year column to get rid of the decimals and and the random format and keep only the years. Is there an efficient way to do this in Pandas?
[ "Setup\nimport pandas as pd # 1.5.1\n\n\nso = pd.DataFrame({\n \"Countries\": [*[\"Canada\"]*5, *[\"Brazil\"]*5],\n \"Year\": [1990.0, 1991.0, 1992.0, 1993.0, 1994.0, 2020.0, 2021.0, 2021.0, \"2011-21\", 2021.0],\n \"Value\": 1 # placeholder\n})\n\nprint(so)\n\n Countries Year Value\n0 Canada ...
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python", "python_3.x" ]
stackoverflow_0074493847_dataframe_pandas_python_python_3.x.txt
Q: Get a column, modify, re insert into dataframe as new column? I have a dataframe and I am pulling out a specific column with the index. I want to perform a split on that column and get the [1] value. The column looks like; Name t_alpaha_omega t_bravo_omega d_charlie_omega t_delta_omega I need to split on _ and ge...
Get a column, modify, re insert into dataframe as new column?
I have a dataframe and I am pulling out a specific column with the index. I want to perform a split on that column and get the [1] value. The column looks like; Name t_alpaha_omega t_bravo_omega d_charlie_omega t_delta_omega I need to split on _ and get alpha, bravo, charlie, delta. Then add those values as a new colu...
[ "Hope the below code helps.\nnewCol= [] \nfor i in range(len(df)):\n a = df.iloc[i].to_list()\n requiredValue = a.split(\"_\")[1]\n newCol.append(requiredValue)\ndf[\"newValue\"] = requiredValue\n\nIt works perfectly for a string though.\n\n", "For this purpose we could use pd.Series.str.extract and defi...
[ 1, 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074494263_dataframe_pandas_python.txt
Q: thread communication, stop the work of a thread until data is entered PySide I've written a simple window with a start button that starts a Qthread. After a few instructions in the thread, I would like to display a SubWindow using Signal. Unfortunately, Qthread does not stop after displaying subWindow. I'm looking...
thread communication, stop the work of a thread until data is entered PySide
I've written a simple window with a start button that starts a Qthread. After a few instructions in the thread, I would like to display a SubWindow using Signal. Unfortunately, Qthread does not stop after displaying subWindow. I'm looking for a solution like while Qthread is running: stop the Qthread, display a SubWind...
[ "probably just send it over a queue, queue.get() is a blocking function so it will pause the thread execution until someone puts something in the queue.\njust create a queue in the caller, let's call it result_queue, the child will call result_queue.get() on it to sleep and wait for an item to be put in it and the ...
[ 0 ]
[]
[]
[ "multithreading", "pyside", "python" ]
stackoverflow_0074493500_multithreading_pyside_python.txt
Q: NameError: name 'dishID' is not defined. Did you mean: 'dishid'? this is the code of the following function Function: def dishID(): query = 'select count(*), max(DishID) from Dish' cur.execute(query) fetch = cur.fetchall() for i in fetch: if i[0] == 0: return 1 else: ...
NameError: name 'dishID' is not defined. Did you mean: 'dishid'?
this is the code of the following function Function: def dishID(): query = 'select count(*), max(DishID) from Dish' cur.execute(query) fetch = cur.fetchall() for i in fetch: if i[0] == 0: return 1 else: return (int(i[1]) + 1) Error code dishname = input('Enter Di...
[ "Okay I looked at your link and the issue is extremely simple; you defined the function dishID only after you actually call it. Here's a simple example of this issue - here's some code that works fine:\ndef test_function():\n print('hi')\n\ntest_function()\n\nOutput: hi\n\nVersus this code, which references test...
[ 0 ]
[]
[]
[ "function", "mysql", "mysql_connector", "python" ]
stackoverflow_0074494295_function_mysql_mysql_connector_python.txt
Q: Calculate mean/median of values in a column based on dates of another column using Python I have a dataframe consisting of temperature values on one column, and the corresponding dates on another column. The dataframe has a time period of 7 days, with measurements taken every minute, the problem is that I don't kn...
Calculate mean/median of values in a column based on dates of another column using Python
I have a dataframe consisting of temperature values on one column, and the corresponding dates on another column. The dataframe has a time period of 7 days, with measurements taken every minute, the problem is that I don't know how to calculate the mean/median of the temperature and see the output per day. Any thoughts...
[ "Firstly, make sure that the 'Timestamp_0' colum is in datetime format. df.Timestamp_0 = pd.to_datetime(df.Timestamp_0)\nThen, create a column of day: df['day'] = df['Timestamp_0'].dt.day\nThen group the Temperature values by that newly created column and apply either mean or median function:\nper_day_mean_temp = d...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074494320_pandas_python.txt
Q: python readline module giving PermissionError: [Errno 1] only when run at startup I'm making a console based game that saves input history, to help with debugging I created a function that will automatically input commands on start def __readfile (self) -> None: lines = None with open("insts.txt", "r") as ...
python readline module giving PermissionError: [Errno 1] only when run at startup
I'm making a console based game that saves input history, to help with debugging I created a function that will automatically input commands on start def __readfile (self) -> None: lines = None with open("insts.txt", "r") as f: lines = f.read().split("\n") if (lines == None): print("attempte...
[ "It appears to be a Mac-specific issue with readline. According to this answer, you need to use gnureadline on the Mac, rather than readline.\nimport gnureadline as readline\n\n" ]
[ 0 ]
[]
[]
[ "permission_denied", "python", "readline" ]
stackoverflow_0070735564_permission_denied_python_readline.txt
Q: pyodbc with MultiSubnetFailover Recently, one of our servers was migrated to 3-node cluster from a pylon server. The connection string below is what I used previously via python and pyodbc and never had any issues. server = 'test_server' database = 'test_db' cnxn = 'DRIVER={SQL Server};SERVER='+server+';DATABASE...
pyodbc with MultiSubnetFailover
Recently, one of our servers was migrated to 3-node cluster from a pylon server. The connection string below is what I used previously via python and pyodbc and never had any issues. server = 'test_server' database = 'test_db' cnxn = 'DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';Trusted_Connection=yes'...
[ "The ancient SQL Server ODBC driver that ships with Windows doesn't support MultiSubnetFailover. I suggest you move to a modern driver or have your DBA set RegisterAllProvidersIP to zero to support down level clients.\nIn the interim, you could specify the current listener IP address or the host name of the current...
[ 0 ]
[]
[]
[ "database_connection", "odbc", "pyodbc", "python", "sql_server" ]
stackoverflow_0074494262_database_connection_odbc_pyodbc_python_sql_server.txt
Q: How do I call the function next() without type it again? The idea is to be able to call the next number every time it is called data, but as you know I cant type next() everytime in the code, is there a way to achieve that? thanks for your help. class Sample(): def __init__(self, begin, end): self.beg...
How do I call the function next() without type it again?
The idea is to be able to call the next number every time it is called data, but as you know I cant type next() everytime in the code, is there a way to achieve that? thanks for your help. class Sample(): def __init__(self, begin, end): self.begin = begin self.end = end #self.counter = 0 ...
[ "You can hide the call to next() in a property getter.\nclass Sample():\n def __init__(self, begin, end):\n self.begin = begin\n self.end = end\n self._sequence = self.number()\n\n def number(self):\n for i in range(self.begin, self.end):\n yield i\n\n @property\n ...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074493990_python_python_3.x.txt
Q: F-string with jinja templating in airflow to pass dynamic values to op_kwargs I am trying to pull values using xcom_pull in airflow dynamically The below mentioned formatting doesn't work for me when I piece together jinja templating with f-strings in op_kwargs. Appreciate if anyone can help me here. op_kwargs={'n...
F-string with jinja templating in airflow to pass dynamic values to op_kwargs
I am trying to pull values using xcom_pull in airflow dynamically The below mentioned formatting doesn't work for me when I piece together jinja templating with f-strings in op_kwargs. Appreciate if anyone can help me here. op_kwargs={'names':"{{ ti.xcom_pull(key = '" + f'name{i+1}' + ", task_ids='places' ) }}"}
[ "Using fstring require to set proper number of brackets for Jinja. You can do:\nop_kwargs={'names': f\"{{{{ ti.xcom_pull(key='name{i+1}', task_ids='places') }}}}\"}\n\nExample (This is just a minimal example for your parameters to clarify how this works):\nfrom datetime import datetime\nfrom airflow import DAG\nfro...
[ 0 ]
[]
[]
[ "airflow", "f_string", "jinja2", "keyword_argument", "python" ]
stackoverflow_0074494267_airflow_f_string_jinja2_keyword_argument_python.txt
Q: What's the correct way to use a TypeVar with a parameterized bound? I occasionally run into a scenario like the following: from typing import Generic, TypeVar T = TypeVar('T') class Widget(Generic[T]): content: T class Jibbit(Generic[T]): element: T class ThingHolder: thing: Widget | Jibbit In the...
What's the correct way to use a TypeVar with a parameterized bound?
I occasionally run into a scenario like the following: from typing import Generic, TypeVar T = TypeVar('T') class Widget(Generic[T]): content: T class Jibbit(Generic[T]): element: T class ThingHolder: thing: Widget | Jibbit In the Python standard library, this situation arises in logging.handlers.Queue...
[ "It appears that you're supposed to parameterize the types in the bound= itself, and not attempt to parameterize the new type variable:\nThing = TypeVar('Thing', bound=Widget[Any] | Jibbit[Any])\n\n\nclass ThingHolder(Generic[Thing]):\n thing: Thing\n\n def __init__(self, thing: Thing) -> None:\n self....
[ 1 ]
[]
[]
[ "mypy", "python", "type_hinting" ]
stackoverflow_0074494466_mypy_python_type_hinting.txt
Q: Compare with another column value train.loc[:,'nd_mean_2021-04-15':'nd_mean_2021-08-27'] > train['q_5'] I get Automatic reindexing on DataFrame vs Series comparisons is deprecated and will raise ValueError in a future version. Do left, right = left.align(right, axis=1, copy=False)before e.g.left == right` and so...
Compare with another column value
train.loc[:,'nd_mean_2021-04-15':'nd_mean_2021-08-27'] > train['q_5'] I get Automatic reindexing on DataFrame vs Series comparisons is deprecated and will raise ValueError in a future version. Do left, right = left.align(right, axis=1, copy=False)before e.g.left == right` and something strange output with a lot of co...
[ "I've tested your original solution, and two additional ways of performing this comparison you want to make.\nTo cut to the chase, the following option had the smallest execution time:\n\n%%timeit\n\nsliced_df = df.loc[:, 'nd_mean_2021-04-15':'nd_mean_2021-08-27']\ncomparisson_df = pd.DataFrame({col: df['q_5'] for ...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074494050_pandas_python.txt
Q: Passing wildcard LIKE parameter to read_sql_query() Every time I run the code below, I receive an execution failed on sql error. lookup = f'12545%' sql = pd.read_sql_query( ''' Select * From table Where Name like ? ''' ,conn,lookup) Basically, I think I need the following passed inside the double quotes as a para...
Passing wildcard LIKE parameter to read_sql_query()
Every time I run the code below, I receive an execution failed on sql error. lookup = f'12545%' sql = pd.read_sql_query( ''' Select * From table Where Name like ? ''' ,conn,lookup) Basically, I think I need the following passed inside the double quotes as a parameter: "'12545%'" Not sure what the best way there is to...
[ "You need to pass the parameters as a keyword argument, because it's the 5th positional argument to the function.\nYou have to put all the parameters in a list or tuple, not a single string.\nql = pd.read_sql_query(\n'''\nSelect *\nFrom table\nWhere Name like ?\n'''\n,conn,params=[lookup])\n\n" ]
[ 2 ]
[]
[]
[ "pandas", "pyodbc", "python", "sql" ]
stackoverflow_0074494522_pandas_pyodbc_python_sql.txt
Q: TypeError: only integer scalar arrays can be converted to a scalar index for Phase Estimation Write a function to estimate the phase of an image from a symmetric region at the center of k-space. Hint: use the method shown in class, which includes zero-padding and filtering. (see format below. Note: The format belo...
TypeError: only integer scalar arrays can be converted to a scalar index for Phase Estimation
Write a function to estimate the phase of an image from a symmetric region at the center of k-space. Hint: use the method shown in class, which includes zero-padding and filtering. (see format below. Note: The format below is an example format. You can change it as you wish.) def estimate_phs(k_space,N): kx, ky = kdat...
[ "def estimate_phs (kdata,N):\n kx, ky = kdata.shape\n phase = np.zeros((kx,N), dtype=kdata.dtype)\n phase_ref = (ky - (N // 2)) * 2\n hamming = window('hamm', (kx, phase_ref))\n phase[:, ky - phase_ref:ky] = kdata[:, ky - phase_ref:ky] * hamming\n estimated_phase = np.angle(ifft2c(x=phase))\n r...
[ 0 ]
[]
[]
[ "python", "signal_processing" ]
stackoverflow_0074480682_python_signal_processing.txt
Q: How to extract a nested tag? I want to extract 'span' tag from 'p' but I don't know how to do it html = " <div id="tab-description" class="plugin-description section"> <h2 id="description-header">Description</h2> <p><span class="embed-youtube" style="text-align:center; display: block;"><iframe class="youtu...
How to extract a nested tag?
I want to extract 'span' tag from 'p' but I don't know how to do it html = " <div id="tab-description" class="plugin-description section"> <h2 id="description-header">Description</h2> <p><span class="embed-youtube" style="text-align:center; display: block;"><iframe class="youtube-player"src="https://www.youtube...
[ "To get <span> select it directly:\nsoup.find(id=\"tab-description\").p.span\n\nor\nsoup.find(id=\"tab-description\").find('span')\n\nor\nsoup.select_one('#tab-description p > span')\n\nBe aware Not an option to scrape contents from the <iframe>, if this should be the intension. If so? This would be predestined for...
[ 0 ]
[]
[]
[ "beautifulsoup", "html", "python", "web_scraping" ]
stackoverflow_0074494504_beautifulsoup_html_python_web_scraping.txt
Q: How to plot this dataset? (error: no numeric data to plot) So this is how my dataset looks like but when i use plot.line() it gives me the error " no numeric data to plot" apply to numeric doesn't seem to work A: check if the below code helps. import matplotlib.pyplot as plt x = df.iloc[:,0] y = df.iloc[:,1] pl...
How to plot this dataset? (error: no numeric data to plot)
So this is how my dataset looks like but when i use plot.line() it gives me the error " no numeric data to plot" apply to numeric doesn't seem to work
[ "check if the below code helps.\nimport matplotlib.pyplot as plt\nx = df.iloc[:,0]\ny = df.iloc[:,1]\nplt.scatter(x, y, s=area, c=colors, alpha=0.5)\nplt.show()\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074494627_dataframe_pandas_python.txt
Q: Snake Game keep adding food and removing i created a snake game and i have one problem in function food() it keep adding food on screen and removing it i don't know how to fix this i tried with food_statement like = "wait" when there's a food in screen and draw when it's not food can you help me code is working pr...
Snake Game keep adding food and removing
i created a snake game and i have one problem in function food() it keep adding food on screen and removing it i don't know how to fix this i tried with food_statement like = "wait" when there's a food in screen and draw when it's not food can you help me code is working properly until hit food function? import pygame ...
[ "food is called in each frame. Thus, when the coordinates are generated in the function 'food', new random coordinates are generated in each frame. You must set the coordinates of the food once before the application loop:\nfoodx = random.randint(0,750)\nfoody = random.randint(0,550)\n\ndef food():\n pygame.draw...
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074494680_pygame_python.txt
Q: Is it possible to paginate put_item in boto3? When I use boto3 I can paginate if I am making a query or scan Is it possible to do the same with put_item? A: The closest to "paginating" PutItem with boto3 is probably the included BatchWriter class and associated context manager. This class handles buffering and s...
Is it possible to paginate put_item in boto3?
When I use boto3 I can paginate if I am making a query or scan Is it possible to do the same with put_item?
[ "The closest to \"paginating\" PutItem with boto3 is probably the included BatchWriter class and associated context manager. This class handles buffering and sending items in batches. Aside from PutItem, it supports DeleteItem as well.\nHere is an example of how to use it:\nimport boto3\n\ndynamodb = boto3.resource...
[ 2, 1 ]
[]
[]
[ "amazon_dynamodb", "amazon_web_services", "boto3", "python" ]
stackoverflow_0074493780_amazon_dynamodb_amazon_web_services_boto3_python.txt
Q: How can I check for Python version in a program that uses new language features? If I have a Python script that requires at least a particular version of Python, what is the correct way to fail gracefully when an earlier version of Python is used to launch the script? How do I get control early enough to issue an ...
How can I check for Python version in a program that uses new language features?
If I have a Python script that requires at least a particular version of Python, what is the correct way to fail gracefully when an earlier version of Python is used to launch the script? How do I get control early enough to issue an error message and exit? For example, I have a program that uses the ternery operator (...
[ "You can test using eval:\ntry:\n eval(\"1 if True else 2\")\nexcept SyntaxError:\n # doesn't have ternary\n\nAlso, with is available in Python 2.5, just add from __future__ import with_statement.\nEDIT: to get control early enough, you could split it into different .py files and check compatibility in the main f...
[ 117, 107, 34, 22, 15, 9, 8, 7, 3, 2, 2, 1, 1, 1, 1, 1, 0 ]
[ "How about this:\nimport sys\n\ndef testPyVer(reqver):\n if float(sys.version[:3]) >= reqver:\n return 1\n else:\n return 0\n\n#blah blah blah, more code\n\nif testPyVer(3.0) == 1:\n #do stuff\nelse:\n #print python requirement, exit statement\n\n", "The problem is quite simple. You checked if the versi...
[ -2, -3 ]
[ "python", "version" ]
stackoverflow_0000446052_python_version.txt
Q: Split list of dictionaries in separate lists based primarily on list size but secondarily based on condition I currently have a list of dictionaries that looks like that: total_list = [ {'email': 'usera@email.com', 'id': 1, 'country': 'UK'}, {'email': 'usera@email.com', 'id': 1, 'country': 'Germany'}, ...
Split list of dictionaries in separate lists based primarily on list size but secondarily based on condition
I currently have a list of dictionaries that looks like that: total_list = [ {'email': 'usera@email.com', 'id': 1, 'country': 'UK'}, {'email': 'usera@email.com', 'id': 1, 'country': 'Germany'}, {'email': 'userb@email.com', 'id': 2, 'country': 'UK'} {'email': 'userc@email.com', 'id': 3, 'country': 'Ital...
[ "This solution starts of by only working with the list of all emails. The emails are then grouped based on their frequency and the limit on group size. Later the remaining data, i.e. id and country, are joined back on the email groups.\nThe first function create_groups works on the list of emails. It counts the num...
[ 3, 0, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074319258_dictionary_list_python.txt
Q: How to calculate percentage change with zero in pandas? I want to calculate the percentage change for the following data frame. import pandas as pd df = pd.DataFrame({'team': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C'], 'points': [12, 0, 19, 22, 0, 25, 0, 30], 'score': [12, 0, 1...
How to calculate percentage change with zero in pandas?
I want to calculate the percentage change for the following data frame. import pandas as pd df = pd.DataFrame({'team': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C'], 'points': [12, 0, 19, 22, 0, 25, 0, 30], 'score': [12, 0, 19, 22, 0, 25, 0, 30] ...
[ "So you just want to replace the infinite values with 1?\nimport numpy as np\n\ndf[['points', 'score']] = (\n df.groupby('team')\n .pct_change()\n .replace(np.inf, 1)\n)\n\nOutput:\n team points score\n0 A NaN NaN\n1 A -1.0 -1.0\n2 A 1.0 1.0\n3 B NaN NaN\n4 B -1...
[ 1, 0, 0 ]
[]
[]
[ "data_science_experience", "dataframe", "group_by", "pandas", "python" ]
stackoverflow_0074494441_data_science_experience_dataframe_group_by_pandas_python.txt
Q: How do i make a working slash command in discord.py I am trying to make a slash command with discord.py I have tried a lot of stuff it doesn't seem to be working. Help would be appreciated. A: Note: I will include a version for pycord at the end because I think it's much simpler, also it was the original answer....
How do i make a working slash command in discord.py
I am trying to make a slash command with discord.py I have tried a lot of stuff it doesn't seem to be working. Help would be appreciated.
[ "Note: I will include a version for pycord at the end because I think it's much simpler, also it was the original answer.\n\ndiscord.py version\nFirst make sure that you have the newest version of discord.py installed.\nIn your code, you first import the library:\nimport discord\nfrom discord import app_commands\n\...
[ 13, 2, 1, 0 ]
[ "discord.py does not support slash commands and will never add support for slash commands (as it has shut down) thus I recommend disnake (a popular fork). Specifically disnake because out of all the forks disnake seems to be the more intellectual one.\n" ]
[ -12 ]
[ "discord", "discord.py", "python" ]
stackoverflow_0071165431_discord_discord.py_python.txt
Q: Why sum function is slower if the 'start' argument is an instance of custom class? I was playing around with sum function and observed the following behaviour. case 1: source = """ class A: def __init__(self, a): self.a = a def __add__(self, other): return self.a + other; sum([*range(...
Why sum function is slower if the 'start' argument is an instance of custom class?
I was playing around with sum function and observed the following behaviour. case 1: source = """ class A: def __init__(self, a): self.a = a def __add__(self, other): return self.a + other; sum([*range(10000)], start=A(10)) """ import timeit print(timeit.timeit(stmt=source)) As you can s...
[ "builtin_sum_impl has 2 implementations inside, one if the start is a number which skips creating python \"number objects\" and just sums numbers in C.\nthe other slower implementation when start is not a number, which forces the __add__ method of \"number objects\" to be called, (because it assumes you are summing...
[ 5 ]
[ "Maybe looking at the byte-code can help understand what happens. If you run\nimport dis\n\ndef test_range():\n class A:\n def __init__(self, a):\n self.a = a\n\n def __add__(self, other):\n return self.a + other\n\n sum([*range(10000)], start=10)\n\ndis.dis(test_range)\n\n...
[ -1 ]
[ "cpython", "optimization", "python", "python_3.11", "python_3.x" ]
stackoverflow_0074489410_cpython_optimization_python_python_3.11_python_3.x.txt
Q: Rock paper scissors game how to make it infinite How can I make it so the game is infinite? and is there a way to simplify this code? I have tried to work around but can't seem to figure it out. # A rock paper scissors game. import random Move1=input("Enter your move: (r)ock (p)aper (s)cissors or (q)uit: ").lower...
Rock paper scissors game how to make it infinite
How can I make it so the game is infinite? and is there a way to simplify this code? I have tried to work around but can't seem to figure it out. # A rock paper scissors game. import random Move1=input("Enter your move: (r)ock (p)aper (s)cissors or (q)uit: ").lower() Move2=["r","p","s"] while Move1 != "q": if Mo...
[ "You have to re-evaluate the input at the end of the while loop. Or you put it into the while condition. So you could do while (Move1 := input(...)) != \"q\".\nAlso your first if check is always true because of the or \"p\". You would have to do or Move1 == \"p\" or Move1 == \"s\" or Move1 == \"q\"\nYou could simpl...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074494604_python.txt
Q: How do I concatenate integers with lists in Python? I have a python script that creates lists of numbers and I add some of those numbers together as integers. ddtricks = [deal.dd_tricks("4SN"), \ deal.dd_tricks("5HE"),deal.dd_tricks("5DE"),deal.dd_tricks("5CE"), \ deal.dd_tricks("5HW"),deal...
How do I concatenate integers with lists in Python?
I have a python script that creates lists of numbers and I add some of those numbers together as integers. ddtricks = [deal.dd_tricks("4SN"), \ deal.dd_tricks("5HE"),deal.dd_tricks("5DE"),deal.dd_tricks("5CE"), \ deal.dd_tricks("5HW"),deal.dd_tricks("5DW"),deal.dd_tricks("5CW") ] ddscores = ...
[ "You can either wrap them in a list to concatenate them with other lists:\noutputlist = ddtricks + ddscores + [MaxEWScore, Bid4SGood]\n\nor use spread syntax for the existing lists:\noutputlist = [*ddtricks, *ddscores, MaxEWScore, Bid4SGood]\n\nAnd when you're writing to the file, you can use join() instead of a lo...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074494658_python.txt
Q: Django regroup tag get fields values I have a web page where I have two models for Products and Categories. I have this navbar where you can filter the Productos by categories, so in order to make it dynamic I passed the categories to the navbar and then applied a regroup since I'm getting the categories from the ...
Django regroup tag get fields values
I have a web page where I have two models for Products and Categories. I have this navbar where you can filter the Productos by categories, so in order to make it dynamic I passed the categories to the navbar and then applied a regroup since I'm getting the categories from the model Products since is the one the page i...
[ "Based on the below line which you have in your get_queryset() of your class-based view:\n\ncategoria = self.kwargs['slug']\n\n\ncategoria is the value of 'slug' key in the request and of course it is an instance of str data type in python programming language.\nBut based on what I can find out from your question y...
[ 1 ]
[]
[]
[ "django", "django_templates", "django_views", "python", "templatetags" ]
stackoverflow_0074494575_django_django_templates_django_views_python_templatetags.txt
Q: How can I run my class only once in a while loop in pygame? I have this function: def draw_image(image, xy ,draw_img=True,camera=False): all_images.append(Image(image, xy, draw_img, camera)) #draw all images for image in all_images: image.run() pass and in the class I have this: class Imag...
How can I run my class only once in a while loop in pygame?
I have this function: def draw_image(image, xy ,draw_img=True,camera=False): all_images.append(Image(image, xy, draw_img, camera)) #draw all images for image in all_images: image.run() pass and in the class I have this: class Image: def __init__(self, image, xy, draw_img, camera): s...
[ "If you want to control something over time in Pygame you have two options:\n\nUse pygame.time.get_ticks() to measure time and and implement logic that controls the object depending on the time.\n\nUse the timer event. Use pygame.time.set_timer() to repeatedly create a USEREVENT in the event queue. Change object st...
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074308675_pygame_python.txt
Q: on_message not being triggered when using interactions.Client I'm using Interactions.py (client = interactions.Client) so that I can use its sophisticated slash commands system, but as a result the on_message event method is no longer triggered. When I use Discord.py (client = discord.Client) the on_message metho...
on_message not being triggered when using interactions.Client
I'm using Interactions.py (client = interactions.Client) so that I can use its sophisticated slash commands system, but as a result the on_message event method is no longer triggered. When I use Discord.py (client = discord.Client) the on_message method works successfully. How do I get on_message to work while using t...
[ "It would be on_message_create, as this is the name that the discord api uses\n" ]
[ 1 ]
[]
[]
[ "discord.py", "discord_interactions", "python" ]
stackoverflow_0074332471_discord.py_discord_interactions_python.txt
Q: Can't import scipy in Spyder: ImportError results I updated some packages this morning using conda, including scipy. The new version is 1.9.3. I can no longer import certain modules from my Spyder console: >>> import scipy.special Traceback (most recent call last): File "C:\Users\igurin\AppData\Local\Temp\ipyke...
Can't import scipy in Spyder: ImportError results
I updated some packages this morning using conda, including scipy. The new version is 1.9.3. I can no longer import certain modules from my Spyder console: >>> import scipy.special Traceback (most recent call last): File "C:\Users\igurin\AppData\Local\Temp\ipykernel_19736\2717555404.py", line 1, in <module> impo...
[ "I found an answer on GitHub for Spyder. I removed Anaconda from my Windows path, and the import works now. I'm treating this as a workaround rather than a solution, though.\n" ]
[ 0 ]
[]
[]
[ "import", "python", "scipy", "spyder" ]
stackoverflow_0074494510_import_python_scipy_spyder.txt
Q: Forming a frame of zeros around a matrix in python I am trying to pad a matrix with zeros, but am not really sure how to do it. Basically I need to surround a matrix with an n amount of zeros. The input matrix is huge (it represents an image) Example: Input: 1 2 3 4 5 6 7 8 4 3 2 1 n = 2 Output: 0 0 0 0 0 0 0 0 ...
Forming a frame of zeros around a matrix in python
I am trying to pad a matrix with zeros, but am not really sure how to do it. Basically I need to surround a matrix with an n amount of zeros. The input matrix is huge (it represents an image) Example: Input: 1 2 3 4 5 6 7 8 4 3 2 1 n = 2 Output: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 0 0 0 0 5 6 7 8 0 0 0 0 4 3 ...
[ "You can use NumPy's slice notation.\nimport numpy as np\n\n#input matrix\nA = np.array([[1,2,3,4],\n [3,4,5,6]])\n\n#get matrix shape\nx,y=A.shape\n\n#set amount of zeros\nn=2 \n\n#create zero's matrix\nB=np.zeros((x+2*n,y+2*n),dtype=int)\n\n# insert & slice\nB[n:x+n, n:y+n] = A\n\n#show result\nfo...
[ 0 ]
[]
[]
[ "matrix", "padding", "python", "zero_pad", "zero_padding" ]
stackoverflow_0074494304_matrix_padding_python_zero_pad_zero_padding.txt
Q: How do i analyze the running time of a function with a for loop with an if statement? For example, let the function consist: def myfunc(): total = 0 for i in range(0, n): total+=i if total >= n: return total return 0 What would the running time be? I cant seem to figure out a wa...
How do i analyze the running time of a function with a for loop with an if statement?
For example, let the function consist: def myfunc(): total = 0 for i in range(0, n): total+=i if total >= n: return total return 0 What would the running time be? I cant seem to figure out a way to analyze this problem.
[ "You can define your own decorator, like this:\ndef timed_function(f):\n def wrapper(*args, **kwargs):\n import time\n start_time = time.time()\n result = f(*args, **kwargs)\n elapsed = time.time() - start_time\n print(\"{} took {} seconds to run.\".format(f, elapsed))\n ...
[ 1 ]
[]
[]
[ "python", "running_count" ]
stackoverflow_0074494820_python_running_count.txt
Q: Insert multiple rows while inheriting cell styles I have an XLSX file which I want to use as a minimum template to be expanded and filled with user data using openpyxl. With 'minimum' I mean that I want to define just one or two rows within the XLSX template in the way that I later insert further rows while keepin...
Insert multiple rows while inheriting cell styles
I have an XLSX file which I want to use as a minimum template to be expanded and filled with user data using openpyxl. With 'minimum' I mean that I want to define just one or two rows within the XLSX template in the way that I later insert further rows while keeping the format / style of the rows from the template. Exa...
[ "I had the same issue and came up with that function which inserts a number of rows under the \"pointer\" row and copies the style from each cell in that row to the newly inserted rows.\nimport openpyxl.worksheet.worksheet as _sheet\nfrom copy import copy\n\ndef insertRowsFormat(rowP: int, number: int, sheet: _she...
[ 0 ]
[]
[]
[ "openpyxl", "python" ]
stackoverflow_0066933271_openpyxl_python.txt
Q: How to apply default value to Python dataclass field when None was passed? I need a class that will accept a number of parameters, I know that all parameters will be provided but some maybe passed as None in which case my class will have to provide default values. I want to setup a simple dataclass with a some def...
How to apply default value to Python dataclass field when None was passed?
I need a class that will accept a number of parameters, I know that all parameters will be provided but some maybe passed as None in which case my class will have to provide default values. I want to setup a simple dataclass with a some default values like so: @dataclass class Specs1: a: str b: str = 'Bravo' ...
[ "The simple solution is to just implement the default arguments in __post_init__() only!\n@dataclass\nclass Specs2:\n a: str\n b: str\n c: str\n\n def __post_init__(self):\n if self.b is None:\n self.b = 'Bravo'\n if self.c is None:\n self.c = 'Charlie'\n\n(Code is no...
[ 17, 11, 11, 5, 2, 1, 0, 0 ]
[ "Not too clear what you are trying to do with your Class. Should these defaults not rather be properties? \nMaybe you need a definition used by your class that has default parameters such as: \ndef printMessage(name, msg = \"My name is \"): \n print(\"Hello! \",msg + name)\n\nprintMessage(\"Jack\")\n\nSame th...
[ -2 ]
[ "default_value", "python", "python_3.x", "python_dataclasses" ]
stackoverflow_0056665298_default_value_python_python_3.x_python_dataclasses.txt
Q: Groupby: how to compute a tranformation and division in every value by group I have a database like this: participant time1 time2 ... time27 1 0.003 0.001 0.003 1 0.003 0.002 0.001 1 0.006 0.003 0.003 1 0.003 0.001 0.003 2 0.003...
Groupby: how to compute a tranformation and division in every value by group
I have a database like this: participant time1 time2 ... time27 1 0.003 0.001 0.003 1 0.003 0.002 0.001 1 0.006 0.003 0.003 1 0.003 0.001 0.003 2 0.003 0.003 0.001 2 0.003 0.003 0.001 3 0.006 0.00...
[ "You can use:\ndf.join(df.groupby('participant')\n .transform(lambda s: np.log1p(s)/s.max())\n .add_suffix('_trans')\n )\n\nOutput (as new columns):\n participant time1 time2 time27 time1_trans time2_trans time27_trans\n0 1 0.003 0.001 0.003 0.499251 0.333167 ...
[ 2 ]
[]
[]
[ "group_by", "pandas", "python" ]
stackoverflow_0074494675_group_by_pandas_python.txt
Q: how to sample points in 3D in python with origin and normal vector I have two points p1(x1, y1, z1) and p2(x2, y2, z2) in 3D. And I want to sample points in a circle with radius r that is centered at p1, and the plane which is perpendicular to the vector p2-p1 (so p2-p1 would be the normal vector of that plane). I...
how to sample points in 3D in python with origin and normal vector
I have two points p1(x1, y1, z1) and p2(x2, y2, z2) in 3D. And I want to sample points in a circle with radius r that is centered at p1, and the plane which is perpendicular to the vector p2-p1 (so p2-p1 would be the normal vector of that plane). I have the code for sampling in XOY plane using polar system, but sufferi...
[ "At first you need to define two base vectors in the circle's plane.\nThe first one is arbitrary vector orthogonal to normal n = p2-p1\nChoose component of normal with the largest magnitude and component with the second magnitude.\nExchange their values, negate the largest, and make the third component zero (note t...
[ 2, 0 ]
[]
[]
[ "geometry", "linear_algebra", "numpy", "python" ]
stackoverflow_0071160423_geometry_linear_algebra_numpy_python.txt
Q: BeautifulSoup not returning links For my python bootcamp I am trying to create a log of the articles from this site, and return the highest upvoted. The rest of the code works, but I cannot get it to return the href properly. I get "none." I have tried everything I know to do... can anyone provide any guidance? fr...
BeautifulSoup not returning links
For my python bootcamp I am trying to create a log of the articles from this site, and return the highest upvoted. The rest of the code works, but I cannot get it to return the href properly. I get "none." I have tried everything I know to do... can anyone provide any guidance? from bs4 import BeautifulSoup import requ...
[ "Try:\n\n...\n\n article_link = article_tag.a.get(\"href\") # <--- put .a here\n\n...\n\n\nfrom bs4 import BeautifulSoup\nimport requests\n\n\nresponse = requests.get(\"https://news.ycombinator.com/\")\nyc_web_page = response.text\n\n\nsoup = BeautifulSoup(yc_web_page, \"html.parser\")\narticles = soup.find_a...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "html_parsing", "parsing", "python" ]
stackoverflow_0074494747_beautifulsoup_html_parsing_parsing_python.txt
Q: Limit overpy query to specific area (e.g. country) In the following code I am defining the spatial extent of the query using a bounding box. How could I modify the code to instead use a country as the extent of my query? Thank you. api = overpy.Overpass() result = api.query("""<osm-script> <query type="node"> ...
Limit overpy query to specific area (e.g. country)
In the following code I am defining the spatial extent of the query using a bounding box. How could I modify the code to instead use a country as the extent of my query? Thank you. api = overpy.Overpass() result = api.query("""<osm-script> <query type="node"> <has-kv k="crossing" v="zebra"/> <bbox-query e="6....
[ "In overpass turbo a count of the zebra crossings in Ireland:\n[out:json];\narea[\"name\"=\"Ireland\"]->.boundaryarea;\n(\n nwr(area.boundaryarea)[crossing=zebra];\n);\n\nout body;\n\nAnd with overpy a count of the zebra crossings in Ireland:\nimport overpy\n\napi = overpy.Overpass()\n\nresult = api.query(\"\"\"\n...
[ 0 ]
[]
[]
[ "openstreetmap", "overpass_api", "python" ]
stackoverflow_0071433686_openstreetmap_overpass_api_python.txt
Q: PySimpleGUI is only showing black screen (python) When i start this python script: import PySimpleGUI as sg layout = [[sg.Text("Hello from PySimpleGUI")], [sg.Button("OK")]] # Create the window window = sg.Window("Demo", layout) # Create an event loop while True: event, values = window.read() # End prog...
PySimpleGUI is only showing black screen (python)
When i start this python script: import PySimpleGUI as sg layout = [[sg.Text("Hello from PySimpleGUI")], [sg.Button("OK")]] # Create the window window = sg.Window("Demo", layout) # Create an event loop while True: event, values = window.read() # End program if user closes window or # presses the OK butto...
[ "In VSCode I had to update the settings.json of python\n\"python.defaultInterpreterPath\": \"/your/venv/bin/python\",\n\nReference: Pylint \"unresolved import\" error in Visual Studio Code\n" ]
[ 0 ]
[]
[]
[ "pysimplegui", "python", "user_interface" ]
stackoverflow_0074483062_pysimplegui_python_user_interface.txt
Q: Find perpendicular to given vector (Velocity) in 3D I have a object A move with Velocity (v1, v2, v3) in 3D space. Object position is (px,py,pz) Now i want to add certain particles around object A (in radius dis) on plane which perpendicular to its Velocity direction. I find something call "cross product" but see...
Find perpendicular to given vector (Velocity) in 3D
I have a object A move with Velocity (v1, v2, v3) in 3D space. Object position is (px,py,pz) Now i want to add certain particles around object A (in radius dis) on plane which perpendicular to its Velocity direction. I find something call "cross product" but seen that no use in this case. Anyone can help? I'm new to py...
[ "The plane perpendicular to a vector ⟨A, B, C⟩ has the general equation Ax + By + Cz + K = 0.\n", "The equation of the plane is:\nv1*(x-px) + v2*(y-py) + v3*(z-pz) = 0\n\nWhen you know (x,y) you can find z and so on.\nExample:\nz = pz - (v1*(x-px) + v2*(y-py))/v3\n", "Lets say we have a point p1, and we want to...
[ 1, 0, 0 ]
[]
[]
[ "python", "vector" ]
stackoverflow_0011134610_python_vector.txt
Q: GPA Calculator + failure testing My code is only inputting one print command when there are two that need to be put out. I know this problem is simple but I need a new perspective here is my code: name = input("What is your name? \n") h1 = ("Class Name") h2 = ("Class Grade") h3 = ("Credit Hours") point = input("\n...
GPA Calculator + failure testing
My code is only inputting one print command when there are two that need to be put out. I know this problem is simple but I need a new perspective here is my code: name = input("What is your name? \n") h1 = ("Class Name") h2 = ("Class Grade") h3 = ("Credit Hours") point = input("\nEnter your class name followed by your...
[ "You need another loop, like the one you used to print the grade table.\nfor item in class_data:\n if item[1] in (\"D\", \"F\"):\n print(f\"failing {item[0]}\")\n\n" ]
[ 0 ]
[]
[]
[ "computer_science", "gpa", "python" ]
stackoverflow_0074494900_computer_science_gpa_python.txt
Q: discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: unsupported operand type(s) for +: 'int and NoneType I was coding a Tax calculator system and when I'm using the function It gives me the error : discord.errors.ApplicationCommandInvokeError: Application Command raise...
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: unsupported operand type(s) for +: 'int and NoneType
I was coding a Tax calculator system and when I'm using the function It gives me the error : discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: unsupported operand type(s) for +: 'int' and 'NoneType', I tried Everything but it didn't work. Here's the function (tax calculat...
[ "Your tax() function isn't returning anything, so by default it returns None.\nI suppose you want to send the protax variable. If that is the case, this code should work:\nasync def tax(args):\n args3 = 5\n protax= round(int(args)*args3/100)\n if protax == 0:\n protax = 1\n return protax\n\n" ]
[ 0 ]
[]
[]
[ "discord", "discord.py", "pycord", "python", "python_3.x" ]
stackoverflow_0074493862_discord_discord.py_pycord_python_python_3.x.txt
Q: How to use tkinter as ttk I am working on a big programme and I want Combobox to accept text only to be entered in it I use This Code import tkinter import ttk import re win = tkinter.Tk() def num_only(num): if str.isdecimal(num): return True elif num=="": return True else: return False def text_only(txt): if re....
How to use tkinter as ttk
I am working on a big programme and I want Combobox to accept text only to be entered in it I use This Code import tkinter import ttk import re win = tkinter.Tk() def num_only(num): if str.isdecimal(num): return True elif num=="": return True else: return False def text_only(txt): if re.match("^\[a-z\]*$",txt.lower())...
[ "ttk is a module of tkinter, so you have to import it like this:\nfrom tkinter import ttk\n\nOr instead of calling ttk.Combobox (note that python is case sensitive, so a call to ttk.combobox will not work), you can call it like\ntkinter.ttk.Combobox\n\nAlso, according to this post, you have to register your validat...
[ 0 ]
[]
[]
[ "combobox", "python", "tkinter", "ttk" ]
stackoverflow_0074494569_combobox_python_tkinter_ttk.txt
Q: Pandas Converting CSV to Parquet - String having , not able to convert I am using Pandas to Convert CSV to Parquet and below is the code, it is straight Forward. import pandas as pd df = pd.read_csv('path/xxxx.csv') print(df) df.to_parquet('path/xxxx.parquet') Problem In a String for Example :- David,Johnson. If ...
Pandas Converting CSV to Parquet - String having , not able to convert
I am using Pandas to Convert CSV to Parquet and below is the code, it is straight Forward. import pandas as pd df = pd.read_csv('path/xxxx.csv') print(df) df.to_parquet('path/xxxx.parquet') Problem In a String for Example :- David,Johnson. If there is a , getting error saying there is a problem in the data. If i remov...
[ "Do you need to keep comma in the name of the file? Otherwise you can do input='David,Johnson', output=input.replace(',','_'). I don't think it is generally a good practice to have comma in your file names.\n" ]
[ 0 ]
[]
[]
[ "dataframe", "pandas", "pip", "pyarrow", "python" ]
stackoverflow_0074494249_dataframe_pandas_pip_pyarrow_python.txt
Q: Searching for substrings in a list of dicts I have a list of dicts I need to search through the "Receiver" keys, and only output dicts that share the last X characters, inside the receiver value, with any other dict. In this case, we search the last 3 characters of each Receiver value against all other Receiver va...
Searching for substrings in a list of dicts
I have a list of dicts I need to search through the "Receiver" keys, and only output dicts that share the last X characters, inside the receiver value, with any other dict. In this case, we search the last 3 characters of each Receiver value against all other Receiver values. This is what i have so far transactions = [...
[ "You can first count the occurences and then filter the list according to the count.\nfrom collections import Counter\n\ntransactions = [\n {\"Receiver\":\"alice111\",\"Amount\":50},\n {\"Receiver\":\"alice222\",\"Amount\":60},\n {\"Receiver\":\"alice111\",\"Amount\":70},\n {\"Receiver\":\"bob111\",\"Am...
[ 1, 1 ]
[]
[]
[ "dictionary", "list", "python", "regex", "substring" ]
stackoverflow_0074493831_dictionary_list_python_regex_substring.txt
Q: How fix this error on python (selenium) - json.decoder.JSONDecodeError: Iniciado! [WDM] - Downloading: 19.0kB [00:00, 19.5MB/s] Traceback (most recent call last): File "main.py", line 58, in FIREFOX(login) File "main.py", line 26, in FIREFOX driver = webdriver.Firefox(executable_path=GeckoDriverManager().install(...
How fix this error on python (selenium) - json.decoder.JSONDecodeError:
Iniciado! [WDM] - Downloading: 19.0kB [00:00, 19.5MB/s] Traceback (most recent call last): File "main.py", line 58, in FIREFOX(login) File "main.py", line 26, in FIREFOX driver = webdriver.Firefox(executable_path=GeckoDriverManager().install()) File "C:\Users\moonl\AppData\Local\Programs\Python\Python38\lib\site-pack...
[ "Its very unclear, but seems that is libary error. We need see a part of your code that points to json.\nSee that if you have the:\nimport json\nIf you trying to read a txt file as json, try:\nwith open('/xxxx/xxxxx/xxxx.xxx') as jsonfile:\ndata = json.load(jsonfile)\nOther topic in stackoverflow can help you, plea...
[ 0 ]
[]
[]
[ "python", "selenium", "selenium_webdriver" ]
stackoverflow_0074493794_python_selenium_selenium_webdriver.txt
Q: elif not working as expected and the loop starts again inside a while loop all the if and elif statements are working except elif user_choice.upper() == "C" I tried inputting the choice C and expected the program to print "miles travelled" but the program went and again asked for input # Game info print("Welcome t...
elif not working as expected and the loop starts again
inside a while loop all the if and elif statements are working except elif user_choice.upper() == "C" I tried inputting the choice C and expected the program to print "miles travelled" but the program went and again asked for input # Game info print("Welcome to camel") print("You have stolen a camel too make your way a...
[ "You are missing a pair of brackets. Replace elif user_choice.upper == \"C\": with elif user_choice.upper() == \"C\":. Complete code below:\n# Game info\nprint(\"Welcome to camel\")\nprint(\"You have stolen a camel too make your way across the great Mobi desert\")\nprint(\"The natives are chasing you and want their...
[ 0, 0 ]
[]
[]
[ "conditional_statements", "if_statement", "python", "while_loop" ]
stackoverflow_0074494943_conditional_statements_if_statement_python_while_loop.txt
Q: Count how many times each function gets called I want to count how many times each function get called. I have a wrapper to do the counting and save it into a global variable def counter(f): global function_calls function_calls = 0 def wrapper(*args, **kwargs): global function_calls fu...
Count how many times each function gets called
I want to count how many times each function get called. I have a wrapper to do the counting and save it into a global variable def counter(f): global function_calls function_calls = 0 def wrapper(*args, **kwargs): global function_calls function_calls += 1 return f(*args, **kwargs) ...
[ "Instead of a single global int, store per-function counts in a dict.\ndef counter(f):\n global function_calls\n function_calls = {}\n\n def wrapper(*args, **kwargs):\n global function_calls\n function_calls[f.__name__] = function_calls.setdefault(f.__name__, 0) + 1\n return f(*args, *...
[ 3, 1 ]
[]
[]
[ "decorator", "python", "python_3.x", "python_decorators" ]
stackoverflow_0074494811_decorator_python_python_3.x_python_decorators.txt
Q: Setting a value in a nested Python dictionary given a list of indices and value I'm trying to programmatically set a value in a dictionary, potentially nested, given a list of indices and a value. So for example, let's say my list of indices is: ['person', 'address', 'city'] and the value is 'New York' I want as...
Setting a value in a nested Python dictionary given a list of indices and value
I'm trying to programmatically set a value in a dictionary, potentially nested, given a list of indices and a value. So for example, let's say my list of indices is: ['person', 'address', 'city'] and the value is 'New York' I want as a result a dictionary object like: { 'Person': { 'address': { 'city': 'New York' } }...
[ "Something like this could help:\ndef nested_set(dic, keys, value):\n for key in keys[:-1]:\n dic = dic.setdefault(key, {})\n dic[keys[-1]] = value\n\nAnd you can use it like this:\n>>> d = {}\n>>> nested_set(d, ['person', 'address', 'city'], 'New York')\n>>> d\n{'person': {'address': {'city': 'New Yor...
[ 72, 5, 3, 3, 2, 2, 1, 1, 0 ]
[ "This is much easier in Perl:\nmy %hash;\n$hash{\"aaa\"}{\"bbb\"}{\"ccc\"}=1; # auto creates each of the intermediate levels\n # of the hash (aka: dict or associated array)\n\n" ]
[ -2 ]
[ "dictionary", "list", "python" ]
stackoverflow_0013687924_dictionary_list_python.txt
Q: Optimizing Python Code: String Assignment from List I have a CSV file and I read the contents. I need to verify that every element of each row is not empty: fname = row[0] if fname is None: flag = -1 lname = row[1] if lname is None: flag = -1 phone = row[2] if phone is None: flag = -1 email = row[3] if...
Optimizing Python Code: String Assignment from List
I have a CSV file and I read the contents. I need to verify that every element of each row is not empty: fname = row[0] if fname is None: flag = -1 lname = row[1] if lname is None: flag = -1 phone = row[2] if phone is None: flag = -1 email = row[3] if email is None: flag = -1 [...] Is there a way to op...
[ "if all([len(e) for e in row]):\n # Row is good\nelse:\n # Row is bad\n\n\nWe can't just do all(row) because there may be a non-empty but falsey value.\n", "This could help you\nwith open('testdata1.csv', 'r') as csv_file:\ncsv_reader = csv.reader(csv_file)\nfor row in csv_reader:\n if not row[0]:\n ...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074494740_python.txt
Q: How could I find the Sender Department in Microsoft Outlook using win32com in Python? I am programming a script to return each person - along with their department - that was a part of a thread in my Junk folder. As of now I have managed to correctly return their names, however despite trying multiple different me...
How could I find the Sender Department in Microsoft Outlook using win32com in Python?
I am programming a script to return each person - along with their department - that was a part of a thread in my Junk folder. As of now I have managed to correctly return their names, however despite trying multiple different methods, I have been unable to access the Departments property. Here is an example of what I ...
[ "There is no reason to use CreateRecipient / Recipient.Resolve - MailItem.Sender property already exposes the AddressEntry object for the sender. Once you get ExchangeUser object from AddressEntry.GetExchangeUser() (check for null), just use the ExchangeUser.Department property.\n" ]
[ 1 ]
[]
[]
[ "outlook", "python" ]
stackoverflow_0074494922_outlook_python.txt
Q: I am trying to install requirements.txt for my project but it returns the error given below? Trying to install these packages but the same thing comes up every time. What should I do ? tensorflow==2.4.1 nltk==3.5 keras==2.4.3 numpy==1.19.5 streamlit==0.52.1 seaborn==0.11.1 tweepy==3.10.0 textblob==0.15.3 flask==1....
I am trying to install requirements.txt for my project but it returns the error given below?
Trying to install these packages but the same thing comes up every time. What should I do ? tensorflow==2.4.1 nltk==3.5 keras==2.4.3 numpy==1.19.5 streamlit==0.52.1 seaborn==0.11.1 tweepy==3.10.0 textblob==0.15.3 flask==1.1.2 pandas==1.2.2 matplotlib==3.2 scikit_learn==0.24.1 statsmodels==0.12.2 yfinance==0.1.54 alpha_...
[ "It says that requirements.txt does not exist in the current working directory. Is the file in the directory \\Stock-Market..?\nAnother thing that I noticed is that you don't have a virtual environment activated. But I don't know if you want to install it specifically in a venv.\n" ]
[ 0 ]
[]
[]
[ "python", "requirements.txt" ]
stackoverflow_0074494896_python_requirements.txt.txt
Q: Why do I get module 'numpy' has no attribute 'json_normalize' when using pd.json_normalize() I have a simple code that scrapes reviews from an app in Google Playstore. The scrapping runs well and returns a json data. I decided to normalize it and get pandas dataframe. All I keep getting is module 'numpy' has no at...
Why do I get module 'numpy' has no attribute 'json_normalize' when using pd.json_normalize()
I have a simple code that scrapes reviews from an app in Google Playstore. The scrapping runs well and returns a json data. I decided to normalize it and get pandas dataframe. All I keep getting is module 'numpy' has no attribute 'json_normalize' Please I need help, all solutions I saw online have not worked. Below is ...
[ "Your renaming your pandas import as pd, then renaming numpy also as pd - as the numpy import is last, it is now pd instead of pandas.\nimport pandas as pd\nimport numpy as pd\n\nchange it to this (assuming you need to import numpy at all):\nimport pandas as pd\nimport numpy as np\n\n" ]
[ 1 ]
[]
[]
[ "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0074495157_dataframe_numpy_pandas_python.txt
Q: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet | APScheduler I have this APScheduler code: import atexit from apscheduler.schedulers.background import BackgroundScheduler from main.utils import run_employee_import scheduler = BackgroundScheduler() scheduler.add_job(run_employee_import, "interv...
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet | APScheduler
I have this APScheduler code: import atexit from apscheduler.schedulers.background import BackgroundScheduler from main.utils import run_employee_import scheduler = BackgroundScheduler() scheduler.add_job(run_employee_import, "interval", minutes=2) scheduler.start() # Shut down the scheduler when exiting the app atex...
[ "I completely changed the way I run the scheduler. And it worked, let me share the solution with you:\nI create a .py file inside the app:\napp/bulk_task.py\n\nI create a start function and put the schedule code in it:\nfrom apscheduler.schedulers.background import BackgroundScheduler\nfrom main.utils import **<MY_...
[ 0 ]
[]
[]
[ "apscheduler", "django", "python" ]
stackoverflow_0074495052_apscheduler_django_python.txt
Q: Best way to constantly check for scheduled events on a website So I am making a website, and something that required for part of the security is having a waiting period when trying to do something, for example trying to delete something, this would help incase someone's account was stolen and someone tried to ruin...
Best way to constantly check for scheduled events on a website
So I am making a website, and something that required for part of the security is having a waiting period when trying to do something, for example trying to delete something, this would help incase someone's account was stolen and someone tried to ruin their account. I'm already using SQLite so I'm going to create a ta...
[ "I would either create a cron job on your server (which is the most straightforward)\nor use a schedule module to schedule your task, see example:\nimport time\n\nimport schedule\nfrom sharepoint_cleaner import main as cleaner\nfrom sharepoint_uploader import main as uploader\nfrom transfer_statistics import main a...
[ 0 ]
[]
[]
[ "multithreading", "python", "scheduled_tasks" ]
stackoverflow_0074495057_multithreading_python_scheduled_tasks.txt
Q: Pandas: Pivot multi-index, with one 'shared' column I have a pandas dataframe that can be represented like: test_dict = {('a', 1) : {'shared':0,'x':1, 'y':2, 'z':3}, ('a', 2) : {'shared':1,'x':2, 'y':4, 'z':6}, ('b', 1) : {'shared':0,'x':10, 'y':20, 'z':30}, ('b', 2) : {'shared...
Pandas: Pivot multi-index, with one 'shared' column
I have a pandas dataframe that can be represented like: test_dict = {('a', 1) : {'shared':0,'x':1, 'y':2, 'z':3}, ('a', 2) : {'shared':1,'x':2, 'y':4, 'z':6}, ('b', 1) : {'shared':0,'x':10, 'y':20, 'z':30}, ('b', 2) : {'shared':1,'x':100, 'y':200, 'z':300}} example = pd.DataFrame.fr...
[ "A possible solution, which uses only dataframe manipulations and then converts to dictionary:\nxyz = ['x', 'y', 'z']\nout = (example.assign(xyz=example[xyz].apply(list, axis=1)).reset_index()\n .pivot(index='level_0', columns=['level_1', 'shared'], values='xyz')\n .applymap(lambda x: dict(zip(xyz, x)))...
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074494291_pandas_python.txt
Q: Why is Django trying to find my image in such directory? Instead"/media/", it tries to find here ??? The idea was to put several images in one object and everything works in the admin panel, but in the html template it paves the wrong path to the image. Tell me what am I doing wrong? models.py ` class Product(mode...
Why is Django trying to find my image in such directory?
Instead"/media/", it tries to find here ??? The idea was to put several images in one object and everything works in the admin panel, but in the html template it paves the wrong path to the image. Tell me what am I doing wrong? models.py ` class Product(models.Model): name = models.CharField(max_length=255, verbose...
[ "Add this to your project urls.py (not the one in the app).\nurlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074494992_django_python.txt
Q: how can I display the other elements of my code? This is my code: def formater_les_parties(parties): from datetime import datetime i = f'{(len(parties[:-1]))} : {parties[0].get("date")}, {parties[0].get("joueurs")[0]} {"vs"} {parties[0].get("joueurs")[1]}, {"gagnant"}: {parties[0].get("gagnant")} \n' ...
how can I display the other elements of my code?
This is my code: def formater_les_parties(parties): from datetime import datetime i = f'{(len(parties[:-1]))} : {parties[0].get("date")}, {parties[0].get("joueurs")[0]} {"vs"} {parties[0].get("joueurs")[1]}, {"gagnant"}: {parties[0].get("gagnant")} \n' for w in range((len(parties))): i += str(w) ...
[ "Not only what @quamrana said, but you only use parties[0]; here's what you wanted to do:\ndef formater_les_parties(parties):\n from datetime import datetime\n i = ''\n for w in range((len(parties))):\n i += f'{w} : {parties[w].get(\"date\")}, {parties[w].get(\"joueurs\")[0]} {\"vs\"} {parties[w].g...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074495154_python_python_3.x.txt
Q: How to get keyboard input in pygame? I am making a game in pygame 1.9.2. It's a faily simple game in which a ship moves between five columns of bad guys who attack by moving slowly downward. I am attempting to make it so that the ship moves left and right with the left and right arrow keys. Here is my code: keys=p...
How to get keyboard input in pygame?
I am making a game in pygame 1.9.2. It's a faily simple game in which a ship moves between five columns of bad guys who attack by moving slowly downward. I am attempting to make it so that the ship moves left and right with the left and right arrow keys. Here is my code: keys=pygame.key.get_pressed() if keys[K_LEFT]: ...
[ "You can get the events from pygame and then watch out for the KEYDOWN event, instead of looking at the keys returned by get_pressed()(which gives you keys that are currently pressed down, whereas the KEYDOWN event shows you which keys were pressed down on that frame).\nWhat's happening with your code right now is ...
[ 111, 17, 12, 2, 1, 1, 0, 0 ]
[ "You should use clock.tick(10) as stated in the docs.\n", "all of the answers above are too complexicated i would just change the variables by 0.1 instead of 1\nthis makes the ship 10 times slower\nif that is still too fast change the variables by 0.01\nthis makes the ship 100 times slower\ntry this\nkeys=pygame....
[ -2, -3, -3 ]
[ "keyboard", "pygame", "python" ]
stackoverflow_0016044229_keyboard_pygame_python.txt
Q: How to use a Django (Python) Login Form? I builded a login form in Django. Now I have a problem with the routing. When I select the login button, the form doesn`t send the correct awnser. I think the form in the frontend cannot gets the correct awnser from the view.py file. So it will send no awnser and the login ...
How to use a Django (Python) Login Form?
I builded a login form in Django. Now I have a problem with the routing. When I select the login button, the form doesn`t send the correct awnser. I think the form in the frontend cannot gets the correct awnser from the view.py file. So it will send no awnser and the login process canot work and the form is a simple st...
[ "def login(request):\n if request.method = 'POST':\n username = request.POST['username']\n password = request.method = POST['password']\n\n user = auth.authenticate(username=username, password=password)\n\n if user is not None:\n auth.login(request, user)\n retur...
[ 0 ]
[]
[]
[ "django", "html", "python" ]
stackoverflow_0074495020_django_html_python.txt
Q: AWS Lambda Python Cryptography - Cannot open shared object files I am working on a Serverless Flask app that is deployed to AWS Lambda. The program uses the Cryptography library (using version 3.4.7). Locally, the program runs fine without any issue. However, whenever deployed on Lambda, the following error app...
AWS Lambda Python Cryptography - Cannot open shared object files
I am working on a Serverless Flask app that is deployed to AWS Lambda. The program uses the Cryptography library (using version 3.4.7). Locally, the program runs fine without any issue. However, whenever deployed on Lambda, the following error appears: from cryptography.fernet import Fernet File "/var/task/cryptogr...
[ "I had a similar problem before that was resolved by running the deployment command from a linux machine. I use a mac for development and I was trying to deploy my lambda function from my mac. However, when it was deployed some of the dependencies threw import errors.\nFrom my experience, it was due to the operatin...
[ 1, 1, 0, 0 ]
[]
[]
[ "amazon_web_services", "aws_lambda", "python", "python_cryptography", "serverless_framework" ]
stackoverflow_0067646196_amazon_web_services_aws_lambda_python_python_cryptography_serverless_framework.txt
Q: Slice of 2d numpy array with another array I have a quite large 2d array, and I need to get both the index of the maximum value in axis 1, and the maximum value itself. I can retrieve these two values as follows: import numpy as np a = np.arange(27).reshape(9, 3) idx = np.argmax(a, axis=1) max_val = np.max(a, axis...
Slice of 2d numpy array with another array
I have a quite large 2d array, and I need to get both the index of the maximum value in axis 1, and the maximum value itself. I can retrieve these two values as follows: import numpy as np a = np.arange(27).reshape(9, 3) idx = np.argmax(a, axis=1) max_val = np.max(a, axis=1) However, since I have already found the ind...
[ "Your a and argmax:\nIn [602]: a\nOut[602]: \narray([[ 0, 1, 2],\n [ 3, 4, 5],\n [ 6, 7, 8],\n [ 9, 10, 11],\n [12, 13, 14],\n [15, 16, 17],\n [18, 19, 20],\n [21, 22, 23],\n [24, 25, 26]])\n\nIn [603]: idx\nOut[603]: array([2, 2, 2, 2, 2, 2, 2, 2, 2], dtype=int...
[ 1 ]
[]
[]
[ "arrays", "numpy", "performance", "python" ]
stackoverflow_0074495151_arrays_numpy_performance_python.txt
Q: discord.py get server id with on_ready() function I want to load some information about a server from a json file, each server is identified within this file by its guild.id. However if I want to try and load some data at the start with on_ready(), I cant use ctx, which I need to get the current servers guild.id, ...
discord.py get server id with on_ready() function
I want to load some information about a server from a json file, each server is identified within this file by its guild.id. However if I want to try and load some data at the start with on_ready(), I cant use ctx, which I need to get the current servers guild.id, so I can identify it within the file. (sorry if that's ...
[ "You can use discord.utils, which would look like the following:\nguild = discord.utils.get(bot.guilds, id=378473289473829)\n\nYou can use what every ID you want, just be sure to replace bot with the name of your Client instance.\nThis works in on_ready, without any ctx\n", "You could use bot.guilds which is a li...
[ 2, 1 ]
[]
[]
[ "discord", "discord.py", "python", "python_3.x" ]
stackoverflow_0074493134_discord_discord.py_python_python_3.x.txt
Q: Recursive function to check if a given number is Fibonacci I'm new to python and I'm am having problems building a recursive function that checks if a given number is a Fibonacci number. This is my code. def isFib(n): if n <= 1: return n else: return (n - 1) + (n - 2) if isFib(n) =...
Recursive function to check if a given number is Fibonacci
I'm new to python and I'm am having problems building a recursive function that checks if a given number is a Fibonacci number. This is my code. def isFib(n): if n <= 1: return n else: return (n - 1) + (n - 2) if isFib(n) == 1 or isFib(n) == isFib(n - 1) + isFib(n - 2): return T...
[ "The first part of your function is an if statement. If True, it returns a value - if False, it also returns a value. So, the second part of your function cannot possible execute, and the function isn't recursive (since you don't call the function again in either return statement).\nMore generally, what you're doin...
[ 2 ]
[]
[]
[ "fibonacci", "function", "python", "recursion" ]
stackoverflow_0074495255_fibonacci_function_python_recursion.txt
Q: Error on installing pyqt5(pip install pyqt5) I have installed pyqt5 once on another pc. I am trying to install pyqt5 on my notebook. My notebook specs are: 64bit AMD Ryzen 7 5800H MS Windows 10 Pro I tried : > pip install pyqt5 on cmd and had error: Using cached PyQt5-5.15.6.tar.gz (3.2 MB) Installing build de...
Error on installing pyqt5(pip install pyqt5)
I have installed pyqt5 once on another pc. I am trying to install pyqt5 on my notebook. My notebook specs are: 64bit AMD Ryzen 7 5800H MS Windows 10 Pro I tried : > pip install pyqt5 on cmd and had error: Using cached PyQt5-5.15.6.tar.gz (3.2 MB) Installing build dependencies ... error error: subprocess-exited-wi...
[ "I was able to solve the problem by installing the latest Python version 3.10.5, updating pip alone did not help. I was using Python 3.8.9 before that.\n", "You may have python installed somewhere else on your computer that isn't the latest version and your system environment variables is pointing to that. Make s...
[ 0, 0, 0 ]
[]
[]
[ "pip", "pyqt", "pyqt5", "python" ]
stackoverflow_0072424212_pip_pyqt_pyqt5_python.txt
Q: How to handle duplicate messages in Kafka I know duplicate messages can produce on both the producer side and the consumer side. And I also know, Kafka deduplicates messages on the producer side by enabling idempotency. But how about the consumer side? I see two different solutions: Writing idempotent consumer if...
How to handle duplicate messages in Kafka
I know duplicate messages can produce on both the producer side and the consumer side. And I also know, Kafka deduplicates messages on the producer side by enabling idempotency. But how about the consumer side? I see two different solutions: Writing idempotent consumer if possible Keep the message ID in the consumer's...
[ "As Paweł Szymczyk and OneCricketeer said in the comments, we should use the Transactional Outbox pattern in these cases.\nUsing this pattern we can even convert non-database operations to database operations too.\nFor example, we can use the Transactional Outbox pattern to trigger another event that calls an API i...
[ 0 ]
[]
[]
[ "apache_kafka", "python" ]
stackoverflow_0074483533_apache_kafka_python.txt
Q: AWS CodeArtifact error with 401 Unauthorized when trying to upload with twine I'm having issues pushing python package into CodeArtifact using twine. I would love your ideas on what this might be and how to debug this. I've setup the repository following this doc. Running aws codeartifact login --tool twine is suc...
AWS CodeArtifact error with 401 Unauthorized when trying to upload with twine
I'm having issues pushing python package into CodeArtifact using twine. I would love your ideas on what this might be and how to debug this. I've setup the repository following this doc. Running aws codeartifact login --tool twine is successful and I see the password updated in the ~/.pypirc file: $ aws codeartifact lo...
[ "As a workaround, I created a new repository and migrated to it. After a while deleted the problematic repository. Never got to the bottom of this.\n" ]
[ 0 ]
[]
[]
[ "amazon_web_services", "aws_cli", "aws_codeartifact", "python", "twine" ]
stackoverflow_0074296513_amazon_web_services_aws_cli_aws_codeartifact_python_twine.txt
Q: Python runs on terminal, not on web browser I'm trying to run a simple python script on my webserver, but it's not showing up in the web browser. In terminal I check if python is installed: whereis python python: /usr/bin/python2.7 /usr/bin/python2.7-config /usr/bin/python /usr/lib/python2.7 /usr/lib64/python2.7 /...
Python runs on terminal, not on web browser
I'm trying to run a simple python script on my webserver, but it's not showing up in the web browser. In terminal I check if python is installed: whereis python python: /usr/bin/python2.7 /usr/bin/python2.7-config /usr/bin/python /usr/lib/python2.7 /usr/lib64/python2.7 /etc/python /usr/local/bin/python3.9-config /usr/l...
[ "The browser doesn't have a Python interpreter. So opening the file in a browser is just going to show your source code. If you want it to show on a browser you need to run it on a server where it can be interpreted. A simple solution is to use Flask, which comes with a development server. Once you've installed fla...
[ 1 ]
[]
[]
[ "html", "python", "python_2.7", "web" ]
stackoverflow_0074495234_html_python_python_2.7_web.txt
Q: How do I type the `__prepare__` method for a metaclass? I’m trying to write a simple metaclass that intercepts every function declaration and replaces it with a dummy function: from dataclasses import dataclass from typing import Any, Mapping @dataclass class DummyCall: args: tuple[Any, ...] kwargs: dict[...
How do I type the `__prepare__` method for a metaclass?
I’m trying to write a simple metaclass that intercepts every function declaration and replaces it with a dummy function: from dataclasses import dataclass from typing import Any, Mapping @dataclass class DummyCall: args: tuple[Any, ...] kwargs: dict[str, Any] def _dummy_function(*args: Any, **kwargs: Any) -...
[ "The reason was that I didn’t use the exact same argument names as in the .pyi file.\nThis works:\n@classmethod\ndef __prepare__(metacls, __name: str, __bases: tuple[type, ...], **kwds: Any) -> Mapping[str, object]:\n …\n\nInterestingly, the type doesn’t need to match exactly. I was able to use tuple instead of ...
[ 1 ]
[]
[]
[ "mypy", "python", "type_hinting" ]
stackoverflow_0074495312_mypy_python_type_hinting.txt
Q: How to change a Label text on another screen by pressing a Button Python Kivy How can I change the value of text in Label on the 2nd screen by pressing a Button on the 1st screen? In my example, I have 2 screens, on the first there are 3 buttons; one should change the text to "1st text", second should change the t...
How to change a Label text on another screen by pressing a Button Python Kivy
How can I change the value of text in Label on the 2nd screen by pressing a Button on the 1st screen? In my example, I have 2 screens, on the first there are 3 buttons; one should change the text to "1st text", second should change the text to "2nd text" and the third is used to move between these two screens. On the s...
[ "In the kv file call a function in the screen 1 class. You can then use the get_screen function to access the other screen and change its text in that function.\nWould probably look something like:\n(in the kv file)\non_press: root.functionname()\n\n(main python file)\ndef functionname(self):\n self.manager....
[ 1 ]
[]
[]
[ "kivy", "kivy_language", "python" ]
stackoverflow_0074495199_kivy_kivy_language_python.txt
Q: How to pd.read_xml from zipfile with UTF-16 encoding? I have a Zip archive with a number of xml files, which I would like to read into a Pandas data frame. The xml files are UTF-16 encoded, hence they can be read as: import pandas as pd # works with open("data1.xml", encoding='utf-16') as f: data = pd.read_xm...
How to pd.read_xml from zipfile with UTF-16 encoding?
I have a Zip archive with a number of xml files, which I would like to read into a Pandas data frame. The xml files are UTF-16 encoded, hence they can be read as: import pandas as pd # works with open("data1.xml", encoding='utf-16') as f: data = pd.read_xml(f) # works data = pd.read_xml("data1.xml", encoding='utf...
[ "ZipFile.open reads in binary mode. To read as UTF-16 text wrap in a TextIoWrapper.\nBelow assumes a test.zip file with UTF-16-encoded test.xml inside:\nimport zipfile\nimport pandas as pd\nimport io\n\nz = zipfile.ZipFile('test.zip')\nwith z.open(\"test.xml\") as f:\n t = io.TextIOWrapper(f, encoding='utf-16')...
[ 2 ]
[]
[]
[ "pandas", "python", "python_3.x", "xml", "zip" ]
stackoverflow_0074491605_pandas_python_python_3.x_xml_zip.txt
Q: How to install SciPy on Apple Silicon (ARM / M1) I have successfully installed python 3.9.1 with Numpy and Matplotlib on a new Mac mini with Apple Silicon. However, I cannot install SciPy : I get compilation errors when using python3 -m pip install scipy I also tried installing everything from brew, and import sc...
How to install SciPy on Apple Silicon (ARM / M1)
I have successfully installed python 3.9.1 with Numpy and Matplotlib on a new Mac mini with Apple Silicon. However, I cannot install SciPy : I get compilation errors when using python3 -m pip install scipy I also tried installing everything from brew, and import scipy works, but using it gives a seg fault. I have inst...
[ "It's possible to install on regular arm64 brew python, you need to compile it yourself.\nIf numpy is already installed (from wheels) you'll need to uninstall it:\npip3 uninstall -y numpy pythran\n\nI had to compile numpy, which requires cython and pybind11:\npip3 install cython pybind11\n\nThen numpy can be compil...
[ 70, 64, 46, 12, 10, 4, 3, 2, 2, 1, 0, 0 ]
[]
[]
[ "apple_m1", "apple_silicon", "arm", "python", "scipy" ]
stackoverflow_0065745683_apple_m1_apple_silicon_arm_python_scipy.txt
Q: pandas converting floats to strings without decimals I have a dataframe df = pd.DataFrame([ ['2', '3', 'nan'], ['0', '1', '4'], ['5', 'nan', '7'] ]) print df 0 1 2 0 2 3 nan 1 0 1 4 2 5 nan 7 I want to convert these strings to numbers and sum the columns and...
pandas converting floats to strings without decimals
I have a dataframe df = pd.DataFrame([ ['2', '3', 'nan'], ['0', '1', '4'], ['5', 'nan', '7'] ]) print df 0 1 2 0 2 3 nan 1 0 1 4 2 5 nan 7 I want to convert these strings to numbers and sum the columns and convert back to strings. Using astype(float) seems to get...
[ "Converting to int (i.e. with .astype(int).astype(str)) won't work if your column contains nulls; it's often a better idea to use string formatting to explicitly specify the format of your string column; (you can set this in pd.options):\n>>> pd.options.display.float_format = '{:,.0f}'.format\n>>> df.astype(float)....
[ 30, 23, 23, 3, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0038516316_pandas_python.txt
Q: How to generate valid timestamps from YouTube subtitles, downloaded with wrong timestamps? (using pytube) Using pytube, I am trying to download a YouTube video, translate the subtitles and embed the translated subtitles back into the video, then download it to my PC. This is a part of my code, changed so it will b...
How to generate valid timestamps from YouTube subtitles, downloaded with wrong timestamps? (using pytube)
Using pytube, I am trying to download a YouTube video, translate the subtitles and embed the translated subtitles back into the video, then download it to my PC. This is a part of my code, changed so it will be easy to understand. from pytube import YouTube as YT yt = YT("https://www.youtube.com/watch?v=ZFGAz6vZx1E") ...
[ "when you generate the caption as xml, you will notice that the time multiplied to 1000 for some reason\nTime after \"t=\" is the when text starts to appear in seconds, \"d=\" is when it ends\nSo i just spilled the time, divide it by 1000 , make it in as \"hour:minutes:second\" , take the text and put all in my fil...
[ 0 ]
[]
[]
[ "caption", "python", "pytube", "srt" ]
stackoverflow_0074330836_caption_python_pytube_srt.txt
Q: Pandas dataframe with N columns I need to use Python with Pandas to write a DataFrame with N columns. This is a simplified version of what I have: Ind=[[1, 2, 3],[4, 5, 6],[7, 8, 9],[10, 11, 12]] DAT = pd.DataFrame([Ind[0],Ind[1],Ind[2],Ind[3]], index=None).T DAT.head() Out 0 1 2 3 0 1 4 7 10 1...
Pandas dataframe with N columns
I need to use Python with Pandas to write a DataFrame with N columns. This is a simplified version of what I have: Ind=[[1, 2, 3],[4, 5, 6],[7, 8, 9],[10, 11, 12]] DAT = pd.DataFrame([Ind[0],Ind[1],Ind[2],Ind[3]], index=None).T DAT.head() Out 0 1 2 3 0 1 4 7 10 1 2 5 8 11 2 3 6 9 12 ...
[ "You can just pass the list directly:\ndata = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]\ndf = pd.DataFrame(data, index=None).T\ndf.head()\n\nOutputs:\n 0 1 2\n0 1 2 3\n1 4 5 6\n2 7 8 9\n3 10 11 12\n\n" ]
[ 2 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074495578_pandas_python.txt
Q: Why does tf.executing_eagerly() return False in TensorFlow 2? Let me explain my set up. I am using TensorFlow 2.1, the Keras version shipped with TF, and TensorFlow Probability 0.9. I have a function get_model that creates (with the functional API) and returns a model using Keras and custom layers. In the __init__...
Why does tf.executing_eagerly() return False in TensorFlow 2?
Let me explain my set up. I am using TensorFlow 2.1, the Keras version shipped with TF, and TensorFlow Probability 0.9. I have a function get_model that creates (with the functional API) and returns a model using Keras and custom layers. In the __init__ method of these custom layers A, I call a method A.m, which execut...
[ "As far as I know, when an input to a custom layer is symbolic input, then the layer is executed in graph (non-eager) mode. However, if your input to the custom layer is an eager tensor (as in the following example #1, then the custom layer is executed in the eager mode. So your model's output tf.executing_eagerly(...
[ 2, 1 ]
[]
[]
[ "keras", "python", "tensorflow", "tensorflow2.0", "tensorflow_probability" ]
stackoverflow_0061355474_keras_python_tensorflow_tensorflow2.0_tensorflow_probability.txt
Q: Python tkinter: configure multiple labels with a loop I have a window with multiple labels. Instead of configuring each label individually, I want to use a for loop to configure them. Basically, what I get from the below code is all labels are showing the text 'question #3', but I want each label label to show the...
Python tkinter: configure multiple labels with a loop
I have a window with multiple labels. Instead of configuring each label individually, I want to use a for loop to configure them. Basically, what I get from the below code is all labels are showing the text 'question #3', but I want each label label to show the right text accordingly - so label1 needs to have the text ...
[ "The easiest way to do so by only modifying your code will involve using zip. Your code just have some looping issues. \nfor x, l in zip(nums,labels): #change your for loops to this\n jk = string + x\n l.config(text=jk)\n\nWriting a concise code involving this: generating the label and the text together could...
[ 1, 0, 0 ]
[]
[]
[ "for_loop", "loops", "python", "tkinter" ]
stackoverflow_0042599924_for_loop_loops_python_tkinter.txt
Q: Getting ALL picture file names from wikimedia commons search So I'm trying to get all the picture files names for a wikimedia image search, but I'm only getting 10 results. As an example, I tried running: import json from io import StringIO import pandas as pd import numpy as np import cv2 import matplotlib.pyplot...
Getting ALL picture file names from wikimedia commons search
So I'm trying to get all the picture files names for a wikimedia image search, but I'm only getting 10 results. As an example, I tried running: import json from io import StringIO import pandas as pd import numpy as np import cv2 import matplotlib.pyplot as plt import urllib.request import requests import time import s...
[ "MediaWiki API queries are paginated. This means that each API call will return a maximum number of results, and you will need to include additional parameters in subsequent requests in order to retrieve the remaining results.\nThe official documentation has an example that demonstrates how to submit the continuat...
[ 0 ]
[]
[]
[ "image", "python", "wikimedia_commons" ]
stackoverflow_0074495385_image_python_wikimedia_commons.txt
Q: How to change a dataframe column from String type to Double type in PySpark? I have a dataframe with column as String. I wanted to change the column type to Double type in PySpark. Following is the way, I did: toDoublefunc = UserDefinedFunction(lambda x: x,DoubleType()) changedTypedf = joindf.withColumn("label",to...
How to change a dataframe column from String type to Double type in PySpark?
I have a dataframe with column as String. I wanted to change the column type to Double type in PySpark. Following is the way, I did: toDoublefunc = UserDefinedFunction(lambda x: x,DoubleType()) changedTypedf = joindf.withColumn("label",toDoublefunc(joindf['show'])) Just wanted to know, is this the right way to do it a...
[ "There is no need for an UDF here. Column already provides cast method with DataType instance :\nfrom pyspark.sql.types import DoubleType\n\nchangedTypedf = joindf.withColumn(\"label\", joindf[\"show\"].cast(DoubleType()))\n\nor short string:\nchangedTypedf = joindf.withColumn(\"label\", joindf[\"show\"].cast(\"dou...
[ 254, 77, 15, 6, 1, 0 ]
[]
[]
[ "apache_spark", "apache_spark_sql", "dataframe", "pyspark", "python" ]
stackoverflow_0032284620_apache_spark_apache_spark_sql_dataframe_pyspark_python.txt
Q: How to fit multiple gaussians on one plot? I'm interested in fitting multiple Gaussian curves to the plot below in python. I need to be able to determine the mean of each gaussian to be able to estimate what 1 photoelectron corresponds to for a signal reading device that took this data. I need to know how to do th...
How to fit multiple gaussians on one plot?
I'm interested in fitting multiple Gaussian curves to the plot below in python. I need to be able to determine the mean of each gaussian to be able to estimate what 1 photoelectron corresponds to for a signal reading device that took this data. I need to know how to do this for an undetermined amount of peaks as each d...
[ "I suppose you're using Gaussian Mixture Model from sklearn.\nIn that case from the docs\nimport numpy as np\nfrom sklearn.mixture import GaussianMixture\nX = np.array([[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]])\ngm = GaussianMixture(n_components=2, random_state=0).fit(X)\n\nThe attributes gm.means_ are th...
[ 0 ]
[]
[]
[ "gaussian_mixture_model", "python", "scikit_learn", "statistics" ]
stackoverflow_0074495113_gaussian_mixture_model_python_scikit_learn_statistics.txt
Q: list of lists coordinates to a list of coordinates with space for SVG file I have a list my_list = [[200.0, 10.0], [250.0, 190.0], [160.0, 210.0]] I want get the list of these coordinate with space between them req_list = "200,10 250,190 160,210" to write these in SVG format for polygons. I tried replacing "[]" ...
list of lists coordinates to a list of coordinates with space for SVG file
I have a list my_list = [[200.0, 10.0], [250.0, 190.0], [160.0, 210.0]] I want get the list of these coordinate with space between them req_list = "200,10 250,190 160,210" to write these in SVG format for polygons. I tried replacing "[]" with " " but replace doesn't work for an array my_list.replace("[", " ")
[ "You can use str.join to the sublists:\nmy_list = [[200.0, 10.0], [250.0, 190.0], [160.0, 210.0]]\n\nreq_list = \" \".join(\",\".join(f\"{int(v)}\" for v in l) for l in my_list)\nprint(req_list)\n\nPrints:\n200,10 250,190 160,210\n\n", "You can iterate through the list and append them into an empty string defined...
[ 1, 1 ]
[]
[]
[ "list", "python", "python_3.x" ]
stackoverflow_0074495642_list_python_python_3.x.txt
Q: non sequitur, should be quick fix. why is y=2, (y==int() False)what did I miss: I just typed this into IDLE shell. maybe somethigns up with it? or it was a snake and it bit me ( as the saying goes) the statement is: y=2 y==int() output: false I even tried: y=23 type(y) output: <class 'int'> input: y==int() o...
non sequitur, should be quick fix. why is y=2, (y==int() False)what did I miss:
I just typed this into IDLE shell. maybe somethigns up with it? or it was a snake and it bit me ( as the saying goes) the statement is: y=2 y==int() output: false I even tried: y=23 type(y) output: <class 'int'> input: y==int() output: False what am I missing? hoping to learn something here
[ "Type in print(int()) into your shell. It will print 0. Since 0 != 2, y != int().\nYou likely want either:\ntype(y) == int\n\ntype(y) is int\n\nor\nisinstance(y, int)\n\nwith the latter being better practice than the former, because it works with class inheritance (thanks to @dskrypa for his comment).\nNote: From t...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074495769_python.txt
Q: Python code is not syntax highlighted in Pycharm notebook? In the screenshot we see a pretty normal-ish python code cell within the Pycharm notebook viewer The viewer "understands" the notebook: it is bringing up the managed Jupyter server option and knows this is [python] code: So then where did the syntax highl...
Python code is not syntax highlighted in Pycharm notebook?
In the screenshot we see a pretty normal-ish python code cell within the Pycharm notebook viewer The viewer "understands" the notebook: it is bringing up the managed Jupyter server option and knows this is [python] code: So then where did the syntax highlighting go to? How can it be [re-]enabled ?
[ "@Wayne was headed the right direction: that link he provided Wrong Code Highlighting in Jupyter Notebooks had suggestion to reload the python interpreter.\nWell in my case the interpreter is Synapse Pyspark and is grayed out since i'm presently running locally. I need to figure out how to change the interpreter: ...
[ 0 ]
[]
[]
[ "jupyter_notebook", "pycharm", "python", "syntax_highlighting" ]
stackoverflow_0074494641_jupyter_notebook_pycharm_python_syntax_highlighting.txt
Q: Py-cord command won't let go I have been trying to update my discord bot to discord.py v2.0 and wanted to switch over to slash commands and cogs. When trying different techniques of achieving this I once used py-cord. I created a test command called latency and it worked but since I struggled with py-cord I uninst...
Py-cord command won't let go
I have been trying to update my discord bot to discord.py v2.0 and wanted to switch over to slash commands and cogs. When trying different techniques of achieving this I once used py-cord. I created a test command called latency and it worked but since I struggled with py-cord I uninstalled py-cord and found a new tech...
[ "When working with slash commands, the discord API registers and deregisters the slash commands on their own servers, and then sets up hooks for your bot.\nThis means that, when the bot connects, it sends an API call to discord to tell it what commands it has, after which you need to wait for Discord to register th...
[ 2 ]
[]
[]
[ "discord", "discord.py", "pycord", "python" ]
stackoverflow_0074495649_discord_discord.py_pycord_python.txt
Q: Multi-label classification predicting exactly n out of m options Say I have m objects and I want to pick which n will be chosen (where m and n are both known). I could run multi-label classification and get the probability that each of the m is chosen and take the n most likely, but that ignores the correlation be...
Multi-label classification predicting exactly n out of m options
Say I have m objects and I want to pick which n will be chosen (where m and n are both known). I could run multi-label classification and get the probability that each of the m is chosen and take the n most likely, but that ignores the correlation between items. I'm wondering if there is a modeling approach (ideally in...
[ "Seems kind of similar to a language model where you want to predict the most likely sentence. If you have the output probabilities for all words, you wouldn't just pick the n likeliest since the sentence would probably make no sense. Instead you condition it on the words you've already chosen.\nSo in your case, th...
[ 0 ]
[]
[]
[ "classification", "deep_learning", "keras", "neural_network", "python" ]
stackoverflow_0074493406_classification_deep_learning_keras_neural_network_python.txt
Q: Kivy Python - getting "FileNotFoundError: [Errno 2] No such file or directory: 'unzip'" I tried to create an APK file by using WSL and get this: # Unpacking Android NDK # Run ['unzip', '-q', '/home/tarpetos/.buildozer/android/platform/android-ndk-r23b-linux.zip'] # Cwd /home/tarpetos/.buildozer/android/platform Tr...
Kivy Python - getting "FileNotFoundError: [Errno 2] No such file or directory: 'unzip'"
I tried to create an APK file by using WSL and get this: # Unpacking Android NDK # Run ['unzip', '-q', '/home/tarpetos/.buildozer/android/platform/android-ndk-r23b-linux.zip'] # Cwd /home/tarpetos/.buildozer/android/platform Traceback (most recent call last): File "/usr/local/bin/buildozer", line 11, in <module> ...
[ "So, to solve this you need to enter to terminal sudo apt-get install unzip. And than this problem will be solved.\n" ]
[ 0 ]
[]
[]
[ "android", "filenotfounderror", "kivy", "python" ]
stackoverflow_0074495652_android_filenotfounderror_kivy_python.txt
Q: How to set the default value for float in sqlalchemy? Using Flask-SQLAlchemy. I wish to set a default value for a property on a model: priority = sa.Column(sa.Float, server_default='0.5') But it does not get set in table: priority double precision, A: i had the same problem, this is what i used to solve it. ser...
How to set the default value for float in sqlalchemy?
Using Flask-SQLAlchemy. I wish to set a default value for a property on a model: priority = sa.Column(sa.Float, server_default='0.5') But it does not get set in table: priority double precision,
[ "i had the same problem, this is what i used to solve it.\nserver_default=u'0.5'\n\n" ]
[ 1 ]
[]
[]
[ "flask", "flask_sqlalchemy", "python", "sqlalchemy" ]
stackoverflow_0031558023_flask_flask_sqlalchemy_python_sqlalchemy.txt
Q: Error while using numpy random.normalvariate() I tried to generate random probs by using the following line code: probs = [np.clip(random.normalvariate(0.1, 0.05), 0, 1) for x in range(1000)] Unexpectedly I faced the following error message: AttributeError: module 'numpy.random' has no attribute 'normalvariate' ...
Error while using numpy random.normalvariate()
I tried to generate random probs by using the following line code: probs = [np.clip(random.normalvariate(0.1, 0.05), 0, 1) for x in range(1000)] Unexpectedly I faced the following error message: AttributeError: module 'numpy.random' has no attribute 'normalvariate' Any idea how to solve this? I checked out the docs I...
[ "It seems that you make confusion between random module whose documenttion is : https://docs.python.org/3.11/library/random.html\nAnd random sub-module that belongs to numpy, its documentation can be found here https://numpy.org/doc/stable/reference/random/index.html\nError origin\nIt seems that you imported numpy....
[ -1 ]
[]
[]
[ "numpy", "python", "random" ]
stackoverflow_0074495445_numpy_python_random.txt
Q: Python selenium timeout exception without message when clicking I want to search specific word in ScienceDirect and when is shows results I want to click 100 result per page at the bottom on page. HTML code: <a class="anchor" data-aa-region="srp-pagination-options" data-aa-name="srp-100-results-per-page" href="/se...
Python selenium timeout exception without message when clicking
I want to search specific word in ScienceDirect and when is shows results I want to click 100 result per page at the bottom on page. HTML code: <a class="anchor" data-aa-region="srp-pagination-options" data-aa-name="srp-100-results-per-page" href="/search?qs=Python&amp;show=100"><span class="anchor-text">100</span></a>...
[ "Use for example this CSS selector:\n \"div#srp-pagination-options li:nth-child(3)\"\n\n" ]
[ 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074493243_python_selenium.txt
Q: Replace dataframe null values with dictionary in Python I have a dataframe (really big) what have some null values and I can replaces them because there are two columns: Name and Weight, Name appears many times, sometimes with weight, sometimes not. This is a little example and what I tried for solve it. First I c...
Replace dataframe null values with dictionary in Python
I have a dataframe (really big) what have some null values and I can replaces them because there are two columns: Name and Weight, Name appears many times, sometimes with weight, sometimes not. This is a little example and what I tried for solve it. First I created the dataframe: import pandas as pd import numpy as np ...
[ "Maybe you can fill the NaNs in .groupby:\ndf[\"Weight\"] = df.groupby(\"Name\", group_keys=False)[\"Weight\"].apply(\n lambda x: x.fillna(x.max())\n)\nprint(df)\n\nPrints:\n Name Weight\n0 AA 12.0\n1 BB 15.0\n2 CC 14.0\n3 AA 12.0\n4 BB 15.0\n5 CC 14.0\n6 AA 12.0\n7 BB 1...
[ 1 ]
[]
[]
[ "dataframe", "dictionary", "loops", "pandas", "python" ]
stackoverflow_0074495757_dataframe_dictionary_loops_pandas_python.txt