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: I want to receive information from the user from discord, but I don't know what to do. ( discord.py ) I want to receive information from the user from discord, but I don't know what to do. I want to make a class to input data if user write !make [name] [data], bot generate class A, A(name, data) The following is t...
I want to receive information from the user from discord, but I don't know what to do. ( discord.py )
I want to receive information from the user from discord, but I don't know what to do. I want to make a class to input data if user write !make [name] [data], bot generate class A, A(name, data) The following is the code I made. What should I do? Ps. command_prefix is not working properly. What should I do with this? `...
[ "I advice to not using on message for making commands\nwhat I do advice:\nimport discord\nfrom discord.ext import commands\n \n@bot.command(name=\"name here if you want a different one than the function name\", description=\"describe it here\", hidden=False) #set hidden to True to hide it in the help\nasync def ...
[ 0 ]
[]
[]
[ "discord", "python" ]
stackoverflow_0074670633_discord_python.txt
Q: How do I get the client IP address of a websocket connection in Django Channels? I need to get the client IP address of a websocket connection for some extra functionality I would like to implement. I have an existing deployed Django server running an Nginx-Gunicorn-Uvicorn Worker-Redis configuration. As one might...
How do I get the client IP address of a websocket connection in Django Channels?
I need to get the client IP address of a websocket connection for some extra functionality I would like to implement. I have an existing deployed Django server running an Nginx-Gunicorn-Uvicorn Worker-Redis configuration. As one might expect, during development, whilst running a local server, everything works as expect...
[ "Client IP has nothing to do with channels\nself.scope[\"client\"][0] is undefined because when you receive data from the front end at the backend there is no data with the name client. so try to send it from the frontend. you can send a manual, static value at first to verify and then find techniques to read the I...
[ 0 ]
[]
[]
[ "django", "django_channels", "nginx", "python" ]
stackoverflow_0074605177_django_django_channels_nginx_python.txt
Q: Same optimization code different results on different computers I am running nested optimization code. sp.optimize.minimize(fun=A, x0=D, method="SLSQP", bounds=(E), constraints=({'type':'eq','fun':constrains}), options={'disp': True, 'maxiter':100, 'ftol':1e-05}) sp.optimize.minimize(fun=B, x0=C, method="Nelder-M...
Same optimization code different results on different computers
I am running nested optimization code. sp.optimize.minimize(fun=A, x0=D, method="SLSQP", bounds=(E), constraints=({'type':'eq','fun':constrains}), options={'disp': True, 'maxiter':100, 'ftol':1e-05}) sp.optimize.minimize(fun=B, x0=C, method="Nelder-Mead", options={'disp': True}) The first minimization is the part of ...
[ "You should never expect numerical methods to perform identically on different devices; or even different runs of the same code on the same device. Due to the finite precision of the machine you can never calculate the \"real\" result, but only numerical approximations. During a long optimization task these differe...
[ 0, 0 ]
[]
[]
[ "minimization", "optimization", "python", "scipy" ]
stackoverflow_0046043768_minimization_optimization_python_scipy.txt
Q: Execute python function from Java code and get result I am working with a Python library but everything else is in Java. I want to be able to access and use the Python library from Java, so I started researching and using Jython. I need to use numpy and neurokit libraries. I write this simple code in Java: Python...
Execute python function from Java code and get result
I am working with a Python library but everything else is in Java. I want to be able to access and use the Python library from Java, so I started researching and using Jython. I need to use numpy and neurokit libraries. I write this simple code in Java: PythonInterpreter interpreter = new PythonInterpreter(); interpre...
[ "Following code can be used for executing python script\n private void runPythonCode(String pythonScript) {\n ProcessBuilder pb = new ProcessBuilder(\"python\", pythonScript);\n\n Process process = pb.start();\n int errCode = process.waitFor();\n\n if (errCode == 1) {\n System.out.println(\...
[ 0, 0 ]
[]
[]
[ "java", "jython", "numpy", "python" ]
stackoverflow_0060171954_java_jython_numpy_python.txt
Q: str object is not callable while importing the dataset on jupyter notebook. what to do? I tried to import the dataset on jupyter notebook. But it indicates error as str object is not callable,even the pathway of the file are obsolutely okay. or Are there any problems with anaconda? help me out!! here is my code af...
str object is not callable while importing the dataset on jupyter notebook. what to do?
I tried to import the dataset on jupyter notebook. But it indicates error as str object is not callable,even the pathway of the file are obsolutely okay. or Are there any problems with anaconda? help me out!! here is my code after importing the libraries: df=pd.read_csv('Nutrients.csv') Even everything is okay it stil...
[ "In pandas.read_csv, the string which is passed inside as a parameter is the name of the file. If the file does not exist, then python just considers the value as a string which in your case is the same.\nTry checking out the location of the jupyter notebook that you are running the code in and the file you want to...
[ 0 ]
[]
[]
[ "dataset", "pandas", "python", "read.csv", "string" ]
stackoverflow_0074669070_dataset_pandas_python_read.csv_string.txt
Q: Generate random numbers list with limit on each element and on total Assume I have a list of values, for example: limits = [10, 6, 3, 5, 1] For every item in limits, I need to generate a random number less than or equal to the item. However, the catch is that the sum of elements in the new random list must be equ...
Generate random numbers list with limit on each element and on total
Assume I have a list of values, for example: limits = [10, 6, 3, 5, 1] For every item in limits, I need to generate a random number less than or equal to the item. However, the catch is that the sum of elements in the new random list must be equal to a specified total. For example if total = 10, then one possible rand...
[ "To generate such a list, you can use numpy's random.multinomial function. This function allows you to generate a list of random numbers that sum to a specified total, where each number is chosen from a different bin with a specified size.\nFor example, to generate a list of 5 random numbers that sum to 10, where t...
[ 1, 1 ]
[]
[]
[ "numpy", "pandas", "python", "scipy" ]
stackoverflow_0074670818_numpy_pandas_python_scipy.txt
Q: How can I load a saved JSON tree with treelib? I have made a Python script wherein I process a big html with BeautifulSoup while I build a tree from it using treelib: http://xiaming.me/treelib/. I have found that this library comes with methods to save the tree file on my system and also parsing it to JSON. But af...
How can I load a saved JSON tree with treelib?
I have made a Python script wherein I process a big html with BeautifulSoup while I build a tree from it using treelib: http://xiaming.me/treelib/. I have found that this library comes with methods to save the tree file on my system and also parsing it to JSON. But after I do this, how can I load it? It is not efficien...
[ "The simple Answer\nWith this treelib, you can't.\nAs they say in their documentation (http://xiaming.me/treelib/pyapi.html#node-objects):\ntree.save2file(filename[, nid[, level[, idhidden[, filter[, key[, reverse]]]]]]])\n Save the tree into file for offline analysis.\n\nIt does not contain any JSON-Parser, so ...
[ 1, 1, 0 ]
[]
[]
[ "json", "python", "tree" ]
stackoverflow_0035031748_json_python_tree.txt
Q: Extract a value from a JSON string stored in a pandas data frame column I have a pandas dataframe with a column named json2 which contains a json string coming from an API call: "{'obj': [{'timestp': '2022-12-03', 'followers': 281475, 'avg_likes_per_post': 7557, 'avg_comments_per_post': 182, 'avg_views_per_post': ...
Extract a value from a JSON string stored in a pandas data frame column
I have a pandas dataframe with a column named json2 which contains a json string coming from an API call: "{'obj': [{'timestp': '2022-12-03', 'followers': 281475, 'avg_likes_per_post': 7557, 'avg_comments_per_post': 182, 'avg_views_per_post': 57148, 'engagement_rate': 2.6848}, {'timestp': '2022-12-02', 'followers': 281...
[ "The key named obj occurs in list of dictionaries. Before you define another key, you must also specify the index of the list element.\nimport ast\ndf['json2']=df['json2'].apply(ast.literal_eval) #if dictionary's type is string, convert to dictionary.\n\ndef get_followers(x):\n if x['obj'][0]['timestp']=='2022-1...
[ 1 ]
[]
[]
[ "dictionary", "json", "pandas", "python" ]
stackoverflow_0074670977_dictionary_json_pandas_python.txt
Q: function that returns the length of the longest run of repetition in a given list im trying to write a function that returns the length of the longest run of repetition in a given list Here is my code: ` def longest_repetition(a): longest = 0 j = 0 run2 = 0 while j <= len(a)-1: for i in a: run = ...
function that returns the length of the longest run of repetition in a given list
im trying to write a function that returns the length of the longest run of repetition in a given list Here is my code: ` def longest_repetition(a): longest = 0 j = 0 run2 = 0 while j <= len(a)-1: for i in a: run = a.count(a[j] == i) if run == 1: run2 += 1 if run2 > longest: ...
[ "First of all, let's check if you were consistent with your question (function that returns the length of the longest run of repetition):\ne.g.:\na = [4,1,2,4,7,9,4]\nb = [5,3,5,6,9,4,4,4,4]\n(assuming, you are only checking single position, e.g. c = [1,2,3,1,2,3] could have one repetition of sequence 1,2,3 - i am ...
[ 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0074670644_list_python.txt
Q: Python array, get item on position with variable vin = txid['vin'][0]['txid'] How I get something like: vout = 3 vin = txid['vin'][vout]['txid'] I assume it won't work like this.... A: You can even use it as user input. No problem at all. txid = {'vin': [{'txid' : 10}, {'txid' : 20}, {'txid' : 30}, {'txid' : 4...
Python array, get item on position with variable
vin = txid['vin'][0]['txid'] How I get something like: vout = 3 vin = txid['vin'][vout]['txid'] I assume it won't work like this....
[ "You can even use it as user input. No problem at all.\ntxid = {'vin': [{'txid' : 10}, {'txid' : 20}, {'txid' : 30}, {'txid' : 40}]}\n\nvin = txid['vin'][0]['txid']\nprint(vin)\n\nvout = 3\nvin = txid['vin'][vout]['txid']\nprint(vin)\n\nOutput:\n10\n40\n\n" ]
[ 0 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0074671001_arrays_python.txt
Q: (flask + socket.IO) Result of emit callback is the response of my REST endpoint Just to give a context here, I'm a node.JS developer, but I'm on a project that I need to work with Python using Flask framework. The problem is, when a client request to an endpoint of my rest flask app, I need to emit an event using ...
(flask + socket.IO) Result of emit callback is the response of my REST endpoint
Just to give a context here, I'm a node.JS developer, but I'm on a project that I need to work with Python using Flask framework. The problem is, when a client request to an endpoint of my rest flask app, I need to emit an event using socket.IO, and get some data from the socket server, then this data is the response o...
[ "I'm going to give you one way to implement what you want specifically, but I believe you have an important design flaw in this, as I explain in a comment above. In the way you have this coded, your socketio.Server() object will broadcast to all your clients, so will not be able to get a callback. If you want to em...
[ 2, 0 ]
[]
[]
[ "flask", "flask_socketio", "python", "socket.io" ]
stackoverflow_0043301977_flask_flask_socketio_python_socket.io.txt
Q: Reversed double linked list by python why can't print reversed this double linked list by python? always print 6 or None please can anyone help me fast to pass this task /////////////////////////////////////////////////////////////////////////// class Node: def __init__(self, data=None, next=None, prev=None...
Reversed double linked list by python
why can't print reversed this double linked list by python? always print 6 or None please can anyone help me fast to pass this task /////////////////////////////////////////////////////////////////////////// class Node: def __init__(self, data=None, next=None, prev=None): self.data = data ...
[ "Your printReverse seems to do something else than what its name suggests. I would think that this function would just iterate the list nodes in reversed order and print the values, but it actually reverses the list, and doesn't print the result because of a bug.\nThe error in your code is that the final loop has a...
[ 1 ]
[]
[]
[ "linked_list", "python" ]
stackoverflow_0074670265_linked_list_python.txt
Q: Stuck on Python "KeyError: " in BFS code of a water jug scenario Intended Function of code: Takes a user input for the volume of 3 jars(1-9) and output the volumes with one of the jars containing the target length. jars can be Emptied/Filled a jar, or poured from one jar to another until one is empty or full. With...
Stuck on Python "KeyError: " in BFS code of a water jug scenario
Intended Function of code: Takes a user input for the volume of 3 jars(1-9) and output the volumes with one of the jars containing the target length. jars can be Emptied/Filled a jar, or poured from one jar to another until one is empty or full. With the code I have, i'm stuck on a key exception error . Target length i...
[ "Strange but when I first ran this in the IPython interpreter I got a different exception:\n... :35, in Graph.isAdjacent(self, a, b)\n 34 def isAdjacent(self, a: GraphNode, b: GraphNode) -> bool:\n---> 35 if self.V[a]==b:\n 36 return True\n 37 return False\n\n<class 'str'>: (<class 'Recu...
[ 1 ]
[]
[]
[ "breadth_first_search", "graph_traversal", "python" ]
stackoverflow_0074664111_breadth_first_search_graph_traversal_python.txt
Q: Extraction multiple data points from a long sentence/paragraph I was looking for an approach or any useful libraries to extract multiple data points that corresponds to different years, from a single paragraph. For eg. The total volume of the sales in the year 2019 is 400 whereas in the year 2020 is 600. That's a...
Extraction multiple data points from a long sentence/paragraph
I was looking for an approach or any useful libraries to extract multiple data points that corresponds to different years, from a single paragraph. For eg. The total volume of the sales in the year 2019 is 400 whereas in the year 2020 is 600. That's about 50% \increase in size In the above example, i need to extract,...
[ "One approach you could take is to use regular expressions to search for patterns in the text that match the information you're looking for. For example, in the sentence \"The total volume of the sales in the year 2019 is 400 whereas in the year 2020 is 600.\", you could use the following regular expression to matc...
[ 1 ]
[]
[]
[ "nlp", "python" ]
stackoverflow_0074671055_nlp_python.txt
Q: What is the difference between __str__ and __repr__? What is the difference between __str__ and __repr__ in Python? A: Alex summarized well but, surprisingly, was too succinct. First, let me reiterate the main points in Alex’s post: The default implementation is useless (it’s hard to think of one which wouldn’t...
What is the difference between __str__ and __repr__?
What is the difference between __str__ and __repr__ in Python?
[ "Alex summarized well but, surprisingly, was too succinct.\nFirst, let me reiterate the main points in Alex’s post:\n\nThe default implementation is useless (it’s hard to think of one which wouldn’t be, but yeah)\n__repr__ goal is to be unambiguous\n__str__ goal is to be readable\nContainer’s __str__ uses contained...
[ 3334, 749, 498, 207, 201, 164, 49, 48, 37, 16, 15, 14, 12, 9, 9, 9, 8, 6, 6, 5, 5, 4, 4, 3, 3, 1, 1, 1, 0 ]
[]
[]
[ "magic_methods", "python", "repr" ]
stackoverflow_0001436703_magic_methods_python_repr.txt
Q: Convert Variable Name to String? I would like to convert a python variable name into the string equivalent as shown. Any ideas how? var = {} print ??? # Would like to see 'var' something_else = 3 print ??? # Would print 'something_else' A: TL;DR: Not possible. See 'conclusion' at the end. There is an usage sc...
Convert Variable Name to String?
I would like to convert a python variable name into the string equivalent as shown. Any ideas how? var = {} print ??? # Would like to see 'var' something_else = 3 print ??? # Would print 'something_else'
[ "TL;DR: Not possible. See 'conclusion' at the end.\n\nThere is an usage scenario where you might need this. I'm not implying there are not better ways or achieving the same functionality.\nThis would be useful in order to 'dump' an arbitrary list of dictionaries in case of error, in debug modes and other similar si...
[ 62, 41, 14, 12, 7, 6, 3, 2, 2, 2, 2, 2, 2, 2, 1, 0, 0, 0, 0, 0, 0 ]
[ "This module works for converting variables names to a string:\nhttps://pypi.org/project/varname/\nUse it like this:\nfrom varname import nameof\n\nvariable=0\n\nname=nameof(variable)\n\nprint(name)\n\n//output: variable\n\nInstall it by:\npip install varname\n\n", "print \"var\"\nprint \"something_else\"\n\nOr d...
[ -1, -3 ]
[ "python", "string", "variables" ]
stackoverflow_0001534504_python_string_variables.txt
Q: AWS S3 Boto3 Python - An error occurred (AccessDenied) when calling the DeleteObject operation: Access Denied I am having a problem implementing delete_object. def delete_image_from_s3(img=None): if img: try: response = client.delete_object( Bucket='my-bucket', Key='...
AWS S3 Boto3 Python - An error occurred (AccessDenied) when calling the DeleteObject operation: Access Denied
I am having a problem implementing delete_object. def delete_image_from_s3(img=None): if img: try: response = client.delete_object( Bucket='my-bucket', Key='uploads/img.jpg', ) print(response) except ClientError as ce: print("er...
[ "The policy you have shown appears to be a Bucket Policy that is assigned to a specific bucket. This policy is granting anyone in the world permission to use your S3 bucket, so it is not recommended from a security viewpoint. You should remove this bucket policy.\nYou have mentioned that the provided code is runnin...
[ 0 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "boto3", "python" ]
stackoverflow_0074669404_amazon_s3_amazon_web_services_boto3_python.txt
Q: KeyError: '...' keeps coming back I keep getting the error and can't find where the problem lies. I'm trying so I can choose wether I want the attack the creature or both printed and what type the creature is: 'easy', 'medium' or 'hard', I want to store that into a variable. creature = {'easy': ['chicken', 'slime'...
KeyError: '...' keeps coming back
I keep getting the error and can't find where the problem lies. I'm trying so I can choose wether I want the attack the creature or both printed and what type the creature is: 'easy', 'medium' or 'hard', I want to store that into a variable. creature = {'easy': ['chicken', 'slime', 'rat'], 'medium': ['wolf'...
[ "You might want something like:\nchosen_level = 'easy'\ngame_data = dict(zip(creature[chosen_level], attack[chosen_level]))\n\nimport random\ncre = random.choice(list(game_data))\natt = game_data[cre]\n\nprint(cre, att) \n\nOutput: rat scratches\n" ]
[ 2 ]
[]
[]
[ "dictionary", "keyerror", "python" ]
stackoverflow_0074671020_dictionary_keyerror_python.txt
Q: How do I fill a dictionary with indices in a for loop? I have a transposed Dataframe tr: 7128 8719 14051 14636 JDUTC_0 2451957.36 2452149.36 2457243.98 2452531.89 JDUTC_1 2451957.37 2452149.36 2457243.99 2452531.90 JDUTC_2 2451957.37 2452149.36 2457244.00 2452531.91 JDUTC_3 NaN 2452149.36 NaN NaN JDUTC_4 NaN...
How do I fill a dictionary with indices in a for loop?
I have a transposed Dataframe tr: 7128 8719 14051 14636 JDUTC_0 2451957.36 2452149.36 2457243.98 2452531.89 JDUTC_1 2451957.37 2452149.36 2457243.99 2452531.90 JDUTC_2 2451957.37 2452149.36 2457244.00 2452531.91 JDUTC_3 NaN 2452149.36 NaN NaN JDUTC_4 NaN 2452149.36 NaN NaN JDUTC_5 NaN 2452149.36 NaN ...
[ "The problem is you are assigning same list to all keys.\na = {}\nb=[] # < --- You create one Array/list 'b'\nfor _, contents in tr.items():\n b.clear()\n for ind, val in enumerate(contents):\n if np.isnan(val):\n b.append(ind)\n continue\n else:\n pass\n prin...
[ 1, 1 ]
[]
[]
[ "dictionary", "for_loop", "python" ]
stackoverflow_0074669044_dictionary_for_loop_python.txt
Q: Add toolbar button icon matplotlib I want to add an icon to a custom button in a matplotlib figure toolbar. How can I do that? So far, I have the following code: import matplotlib matplotlib.rcParams["toolbar"] = "toolmanager" import matplotlib.pyplot as plt from matplotlib.backend_tools import ToolToggleBase cla...
Add toolbar button icon matplotlib
I want to add an icon to a custom button in a matplotlib figure toolbar. How can I do that? So far, I have the following code: import matplotlib matplotlib.rcParams["toolbar"] = "toolmanager" import matplotlib.pyplot as plt from matplotlib.backend_tools import ToolToggleBase class NewTool(ToolToggleBase): ...[tool...
[ "The tool can have an attribute image, which denotes the path to a png image.\nimport matplotlib\nmatplotlib.rcParams[\"toolbar\"] = \"toolmanager\"\nimport matplotlib.pyplot as plt\nfrom matplotlib.backend_tools import ToolBase\n\nclass NewTool(ToolBase):\n image = r\"C:\\path\\to\\hiker.png\"\n\nfig = plt.figu...
[ 7, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0052971285_matplotlib_python.txt
Q: How to apply contour to z matrix which has the same dimension as x- and y matrix My dataset contains x, y coordinate and energy surface z. I need to turn those into this image. The problem is that z need to have the dimension of (x, y) but all three of them are 1D numpy array with length = 10201 (also some values ...
How to apply contour to z matrix which has the same dimension as x- and y matrix
My dataset contains x, y coordinate and energy surface z. I need to turn those into this image. The problem is that z need to have the dimension of (x, y) but all three of them are 1D numpy array with length = 10201 (also some values in z are inf). I tried to turn z into a meshgrid with Z, Z = np.meshgrid(z,z) and the...
[ "To create a contour plot from your 1D arrays of x, y, and z coordinates, you can use NumPy's meshgrid function to create 2D grids from your 1D arrays, and then use the contour function from Matplotlib to create the contour plot.\nFirst, you need to create 2D grids from your 1D arrays of x and y coordinates using N...
[ 0 ]
[]
[]
[ "contour", "matplotlib", "python" ]
stackoverflow_0074671161_contour_matplotlib_python.txt
Q: Creating folder if it does not exist, move files there I am python newbie and have read countless answers here and in other sources, on how to create folders if they do not exist and move files there. However, still I cannot bring it to work. So what I want to do is the following: Keep my downloads folder clean. I...
Creating folder if it does not exist, move files there
I am python newbie and have read countless answers here and in other sources, on how to create folders if they do not exist and move files there. However, still I cannot bring it to work. So what I want to do is the following: Keep my downloads folder clean. I want to run the script, it is supposed to move all files to...
[ "os.makedirs has a switch to create a folder if it does not exist.\nuse it like this:\nos.makedirs(foldern_name, exist_ok=True)\n\nso just replace that try...except part of code which is this:\n\ntry:\n\n [os.makedirs(e) for e in ext_final]\n\nexcept:\n\n print(\"Folder already exists!\")\n\nwith this:\nfor e...
[ 0, 0, 0 ]
[]
[]
[ "operating_system", "python", "shutil" ]
stackoverflow_0074670080_operating_system_python_shutil.txt
Q: Regex match a string of 18 characters (4 digits + 14 letters uppercase) please help me find a regex match this combination here it is a few examples of strings i want , I hope it helps you 1st example "HBYVHDV86DBYF44CGB" 2nd example "NGCDV15DVDB81JHDBR" 3rd example "MOX48DVPLYBJHD63JH" As you can see, there ...
Regex match a string of 18 characters (4 digits + 14 letters uppercase)
please help me find a regex match this combination here it is a few examples of strings i want , I hope it helps you 1st example "HBYVHDV86DBYF44CGB" 2nd example "NGCDV15DVDB81JHDBR" 3rd example "MOX48DVPLYBJHD63JH" As you can see, there is something special , the four numbers are divided into two parts on the st...
[ "You can use look-ahead to test one of the conditions, like the total length of the input. The other conditions can be expressed close to what you proposed, but with double digits (\\d\\d) and end-of-input anchors (^ and $)\n^(?=\\w{18}$)[A-Za-z]+\\d\\d[A-Za-z]+\\d\\d[A-Za-z]+$\n\n" ]
[ 0 ]
[]
[]
[ "digits", "letter", "python", "regex", "uppercase" ]
stackoverflow_0074668785_digits_letter_python_regex_uppercase.txt
Q: when I run the following function I received this error IndexError: index 0 is out of bounds for axis 0 with size 0 index problem while running predication funcation def predict_death(anaemia,high_blood_pressure,serum_creatinine,serum_sodium,smoking): anaemia_index = np.where(X.columns==anaemia)[0][0] ...
when I run the following function I received this error IndexError: index 0 is out of bounds for axis 0 with size 0
index problem while running predication funcation def predict_death(anaemia,high_blood_pressure,serum_creatinine,serum_sodium,smoking): anaemia_index = np.where(X.columns==anaemia)[0][0] x = np.zeros(len(X.columns)) x[0] =high_blood_pressure x[1] = serum_creatinine x[2] = serum_sodium x[3] =...
[ "t looks like you are trying to use the np.where function to find the index of a column in the X DataFrame by its name. However, the np.where function does not work like this - it returns the indices of elements in an array that match a specified condition.\nTo get the index of a column in a DataFrame by its name, ...
[ 0 ]
[]
[]
[ "deep_learning", "for_loop", "function", "machine_learning", "python" ]
stackoverflow_0074670166_deep_learning_for_loop_function_machine_learning_python.txt
Q: Flask-SQLAlchemy Legacy vs New Query Interface I am trying to update some queries in a web application because as stated in Flask-SQLAlchemy You may see uses of Model.query or session.query to build queries. That query interface is considered legacy in SQLAlchemy. Prefer using the session.execute(select(...)) inst...
Flask-SQLAlchemy Legacy vs New Query Interface
I am trying to update some queries in a web application because as stated in Flask-SQLAlchemy You may see uses of Model.query or session.query to build queries. That query interface is considered legacy in SQLAlchemy. Prefer using the session.execute(select(...)) instead. I have a query: subnets = db.session.query(Sub...
[ "As noted in the comments to the question, your second example is not directly comparable to your first example because your second example is missing the .all() at the end.\nSide note:\nsession.scalars(select(Subnet).order_by(Subnet.id)).all()\n\nis a convenient shorthand for\nsession.execute(select(Subnet).order_...
[ 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0074668995_python_sqlalchemy.txt
Q: How to access the first two elements for each product_catogory I have already sorted the dataframe(dfDogNew) based on product_category and quantity_sold. Now I want to access the first two most sold product in each product category, how can I achieve this? I have written a for loop to access them, but the system t...
How to access the first two elements for each product_catogory
I have already sorted the dataframe(dfDogNew) based on product_category and quantity_sold. Now I want to access the first two most sold product in each product category, how can I achieve this? I have written a for loop to access them, but the system tells me there is a key error, does anyone can help me on this? Thank...
[ "It looks like you're trying to filter your DataFrame to get the first two rows for each unique value of the product_category column. One way to do this is to use the DataFrame.groupby method, which allows you to group your data by a particular column and then apply a function to each group.\nIn your case, you can ...
[ 1 ]
[]
[]
[ "numpy_slicing", "pandas", "python" ]
stackoverflow_0074671202_numpy_slicing_pandas_python.txt
Q: Displaying text onto pygame window from file using readline() I'm currently trying to read text from a .txt file then display it onto a pygame window. The problem I'm facing is that it just displays nothing at all when I try to read through the whole txt file using a readline() loop. When I run the code below, it ...
Displaying text onto pygame window from file using readline()
I'm currently trying to read text from a .txt file then display it onto a pygame window. The problem I'm facing is that it just displays nothing at all when I try to read through the whole txt file using a readline() loop. When I run the code below, it prints all the lines to the terminal but doesn't display it onto th...
[ "You have to add the lines read from the file to a list (see How to read a file line-by-line into a list?):\nlist_of_lines = []\nwith open('file.txt') as file:\n list_of_lines = [line.rstrip() for line in file]\n\nAfter that you can render the text lines from the list:\nfont = pygame.font.SysFont('impact', 30)\n...
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0074671176_pygame_python.txt
Q: Find the Gaussian probability density of x for a normal distribution So, I'm supposed to write a function normpdf(x , avg, std) that returns the Gaussian probability density function of x for a normal distribution with mean avg and standard deviation std, with avg = 0 and std = 1. This is what I got so far, but wh...
Find the Gaussian probability density of x for a normal distribution
So, I'm supposed to write a function normpdf(x , avg, std) that returns the Gaussian probability density function of x for a normal distribution with mean avg and standard deviation std, with avg = 0 and std = 1. This is what I got so far, but when I click run, I get this message: Input In [95] return pdf ^ Syn...
[ "You don't need the math module. Use just numpy functions:\nimport numpy as np\n\n\ndef normpdf(x, avg=0, std=1):\n exp = np.exp(-0.5 * ((x - avg) / std) ** 2)\n pdf = (1 / (std * np.sqrt(2 * np.pi)) * exp)\n return pdf\n\n\nx = np.linspace(1, 50)\n\nprint(normpdf(x))\n\nThe code above will result in:\n[2....
[ 2, 1, 0 ]
[]
[]
[ "gaussian", "normal_distribution", "python" ]
stackoverflow_0074670914_gaussian_normal_distribution_python.txt
Q: Rewrite a pay computation with time-and-a-half for overtime and create a function called computepay which takes two parameters(hours and rate0 Here is my code (btw I am new to Stackoverflow and coding in general so forgive me if I made some mistakes in formatting this question): hours = int(input('Enter hours:')) ...
Rewrite a pay computation with time-and-a-half for overtime and create a function called computepay which takes two parameters(hours and rate0
Here is my code (btw I am new to Stackoverflow and coding in general so forgive me if I made some mistakes in formatting this question): hours = int(input('Enter hours:')) rate = int(input('Enter rate:')) pay =('Your pay this month' + str((hours + hours/2) * rate)) def computepay(hours,rate): pay =('Your pay this mont...
[ "To take into account overtime versus regular rates of pay it seems like you will need to know how much time the employee worked in each category. With that in mind, here is a simplified example to illustrate some of the key concepts.\nExample:\ndef computepay(hours, rate):\n return hours * rate\n\nregular_rate...
[ 0, 0, 0, 0, 0 ]
[]
[]
[ "function", "parameters", "python" ]
stackoverflow_0067036969_function_parameters_python.txt
Q: How to create a FILE HANDLER project in Python that can do the below given tasks: Read content from a txt file character by character. Get number of characters, words, spaces and lines in a file. Find no. of lines in the file. Find the line no. which contains a specific word. PS: Please provide a basic code so th...
How to create a FILE HANDLER project in Python that can do the below given tasks:
Read content from a txt file character by character. Get number of characters, words, spaces and lines in a file. Find no. of lines in the file. Find the line no. which contains a specific word. PS: Please provide a basic code so that a beginner can understand
[ "SpesificWord = input() #get the specific word\nwith open('file.txt','r',encoding='utf-8') as file: #open the file\n for index, line in enumerate(file): #index is current no of file, line is current line\n print(len(line)) # prints the length of line - including space etc.\n print(f'Cur...
[ 0 ]
[]
[]
[ "filehandler", "python" ]
stackoverflow_0074669712_filehandler_python.txt
Q: Python Error Help : IndexError: list index out of range def read_file(): '''reads input file returns a list of information''' #your code here A: The error IndexError: list index out of range is raised when you try to access an index in a list that doesn't exist. For example, if you try to access the 10th element...
Python Error Help : IndexError: list index out of range
def read_file(): '''reads input file returns a list of information''' #your code here
[ "The error IndexError: list index out of range is raised when you try to access an index in a list that doesn't exist. For example, if you try to access the 10th element of a list that only has 3 elements, you will get this error.\nIn your code, you are trying to access the elements in temp using the indices [0], [...
[ 1 ]
[]
[]
[ "index_error", "python" ]
stackoverflow_0074671322_index_error_python.txt
Q: Python : How to contrast contrast data I don't know what is the term for this, but what get the closest to it is the process of contrasting an image. Basically i have a list of values going from 0 to 100. I would like that values over 50 come closer to 100 and values under 50 come closer to 0. for example : [0, 23...
Python : How to contrast contrast data
I don't know what is the term for this, but what get the closest to it is the process of contrasting an image. Basically i have a list of values going from 0 to 100. I would like that values over 50 come closer to 100 and values under 50 come closer to 0. for example : [0, 23, 50,58,100] would become something like thi...
[ "The following code might give you some ideas. If it doesn't meet your needs then you need to clearly explain just what those needs are.\ndef contrast(nums):\n contrasted = []\n for num in nums:\n if num < 50:\n contrasted.append(num//2)\n elif num > 50:\n contrasted.append...
[ 1 ]
[]
[]
[ "math", "python" ]
stackoverflow_0074666019_math_python.txt
Q: How to compare two columns in DataFrame and change value of third column based on that comparison? I have following table in Pandas: index | project | category | period | update | amount 0 | 100130 | labour | 202201 | 202203 | 1000 1 | 100130 | labour | 202202 | 202203 | 1000 2 | 100130 | labour...
How to compare two columns in DataFrame and change value of third column based on that comparison?
I have following table in Pandas: index | project | category | period | update | amount 0 | 100130 | labour | 202201 | 202203 | 1000 1 | 100130 | labour | 202202 | 202203 | 1000 2 | 100130 | labour | 202203 | 202203 | 1000 3 | 100130 | labour | 202204 | 202203 | 1000 4 | 100130 | labour...
[ "table[\"amount\"] = 0 if table[\"period\"] < table[\"update\"] else None\n\n", "I did some more research and this code seems to solve my problem:\ndef check_update(row):\n if row[\"period\"] < row[\"update\"]:\n return 0\n else:\n return row[\"amount\"]\n\ntable[\"amount2\"] = table.apply(che...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074670499_pandas_python.txt
Q: How to perform calculations on a subset of a column in a pandas dataframe? With a dataset such as this: famid birth age ht 0 1 1 one 2.8 1 1 1 two 3.4 2 1 2 one 2.9 3 1 2 two 3.8 4 1 3 one 2.2 5 1 3 two 2.9 ...where we've got va...
How to perform calculations on a subset of a column in a pandas dataframe?
With a dataset such as this: famid birth age ht 0 1 1 one 2.8 1 1 1 two 3.4 2 1 2 one 2.9 3 1 2 two 3.8 4 1 3 one 2.2 5 1 3 two 2.9 ...where we've got values for a variable ht for different categories of, for example, age , I would...
[ "To adjust a subset of a column in a pandas dataframe, you can use the loc method. The loc method allows you to access a subset of the dataframe by specifying the values in the rows and columns that you want. In your case, you want to adjust the values in the ht column where the age column is equal to one. You can ...
[ 2, 2, 1, 1, 1 ]
[]
[]
[ "dataframe", "pandas", "python" ]
stackoverflow_0074670948_dataframe_pandas_python.txt
Q: how to check if a number is even or not in python I am attempting to make a collatz conjecture program, but I can't figure out how to check for even numbers this is my current code for it elif (original_collatz % 2) == 0: new_collatz = collatz/2 anyone have an idea how to check i tried it with modulo ...
how to check if a number is even or not in python
I am attempting to make a collatz conjecture program, but I can't figure out how to check for even numbers this is my current code for it elif (original_collatz % 2) == 0: new_collatz = collatz/2 anyone have an idea how to check i tried it with modulo but could figure out how it works, and my program just...
[ "The problem is not that \"your program ignore the lines\", it's that you test the parity of original_collatz which doesn't change.\n\nYou need to check the parity of collatz\nYou need to use integer division (//) when dividing by two or collatz will become a float.\nYou don't really need to use new_collatz as an i...
[ 1, 1 ]
[]
[]
[ "collatz", "integer", "modulo", "python" ]
stackoverflow_0074671339_collatz_integer_modulo_python.txt
Q: How can I catch all errors from a create.sql just like SQLite gives? I have a create.sql (and a populate.sql) that create a SQLite3 database (and populate it with some dummy data). I then save the resulting database and make some further analysis. I use Python to automate this process for several pairs of sql file...
How can I catch all errors from a create.sql just like SQLite gives?
I have a create.sql (and a populate.sql) that create a SQLite3 database (and populate it with some dummy data). I then save the resulting database and make some further analysis. I use Python to automate this process for several pairs of sql files. db_mem = sqlite3.connect(":memory:") cur = db_mem.cursor() try: wit...
[ "The executescript() will run the whole sql file but will raise exception when an error occurs.\nSince you want to continue the DB schema creation regardless of errors, you could switch from using executescript() to looping over the sql statements list by calling the execute() on each of them.\nThis example will de...
[ 1 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0074671110_python_sqlite.txt
Q: Facing Import Error when importing esda and libpysal libraries Even though I have installed both the libraries several times using different orders in different virtual environments, I'm still facing an issue where I'm not able to import and use certain geospatial libraries like esda and libpysal. The following er...
Facing Import Error when importing esda and libpysal libraries
Even though I have installed both the libraries several times using different orders in different virtual environments, I'm still facing an issue where I'm not able to import and use certain geospatial libraries like esda and libpysal. The following error shows up: ImportError Traceback (m...
[ "install pygeos i.e conda install pygeos\nit worked for me\n", "I found same issue when running example code from a couple of years ago. The pysal API has changed.\nImport libpysal first then import the esda libraries eg\nimport libpysal\nfrom esda.moran import Moran\nfrom esda.smaup import Smaup\n\nsee\nhttps://...
[ 0, 0 ]
[]
[]
[ "geospatial", "gis", "import", "jupyter_notebook", "python" ]
stackoverflow_0068841646_geospatial_gis_import_jupyter_notebook_python.txt
Q: Browser opens twice when running script I'm working on a web driver and I'm trying to implement classes into my code. I had this working but as soon as I turned it into a class my browser started opening twice when I ran the program. It will open a browser, then open the second browser, run the commands and then l...
Browser opens twice when running script
I'm working on a web driver and I'm trying to implement classes into my code. I had this working but as soon as I turned it into a class my browser started opening twice when I ran the program. It will open a browser, then open the second browser, run the commands and then leave the first browser open. Can any tell me ...
[ "It looks like you are creating a new instance of the webdriver.Chrome class when you initialize the About class in this line:\ngo = About(webdriver.Chrome())\n\nThis is causing a new Chrome browser to be opened when you create the About object. Instead, you should create the webdriver.Chrome object outside of the ...
[ 0 ]
[]
[]
[ "google_chrome", "python", "selenium", "selenium_webdriver", "webdriver" ]
stackoverflow_0041432728_google_chrome_python_selenium_selenium_webdriver_webdriver.txt
Q: How to effectively loop through each pixel for saving time with numpy? As you know looping through each pixels and accessing their values with opencv takes too long. As a beginner I'm trying to learn opencv myself when I tried this approach it took me around 7-10 seconds of time to loop through image and perform o...
How to effectively loop through each pixel for saving time with numpy?
As you know looping through each pixels and accessing their values with opencv takes too long. As a beginner I'm trying to learn opencv myself when I tried this approach it took me around 7-10 seconds of time to loop through image and perform operations. code is as below original_image = cv2.imread(img_f) image = np.a...
[ "You can take advantage of NumPy's vectorized operations to eliminate all loops which should be much faster.\n# Remove grey background\nis_grey = ((150 <= image) & (image <= 180)).all(axis=2, keepdims=True)\nimage = np.where(is_grey, 0, image)\n\n# Remove green dashes\nis_green_dash = (image[..., 0] == 0) & (image[...
[ 3, 1, 0, 0 ]
[]
[]
[ "cv2", "image_processing", "numpy", "python" ]
stackoverflow_0074664212_cv2_image_processing_numpy_python.txt
Q: how to check if a line contains text and then stop after it reaches a blank line? [Python] am writing this algorithm that takes strings from a text file and appends them to an array. if the strings are in continuous line ex. ABCD EFG HIJK LMNOP then they would be appended into the same array until it reaches a bl...
how to check if a line contains text and then stop after it reaches a blank line? [Python]
am writing this algorithm that takes strings from a text file and appends them to an array. if the strings are in continuous line ex. ABCD EFG HIJK LMNOP then they would be appended into the same array until it reaches a blank line at which point it stops and starts appending the next number of continuous arrays to a ...
[ "Simply check if the current line equal the new line character.\nwith open('filename.txt', 'r') as f:\n for line in f:\n if line == '\\n':\n print('Empty line')\n else:\n print('line contain string')\n\n", "If you're stripping the linebreak off each line, you can just check ...
[ 0, 0 ]
[]
[]
[ "file", "python", "txt" ]
stackoverflow_0074671373_file_python_txt.txt
Q: Create multicategory chart by python I have the data like the following in excel: company month-year #people got interviewed # people employed link to the data: (https://docs.google.com/spreadsheets/d/1DwZt9fpnzR9yUNBMjmqA1hg11d-2dXNs/edit?usp=share_link&ouid=113997824301423906122&rtpof=true&sd=true) when I try ...
Create multicategory chart by python
I have the data like the following in excel: company month-year #people got interviewed # people employed link to the data: (https://docs.google.com/spreadsheets/d/1DwZt9fpnzR9yUNBMjmqA1hg11d-2dXNs/edit?usp=share_link&ouid=113997824301423906122&rtpof=true&sd=true) when I try to create multicategory chart(compa...
[ "Once you made the dates month-year, they were object type--character strings, not dates—as in date-type. When you sorted, you sorted by calendar month.\nFirst, use strptime to make it a date, sort it, then use strftime.\nimport pandas as pd\nimport plotly.graph_objects as go\nfrom datetime import datetime as dt\n\...
[ 0 ]
[]
[]
[ "linux", "plotly", "python" ]
stackoverflow_0074625714_linux_plotly_python.txt
Q: Scrape tweets by Python and BeautifulSoup I want to scrape the tweets of a specific account on Twitter via SB but it is not working for me this is my code : import facebook as fb from bs4 import BeautifulSoup as bs import requests myUrl = requests.get('https://twitter.com/search?q=(from%3AAlMosahf...
Scrape tweets by Python and BeautifulSoup
I want to scrape the tweets of a specific account on Twitter via SB but it is not working for me this is my code : import facebook as fb from bs4 import BeautifulSoup as bs import requests myUrl = requests.get('https://twitter.com/search?q=(from%3AAlMosahf)&src=typed_query&f=live') source = myUrl.c...
[ "It looks like you're trying to scrape Twitter using Beautiful Soup, but the code you've provided won't work for several reasons.\nFirst, the Twitter website uses JavaScript to dynamically generate its content, which means that the raw HTML you get from a requests.get() call won't include the tweets you're looking ...
[ 2, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0074669065_beautifulsoup_python.txt
Q: Dicts not being popped from list? The context doesn't matter too much, but I came across the problem that while trying to pop dict objects from a list, it wouldn't delete all of them. I'm doing this to filter for certain values in the dict objects, and I was left with things that should have been removed. Just to ...
Dicts not being popped from list?
The context doesn't matter too much, but I came across the problem that while trying to pop dict objects from a list, it wouldn't delete all of them. I'm doing this to filter for certain values in the dict objects, and I was left with things that should have been removed. Just to see what would happen, I tried deleting...
[ "It looks like you're using a for loop to iterate over the list and calling pop on the list at the same time. This is generally not a good idea because the for loop uses an iterator to go through the items in the list, and modifying the list while you're iterating over it can cause the iterator to become confused a...
[ 3, 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074671420_python_python_3.x.txt
Q: Count of distinct values in pandas column which has list of values I have a dataframe column which contains lists of values. I am interested in getting the count of each distinct value inside the list across the column using python. A: To visualize it: import seaborn as sns sns.countplot(x='ColumnName',data=df) ...
Count of distinct values in pandas column which has list of values
I have a dataframe column which contains lists of values. I am interested in getting the count of each distinct value inside the list across the column using python.
[ "To visualize it:\nimport seaborn as sns\nsns.countplot(x='ColumnName',data=df)\n\ntoo see counts normally:\ndf['ColumnName'].value_counts()\n\n" ]
[ 1 ]
[]
[]
[ "data_science", "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0074671443_data_science_dataframe_numpy_pandas_python.txt
Q: why my react hook(usestate) not rendering? i'm using django restframework for my server side, i have fetch my datas on ReactJS, set it using "setPosts", consoled my response and i am getting my require response but when i try to render it in my return() block. i am not getting the data. rather i am having a blank ...
why my react hook(usestate) not rendering?
i'm using django restframework for my server side, i have fetch my datas on ReactJS, set it using "setPosts", consoled my response and i am getting my require response but when i try to render it in my return() block. i am not getting the data. rather i am having a blank page. i am using a windows 11 and python 3.11.0 ...
[ "The issue here is with your map function. Try the following syntax:\n{ posts.map((post) => (\n <div className=\"music_container\" onClick={playPause} id=\"music_container\">\n <img id=\"music_image\" src={'http://127.0.0.1:8000'+post.image} />\n <button>\n <FontAwesomeIcon icon={icon} ...
[ 0 ]
[]
[]
[ "django_rest_framework", "python", "reactjs" ]
stackoverflow_0074671368_django_rest_framework_python_reactjs.txt
Q: counting occurrences between 1 and 10 of an array I have an initial_array with numbers between 10 and 1, in descending order. initial_array = np.array ([10,10,7,4,2]) I want an output_array which counts the number of occurrences between 1 and 10. output_array = [ 0 1 0 1 0 0 1 0 0 2] A: Here is one possible so...
counting occurrences between 1 and 10 of an array
I have an initial_array with numbers between 10 and 1, in descending order. initial_array = np.array ([10,10,7,4,2]) I want an output_array which counts the number of occurrences between 1 and 10. output_array = [ 0 1 0 1 0 0 1 0 0 2]
[ "Here is one possible solution using the np.bincount function:\nimport numpy as np\n\n# create initial array with numbers between 10 and 1, in descending order\ninitial_array = np.array([10, 10, 7, 4, 2])\n\n# create output array that counts the number of occurrences between 1 and 10\noutput_array = np.bincount(ini...
[ 2 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0074671493_arrays_python.txt
Q: How do i put numpy.float64 data into dataframe? Im having 5 differents dataframes with values like this: tanggal komoditas harga 1 Beras Sembako 12000 2 Beras Sembako 12000 ... Beras Sembako ... 31 Beras Sembako 11000 (the only difference between each dataframes is on the 'komoditas' columns values is having...
How do i put numpy.float64 data into dataframe?
Im having 5 differents dataframes with values like this: tanggal komoditas harga 1 Beras Sembako 12000 2 Beras Sembako 12000 ... Beras Sembako ... 31 Beras Sembako 11000 (the only difference between each dataframes is on the 'komoditas' columns values is having different names) Im using this loop to g...
[ "Mark Ransom pointed out the issue in a comment. The fix is to append mean to rata in the loop:\nrata = []\nfor z in dfs:\n for x in tanggal:\n mean = z.loc[z['tanggal'] == x, 'harga'].mean()\n rata.append(mean)\n\nAt this point, rata will be a list such that len(rata) == len(tanggal)*len(dfs) and ...
[ 0 ]
[]
[]
[ "arrays", "dataframe", "numpy", "pandas", "python" ]
stackoverflow_0074667526_arrays_dataframe_numpy_pandas_python.txt
Q: Python Azure Can't Create Blob Container: This request is not authorized to perform this operation I'm trying to create a blob container within a Azure storage account with Azure's python API. def create_storage_container(storageAccountName: str, containerName: str): print(f"Creating storage container '{contai...
Python Azure Can't Create Blob Container: This request is not authorized to perform this operation
I'm trying to create a blob container within a Azure storage account with Azure's python API. def create_storage_container(storageAccountName: str, containerName: str): print(f"Creating storage container '{containerName}' in storage account '{storageAccountName}'") credentials = DefaultAzureCredential() url...
[ "Check the RBAC roles your user is assigned to for the storage account. The default ones don’t always enable you to view data and sounds like it’s causing your problems.\n" ]
[ 0 ]
[]
[]
[ "azure", "azure_python_sdk", "python" ]
stackoverflow_0074670530_azure_azure_python_sdk_python.txt
Q: Python code to do breadth-first discovery of a non-binary tree My problem: I have a known root node that I'm starting with and a specific other target node that I'm trying to find the shortest path to. I'm trying to write Python code to implement the Iterative Deepening Breadth-First Search algo, up to some max de...
Python code to do breadth-first discovery of a non-binary tree
My problem: I have a known root node that I'm starting with and a specific other target node that I'm trying to find the shortest path to. I'm trying to write Python code to implement the Iterative Deepening Breadth-First Search algo, up to some max depth (say, 5 vertices). However, there are two features that (I belie...
[ "You're basically looking for the Dijkstra algorithm. Dijkstra's algorithm adapts Breadth First Search to let you find the shortest path to your target. In order to retrieve the shortest path from the origin to a node, all that needs to be stored is the parent for each node discovered\nLet's say this is your tree n...
[ 1, 0 ]
[]
[]
[ "breadth_first_search", "graph_theory", "python", "tree" ]
stackoverflow_0074669889_breadth_first_search_graph_theory_python_tree.txt
Q: How to avoid Segmentation fault in pycocotools during decoding of RLE Here is a sample of decoding corrupted RLE: from pycocotools import mask # pycocotools version is 2.0.2 mask.decode({'size': [1024, 1024], 'counts': "OeSOk0[l0VOaSOn0kh0cNmYO'"}) As result it fails with Segmentation fault (core dumped) It loo...
How to avoid Segmentation fault in pycocotools during decoding of RLE
Here is a sample of decoding corrupted RLE: from pycocotools import mask # pycocotools version is 2.0.2 mask.decode({'size': [1024, 1024], 'counts': "OeSOk0[l0VOaSOn0kh0cNmYO'"}) As result it fails with Segmentation fault (core dumped) It looks like this: Python 3.6.15 (default) [GCC 9.4.0] on linux Type "help", "c...
[ "This issue is solved by updating pycocotools to version 2.0.5\n" ]
[ 0 ]
[]
[]
[ "pycocotools", "python", "rle" ]
stackoverflow_0073491138_pycocotools_python_rle.txt
Q: Why is my else clause not working in Django? I'm trying to create a search error for my ecommerce website. When a user inputs a search that is not in the database, it should return the search error page. Though it seems my else clause isn't working. I tried putting the else clause in the search.html page, but it k...
Why is my else clause not working in Django?
I'm trying to create a search error for my ecommerce website. When a user inputs a search that is not in the database, it should return the search error page. Though it seems my else clause isn't working. I tried putting the else clause in the search.html page, but it keeps giving me errors and it seems when I try to f...
[ "I think you want to check if products = Product.objects.filter(title__icontains=searched) is returning results instead of checking if \"searched\" is in the GET arguments.\nTo check if the database returned results you can you exists()\nhttps://docs.djangoproject.com/en/4.1/ref/models/querysets/#django.db.models.q...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074671375_django_python.txt
Q: Apache Beam Python DoFn process method and keyword arguments I am using Apache Beam SDK 2.43.0 with Python 3.8 and I am seeing some behaviour in the example below that I do not understand. If I run the snippet as given, I get the error: ... File "apache_beam\runners\common.py", line 983, in apache_beam.runners...
Apache Beam Python DoFn process method and keyword arguments
I am using Apache Beam SDK 2.43.0 with Python 3.8 and I am seeing some behaviour in the example below that I do not understand. If I run the snippet as given, I get the error: ... File "apache_beam\runners\common.py", line 983, in apache_beam.runners.common.PerWindowInvoker._invoke_process_per_window TypeError: pro...
[ "From what I understood, the behaviour is if you have only the side input parameter, you can pass it with a keyword argument or positional argument, but if you have multiple parameters, you have to use positional arguments :\n\nOnly side input argument :\n\ndef test_side_input(self):\n import apache_beam as...
[ 1 ]
[]
[]
[ "apache_beam", "parameter_passing", "python" ]
stackoverflow_0074670833_apache_beam_parameter_passing_python.txt
Q: doubling object in Python how do I double the object side by side? print(" *\n * *\n * *\n * *\n*** ***\n * *\n * *\n *****" *2) this code puts the objects one below another, how do i do that it prints it besides? A: You could try something like that: obj = " *\n * *\n * *\n * *...
doubling object in Python
how do I double the object side by side? print(" *\n * *\n * *\n * *\n*** ***\n * *\n * *\n *****" *2) this code puts the objects one below another, how do i do that it prints it besides?
[ "You could try something like that:\nobj = \" *\\n * *\\n * *\\n * *\\n*** ***\\n * *\\n * *\\n *****\"\n\nlines = obj.split('\\n')\nspace = len(max(lines, key=len)) + 3\n\nfor line in lines:\n print(line + \" \"* (space - len(line)) + line)\n\n", "Use a multiline string for your image, it...
[ 2, 1, 0 ]
[ "To print the object side by side, you can use the join() method. The join() method takes a list of strings and concatenates them together, using the string on which the method is called as a separator.\nFor example, you can use the following code to print the object side by side:\nobj = \" *\\n * \\n * \\n * \\n *...
[ -4 ]
[ "python" ]
stackoverflow_0074671391_python.txt
Q: Python can't access global variable modified in a loop in another loop because of threading I'm currently working on a small project with the OpenWeatherMap API and used threading for the first time. I don't know if this is the best "solution" to my code, but the rest of my project is working fine and I'm having o...
Python can't access global variable modified in a loop in another loop because of threading
I'm currently working on a small project with the OpenWeatherMap API and used threading for the first time. I don't know if this is the best "solution" to my code, but the rest of my project is working fine and I'm having only this one last issue. It seems like it's coming from the way the threading is handled, that th...
[ "It sounds like the variable desc is not defined in the other function. You can fix this by making desc a global variable that can be accessed by both functions. You can do this by adding the global keyword before the variable name in both functions, like this:\ndef weather():\n global desc\n # [code for the API ...
[ 0 ]
[]
[]
[ "multithreading", "python", "python_multithreading" ]
stackoverflow_0074671542_multithreading_python_python_multithreading.txt
Q: Django AWS S3 media files Working with Django, I am trying to use AWS S3 storage only for uploading and reading files which is working well at MEDIA_URL but the problem when using AWS S3 is that somehow I am losing reference to STATIC_URL where CSS and javascript files are I only want MEDIA_URL pointing to S3 and...
Django AWS S3 media files
Working with Django, I am trying to use AWS S3 storage only for uploading and reading files which is working well at MEDIA_URL but the problem when using AWS S3 is that somehow I am losing reference to STATIC_URL where CSS and javascript files are I only want MEDIA_URL pointing to S3 and keep my STATIC_URL away from A...
[ "Change STATIC_URL to \"STATIC_ROOT = os.path.join(BASE_DIR,'static')\". Could use decouple to hide those variables too.\n" ]
[ 0 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "django", "python" ]
stackoverflow_0024734733_amazon_s3_amazon_web_services_django_python.txt
Q: Handle Google authentication in FastAPI I am trying to implement a Google authentication on a FastAPI application. I have a local register and login system with JWT that works perfectly, but the 'get_current_user' method depends on the oauth scheme for the local authentication: async def get_current_user(token: st...
Handle Google authentication in FastAPI
I am trying to implement a Google authentication on a FastAPI application. I have a local register and login system with JWT that works perfectly, but the 'get_current_user' method depends on the oauth scheme for the local authentication: async def get_current_user(token: str = Depends(oauth2_scheme)): credentials_exce...
[ "from fastapi import Request, HTTPException\nfrom fastapi.security import HTTPBearer, HTTPAuthorizationCredentials\n\n\n\n\nclass JWTBearer(HTTPBearer):\n def __init__(self, auto_error: bool = True):\n super(JWTBearer, self).__init__(auto_error=auto_error)\n\n async def __call__(self, request: Request)...
[ 0 ]
[]
[]
[ "authentication", "fastapi", "oauth_2.0", "python" ]
stackoverflow_0073945475_authentication_fastapi_oauth_2.0_python.txt
Q: Grade computing program I am learning python. The question is "Write a grade program using a function called computegrade that takes a score as its parameter and returns a grade as a string." # Score Grade #>= 0.9 A #>= 0.8 B #>= 0.7 C #>= 0.6 D # < 0.6 F How do I get the grades when I run t...
Grade computing program
I am learning python. The question is "Write a grade program using a function called computegrade that takes a score as its parameter and returns a grade as a string." # Score Grade #>= 0.9 A #>= 0.8 B #>= 0.7 C #>= 0.6 D # < 0.6 F How do I get the grades when I run this program? As I am not assi...
[ "You're not seeing the grades because you're not telling python to run computegrade. If you do\ntry:\n score = float(score)\n computegrade()\n\nIt'll be done with.\nSome observations about the computegrade method. I advise you to make it accept score as an argument\ndef computegrade(score):\n # grade calcu...
[ 0, 0, 0 ]
[ "You aren’t calling the function; you have told Python what the function is, but not called it. \nWhat you need to do is \nscore = float(score) \ngrade = computegrade()\nprint(‘Score :’, score,’ Grade :’, grade)\n\nIt is better practice to define your function so that it takes a parameter ;\ndef computegrade( score...
[ -1, -1 ]
[ "python" ]
stackoverflow_0057454202_python.txt
Q: pulp constraint: exactly N in a category, up to X of a second choice, same category I have a problem I'm trying to solve for where I want N players from one team, and up to X players from a second team, but I don't particularly care which team fills those constraints. For example, if N=5 and X=2, I could have 5 fr...
pulp constraint: exactly N in a category, up to X of a second choice, same category
I have a problem I'm trying to solve for where I want N players from one team, and up to X players from a second team, but I don't particularly care which team fills those constraints. For example, if N=5 and X=2, I could have 5 from one team and up to 2 from a second, different, team. How would I write such a constrai...
[ "Here's how I would attack this... In pseudocode....\n\nmake a set of teams that you can use to index a couple of new variables.\n\nMake subsets of your players grouped by team, or use pandas data frame filters to limit summations of players to the team of interest.\n\nMake 2 new variables, that are binary \"indic...
[ 1 ]
[]
[]
[ "constraints", "pulp", "python" ]
stackoverflow_0074670229_constraints_pulp_python.txt
Q: Error in converting torch tensor to numpy.ndarray var1 = tensor([[[[0., 1., 1., ..., 1., 0., 0.], [0., 0., 1., ..., 0., 0., 0.], [0., 0., 0., ..., 0., 0., 1.], ..., [0., 0., 0., ..., 1., 1., 1.], [0., 0., 0., ..., 1., 1., 1.], [0., 0., 0., ..., 1., ...
Error in converting torch tensor to numpy.ndarray
var1 = tensor([[[[0., 1., 1., ..., 1., 0., 0.], [0., 0., 1., ..., 0., 0., 0.], [0., 0., 0., ..., 0., 0., 1.], ..., [0., 0., 0., ..., 1., 1., 1.], [0., 0., 0., ..., 1., 1., 1.], [0., 0., 0., ..., 1., 1., 1.]]]]) print(var1.size()) print(type(var1)) print...
[ "As hpaulj hinted at in a comment, var1.argmax(dim=1) will result in a zero tensor because you have var1.size(1) == 1.\n", "The error seems to occur when using argmax() on the tensor. The argmax() function returns the index of the maximum value of a tensor along a given dimension. In your code, you are using argm...
[ 0, 0 ]
[]
[]
[ "machine_learning", "numpy", "python", "pytorch", "tensor" ]
stackoverflow_0074669588_machine_learning_numpy_python_pytorch_tensor.txt
Q: How do I run python cgi script on apache2 server on Ubuntu 16.04? I am a newbie so I saw some tutorials. I have a python script as first.py #!/usr/bin/python3 print "Content-type: text/html\n" print "Hello, world!" I have multiple versions of python on my computer. I couldn't figure out my cgi enabled directory so...
How do I run python cgi script on apache2 server on Ubuntu 16.04?
I am a newbie so I saw some tutorials. I have a python script as first.py #!/usr/bin/python3 print "Content-type: text/html\n" print "Hello, world!" I have multiple versions of python on my computer. I couldn't figure out my cgi enabled directory so I pasted this code at three places /usr/lib/cgi-bin/first.py /usr/li...
[ "To python cgi script on apache2 server on Ubuntu(Tested on Ubuntu 20.04) from scratch, Follow these steps(Expects python is installed and works perfectly).\n\nInstall apache2 sever.\nsudo apt install apache2\n\n\nEnable CGI module.\nsudo a2enmod cgi\n\n\n\n\nHere we set /var/www/cgi-bin/ as cgi-bin directory. If y...
[ 7, 4, 0, 0 ]
[]
[]
[ "apache2", "cgi", "python", "server_side_scripting", "ubuntu" ]
stackoverflow_0044871139_apache2_cgi_python_server_side_scripting_ubuntu.txt
Q: Pycharm how to switch back to English? I have been using Pycharm in English but today when I opened it, its interface got partially translated to Chinese, totally unexpected and unwanted. How can I switch back to English without reinstalling Pycharm? Thanks! A: go for settings and make it as default settings,co...
Pycharm how to switch back to English?
I have been using Pycharm in English but today when I opened it, its interface got partially translated to Chinese, totally unexpected and unwanted. How can I switch back to English without reinstalling Pycharm? Thanks!
[ "go for settings and make it as default settings,consider the below image for the referance,count the row and select ok\n", "New version of pycharm let you unselect the Chinese interface and back to English interface.\n" ]
[ 2, 0 ]
[]
[]
[ "internationalization", "locale", "pycharm", "python", "user_interface" ]
stackoverflow_0047129007_internationalization_locale_pycharm_python_user_interface.txt
Q: SPARQL filter by date for multiple predicates parameters with same subject I would like to select the car brands (filter contains prefix "dbr:") where schema:Motor and filter schema:dateManufactured > year 2000. This is the source data (at the bottom you will find my query). As per RedCrusaderJr answer, we got now...
SPARQL filter by date for multiple predicates parameters with same subject
I would like to select the car brands (filter contains prefix "dbr:") where schema:Motor and filter schema:dateManufactured > year 2000. This is the source data (at the bottom you will find my query). As per RedCrusaderJr answer, we got now the brands but I don't know how to specify the query to filter the date of manu...
[ "For the follow up on the original question, if I understand you correctly, you want all URIs with a specific prefix, which you'd get with this query:\nSELECT DISTINCT ?o\n{ \n ?s ?p ?o\n FILTER CONTAINS(str(?o), \"http://dbpedia.org/resource/\")\n}\n\nFor your data set you'd get these URIs:\ndbpedia:Ford...
[ 0 ]
[]
[]
[ "python", "rdf", "schema", "sparql" ]
stackoverflow_0074666967_python_rdf_schema_sparql.txt
Q: Inserting alpha value to a 4-dimentsional RGB numpy array Following this tutorial, I am trying to build a color cube in matplotlib. spatialAxes = [self.step, self.step, self.step] r, g, b= np.indices((self.step+1, self.step+1, self.step+1)) / 16.0 rc = self.midpoints(r) gc = self.mi...
Inserting alpha value to a 4-dimentsional RGB numpy array
Following this tutorial, I am trying to build a color cube in matplotlib. spatialAxes = [self.step, self.step, self.step] r, g, b= np.indices((self.step+1, self.step+1, self.step+1)) / 16.0 rc = self.midpoints(r) gc = self.midpoints(g) bc = self.midpoints(b) cube = np.on...
[ "You can make colors an array with a forth component like this:\n# combine the color components\ncolors = np.zeros(sphere.shape + (4, ))\ncolors[..., 0] = rc\ncolors[..., 1] = gc\ncolors[..., 2] = bc\ncolors[..., 3] = 0.2 # opacity (alpha)\n\nBTW, I (half unconsciously) used the matplotlib example that you linked...
[ 1 ]
[]
[]
[ "matplotlib", "numpy", "python" ]
stackoverflow_0074671536_matplotlib_numpy_python.txt
Q: I need help regarding a python error: _tkinter.TclError: bitmap "class.ico" not defined I wanted to create an image classification app in python as a university project, but I get the error you can see on the pic below: Error message: Error_image I have 2 python files a teach.py, which teaches the pictures to the ...
I need help regarding a python error: _tkinter.TclError: bitmap "class.ico" not defined
I wanted to create an image classification app in python as a university project, but I get the error you can see on the pic below: Error message: Error_image I have 2 python files a teach.py, which teaches the pictures to the algorithm and saves it and a main.py which loads the saved model and a gui to uplad and predi...
[ "It looks like you are trying to use a bitmap image with the Tkinter library in Python, but the image you are trying to use has not been defined. To fix this error, you need to make sure that the bitmap image has been defined before you try to use it. This can be done by using the BitmapImage class in Tkinter to cr...
[ 0 ]
[]
[]
[ "keras", "machine_learning", "python", "tensorflow", "tkinter" ]
stackoverflow_0074670274_keras_machine_learning_python_tensorflow_tkinter.txt
Q: How do I decompose() a reoccurring row in a table that I find located in an html page? The row is a duplicate of the header row. The row occurs over and over again randomly, and I do not want it in the data set (naturally). I think the HTML page has it there to remind the viewer what column attributes they are loo...
How do I decompose() a reoccurring row in a table that I find located in an html page?
The row is a duplicate of the header row. The row occurs over and over again randomly, and I do not want it in the data set (naturally). I think the HTML page has it there to remind the viewer what column attributes they are looking at as they scroll down. Below is a sample of one of the row elements I want delete: <tr...
[ "It is possible to create a loop that iterates through each row in an HTML table and delete a row if the first cell in the row matches a certain value. This can be done using a combination of the HTML DOM (Document Object Model) and JavaScript.\nFirst, you will need to use the getElementsByTagName method to retriev...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074671640_python.txt
Q: ValueError: non-broadcastable output operand with shape (1,) doesn't match the broadcast shape (1,15) after running this code I keep getting the same error: note:(the data is in excel file (Heights : 16 column) and (Wights:16 column) I tried to change the epochs_num and it keeps giving the same problem... import p...
ValueError: non-broadcastable output operand with shape (1,) doesn't match the broadcast shape (1,15)
after running this code I keep getting the same error: note:(the data is in excel file (Heights : 16 column) and (Wights:16 column) I tried to change the epochs_num and it keeps giving the same problem... import pandas as pd import matplotlib.pyplot as plt import numpy as np # Load the dataset data = pd.read_csv('heigh...
[ "I can reproduce the error message with\nIn [5]: x=np.array([1])\n\nIn [6]: x+=np.ones((1,5),int)\n---------------------------------------------------------------------------\nValueError Traceback (most recent call last)\nInput In [6], in <cell line: 1>()\n----> 1 x+=np.ones((1,5),int...
[ 0, 0 ]
[]
[]
[ "linear_regression", "numpy", "pandas", "python" ]
stackoverflow_0074658165_linear_regression_numpy_pandas_python.txt
Q: I'm wondering why I'm getting a TypeError: argument of type 'int' is not iterable I'm trying to make a list of names based off the last number in the values list. The new list will be ordered based on highest number to lowest number but is a list of the names. folks = {'Leia': [28, 'F', 'W', False, True, 'Unemploy...
I'm wondering why I'm getting a TypeError: argument of type 'int' is not iterable
I'm trying to make a list of names based off the last number in the values list. The new list will be ordered based on highest number to lowest number but is a list of the names. folks = {'Leia': [28, 'F', 'W', False, True, 'Unemployed',1], 'Junipero': [15, 'M', 'E', False, False, 'Teacher', 0.2115833605402659...
[ "I would use the key argument to the sorted function\nsorted(folks, key=lambda x: folks[x][-1])[::-1]\n\n\nsorted pulls the keys out of the dictionary\nkey=lambda x: folks[x][-1] determines how to sort those keys\n[::-1] reverses the list.\n\nI get:\n['Leia',\n 'Sunita',\n 'Luitgard',\n 'Gorou',\n 'Issur',\n # ... ...
[ 1, 0 ]
[]
[]
[ "dictionary", "list", "python", "typeerror" ]
stackoverflow_0074671633_dictionary_list_python_typeerror.txt
Q: What is wrong with my code? I am a newbie and I don't know why it isn't working. (Python) Sorry, I've only been using python for about an hour, I'm using PyCharm if that has to do with the problem, I don't think it does though. Here is my code: userAge = input("Hi, how old are you?\n") longRussiaString = ( "W...
What is wrong with my code? I am a newbie and I don't know why it isn't working. (Python)
Sorry, I've only been using python for about an hour, I'm using PyCharm if that has to do with the problem, I don't think it does though. Here is my code: userAge = input("Hi, how old are you?\n") longRussiaString = ( "When will you guys stop telling me about how you had to walk uphill both ways for 10 miles to" ...
[ "It seems you're looking to see if a number occurs in a range. This can be accomplished very directly in Python. Just remember that the end of the range is exclusive: 0 to 5 is covered by range(0, 6).\n>>> n = 16\n>>> n in range(0, 17)\nTrue\n>>> n in range(0, 6)\nFalse\n>>> n not in range(0, 6)\nTrue\n>>>\n\n", ...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074671685_python.txt
Q: My Python Recursive Function is returning None I made a function that is being called recursively, and the condition for it to keep being called is a user input. The recursion is working but the final value of the variable is being returned as None. I am a beginner at Python and i am trying to learn Functions and ...
My Python Recursive Function is returning None
I made a function that is being called recursively, and the condition for it to keep being called is a user input. The recursion is working but the final value of the variable is being returned as None. I am a beginner at Python and i am trying to learn Functions and Recursion before going to Classes, OOP, Wrappers, et...
[ "The problem is that when the case variable is equal to 0, the return valor statement is being executed within the switch() function, but this function is being called recursively so the value of valor is not being returned to the caller.\nTo fix this, you can add another return statement at the end of the switch()...
[ 1, 0, 0 ]
[]
[]
[ "function", "python", "python_3.x", "recursion" ]
stackoverflow_0074671577_function_python_python_3.x_recursion.txt
Q: (Python) What is wrong in my code causing my program to crash index error Program will run the first time through, but in the second loop it will sometimes crash. It was noted to me that it may be in regard to the toppers line, where a topper can be selected. Error: "IndexError: list index out of range" import ran...
(Python) What is wrong in my code causing my program to crash index error
Program will run the first time through, but in the second loop it will sometimes crash. It was noted to me that it may be in regard to the toppers line, where a topper can be selected. Error: "IndexError: list index out of range" import random toppers = ['holographic', 'flakies', 'glitter', 'microshimmer'] def toppe...
[ "toppers = ['holographic', 'flakies', 'glitter', 'microshimmer']\n\nrandomTop = random.randint(1,4)\nprint('The topper you should use is ' + toppers[randomTop] + '.')\n\ntoppers is a list with four items. Python lists are indexed starting at zero, so the valid indexes are 0-3.\nBut you're picking a random number f...
[ 1 ]
[]
[]
[ "index_error", "python" ]
stackoverflow_0074671695_index_error_python.txt
Q: How do I make add the input parts into the loop like the menu? The part of the code that ask for the length of the list and then the actual numbers the users want to use needs to be looped into the program like the menu is looped in. So that once it runs and the program is fulfilled it can loop again. However, the...
How do I make add the input parts into the loop like the menu?
The part of the code that ask for the length of the list and then the actual numbers the users want to use needs to be looped into the program like the menu is looped in. So that once it runs and the program is fulfilled it can loop again. However, the program needs to completely end once the number -1000 is entered or...
[ "See comments in line.\nimport sys # will be used to exit the game.\n\nnumbersEntered = [] # Accumulate the numbers provided by the user\n\n\n# Since I see you are familiar with functions, use a function to end\n\ndef quit_game():\n print('Quit Game')\n sys.exit()\n\n\ndef menu():\n print(\"[A] Smallest\...
[ 0 ]
[]
[]
[ "arrays", "nested_loops", "python", "while_loop" ]
stackoverflow_0074671052_arrays_nested_loops_python_while_loop.txt
Q: How can I receive data that someone is sending me through a HTTP GET request (data encoded in the path or query string parameters) I will be receiving data shared via "a HTTP (or HTTPS) GET request" every five minutes, so I am developing a flask server to 'listen' for this data. I understand from trawling google t...
How can I receive data that someone is sending me through a HTTP GET request (data encoded in the path or query string parameters)
I will be receiving data shared via "a HTTP (or HTTPS) GET request" every five minutes, so I am developing a flask server to 'listen' for this data. I understand from trawling google that this is an uncommon way to share data, and I haven't been able to find documentation on how to ingest this data. Any nudges would be...
[ "Here is one way to accept the string and assign it to the receivedstring variable in your Flask server:\nfrom flask import Flask, request, abort\n\napp = Flask(__name__)\n\n@app.route('/webhook', methods=['GET'])\ndef webhook():\n if request.method == 'GET':\n receivedstring = request.args.get('Date_Even...
[ 1 ]
[]
[]
[ "flask", "python", "python_requests" ]
stackoverflow_0074671667_flask_python_python_requests.txt
Q: Bag of words process with comments data? I have a training set "x" containing an array, where each list within the array refers to the words of a comment. So if I run: len(x)" returns 8000 In particular, I want to choose the common tokens in at least 1% of the comments and then count the number of times each of ...
Bag of words process with comments data?
I have a training set "x" containing an array, where each list within the array refers to the words of a comment. So if I run: len(x)" returns 8000 In particular, I want to choose the common tokens in at least 1% of the comments and then count the number of times each of those tokens appears in each review and genera...
[ "To create a list of tokens that appear in at least 1% of the reviews, you can use a dictionary to count the number of times each token appears in the training set, and then filter the dictionary to only include tokens that appear in at least 1% of the reviews.\nHere's an example of how you could do this:\n# First,...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074671742_python.txt
Q: FileNotFoundError: [Errno 2] No such file or directory: '1.pdf' So I was making a PDF Merger using Python as I found it to be a good project for a beginner like me. I started off with using PyPDF4 and after all the hard work (not that hard) had been done I ran the program only to be greeted by "FileNotFoundError: ...
FileNotFoundError: [Errno 2] No such file or directory: '1.pdf'
So I was making a PDF Merger using Python as I found it to be a good project for a beginner like me. I started off with using PyPDF4 and after all the hard work (not that hard) had been done I ran the program only to be greeted by "FileNotFoundError: [Errno 2] No such file or directory: '1.pdf'". First question up, it ...
[ "You have to pass complete(absolute) path along with file name to manager.append(files) at line#12. The directory you got at Ln#6 is used to retrieve the list of files, however you have not used this while appending the files at Ln#12\n", "@venkat is correct in his answer. manager.append(files) does not contain t...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0067101966_python.txt
Q: How do you provide an error when an invalid input is provided ie. (a color other than purple or sky blue) or a number while True: try: color1 = str(input("What should the color of the broken window be, Purple or Sky Blue? > ")).lower().strip() color2 = str(input("What should the color of the br...
How do you provide an error when an invalid input is provided ie. (a color other than purple or sky blue) or a number
while True: try: color1 = str(input("What should the color of the broken window be, Purple or Sky Blue? > ")).lower().strip() color2 = str(input("What should the color of the broken window, white Yellow or Pink? > ")).lower().strip() user_info = {"color2": color1, "color2": color2,} exce...
[ "To check if the input is valid, you can use an if statement inside the try block to check if the input matches the expected colors. If the input is not valid, you can raise a ValueError to indicate that there was an issue with the input. Here is an example of how you can do this:\nwhile True:\n try:\n co...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074671719_python.txt
Q: python how can I convert shap values to probability increase/decreases? Issue on shap's repo: https://github.com/slundberg/shap/issues/2783 So currently, I know how to convert the base (expected) value from log odds to probability, with explainer = shap.TreeExplainer(model) shap_values = explainer.shap_values(X_tr...
python how can I convert shap values to probability increase/decreases?
Issue on shap's repo: https://github.com/slundberg/shap/issues/2783 So currently, I know how to convert the base (expected) value from log odds to probability, with explainer = shap.TreeExplainer(model) shap_values = explainer.shap_values(X_train) odds = np.exp(explainer.expected_value) odds / (1 + odds) This works fi...
[ "I think I may have found the answer, not sure if it's correct because the only way to compare is by visual approximation, but here is what I came up with. If anyone could try it out and determine is the calculation is off, that would be amazing!\nFirst, we have to create a helper function to convert log odds to pr...
[ 0 ]
[]
[]
[ "machine_learning", "math", "probability", "python", "shap" ]
stackoverflow_0074664259_machine_learning_math_probability_python_shap.txt
Q: python FastAPI websocket, Popen - print device stdout works, but stdout to websocket client doesn't I have a websocket server and a js/html client. When I click a button on the client, it invokes a shell command on the server. I use Popen to call the command cat /dev/ttyUSB0 to read the content of a device which i...
python FastAPI websocket, Popen - print device stdout works, but stdout to websocket client doesn't
I have a websocket server and a js/html client. When I click a button on the client, it invokes a shell command on the server. I use Popen to call the command cat /dev/ttyUSB0 to read the content of a device which is constantly changing. When I print the output on terminal it works, but when I send the output through t...
[]
[]
[ "I think the issue is that your websocket server is not handling the client's messages properly. When the client sends a message, the server receives it and parses it as JSON. If the type property of the message is \"monitor\", the server starts running the run_command function. However, your run_command function d...
[ -1 ]
[ "fastapi", "popen", "python", "stdout", "websocket" ]
stackoverflow_0074671794_fastapi_popen_python_stdout_websocket.txt
Q: what is the meaning of the line bboxes= utils.format_boxes(bboxes,height,weight) I'm trying for object tracking using webcam using yolov4. I want to know the meaning of this line -> bboxes = utils.format_boxes(bboxes, original_h, original_w). I'm using https://github.com/theAIGuysCode/yolov4-deepsort.git reposit...
what is the meaning of the line bboxes= utils.format_boxes(bboxes,height,weight)
I'm trying for object tracking using webcam using yolov4. I want to know the meaning of this line -> bboxes = utils.format_boxes(bboxes, original_h, original_w). I'm using https://github.com/theAIGuysCode/yolov4-deepsort.git repository for cloning. One can find the above line in object_tracer.py file. - line 151. # f...
[ "The answer is literally in the comment at the first line of the code you pasted.\nThis method translates bounding boxes in normalized coordinates (xmin, ymin, xmax, y max) to not normalized coordinates (xmin, ymin, width, height).\nCoordinates are usually expressed in pixels, which is the not normalized form. Norm...
[ 0 ]
[]
[]
[ "python", "yolov4" ]
stackoverflow_0074645659_python_yolov4.txt
Q: RuntimeError: Sizes of tensors must match except in dimension 0. Expected size 30 but got size 31 for tensor number 1 in the list Here's the part of my code. from transformers import BertTokenizer,BertForSequenceClassification,AdamW tokenizer = BertTokenizer.from_pretrained('bert-base-uncased',do_lower_case = True...
RuntimeError: Sizes of tensors must match except in dimension 0. Expected size 30 but got size 31 for tensor number 1 in the list
Here's the part of my code. from transformers import BertTokenizer,BertForSequenceClassification,AdamW tokenizer = BertTokenizer.from_pretrained('bert-base-uncased',do_lower_case = True,truncation=True) input_ids = [] attention_mask = [] for i in text: encoded_data = tokenizer.encode_plus( i, add_special_t...
[ "The error message says that you are trying to concatenate tensors of different sizes along the 0th dimension, which is not allowed. This is likely happening because you are not specifying the pad_to_max_length argument when calling tokenizer.encode_plus(), which means that the length of the encoded tensors will no...
[ 1 ]
[]
[]
[ "bert_language_model", "machine_learning", "python", "sentiment_analysis", "torch" ]
stackoverflow_0074668301_bert_language_model_machine_learning_python_sentiment_analysis_torch.txt
Q: How do I change the variables inside of a python table? This is my table. playerdata = { 'Saves' : [{ 'name' : charactername, 'class' : playerclass, 'level' : level, 'race' : playerrace, 'Inventory' : [{ 'Slot 1' : 'Test', 'Slot 2' : 'Test', 'Slot 3' : 'Test' }], 'At...
How do I change the variables inside of a python table?
This is my table. playerdata = { 'Saves' : [{ 'name' : charactername, 'class' : playerclass, 'level' : level, 'race' : playerrace, 'Inventory' : [{ 'Slot 1' : 'Test', 'Slot 2' : 'Test', 'Slot 3' : 'Test' }], 'Attributes' : [{ 'Dexterity' : attDexterity, 'Stren...
[ "To update the value in the table when the variable charactername changes, you can use the following code:\n# Update the value of charactername in the table\nplayerdata['Saves'][0]['name'] = charactername\n\nThis code accesses the Saves key in the playerdata dictionary, then accesses the first element in the Saves ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074671769_python.txt
Q: Timeseries split datetime data type to seperate date and time columns I am importing a CSV file that contains a nonformatted dataset, the date and time are separated but the data type is an object, and the times' time zone is incorrect. The timezone of this original dataset is EET which is currently 7-hour differe...
Timeseries split datetime data type to seperate date and time columns
I am importing a CSV file that contains a nonformatted dataset, the date and time are separated but the data type is an object, and the times' time zone is incorrect. The timezone of this original dataset is EET which is currently 7-hour difference from eastern standard time, (sometimes it is 6 hours during daylight sa...
[ "sample:\ndata = {\n \"date\": [\"2022-12-02\"],\n \"time\": [\"23:55:00\"]\n}\ndf = pd.DataFrame(data)\n\ncode:\ndf[\"datetime\"] = (\n pd.to_datetime(df[\"date\"].str.cat(df[\"time\"], sep=\" \"))\n .dt.tz_localize(\"UTC\")\n .dt.tz_convert(\"US/Mountain\")\n .dt.tz_localize(None)\n)\ndf[\"date\...
[ 0 ]
[]
[]
[ "datetime", "pandas", "python", "time_series", "types" ]
stackoverflow_0074671714_datetime_pandas_python_time_series_types.txt
Q: How to order list of lists of strings by another list of lists of floats in Pandas I have a Pandas dataframe such that df['cname']: 0 [berkshire, hathaway] 1 [icbc] 2 [saudi, arabian, oil, company, saudi, aramco] 3 ...
How to order list of lists of strings by another list of lists of floats in Pandas
I have a Pandas dataframe such that df['cname']: 0 [berkshire, hathaway] 1 [icbc] 2 [saudi, arabian, oil, company, saudi, aramco] 3 [jpmorgan, chase] 4 [china, construction, bank] Name: tokenized_...
[ "To sort the list of tokens in f_sp['tokenized_company_name'] by the corresponding value in tf_sp['output_column'], you can use the zip function to combine the two columns and then sort the resulting list of tuples by the value of the second element in each tuple (which is the corresponding value from tf_sp['output...
[ 0, 0 ]
[]
[]
[ "nlp", "pandas", "python", "string", "token" ]
stackoverflow_0074671883_nlp_pandas_python_string_token.txt
Q: asyncg - transaction requirement I found in the asyncpg documentation that every call to сonnection.execute() or connection.fetch() should be wrapped in async with connection.transaction():. But in one of the repositories I saw the following code without wrapping it in a transaction: async def bench_asyncpg_con():...
asyncg - transaction requirement
I found in the asyncpg documentation that every call to сonnection.execute() or connection.fetch() should be wrapped in async with connection.transaction():. But in one of the repositories I saw the following code without wrapping it in a transaction: async def bench_asyncpg_con(): start = time.monotonic() for ...
[ "The reason why the code in your example doesn't have a transaction is because it's just fetching data from the database. There are no changes happening to the database (no udpates, no inserted data, no deleting of data, etc..) Quoted from asyncpg docs:\n\nWhen not in an explicit transaction block, any changes to t...
[ 1 ]
[]
[]
[ "asyncpg", "python" ]
stackoverflow_0071783811_asyncpg_python.txt
Q: How to replace a value in a matrix by index Let's say I have a 4X4 matrix containing value from 1 to 20. If I want the element at line 2 column 3 to be equal to 100, how can I do this ? A: First, import the numpy library: import numpy as np Then, create the matrix: matrix = np.array([[1,2,3], [4,5,6], [7,8,9]...
How to replace a value in a matrix by index
Let's say I have a 4X4 matrix containing value from 1 to 20. If I want the element at line 2 column 3 to be equal to 100, how can I do this ?
[ "First, import the numpy library:\n\nimport numpy as np\n\nThen, create the matrix:\n\nmatrix = np.array([[1,2,3], [4,5,6], [7,8,9]])\n\nFinally, use the index to replace the value:\n\nmatrix[1,2] = 10\nThe new matrix will be:\n\n[[ 1 2 3]\n [ 4 5 10]\n [ 7 8 9]]\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074671888_python.txt
Q: No module named 'Adafruit_GPIO' I am doing the project in this video (https://www.youtube.com/watch?v=9sb_zuHGmY4) with the OLED screen. The step by step guide I followed (https://www.the-diy-life.com/diy-raspberry-pi-4-desktop-case-with-oled-stats-display/) and I get this error: Traceback (most recent call last):...
No module named 'Adafruit_GPIO'
I am doing the project in this video (https://www.youtube.com/watch?v=9sb_zuHGmY4) with the OLED screen. The step by step guide I followed (https://www.the-diy-life.com/diy-raspberry-pi-4-desktop-case-with-oled-stats-display/) and I get this error: Traceback (most recent call last): File "stats.py", line 23, in <modu...
[ "When in doubt, take a look at the official docs! You're missing an old library.\nWhile you may be able to bring it in, the maintainers have actually deprecated it and suggest another https://github.com/adafruit/Adafruit_Python_GPIO\n\nThis library has been deprecated in favor of our python3 Blinka library. We have...
[ 0, 0 ]
[]
[]
[ "adafruit", "python", "raspberry_pi4" ]
stackoverflow_0065148950_adafruit_python_raspberry_pi4.txt
Q: AssertionError: Label class 15 exceeds nc=1 in data/coco128.yaml. Possible class labels are 0-0 I've been building the yolov5 environment and trying to run it for the last few days. I used the following code to test whether My setup was successful. python train.py --img 640 --data data/coco128.yaml --cfg models/yo...
AssertionError: Label class 15 exceeds nc=1 in data/coco128.yaml. Possible class labels are 0-0
I've been building the yolov5 environment and trying to run it for the last few days. I used the following code to test whether My setup was successful. python train.py --img 640 --data data/coco128.yaml --cfg models/yolov5s.yaml --weights weights/yolov5s.pt --batch-size 16 --epochs 100 And then it gave me the followi...
[ "I found this exact error too.\nIn your .txt files you've created for the annotations, there will be an integer number followed by four floats (ie, 13 0.3434 0.251 0.4364 0.34353) - something like that.\nThis error essentially articulates that your number of classes (ie, the number of different objects you're tryin...
[ 1, 0, 0 ]
[]
[]
[ "python", "yolov5" ]
stackoverflow_0063950508_python_yolov5.txt
Q: Django REST Framework - return a value from get_queryset? I am trying to return a value from get_queryset. def get_queryset(self): if self.request.user.is_superuser: return StockPriceModel.objects.order_by('ticker').distinct() elif not self.request.user.is_authenticated: print('in') p...
Django REST Framework - return a value from get_queryset?
I am trying to return a value from get_queryset. def get_queryset(self): if self.request.user.is_superuser: return StockPriceModel.objects.order_by('ticker').distinct() elif not self.request.user.is_authenticated: print('in') print(self.request.data) last_price = StockPriceModel.ob...
[ "Because, get_queryset() always return a queryset of objects or a list of objects.\nYou cannot return an object or a field from the get_queryset method.\nthe last_price value will be printed, but it is a field value and therefore the get_queryset method will not return it.\nWhen you add [0], it takes the first obje...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074657136_django_python.txt
Q: Getting field from another model into my custom serializer I am trying to get 'first_name' and 'last_name' field into my serializer that uses a model which has no user information: This is the serializers.py file: enter image description here This is the models.py file (from django-friendship model): enter image d...
Getting field from another model into my custom serializer
I am trying to get 'first_name' and 'last_name' field into my serializer that uses a model which has no user information: This is the serializers.py file: enter image description here This is the models.py file (from django-friendship model): enter image description here I am also attaching views.py: enter image descri...
[ "In this case I would make a serializer for the user and then use that in the FriendshipRequestSerializer.\nclass UserSerializer(serializers.ModelSerializer):\n \n class Meta:\n model = User\n fields = ('id', 'first_name', 'last_name',)\n\n\nclass FriendshipRequestSerialiser(serializers.ModelSer...
[ 0 ]
[]
[]
[ "django", "django_rest_framework", "python" ]
stackoverflow_0074671836_django_django_rest_framework_python.txt
Q: how to condition a url depending on the parameters in flask? I currently have my site like this: @main.route("/reports", methods=["GET", "POST"]) def reports(): return render_template( "template.html") I intend to add a new design and place it in the following way if in the url they add "/reports/1" or "/reports/...
how to condition a url depending on the parameters in flask?
I currently have my site like this: @main.route("/reports", methods=["GET", "POST"]) def reports(): return render_template( "template.html") I intend to add a new design and place it in the following way if in the url they add "/reports/1" or "/reports/0" direct them to a different template: @main.route("/reports/<int...
[ "http://127.0.0.1:8000/reportes looks like a typo (extra \"e\").\nAnyway you can add one more route to your function as follows:\n@main.route(\"/reports\", methods=[\"GET\", \"POST\"])\n@main.route(\"/reports/<int:ds>\", methods=[\"GET\", \"POST\"])\ndef reports(ds=1): # <-- provide here the default value you want...
[ 0 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0074670576_flask_python.txt
Q: The tkinter window of my rotating cube animation does not showing anyting from tkinter import * from math import * import time root = Tk() canvas = Canvas(root, width=500, height=500, bg='black') canvas.pack() class Cube: def __init__(self, canvas, x, y, size, colors): self.x = x self.y = y ...
The tkinter window of my rotating cube animation does not showing anyting
from tkinter import * from math import * import time root = Tk() canvas = Canvas(root, width=500, height=500, bg='black') canvas.pack() class Cube: def __init__(self, canvas, x, y, size, colors): self.x = x self.y = y self.size = size self.colors = colors self.canvas = canv...
[]
[]
[ "I don't think your looop works like you expect it to\nYou never exit the while loop to start the main loop.\ninstead you might wanna try something like this:\ndef update_cube():\n cube.rotate_y(0.01)\n cube.rotate_x(0.01)\n canvas.delete(\"all\")\n cube.draw()\n root.update()\n root.after(10, upd...
[ -1 ]
[ "python", "tkinter" ]
stackoverflow_0074671737_python_tkinter.txt
Q: I'm learning how to work with files in Python using Jupyter notebook. Why do I have to use open() each time to print what I'd like to? I tried: my_file = open("test.txt") for line in my_file: print("Here it says: " + line) lines = my_file.readlines() print(lines[1]) But the second print command did not p...
I'm learning how to work with files in Python using Jupyter notebook. Why do I have to use open() each time to print what I'd like to?
I tried: my_file = open("test.txt") for line in my_file: print("Here it says: " + line) lines = my_file.readlines() print(lines[1]) But the second print command did not print anything. then I tried: my_file = open("test.txt") for line in my_file: print("Here it says: " + line) my_file = open("test.tx...
[ "# See comments in line.\nfi = open(\"test.txt\", 'w')\nfor n in range(10):\n fi.write(str(n))\nfi.close()\n\nmy_file = open(\"test.txt\")\nfor line in my_file:\n print(\"Here it says: \" + line)\n# The file indicates there are no more lines by setting the EOF\n# End of file marker\nlines = my_file.readlines(...
[ 0 ]
[]
[]
[ "jupyter_notebook", "python" ]
stackoverflow_0074671890_jupyter_notebook_python.txt
Q: How can I make an int to add each value of the matrix and add 20% with input a = [ [200,300,5000,400],[554,500,1000,652],[800,500,650,800],[950,120,470,500],[500,600,2000,100]] for i in range(len(a)): for j in range(len(a[i])): print(a[i][j], end=' ') print() I am trying to increase each value by ...
How can I make an int to add each value of the matrix and add 20% with input
a = [ [200,300,5000,400],[554,500,1000,652],[800,500,650,800],[950,120,470,500],[500,600,2000,100]] for i in range(len(a)): for j in range(len(a[i])): print(a[i][j], end=' ') print() I am trying to increase each value by 20%, and then print the matrix with the increase, For example, this is the origin...
[ "This should work if you want to modify the original matrix; if not, Chris' answer is simpler.\nfor x in a:\n for i in range(len(x)):\n x[i] = int(x[i] * 1.2)\n\n", "You may wish to generate a new \"matrix\" with your adjusted values, in which case list comprehensions can be useful:\nb = [[int(y * 1.2) ...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074671824_python.txt
Q: How to extract the member from single-member set in python? I recently encountered a scenario in which if a set only contained a single element, I wanted to do something with that element. To get the element, I settled on this approach: element = list(myset)[0] But this isn't very satisfying, as it creates an un...
How to extract the member from single-member set in python?
I recently encountered a scenario in which if a set only contained a single element, I wanted to do something with that element. To get the element, I settled on this approach: element = list(myset)[0] But this isn't very satisfying, as it creates an unnecessary list. It could also be done with iteration, but iterat...
[ "Tuple unpacking works.\n(element,) = myset\n\n(By the way, python-dev has explored but rejected the addition of myset.get() to return an arbitrary element from a set. Discussion here, Guido van Rossum answers 1 and 2.)\nMy personal favorite for getting an arbitrary element is (when you have an unknown number, but ...
[ 129, 31, 25, 15, 2, 2, 0, 0 ]
[]
[]
[ "python", "set" ]
stackoverflow_0001619514_python_set.txt
Q: Parse date in pandas with unit='D' What is wrong with this? pd.to_datetime('2022-01-01',unit='D') If I do it without the unit pd.to_datetime('2022-01-01') no error is raised. However, insted of the standard unit ns I rather want D. A: There is a quite clear description and examples on the official documentaito...
Parse date in pandas with unit='D'
What is wrong with this? pd.to_datetime('2022-01-01',unit='D') If I do it without the unit pd.to_datetime('2022-01-01') no error is raised. However, insted of the standard unit ns I rather want D.
[ "There is a quite clear description and examples on the official documentaiton.\nLet's take an example from it:\npd.to_datetime([1, 2, 3], unit='D',\n origin=pd.Timestamp('1960-01-01'))\n\nOutput:\nDatetimeIndex(['1960-01-02', '1960-01-03', '1960-01-04'], dtype='datetime64[ns]', freq=None)\n\nWhat has...
[ 1 ]
[]
[]
[ "datetime", "pandas", "parsing", "python", "timestamp" ]
stackoverflow_0074671728_datetime_pandas_parsing_python_timestamp.txt
Q: Solving an ODE with a Time-Dependent Variable For the 2 systems of ODE, I am using RK4 to solve. From 0 <= t <= 30, b is a constant. But at t >= 30, b is a time-dependent variable where b = 1.2 * exp(-0.5 * (t - 30)). I tried to implement it, but there's an error saying setting an array element with a sequence. Ho...
Solving an ODE with a Time-Dependent Variable
For the 2 systems of ODE, I am using RK4 to solve. From 0 <= t <= 30, b is a constant. But at t >= 30, b is a time-dependent variable where b = 1.2 * exp(-0.5 * (t - 30)). I tried to implement it, but there's an error saying setting an array element with a sequence. How should I implement the time-variable? a = 0.05 b ...
[ "In the first code I use the integrator developed in scipy.integrate.solve_ivp from scipy.\nCode 1.\n##########################################\n# AUTHOR : CARLOS DUARDO DA SILVA LIMA #\n# DATE : 03/12/2022 #\n# LANGUAGE: python #\n# IDE : GOOGLE COLAB ...
[ 0 ]
[]
[]
[ "math", "ode", "python" ]
stackoverflow_0074647657_math_ode_python.txt
Q: Why my flask app can't handle more than one client? I created a simple flask application that needs authentication to have access to the data. When I run this application locally it works fine (accepts more than one client), however when I host the app on railway or heroku it can't handle more than one client. Ex:...
Why my flask app can't handle more than one client?
I created a simple flask application that needs authentication to have access to the data. When I run this application locally it works fine (accepts more than one client), however when I host the app on railway or heroku it can't handle more than one client. Ex: when I access the URL on a computer and log in, if I acc...
[ "As official Flask's documentation says, never run your application in production in dev mode (what app.run() actually is).\nPlease refer to this section if you are going to deploy in self-hosted machine: https://flask.palletsprojects.com/en/2.2.x/deploying/\nAnd if you are going to deploy to Heroku, you need to pr...
[ 0 ]
[]
[]
[ "flask", "gunicorn", "heroku", "python" ]
stackoverflow_0074671705_flask_gunicorn_heroku_python.txt
Q: Triangulation Plot python curved scattered data I'm trying to get a interpolated contour surface with triangulation from matplotlib. My data looks like a curve and I can't get rid of the data below the curve. I would like to have the outside datapoints as boundaries. I got the code from this tutorial import matplo...
Triangulation Plot python curved scattered data
I'm trying to get a interpolated contour surface with triangulation from matplotlib. My data looks like a curve and I can't get rid of the data below the curve. I would like to have the outside datapoints as boundaries. I got the code from this tutorial import matplotlib.tri as tri fig, (ax1, ax2) = plt.subplots(nrows=...
[ "I managed to find a way to not plot the triangles at the bottom by using the following code:\nxtri = x_after[triangles] - np.roll(x_after[triangles], 1, axis=1)\nytri = y_after[triangles] - np.roll(y_after[triangles], 1, axis=1)\nmaxi = np.max(np.sqrt(xtri**2 + ytri**2), axis=1)\nmax_radius = 4.5\ntriang.set_mask(...
[ 0, 0 ]
[]
[]
[ "interpolation", "matplotlib", "python", "triangulation" ]
stackoverflow_0074659764_interpolation_matplotlib_python_triangulation.txt
Q: How to solve the problem 'zsh: command not found: jupyter' I bought Macbook air M1, and I tried to install jupyter notebook with this code. pip3 install --upgrade pip pip3 install jupyter and I tried to open jupyter notebook with this code. jupyter notebook but, then, this code appeared. zsh: command not found:...
How to solve the problem 'zsh: command not found: jupyter'
I bought Macbook air M1, and I tried to install jupyter notebook with this code. pip3 install --upgrade pip pip3 install jupyter and I tried to open jupyter notebook with this code. jupyter notebook but, then, this code appeared. zsh: command not found: jupyter enter image description here
[ "First, you need to find where it was installed.\npip3 show jupyter | grep Location\n\nExample:\n$ pip3 show pip | grep Location\n\nLocation: /usr/lib/python3/dist-packages\n\nThen you need to ensure that the path you get is in your PATH.\nExample:\n$ export PATH=/usr/lib/python3/dist-packages:$PATH\n\n", "Try ad...
[ 6, 0 ]
[]
[]
[ "jupyter", "jupyter_notebook", "macos", "python" ]
stackoverflow_0069614802_jupyter_jupyter_notebook_macos_python.txt
Q: Difference between defining typing.Dict and dict? I am practicing using type hints in Python 3.5. One of my colleague uses typing.Dict: import typing def change_bandwidths(new_bandwidths: typing.Dict, user_id: int, user_name: str) -> bool: print(new_bandwidths, user...
Difference between defining typing.Dict and dict?
I am practicing using type hints in Python 3.5. One of my colleague uses typing.Dict: import typing def change_bandwidths(new_bandwidths: typing.Dict, user_id: int, user_name: str) -> bool: print(new_bandwidths, user_id, user_name) return False def my_change_bandw...
[ "There is no real difference between using a plain typing.Dict and dict, no.\nHowever, typing.Dict is a Generic type * that lets you specify the type of the keys and values too, making it more flexible:\ndef change_bandwidths(new_bandwidths: typing.Dict[str, str],\n user_id: int,\n ...
[ 285, 39, 11, 0 ]
[]
[]
[ "dictionary", "python", "python_typing", "type_hinting" ]
stackoverflow_0037087457_dictionary_python_python_typing_type_hinting.txt
Q: my raspberry pi pico oled display code is returning 'OSError: [Errno 5] EIO' I've been trying to use an ssd1306 oled display with a raspberry pi pico but every time I run the code it returns an error. I don't know what the error means and can't really find anything online for it. I was able to "fix" it yesterday b...
my raspberry pi pico oled display code is returning 'OSError: [Errno 5] EIO'
I've been trying to use an ssd1306 oled display with a raspberry pi pico but every time I run the code it returns an error. I don't know what the error means and can't really find anything online for it. I was able to "fix" it yesterday by changing the address in the library file it uses, but although it worked, the is...
[ "Thank you, odog, your error helped me track mine down. This simple example now works for me:\nfrom machine import Pin, I2C\nfrom ssd1306 import SSD1306_I2C\n\ni2c=I2C(0,sda=Pin(0), scl=Pin(1), freq=400000)\n\ndevices = i2c.scan()\ntry:\n oled = SSD1306_I2C(128, 64, i2c,addr=devices[0])\n oled.text(\"hello w...
[ 0 ]
[]
[]
[ "python", "raspberry_pi_pico", "thonny" ]
stackoverflow_0074659614_python_raspberry_pi_pico_thonny.txt