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:
Parameter validation failed: Invalid type for parameter Key., value: , type: , valid types:
I have 2 Lambda, 1 is doing a batch_write and put_item to ddb. The other lambda does the get_item from first lambda (It has permissions to get_item).
ERROR:
[ERROR] ParamValidationError: Parameter validation failed:
Invali... | Parameter validation failed: Invalid type for parameter Key., value: , type: , valid types: | I have 2 Lambda, 1 is doing a batch_write and put_item to ddb. The other lambda does the get_item from first lambda (It has permissions to get_item).
ERROR:
[ERROR] ParamValidationError: Parameter validation failed:
Invalid type for parameter Key.active_employee, value: jen, type: <class 'str'>, valid types: <class 'di... | [
"In Lambda 2 you are using the low level client, which expects DynamoDB JSON such as:\n{'active_employee':{'S':'jen'}}\nNow, for you to make it work in your current context, you would be better using the Resource client, as you do in Lambda 1.\ndynamodb = boto3.resource(\"dynamodb\", region_name='us-west-2')\n\ntab... | [
0
] | [] | [] | [
"amazon_dynamodb",
"python"
] | stackoverflow_0074502228_amazon_dynamodb_python.txt |
Q:
Passing a variable to a function that is many calls deep
An abstract example:
def a():
d_results = []
for i in range(10):
b(i, d_results)
# do something that needs d_results
def b(i, d_results):
# do clever b-stuff
c(d_results)
# more b-stuff
def c(d_results):
# do clever c-stuff
d(d_results)... | Passing a variable to a function that is many calls deep | An abstract example:
def a():
d_results = []
for i in range(10):
b(i, d_results)
# do something that needs d_results
def b(i, d_results):
# do clever b-stuff
c(d_results)
# more b-stuff
def c(d_results):
# do clever c-stuff
d(d_results)
# more c-stuff
def d(d_results):
result = ...
d_result... | [
"You can make your entire application (or at least this portion of it) a class and have d_results as an attribute.\nclass MyApplication:\n def __init__(self):\n self.d_results = []\n \n def a(self):\n for i in range(10):\n self.b(self,i)\n # do something that needs d_res... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074504378_python.txt |
Q:
Divide a LINESTRING with a list of LINESTRING
I'm searching a solution to divide Main Line with more than one overlapped lines. In this example I've four lines (I've applied an offset on Line 1, Line 2 and Line 3 in this chart to facilitate reading):
Below the lines:
from shapely import wkt
main_line = wkt.loads... | Divide a LINESTRING with a list of LINESTRING | I'm searching a solution to divide Main Line with more than one overlapped lines. In this example I've four lines (I've applied an offset on Line 1, Line 2 and Line 3 in this chart to facilitate reading):
Below the lines:
from shapely import wkt
main_line = wkt.loads('LINESTRING (461179.6655721677 4507148.788223281, ... | [
"Assuming the exercise is as the one presented, (all lines have the same origin), modify your code to do the following:\n\nOrder lines in descending length order, from the longest to the shortest (being the main line the longest)\nThen iterate the line list and do the symmetric difference only with the line followi... | [
1
] | [] | [] | [
"python",
"shapely"
] | stackoverflow_0074503433_python_shapely.txt |
Q:
Python Selenium - how to get all urls on a page that only load the link after clicking on the div?
I'm trying to scrap the results from this page https://www.zapimoveis.com.br/aluguel/apartamentos/sp+sao-paulo+zona-sul+itaim-bibi/ using Selenium, but I got stuck on obtaining the url of each result. It seems safe t... | Python Selenium - how to get all urls on a page that only load the link after clicking on the div? | I'm trying to scrap the results from this page https://www.zapimoveis.com.br/aluguel/apartamentos/sp+sao-paulo+zona-sul+itaim-bibi/ using Selenium, but I got stuck on obtaining the url of each result. It seems safe to say that each card's url is not stored on a <a> element and apparently not stored at all at any point ... | [
"I checked out the site and it looks like each card-container has a data-id that can be used to access the listing.\nThe link for this card:\n<div data-id=\"2593637292\" class=\"card-container js-listing-card\">{THE HTML FOR THAT CARD}</div>\n\nwould be https://www.zapimoveis.com.br/imovel/2593637292.\n"
] | [
2
] | [] | [] | [
"javascript",
"python",
"selenium"
] | stackoverflow_0074504730_javascript_python_selenium.txt |
Q:
How to distinguish negative numbers from input that is not a number
I am trying to build a simple game and I would like Python to return a message when a player enters a negative number. My issue is that negative numbers are interpreted as strings when the player tries to enter them.
Here is my script:
while True:... | How to distinguish negative numbers from input that is not a number | I am trying to build a simple game and I would like Python to return a message when a player enters a negative number. My issue is that negative numbers are interpreted as strings when the player tries to enter them.
Here is my script:
while True:
user_guess = input("Guess a number: ")
if user_guess.isdigit():
... | [
"The code you have written is not wrong but it's not very idiomatic in Python and because of that you'll have to fight the language to add the \"parse negative\" functionality. Consider you could write something like:\nuser_guess = input(\"Guess a number: \")\nif is_positive_or_negative_number(user_guess):\n use... | [
0,
0,
0
] | [
"def input_number(message):\n while True:\n user_guess = input(message)\n try:\n n = int(user_guess)\n if n < 0:\n print(\"Too low, guess a number between 0 and 10.\")\n elif n > 10:\n print(\"Too high, guess a number between 0 and 10.\... | [
-1,
-1
] | [
"negative_integer",
"python"
] | stackoverflow_0074504679_negative_integer_python.txt |
Q:
self need in call to parent class by name when using multi inheritance
Edit: Thanks for the replies. This is a practice exercise from a website that I'm using to learn, I haven't designed it. I want to confirm that the Wolf.action(self) is an static call and ask why would you make Wolf inherit from Animal if you c... | self need in call to parent class by name when using multi inheritance | Edit: Thanks for the replies. This is a practice exercise from a website that I'm using to learn, I haven't designed it. I want to confirm that the Wolf.action(self) is an static call and ask why would you make Wolf inherit from Animal if you can only use Dog Class' methods with super() due to MRO (in Diamond scheme). ... | [
"Wolf.action is the actual function, not a bound method that implicitly includes self when you try to call it.\nHowever, if you use super properly, you don't need an explicit call to Wolf.action.\nclass Animal:\n def __init__(self, name):\n self.name = name\n\n def action(self):\n pass\n \nclass Dog(Anima... | [
1
] | [] | [] | [
"class",
"python",
"self"
] | stackoverflow_0074504782_class_python_self.txt |
Q:
How to set the `xpath` of pandas's read_xml?
I want to parse data from a xml file of its Component part:
<Component>
<UnderlyingSecurityID>300001</UnderlyingSecurityID>
<UnderlyingSecurityIDSource>102</UnderlyingSecurityIDSource>
<UnderlyingSymbol>特锐德</UnderlyingSymbol>
<ComponentShare>300.00</ComponentSha... | How to set the `xpath` of pandas's read_xml? | I want to parse data from a xml file of its Component part:
<Component>
<UnderlyingSecurityID>300001</UnderlyingSecurityID>
<UnderlyingSecurityIDSource>102</UnderlyingSecurityIDSource>
<UnderlyingSymbol>特锐德</UnderlyingSymbol>
<ComponentShare>300.00</ComponentShare>
<SubstituteFlag>1</SubstituteFlag>
<Premiu... | [
"So in short the solution here is to figure out which node you want, in this case the Component (case-sensitive), and set the xpath as follows adding //.\npd.read_xml(your_xml_file, xpath='//Component')\n\n",
"You can use xml.etree.ElementTree, instead of pd.xml_read():\nimport xml.etree.ElementTree as ET\nimport... | [
0,
0
] | [] | [] | [
"pandas",
"python",
"xml"
] | stackoverflow_0068281666_pandas_python_xml.txt |
Q:
I had a problem with python library pikepdf
When trying to install the python moduel pikepdf using pip, this error pops up:
Building wheels for collected packages: pikepdf
Building wheel for pikepdf (pyproject.toml) ... error
error: subprocess-exited-with-error
× Building wheel for pikepdf (pyproject.toml) ... | I had a problem with python library pikepdf | When trying to install the python moduel pikepdf using pip, this error pops up:
Building wheels for collected packages: pikepdf
Building wheel for pikepdf (pyproject.toml) ... error
error: subprocess-exited-with-error
× Building wheel for pikepdf (pyproject.toml) did not run successfully.
│ exit code: 1
╰─> ... | [
"Just list all versions available for pidepdf:\npip index versions pikepdf\n\nPick one and install it:\npip install pikepdf==5.6.1\n\nCheck back in a later version whether this is resolved.\nIssues like these can be reported in their tracker: https://github.com/pikepdf/pikepdf/issues\nThe problem listed is known. F... | [
1,
0
] | [] | [] | [
"pikepdf",
"python"
] | stackoverflow_0069686925_pikepdf_python.txt |
Q:
Split and convert str to int
I'm making a shopping cart list, where the products are added and identified by their codes.
The system has to add, remove, show and checkout.
Show and checkout commands are working fine.
Add is working fine too, but it has a particularity: it´s mandatory to add with "Add 15", "Add 70"... | Split and convert str to int | I'm making a shopping cart list, where the products are added and identified by their codes.
The system has to add, remove, show and checkout.
Show and checkout commands are working fine.
Add is working fine too, but it has a particularity: it´s mandatory to add with "Add 15", "Add 70" (whatever other number). I can't ... | [
"You forgot to change the type of \"command[1]\" in the if. The following code works:\ncart = []\nwhile True:\n command = str(input(\"Command: \")).split()\n if \"add\" in command:\n cart.append(int(command[1]))\n elif \"remove\" in command:\n if int(command[1]) in cart: # There you forgot to... | [
3,
0
] | [] | [] | [
"integer",
"list",
"python",
"string"
] | stackoverflow_0074504776_integer_list_python_string.txt |
Q:
Not sure of the Print Structure with YouTube v3 API
So I was creating a script to list information from Google's V3 YouTube API and I used the structure that was shown on their Site describing it, so I'm pretty sure I'm misunderstanding something.
I tried using the structure that was shown to print JUST the Video'... | Not sure of the Print Structure with YouTube v3 API | So I was creating a script to list information from Google's V3 YouTube API and I used the structure that was shown on their Site describing it, so I'm pretty sure I'm misunderstanding something.
I tried using the structure that was shown to print JUST the Video's Title as a test
and was expecting that to print, howev... | [
"you need to access the keys in the dictionary separately.\nimport sys, json, requests\n\nvidCode = input('\\nVideo Code Here: ')\n\nurl = requests.get(f'https://youtube.googleapis.com/youtube/v3/videos?part=snippet%2CcontentDetails%2Cstatistics&id={vidCode}&key=(not sharing the api key, lol)')\ntext = url.text\n\n... | [
0
] | [] | [] | [
"google_api",
"json",
"python",
"python_3.x",
"youtube_api"
] | stackoverflow_0074504824_google_api_json_python_python_3.x_youtube_api.txt |
Q:
Discord.py music bot Wavelink error: `TypeError: Type must meet VoiceProtocol abstract base class.`
The print:
0|Runa | <class 'wavelink.player.Player'>
The error:
0|Runa | vc:wavelink.Player=await ctx.author.voice.channel.connect(cls= wavelink.Player)
0|Runa | File "/usr/local/lib/python3.8/dist... | Discord.py music bot Wavelink error: `TypeError: Type must meet VoiceProtocol abstract base class.` | The print:
0|Runa | <class 'wavelink.player.Player'>
The error:
0|Runa | vc:wavelink.Player=await ctx.author.voice.channel.connect(cls= wavelink.Player)
0|Runa | File "/usr/local/lib/python3.8/dist-packages/nextcord/abc.py", line 1683, in connect
0|Runa | raise TypeError("Type must meet VoiceP... | [
"I had the same issue, you need to run below for voice support:\nLinux/macOS\npython3 -m pip install -U \"discord.py[voice]\"\nWindows\npy -3 -m pip install -U discord.py[voice]\nthis resolved the issue for me. I'm using nextcord, so used below:\nLinux/macOS\npython3 -m pip install -U \"nextcord[voice]\"\nWindows\n... | [
0
] | [] | [] | [
"audio_player",
"discord",
"discord.py",
"python",
"voice"
] | stackoverflow_0074451569_audio_player_discord_discord.py_python_voice.txt |
Q:
On Matplotlib on python, how do I put a red circle on a specific point?
My code I currently have is below, I want to put a filled in red circle where I have the plt.text below. How would I do that?
plt.plot('Month', 'Total Profit', data=fruit_sales_df, color='g', ls='--')
plt.ylim(35000, 74999)
plt.text(11, 70476,... | On Matplotlib on python, how do I put a red circle on a specific point? | My code I currently have is below, I want to put a filled in red circle where I have the plt.text below. How would I do that?
plt.plot('Month', 'Total Profit', data=fruit_sales_df, color='g', ls='--')
plt.ylim(35000, 74999)
plt.text(11, 70476, '70476')
plt.title("Total Profit Trend by Month")
plt.xlabel("Month")
plt.yl... | [
"Meaning just a point? You can add data consisting of one point only.\nimport matplotlib.pyplot as plt\n\nplt.plot([1, 2], [3, 4], color='g', ls='--')\nplt.text(1.5, 3.7, '70476')\nplt.plot(1.5, 3.5, color='red', marker='o')\nplt.title(\"Total Profit Trend by Month\")\nplt.xlabel(\"Month\")\nplt.ylabel(\"Total Prof... | [
2,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074504770_matplotlib_python.txt |
Q:
Python prime number calculator
prime = [2]
while len(prime) <= 1000:
i=3
a = 0
for number in prime:
testlist= []
testlist.append(i%number)
if 0 in testlist:
i=i+1
else:
prime.append(i)
i=i+1
print(prime[999])
Trying to make a program that computes primes... | Python prime number calculator | prime = [2]
while len(prime) <= 1000:
i=3
a = 0
for number in prime:
testlist= []
testlist.append(i%number)
if 0 in testlist:
i=i+1
else:
prime.append(i)
i=i+1
print(prime[999])
Trying to make a program that computes primes for online course. This program nev... | [
"As the comments to your question pointed out, there is several errors in your code.\nHere is a version of your code working fine.\nprime = [2]\ni = 3\nwhile len(prime) <= 1000:\n testlist = []\n for number in prime:\n testlist.append(i % number)\n if 0 not in testlist:\n prime.append(i)\n ... | [
2,
0,
0
] | [] | [] | [
"conditional",
"list",
"python"
] | stackoverflow_0024252934_conditional_list_python.txt |
Q:
Problem with making .exe from python file by PyInstaller
My script .py work perfectly, but .exe sadly doesn't work. Im running on newest PyInstaller.
Here is my script
I already tried everyting that i can think of here is options that i used:
Options used
-w : does't have .exe file
-- onefile -w and -F -w : The... | Problem with making .exe from python file by PyInstaller | My script .py work perfectly, but .exe sadly doesn't work. Im running on newest PyInstaller.
Here is my script
I already tried everyting that i can think of here is options that i used:
Options used
-w : does't have .exe file
-- onefile -w and -F -w : The specified module could not be found.
--F , --onefile and no ... | [
"Not all python code can be compiled into a .exe.\n",
"I was able to work around this issue by importing pywintypes into my script before win32print module.\n"
] | [
0,
0
] | [] | [] | [
"exe",
"pyinstaller",
"python",
"python_3.x",
"pywin32"
] | stackoverflow_0074504169_exe_pyinstaller_python_python_3.x_pywin32.txt |
Q:
How to ignore duplicate keys using the psycopg2 copy_from command copying .csv file into postgresql database
I'm using Python. I have a daily csv file that I need to copy daily into a postgresql table. Some of those .csv records may be same day over day so I want to ignore those, based on a primary key field. Us... | How to ignore duplicate keys using the psycopg2 copy_from command copying .csv file into postgresql database | I'm using Python. I have a daily csv file that I need to copy daily into a postgresql table. Some of those .csv records may be same day over day so I want to ignore those, based on a primary key field. Using cursor.copy_from,Day 1 all is fine, new table created. Day 2, copy_from throws duplicate key error (as it sho... | [
"This is how I'm doing it with psycopg3.\nAssumes the file is in the same folder as the script and that it has a header row.\nfrom pathlib import Path\nfrom psycopg import sql\n\nfile = Path(__file__).parent / \"the_data.csv\"\ntarget_table = \"mytable\"\nconn = <your connection>\n\nwith conn.cursor() as cur:\n\n ... | [
0
] | [] | [] | [
"postgresql",
"psycopg2",
"python"
] | stackoverflow_0073200153_postgresql_psycopg2_python.txt |
Q:
Python Openpyxl Copy Data From Rows Based on Cell Value& Paste In Specific Rows of ExcelSheet
I am trying to copy data by rows based on Column ['A'] cell value from one sheet and paste in row2 of another sheet. The paste in sheet is an existing worksheet, row 1 of the worksheet is my header row so i want to paste... | Python Openpyxl Copy Data From Rows Based on Cell Value& Paste In Specific Rows of ExcelSheet | I am trying to copy data by rows based on Column ['A'] cell value from one sheet and paste in row2 of another sheet. The paste in sheet is an existing worksheet, row 1 of the worksheet is my header row so i want to paste the copied data starting from row2. I do not want to append as I have existing formula columns in ... | [
"There seems to be some inconsistencies in your code e.g.\nwb_cpy = load_workbook(r'C:\\Users\\me\\documents\\sourcefolder\\copyfromfile.xlsx')\nws = wb_src[\"sheet1\"]\n\nws is referencing a workbook object different to that just created or indeed does not appear to exist anywhere in your code. Similar with the ne... | [
1
] | [] | [] | [
"openpyxl",
"python"
] | stackoverflow_0074448799_openpyxl_python.txt |
Q:
Django migration not applied to the DB
I had an Django2.2.3 app, it was working fine. But I had to chane the name of a field in a table, and add another field. Then I ran ./manage.py makemigrations && ./manage.py migrate. Besides the terminal prompt:
Running migrations:
No migrations to apply.
No error is throw... | Django migration not applied to the DB | I had an Django2.2.3 app, it was working fine. But I had to chane the name of a field in a table, and add another field. Then I ran ./manage.py makemigrations && ./manage.py migrate. Besides the terminal prompt:
Running migrations:
No migrations to apply.
No error is throwed. But then when I go to the MySQLWorkbench... | [
"Make sure the app with the migrations is in the INSTALLED_APPS. Django won't look at the app for changes otherwise.\n",
"Adding new few fields to an existing model (table) is one reason for this problem. A way to go about this is simply as follows:\na) un-apply the migrations for that app:\npython3 manage.py mig... | [
0,
0
] | [] | [] | [
"django",
"migration",
"mysql",
"python"
] | stackoverflow_0065929264_django_migration_mysql_python.txt |
Q:
Problem with python logging.handlers.SMTPHandler, 'credentials' not recognized as attribute of SMTPHandler
I'm trying to set up email logging of critical errors in my python application. I keep running into an error trying to initialize the SMTPHandler:
AttributeError: 'SMTPHandler' object has no attribute 'creden... | Problem with python logging.handlers.SMTPHandler, 'credentials' not recognized as attribute of SMTPHandler | I'm trying to set up email logging of critical errors in my python application. I keep running into an error trying to initialize the SMTPHandler:
AttributeError: 'SMTPHandler' object has no attribute 'credentials'
I'm using Python 3.10. I carved out a component of the program where I'm getting the error.
import loggin... | [
"You have the full source code for all of the standard modules on your computer. I just took a quick look, and although the SMTPHandler accepts a credentials argument, it stores that argument in self.username and self.password.\n"
] | [
0
] | [] | [] | [
"credentials",
"python"
] | stackoverflow_0074504966_credentials_python.txt |
Q:
How to remove characters from string?
How to remove user defined letters from a user defined sentence in Python?
Hi, if anyone is willing to take the time to try and help me out with some python code.
I am currently doing a software engineering bootcamp which the current requirement is that I create a program wher... | How to remove characters from string? | How to remove user defined letters from a user defined sentence in Python?
Hi, if anyone is willing to take the time to try and help me out with some python code.
I am currently doing a software engineering bootcamp which the current requirement is that I create a program where a user inputs a sentence and then a user ... | [
"If I understood correctly we can use str.maketrans and str.translate methods here like\nfrom itertools import repeat\n\nsentence1 = sentence.translate(str.maketrans(dict(zip(letters, repeat(None)))))\n\nWhat this does line by line:\n\ncreate mapping of letters to None which will be interpreted as \"remove this cha... | [
3,
2,
2,
2
] | [
"user_word = input(\"What is your prefered sentence? \") \n\nuser_letter_to_remove = input(\"which letters would you like to delete? \")\n\n#list of letter to remove\n\nletters =str(user_letter_to_remove)\n\nfor i in letters:\n user_word = user_word.replace(i,\"\")\n\nprint(user_word)\n\n"
] | [
-1
] | [
"python",
"regex",
"replace",
"string",
"strip"
] | stackoverflow_0055747901_python_regex_replace_string_strip.txt |
Q:
Data Science Data Analysis - How to derive an equation for this Y variable?
I am using gradient boosting algorithm to predict some 'Y' parameter.
How to derive an equation for this Y independent variable?
Interestingly, I have looked through many GB-tutorials in the Internet but none of them showed how to derive a... | Data Science Data Analysis - How to derive an equation for this Y variable? | I am using gradient boosting algorithm to predict some 'Y' parameter.
How to derive an equation for this Y independent variable?
Interestingly, I have looked through many GB-tutorials in the Internet but none of them showed how to derive an equation for this Y independent variable also I didn't find how to print summar... | [
"First things first, in the standard terminology of ML (where {X, y} refer to your training data and y is what your model is trying to predict), X are called the independent variables and y is called the dependent variable. With that out of the way, here is my 2 cents on the \"equation of the dependent variable via... | [
0
] | [] | [] | [
"data_science",
"ensemble_learning",
"machine_learning",
"python",
"regression"
] | stackoverflow_0074504886_data_science_ensemble_learning_machine_learning_python_regression.txt |
Q:
Error when installing Ctypes package into python
I get an error when trying to install ctypes package in python 3.10.8. I tried every solution I could find but nothing worked.
I tried using
pip install ctypes
I also tried using another name in case they changed the name
pip install ctype
A:
The ctypes module ava... | Error when installing Ctypes package into python | I get an error when trying to install ctypes package in python 3.10.8. I tried every solution I could find but nothing worked.
I tried using
pip install ctypes
I also tried using another name in case they changed the name
pip install ctype
| [
"The ctypes module available on PyPI was last released in May, 2007. It is ancient.\nctypes has been bundled with Python since version 2.5. You don't need to install it separately. Just use it.\n"
] | [
2
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074504993_python_python_3.x.txt |
Q:
Include files in Sphinx output on any path
I have a project that I'm documenting where I've ended up with a structure like
docs/
conf.py
development/
architecture.rst
uimockups/
index.html
static/
<supporting css and js files>
mockup1/
index.html
... | Include files in Sphinx output on any path | I have a project that I'm documenting where I've ended up with a structure like
docs/
conf.py
development/
architecture.rst
uimockups/
index.html
static/
<supporting css and js files>
mockup1/
index.html
ui1.html
ui2.html
mockup2/
... | [
"Well, I figured out a solution, but it isn't what I'd consider the best solution.\nSince I wanted to be able to also do python -m http.server in the docs/development/uimockups folder and have it work, I ended up:\n\nRenaming docs/development/uimockups/static to docs/development/uimockups/_static.\nChanging all .ht... | [
1,
0
] | [] | [] | [
"python",
"python_sphinx"
] | stackoverflow_0048544965_python_python_sphinx.txt |
Q:
Unable to install AWS Elastic Beanstalk CLI (Win10, Python 3.6, Pip 9.0.1)
I am trying to install awsebcli on my machine and I am unable to run the command
eb --version
It shows this error:
'eb' is not recognized as an internal or external command,
operable program or batch file.
This is my Python version:
C:\>py... | Unable to install AWS Elastic Beanstalk CLI (Win10, Python 3.6, Pip 9.0.1) | I am trying to install awsebcli on my machine and I am unable to run the command
eb --version
It shows this error:
'eb' is not recognized as an internal or external command,
operable program or batch file.
This is my Python version:
C:\>python --version
Python 3.6.0
This is my pip version:
C:\>pip --version
pip 9.0.1... | [
"After a great deal of running around I managed to figure out that I was missing an additional PATH entry, both of these were required to get eb to run on windows:\n%USERPROFILE%\\AppData\\Local\\Programs\\Python\\Python36\\Scripts\n%USERPROFILE%\\AppData\\Roaming\\Python\\Python36\\Scripts\n\nNOTE: If you have Pyt... | [
33,
17,
8,
4,
3,
1,
0,
0,
0
] | [] | [] | [
"amazon_elastic_beanstalk",
"amazon_web_services",
"python"
] | stackoverflow_0041729006_amazon_elastic_beanstalk_amazon_web_services_python.txt |
Q:
Difficulty instantiating a subclass [object has no attribute]
I get two types of errors when I try to start or initiate the member function temp_controll from the subclass Temperature_Controll. The issue is that the while loops are started in a new thread.
I am having trouble passing the modbus client connection t... | Difficulty instantiating a subclass [object has no attribute] | I get two types of errors when I try to start or initiate the member function temp_controll from the subclass Temperature_Controll. The issue is that the while loops are started in a new thread.
I am having trouble passing the modbus client connection to the member function.
AttributeError: 'ModbusTcpClient' object ha... | [
"You get this error:\n AttributeError: 'ModbusTcpClient' object has no attribute 'modbus'\n\nbecause when the Thread that you create:\nt2 = threading.Thread(target=control, args=(client, 'get'))\ncalls Temperature_Controll2.temp_controll(client, 'get'),\non this line: rp = self.modbus.read_coils(524, 0x1) the self ... | [
0,
0,
0
] | [] | [] | [
"class",
"inheritance",
"member_functions",
"python",
"python_multithreading"
] | stackoverflow_0074501121_class_inheritance_member_functions_python_python_multithreading.txt |
Q:
Pandas groupby - divide by the sum of all groups
I have a DataFrame df and I create gb = df.groupby("column1"). Now I would like to do the following:
x = gb.apply(lambda x: x["column2"].sum() / df["column2"].sum())
It works but I would like to based everytinh on x not x and df. Ideally I expected that there is a f... | Pandas groupby - divide by the sum of all groups | I have a DataFrame df and I create gb = df.groupby("column1"). Now I would like to do the following:
x = gb.apply(lambda x: x["column2"].sum() / df["column2"].sum())
It works but I would like to based everytinh on x not x and df. Ideally I expected that there is a function x.get_source_df and then my solution would be:... | [
"you should not use apply here, may be you find it interesting, optimal method would be\ndf.groupby('column1')['column2'].sum().div(df['column2'].sum())\n\nIt works for more than one column too.\n",
"I am not sure in your explanation that you want to divide for the sum of each group or divide for the sum of the e... | [
0,
0
] | [] | [] | [
"group_by",
"pandas",
"python"
] | stackoverflow_0074500059_group_by_pandas_python.txt |
Q:
How to add a 1d array to a 2d array element-wise to get a 3d array in numpy
I have a 2d array of values, and I want to add a 1d array to this 2d array element wise such that I would get a 3d array where each element is the original 2d array plus a respective element of the 1d array. For example:
A = np.array([
... | How to add a 1d array to a 2d array element-wise to get a 3d array in numpy | I have a 2d array of values, and I want to add a 1d array to this 2d array element wise such that I would get a 3d array where each element is the original 2d array plus a respective element of the 1d array. For example:
A = np.array([
[10, 9, 8, 7, 6],
[5, 4, 3, 2, 1]
])
B = np.array([1, 2, 3])
#What A + B sh... | [
"I believe this gives you the output you're after?\nimport numpy as np\n\nA = np.array([\n [10, 9, 8, 7, 6],\n [5, 4, 3, 2, 1]\n])\nB = np.array([1, 2, 3])\n\nA = A.reshape(1, 2, 5)\nB = B.reshape(3, 1, 1)\n\nfor each in A + B:\n print (each)\n \n# Result:\n # [[11 10 9 8 7]\n # [ 6 5 4 3 ... | [
0,
0,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074504800_numpy_python.txt |
Q:
error using np.argmax when applying keepdims
I am running my Python code and recieving this error on keepdims:
enter image description here
This is the code:
enter image description here
It worked fine to run this command on my computer a few days ago but I have ran other codes etc after that might have done somet... | error using np.argmax when applying keepdims | I am running my Python code and recieving this error on keepdims:
enter image description here
This is the code:
enter image description here
It worked fine to run this command on my computer a few days ago but I have ran other codes etc after that might have done something.
It works to write keepdims on amax, just not... | [
"For an array x, a simple way to replicate the behavior of np.argmax(x, axis=0, keepdims=True) is np.argmax(x, axis=0)[np.newaxis, ...]. Note that this is specifically for the case axis=0.\nOther alternatives include np.expand_dims(np.argmax(x, axis=0), 0) and np.argmax(x, axis=0).reshape((1,) + x.shape[1:]).\nFor ... | [
0
] | [] | [] | [
"argmax",
"numpy",
"python"
] | stackoverflow_0074501160_argmax_numpy_python.txt |
Q:
Bs4 fail when try to get next url
There is my code
def parser():
flag = True
url = 'https://quotes.toscrape.com'
while flag:
responce = requests.get(url)
soup = BeautifulSoup(responce.text, 'html.parser')
quote_l = soup.find_all('span', {'class': 'text'})
q_count = 0
... | Bs4 fail when try to get next url | There is my code
def parser():
flag = True
url = 'https://quotes.toscrape.com'
while flag:
responce = requests.get(url)
soup = BeautifulSoup(responce.text, 'html.parser')
quote_l = soup.find_all('span', {'class': 'text'})
q_count = 0
for i in range(len(quote_l)):
... | [
"Upon reaching the last page there will be no Next button so you need an exit condition check prior to attempting to access the href for next page. One possibility would be to add the following lines before your current last line:\nnext_page = soup.find('li', {'class': 'next'})\nif not next_page: flag = False # or... | [
0
] | [] | [] | [
"beautifulsoup",
"html_parsing",
"parsing",
"python"
] | stackoverflow_0074503332_beautifulsoup_html_parsing_parsing_python.txt |
Q:
Random array generation using Numba wrapper
Suppose I want to generate an array using njit which is a library of Numba. The following approach is throwing an error and I have no idea why. I followed this from speed up function that takes a function as argument with numba.
import numpy as np
from numba import pran... | Random array generation using Numba wrapper | Suppose I want to generate an array using njit which is a library of Numba. The following approach is throwing an error and I have no idea why. I followed this from speed up function that takes a function as argument with numba.
import numpy as np
from numba import prange, njit
def numpy_random(n):
return np.ran... | [
"To clarify the error, Numba basically reports No implementation of function [...] found for signature normal(size=int64) and then unsupported call signature. Thus, Numba does not support calling normal with a size attribute. This is actually documented.\nA simple way to reproduce the error is to execute this code... | [
1
] | [] | [] | [
"numba",
"numpy",
"python"
] | stackoverflow_0074505047_numba_numpy_python.txt |
Q:
passing input between multiple functions?
im currently trying to pass input between multiple functions. As of now im having an extremely hard time figuring out how to do it with my program. My program consists of 2 functions. main() will get the user input, remove all punctuation and capital() will take that outpu... | passing input between multiple functions? | im currently trying to pass input between multiple functions. As of now im having an extremely hard time figuring out how to do it with my program. My program consists of 2 functions. main() will get the user input, remove all punctuation and capital() will take that output and turn it into all caps. However, when i ca... | [
"The reason this might be happening is because you are calling main() prior to assignment, which does not work on some versions of python if I remember correctly. You could update to a newer version, but a better way is to use parameters like you explained.\nTo make a parameter, you could have your capital() functi... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074505140_python.txt |
Q:
I can not understand why my test and predict y plot for my regression model is like that?
I am working on a regression model (Decision Tree) on a multidimensional data, with 16 features. The model r2_score is 0.97. The y test and y predict plot looks so wrong! the range of x is not the same.
would you please tel... | I can not understand why my test and predict y plot for my regression model is like that? | I am working on a regression model (Decision Tree) on a multidimensional data, with 16 features. The model r2_score is 0.97. The y test and y predict plot looks so wrong! the range of x is not the same.
would you please tell me what is the problem?
I have also tried to fit the model in one dimension to check the x ra... | [
"Matplotlib's plot function draws a single line by connecting the points in the order that they are drawn. The reason you are seeing a mess is because the points are not ordered along the x-axis.\nIn a regression model, you have a function f(x) -> R where f here is your decision tree and x is in the 16 dimensional ... | [
1
] | [] | [] | [
"decision_tree",
"machine_learning",
"matplotlib",
"python",
"regression"
] | stackoverflow_0074505098_decision_tree_machine_learning_matplotlib_python_regression.txt |
Q:
Runge Kutta constants diverging for Lorenz system?
I'm trying to solve the Lorenz system using the 4th order Runge Kutta method, where
dx/dt=a*(y-x)
dy/dt=x(b-z)-y
dx/dt=x*y-c*z
Since this system doesn't depend explicity on time, it's possibly to ignore that part in the iteration, so I just have
dX=F(x,y,z)
def f... | Runge Kutta constants diverging for Lorenz system? | I'm trying to solve the Lorenz system using the 4th order Runge Kutta method, where
dx/dt=a*(y-x)
dy/dt=x(b-z)-y
dx/dt=x*y-c*z
Since this system doesn't depend explicity on time, it's possibly to ignore that part in the iteration, so I just have
dX=F(x,y,z)
def func(x0):
a=10
b=38.63
c=8/3
fx=a*(x0[1]-... | [
"You have an extra call of f(x0) in the calculation of k1, k2 and k3. Change the function kcontants to\ndef kcontants(f,h,x0):\n k0=h*f(x0)\n k1=h*f(x0 + k0/2)\n k2=h*f(x0 + k1/2)\n k3=h*f(x0 + k2)\n #note returned K is a matrix\n return np.array([k0,k1,k2,k3])\n\n",
"Have you looked at differe... | [
1,
0,
0
] | [] | [] | [
"lorenz_system",
"numerical_methods",
"python",
"runge_kutta"
] | stackoverflow_0055884705_lorenz_system_numerical_methods_python_runge_kutta.txt |
Q:
sklearn Cross validation scoring , scores are all nan
I'm trying to make a multiclass classification here and the score from the cross validaiton are all nan
Below the code which works perfectly for binary classifcation
when i only keep accuracy and balanced_accuracy it shows the actual score when i add f1 or prec... | sklearn Cross validation scoring , scores are all nan | I'm trying to make a multiclass classification here and the score from the cross validaiton are all nan
Below the code which works perfectly for binary classifcation
when i only keep accuracy and balanced_accuracy it shows the actual score when i add f1 or precison or recall all scores turns into nan
the problem that m... | [
"For precision_score, recall_score and f1_score, I think you can try using parameter average = micro (or macro and weighted) for multiple targets. Because its default value is binary.\n"
] | [
1
] | [] | [] | [
"classification",
"machine_learning",
"multilabel_classification",
"python",
"scikit_learn"
] | stackoverflow_0074505106_classification_machine_learning_multilabel_classification_python_scikit_learn.txt |
Q:
Best way to flatten and remap ORM to Pydantic Model
I am using Pydantic with FastApi to output ORM data into JSON. I would like to flatten and remap the ORM model to eliminate an unnecessary level in the JSON.
Here's a simplified example to illustrate the problem.
original output: {"id": 1, "billing":
... | Best way to flatten and remap ORM to Pydantic Model | I am using Pydantic with FastApi to output ORM data into JSON. I would like to flatten and remap the ORM model to eliminate an unnecessary level in the JSON.
Here's a simplified example to illustrate the problem.
original output: {"id": 1, "billing":
[
{"id": 1, "order_id": 1,... | [
"What if you override the from_orm class method?\nclass Order(BaseModel):\n id: int\n name: List[str] = None\n billing: List[Billing]\n\n class Config:\n orm_mode = True\n\n @classmethod\n def from_orm(cls, obj: Any) -> 'Order':\n # `obj` is the orm model instance\n if hasattr... | [
10,
1
] | [] | [] | [
"fastapi",
"nested",
"pydantic",
"python",
"sqlalchemy"
] | stackoverflow_0068850403_fastapi_nested_pydantic_python_sqlalchemy.txt |
Q:
MovingSum of list of integers
I want to calculate the moving sum of a list of integers with a window of size 3. I have a class as such:
class MovingSum:
def __init__(self, window=3):
self.window = window
def push(self, nums: List[int]):
pass
def belongs(self, total) -> bool:
... | MovingSum of list of integers | I want to calculate the moving sum of a list of integers with a window of size 3. I have a class as such:
class MovingSum:
def __init__(self, window=3):
self.window = window
def push(self, nums: List[int]):
pass
def belongs(self, total) -> bool:
pass
I need to calculate the movi... | [
"If I understand you correctly, you have a constant stream of numbers coming in, and you want the total of each n-item window (which I'll call a group) within that. So, you'll need a list of totals of all the groups so far, and you'll need to keep track of the running total of the items within the current (partial)... | [
1
] | [] | [] | [
"array_algorithms",
"python"
] | stackoverflow_0074505125_array_algorithms_python.txt |
Q:
Why merging 2 data frames gives me one with triple the rows
I have df1:
x y no.
0 -17.7 -0.785430 y1
1 -15.0 -3820.085000 y4
2 -12.5 2.138833 y3
.. .... ........ ..
40 15.6 5.486901 y2
41 19.2 1.980686 y3
42 19.6 9.364718 y2
and df2:
delta y x
0 ... | Why merging 2 data frames gives me one with triple the rows | I have df1:
x y no.
0 -17.7 -0.785430 y1
1 -15.0 -3820.085000 y4
2 -12.5 2.138833 y3
.. .... ........ ..
40 15.6 5.486901 y2
41 19.2 1.980686 y3
42 19.6 9.364718 y2
and df2:
delta y x
0 0.053884 -17.7
1 0.085000 -15.0
2 0.143237 -12.5
.. ... | [
"try the following: df1.join(df2)\njoin is a column-wise left join\npd.merge is a column-wise inner join\npd.concat is a row-wise outer join\npd.concat:\ntakes Iterable arguments. Thus, it cannot take DataFrames directly (use [df,df2])\nDimensions of DataFrame should match along axis\nJoin and pd.merge:\ncan take D... | [
1,
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074504496_dataframe_pandas_python.txt |
Q:
Python: Sort dictionary keys case-insensitive and return the dictionary in the same format unchanged
I'm new to Python3 and I'm not fully aware of all its useful functions yet.
I have the following dictionary:
my_dict = {'david': ('18', 'Paris', '253-345-5434'), 'Joe': ('19', 'Dubai', '675-353-2345'), 'Luc': ('31'... | Python: Sort dictionary keys case-insensitive and return the dictionary in the same format unchanged | I'm new to Python3 and I'm not fully aware of all its useful functions yet.
I have the following dictionary:
my_dict = {'david': ('18', 'Paris', '253-345-5434'), 'Joe': ('19', 'Dubai', '675-353-2345'), 'Luc': ('31', 'Istanbul', '766-673-3451')}
the dictionary keys are strings and each key has a tuple value that contai... | [
"from collections import OrderedDict\n...\nprint(\n OrderedDict(sorted(my_dict.items()))\n)\n\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074505148_python_python_3.x.txt |
Q:
getting error : ModuleNotFoundError: No module named 'trialrisk.urls' in python
I'm new here in django python, right now I'm working with rest api, So I have created new app trialrisk, first i have added my app in settings.py file, After then when I am trying to add url in urls.py file I'm getting an error : Modul... | getting error : ModuleNotFoundError: No module named 'trialrisk.urls' in python | I'm new here in django python, right now I'm working with rest api, So I have created new app trialrisk, first i have added my app in settings.py file, After then when I am trying to add url in urls.py file I'm getting an error : ModuleNotFoundError: No module named 'trialrisk.urls' in python, Here I have added the who... | [
"There is no urls.py file in trialrisk folder. Create the same in trialrisk folder and import from it.\n",
"In addition to adding urls.py to trialrisk, you'll also have to add a urlpatterns object to it e.g. urlpatterns = [], or you'll get an error like this\nraise ImproperlyConfigured(msg.format(name=self.urlcon... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0059099801_django_python.txt |
Q:
How can I have a query set in the DetailView?
Field 'id' expected a number but got <django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x1024f3c70>.
This is the error message and
class ProductDetail(DetailView):
model = Product
def get_context_data(self, **kwargs):
context =... | How can I have a query set in the DetailView? | Field 'id' expected a number but got <django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x1024f3c70>.
This is the error message and
class ProductDetail(DetailView):
model = Product
def get_context_data(self, **kwargs):
context = super(ProductDetail, self).get_context_data()
... | [
"You access the object with self.object, so:\nclass ProductDetail(DetailView):\n model = Product\n\n def get_context_data(self, *args, **kwargs):\n context = super().get_context_data(*args, **kwargs)\n context['related_products'] = Product.objects.filter(\n category_id=self.object.cat... | [
1
] | [] | [] | [
"django",
"django_views",
"python"
] | stackoverflow_0074505326_django_django_views_python.txt |
Q:
group or unpivot df not considering empty values
I have a df like this :
PRODUCTNUMBER
Jerarquía principal
Jerarquía secundaria marcas
COT
Ecommerce
dabra-catalog
Dexter-ecommerce
Stockcenter-ecommerce
AD802309
Medias-Hombre
ADIDAS
950699
NaN
NaN
NaN
NaN
AD481076
NaN
Adidas
950699
NaN
NaN
NaN
NaN
AD481137
Medi... | group or unpivot df not considering empty values | I have a df like this :
PRODUCTNUMBER
Jerarquía principal
Jerarquía secundaria marcas
COT
Ecommerce
dabra-catalog
Dexter-ecommerce
Stockcenter-ecommerce
AD802309
Medias-Hombre
ADIDAS
950699
NaN
NaN
NaN
NaN
AD481076
NaN
Adidas
950699
NaN
NaN
NaN
NaN
AD481137
Medias-Hombre
Adidas
950699
Medias-Hombre
Medias-H... | [
"Try with melt\nout = df.melt('PRODUCTNUMBER',\n value_name='PRODUCTCATEGORYHIERARCHYNAME',\n var_name='PRODUCTCATEGORYNAME').dropna()\nOut[201]: \n PRODUCTNUMBER PRODUCTCATEGORYNAME PRODUCTCATEGORYHIERARCHYNAME\n0 AD802309 Jerarquía principal Med... | [
2,
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"pivot",
"python",
"unpivot"
] | stackoverflow_0074505019_dataframe_pandas_pivot_python_unpivot.txt |
Q:
Download or working with such Large Dataset
The size of this ML Competition dataset is very large.
Here are some issues I am facing:
My PC is not that strong to process and work with this much large dataset.
My internet connection is not that fast to download.
My drive has only 10 GB left, so can't fetch this dat... | Download or working with such Large Dataset | The size of this ML Competition dataset is very large.
Here are some issues I am facing:
My PC is not that strong to process and work with this much large dataset.
My internet connection is not that fast to download.
My drive has only 10 GB left, so can't fetch this dataset with Colab either.
Can't upload the dataset ... | [
"Use distributed system like Apache Spark framework. PySpark and Dask are very efficient to handle big data.\n"
] | [
1
] | [] | [] | [
"dataset",
"kaggle",
"machine_learning",
"python"
] | stackoverflow_0074502068_dataset_kaggle_machine_learning_python.txt |
Q:
Modify requiremet.txt file to install from private repos on heroku
I have an app deployed in Heroku , now I got a lot of private repos need to be included in requirements.txt file , I set my GitHub access token and need to put it in Heroku environment variables to be included in requirements.txt file , I already t... | Modify requiremet.txt file to install from private repos on heroku | I have an app deployed in Heroku , now I got a lot of private repos need to be included in requirements.txt file , I set my GitHub access token and need to put it in Heroku environment variables to be included in requirements.txt file , I already tried a lot to pass it but its not read by the file unless I hard code it... | [
"Choose a private repository\nFor an organization and private libraries, you have only one option, no matter the language:\nAn artifact repository.\n\nYou need to deploy it and configure it\nPush your private libraries.\nCreate a user/password and configure them in the machine where yo build your apps. Also you cou... | [
0
] | [] | [] | [
"git",
"github",
"heroku",
"python"
] | stackoverflow_0074505276_git_github_heroku_python.txt |
Q:
after making a .exe file using auto-py-to-exe it didnt run
I make a calculator. Now my desire to make a .exe file to use my python file.
so I use auto-py-to-exe and convert my script to an EXE file.
but when I run this file using mouse double click it didn't work.
My calculator code:
from tkinter import *
root = ... | after making a .exe file using auto-py-to-exe it didnt run | I make a calculator. Now my desire to make a .exe file to use my python file.
so I use auto-py-to-exe and convert my script to an EXE file.
but when I run this file using mouse double click it didn't work.
My calculator code:
from tkinter import *
root = Tk()
root.title("Calculator")
root.iconbitmap('miracle_logo_icon... | [
"Open Setting/Update & Security/Windows Security\nThen Go to \"Virus & threat protection\" then click on \"Protection history\".You will see here the list of threats removed by Windows Defender. Search your file name and then \"Allow\" the threat from here. This will add your exe to the \"Allowed Threats\" section ... | [
1
] | [
"I had the same result. Auto-py-to-exe is clearly a hack. It was written Trojans on windows defender. JUST DON'T USE IT\n"
] | [
-1
] | [
"auto_py_to_exe",
"python"
] | stackoverflow_0067930573_auto_py_to_exe_python.txt |
Q:
Python Anaconda interpreter is in a Conda environment, but the environment has not been activated
I have been using a working Anaconda install (Python 3.7) for about a year, but suddenly I'm getting this warning when I run the interpreter:
> python
Python 3.7.3 (default, Mar 27 2019, 17:13:21) [MSC v.1915 64 bit (... | Python Anaconda interpreter is in a Conda environment, but the environment has not been activated | I have been using a working Anaconda install (Python 3.7) for about a year, but suddenly I'm getting this warning when I run the interpreter:
> python
Python 3.7.3 (default, Mar 27 2019, 17:13:21) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
Warning:
This Python interpreter is in a conda environment, but the... | [
"If you receive this warning, you need to activate your environment. To do so on Windows, use the Anaconda Prompt shortcut in your Windows start menu. If you have an existing cmd.exe session that you’d like to activate conda in run:\ncall <your anaconda/miniconda install location>\\Scripts\\activate base.\n",
"I ... | [
1,
0
] | [] | [] | [
"anaconda",
"python",
"python_3.x"
] | stackoverflow_0062333071_anaconda_python_python_3.x.txt |
Q:
How can I shuffle the values of the cards and print 2 hands?
Im trying to shuffle the cards, and from the shuffled deck print out 2 hands like in poker (so 10 cards total). but rather than connecting it to the original code itself i made a seperate block that'll shuffle and get the 2 hands and dont know how to con... | How can I shuffle the values of the cards and print 2 hands? | Im trying to shuffle the cards, and from the shuffled deck print out 2 hands like in poker (so 10 cards total). but rather than connecting it to the original code itself i made a seperate block that'll shuffle and get the 2 hands and dont know how to connect it to the original code.
need to shuffle whats below and get ... | [
"I am not completely clear on your question, but as you told you are learning python, I decided to help you with some implementation that, as I hope, could inspire you and motivate to learn new coding concepts and idioms.\nSome of the features I use here are: enums, dataclasses, itertools, overriding __repr__, fstr... | [
0
] | [] | [] | [
"loops",
"python",
"shuffle"
] | stackoverflow_0074505074_loops_python_shuffle.txt |
Q:
How to create a function that converts month values into quarter using if statement in python
I need to create a function called as convert_to_qtr() that converts monthly values in the month value of data frame into quarters. Given below is the month data frame below:-
In the convert_to_qtr() function, we should ... | How to create a function that converts month values into quarter using if statement in python | I need to create a function called as convert_to_qtr() that converts monthly values in the month value of data frame into quarters. Given below is the month data frame below:-
In the convert_to_qtr() function, we should use the following if conditions:-
• If the month input is Jan-Mar, then the function returns “Q1”
•... | [
"def convert_to_quarter( month):\n months = [ 'January', 'February', 'March', 'April ', 'May', 'June', \\\n 'July', 'August', 'September', 'October', 'November', 'December']\n return months.index[ 'month'] // 3\n\n",
"Try the following:\ndef convert_to_quarterly(excl_merged):\n if excl_merged['Mo... | [
1,
0,
0,
0,
0
] | [] | [] | [
"function",
"pandas",
"python"
] | stackoverflow_0074503136_function_pandas_python.txt |
Q:
TypeError: descriptor 'append' for 'list' objects doesn't apply to a 'str' object. Iterating through a folder and return a list in python
this is my first time trying to write a script on my own and I'm trying to make something that looks through my folders and return a list, and I'm keep getting this TypeError: d... | TypeError: descriptor 'append' for 'list' objects doesn't apply to a 'str' object. Iterating through a folder and return a list in python | this is my first time trying to write a script on my own and I'm trying to make something that looks through my folders and return a list, and I'm keep getting this TypeError: descriptor 'append' for 'list' objects doesn't apply to a 'str' object
anyone have any ideas? Thank you so much!
import os
path = input("Where ... | [
"You're misusing append() a bit - how should that method now to which list to append the values? You either have to specify the list myFolder as the first argument (list.append(myFolder, f)) or, a bit cleaner, call append() on the instance: myFolder.append(f)\nYou can read up a bit more on the details in the docs h... | [
0
] | [] | [] | [
"list",
"python",
"python_3.x"
] | stackoverflow_0074505317_list_python_python_3.x.txt |
Q:
Having trouble with python3 print syntax
I've started to learn python about 4 days ago. To practice, I've decided to make a program that calculates combinations.
Here is the code:
print('Insert values for your combination (Cp,n)')
def combin(exemplo):
print('insert p value')
p = int(input())
print('ins... | Having trouble with python3 print syntax | I've started to learn python about 4 days ago. To practice, I've decided to make a program that calculates combinations.
Here is the code:
print('Insert values for your combination (Cp,n)')
def combin(exemplo):
print('insert p value')
p = int(input())
print('insert n value')
n = int(input())
exemplo... | [
"Hey nothing to worry about, its just a typo with missing parenthesis\nhope you find the solution :)\nres = int(exemplo[0]/(fator(exemplo[0]-exemplo[1])*fator(exemplo[1]))\n\n",
"Hey in the following line:\nres = int(exemplo[0]/(fator(exemplo[0]-exemplo[1])*fator(exemplo[1]))\n\nyou are missing a closing bracket.... | [
1,
0,
0
] | [] | [] | [
"printing",
"python",
"syntax"
] | stackoverflow_0074505077_printing_python_syntax.txt |
Q:
create pairs of vectors based on if the value of the first element of 1 vector is equal to the same element in the other vector
I have an array that has 17k+ vectors with 3 elements in each vector.
Each vector has a value for MovieTitle, AverageRating and CountRating, see example vector below:
vector = [MovieTitle... | create pairs of vectors based on if the value of the first element of 1 vector is equal to the same element in the other vector | I have an array that has 17k+ vectors with 3 elements in each vector.
Each vector has a value for MovieTitle, AverageRating and CountRating, see example vector below:
vector = [MovieTitle AverageRating CountRating]
Array1 = MergedDF[["Title", "AveRating", "CountRating"]].to_numpy()
print(Array1)
Array1
I need to creat... | [
"To create pairs you only need a nested loop.\nr,c=Array1.shape\nArray2=[]\nfor ix1 in range(r-1):\n for ix2 in range(ix1+1,r):\n Array2.append((Array1[ix1],Array1[ix2]))\n \n\n\n\n"
] | [
0
] | [] | [] | [
"arrays",
"combinations",
"python",
"vector"
] | stackoverflow_0074505420_arrays_combinations_python_vector.txt |
Q:
Calculating CRC16 in Python for modbus
Firstly, sorry! I am a beginner...
I got the following byte sequence on a modbus: "01 04 08 00 00 00 09 00 00 00 00 f8 0c". The CRC on bold on this byte sequence is correct. However, to check/create the CRC I have to follow the device especs that states:
The error checking mu... | Calculating CRC16 in Python for modbus | Firstly, sorry! I am a beginner...
I got the following byte sequence on a modbus: "01 04 08 00 00 00 09 00 00 00 00 f8 0c". The CRC on bold on this byte sequence is correct. However, to check/create the CRC I have to follow the device especs that states:
The error checking must be done using a 16 bit CRC implemented as... | [
"Use 0x18005 instead of 0x1A001.\n",
"Modbus shortcut, if not diving into the CRC detail\nfrom pymodbus.utilities import computeCRC\n\n"
] | [
1,
0
] | [] | [] | [
"crc",
"modbus",
"python",
"python_2.x"
] | stackoverflow_0069369408_crc_modbus_python_python_2.x.txt |
Q:
Convert from dictionary to dataframe when arrays aren't equal length?
I have a dictionary like this:
{1: ["a", "b", "c"],
2: ["d", "e", "f", "g"]}
that I want to turn into a dataframe like this:
id
item
1
a
1
b
1
c
2
d
2
e
2
f
2
g
but when I try use pandas.DataFrame.from_dict() I get an error because my ... | Convert from dictionary to dataframe when arrays aren't equal length? | I have a dictionary like this:
{1: ["a", "b", "c"],
2: ["d", "e", "f", "g"]}
that I want to turn into a dataframe like this:
id
item
1
a
1
b
1
c
2
d
2
e
2
f
2
g
but when I try use pandas.DataFrame.from_dict() I get an error because my arrays aren't the same length. How can I accomplish what I'm... | [
"Example\ndata = {1: [\"a\", \"b\", \"c\"],\n 2: [\"d\", \"e\", \"f\", \"g\"]}\n\nCode\npd.Series(data).explode()\n\noutput(series):\n1 a\n1 b\n1 c\n2 d\n2 e\n2 f\n2 g\ndtype: object\n\n\nif you want result to dataframe, use following code:\npd.Series(data).explode().reset_index().set_ax... | [
2,
0
] | [] | [] | [
"dictionary",
"numpy",
"pandas",
"python"
] | stackoverflow_0074505455_dictionary_numpy_pandas_python.txt |
Q:
Not enough parameters for sql statement. Want to update table (python-mysql connect)
import sys
import mysql.connector
mydb = mysql.connector.connect(host='localhost', user='root', passwd='anohacker', database='csproj')
cursor = mydb.cursor(buffered=True)
nameb=input("enter your name: ")
bookbor=int(input("Enter ... | Not enough parameters for sql statement. Want to update table (python-mysql connect) |
import sys
import mysql.connector
mydb = mysql.connector.connect(host='localhost', user='root', passwd='anohacker', database='csproj')
cursor = mydb.cursor(buffered=True)
nameb=input("enter your name: ")
bookbor=int(input("Enter book code to borrow: "))
def borrow(nameb,bookbor):
bquery="update inventory set name_... | [
"you need to provide the data for the query as a tuple so:\nbquery=\"update inventory set name_of_borrower=%s where book_code=%s\"\ncursor.execute(bquery,(nameb,bookbor))\n\nsee https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html\n"
] | [
0
] | [] | [] | [
"mysql",
"mysql_connector",
"mysql_python",
"python"
] | stackoverflow_0074505488_mysql_mysql_connector_mysql_python_python.txt |
Q:
find all permutations from a list of lists where outputs contain all, none, or any of the items in each list
I have any arbitrary number of lists with an arbitrary number of elements. I need to find the permutations such that each permutation contains all, any, or none of the elements from each list
l1 = ['red', '... | find all permutations from a list of lists where outputs contain all, none, or any of the items in each list | I have any arbitrary number of lists with an arbitrary number of elements. I need to find the permutations such that each permutation contains all, any, or none of the elements from each list
l1 = ['red', 'blue', 'green']
l2 = ['big','small','medium']
l3 = ['fast','slow','stopped']
res = function([l1,l2,l3])
res = [(... | [
"I guess here's my hacky solution.\nproducts = []\nfor r in range(len(l1)+1):\n perm = list(itertools.combinations(l1, r))\n for r2 in range(len(l2)+1):\n perm2 = list(itertools.combinations(l2, r2)) \n for r3 in range(len(l3)+1):\n perm3 = list(itertools.combinations(l3, r3))\n ... | [
0
] | [] | [] | [
"combinatorics",
"permutation",
"python",
"python_itertools"
] | stackoverflow_0074505467_combinatorics_permutation_python_python_itertools.txt |
Q:
How to apply maps to dataframes based on a field value?
I have a script where I loop through a dataframe based on one of its field values.
Something like
import pandas as pd
import numpy as np
data = {
"thevalue": [0,0,1,2,2,3,5,5,5],
"firstname": ["Sally", "Mary", "John","Peter","Julius","Cornelius","Athos",... | How to apply maps to dataframes based on a field value? | I have a script where I loop through a dataframe based on one of its field values.
Something like
import pandas as pd
import numpy as np
data = {
"thevalue": [0,0,1,2,2,3,5,5,5],
"firstname": ["Sally", "Mary", "John","Peter","Julius","Cornelius","Athos","Porthos","Aramis"],
"age": [50, 40, 30,20,10,20,11,12,23]
... | [
"you can divide dataframe by group with following code:\ng = df.groupby('thevalue')\n[g.get_group(x) for x in g.groups]\n\nlet's use code above to get desired output :\ng = df.groupby('thevalue')\nrange_v = range(df['thevalue'].min(), df['thevalue'].max() + 1)\n[(x, g.get_group(x)) if x in g.groups else (x, pd.Data... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074505510_dataframe_pandas_python.txt |
Q:
Insert input into list by the name of the menu, and then calculating its price after selecting the items
I wanted a create a function in Python where the user inputs the name of the menu and then it returns it in their order. After they are finished with ordering, the function would then calculate the price. My pr... | Insert input into list by the name of the menu, and then calculating its price after selecting the items | I wanted a create a function in Python where the user inputs the name of the menu and then it returns it in their order. After they are finished with ordering, the function would then calculate the price. My problem is I typed "Apple", but it came back empty. Is there anyway I could get around this? Any assistance is a... | [
"The way you use a dictionary is to have a key and a value related to it, in this case your menu dictionary should be {\"item\":price}.\nThat way if you want to know the price of an Apple yo do\nprint(menu[\"Apple\"])\n\nDid not understand why the Try/except in this case.\nmenu = {\"Apple\" : 9.00, \"Banana\" : 5.... | [
0
] | [] | [] | [
"dictionary",
"input",
"list",
"python"
] | stackoverflow_0074505486_dictionary_input_list_python.txt |
Q:
Selenium WebDriver to extract only paragraphs
I am totally new to all of this. I am trying to extract articles from a lot of pages but I put only 4 URLS in the code below and need to extract only important paragraphs from <p>text</p> == $0.
Here is my code for this sample:
currency = 'BTC'
btc_today = pd.DataFrame... | Selenium WebDriver to extract only paragraphs | I am totally new to all of this. I am trying to extract articles from a lot of pages but I put only 4 URLS in the code below and need to extract only important paragraphs from <p>text</p> == $0.
Here is my code for this sample:
currency = 'BTC'
btc_today = pd.DataFrame({'Currency':[],
'D... | [
"I am assuming you need to get the main content, for that, change the locator for the 'content':\ncontent = driver.find_elements(By.CSS_SELECTOR, '.WYSIWYG.articlePage p')\n\nAlso, there are unnecessary '<p>' tags with the content - \"Position added successfully to: \" and \"Continue reading on DailyCoin\", you can... | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver",
"web_scraping"
] | stackoverflow_0074504175_python_selenium_selenium_webdriver_web_scraping.txt |
Q:
python app with selenium failes with MaxRetryError
i am trying to host a python app in docker
i am running selenium standalone chrome in docker and i can connect to it running my python app locally.
my application looks like this:
def web_scrape():
url = "https://who.maps.arcgis.com/apps/opsdashboard/index.html#/e... | python app with selenium failes with MaxRetryError | i am trying to host a python app in docker
i am running selenium standalone chrome in docker and i can connect to it running my python app locally.
my application looks like this:
def web_scrape():
url = "https://who.maps.arcgis.com/apps/opsdashboard/index.html#/ead3c6475654481ca51c248d52ab9c61"
#setup webdriver
option... | [
"how have you setup your testing environment in docker, plus you could replace localhost with selenium-hub at the command_executor argument in the meantime\n",
"Had the same issue. Tests running from Docker container were failing to drive Chrome using Selenium running in Docker container.\nThe issue was that Sele... | [
0,
0,
0
] | [] | [] | [
"docker",
"python",
"selenium_chromedriver",
"selenium_webdriver"
] | stackoverflow_0065338801_docker_python_selenium_chromedriver_selenium_webdriver.txt |
Q:
How do I use QT6 Dark Theme with PySide6?
Simple demo application I am trying to set the theme to dark. I would prefer a code version (non QtQuick preferred), but only way I see for Python is with a QtQuick config file, and even that does not work.
from PySide6 import QtWidgets
from PySide6 import QtQuick
if __na... | How do I use QT6 Dark Theme with PySide6? | Simple demo application I am trying to set the theme to dark. I would prefer a code version (non QtQuick preferred), but only way I see for Python is with a QtQuick config file, and even that does not work.
from PySide6 import QtWidgets
from PySide6 import QtQuick
if __name__ == '__main__':
app = QtWidgets.QApplic... | [
"import sys\nsys.argv += ['-platform', 'windows:darkmode=2']\napp = QApplication(sys.argv)\n\nabove 3 lines can change your window to dark mode if you are using windows and Fusion style makes the app more beautiful, tested in windows 10, 11\nexample:-\nfrom PySide6.QtWidgets import (\n QApplication,\n QCheckB... | [
2
] | [] | [] | [
"pyside6",
"python",
"python_3.x",
"qt6"
] | stackoverflow_0073060080_pyside6_python_python_3.x_qt6.txt |
Q:
Adding Nodes to a graph displays object instead of string (adjacency list)
I'm learning how to create a graph using an adjacency list on Python. My current problem is when trying to add a node to the list, it displays the Node object at 0x0000.... instead of a string. When I try to print out the list, I get TypeEr... | Adding Nodes to a graph displays object instead of string (adjacency list) | I'm learning how to create a graph using an adjacency list on Python. My current problem is when trying to add a node to the list, it displays the Node object at 0x0000.... instead of a string. When I try to print out the list, I get TypeError: list indices must be integers or slices, not Node".
I can't seem to figure ... | [
"You can specify string representation of your object by implementing __repr__\nSee details in the docs and this question\nHere is a working example (nodeList is fixed too)\nclass Node:\n def __init__(self, name):\n self.name = name\n self.visited = False\n self.adjacency = []\n\n def add... | [
1
] | [] | [] | [
"adjacency_list",
"data_structures",
"graph",
"python",
"python_3.x"
] | stackoverflow_0074505246_adjacency_list_data_structures_graph_python_python_3.x.txt |
Q:
Python error in VSCode :Sorry, something went wrong activating IntelliCode support for Python
My code is not working in vscode when i click to run code i saw this error:
Sorry, something went wrong activating IntelliCode support for Python.
Please check the "Python" and "VS IntelliCode" output windows for
details... | Python error in VSCode :Sorry, something went wrong activating IntelliCode support for Python | My code is not working in vscode when i click to run code i saw this error:
Sorry, something went wrong activating IntelliCode support for Python.
Please check the "Python" and "VS IntelliCode" output windows for
details.
and when i try to run code again i saw this message;
Code is already running
Code dont stop wh... | [
"I would just like to add a few helpful links:\nIntellicode Issue 57\nIntellicode Issue 266\nGitmemory issue 486082039\nFor a lot of people, it just began working after a few tries randomly. See this text (quoted from issue 57):\n\nThere's a race condition in the activation of both the IntelliCode and Python langua... | [
2,
1,
0,
0
] | [] | [] | [
"python",
"runtime_error",
"visual_studio_code"
] | stackoverflow_0068637153_python_runtime_error_visual_studio_code.txt |
Q:
Remove Redundant Parenthesis in an Arithmetic Expression
I'm trying to remove redundant parentheses from an arithmetic expression. For example, if I have the expression (5+((2*3))), I want the redundant parenthesis between (2*3) removed. The output that I want is (5+(2*3)).
I'm getting this arithmetic expression f... | Remove Redundant Parenthesis in an Arithmetic Expression | I'm trying to remove redundant parentheses from an arithmetic expression. For example, if I have the expression (5+((2*3))), I want the redundant parenthesis between (2*3) removed. The output that I want is (5+(2*3)).
I'm getting this arithmetic expression from performing an inorder traversal on an expression tree. The... | [
"Instead of adding the parenthesis around the parent/root expression, one option is to add the parentheses before and after recursing down on each of the left and right children. If those children are leaves, meaning they do not have children, do not add parentheses.\nIn practice, this might look something like thi... | [
1
] | [] | [] | [
"python",
"python_3.x",
"string",
"traversal",
"tree"
] | stackoverflow_0074505569_python_python_3.x_string_traversal_tree.txt |
Q:
How to resolve No module named 'hmmlearn' error in Jupyter Notebook
I'm new to hmmlearn and am trying to use the Jupyter Notebook to work through this Gaussian HMM of stock data example. However, when I run the following code, I get an error.
from __future__ import print_function
import datetime
import numpy as ... | How to resolve No module named 'hmmlearn' error in Jupyter Notebook | I'm new to hmmlearn and am trying to use the Jupyter Notebook to work through this Gaussian HMM of stock data example. However, when I run the following code, I get an error.
from __future__ import print_function
import datetime
import numpy as np
from matplotlib import cm, pyplot as plt
from matplotlib.dates import ... | [
"This page provides 32- and 64-bit Windows binaries of many scientific open-source extension packages for the official CPython distribution of the Python programming language. \nSelect the appropriate file according to your system requirements. (For me, it's python 3.7 and windows 64 bit)\nAfter you downloaded thi... | [
2,
0
] | [] | [] | [
"hmmlearn",
"jupyter_notebook",
"numpy",
"python"
] | stackoverflow_0048355747_hmmlearn_jupyter_notebook_numpy_python.txt |
Q:
On Matplotlib, how do i move my legend where I want it?
How would I move my legend to inside the graph right under where my title is?
plt.plot([1, 2], [3, 4], color='r', label="Apple")
plt.plot([3, 4], [5, 6], color='g', label="Pear")
plt.title("Total Profit Trend by Month")
plt.legend()
plt.show()
A:
You can us... | On Matplotlib, how do i move my legend where I want it? | How would I move my legend to inside the graph right under where my title is?
plt.plot([1, 2], [3, 4], color='r', label="Apple")
plt.plot([3, 4], [5, 6], color='g', label="Pear")
plt.title("Total Profit Trend by Month")
plt.legend()
plt.show()
| [
"You can use: plt.legend(loc='upper left') or you can replace 'upper left' by the following locations:\nupper right,\nlower left,\nlower right,\nright,\ncenter left,\ncenter right,\nlower center,\nupper center,\ncenter.\n"
] | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074505551_matplotlib_python.txt |
Q:
How to remove the none error from the output
I'm creating a recursive function that creates n lines of asterisk. I do not have problems on writing code, but just am wondering why None appears in my output.
Here is my code:
def recursive_lines(n):
for n in range(0,n):
print ('*' + ('*'*n)) # Print aster... | How to remove the none error from the output | I'm creating a recursive function that creates n lines of asterisk. I do not have problems on writing code, but just am wondering why None appears in my output.
Here is my code:
def recursive_lines(n):
for n in range(0,n):
print ('*' + ('*'*n)) # Print asterisk
print(recursive_lines(5)) # Enter an inte... | [
"You are printing out recursive_lines(5), but inside the function, you are already printing the values. Simply remove the print that is around recursive_lines(5)\n",
"The None is printing because you are using print(recursive_lines(5)) even though your function is not returning anything. Remove the print statemen... | [
0,
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074505681_python_python_3.x.txt |
Q:
How to remove all items that are in between two duplicates in a list
How do I write a program that will remove all the items that are in between two duplicates in a list and it will also remove the second duplicate.
For example,
a = [ (0,0) , (1,0) , (2,0) , (3,0) , (1,0) ]
In the list a, we see that (1,0) occurs ... | How to remove all items that are in between two duplicates in a list | How do I write a program that will remove all the items that are in between two duplicates in a list and it will also remove the second duplicate.
For example,
a = [ (0,0) , (1,0) , (2,0) , (3,0) , (1,0) ]
In the list a, we see that (1,0) occurs more than once in the list. Thus I want to remove all the items in between... | [
"Here's one way to do that by using index:\nlst = [(0,0), (1,0), (2,0), (3,0), (1,0), (5,0), (6,0), (7,0), (8,0), (5,0), (9,0), (10,0)]\n\noutput = []\n\nwhile lst: # while `lst` is non-empty\n x, *lst = lst # if lst = [1,2,3], for example, now x = 1 and lst = [2,3]\n output.append(x)\n try: # try finding ... | [
2,
0
] | [] | [] | [
"duplicates",
"list",
"python",
"python_3.x"
] | stackoverflow_0074505592_duplicates_list_python_python_3.x.txt |
Q:
Create a column based on conditions and calculation
Below is my dataframe:
df = pd.DataFrame({"ID" : [1, 1, 2, 2, 2, 3, 3],
"length" : [0.7, 0.7, 0.8, 0.6, 0.6, 0.9, 0.9],
"comment" : ["typed", "handwritten", "typed", "typed", "handwritten", "handwritten", "handwritten"]})
df
... | Create a column based on conditions and calculation | Below is my dataframe:
df = pd.DataFrame({"ID" : [1, 1, 2, 2, 2, 3, 3],
"length" : [0.7, 0.7, 0.8, 0.6, 0.6, 0.9, 0.9],
"comment" : ["typed", "handwritten", "typed", "typed", "handwritten", "handwritten", "handwritten"]})
df
ID length comment
0 1 0.7 typed
1 1 0.7 ... | [
"Find the IDs that satisfy the special condition using groupby. Using the IDs and the comment, compute the Calculated length using np.where as follows\n>>> grp_ids = df.groupby(\"ID\")[[\"length\", \"comment\"]].nunique()\n>>> grp_ids\n length comment\nID\n1 1 2\n2 2 2\n3 1 ... | [
0
] | [
"use np.where if comment column exist only typed or handwritten.\nimport numpy as np\ncond1 = df['comment'] == 'typed'\ndf.assign(Calculated_Length=np.where(cond1, df['length'] * 5, df['length'] * 7))\n\noutput:\n ID length comment Calculated_Length\n0 1 0.7 typed 3.5\n1 1 0.7 handwri... | [
-1
] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074505643_numpy_pandas_python.txt |
Q:
How to set PyQt element text from another running script?
I have a client socket program and a server socket program in python. The client sends a message and the server echos the message as well as stores some variables about the clients ip and port number.
I made a GUI in PyQt with some text fields to store the ... | How to set PyQt element text from another running script? | I have a client socket program and a server socket program in python. The client sends a message and the server echos the message as well as stores some variables about the clients ip and port number.
I made a GUI in PyQt with some text fields to store the clients ip and port number.
The problem is I need to run both t... | [
"musicamantes advice worked:\n\nThe QApplication and any UI element must be in the main thread, anything else is in other threads. Use QThread subclasses and custom signals, and also don't modify pyuic files (as clearly written in their headers), but follow the official guidelines about using Designer instead.\n\nI... | [
0
] | [] | [] | [
"pyqt",
"pyqt6",
"python",
"python_3.x",
"python_multithreading"
] | stackoverflow_0074504651_pyqt_pyqt6_python_python_3.x_python_multithreading.txt |
Q:
Regular expression for the name O`Malley, John F
I am unable to generate a regular expression for the name O`Malley, John F.
Right now, I have the following.
re.compile(r'^[A-Z][a-z]+`, [A-Z][a-z]+ [A-Z][a-z]+.$')
Any help or what am I doing wrong?
A:
For that specific name (format), the back tick is in the wron... | Regular expression for the name O`Malley, John F | I am unable to generate a regular expression for the name O`Malley, John F.
Right now, I have the following.
re.compile(r'^[A-Z][a-z]+`, [A-Z][a-z]+ [A-Z][a-z]+.$')
Any help or what am I doing wrong?
| [
"For that specific name (format), the back tick is in the wrong place:\nre.compile(r'^[A-Z]`{0,1}[a-z]+, [A-Z][a-z]+ [A-Z][a-z]+.$')\n\nYou are asking for the regex for that specific name format, the above will catch a name with or without the back tick on the second position.\nYou should take into account the comm... | [
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074505636_python_regex.txt |
Q:
asyncio.sleep(0) does not yield control to the event loop
I have a simple async setup which includes two coroutines: light_job and heavy_job. light_job halts in the middle and heavy_job starts. I want heavy_job to yield the control in the middle and allow light_job to finish but asyncio.sleep(0) is not working as ... | asyncio.sleep(0) does not yield control to the event loop | I have a simple async setup which includes two coroutines: light_job and heavy_job. light_job halts in the middle and heavy_job starts. I want heavy_job to yield the control in the middle and allow light_job to finish but asyncio.sleep(0) is not working as I expect.
this is the setup:
import asyncio
import time
loop =... | [
"Call asyncio.sleep(0) 3 times:\nimport asyncio\nimport time\n\n\nasync def light_job():\n print(\"hello \")\n print(time.time())\n await asyncio.sleep(1)\n print(time.time())\n print(\"world!\")\n\n\nasync def heavy_job():\n print(\"heavy start\")\n time.sleep(3)\n print(\"heavy halt starte... | [
4,
3
] | [] | [] | [
"python",
"python_asyncio"
] | stackoverflow_0074493571_python_python_asyncio.txt |
Q:
If always true when checking strings
I'm developing a chatbot project for college, and in the following code block, the first if is always going as a true value, no matter what. I really need help and don't know what to do, cause this project is due on monday.
def registeredClient():
print('Olá, bem-vindo a WE... | If always true when checking strings | I'm developing a chatbot project for college, and in the following code block, the first if is always going as a true value, no matter what. I really need help and don't know what to do, cause this project is due on monday.
def registeredClient():
print('Olá, bem-vindo a WE-RJ Telecom!')
userInputString = str(... | [
"I updated the conditions. In your case your conditions were checking if the strings themselves were truthly which is why your first case would result in true.\n\n\ndef registeredClient():\n print('Olá, bem-vindo a WE-RJ Telecom!')\n\n userInputString = str(input('O que você precisa?\\nCaso queira contratar o... | [
1,
0
] | [] | [] | [
"if_statement",
"python",
"python_3.x",
"string"
] | stackoverflow_0074505753_if_statement_python_python_3.x_string.txt |
Q:
How can I iterate a list of data using 2D list in python?
I want to create a variable called containing a 2D (nested) list of 2 rows and 3 columns literal containing the values like this:
3 14 67
13 24 19
the code I have now is sth like this but the outcome doesn't give me the outcome I want:
for row in... | How can I iterate a list of data using 2D list in python? | I want to create a variable called containing a 2D (nested) list of 2 rows and 3 columns literal containing the values like this:
3 14 67
13 24 19
the code I have now is sth like this but the outcome doesn't give me the outcome I want:
for row in range(2):
new_list = []
for col in range(3):
n... | [
"You can use my code:\na_list = [3, 14, 67, 13, 24, 19] \nnew_list = []\nnew_list += [a_list[0:3]]\nnew_list += [a_list[3:6]]\n\n",
"Your problem is two-fold, you need to instantiate the correct number of lists to hold your elements; and you also need to pull elements from a_list in order.\nYou need to accumulate... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074505648_python.txt |
Q:
Unable to create jira Bug using python
I am using below code to create ticket in jira.
I am able to create only TASK. When i create Bug or Story I am getting below error .
issue_dict = {
'project': {'key': 'TEST'},
'summary': 'New issue from jira-python',
'description': 'Look into this one',
'issue... | Unable to create jira Bug using python | I am using below code to create ticket in jira.
I am able to create only TASK. When i create Bug or Story I am getting below error .
issue_dict = {
'project': {'key': 'TEST'},
'summary': 'New issue from jira-python',
'description': 'Look into this one',
'issuetype': {'name': 'Bug'}
}
new_issue = jira.c... | [
"If you look at the error, you can see it says:\n\n\"errors\":{\"issuetype\":\"Specify an issue type\"}\n\nSo clearly something must be wrong with how you've set issuetype.\n\nHave you tried looking at the API docs? It seems you could try:\n\nSpecifying the Issue Type via the issuetypeNames parameter rather than ju... | [
0
] | [] | [] | [
"jira",
"python"
] | stackoverflow_0074505631_jira_python.txt |
Q:
How to combine two code points to get one?
I know that unicode code point for Á is U+00C1. I read on internet and many forums and articles that I can also make an Á by combining characters ´ (unicode: U+00B4) and A (unicode: U+0041).
My question is simple. How to do it? I tried something like this. I decided to tr... | How to combine two code points to get one? | I know that unicode code point for Á is U+00C1. I read on internet and many forums and articles that I can also make an Á by combining characters ´ (unicode: U+00B4) and A (unicode: U+0041).
My question is simple. How to do it? I tried something like this. I decided to try it in golang, but it's perfectly fine if someo... | [
"It looks like the ´ (U+00B4) character you provided is not actually a combining character as Unicode defines it.\n>>> \"A\\u00b4\"\n'A´'\n\nIf we use ◌́ (U+0301) instead, then we can just place it in sequence with a character like A and get the expected output:\n>>> \"A\\u0301\"\n'Á'\n\nUnless I'm misunderstandin... | [
2,
1
] | [] | [] | [
"go",
"python",
"unicode",
"utf",
"utf_8"
] | stackoverflow_0074505405_go_python_unicode_utf_utf_8.txt |
Q:
Specific tensor decomposition
I want to decompose a 3-dimensional tensor using SVD.
I am not quite sure if and, how following decomposition can be achieved.
I already know how I can split the tensor horizontally from this tutorial: tensors.org Figure 2.2b
d = 10; A = np.random.rand(d,d,d)
Am = A.reshape(d**2,d)
... | Specific tensor decomposition | I want to decompose a 3-dimensional tensor using SVD.
I am not quite sure if and, how following decomposition can be achieved.
I already know how I can split the tensor horizontally from this tutorial: tensors.org Figure 2.2b
d = 10; A = np.random.rand(d,d,d)
Am = A.reshape(d**2,d)
Um,Sm,Vh = LA.svd(Am,full_matrices=... | [
"Matrix methods can be naturally extended to higher-orders. SVD, for instance, can be generalized to tensors e.g. with the Tucker decomposition, sometimes called a higher-order SVD.\nWe maintain a Python library for tensor methods, TensorLy, which lets you do this easily. In this case you want a partial Tucker as y... | [
2,
0
] | [] | [] | [
"numpy",
"python",
"tensor"
] | stackoverflow_0066753122_numpy_python_tensor.txt |
Q:
Can't import UDF from python to Excel using xlwings
I am using python to write a function and then using xlwings I am trying to import it into Excel but I faced the following error:
My xlwings version is 0.28.5, and python's is 3.10, and I am using Excel 2013. also both
xlwings32-0.28.5.dll and xlwings64-0.28.5 a... | Can't import UDF from python to Excel using xlwings | I am using python to write a function and then using xlwings I am trying to import it into Excel but I faced the following error:
My xlwings version is 0.28.5, and python's is 3.10, and I am using Excel 2013. also both
xlwings32-0.28.5.dll and xlwings64-0.28.5 are in the same folder as the python3.10.exe
the name of ... | [
"I have solved this by uninstalling the python version that I have and the reinstalling it using anaconda3 distribution. after that from the anaconda prompt type xlwings addin install and every thing worked fine.\n"
] | [
0
] | [] | [] | [
"excel",
"python",
"xlwings"
] | stackoverflow_0074456094_excel_python_xlwings.txt |
Q:
Date conversion in Pyspark Dataframe
I have a date in Pyspark dataframe in "String" format as "dd-MMM-yyyy ( eg "01-Jan-2022").
I want to convert this to date with the same format so the Output should be
01-Jan-2022
The code i am using for this is as below, but the format doesn't convert properly. It converts the... | Date conversion in Pyspark Dataframe | I have a date in Pyspark dataframe in "String" format as "dd-MMM-yyyy ( eg "01-Jan-2022").
I want to convert this to date with the same format so the Output should be
01-Jan-2022
The code i am using for this is as below, but the format doesn't convert properly. It converts the date to "dd-MM-yyyy" format (ie 01-01-202... | [
"The documentation of to_date links to the format definition here.\nHave you tried using dd-LLL-yyyy?\n",
"Assume your original data has date as string:\ndf = spark.createDataFrame(data=[[\"01-Jan-2022\",],[\"31-Dec-2022\",]], schema=[\"date_initial\"])\ndf.show()\n\n+------------+\n|date_initial|\n+------------+... | [
0,
0
] | [] | [] | [
"azure_databricks",
"pyspark",
"python"
] | stackoverflow_0074504540_azure_databricks_pyspark_python.txt |
Q:
Creating 3-Way Data Tensor in Python and performing PARAFAC decomposition
I'm new to Python and Data Science and replicating a research paper I found on Vehicle Maintenance.
I'm trying to analyze vehicle maintenance data to find seasonal patterns in component maintenance over absolute time and also component mai... | Creating 3-Way Data Tensor in Python and performing PARAFAC decomposition | I'm new to Python and Data Science and replicating a research paper I found on Vehicle Maintenance.
I'm trying to analyze vehicle maintenance data to find seasonal patterns in component maintenance over absolute time and also component maintenance patterns over the age of a vehicle. By component I mean a specific par... | [
"You can use TensorLy which implements tensor operations, decompositions and regressions, and in particular, allows you to apply PARAFAC easily.\nAlso checkout the notebooks for an introduction to tensor methods with TensorLy. There is also a chapter on tensor decomposition that includes Parafac and demonstrates ho... | [
3,
0
] | [] | [] | [
"data_science",
"multidimensional_array",
"python",
"tensor"
] | stackoverflow_0048327766_data_science_multidimensional_array_python_tensor.txt |
Q:
Re-compose a Tensor after tensor factorization
I am trying to decompose a 3D matrix using python library scikit-tensor. I managed to decompose my Tensor (with dimensions 100x50x5) into three matrices. My question is how can I compose the initial matrix again using the decomposed matrix produced with Tensor factori... | Re-compose a Tensor after tensor factorization | I am trying to decompose a 3D matrix using python library scikit-tensor. I managed to decompose my Tensor (with dimensions 100x50x5) into three matrices. My question is how can I compose the initial matrix again using the decomposed matrix produced with Tensor factorization? I want to check if the decomposition has any... | [
"The CP product of, for example, 4 matrices\n\ncan be expressed using Einstein notation as\n\nor in numpy as\nnumpy.einsum('az,bz,cz,dz -> abcd', A, B, C, D)\n\nso in your case you would use\nnumpy.einsum('az,bz->ab', P.U[0], P.U[1])\n\nor, in your 3-matrix case\nnumpy.einsum('az,bz,cz->abc', P.U[0], P.U[1], P.U[2]... | [
7,
0
] | [] | [] | [
"data_science",
"math",
"python",
"scikits"
] | stackoverflow_0039748285_data_science_math_python_scikits.txt |
Q:
Keep only functions in a Python script
Assume I have a Python script or module bar.py like this one
# bar.py
some_variable = 1
print(some_variable)
def some_function():
print('hello')
I need to create a copy of the script that only keeps the functions and does not contain any module-level code. For example, I ... | Keep only functions in a Python script | Assume I have a Python script or module bar.py like this one
# bar.py
some_variable = 1
print(some_variable)
def some_function():
print('hello')
I need to create a copy of the script that only keeps the functions and does not contain any module-level code. For example, I would need to automatically create a copy of... | [
"In this way you can find all callable objects in the bar:\n>>> import bar\n>>> list(filter(lambda item: callable(getattr(bar, item)), bar.__dir__()))\n['f']\n\nTo copy them you can store all callable objects in a list, tuple or any other data structure that fits your need.\n>>> list(map(lambda attr: getattr(bar, a... | [
0
] | [] | [] | [
"python",
"python_3.x",
"python_import"
] | stackoverflow_0074505931_python_python_3.x_python_import.txt |
Q:
Is there a way in Python to return a value via an output parameter?
Some languages have the feature to return values using parameters also like C#.
Let’s take a look at an example:
class OutClass
{
static void OutMethod(out int age)
{
age = 26;
}
static void Main()
{
int value;
... | Is there a way in Python to return a value via an output parameter? | Some languages have the feature to return values using parameters also like C#.
Let’s take a look at an example:
class OutClass
{
static void OutMethod(out int age)
{
age = 26;
}
static void Main()
{
int value;
OutMethod(out value);
// value is now 26
}
}
So is t... | [
"Python can return a tuple of multiple items:\ndef func():\n return 1,2,3\n\na,b,c = func()\n\nBut you can also pass a mutable parameter, and return values via mutation of the object as well:\ndef func(a):\n a.append(1)\n a.append(2)\n a.append(3)\n\nL=[]\nfunc(L)\nprint(L) # [1,2,3]\n\n",
"You mean... | [
83,
8,
4,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004702249_python.txt |
Q:
How can I change an html based on which link the user clicks?
I've created a database of recipes and on a recipes.html I display all the recipes and made the names links that I want to bring you to a new page that displays all of that recipes information. How can I make another html page for the single recipe that... | How can I change an html based on which link the user clicks? | I've created a database of recipes and on a recipes.html I display all the recipes and made the names links that I want to bring you to a new page that displays all of that recipes information. How can I make another html page for the single recipe that will change depending on which recipe a user chooses? I don't want... | [
"You can use href with parameters and pass in an argument, such as single-recipe?id=apple_pie.\nThen in flask you can get the id by doing\n@app.route(...)\ndef single-recipe():\n id = request.args.get('id')\n\nAnd return the relevant page\n"
] | [
1
] | [] | [] | [
"flask",
"python",
"sql"
] | stackoverflow_0074505531_flask_python_sql.txt |
Q:
Assigning value in python list
I tried to create a tic tac toe program with python list:
theBoard=[' '' '' ']*3
def userInput(board):
loop=True
while loop:
userInput=input("Please enter (row,column)")
row=int(userInput[0])
column=int(userInput[2])
if row<1 or row>3:
... | Assigning value in python list | I tried to create a tic tac toe program with python list:
theBoard=[' '' '' ']*3
def userInput(board):
loop=True
while loop:
userInput=input("Please enter (row,column)")
row=int(userInput[0])
column=int(userInput[2])
if row<1 or row>3:
print('[ERROR: Invalid Input]')
... | [
"In the line\ntheBoard=[' '' '' ']*3\n\nYou are creating a list of size 9\nin the line\nboard[row-1][column-1]\n\nYou are treating the list as if it is a 2d list\nTo make theBoard in to a 2d list try:\ntheBoard=[' ',' ',' ']\ntheBoard = [theBoard,theBoard,theBoard]\n\n",
"Well, its not the program, its you who mi... | [
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074506004_list_python.txt |
Q:
Streamlit app keep showing "Please wait..." and give error in terminal
The following error occurred in the terminal in Pycharm by running
streamlit run app.py
2022-08-19 20:50:02.531 Uncaught exception
Traceback (most recent call last):
File "e:\project\movies-recommender-system\venv\lib\site-packages\tornado\ht... | Streamlit app keep showing "Please wait..." and give error in terminal | The following error occurred in the terminal in Pycharm by running
streamlit run app.py
2022-08-19 20:50:02.531 Uncaught exception
Traceback (most recent call last):
File "e:\project\movies-recommender-system\venv\lib\site-packages\tornado\http1connection.py", line 276, in _read_message
delegate.finish()
File "... | [
"I had the same issue. Uninstall streamlit and install the version 1.11.0\nType into the terminal:\npip uninstall streamlit\n\npip install streamlit==1.11.0\n\n",
"This problem shows up because of the streaming version. You can uninstall and reinstall the previous version.\nTry this command:\n\n\npip uninstall st... | [
4,
0
] | [] | [] | [
"python",
"streamlit",
"web_applications"
] | stackoverflow_0073419067_python_streamlit_web_applications.txt |
Q:
Sphinx cannot find my python files. Says 'no module named ...'
I have a question regarding the Sphinx autodoc generation. I feel that what I am trying to do should be very simple, but for some reason, it won't work.
I have a Python project of which the directory is named slotting_tool. This directory is located a... | Sphinx cannot find my python files. Says 'no module named ...' | I have a question regarding the Sphinx autodoc generation. I feel that what I am trying to do should be very simple, but for some reason, it won't work.
I have a Python project of which the directory is named slotting_tool. This directory is located at C:\Users\Sam\Desktop\picnic-data-shared-tools\standalone\slotting_... | [
"This is the usual \"canonical approach\" to \"getting started\" applied to the case when your source code resides in a src directory like Project/src instead of simply being inside the Project base directory.\nFollows these steps:\n\nCreate a docs directory in your Project directory (it's from this docs directory ... | [
21,
5,
3,
0
] | [
"For me installing the package via setup.py file and re-running corresponding commands fixed the problem:\n$ python setup.py install\n\n"
] | [
-2
] | [
"autodoc",
"python",
"python_3.x",
"python_sphinx"
] | stackoverflow_0053668052_autodoc_python_python_3.x_python_sphinx.txt |
Q:
How I convert tensoflow Linear(kernel_constraint=max_norm) to pyotch code?
Dense(self.latent_dim, kernel_constraint=max_norm(0.5))(en_conv)
I want to convert the above tensoflow code to pytorch, but I don't understand kernel_constraint=max_norm(0.5). How can I convert it?
| How I convert tensoflow Linear(kernel_constraint=max_norm) to pyotch code? | Dense(self.latent_dim, kernel_constraint=max_norm(0.5))(en_conv)
I want to convert the above tensoflow code to pytorch, but I don't understand kernel_constraint=max_norm(0.5). How can I convert it?
| [] | [] | [
"one way possible is to do it by a custom layer that you can use in the model as a custom layer. Kernel constrain is the same as you do by initializing the value in the simple Dense layer.\n\nSample: Dense layer with initial weight, you can use tf.zeros() or tf.ones() or random function or tf.constant() but the mod... | [
-1
] | [
"python",
"pytorch",
"tensorflow"
] | stackoverflow_0074505815_python_pytorch_tensorflow.txt |
Q:
Reading in a web based text file I am getting a ton of errors with json()
I am getting a bunch of errors with respect to the json function. My code is below and it's pretty straight forward. I am trying to request this text file on the web and write it to a new file. Then parse the data to get the first IP address... | Reading in a web based text file I am getting a ton of errors with json() | I am getting a bunch of errors with respect to the json function. My code is below and it's pretty straight forward. I am trying to request this text file on the web and write it to a new file. Then parse the data to get the first IP address in each row. I am first just trying to get past all of these errors.
#extracti... | [
"This may not be exactly optimized but it works and probably can be fixed up a bit. As mentioned in the comments you were trying to read the site as json data when it is a text file so I changed webtext = requests.get(url).json() to webtext = requests.get(url).text and added some parsing below your line Lines = we... | [
0
] | [] | [] | [
"json",
"parsing",
"python",
"text_files"
] | stackoverflow_0074505872_json_parsing_python_text_files.txt |
Q:
Measure distance between meshes
For my project, I need to measure the distance between two STL files. I wrote a script that allows reading the files, positioning them in relation to each other in the desired position. Now, in the next step I need to check the distance from one object to the other. Is there a funct... | Measure distance between meshes | For my project, I need to measure the distance between two STL files. I wrote a script that allows reading the files, positioning them in relation to each other in the desired position. Now, in the next step I need to check the distance from one object to the other. Is there a function or script available on a library ... | [
"Pyvista offers a really easy way of calculating just that:\nimport pyvista as pv\nimport numpy as np\n\nmesh_1 = pv.read(**path to mesh 1**)\nmesh_2 = pv.read(**path to mesh 2**)\n\nclosest_cells, closest_points = mesh_2.find_closest_cell(mesh_1.points, return_closest_point=True)\nd_exact = np.linalg.norm(mesh_1 .... | [
1,
0
] | [] | [] | [
"ascii",
"distance",
"intersection",
"python",
"stl_format"
] | stackoverflow_0061159587_ascii_distance_intersection_python_stl_format.txt |
Q:
understanding librosa.feature.spectral_contrast
i am using python and
I am trying to use this function but i am struggling with it.
def extract_feature_for_one_signal(signal):
signal = signal.astype(float)
mel = np.mean(librosa.feature.melspectrogram(signal, sr=SAMPLE_RATE, n_fft=N_FFT, hop_length=HOP_L... | understanding librosa.feature.spectral_contrast | i am using python and
I am trying to use this function but i am struggling with it.
def extract_feature_for_one_signal(signal):
signal = signal.astype(float)
mel = np.mean(librosa.feature.melspectrogram(signal, sr=SAMPLE_RATE, n_fft=N_FFT, hop_length=HOP_LENGTH).T, axis=0)
mfccs = np.mean(librosa.feature... | [
"Your nyquist is would be greater than the sampling rate. Try redcuing the number of filter band from default 6 to maybe 3 or 4. You can also reduce your fmin to say 50.\nThe sampling rate you have choosen is too small. Keep it around 44100, which is the standard. It should work fine then\n"
] | [
0
] | [] | [] | [
"librosa",
"python"
] | stackoverflow_0064119762_librosa_python.txt |
Q:
Fill NaN with the max value from a group
I have an input data as shown:
df = pd.DataFrame({"colony" : [22, 22, 22, 33, 33, 33],
"measure" : [np.nan, 7, 11, 13, np.nan, 9,],
"net/gross" : [np.nan, "gross", "net", "gross", "np.nan", "net"]})
df
colony measure net/gross
0 ... | Fill NaN with the max value from a group | I have an input data as shown:
df = pd.DataFrame({"colony" : [22, 22, 22, 33, 33, 33],
"measure" : [np.nan, 7, 11, 13, np.nan, 9,],
"net/gross" : [np.nan, "gross", "net", "gross", "np.nan", "net"]})
df
colony measure net/gross
0 22 NaN NaN
1 22 7 ... | [
"You can use SeriesGroupBy.transform to get the maximum value for each group then use pandas.Series.fillna.\nTry this :\ndf['measure']= df['measure'].fillna(df.groupby('colony')['measure'].transform('max'))\n\n# Output :\nprint(df)\n\n colony measure\n0 22 11.0\n1 22 7.0\n2 22 11.0\n3... | [
0
] | [] | [] | [
"numpy",
"pandas",
"python"
] | stackoverflow_0074506156_numpy_pandas_python.txt |
Q:
Check for substrings in sequential order using python
I’m currently developing a Blender Add-on that is a lip-sync tool for 2D and 3D animations, and this Add-on includes a Phoneme extractor tool that extracts phonemes from each word.
for example, the sentence I love pizza which is aɪ lʌv ˈpiːtsə. That’s the reaso... | Check for substrings in sequential order using python | I’m currently developing a Blender Add-on that is a lip-sync tool for 2D and 3D animations, and this Add-on includes a Phoneme extractor tool that extracts phonemes from each word.
for example, the sentence I love pizza which is aɪ lʌv ˈpiːtsə. That’s the reason why I’m making a script that will evaluate each character... | [
"You could do this just by looping through the string with a forloop and just having a massive switch statment. You could also have a dictionary of phonemes and their acording functions.\naString = \"bca\"\n\"\"\"\nit got a bit convoluted but the lambda: print(\"contains a\") really just allows you\nto call a funct... | [
0
] | [] | [] | [
"blender",
"evaluate",
"find",
"python",
"string"
] | stackoverflow_0074505647_blender_evaluate_find_python_string.txt |
Q:
How can i get chemical element list?
I'd like to share something with a chemical formula. For example
C14H19NO, C10H12O2, C15H26O
to
{"C14","H19","N","O","C10","H12","O2","C15","H26","O"} like this
I also want to know how to process .txt at once please help me..
num=["1","2","3","4","5","6","7","8","9","0"]
text=... | How can i get chemical element list? | I'd like to share something with a chemical formula. For example
C14H19NO, C10H12O2, C15H26O
to
{"C14","H19","N","O","C10","H12","O2","C15","H26","O"} like this
I also want to know how to process .txt at once please help me..
num=["1","2","3","4","5","6","7","8","9","0"]
text=input("C9H8Cl3")
lis=list(text)
for i in ... | [
"Generally, we can use re.findall here:\nimport re\n\ninp = [\"C14H19NO\", \"C10H12O2\", \"C15H26O\"]\nfor f in inp:\n atoms = re.findall(r'[A-Z][a-z]?[0-9]*', f)\n print(atoms)\n\nThis prints:\n['C14', 'H19', 'N', 'O']\n['C10', 'H12', 'O2']\n['C15', 'H26', 'O']\n\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074506148_python.txt |
Q:
WinError 267 The directory name is invalid
I tried this code in jupyter notebook, and this error occured.
Error : [WinError 267] The directory name is invalid: 'plantdisease/PlantVillage/Pepper__bell___Bacterial_spot/0022d6b7-d47c-4ee2-ae9a-392a53f48647___JR_B.Spot 8964.JPG/'
I'm using python 3.6 in anaconda envi... | WinError 267 The directory name is invalid | I tried this code in jupyter notebook, and this error occured.
Error : [WinError 267] The directory name is invalid: 'plantdisease/PlantVillage/Pepper__bell___Bacterial_spot/0022d6b7-d47c-4ee2-ae9a-392a53f48647___JR_B.Spot 8964.JPG/'
I'm using python 3.6 in anaconda environment, I tried running this code but it showed... | [
"Your path is invalid because it is not a directory. It is a file\n",
"I have changed the path to this\ndirectory_root = 'D:\\Coding files\\Plant disease/x/'\nx is the folder in which PlantVillage dataset is saved in\n\n\n"
] | [
0,
0
] | [] | [] | [
"artificial_intelligence",
"python"
] | stackoverflow_0059332004_artificial_intelligence_python.txt |
Q:
Can I make my padx and pady in place() [In python GUI]
I was trying to use padx and pady in place() in Python tkinter GUI
something I tried :
I want to know that how can I use padx and pady in place() in this way:
from tkinter import *
app = Tk()
app.geometry("433x255")
border = Frame(background = "red")
aboutme =... | Can I make my padx and pady in place() [In python GUI] | I was trying to use padx and pady in place() in Python tkinter GUI
something I tried :
I want to know that how can I use padx and pady in place() in this way:
from tkinter import *
app = Tk()
app.geometry("433x255")
border = Frame(background = "red")
aboutme = Label(border, text = "welcome to my tkinter GUI").place(pad... | [
"I don't think you can use padx and pady configurations on place.\nHere is full list of what you can use.\nhttps://tcl.tk/man/tcl8.6/TkCmd/place.htm#M6\n"
] | [
1
] | [] | [] | [
"python",
"tkinter",
"user_interface"
] | stackoverflow_0074506174_python_tkinter_user_interface.txt |
Q:
Simple python iteration exercise..stuck with try and except
Write a program which repeatedly reads numbers until the user enters "done". Once "done" is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number, detect their mistake using try and except and pri... | Simple python iteration exercise..stuck with try and except | Write a program which repeatedly reads numbers until the user enters "done". Once "done" is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number.
This is what I h... | [
"I know this is old, but thought I'd throw my 2-cents in there (since I myself many years later am using the same examples to learn). You could try: \nvalues=[]\nwhile True: \n A=input('Please type in a number.\\n')\n if A == 'done':\n break\n try:\n B=int(A)\n values.append(B)\n ex... | [
1,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0039175218_python.txt |
Q:
Clicking a button by class name using selenium with python
Probably a silly question, but I have spent a ridiculous amount of time trying to figure this out. I am building a scrapper bot using selenium in python, and I am just trying to click a button on a web page. The web page opens and resizes...
def initalize_... | Clicking a button by class name using selenium with python | Probably a silly question, but I have spent a ridiculous amount of time trying to figure this out. I am building a scrapper bot using selenium in python, and I am just trying to click a button on a web page. The web page opens and resizes...
def initalize_browser():
driver.get("**website name**")
driver.maximize_window... | [
"The method find_element_by_xpath is deprecated now. Use this line:\ndriver.find_element(By.XPATH, '//button[@class=\"mx-auto green-btn btnHref\"]').click()\n\ninstead of:\ndriver.find_element_by_xpath('//button[@class=\"mx-auto green-btn btnHref\"]').click()\n\nAnd be sure you have this in imports:\nfrom selenium.... | [
1
] | [] | [] | [
"python",
"selenium",
"selenium_chromedriver"
] | stackoverflow_0074333322_python_selenium_selenium_chromedriver.txt |
Q:
How would I sort this json based off of each id's score value using Python?
I'm trying to put these ID's in order based off of each ones score value, highest being on the top and lowest being on the bottom
{
"Users": {
"586393728470745123": {
"score": 150,
"name": "user1"
},
"4374651223... | How would I sort this json based off of each id's score value using Python? | I'm trying to put these ID's in order based off of each ones score value, highest being on the top and lowest being on the bottom
{
"Users": {
"586393728470745123": {
"score": 150,
"name": "user1"
},
"437465122378874895": {
"score": 115,
"name": "user2"
},
"904032786854... | [
"Well, i don't know what data structure you want to get, but in Python, dicts do not have no particular order of keys. So, if having a list of user id's, sorted by their score, try something like this (Scores is the dict you posted):\nsorted(list(Scores[\"Users\"]),key= lambda x: Scores[\"Users\"][x][\"score\"])\n\... | [
0
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074506230_json_python.txt |
Q:
How do I merge and sort JSON objects using its counts?
I got two json objects that I need to combine together based on ID and do count and sort operations on it.
Here is the first object comments:
[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati except... | How do I merge and sort JSON objects using its counts? | I got two json objects that I need to combine together based on ID and do count and sort operations on it.
Here is the first object comments:
[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\... | [
"Assuming your posts and comments data structures are lists, you can use python's defaultdict to count the comments. Then, use posts.sort(key=...) to sort your posts based on the collected counts using the key parameter. Altogether, it could like like this:\nimport json\nfrom collections import defaultdict\n\nposts... | [
2,
1
] | [] | [] | [
"django",
"json",
"python",
"sorting"
] | stackoverflow_0074505491_django_json_python_sorting.txt |
Q:
I want to install scipy in debian10/armv7l environment, but it fails
root@ZZZZZ:/home/dev/packages/scipy-1.9.3# pip install .
Processing /home/dev/packages/scipy-1.9.3
Installing build dependencies ... error
error: subprocess-exited-with-error
× pip subprocess to install build dependencies did not run succe... | I want to install scipy in debian10/armv7l environment, but it fails | root@ZZZZZ:/home/dev/packages/scipy-1.9.3# pip install .
Processing /home/dev/packages/scipy-1.9.3
Installing build dependencies ... error
error: subprocess-exited-with-error
× pip subprocess to install build dependencies did not run successfully.
│ exit code: 1
╰─> [369 lines of output]
Ignoring numpy... | [
"This is an error that happens with your pip version. Try to downgrade it to pip=19.0 and try again to see if it works. Also you can try the solution here if downgrading pip doesn't work.\n"
] | [
0
] | [] | [] | [
"pip",
"python",
"python_wheel",
"scipy"
] | stackoverflow_0074506114_pip_python_python_wheel_scipy.txt |
Q:
Error: File could not be downloaded from url: 2Cpatcha Api
I am trying to solve normal captcha using 2Captcha python API, but it gives error that file could not be downloaded. I dont know why is this happening, as I can download it manually from browser and do save as .png to download it. The below is the code
imp... | Error: File could not be downloaded from url: 2Cpatcha Api | I am trying to solve normal captcha using 2Captcha python API, but it gives error that file could not be downloaded. I dont know why is this happening, as I can download it manually from browser and do save as .png to download it. The below is the code
import sys
import os
sys.path.append(os.path.dirname(os.path.dirna... | [
"Your code is fine and it is the problem caused by headers. The url expects headers from you and you are not providing headers. This causes error response which the PIL library can not understand.\nThe working code will be\nurl = 'https://v2.gcchmc.org/captcha/image/aa699f305917812978c911e87ab126a782f726e7/'\nimpor... | [
2
] | [] | [] | [
"2captcha",
"python",
"python_imaging_library",
"python_requests"
] | stackoverflow_0074455872_2captcha_python_python_imaging_library_python_requests.txt |
Q:
python tkinter main window
I was trying to open a code with pycharm and the following lines are the begining . but it doesn't open any window . what should I do ?
import tkinter
mainwindow=tkinter.Tk()
mainwindow.title("Calculator")
mainwindow.geometry('480x240')
buttonOne= tkinter.Button(mainwindow,text='1')
it ... | python tkinter main window | I was trying to open a code with pycharm and the following lines are the begining . but it doesn't open any window . what should I do ?
import tkinter
mainwindow=tkinter.Tk()
mainwindow.title("Calculator")
mainwindow.geometry('480x240')
buttonOne= tkinter.Button(mainwindow,text='1')
it runs and instantly closes withou... | [
"In order to make sure the window doesn't close you need the mainloop function.\nimport tkinter\nmainwindow=tkinter.Tk()\nmainwindow.title(\"Calculator\")\nmainwindow.geometry('480x240')\nbuttonOne= tkinter.Button(mainwindow,text='1')\ntkinter.mainloop()\n\n"
] | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074506323_python_tkinter.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.