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: SyntaxError: invalid non-printable character U+0016. What is the cause? import discord from discord.ext import commands import secrets from secrets import TOKEN client = discord.Client() @client.event async def on_ready(): print("Bot is ready.") client.run(f"{TOKEN}") I'm using VSC and I just wrote this co...
SyntaxError: invalid non-printable character U+0016. What is the cause?
import discord from discord.ext import commands import secrets from secrets import TOKEN client = discord.Client() @client.event async def on_ready(): print("Bot is ready.") client.run(f"{TOKEN}") I'm using VSC and I just wrote this code into my main file. I'm not sure why but it keeps saying: File "<stdin>", l...
[ "Your Python file seems perfectly fine from a syntax point of view. This WebRepl has no problem parsing it: https://www.online-python.com/LE9maKwF8z . (It can't find discord, but that's fine and the syntax is ok).\nIt looks like a VSC problem. Try saving the file and run it with\npython3 main.py\n\nto validate that...
[ 0 ]
[]
[]
[ "discord", "discord.py", "python" ]
stackoverflow_0074586820_discord_discord.py_python.txt
Q: webbrowser.open(site) doesn't process korean characters I'm quite an infrequent coder, I hope my question won't be too obvious. I have this very simple code to open some websites based on string (open website for a specific word) which works on Windows but somehow doesn't on my new computer with Mac OS. The tricky...
webbrowser.open(site) doesn't process korean characters
I'm quite an infrequent coder, I hope my question won't be too obvious. I have this very simple code to open some websites based on string (open website for a specific word) which works on Windows but somehow doesn't on my new computer with Mac OS. The tricky part is that I'm using Korean alphabet (I learn this languag...
[ "I think the problem is that the word isn't getting properly URL-encoded (i.e. '가다' needs to be converted to '%EA%B0%80%EB%8B%A4' for use in a URL). Some browsers deal with this differently than others, and I think you're seeing a difference between the browser you use on Windows vs. on macOS. To encode it, you can...
[ 0, 0 ]
[]
[]
[ "macos", "python", "python_webbrowser" ]
stackoverflow_0074586320_macos_python_python_webbrowser.txt
Q: How to swap two elsticsearch indexes I want to implement cash for highly loaded elasticsearch-based search system. I want to store cash in special elastic index. The problem is in cache warm-up: once an hour my system needs to update cached results with the fresh ones. So, I'm creating a new empty index and fill i...
How to swap two elsticsearch indexes
I want to implement cash for highly loaded elasticsearch-based search system. I want to store cash in special elastic index. The problem is in cache warm-up: once an hour my system needs to update cached results with the fresh ones. So, I'm creating a new empty index and fill it with updated results, then I need to swa...
[ "For this kind of scenario you use something that is called \"index alias swapping\".\nYou have an alias that points to your current index, you fill a new index with the fresh records, and then you point this alias to the new index.\nSomething like this:\n\nCurrent index name is items-2022-11-26-001\nCreate alias i...
[ 1 ]
[]
[]
[ "elasticsearch", "full_text_search", "python" ]
stackoverflow_0074581027_elasticsearch_full_text_search_python.txt
Q: How can I iterate a list with repeated values? I'm having a problem in my code where I'm trying to check if (in my case) there is a review already created with that title from that reviewer. For that I'm doing: def review_result(self): print("Complete your review") title = input("Title of the paper: ") ...
How can I iterate a list with repeated values?
I'm having a problem in my code where I'm trying to check if (in my case) there is a review already created with that title from that reviewer. For that I'm doing: def review_result(self): print("Complete your review") title = input("Title of the paper: ") reviewer = input("Reviewer's name: ") for x in ...
[ "You can use enumerate:\nfor index, x in enumerate(self.__review):\n current_review = x\n next_review = self.__review[index + 1] # note that this will error when you reach the last item on the list, make sure you have handling for it!\n # more code\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074586958_python.txt
Q: How do I filter a dataframe based on complicated conditions? Right now my dataframes look like this (I simplified it cause the original has hundreds of rows) import pandas as pd Winner=[[1938,"Italy"],[1950,"Uruguay"],[2014,"Germany"]] df=pd.DataFrame(Winner, columns=['Year', 'Winner']) print(df) MatchB=[[1938,"...
How do I filter a dataframe based on complicated conditions?
Right now my dataframes look like this (I simplified it cause the original has hundreds of rows) import pandas as pd Winner=[[1938,"Italy"],[1950,"Uruguay"],[2014,"Germany"]] df=pd.DataFrame(Winner, columns=['Year', 'Winner']) print(df) MatchB=[[1938,"Germany",1.0],[1938,"Germany",2.0],[1938,"Brazil",1.0],[1950,"Ital...
[ "You can merge.\ndf = pd.merge(left=df, right=df2B, left_on=[\"Year\", \"Winner\"], right_on=[\"Year\", \"Away Team Name\"])\nprint(df)\n\nOutput:\n Year Winner Away Team Name Away Team Goals\n0 2014 Germany Germany 1.0\n\n" ]
[ 0 ]
[]
[]
[ "dataframe", "filter", "pandas", "python" ]
stackoverflow_0074586976_dataframe_filter_pandas_python.txt
Q: How would I get multiple Inputs from entry on a button press, Tkinter? I'm working on a project for a friend where I need to make 12 entries and have them saved as a xml file when I press the button, but I keep getting it to duplicate the input to the other boxes and only print it once. import tkinter as tk from t...
How would I get multiple Inputs from entry on a button press, Tkinter?
I'm working on a project for a friend where I need to make 12 entries and have them saved as a xml file when I press the button, but I keep getting it to duplicate the input to the other boxes and only print it once. import tkinter as tk from tkinter import * from tkinter.ttk import * # ...
[ "As mentioned in the comment in your question, your code with added stringvars and modified callback:\nimport tkinter as tk\nfrom tkinter import *\nfrom tkinter.ttk import *\n\n# GUI\n# ---------------------------------------------------------------\n#\n\n# Root Setup and size\nroot = ...
[ 0 ]
[]
[]
[ "python", "python_3.x", "tkinter" ]
stackoverflow_0074586821_python_python_3.x_tkinter.txt
Q: Why is this command not working? is it me or the code? When I try to use the command !addrole it is supposed to give me the role but the bot won't. import discord from discord.ext import commands client = commands.Bot(command_prefix='!',intents = intents) @client.command(pass_context=True) @commands.has_role("AD...
Why is this command not working? is it me or the code?
When I try to use the command !addrole it is supposed to give me the role but the bot won't. import discord from discord.ext import commands client = commands.Bot(command_prefix='!',intents = intents) @client.command(pass_context=True) @commands.has_role("ADMIN") async def addrole(ctx): member = ctx.message.aut...
[ "Seems like you are missing message intents.\nintents.messages = True\nclient = commands.Bot(command_prefix=\"!\", intents = intents)\n# ...\n\nFollow the instructions here to enable message intents like any other intent on the bot's developer portal:\nhttps://discordpy.readthedocs.io/en/stable/intents.html\n" ]
[ 1 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0074586797_discord.py_python.txt
Q: Network-X edge_betweeness_centrality function does not take weight into account I am trying to randomize the link weights of a network x graph to change the betweenness centrality of that network. I have verified that the weights do change but it does not change the output of the edge_betweeness_centrality functio...
Network-X edge_betweeness_centrality function does not take weight into account
I am trying to randomize the link weights of a network x graph to change the betweenness centrality of that network. I have verified that the weights do change but it does not change the output of the edge_betweeness_centrality function. I suspect it has something to do with adding objects to the nodes and edges as I w...
[ "I am relatively inexperienced with network algorithms in general, so take my answer and terminology here with a boulder of salt.\nFirst off, I think your code actually does work. Try, for example, redefining org_net as:\norg_net = nx.random_geometric_graph(10, 3, seed=42)\n\nThis does indeed produce different bet...
[ 0 ]
[]
[]
[ "networkx", "python" ]
stackoverflow_0074584989_networkx_python.txt
Q: How to sample `n=1000` vector from Multivariate Normal distribution? I want to sample the number of m=10 of size n=1000 vectors (1000 dimension) from Multivariate Normal distribution with mean vector (0,0,..,0) and covariance matrix identity I_n and then divided by its l_2 norm. Based on the answer, I try the fol...
How to sample `n=1000` vector from Multivariate Normal distribution?
I want to sample the number of m=10 of size n=1000 vectors (1000 dimension) from Multivariate Normal distribution with mean vector (0,0,..,0) and covariance matrix identity I_n and then divided by its l_2 norm. Based on the answer, I try the following code: import random m = 2 n = 5 random.seed(1000001) x = np.random...
[ "Use np.zeros(), and np.eye(), and size, to provide the parameters for the multivariate_normal function in order to create the array. Then normalize the data using the l2 norm parameter of the normalize function from sklearn. We can then validate this l2 normalization by checking the sum of the squared values in ea...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074587012_python.txt
Q: How to count the extracted elements? I need to know the number of links that return in the extraction below: for produtos in classeprodutos: link = produtos.find_element(By. TAG_NAME, "a") lista_link.append(print(link.get_attribute("href"))) A: You have to call an iterable maeaning a list inside len() fu...
How to count the extracted elements?
I need to know the number of links that return in the extraction below: for produtos in classeprodutos: link = produtos.find_element(By. TAG_NAME, "a") lista_link.append(print(link.get_attribute("href")))
[ "You have to call an iterable maeaning a list inside len() function to count the total number like:\nprint(len(classeprodutos))\n\n#OR\nlista_link = []\nfor produtos in classeprodutos:\n link = produtos.find_element(By. TAG_NAME, \"a\")\n lista_link.append(link.get_attribute(\"href\"))\n\nprint(len(lista_link...
[ 1 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074586395_python_selenium.txt
Q: How to filter data from a dataframe so that only values ​linked to a specific string remain. Python so I got this dataframe showing the leading causes of death for each year in Chile. Original Dataframe What I want to do is to make something like this: What i want to make I want to make that so I can see how that ...
How to filter data from a dataframe so that only values ​linked to a specific string remain. Python
so I got this dataframe showing the leading causes of death for each year in Chile. Original Dataframe What I want to do is to make something like this: What i want to make I want to make that so I can see how that specific cause of death varies in the years shown. I made the dataframe so "Causas 2 de año 2016" is a di...
[ "You should use df.query. With that function one can make a filter from the dataframe\n", "Probably is there a better way, but in the meantime this give exactly what you asked for\nimport pandas as pd\n\ndf = pd.read_csv(\"causas.csv\")\n\ncausa=\"Enfermedades cerebrovasculares\"\n\ni = df.columns\ndf3=pd.DataFra...
[ 0, 0 ]
[]
[]
[ "dataframe", "jupyter_notebook", "numpy", "pandas", "python" ]
stackoverflow_0074578711_dataframe_jupyter_notebook_numpy_pandas_python.txt
Q: Please inform Django connecting to mysql for M1mac I want to connect django to mysql. So I tried pip install mysqlclient, but I get the following error. [running environment] machin: M1 Mac OS ventura mysql8.0.30: installed by brew [trying note] installing Cmake : not solve Please let me know the latest solution f...
Please inform Django connecting to mysql for M1mac
I want to connect django to mysql. So I tried pip install mysqlclient, but I get the following error. [running environment] machin: M1 Mac OS ventura mysql8.0.30: installed by brew [trying note] installing Cmake : not solve Please let me know the latest solution for M1 Mac. [erro logs] $ pip install mysqlclient Collect...
[ "Use:\npip install wheel\npip install --upgrade setuptools\n\n" ]
[ 0 ]
[]
[]
[ "macos", "mysql", "pip", "python" ]
stackoverflow_0074587075_macos_mysql_pip_python.txt
Q: Separating 2 bar groups in Plotly - Python I have two groups of data I'm working with, which I'd like to show in a bar plot using plotly (example for data is shown below). import numpy as np import plotly.express as px import plotly.graph_objects as go values1 = abs(np.random.normal(0.5, 0.3, 13)) # random data a...
Separating 2 bar groups in Plotly - Python
I have two groups of data I'm working with, which I'd like to show in a bar plot using plotly (example for data is shown below). import numpy as np import plotly.express as px import plotly.graph_objects as go values1 = abs(np.random.normal(0.5, 0.3, 13)) # random data and names values2 = abs(np.random.normal(0.5, 0.3...
[ "The only functions to adjust the spacing of bars in plotly are the spacing of bars and the type of spacing within a group. So you can force spacing by inserting a null-valued graph in between.\nfig.update_layout(barmode='group', bargroupgap=0.2)\n\n\nfig = go.Figure()\n\nfig.add_trace(go.Bar(\n x = names,\n ...
[ 1, 0 ]
[]
[]
[ "bar_chart", "plotly_python", "python" ]
stackoverflow_0074585842_bar_chart_plotly_python_python.txt
Q: Web scraping specific td tag from a table with python I am trying to extract the text from the first <td> tag but there are multiple identical class tags in a row which I am having trouble extracting a single one (the final golf score from the golfer, -19 in the example below). I cannot get python to pick it up at...
Web scraping specific td tag from a table with python
I am trying to extract the text from the first <td> tag but there are multiple identical class tags in a row which I am having trouble extracting a single one (the final golf score from the golfer, -19 in the example below). I cannot get python to pick it up at all. I have it picking up the golfers name, but that's it....
[ "You can try the next example using CSS selectors correctly\nfrom bs4 import BeautifulSoup\nimport requests\n\nhtml_text = requests.get('https://www.espn.com/golf/leaderboard/_/tournamentId/401465506').text\n\nsoup = BeautifulSoup(html_text, 'lxml')\ngolfers = soup.find_all('tr', class_ = 'PlayerRow__Overview Playe...
[ 0 ]
[]
[]
[ "html", "python", "web_scraping" ]
stackoverflow_0074587155_html_python_web_scraping.txt
Q: Renaming a header to a csv file using python and adding numeric value on that Column I'm pretty new with Python programming and would like to seek your expertise/help on how to achieve my goal. So far, what I have done is to delete unnecessary columns from a CSV file using Python. Now, I want to rename a specific ...
Renaming a header to a csv file using python and adding numeric value on that Column
I'm pretty new with Python programming and would like to seek your expertise/help on how to achieve my goal. So far, what I have done is to delete unnecessary columns from a CSV file using Python. Now, I want to rename a specific Header "Tags" into "Quantity" on the edited CSV file. I also want to append the value of t...
[ "new = mydata[[\"Part ID\",\"Serial ID\",\"Bin\",\"Cluster\",\"Site\",\"Room\",\"Model MPN\",\"Vendor\",\"Type\",\"State\",\"Tags\"]]\n\n# added lines\nnew = new.rename(columns={'Tags': 'Quantity'})\nnew['Quantity'] = 1\n\nnew.to_csv(p ,index=False)\n\nThis should work.\n" ]
[ 0 ]
[]
[]
[ "csv", "header", "pandas", "python" ]
stackoverflow_0074587190_csv_header_pandas_python.txt
Q: PyTorch backpropagation is too slow by custom loss I'm currently implementing a custom contrastive loss for the network but the training process is very slow. I investigate this problem and finally find that the backpropagation of the custom loss makes the main contribution to the problem. Here is the simplified c...
PyTorch backpropagation is too slow by custom loss
I'm currently implementing a custom contrastive loss for the network but the training process is very slow. I investigate this problem and finally find that the backpropagation of the custom loss makes the main contribution to the problem. Here is the simplified code. n = 2000 neighbors = 2 x = torch.randn((n, n), requ...
[ "As @Flavia Giammarino mentions, avoiding the loops can speed up the backward time. torch.gather function do the correct sampling for the problem.\n>>> t = torch.tensor([[1, 2], [3, 4]])\n>>> torch.gather(t, 1, torch.tensor([[0, 0], [1, 0]]))\ntensor([[ 1, 1],\n [ 4, 3]])\n\nThe final code is below.\nimpor...
[ 0 ]
[]
[]
[ "loss_function", "python", "pytorch" ]
stackoverflow_0074580950_loss_function_python_pytorch.txt
Q: Messed up JSON return? - nested nonsense I have a return form a JSON call via curl that returns this { 'result': { 'today_runtime': 830, 'month_runtime': 39991, 'today_energy': 1293, 'month_energy': 55326, 'local_time': '2022-11-27 13:50:54', 'electricity_charge'...
Messed up JSON return? - nested nonsense
I have a return form a JSON call via curl that returns this { 'result': { 'today_runtime': 830, 'month_runtime': 39991, 'today_energy': 1293, 'month_energy': 55326, 'local_time': '2022-11-27 13:50:54', 'electricity_charge': \[0, 0, 0\], 'current_power': 93860 ...
[ "{\n 'result': {\n 'today_runtime': 830,\n 'month_runtime': 39991,\n 'today_energy': 1293,\n 'month_energy': 55326,\n 'local_time': '2022-11-27 13:50:54',\n 'electricity_charge': \\[0, 0, 0\\],\n 'current_power': 93860\n },\n 'error_code': 0\n}\n\nThat is a ...
[ 2 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074587184_json_python.txt
Q: name "variable" is not define in python I have a question, here I have a problem with my code for my last one semester in college, I made a menu for food n when I input order with [1/2/3/4] and input how much for the order, I got the error like in for i in range(order) h.append(price) ah, I don't know where t...
name "variable" is not define in python
I have a question, here I have a problem with my code for my last one semester in college, I made a menu for food n when I input order with [1/2/3/4] and input how much for the order, I got the error like in for i in range(order) h.append(price) ah, I don't know where the problem bro can your guys help me? how to ...
[ "It says in your screenshot that price is not defined. You need to set price to a value to use it.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074587227_python.txt
Q: Enumerating the Writing of Different Lines in Txt file in Python It seems that every time the string should add up the 4, 1, and 4, for column 1, the total result is just 4*3. Could you help me put an enumeration-like function in here? (I am I very new beginner) Thank you for anything! import os import platform...
Enumerating the Writing of Different Lines in Txt file in Python
It seems that every time the string should add up the 4, 1, and 4, for column 1, the total result is just 4*3. Could you help me put an enumeration-like function in here? (I am I very new beginner) Thank you for anything! import os import platform pathwindows = os.environ['USERPROFILE'] + r"\Documents\Your_Wordle...
[ "I'm going to answer this the best I can according to the post, there was problems with indentation, use of the correct variable to fetch the values (stringlineofinteres instead of line which is the one in the loop), your code, and finally no line to add vaalues to the totals:\nimport os\nimport platform\n\npathwin...
[ 0 ]
[]
[]
[ "enumerate", "python" ]
stackoverflow_0074578921_enumerate_python.txt
Q: How do I access JSON elements and put the contents into lists? I have a JSON list of objects like this: "server-1": { "username": "admin542", "on_break": false, "scheduling_type": 1, "schedule": { "Monday": [ "11:00" ], "Tuesday": [ "12:00", "13:00" ]...
How do I access JSON elements and put the contents into lists?
I have a JSON list of objects like this: "server-1": { "username": "admin542", "on_break": false, "scheduling_type": 1, "schedule": { "Monday": [ "11:00" ], "Tuesday": [ "12:00", "13:00" ], }, "com_type": 2 }, "server-2": { "username": "adm...
[ "data['server-2']['schedule'] is the sub-dictionary you want to access. You can use the .keys() method of this dictionary to get the keys, and the .values() method to get the values.\nschedule_days = list(data['server-2']['schedule'].keys())\nschedule_times = list(data['server-2']['schedule'].values())\n\n" ]
[ 1 ]
[]
[]
[ "json", "python" ]
stackoverflow_0074587147_json_python.txt
Q: Python3: Remove \n from middle of the string while keeping the one in the end I am new to Python and stuck with this problem. I have a multiline string: My name is ABCD \n I am 20 years old \n I like to travel his name is XYZ \n he is 20 years old \n he likes to eat your name is ABC \n you are 20 years old \n you...
Python3: Remove \n from middle of the string while keeping the one in the end
I am new to Python and stuck with this problem. I have a multiline string: My name is ABCD \n I am 20 years old \n I like to travel his name is XYZ \n he is 20 years old \n he likes to eat your name is ABC \n you are 20 years old \n you like to play I want to replace all \n with space but keep the sentence as it is. ...
[ "You can use regex to find the newlines (\\n) that are surrounded by a space \\s.\n\nThe regex pattern looks like r\"(\\s\\n\\s)\"\n\nHere is the example code:\nimport re\n\ntest_string = \"\"\"\nMy name is ABCD \\n I am 20 years old \\n I like to travel\nhis name is XYZ \\n he is 20 years old \\n he likes to eat\n...
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0074587200_python_python_3.x.txt
Q: Django - How to Filter when getting values_list? I have an application that has multiple objects related to one Model. When I try and get data to display in a form (in order to update) it is either giving an error or not displaying any of the data. To illustrate the layout we have OBJECT(ID): Project(1): Issue...
Django - How to Filter when getting values_list?
I have an application that has multiple objects related to one Model. When I try and get data to display in a form (in order to update) it is either giving an error or not displaying any of the data. To illustrate the layout we have OBJECT(ID): Project(1): Issue(1) Issue(42) Issue(66) Issue(97) What is...
[ "To get project instance\nproject_id = get_object_or_404(DevProjects, pk=pk)\n\nTo get issue_ids related to that project instance\nissue_ids = DevIssues.objects.filter(project=project_id).values_list('id', flat=True)\n\nTo get update issue objects\nupdate_issue = DevIssues.objects.filter(id__in=issue_ids)\n\nbut yo...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0074587096_django_python.txt
Q: Add Attribute to Existing Object in Python Dictionary I was attempting to add an attribute to a pre-existing object in a dictionary: key = 'key1' dictObj = {} dictObj[key] = "hello world!" #attempt 236 (j/k) dictObj[key]["property2"] = "value2" ###'str' object does not support item assignment #another attempt ...
Add Attribute to Existing Object in Python Dictionary
I was attempting to add an attribute to a pre-existing object in a dictionary: key = 'key1' dictObj = {} dictObj[key] = "hello world!" #attempt 236 (j/k) dictObj[key]["property2"] = "value2" ###'str' object does not support item assignment #another attempt setattr(dictObj[key], 'property2', 'value2') ###'dict' obje...
[ "As I was writing up this question, I realized my mistake.\nkey = 'key1'\ndictObj = {}\ndictObj[key] = {} #here is where the mistake was\n\ndictObj[key][\"property2\"] = \"value2\"\n\nThe problem appears to be that I was instantiating the object with key 'key1' as a string instead of a dictionary. As such, I was n...
[ 21, 0 ]
[]
[]
[ "attributes", "dictionary", "python" ]
stackoverflow_0034046609_attributes_dictionary_python.txt
Q: Beautifulsoup error: "openpyxl.utils.exceptions.illegalcharactererror" I'm trying to extract texts from html files saved locally in my hard drive. And then paste them in each rows in an excel file. Doing this on Mac, here is the full code: # install/import all prerequisites first # from cgitb import text from open...
Beautifulsoup error: "openpyxl.utils.exceptions.illegalcharactererror"
I'm trying to extract texts from html files saved locally in my hard drive. And then paste them in each rows in an excel file. Doing this on Mac, here is the full code: # install/import all prerequisites first # from cgitb import text from openpyxl import Workbook, load_workbook from bs4 import BeautifulSoup # create...
[ "Openpyxl module raises this exception when you try to assign an ASCII control character (e.g, \"\\x00\", \"\\x01\", ..) to a cell's value. It means that at least one of yourhtml files holds this kind of characters. So, you need to use str.encode to escape those.\nReplace this :\nws.append([datePublished, cd, cat, ...
[ 0 ]
[]
[]
[ "beautifulsoup", "excel", "openpyxl", "python", "python_3.x" ]
stackoverflow_0074587240_beautifulsoup_excel_openpyxl_python_python_3.x.txt
Q: (Pandas/Dataframe) pandas.json_normalize on nested JSON data without uniform record_path I'm attempting to convert a large JSON file to a CSV, but the field that I need to be able to sort data on in the Spreadsheet is all in one cell whenever I convert it to CSV/Normalize the JSON. The main thing I need is the hit...
(Pandas/Dataframe) pandas.json_normalize on nested JSON data without uniform record_path
I'm attempting to convert a large JSON file to a CSV, but the field that I need to be able to sort data on in the Spreadsheet is all in one cell whenever I convert it to CSV/Normalize the JSON. The main thing I need is the hits list of dictionaries not all be in the same cell when I convert it to a csv. (Structure is: ...
[ "Using json_normalize with in a list comp based off keys.\nFinally merge and explode.\nfrom ast import literal_eval\n\nimport pandas as pd\n\n\ndata = literal_eval(open(\"/path/to/file/data.txt\").read())\n\ndf_meta = (\n pd\n .concat([pd.json_normalize(data=data[x]) for x in data], keys=data.keys())\n .dr...
[ 0 ]
[]
[]
[ "dataframe", "json", "json_normalize", "pandas", "python" ]
stackoverflow_0074587293_dataframe_json_json_normalize_pandas_python.txt
Q: It keeps on saying IndexError: String Index out of range I'm coding a discord bot and it works fine until I try and use one of the ! commands (Like !hello) and then It comes up with this ERROR discord.client Ignoring exception in on_message Traceback (most recent call last): File "C:\Users\vanti\PycharmProjec...
It keeps on saying IndexError: String Index out of range
I'm coding a discord bot and it works fine until I try and use one of the ! commands (Like !hello) and then It comes up with this ERROR discord.client Ignoring exception in on_message Traceback (most recent call last): File "C:\Users\vanti\PycharmProjects\discordbot4thtry\venv\Lib\site-packages\discord\client.py",...
[ "You must add the message_content intent.\nintents.message_content = True\n\nThe class definition will look like\ndef run_discord_bot():\n TOKEN = 'This is where the bots token would go'\n intents = discord.Intents.default()\n intents.message_content = True\n client = discord.Client(intents=intents)\n\n...
[ 1 ]
[ "You may want to add the following line to your code :\nif len(user_message) > 0:\n\nLike this:\n @client.event\n async def on_message(message):\n if message.author == client.user:\n return\n\n username = str(message.author)\n user_message = str(message.content)\n channe...
[ -1 ]
[ "discord", "discord.py", "python" ]
stackoverflow_0074587344_discord_discord.py_python.txt
Q: Best way to process the update of dictionary in python I wish to update my dictionary based on my values in a dictionary by looping it but my method is quite naive and not cool so I wish to seek help here to see whether is there better cool way with single line or maybe a few lines to process it to have the same o...
Best way to process the update of dictionary in python
I wish to update my dictionary based on my values in a dictionary by looping it but my method is quite naive and not cool so I wish to seek help here to see whether is there better cool way with single line or maybe a few lines to process it to have the same output? My code: g_keypoints = {"test1": (14,145), "test2": (...
[ "I think you basically want a solution using list comprehension.\ng_keypoints = {\"test1\": (14,145), \"test2\": (15, 151)}\nd = {}\n[(d.update({k+\"_x\":v[0]}), d.update({k+\"_y\":v[1]})) for k,v in g_keypoints.items()]\nprint(d)\n\nThis seems to work and produces the same output you have, although I feel like the...
[ 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074581798_dictionary_python.txt
Q: PIP Install web3 I am having trouble installing web3.py on my macOS by pip The error I am getting is xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun I have followed the docs and make a venv they way the said a...
PIP Install web3
I am having trouble installing web3.py on my macOS by pip The error I am getting is xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun I have followed the docs and make a venv they way the said and still no luck I am ...
[ "I just did it and didn't have a problem. \nTry upgrading your Python version to the latest one available. Download the newest version of it from www.python.org or from your package manager of choice.\nIf you are using home brew just type :\nbrew update \n\nbrew upgrade python3\n\nThen just simple use pip to instal...
[ 1, 0 ]
[]
[]
[ "ethereum", "macos", "python", "python_3.x", "web3" ]
stackoverflow_0054024875_ethereum_macos_python_python_3.x_web3.txt
Q: Dataframe reindexing in order I have a dataframe like this datasource datavalue 0 aaaa.pdf 5 0 bbbbb.pdf 5 0 cccc.pdf 9 I don't know if this is the reason but this seems to be messing a dash display so I would like to reindex it like datasource datavalue 0 aaaa.pdf 5 1 bbbbb.pdf 5...
Dataframe reindexing in order
I have a dataframe like this datasource datavalue 0 aaaa.pdf 5 0 bbbbb.pdf 5 0 cccc.pdf 9 I don't know if this is the reason but this seems to be messing a dash display so I would like to reindex it like datasource datavalue 0 aaaa.pdf 5 1 bbbbb.pdf 5 2 cccc.pdf 9 I used data_all...
[ "I think this is what you are looking for.\ndf.reset_index(drop=True, inplace=True)\n#drop: Do not try to insert index into dataframe columns. This resets the index to the default integer index.\n# inplace: Whether to modify the DataFrame rather than creating a new one.\n\n", "Try:\ndata_all = data_all.reset_inde...
[ 1, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074587386_pandas_python.txt
Q: Generate all possible combination of numbers, letters, symbols python I only managed to generate all possible combination of letters in python. from string import ascii_lowercase from itertools import product minimum_length = 0 maximum_length = 1 for length in range(minimum_length, maximum_length + 1): for com...
Generate all possible combination of numbers, letters, symbols python
I only managed to generate all possible combination of letters in python. from string import ascii_lowercase from itertools import product minimum_length = 0 maximum_length = 1 for length in range(minimum_length, maximum_length + 1): for combo in product(ascii_lowercase, repeat=length): print(''.join(combo)...
[ "According to the official documentation you can leverage the following:\n\nstring.ascii_lowercase\nstring.ascii_uppercase\nstring.punctuation\nstring.digits\n\n", "You can import uppercase letters, numbers, and symbols from the same module (or just define a list containing them yourself).\nThen combine them into...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074587286_python.txt
Q: AttributeError: 'CustomerHelper' object has no attribute 'requests_utility' src\helpers\customers_helper.py:23: AttributeError from ssqaapitest.src.utilities.genericUtilities import generate_random_email_and_password from ssqaapitest.src.utilities.requestsUtility import RequestUtility class CustomerHelper(object):...
AttributeError: 'CustomerHelper' object has no attribute 'requests_utility' src\helpers\customers_helper.py:23: AttributeError
from ssqaapitest.src.utilities.genericUtilities import generate_random_email_and_password from ssqaapitest.src.utilities.requestsUtility import RequestUtility class CustomerHelper(object): def int(self): self.requests_utility = RequestUtility() def create_customer(self, email=None, password=None, **kwargs): if not...
[ "You have a typo in your init function in your class CustomerHelper. You have __int__(self) it should be __init__(self). This is what is creating the attribute error as that variable never gets initialized.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074580631_python.txt
Q: How to add timestamp in python? I want to set timestamp as I wnat. But There was an error in doing it this way like this dir.set({ u'done':False, u'from':datetime.date(2022, 10, 20) }) ('Cannot convert to a Firestore Value', datetime.date(2022, 10, 20), 'Invalid type', <class 'datetime.date'>)...
How to add timestamp in python?
I want to set timestamp as I wnat. But There was an error in doing it this way like this dir.set({ u'done':False, u'from':datetime.date(2022, 10, 20) }) ('Cannot convert to a Firestore Value', datetime.date(2022, 10, 20), 'Invalid type', <class 'datetime.date'>)
[ "Your issue is that Firestore does not accept the python Datetime object as a type.\nInstead, cast your datetime object to a string before sending it over and you should be good.\nSomething like this should work\ndir.set({\n 'done':False,\n 'from':datetime.date(2022, 10, 20).strftime('%Y/%m/%d')\n ...
[ 0 ]
[]
[]
[ "google_cloud_firestore", "python" ]
stackoverflow_0074587407_google_cloud_firestore_python.txt
Q: Comparing previous rows in two columns of a DataFrame I have a dataframe of transactions with the unique ID of a product, seller and buyer. I want to keep a record whether someone has bought a product and later resold it. Here's a simplified view of my dataset: prod_id seller buyer 0 cc_123 x ...
Comparing previous rows in two columns of a DataFrame
I have a dataframe of transactions with the unique ID of a product, seller and buyer. I want to keep a record whether someone has bought a product and later resold it. Here's a simplified view of my dataset: prod_id seller buyer 0 cc_123 x y 1 cc_111 d y 2 cc_025 y x ...
[ "Your attempt almost got there. For sellers, it has no need to groupby.\ndf['resale'] = df.groupby('prod_id')['buyer'].shift(1) == df['seller']\ndf['resale'] = df['resale'].astype(int)\ndf\n\noutput:\n prod_id seller buyer resale\n0 cc_123 x y 0\n1 cc_111 d y 0\n2 cc_025 y ...
[ 2, 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074587238_pandas_python.txt
Q: Don't allow duplicate value records in a list of dictionaries When user adding details to a dictionary, I want check those details are already there or not, When name, age, team and car have same values in another record ignore those inputs and tell the user "It's already there" otherwise "add" details to the dict...
Don't allow duplicate value records in a list of dictionaries
When user adding details to a dictionary, I want check those details are already there or not, When name, age, team and car have same values in another record ignore those inputs and tell the user "It's already there" otherwise "add" details to the dictionary. Also, this duplication check should happen before appending...
[ "# check all values in the driver_det is found in any of the \n# dictionaries in the list driver_list\ndef checkAllInList(driver_det): \n # define the keys we are interested in\n Interest = ['name', 'age', 'team', 'car']\n # get corresponding values from the driver_det\n b = set([value for key, value in...
[ 2 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0074587455_dictionary_list_python.txt
Q: How can I specify a file without listing the entire file path? I am currently using pandas to read an "output.csv" file by specifying the filepath as : df = pd.read_csv(r'C:\users\user1\desktop\project\output.csv') While this works perfectly fine on my local machine, is there a way I can code this so anyone who ru...
How can I specify a file without listing the entire file path?
I am currently using pandas to read an "output.csv" file by specifying the filepath as : df = pd.read_csv(r'C:\users\user1\desktop\project\output.csv') While this works perfectly fine on my local machine, is there a way I can code this so anyone who runs the script can use it? I want to be able to hand this script to c...
[ "If you're shipping out the output.csv in the same directory as the python script, you should be able to reference it directly pd.read_csv('output.csv').\nIf your need to get the full path + filename for the file, you should use os.path.abspath(__file__).\nFinally, if your output.csv is in a static location in all ...
[ 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074587277_pandas_python.txt
Q: Scraping game name containing the "@": scraper recognizes such name as email address I want to scrape games' information. However, some games' name contains "@", such as the game "Ampers@t". When I try to scrape such games' title, the code will return me "[email protected]". Apparently, my code does not recognize ...
Scraping game name containing the "@": scraper recognizes such name as email address
I want to scrape games' information. However, some games' name contains "@", such as the game "Ampers@t". When I try to scrape such games' title, the code will return me "[email protected]". Apparently, my code does not recognize that this is game's name, and is not an email. Here are my codes used. import requests fro...
[ "[Expanded from my comment] If you tweak the function from this answer a bit to\ndef deCFEmail(encTag):\n if not (encTag.get('data-cfemail') or encTag.select('*[data-cfemail]')):\n encTag.append(f'[! no \"data-cfemail\" attribute !]')\n else:\n fp = encTag.get('data-cfemail', None)\n if ...
[ 1 ]
[]
[]
[ "python", "web_scraping" ]
stackoverflow_0074577001_python_web_scraping.txt
Q: TypeError: 'float' object is not callable even after multiple tries enter image description here I cannot figure out how I can get this formula to work. Any help is very appreciated! :) I tried appling everything that is in the picture. But I berly have any knowlage of coding. A: An operator is missing as shown ...
TypeError: 'float' object is not callable even after multiple tries
enter image description here I cannot figure out how I can get this formula to work. Any help is very appreciated! :) I tried appling everything that is in the picture. But I berly have any knowlage of coding.
[ "An operator is missing as shown in the image that's why it raisea s not callable error. having (1)(2)(this is seen as a function call in the interpreter) doesn't mean (1) * (2) in python,\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0074587459_python.txt
Q: How to tell AWS Lambda how to access relative files Python I'm trying to get some Python code to run on AWS Lambda. This is my file structure. I'm trying to run the lambda_handler function in the aws_lambda_function module. The code in aws_lambda_function is: import json from server.server_code import process_req...
How to tell AWS Lambda how to access relative files Python
I'm trying to get some Python code to run on AWS Lambda. This is my file structure. I'm trying to run the lambda_handler function in the aws_lambda_function module. The code in aws_lambda_function is: import json from server.server_code import process_request def lambda_handler(event, context): response = process...
[ "Okay, so it turns out that these AWS messages aren't the most descriptive or helpful for finding where the actual bugs are. It turns out that what I had to do was to go through recursively through every folder in this directory, add an __init__.py file to make the folder a package, and then remove all relative imp...
[ 0 ]
[]
[]
[ "amazon_web_services", "aws_lambda", "python" ]
stackoverflow_0074579538_amazon_web_services_aws_lambda_python.txt
Q: python - Opening another tkinter window with opencv camera don't show live feed I have 2 windows, first is the main window (window1) and another window with opencv (window2). I have a button on window1 that opens window2. Whenever I open window2 on window1 the camera won't show on the GUI. But if I open window2 in...
python - Opening another tkinter window with opencv camera don't show live feed
I have 2 windows, first is the main window (window1) and another window with opencv (window2). I have a button on window1 that opens window2. Whenever I open window2 on window1 the camera won't show on the GUI. But if I open window2 individually which is on a different file, the camera is showing. I tried to put it on ...
[ "I found the answer.\nI fixed it by removing the main loop on window2 since camera window2 also runs in tkinter.\n" ]
[ 0 ]
[]
[]
[ "camera", "python", "tkinter", "window" ]
stackoverflow_0074573165_camera_python_tkinter_window.txt
Q: How to compile a python script into executable program and can be use by others My python script is finished and working and I want to compile and have other users enjoy/benefit from it. The users don't need to install Pycharm or Visual Studio Code, something like an executable file or run in a command prompt then...
How to compile a python script into executable program and can be use by others
My python script is finished and working and I want to compile and have other users enjoy/benefit from it. The users don't need to install Pycharm or Visual Studio Code, something like an executable file or run in a command prompt then execute on their local machine or is there a way to convert it on a Tampermonkey Scr...
[ "This question is probably answered multiple times, but the PyInstaller module is a great way to generate an executable that will run on Windows, and an app that will run on macOS.\nCheck out PyInstaller on PyPI.org: https://pypi.org/project/pyinstaller/\nProject description\nPyPI PyPI - Python Version Read the Doc...
[ 0 ]
[]
[]
[ "command_line", "compiler_construction", "csv", "python" ]
stackoverflow_0074587560_command_line_compiler_construction_csv_python.txt
Q: Django forms: cannot access local variable 'form' where it is not associated with a value Condition: I have a model, created an empty table in the database, and I'm trying to create an html form that will fill in the fields of the corresponding columns of the table. And here's what my app looks like: models.py fro...
Django forms: cannot access local variable 'form' where it is not associated with a value
Condition: I have a model, created an empty table in the database, and I'm trying to create an html form that will fill in the fields of the corresponding columns of the table. And here's what my app looks like: models.py from django.db import models class Cities(models.Model): city = models.CharField(max_length=1...
[ "It is because you haven't defined form for GET method so:\ndef getAbout(request):\n if request.method == 'POST':\n form = RouteForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('some_view_name_to_redirect')\n else:\n form=RouteForm()\n retu...
[ 1, 1 ]
[]
[]
[ "django", "django_forms", "django_models", "django_templates", "python" ]
stackoverflow_0074586586_django_django_forms_django_models_django_templates_python.txt
Q: Python Pandas Import Excel sheet cell as object without quotes in the end My example excel sheet looks like this: Excel sheet data: customer1_data.xlsx = parameter customer1 analysis 1 analysis_name ...
Python Pandas Import Excel sheet cell as object without quotes in the end
My example excel sheet looks like this: Excel sheet data: customer1_data.xlsx = parameter customer1 analysis 1 analysis_name 1month_services analysis_duration [2022-08-23, 2...
[ "You can use pandas.Series.split to convert string delimited to lists :\nc1df[\"customer1\"]= (\n c1df[\"customer1\"].str.strip(\"[]\")\n .str.split(\",\")\n .where(c1df[\"customer1\"].str.contains(\"[\\[\\]]\", regex=True, na=False))\n ...
[ 1 ]
[]
[]
[ "dataframe", "excel", "pandas", "python" ]
stackoverflow_0074587564_dataframe_excel_pandas_python.txt
Q: How to group multiple columns while replacing zero with values (pandas)? Name Cat Dog Frog Pig Ana 0 1 0 0 Ana 1 0 1 0 Name Cat Dog Frog Pig Ana 1 1 1 0 I'd like to group these two rows by name and replace the 'zeros' by one when is filled. The output should be like this A: Use groupby with max() df = df.gr...
How to group multiple columns while replacing zero with values (pandas)?
Name Cat Dog Frog Pig Ana 0 1 0 0 Ana 1 0 1 0 Name Cat Dog Frog Pig Ana 1 1 1 0 I'd like to group these two rows by name and replace the 'zeros' by one when is filled. The output should be like this
[ "Use groupby with max()\ndf = df.groupby('Name').max().reset_index()\n\noutput:\n> df\n\n Name Cat Dog Frog Pig\n0 Ana 1 1 1 0\n\n", "what you might want to do here is an aggregation. One way to obtain your desired output is to use the pandas dataframe methods grouby() and sum()\nHere is how I ...
[ 2, 1 ]
[]
[]
[ "group_by", "pandas", "python", "replace", "sql" ]
stackoverflow_0074587565_group_by_pandas_python_replace_sql.txt
Q: Django Rest How to show all related foreignkey object? I have an blog website and my visitors can also comment on my blog posts. Each blog post have multiple comment and I want to show those comment under my each single blog post. Assume Blog1 have 10 comment so all 10 comment will be show under Blog1 here is my c...
Django Rest How to show all related foreignkey object?
I have an blog website and my visitors can also comment on my blog posts. Each blog post have multiple comment and I want to show those comment under my each single blog post. Assume Blog1 have 10 comment so all 10 comment will be show under Blog1 here is my code: models.py class Blog(models.Model): blog_title = mo...
[ "You can access comments list from blog object using comment_set attribute, so add comment_set field to your serializer:\nclass BlogSerializer(serializers.ModelSerializer): \n comment_set = CommentSerializer(many=True)\n\n class Meta:\n model = Blog\n exclude = (\"author\", \"blog_is_published\...
[ 2 ]
[]
[]
[ "django", "django_rest_framework", "python", "python_3.x" ]
stackoverflow_0074587635_django_django_rest_framework_python_python_3.x.txt
Q: Converting pdf files to txt files but only getting last page of pdf file I'm trying to convert a list of PDF files in a directory to txt. At the moment, however, I'm only getting the last page of the pdf files in the newly created txt. files. The code: import os, PyPDF2 import re for file in os.listdir("Documents...
Converting pdf files to txt files but only getting last page of pdf file
I'm trying to convert a list of PDF files in a directory to txt. At the moment, however, I'm only getting the last page of the pdf files in the newly created txt. files. The code: import os, PyPDF2 import re for file in os.listdir("Documents/Python/"): if file.endswith(".pdf"): fpath=os.path.join("Document...
[ "You are only getting the text of the last page because you are only ever reading the text of the last page of each pdf pageobj=pdfreader.getPage(x-1)\nAlthough it works, it looks like pdfreader.numPages is deprecated now. The way to do it is len(reader.pages) if you wanted the number of pages. You could also just...
[ 0 ]
[]
[]
[ "for_loop", "pdf", "pypdf2", "python", "txt" ]
stackoverflow_0074586987_for_loop_pdf_pypdf2_python_txt.txt
Q: How can I get files dir from opened several foleders in python I trying to make that gather files from several file explorrer with Python I want to move many files to one folder from already opend foleders by file explorer How can I approch opend directory? Manual typing dir one by one is not an option so, what I ...
How can I get files dir from opened several foleders in python
I trying to make that gather files from several file explorrer with Python I want to move many files to one folder from already opend foleders by file explorer How can I approch opend directory? Manual typing dir one by one is not an option so, what I want is I want to get several dir path from opend file explorer
[ "Here is the code I use to get a list of file names that have been copied to the clipboard from Windows Explorer:\nimport ctypes\nimport struct\n\nfrom ctypes.wintypes import BOOL, HWND, HANDLE, HGLOBAL, UINT, LPVOID\nfrom ctypes import c_size_t as SIZE_T\n\nOpenClipboard = ctypes.windll.user32.OpenClipboard\nOpenC...
[ 1 ]
[]
[]
[ "file_move", "python", "visual_studio_code" ]
stackoverflow_0074587650_file_move_python_visual_studio_code.txt
Q: How to solve the coding error with python? Topic: Check adjacent odd numbers Problem description: Enter 5 numbers Input description: Whether the output has adjacent odd numbers. Output description: If there are adjacent odd numbers, output the first group of adjacent odd numbers, otherwise, turn out NO. Sample Inp...
How to solve the coding error with python?
Topic: Check adjacent odd numbers Problem description: Enter 5 numbers Input description: Whether the output has adjacent odd numbers. Output description: If there are adjacent odd numbers, output the first group of adjacent odd numbers, otherwise, turn out NO. Sample Input: Sample Output: 5 6 7 8 9 NO⏎ 8 9 11...
[ "When you use range you are creating an entirely new set of numbers. You need to use the list directly. An easy way to solve this problem is by using zip on the list and an offset of the list\nThis way you can compare the current number with the next number without creating more loops.\n#you can apply your split re...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0074587683_python.txt
Q: Key error on pandas merge, but both dataframes contain the key I'm trying to work with US Census data using the census package. I'm doing API requests through the census package like this: req = c.acs.state_county_tract(tuple(allowed_vars), states.CA.fips, '013', '313102') Then converting to pandas data frames an...
Key error on pandas merge, but both dataframes contain the key
I'm trying to work with US Census data using the census package. I'm doing API requests through the census package like this: req = c.acs.state_county_tract(tuple(allowed_vars), states.CA.fips, '013', '313102') Then converting to pandas data frames and trying to merge the frames: row_df = pd.DataFrame.from_dict(req) ...
[ "I tried to reproduce the error:\n\nKeyError 'state'\n\nIt happens only if I have the following situation:\n\nThe columns of the dataframe that you are reporting, are actually the values of the rows of the dataframe\nThe merge fails because the on key argument is referring to a column that is not there\n\nMore info...
[ 0 ]
[]
[]
[ "census", "jupyter_notebook", "pandas", "python" ]
stackoverflow_0074587675_census_jupyter_notebook_pandas_python.txt
Q: Not sure if I'm answering the wrong question or wrongly answering the right question. Need suggestions please Thank you for taking the time to read my post. I'm in a bit of a limbo here and really need some intervention. I have been working on an individual project. It is a supervised learning regression problem. ...
Not sure if I'm answering the wrong question or wrongly answering the right question. Need suggestions please
Thank you for taking the time to read my post. I'm in a bit of a limbo here and really need some intervention. I have been working on an individual project. It is a supervised learning regression problem. After cleaning, initial analysis, EDA, and feature selection, the chosen dataset now has a total of 8 attributes an...
[ "If I get what you have done in your experiments, you are passing to the regression models all the data except the profit which is the output that you're trying to predict, but you get the current year's profit and not the future one, as expected due to the dataset structure.\nFor doing what you want, predict the n...
[ 1 ]
[]
[]
[ "machine_learning", "prediction", "python", "regression", "supervised_learning" ]
stackoverflow_0074587602_machine_learning_prediction_python_regression_supervised_learning.txt
Q: Jupyter kernel dies while running this neural networks code import numpy as np import cv2 import os import matplotlib.pyplot as plt from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.preprocessing import image from tensorflow.keras.optimizers import RMSprop img = image...
Jupyter kernel dies while running this neural networks code
import numpy as np import cv2 import os import matplotlib.pyplot as plt from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.preprocessing import image from tensorflow.keras.optimizers import RMSprop img = image.load_img("image_location_here") train = ImageDataGenerator(res...
[ "I recently had a similar issue. The issue is being caused by CUDA/cudNN, probably because you are using an incompatible version with Tensorflow. There are two solutions for the same:\n\nUninstall CUDA and reinstall Tensorflow library\nUninstall CUDA and setup the compatible CUDA/cudNN version ( Check https://tenso...
[ 0 ]
[]
[]
[ "conv_neural_network", "jupyter_notebook", "python" ]
stackoverflow_0074587606_conv_neural_network_jupyter_notebook_python.txt
Q: Trying to input a blank for an input that requires 2 values separated by ", " So I am trying to have the while loop end when inputting a blank for the input, but the problem is that the input takes 2 values separated by ", ". It is necessary for me to keep the input like that rather than separating them so how to ...
Trying to input a blank for an input that requires 2 values separated by ", "
So I am trying to have the while loop end when inputting a blank for the input, but the problem is that the input takes 2 values separated by ", ". It is necessary for me to keep the input like that rather than separating them so how to fix this? print(" Input the productIDs and quantities (input blank to complete tran...
[ "while loop should be outer, if you want to iteratively receive the input until a bad format is fed (handled by try-except).\nwhile True:\n try:\n productID, quantity = input(\"Input the productIDs and quantities (input blank to complete transaction)\").split(\", \")\n quantity = int(quantity)\n ...
[ 1, 1, 0 ]
[ "I managed to fix it by using try/except.\nprint(\" Input the productIDs and quantities (input blank to complete transaction)\")\n try:\n productID, quantity = input().split(\", \")\n quantity = int(quantity)\n while quantity >= 1:\n self.addProductToTransaction(productID, quantit...
[ -1 ]
[ "input", "python", "python_3.x" ]
stackoverflow_0074587685_input_python_python_3.x.txt
Q: Get first element of sublist as dictionary key in python I looked but i didn't found the answer (and I'm pretty new to python). The question is pretty simple. I have a list made of sublists: ll [[1,2,3], [4,5,6], [7,8,9]] What I'm trying to do is to create a dictionary that has as key the first element of each su...
Get first element of sublist as dictionary key in python
I looked but i didn't found the answer (and I'm pretty new to python). The question is pretty simple. I have a list made of sublists: ll [[1,2,3], [4,5,6], [7,8,9]] What I'm trying to do is to create a dictionary that has as key the first element of each sublist and as values the values of the coorresponding sublists,...
[ "Using dict comprehension :\n{words[0]:words[1:] for words in lst}\n\noutput:\n{1: [2, 3], 4: [5, 6], 7: [8, 9]}\n\n", "Using dictionary comprehension (For Python 2.7 +) and slicing -\nd = {e[0] : e[1:] for e in ll}\n\nDemo -\n>>> ll = [[1,2,3], [4,5,6], [7,8,9]]\n>>> d = {e[0] : e[1:] for e in ll}\n>>> d\n{1: [2...
[ 11, 7, 2, 2 ]
[ "Another:\nd = {k: v for k, *v in ll}\n\n" ]
[ -1 ]
[ "dictionary", "list", "python", "sublist" ]
stackoverflow_0032604558_dictionary_list_python_sublist.txt
Q: DRF pagination issue in APIView I want to implement LimitOffsetPagination in my APIView which was successful but the url is required to be appended with ?limit=<int>. Something like this: But I do not want to manually add that endpoint. So I tried creating a new pagination.py file: But now I am not getting the p...
DRF pagination issue in APIView
I want to implement LimitOffsetPagination in my APIView which was successful but the url is required to be appended with ?limit=<int>. Something like this: But I do not want to manually add that endpoint. So I tried creating a new pagination.py file: But now I am not getting the pagination prompt for navigation to ne...
[ "You just need to change your return. Instead of return Response(serializer.data) use return paginator.get_paginated_response(serializer.data)\n" ]
[ 1 ]
[]
[]
[ "backend", "django", "django_rest_framework", "python" ]
stackoverflow_0074587600_backend_django_django_rest_framework_python.txt
Q: VS Code: "The isort server crashed 5 times in the last 3 minutes..." I may have messed up some environmental path variables. I was tinkering around VS Code while learning about Django and virtual environments, and changing the directory path of my Python install. While figuring out how to point VS Code's default P...
VS Code: "The isort server crashed 5 times in the last 3 minutes..."
I may have messed up some environmental path variables. I was tinkering around VS Code while learning about Django and virtual environments, and changing the directory path of my Python install. While figuring out how to point VS Code's default Python path, I deleted some User path variables. Then, isort began to refus...
[ "You need to find the location of the python.exe file.\nUsually it is C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python310\\\nYou can also automatically add python to the system environment by deleting and reinstalling it. During installation, a small box is automatically checked to add environment variabl...
[ 1, 1, 0 ]
[]
[]
[ "isort", "python", "python_extensions", "visual_studio_code" ]
stackoverflow_0074467875_isort_python_python_extensions_visual_studio_code.txt
Q: Tensorflow 2.0 list_physical_devices doesn't detect my GPU I recently install tensorflow 2.0 on my computer but when I try to run it on my GPU, the function tf.config.experimental.list_physical_devices('GPU') on Jupyter or Vitual Studio Code it returns me a void array. Do you know why ? My set-up : Computer : MSI ...
Tensorflow 2.0 list_physical_devices doesn't detect my GPU
I recently install tensorflow 2.0 on my computer but when I try to run it on my GPU, the function tf.config.experimental.list_physical_devices('GPU') on Jupyter or Vitual Studio Code it returns me a void array. Do you know why ? My set-up : Computer : MSI Processor : Intel(R) Core(TM) i7-8750H CPU @ 2.220GHz GPU 0 : In...
[ "Providing the solution here (Answer Section), even though it is present in the Comment Section for the benefit of the community.\nInstead of pip install tensorflow, you can try pip3 install --upgrade tensorflow-gpu or just remove tensorflow and then installing \"tensorflow-gpu will resolves your issue. \nAfter ins...
[ 7, 1, 0 ]
[]
[]
[ "gpu", "python", "tensorflow2.0" ]
stackoverflow_0058956619_gpu_python_tensorflow2.0.txt
Q: How can I add Buttons to my bot page in discord.py? So how do I add this button? Image Thanks in advice i tried it with Client.change_presence(activity=discord... , buttons=["Website"]) A: Unfortunately, Discord (and subsequently the discord.py lib) does not have ways for us developers to modify those buttons. B...
How can I add Buttons to my bot page in discord.py?
So how do I add this button? Image Thanks in advice i tried it with Client.change_presence(activity=discord... , buttons=["Website"])
[ "Unfortunately, Discord (and subsequently the discord.py lib) does not have ways for us developers to modify those buttons. Both of those buttons are fairly new to Discord anyways. The button you were seeing is related to the bot \"streaming on Twitch\" (ie Twitch integration) This is autogenerated for anyone who ...
[ 0 ]
[]
[]
[ "discord.py", "python" ]
stackoverflow_0074577024_discord.py_python.txt
Q: How to link 2 items from the same array? First of all, I'm sorry for my bad English. English isn't my main language. So, I have this data, datamhs = np.array([["x", 85, "22222221"], ["y", 85, "22222222"], ["z", 70, "22222223"], ["a", 90, "22222224"], ["b", 60, "22222225"], ["c", 90, "22222226"]]) Is there a way ...
How to link 2 items from the same array?
First of all, I'm sorry for my bad English. English isn't my main language. So, I have this data, datamhs = np.array([["x", 85, "22222221"], ["y", 85, "22222222"], ["z", 70, "22222223"], ["a", 90, "22222224"], ["b", 60, "22222225"], ["c", 90, "22222226"]]) Is there a way to reference each row with itself? For example...
[ "Where do x and y come from? I can't understand\nMaybe you should try something like that\ndef name():\n if 'x' in datamhs[:,0]:\n if 'y' in datamhs[:,1]:\n print(datamhs[:,0])\n print(datamhs[:,1])\n\nThe python interpreter nothing knows about x and y if you have not yet defined them.\n" ]
[ 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074587908_arrays_numpy_python.txt
Q: How to convert result of np.where to array? I have an array from which I want to get the indices of the elements of interest by condition np.where: diff = [19, 403472, 403491, 403491, 403491, 403491, 13, 403478, 13] np.where(diff > np.average(diff)) As result I have tuple: (array([1, 2, 3, 4, 5, 7], dtype=int64),...
How to convert result of np.where to array?
I have an array from which I want to get the indices of the elements of interest by condition np.where: diff = [19, 403472, 403491, 403491, 403491, 403491, 13, 403478, 13] np.where(diff > np.average(diff)) As result I have tuple: (array([1, 2, 3, 4, 5, 7], dtype=int64),) But I want only array: array([1, 2, 3, 4, 5, 7...
[ "np.where(diff > np.average(diff))[0]?\noutput:\narray([1, 2, 3, 4, 5, 7])\n" ]
[ 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0074587951_numpy_python.txt
Q: Storing CSV file in dictionary list of tuples. Each key is a date, each tuple contains 3 corresponding fields, multiple entries per key(date) possible An example to demonstrate my problem, suppose the csv file is formatted like: 2022-11-05,Female,30-39,City of London 2022-11-05,Male,60-69,City of London 2022-11-04...
Storing CSV file in dictionary list of tuples. Each key is a date, each tuple contains 3 corresponding fields, multiple entries per key(date) possible
An example to demonstrate my problem, suppose the csv file is formatted like: 2022-11-05,Female,30-39,City of London 2022-11-05,Male,60-69,City of London 2022-11-04,Female,70-79,City of London 2022-11-04,Female,60-69,City of London Should be read into a dictionary like: {'2022-11-05': [(Female,30-39, City of London), ...
[ "A more pythonic way to express the same solution is:\nfor row in vaccine_data_reader:\n try:\n mydict[row[0]].append(tuple(row[1:]))\n except KeyError:\n mydict[row[0]] = [tuple(row[1:])]\n\n", "I don't think Dictionary Comprehension would be the way here, as dictionary does not allow duplica...
[ 1, 0 ]
[]
[]
[ "csv", "file_io", "python" ]
stackoverflow_0074587824_csv_file_io_python.txt
Q: Issue With Nested Comments Using MPTT in Django and Django Rest Framework API - Result In Detail Not Found I'm trying to create a nested comment system using MPTT but using Django Rest Framework to serialize MPTT tree. I got the nested comments to work - and these comments are added, edited, and deleted by callin...
Issue With Nested Comments Using MPTT in Django and Django Rest Framework API - Result In Detail Not Found
I'm trying to create a nested comment system using MPTT but using Django Rest Framework to serialize MPTT tree. I got the nested comments to work - and these comments are added, edited, and deleted by calling Django Rest Framework API endpoints only - not using Django ORM DB calls at all. Unfortunately, there is a bu...
[ "Okie, I figured it out!\nI think when calling the same object in the Tree of MPTT for GET and PUT somehow spits out a weird bug that prevents me from editing the affected replies. So, my solution now is just creating an endpoint with API view below:\nclass CommentChildrenAV(mixins.CreateModelMixin, generics.Gener...
[ 0 ]
[]
[]
[ "api", "django", "django_rest_framework", "mptt", "python" ]
stackoverflow_0074585468_api_django_django_rest_framework_mptt_python.txt
Q: python/pandas/one dimensional dataframe Creating a 2 dimensional dataframe works fine: y = np.array([[1,2],[3,4]]) df = pd.DataFrame( y, index=[1,2], columns=["a","b"] ) print (df) But if I try to create a one dimensional dataframe I get an error message: z = np.array([5,6]) df2 = pd.DataFrame( z, index=[3], colu...
python/pandas/one dimensional dataframe
Creating a 2 dimensional dataframe works fine: y = np.array([[1,2],[3,4]]) df = pd.DataFrame( y, index=[1,2], columns=["a","b"] ) print (df) But if I try to create a one dimensional dataframe I get an error message: z = np.array([5,6]) df2 = pd.DataFrame( z, index=[3], columns=["a","b"]) print (df2) Error message: Sh...
[ "Just adding []\nz = np.array([5,6])\ndf2 = pd.DataFrame( [z], index=[3], columns=[\"a\",\"b\"])\ndf2\nOut[67]: \n a b\n3 5 6\n\n", "You cannot create a dataframe from a 1D array. Add another dimension to the array before passing it to the constructor:\npd.DataFrame(z[np.newaxis,:], index=[3], columns=[\"a\"...
[ 4, 2, 0, 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0052340276_pandas_python.txt
Q: VSCode Jupyter loads incorrect version of python VSCode's Jupyter isn't actually running the version of python that it displays in the lower left of the screen. Below, it purports to be running 3.9.1, but the output of the cell shows that it is indeed running 3.7.9. I selected the displayed rl environment via: Sel...
VSCode Jupyter loads incorrect version of python
VSCode's Jupyter isn't actually running the version of python that it displays in the lower left of the screen. Below, it purports to be running 3.9.1, but the output of the cell shows that it is indeed running 3.7.9. I selected the displayed rl environment via: Select environment to start Jupyter Server. What doesn't ...
[ "What eventually worked for me was:\n\nClose VSCode\nIn .ipynb pane's top right, change version of Python to the desired conda environment\nStart the kernel\n\nChanging the kernel and then restarting it didn't seem to work.\n", "In VSCode, the Python environment of Jupyter notebook is independent, it uses the Pyt...
[ 2, 1, 0, 0 ]
[]
[]
[ "jupyter_notebook", "python", "python_3.x", "visual_studio_code" ]
stackoverflow_0065503907_jupyter_notebook_python_python_3.x_visual_studio_code.txt
Q: pip connection failure: cannot fetch index base URL http://pypi.python.org/simple/ I run sudo pip install git-review, and get the following messages: Downloading/unpacking git-review Cannot fetch index base URL http://pypi.python.org/simple/ Could not find any downloads that satisfy the requirement git-review ...
pip connection failure: cannot fetch index base URL http://pypi.python.org/simple/
I run sudo pip install git-review, and get the following messages: Downloading/unpacking git-review Cannot fetch index base URL http://pypi.python.org/simple/ Could not find any downloads that satisfy the requirement git-review No distributions at all found for git-review Storing complete log in /home/sai/.pip/pip....
[ "I know this is an old thread, but I encountered this issue today and wanted to share my solution to the problem because I haven't seen this solution elsewhere on SO.\nMy environment: Python 2.7.12/2.7.14 on Ubuntu 12.04.5 LTS in a virtualenv, pip version 1.1.\nMy Errors:\npip install nose\n\nin console:\nCannot fe...
[ 152, 61, 42, 13, 11, 8, 6, 6, 4, 3, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ "For my case, I fix it by:\nI copied libcrypto-1_1-x64.dll and libssl-1_1-x64.dll from Anaconda3\\Library\\bin to \\Anaconda3\\DLLs.\n" ]
[ -1 ]
[ "git", "git_review", "pip", "python", "ubuntu" ]
stackoverflow_0021294997_git_git_review_pip_python_ubuntu.txt
Q: How can I add a restriction so that the # of forward steps won't overshadow the # of backward steps? I have to create a program that tracks a person's motion. F represents forward B represents backward. The values are to be randomly generated between 2-20 as well as the total # of steps being randomly generated fr...
How can I add a restriction so that the # of forward steps won't overshadow the # of backward steps?
I have to create a program that tracks a person's motion. F represents forward B represents backward. The values are to be randomly generated between 2-20 as well as the total # of steps being randomly generated from 10-85 (total will decide when the steps will stop). The # of forward steps has to be greater than the #...
[ "I would tackle it like this:\nimport random\n\ntotal_steps = random.randint(10, 85)\nfwd = random.randint(3,(20, total_steps-1)[total_steps<21])\nbkwd= random.randint(2,fwd-1)\n\nif (fwd+bkwd) > total_steps: \n bkwd = total_steps-fwd\n\nprint(\"Total_steps=\", total_steps, \", fwd=\", fwd, \", bkwd=\", bkwd)\n\...
[ 1, 0 ]
[]
[]
[ "iteration", "loops", "motion", "python", "while_loop" ]
stackoverflow_0074587741_iteration_loops_motion_python_while_loop.txt
Q: Pyautogui error about non-internable object Error Image exist in the folder, but I don't know why program gives an error I don't know what to do help me pls A: pyautogui.click("otvet.png") will take x,y value and you're passing a .png file, i think you wanted to do this: # Locate the image on screen, this will r...
Pyautogui error about non-internable object
Error Image exist in the folder, but I don't know why program gives an error I don't know what to do help me pls
[ "pyautogui.click(\"otvet.png\") will take x,y value and you're passing a .png file,\ni think you wanted to do this:\n# Locate the image on screen, this will return x,y value if image is found and none if it is not\notvet = pyautogui.locateOnScreen(\"otvet.png\")\n\n# Click on the x,y value\npyautogui.click(otvet)\n...
[ 0 ]
[]
[]
[ "image", "object", "pyautogui", "python", "python_3.x" ]
stackoverflow_0074577263_image_object_pyautogui_python_python_3.x.txt
Q: How do I save scraped data to a MySQL database? I have a python script that scrapes data from a job website. I want to save these scraped data to MySQL database but after writing the code, it connects to the database. Now after connecting, it doesn't create table and as result couldn't insert those data into the t...
How do I save scraped data to a MySQL database?
I have a python script that scrapes data from a job website. I want to save these scraped data to MySQL database but after writing the code, it connects to the database. Now after connecting, it doesn't create table and as result couldn't insert those data into the table. Please i need my code to store these scraped da...
[ "Slight issue with the column name. Instead of 'Company Name' it needs to be 'Company_Name'. SQL doesn't like spaces in column names.\nUpdated queries that you should run:\nCREATE TABLE first_tbl \n(\n Company_Name Varchar(300) NOT NULL,\n Keyskill Varchar(400) NOT NULL\n)\n\nINSERT INTO first_tbl \n (Comp...
[ 1, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0074588033_mysql_python.txt
Q: No module named 'keras.saving.hdf5_format' After pip3 installing tensorflow and the transformers library, I'm receiving the titular error when I try loading this from transformers import pipeline classifier = pipeline("text-classification",model='bhadresh-savani/distilbert-base-uncased-emotion') The error traceba...
No module named 'keras.saving.hdf5_format'
After pip3 installing tensorflow and the transformers library, I'm receiving the titular error when I try loading this from transformers import pipeline classifier = pipeline("text-classification",model='bhadresh-savani/distilbert-base-uncased-emotion') The error traceback looks like: RuntimeError: Failed to import tr...
[ "If you are using the latest version of TensorFlow and Keras then you have to try this code and you have got this error as shown below\nRuntimeError: Failed to import transformers.models.distilbert.modeling_tf_distilbert because of the following error (look up to see its traceback):\nNo module named 'keras.saving.h...
[ 2 ]
[]
[]
[ "keras", "python", "tensorflow" ]
stackoverflow_0074586892_keras_python_tensorflow.txt
Q: How to delete a document in MongoDB I am trying to create a delete method in order to delete a document that has the key:"name" and the value:"Rhonda". Whenever I execute my current code, I get an AttributeError saying:"'AnimalShelter' object has no attribute 'delete'". How do I get the method to return the delete...
How to delete a document in MongoDB
I am trying to create a delete method in order to delete a document that has the key:"name" and the value:"Rhonda". Whenever I execute my current code, I get an AttributeError saying:"'AnimalShelter' object has no attribute 'delete'". How do I get the method to return the deleted document's JSON contents? Here is my co...
[ "Problem is that functions that you are defining are outside the class. You have to put indentation on functions in class AnimalShelter\nAlso as pointed out in comment you are missing : in delete\nUpdated animal_sheltor.py\nfrom pymongo import MongoClient\nfrom bson.objectid import ObjectId\n\nclass AnimalShelter(o...
[ 0 ]
[]
[]
[ "mongodb", "python" ]
stackoverflow_0074588047_mongodb_python.txt
Q: What is the python equivalent of setting instances of a class within the __init__() method? I'd like to send in a list of dependencies as part of creating a DAGNode: what is the supported way to achieve a similar behavior in python - given it seems this exact syntax were not supported? from typing import TypeVar, ...
What is the python equivalent of setting instances of a class within the __init__() method?
I'd like to send in a list of dependencies as part of creating a DAGNode: what is the supported way to achieve a similar behavior in python - given it seems this exact syntax were not supported? from typing import TypeVar, Generic T = TypeVar('T') class DAGNode(Generic[T]): # Apparently the `DAGNode` type does no...
[ "Since the class does not exist yet you have to reference it including its name between single quote like this\nfrom typing import TypeVar, Generic, Set\n\nT = TypeVar('T')\nclass DAGNode(Generic[T]):\n\n # Apparently the DAGNode type does not exist yet so this fails\n def __init__(self, type_id: T, dependenc...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0074588016_python.txt
Q: TypeError: list indices must be integers or slices, not Symbol from sympy import * t6,a,b,c = symbols ('t6,a,b,c') result=solve([(a*cos(t6))+(b*sin(t6))+c],[t6]) cs=[(a,-26.468147779101194),(b,4.395890741437306),(c,19.920476269921963)] t6 = result[t6].subs(cs) trying to solve an equation i guess it is because i...
TypeError: list indices must be integers or slices, not Symbol
from sympy import * t6,a,b,c = symbols ('t6,a,b,c') result=solve([(a*cos(t6))+(b*sin(t6))+c],[t6]) cs=[(a,-26.468147779101194),(b,4.395890741437306),(c,19.920476269921963)] t6 = result[t6].subs(cs) trying to solve an equation i guess it is because it has two results because it works fine on simplier equations
[ "There is no need for list (i.e., []) inside solve()\nt6,a,b,c = symbols('t6,a,b,c')\nresult=solve((a*cos(t6))+(b*sin(t6))+c, t6)\ncs=[(a,-26.468147779101194),(b,4.395890741437306),(c,19.920476269921963)]\n\n# solve for t6\nfor i in range(len(result)):\n t6 = result[i].subs(cs)\n print(t6)\n\noutput:\n0.56949...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074588086_python.txt
Q: Pandas version of rbind In R, you can combine two dataframes by sticking the columns of one onto the bottom of the columns of the other using rbind. In pandas, how do you accomplish the same thing? It seems bizarrely difficult. Using append results in a horrible mess including NaNs and things for reasons I don't ...
Pandas version of rbind
In R, you can combine two dataframes by sticking the columns of one onto the bottom of the columns of the other using rbind. In pandas, how do you accomplish the same thing? It seems bizarrely difficult. Using append results in a horrible mess including NaNs and things for reasons I don't understand. I'm just trying t...
[ "Ah, this is to do with how I created the DataFrame, not with how I was combining them. The long and the short of it is, if you are creating a frame using a loop and a statement that looks like this:\nFrame = Frame.append(pandas.DataFrame(data = SomeNewLineOfData))\n\nYou must ignore the index\nFrame = Frame.append...
[ 56, 56, 35, 4, 3, 0 ]
[]
[]
[ "dataframe", "pandas", "python", "r" ]
stackoverflow_0014988480_dataframe_pandas_python_r.txt
Q: Filtering out SQAlchemy query with group_by based on column value being > 0 I am trying to filter out this SQLAlchemy query to only return records where avg_3d_perf > 0 Here is a query I am using: query = query.with_entities(func.max(Signals_light.id).label('id'),Signals_light.symbol,func.max(Signals_light.close)....
Filtering out SQAlchemy query with group_by based on column value being > 0
I am trying to filter out this SQLAlchemy query to only return records where avg_3d_perf > 0 Here is a query I am using: query = query.with_entities(func.max(Signals_light.id).label('id'),Signals_light.symbol,func.max(Signals_light.close).label('close'),func.max(Signals_light.volume).label('volume'),func.max(Signals_li...
[ "Adding query = query.having(func.avg(func.nullif(Signals_light.avg_3d_perf,0)) > 0) after the main query solved my issue.\n" ]
[ 0 ]
[]
[]
[ "filter", "python", "sqlalchemy", "where_clause" ]
stackoverflow_0074203940_filter_python_sqlalchemy_where_clause.txt
Q: AttributeError: module 'collections' has no attribute 'Iterable' I am using the "pdftables" library to extract tables from a pdf. This is my code: import pdftables pg = pdftables.get_pdf_page(open("filename.pdf","rb"),253) print(pg) table = pdftables.page_to_tables(pg) print(table) I am getting this error and...
AttributeError: module 'collections' has no attribute 'Iterable'
I am using the "pdftables" library to extract tables from a pdf. This is my code: import pdftables pg = pdftables.get_pdf_page(open("filename.pdf","rb"),253) print(pg) table = pdftables.page_to_tables(pg) print(table) I am getting this error and I am not sure what's causing it. Traceback (most recent call last): ...
[ "If you don't want to change the source code, there is an easier way. Just use this in your script after importing.\nimport collections\ncollections.Iterable = collections.abc.Iterable\n\n", "As the Error says, the attribute isn't valid. When using collection.Iterable then it not finds the Iterable attribute. Thi...
[ 3, 0 ]
[ "A simple fix that works for python3.10:\nUnder directory\n/usr/lib/python3.10/collections/init.py\nNote: The path might change depending\nAdd this line of code:\nfrom _collections_abc import Iterable\n", "import collections \nfrom _collections_abc import Iterable \ncollection.Iterable = Iterable\n\nThis should w...
[ -1, -1 ]
[ "attributeerror", "pdf", "pdftables", "python" ]
stackoverflow_0072371859_attributeerror_pdf_pdftables_python.txt
Q: How to filter the dates from datetime field in django views.py import datetime from django.shortcuts import render import pymysql from django.http import HttpResponseRedirect from facligoapp.models import Scrapper from django.utils import timezone import pytz roles = "" get_records_by_date = "" def index(request...
How to filter the dates from datetime field in django
views.py import datetime from django.shortcuts import render import pymysql from django.http import HttpResponseRedirect from facligoapp.models import Scrapper from django.utils import timezone import pytz roles = "" get_records_by_date = "" def index(request): if request.method == "POST": from_date = re...
[ "\nI need to get the row start_time and end_time which has dates 2022-11-24.\n\nIt is a DateTimeField so compare its date using __date lookup so use this Queryset:\nScrapper.objects.filter(start_time__date=f_date,end_time__date=t_date)\n\n" ]
[ 3 ]
[]
[]
[ "django", "django_models", "django_queryset", "django_views", "python" ]
stackoverflow_0074588141_django_django_models_django_queryset_django_views_python.txt
Q: How to remove keys-values from dictionary 1 which are not in dictionary 2 based on common keys? I have two large dictionaries and both dictionaries have same keys, (name of images) and have different values. 1st dict named train_descriptions which looks like this: {'15970.jpg': 'Turtle Check Men Navy Blue Shirt', ...
How to remove keys-values from dictionary 1 which are not in dictionary 2 based on common keys?
I have two large dictionaries and both dictionaries have same keys, (name of images) and have different values. 1st dict named train_descriptions which looks like this: {'15970.jpg': 'Turtle Check Men Navy Blue Shirt', '39386.jpg': 'Peter England Men Party Blue Jeans', '59263.jpg': 'Titan Women Silver Watch', .... ...
[ "Use xor to get the difference between the dictionaries\ndiff = train_features.keys() ^ train_descriptions.keys()\nfor k in diff:\n del train_features[k]\n\n", "Using for loop\nfeat = train_features.keys()\ndesc = train_description.keys()\ncommon = list(i for i in feat if i not in decc)\n\nfor i in common: del...
[ 2, 1, 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0074588103_dictionary_python.txt
Q: Numpy - Circular indexing by skip Given a np.arange() array of arbitrary length, x = np.arange(10) for example, what is an efficient way to generate an output array that skips every n values starting from 0 up to n? Sample code with current method and output: def circ(arr, n): y = np.array([]) for i in ran...
Numpy - Circular indexing by skip
Given a np.arange() array of arbitrary length, x = np.arange(10) for example, what is an efficient way to generate an output array that skips every n values starting from 0 up to n? Sample code with current method and output: def circ(arr, n): y = np.array([]) for i in range(n): y = np.concatenate((y, a...
[ "Repeated concatenation is inefficient as you have to create a new array over and over.\nA loop with a single concatenation should be more efficient:\nx = np.arange(10)\nn = 4\n\nout = np.concatenate([x[i::n] for i in range(n)])\n\nOutput:\narray([0, 4, 8, 1, 5, 9, 2, 6, 3, 7])\n\nAs a function:\ndef circ2(arr, n):...
[ 1 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0074588090_arrays_numpy_python.txt
Q: How to hide or disable google chrome maximize and minimize option using selenium python can anyone tell me How to hide or disable google chrome maximize and minimize option using selenium python automation. Refer image link below While automation anyone can't be minimize and maximize chrome browser. A: Use sele...
How to hide or disable google chrome maximize and minimize option using selenium python
can anyone tell me How to hide or disable google chrome maximize and minimize option using selenium python automation. Refer image link below While automation anyone can't be minimize and maximize chrome browser.
[ "Use selenium engine it should do the trick\n" ]
[ 1 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0074588233_python_selenium.txt
Q: Empty list as json response although code is running I am trying to run the following python script to extract data from google scholar.However, when I run the code,I am getting an empty list as a json response.Note that all necessary libraries are installed. headers = { 'User-agent': 'Mozilla/5.0 (Windows NT ...
Empty list as json response although code is running
I am trying to run the following python script to extract data from google scholar.However, when I run the code,I am getting an empty list as a json response.Note that all necessary libraries are installed. headers = { 'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) C...
[ "Your code is working fine but the problem was to save the scraped data correctly in json format. So you can use super powerful and easy tool which is pandas DataFrasme to store data in json format\nfrom bs4 import BeautifulSoup\nimport requests\n#import json\nimport pandas as pd\n\nheaders = {\n 'User-agent': '...
[ 0, 0 ]
[]
[]
[ "beautifulsoup", "json", "python", "web_scraping" ]
stackoverflow_0074587071_beautifulsoup_json_python_web_scraping.txt
Q: Python Tkinter f string to variable Please help, hi guys, how to put end-users email content to an f string in Python? What should we insert here st.insert(INSERT, "...") so that mail.Body # (1) gets st variable and works like mail.Body # (2)? I'm sorry if I don't explain my question clearly. This is my first ques...
Python Tkinter f string to variable
Please help, hi guys, how to put end-users email content to an f string in Python? What should we insert here st.insert(INSERT, "...") so that mail.Body # (1) gets st variable and works like mail.Body # (2)? I'm sorry if I don't explain my question clearly. This is my first question in Python. Please let me know if you...
[ "I found my solution.\nst.insert(INSERT, \"\"\"f\\\"\"\"Hi {row['First Name']}\n\nPlease find the attached report for {row['Vendor']}.\n\nBest regards,\nxxxxxxx\nyuyyyyyyy\nzzzzzz\n\\\"\"\"\n \n\"\"\")\n\nmail.Body = eval(st.get(1.0, END))\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x", "tkinter", "tkinter_entry" ]
stackoverflow_0074588123_python_python_3.x_tkinter_tkinter_entry.txt
Q: Word search puzzle generator in Python I am creating a word search puzzle generator, but I am a beginner in programming, so I´m having some trouble, like some words overlap, and I don't really know where is the problem. So i need a program that asks for the rows and columns, with that information it creates the gr...
Word search puzzle generator in Python
I am creating a word search puzzle generator, but I am a beginner in programming, so I´m having some trouble, like some words overlap, and I don't really know where is the problem. So i need a program that asks for the rows and columns, with that information it creates the grid and organize the word(key) given in the g...
[ "you try to get this [x + direccion[0]*i][y + direccion[1]*i] from this cuadricula 2D list, but you cannot do this because in cuadricula there is not such indices that are given by [x + direccion[0]*i][y + direccion[1]*i] on some lvl of iteration of for i in range(len(palabra)):\n" ]
[ 0 ]
[]
[]
[ "python", "wordsearch" ]
stackoverflow_0074588261_python_wordsearch.txt
Q: Markov Chain: Finding terminal state calculation I'm trying to figure out this problem. Hopefully someone can tell me how to complete this. I consulted the following pages, but I was unable to write a code in java/python that produces the correct output and passes all test cases. I'd appreciate any and all help. M...
Markov Chain: Finding terminal state calculation
I'm trying to figure out this problem. Hopefully someone can tell me how to complete this. I consulted the following pages, but I was unable to write a code in java/python that produces the correct output and passes all test cases. I'd appreciate any and all help. Markov chain probability calculation - Python Calculati...
[ "I'm not sure what the results for the edge cases should be, but what I did for this problem is:\n\nCreated a second matrix that held all of the denominators for each probability by adding up all of the numerators in each row.\nFind the first terminal state in the matrix to use as the bound of the non-terminal stat...
[ 5, 2, 0, 0 ]
[]
[]
[ "java", "python" ]
stackoverflow_0040433526_java_python.txt
Q: Python Class instance object has no attribute 'undefined_method' Class definition class Car: amount_cars = 0 def __init__(self, manufacturer, model, hp): self.manufacturer = manufacturer self.model = model self.hp = hp Car.amount_cars += 1 def print_car_am...
Python Class instance object has no attribute 'undefined_method'
Class definition class Car: amount_cars = 0 def __init__(self, manufacturer, model, hp): self.manufacturer = manufacturer self.model = model self.hp = hp Car.amount_cars += 1 def print_car_amount(self): print("Amount: {}".format(Car.amount_cars)) Creat...
[ "As it is stated in the error message, tou have no method by the name print_info. Probably, you're trying to do:\nmyCar1.print_car_amount()\n\n" ]
[ 4 ]
[ "class Car:\n\namount_cars = 0\n\ndef __init__(self, manufacturer, model, hp):\n self.manufacturer = manufacturer\n self.model = model\n self.hp = hp\n Car.amount_cars += 1\n\ndef print_info(self): # Changed\n print(\"Amount: {}\".format(Car.amount_cars))\n\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0074588076_python.txt
Q: Circle collision, pop-up error "CreaCir' object has no attribute 'radio'" I make a program where I generate circles of random size and position, by means of classes in python, I have managed to generate the circles as I wish but all collide with each other, so I have created a method so that this does not happen b...
Circle collision, pop-up error "CreaCir' object has no attribute 'radio'"
I make a program where I generate circles of random size and position, by means of classes in python, I have managed to generate the circles as I wish but all collide with each other, so I have created a method so that this does not happen but it generates an error that I can not identify "'CreaCir' object has no attri...
[ "The cause of the error is that you have put a CreaCir object in the figs list. So the first item in figs (self.creOne.colisionC(self.figs[j])) is a CreaCir object and this object has no radio.\nJust remove that line of code, it is absolutely unnecessary.\nself.figs.append(CreaCir(self.figs))\nCreate the CreaCir in...
[ 0 ]
[]
[]
[ "class", "pygame", "python" ]
stackoverflow_0074587586_class_pygame_python.txt
Q: Pandas dataframe column name is oriented incorrectly I'm pulling data from Sqlite3 and moving it into a dataframe to work with it. However, I get this weird output where it places the first column name into the second row while the other column names are unaffected in the first row. This creates problems as pandas...
Pandas dataframe column name is oriented incorrectly
I'm pulling data from Sqlite3 and moving it into a dataframe to work with it. However, I get this weird output where it places the first column name into the second row while the other column names are unaffected in the first row. This creates problems as pandas won't recognize the first row's column name (it only sees...
[ "Right now you have CUSIP as an index, so it is showing up in this orientation. To add a new index column and remove this columns index attribute, use:\ndf.reset_index(drop=TRUE)\n\nThe drop=TRUE is to avoid the old index being added as a column.\n" ]
[ 1 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074578718_pandas_python.txt
Q: Python dataclass prints default values when calling fields function I just started to use dataclasses. I have created a python dataclass: from dataclasses import dataclass, fields from typing import Optional @dataclass class CSVData: SUPPLIER_AID: str = "" EAN: Optional[str] = None DESCRIPTION_SHORT: ...
Python dataclass prints default values when calling fields function
I just started to use dataclasses. I have created a python dataclass: from dataclasses import dataclass, fields from typing import Optional @dataclass class CSVData: SUPPLIER_AID: str = "" EAN: Optional[str] = None DESCRIPTION_SHORT: str = "" DESCRIPTION_LONG: str = "Article long description" After c...
[ "This is how the dataclass.fields method works (see documentation). If you want to iterate over the values, you can use asdict or astuple instead:\nfrom dataclasses import dataclass, asdict\nfrom typing import Optional\n\n\n@dataclass\nclass CSVData:\n SUPPLIER_AID: str = \"\"\n EAN: Optional[str] = None\n ...
[ 2 ]
[]
[]
[ "python", "python_dataclasses" ]
stackoverflow_0074588291_python_python_dataclasses.txt
Q: Merge rows in pandas with parent/child relationship Consider this example dataframe: case_number parent_case_number name role paid notes 0 NYC-22-1234 None Bob Cratchit Accountant 50000 Scrooge's favorite accountant. 1 L...
Merge rows in pandas with parent/child relationship
Consider this example dataframe: case_number parent_case_number name role paid notes 0 NYC-22-1234 None Bob Cratchit Accountant 50000 Scrooge's favorite accountant. 1 LON-22-1446 None Ebenezer Scrooge ...
[ "Here is one way to do it:\n# Merge relevant subsets on case_number/parent_case_number\nnew_df = pd.concat(\n [\n df[df[\"parent_case_number\"].isna()].set_index(\"case_number\"),\n df.dropna(subset=\"parent_case_number\")\n .set_index(\"parent_case_number\")\n .pipe(\n lam...
[ 0 ]
[]
[]
[ "pandas", "python" ]
stackoverflow_0074554320_pandas_python.txt
Q: How to upload a csv file using Jinja2 Templates and FastAPI , and return it after modifications? I am using FastAPI to upload a csv file, perform some modifications on it and then return it to the HTML page. I am using Jinja2 as the template engine and HTML in frontend. How can I upload the csv file using Jinja2 t...
How to upload a csv file using Jinja2 Templates and FastAPI , and return it after modifications?
I am using FastAPI to upload a csv file, perform some modifications on it and then return it to the HTML page. I am using Jinja2 as the template engine and HTML in frontend. How can I upload the csv file using Jinja2 template, modify it and then return it to the client? Python code from fastapi.templating import Jinja2...
[ "The working example below is derived from the answers here, here, as well as here, here and here, at which I would suggest you have a look for more details and explanation.\nSample data\ndata.csv\nId,name,age,height,weight\n1,Alice,20,62,120.6\n2,Freddie,21,74,190.6\n3,Bob,17,68,120.0\n\nOption 1 - Return modified...
[ 1, 0 ]
[]
[]
[ "csv", "fastapi", "html", "jinja2", "python" ]
stackoverflow_0074573656_csv_fastapi_html_jinja2_python.txt
Q: "ModuleNotFoundError: No module named 'skpy' " happen even though I already installed Though I installed skpy by pip and pip3, the error happened when I command jupyter execute on the terminal. Python 3.9.13 pip 22.2.2 from /Users/username/opt/anaconda3/lib/python3.9/site-packages/pip (python 3.9) Proof I installe...
"ModuleNotFoundError: No module named 'skpy' " happen even though I already installed
Though I installed skpy by pip and pip3, the error happened when I command jupyter execute on the terminal. Python 3.9.13 pip 22.2.2 from /Users/username/opt/anaconda3/lib/python3.9/site-packages/pip (python 3.9) Proof I installed skpy (base) username@MacBook-Pro-3 test-directory % pip list Package ...
[ "As a play off Rubizzo's answer:\nA very simple fix here is just installing using the same Python version as your juypter notebook is using.\n/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/python -m pip install skpy\n\nShould do it.\nFor further clarification: You seem to have multiple versions o...
[ 1, 0 ]
[]
[]
[ "jupyter_notebook", "python" ]
stackoverflow_0074588148_jupyter_notebook_python.txt
Q: Extract int from objects in column that has multiple metrics that need scaling My column has over 9000 rows of Mb and Kb objects appearing as numbers, that need to be converted all into Kb values (by multiplying Mb values to 1000). This is a snippet of the column values: array(['5.3M', '47M', '556k', '526k', '76M'...
Extract int from objects in column that has multiple metrics that need scaling
My column has over 9000 rows of Mb and Kb objects appearing as numbers, that need to be converted all into Kb values (by multiplying Mb values to 1000). This is a snippet of the column values: array(['5.3M', '47M', '556k', '526k', '76M', '7.6M', '59M', '9.7M', '78M', '72M', '43M', '7.7M', '6.3M', '334k', '93M', ...
[ "We can use np.where() here along with str.extract:\ndf[\"Size\"] = np.where(df[\"Size\"].str.contains(r'M$', regex=True),\n 1000.0*df[\"Size\"].str.extract('(\\d+(?:\\.\\d+)?)').astype(float),\n df[\"Size\"].str.extract('(\\d+(?:\\.\\d+)?)').astype(float))\n\nThe above log...
[ 0 ]
[]
[]
[ "if_statement", "python", "regex", "string", "type_conversion" ]
stackoverflow_0074588355_if_statement_python_regex_string_type_conversion.txt
Q: Check if object attributes are non-empty python I can check if python list or dictionary are empty or not like this lis1, dict1 = [], {} # similar thing can be done for dict1 if lis1: # Do stuff else: print "List is empty" If I try to do this with my class object, i.e checking if my object attributes are ...
Check if object attributes are non-empty python
I can check if python list or dictionary are empty or not like this lis1, dict1 = [], {} # similar thing can be done for dict1 if lis1: # Do stuff else: print "List is empty" If I try to do this with my class object, i.e checking if my object attributes are non-empty by typing if my_object: this always evaluat...
[ "You need to implement the __nonzero__ method (or __bool__ for Python3)\nhttps://docs.python.org/2/reference/datamodel.html#object.nonzero\nclass my_class(object):\n def __init__(self):\n self.lis1 = []\n self.dict1 = {}\n\n def __nonzero__(self):\n return bool(self.lis1 or self.dict1)\n\...
[ 7, 2, 2, 0, 0, 0, 0 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0032836291_if_statement_python.txt
Q: How to take over arguments after virtual env activation in batch and Python I want to execute python script by batch file. when I do that , I want to take over argument to python scipt. But, after activation of venv, it is not possible to take over the argument. The batch file I made is the following: It does not ...
How to take over arguments after virtual env activation in batch and Python
I want to execute python script by batch file. when I do that , I want to take over argument to python scipt. But, after activation of venv, it is not possible to take over the argument. The batch file I made is the following: It does not work. SET file=%~nx1 rem activate virtual env CALL ..\Script\activate.bat rem e...
[ "Try specific file instead of %~nx1.\n'%' may be the problem.\n" ]
[ 0 ]
[]
[]
[ "batch_file", "python" ]
stackoverflow_0074588324_batch_file_python.txt
Q: parsing xml with namespace from request with lxml in python I am trying to get some text out of a table from an online xml file. I can find the tables: from lxml import etree import requests main_file = requests.get('https://training.gov.au/TrainingComponentFiles/CUA/CUAWRT601_R1.xml') main_file.encoding = 'utf-8...
parsing xml with namespace from request with lxml in python
I am trying to get some text out of a table from an online xml file. I can find the tables: from lxml import etree import requests main_file = requests.get('https://training.gov.au/TrainingComponentFiles/CUA/CUAWRT601_R1.xml') main_file.encoding = 'utf-8-sig' root = etree.fromstring(main_file.content) tables = root.xp...
[ "Use the namespace prefix you declared (with namespaces={\"foo\": \"http://www.authorit.com/xml/authorit\"}) e.g. instead of //table[1]/tr/td[@width=\"2700\"]/p[@id=\"4\"][not(*)]/text() use //foo:table[1]/foo:tr/foo:td[@width=\"2700\"]/foo:p[@id=\"4\"][not(*)]/text().\n" ]
[ 0 ]
[]
[]
[ "lxml", "python", "xml", "xpath" ]
stackoverflow_0074587533_lxml_python_xml_xpath.txt
Q: I am trying to print a statement that will show any number that is great than 5 I am trying to print any number that is great than n, which is 5 in this case. It is only printing 6 and 7. I am not sure what I am doing wrong. This is my code. I am looping through the array and testing if i is greater then n (5) lis...
I am trying to print a statement that will show any number that is great than 5
I am trying to print any number that is great than n, which is 5 in this case. It is only printing 6 and 7. I am not sure what I am doing wrong. This is my code. I am looping through the array and testing if i is greater then n (5) list = [2, 3, 4, 5, 6, 7, 8, 9] n = 5 filter_list (list, n) def filter_list (list, n): ...
[ "For me your code working fine just fix the indent. Just adding end '' at print to print on same line.\nlist = [2, 3, 4, 5, 6, 7, 8, 9]\nn = 5\n\n\ndef filter_list (list, n):\n for i in range(len(list)):\n if list[i] > n:\n print (list[i],end =' ')\n \nfilter_list (list, n)\n\nGives #\n6...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0074587535_python.txt
Q: How to set the input channels size? It is an assignment using pytorch for hand gesture recognition. Code: D = np.array(Images).astype('float32') y = np.array(Labels).astype(int) for i in tqdm(range(X.shape[0])): train_data.append(X[i]) # original image train_data.append(rotate(X[i], angle = 45, mode = 'wr...
How to set the input channels size?
It is an assignment using pytorch for hand gesture recognition. Code: D = np.array(Images).astype('float32') y = np.array(Labels).astype(int) for i in tqdm(range(X.shape[0])): train_data.append(X[i]) # original image train_data.append(rotate(X[i], angle = 45, mode = 'wrap')) train_data.append(np.fliplr(X[...
[ "The input should be of the format [batch_size, channels, height, width] in PyTorch, so you have to change your input to (2080, 1, 300, 300) instead of (2080, 300, 300, 3). As per your NN architecture, the input should be single channel and not 3 channel.\nAlso,\nx = x.view(-1, 19.5 * 19.5 * 24) \nwill throw an err...
[ 0 ]
[]
[]
[ "deep_learning", "python", "pytorch" ]
stackoverflow_0074582503_deep_learning_python_pytorch.txt
Q: For some reason odd reason i can't seem to make my code write in the txt file So i have written this code where i want the computer to open a file and write in it what the user have answered to the question i asked him but when ever i open the txt file its empty. import os Welcome = input("Hi my name is Steve. D...
For some reason odd reason i can't seem to make my code write in the txt file
So i have written this code where i want the computer to open a file and write in it what the user have answered to the question i asked him but when ever i open the txt file its empty. import os Welcome = input("Hi my name is Steve. Do you have an account at Steve? ANSWER WITH JUST A YES OR NO ") def register(): ...
[ "You are not writing anything to the file. I have modified the code to add the response to the file and also changed the code to be more accurate.\nwelcome = input(\"Hi my name is Steve. Do you have an account at Steve? ANSWER WITH JUST A YES OR NO \")\n\n\ndef register():\n first_name = input(\"First name: \")\...
[ 1, 0 ]
[]
[]
[ "file", "module", "python" ]
stackoverflow_0074588520_file_module_python.txt
Q: Extracting 2 digits numbers from string I have a file which contains string, from every string I need to append to my list every 2 digit number. Here's the file content: https://pastebin.com/N6gHRaVA I need to iterate every string and check if string on index[i] and on index[i+1] is digit, if yes, append those dig...
Extracting 2 digits numbers from string
I have a file which contains string, from every string I need to append to my list every 2 digit number. Here's the file content: https://pastebin.com/N6gHRaVA I need to iterate every string and check if string on index[i] and on index[i+1] is digit, if yes, append those digits to list and slice the string from those 2...
[ "You're going off the end of the string... Change:\n while i<len(string):\n\nto:\n while i<len(string)-1:\n\nAnd you should be fine.\nIf you were just looking at one character at a time, you could use your original while. The trick here is that you're always looking at a char and also \"one ahead\" of the char. So ...
[ 1, 0, 0, 0 ]
[]
[]
[ "list", "loops", "python", "slice", "string" ]
stackoverflow_0074588308_list_loops_python_slice_string.txt
Q: how to get spacing between grouped bar plot in python I have plotted the grouped bar plot and I want to have spacing between orange and blue bar. I am not sure how to. It is the sample image - I want little space between blue and orange bar. import numpy as np import matplotlib.pyplot as plt N=4 a = [63,13,12,45...
how to get spacing between grouped bar plot in python
I have plotted the grouped bar plot and I want to have spacing between orange and blue bar. I am not sure how to. It is the sample image - I want little space between blue and orange bar. import numpy as np import matplotlib.pyplot as plt N=4 a = [63,13,12,45] b = [22,6,9,9] ind = np.arange(N) width=0.35 fig, ax = ...
[ "Just do this:\nb2 = ax.bar(ind+ 1.2 * width, b, width)\n\n\n", "I am unaware of an dedicated option for such a behavior. The reason is that it would indicate inaccurate measures. You would be no longer sure if the blue/orange bars belong to the same value on the x-axis.\nTherefore, you need to come up with a sma...
[ 1, 0, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0066913686_matplotlib_python.txt
Q: I want to convert string 1F to hex 1F in Python, what should I do? num="1F" nm="1" nm1="2" hex(num)^hex(nm)^hex(nm1) I wrote it like the code above, but hex doesn't work properly. I want to convert the string to hexadecimal, and I want an xor operation of the converted value. What should I do? A: The variable n...
I want to convert string 1F to hex 1F in Python, what should I do?
num="1F" nm="1" nm1="2" hex(num)^hex(nm)^hex(nm1) I wrote it like the code above, but hex doesn't work properly. I want to convert the string to hexadecimal, and I want an xor operation of the converted value. What should I do?
[ "The variable num can be converted to int using int(num, 16). Other variables nm, nm1 are just integers in form of strings. to convert them use int(nm), int(nm1)\nnum = \"1F\"\nnm = \"1\"\nnm1 = \"2\"\n\nresult = int(num, 16) ^ int(nm) ^ int(nm1)\nprint(result)\n\n> 28\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074588543_python.txt
Q: I can't display all texts in the same embed with python from discord bot ok, i'm trying to add all the texts in the same embed of a for bot for discord, but i can't do it, this is what happens to me... It should be all in the same embed What should I do to correct this error? Thank you very much! this is the code...
I can't display all texts in the same embed with python from discord bot
ok, i'm trying to add all the texts in the same embed of a for bot for discord, but i can't do it, this is what happens to me... It should be all in the same embed What should I do to correct this error? Thank you very much! this is the code i am using... import requests import discord from discord.ext import commands...
[ "If you want to send multiple embed, don't create multiple, build the content, then send one\n@bot.command()\nasync def habbo(ctx):\n response = requests.get(\"https://images.habbo.com/habbo-web-leaderboards/hhes/visited-rooms/daily/latest.json\")\n data = response.json()\n content = '\\n'.join(item['name'...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0074588577_python.txt
Q: Cannot install deepspeech of python I want to use DeepSpeech of Mozilla on my Linux 22.04 system, following this website: https://deepspeech.readthedocs.io/en/r0.9/?badge=latest At the very beginning line, at pip3 install deepspeech I got this error: ERROR: Could not find a version that satisfies the requiremen...
Cannot install deepspeech of python
I want to use DeepSpeech of Mozilla on my Linux 22.04 system, following this website: https://deepspeech.readthedocs.io/en/r0.9/?badge=latest At the very beginning line, at pip3 install deepspeech I got this error: ERROR: Could not find a version that satisfies the requirement deepspeech (from versions: none) ERROR:...
[ "The pip command you mentioned above worked for me:\nTry updating your linux packages\nsudo apt update\nsudo apt upgrade\n\nThen trying again if it does not work trying using python\npython -m pip install deepspeech\n\n" ]
[ 0 ]
[]
[]
[ "mozilla_deepspeech", "pip", "python" ]
stackoverflow_0074588517_mozilla_deepspeech_pip_python.txt