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:
Why can't I set the width on my plotly bar chart?
No matter what I try...I cannot seem to adjust the width of my plotly bar chart. Here is my current code and output:
fig = go.Figure(go.Bar(
x=top_10_belg['ID'],
y=top_10_belg['Description'],
marker=dict(color='rgba(50, 171, 96, 0.6)',
l... | Why can't I set the width on my plotly bar chart? | No matter what I try...I cannot seem to adjust the width of my plotly bar chart. Here is my current code and output:
fig = go.Figure(go.Bar(
x=top_10_belg['ID'],
y=top_10_belg['Description'],
marker=dict(color='rgba(50, 171, 96, 0.6)',
line=dict(color='rgba(50, 171, 96, 1.0)',width=1))
,... | [
"The width of the bar chart is set by the number of bars in the list. The value 1.0 sets the interval to zero. So as an example, the width 0.8 is used to list for the category variable. I have reproduced the similar horizontal bar chart in the reference using your decorations.\nfig = go.Figure(go.Bar(\n x=top_10... | [
0
] | [] | [] | [
"plotly",
"python"
] | stackoverflow_0074645139_plotly_python.txt |
Q:
get value of field from an existing module in odoo 15
every product in odoo should have quantity minimum
i have created product and i set the quantity min to it in reordering rule
what i want to do is get the product name and it's quantity min in python
this is my python file
from odoo import fields,models,api
cl... | get value of field from an existing module in odoo 15 | every product in odoo should have quantity minimum
i have created product and i set the quantity min to it in reordering rule
what i want to do is get the product name and it's quantity min in python
this is my python file
from odoo import fields,models,api
class Qty_Min_Alert(models.Model):
_inherit='product.temp... | [
"your question is bit unclear, according to your question what i understood is that you want to set every product in product with a particular quantity which is in your case will be the minimum quantity?\nif so then you have to inherit the product.product and create a method to search all records and then update th... | [
1
] | [] | [] | [
"odoo",
"odoo_15",
"python",
"ubuntu"
] | stackoverflow_0074615440_odoo_odoo_15_python_ubuntu.txt |
Q:
Python Code Line Endings
Which line endings should be used for platform independent code (not file access)?
My next project must run on both Windows and Linux.
I wrote code on Linux and used Hg to clone to Windows and it ran fine with Linux endings. The downside is that if you open the file in something other than... | Python Code Line Endings | Which line endings should be used for platform independent code (not file access)?
My next project must run on both Windows and Linux.
I wrote code on Linux and used Hg to clone to Windows and it ran fine with Linux endings. The downside is that if you open the file in something other than a smart editor the line endin... | [
"In general newlines (as typically used in Linux) are more portable than carriage return and then newline (as used in Windows). Note also that if you store your code on GitHub or another Git repository, it will convert it properly without you having to do anything.\n",
"As John Messenger states, newlines (\\n) a... | [
1,
0
] | [] | [] | [
"line_endings",
"python"
] | stackoverflow_0035639333_line_endings_python.txt |
Q:
What type of line breaks does a Python script normally have?
My boss keeps getting annoyed at me for having Windows line breaks in my Python scripts, but I can't for the life of me work out how they are causing him a problem.
Is '\r\n' the normal line-break for a Python script? Or does that only happen on IDLE fo... | What type of line breaks does a Python script normally have? | My boss keeps getting annoyed at me for having Windows line breaks in my Python scripts, but I can't for the life of me work out how they are causing him a problem.
Is '\r\n' the normal line-break for a Python script? Or does that only happen on IDLE for PC?
PS: OK, it seems when I write the script on a Mac that it h... | [
"This has nothing to do with Python but with the underlying OS. If you save a text file on Windows, you get CRLF linebreaks, if you save it on Mac/Unix systems, you get LF linebreaks (and on stone-age Macs, CR linebreaks).\nUse an editor that allows you to preserve the line break format of your files. No, Notepad d... | [
1,
1,
0,
0,
0
] | [] | [] | [
"line_breaks",
"python",
"python_2.x"
] | stackoverflow_0006907245_line_breaks_python_python_2.x.txt |
Q:
UserWarning: positional arguments and argument "destination" are deprecated - Pytorch nn.modules.module.state_dict()
I am trying to manage the checkpoints of my Pytorch model through torch.save():
Pytorch 1.12.0 and Python 3.7
torch.save({
'epoch': epoch,
'model_state_dict': model.state_dict(),
... | UserWarning: positional arguments and argument "destination" are deprecated - Pytorch nn.modules.module.state_dict() | I am trying to manage the checkpoints of my Pytorch model through torch.save():
Pytorch 1.12.0 and Python 3.7
torch.save({
'epoch': epoch,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict()
}, full_path)
But I am getting the following warning for mode... | [
"I have the same error, as a result it is not logging dict training logs. I'm training using PyTorch Lightning in DDP. I works on single GPU but gives this warming on multi-gpu system with DDP.\n"
] | [
0
] | [] | [] | [
"python",
"pytorch",
"state_dict",
"warnings"
] | stackoverflow_0071600617_python_pytorch_state_dict_warnings.txt |
Q:
Discord Bot, how do I take this code and try to make it work in videos links as well?
My Issue
The code at the bottom works perfectly but it only works with channels. I understand why it's not working but I can't find the right values for the yson decoding.
The code directly below this paragraph is the code that n... | Discord Bot, how do I take this code and try to make it work in videos links as well? | My Issue
The code at the bottom works perfectly but it only works with channels. I understand why it's not working but I can't find the right values for the yson decoding.
The code directly below this paragraph is the code that needs changing a bit I think.
# Finds chan... | [
"I resolved the issue by adding pytube support. You can see how I did it here.\nhttps://github.com/flyinggoatman/YouTube-Link-Extractor\n"
] | [
0
] | [] | [] | [
"beautifulsoup",
"discord",
"discord.py",
"python"
] | stackoverflow_0074646591_beautifulsoup_discord_discord.py_python.txt |
Q:
Stopping messagebox from looping the entire textfile after it found a value
i created register and login app. I made a messagebox that pops up when it found a value in the textfiles and also when it doesnt find the value. However it keeps looping my entire textfiles so it loops untill it find the value. How do i p... | Stopping messagebox from looping the entire textfile after it found a value | i created register and login app. I made a messagebox that pops up when it found a value in the textfiles and also when it doesnt find the value. However it keeps looping my entire textfiles so it loops untill it find the value. How do i prevent it form looping? I tried break but it made it stop at 1st row of textfiles... | [
"You need to add break after the line tkMessageBox.askokcancel(\"System\",\"logged\",). Also the else block should be in same indentation of the for line.\nBelow is the modified Chek():\n def Chek():\n for line in open(\"users.txt\", \"r\").readlines():\n loginn_info = line.split()\n ... | [
0
] | [] | [] | [
"loops",
"messagebox",
"python",
"tkinter"
] | stackoverflow_0074650430_loops_messagebox_python_tkinter.txt |
Q:
Flutter WEB sending file to Django Rest Framework Backend
So in my flutter front end (WEB). I am using Image_picker and then image_cropper packages to obtain a file.
I know flutter web doesn't support Dart/io so instead you have to send your image in a mulitpart request FromBYtes. Normally for an ios/android flut... | Flutter WEB sending file to Django Rest Framework Backend | So in my flutter front end (WEB). I am using Image_picker and then image_cropper packages to obtain a file.
I know flutter web doesn't support Dart/io so instead you have to send your image in a mulitpart request FromBYtes. Normally for an ios/android flutter app you can use fromFile.
Now I send that to my backend as ... | [
"so i figured it out.\nwhen making that call from Flutter WEB YOU MUST include:\nvar profilepic = await http.MultipartFile.fromBytes(\n\"profilepic\", file, filename: 'hello.png');\nThe filename. this is needed for django restframework and multiformparser to be able to save it as image.\n"
] | [
1
] | [] | [] | [
"django",
"django_rest_framework",
"flutter",
"multipartform_data",
"python"
] | stackoverflow_0074649077_django_django_rest_framework_flutter_multipartform_data_python.txt |
Q:
Language Translator Using Google API in Python
I have used this code from geeksforgeeks (https://www.geeksforgeeks.org/language-translator-using-google-api-in-python/), I am trying to run it and it runs without any error, and it prints out:
Speak 'hello' to initiate the Translation !
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... | Language Translator Using Google API in Python | I have used this code from geeksforgeeks (https://www.geeksforgeeks.org/language-translator-using-google-api-in-python/), I am trying to run it and it runs without any error, and it prints out:
Speak 'hello' to initiate the Translation !
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
but when i say "hello" it does not r... | [
"from gtts import gTTS\nfrom io import BytesIO\nfrom pygame import mixer\nimport time\n\ndef speak():\n mp3_fp = BytesIO()\n tts = gTTS('KGF is a Great movie to watch', lang='en')\n tts.write_to_fp(mp3_fp)\n tts.save(\"Audio.mp3\")\n return mp3_fp\n\nmixer.init()\nsound = speak()\nsound.seek(0)\nmixe... | [
0
] | [] | [] | [
"google_api",
"language_translation",
"python"
] | stackoverflow_0074143619_google_api_language_translation_python.txt |
Q:
How do I remove an unwanted word on python using Beautifulsoup?
I just started learning Python, every white level knowledge. I am trying to webscrape from a website and tweet it.
Here's my code.
def scrape ():
page = requests.get("https://www.reuters.com/business/future-of-money/")
soup = BeautifulSoup(pag... | How do I remove an unwanted word on python using Beautifulsoup? | I just started learning Python, every white level knowledge. I am trying to webscrape from a website and tweet it.
Here's my code.
def scrape ():
page = requests.get("https://www.reuters.com/business/future-of-money/")
soup = BeautifulSoup(page.content, "html.parser")
home = soup.find(class_="editorial-fran... | [
"You have to access the span element within h3 to get your desired output\nChange\ntop_post = posts[0].find(\n\"h3\", class_=\"text__text__1FZLe text__dark-grey__3Ml43 text__medium__1kbOh text__heading_3__1kDhc heading__base__2T28j heading__heading_3__3aL54 hero-card__title__33EFM\").text.strip()\n\nto\ntop_post = ... | [
1
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074650519_beautifulsoup_python_web_scraping.txt |
Q:
Fit function in sklearn KNN model does not work: 'n_neighbors does not take value, enter integer value'
I am working on a project where I want to use the KNN model from the sklearn library. I simplified the original problem to the following one. X1, X2 and X3 are the predicters to assign each row to a category (Y... | Fit function in sklearn KNN model does not work: 'n_neighbors does not take value, enter integer value' | I am working on a project where I want to use the KNN model from the sklearn library. I simplified the original problem to the following one. X1, X2 and X3 are the predicters to assign each row to a category (Y- variable), which is either 1 or 2. I used a online instruction and all went fine untill I use the fit functi... | [
"In your example, k is a float, not an integer. The n_neighbors value in KNeighborsClassifier(n_neighbors=k, p=2,metric='euclidean') has to be an integer, not a float.\nYou could convert k into an integer in this example using the math.ceil() function which return the integer that is equal to or greater than the fl... | [
1
] | [] | [] | [
"knn",
"pandas",
"python",
"scikit_learn"
] | stackoverflow_0074650080_knn_pandas_python_scikit_learn.txt |
Q:
Why can't client.message.create() receive an f-string as argument for its body parameter?
I'm building a Flask API, and one of its use cases consists on sending a WhatsApp message to a requested phone number. So far, I've been testing this feature through Twilio's sandbox & phone number in a trial account.
This is... | Why can't client.message.create() receive an f-string as argument for its body parameter? | I'm building a Flask API, and one of its use cases consists on sending a WhatsApp message to a requested phone number. So far, I've been testing this feature through Twilio's sandbox & phone number in a trial account.
This is my use case code:
def send_greetings(order_id):
try:
phone = format_phone_number(
... | [
"There's nothing magical about f-strings. The bad behavior must be caused by something else.\nThere is absolutely no difference in the return values of these two functions:\ndef hello():\n return \"Hello John\"\n\ndef hello_f():\n name = \"John\"\n return f\"Hello {name}\"\n\nAnyone calling these function... | [
3
] | [] | [] | [
"flask",
"python",
"twilio",
"twilio_api",
"whatsapi"
] | stackoverflow_0074650558_flask_python_twilio_twilio_api_whatsapi.txt |
Q:
Trailing tab in the string not getting printed using the print function in python (python3)
I am trying to print a string with \t at both beginning and end, like below.
name2print="\tabhinav\t"
lastname="gupta"
print(name2print,lastname)
Expected output should be
abhinav gupta
But the actual out... | Trailing tab in the string not getting printed using the print function in python (python3) | I am trying to print a string with \t at both beginning and end, like below.
name2print="\tabhinav\t"
lastname="gupta"
print(name2print,lastname)
Expected output should be
abhinav gupta
But the actual output is
abhinav gupta
I tried with lstrip like this and as expected strips only the begi... | [
"The output is correct. \\t adds a variable number of spaces so that the next printed character is at a position which is a multiple of 8 (or whatever is configured in your terminal).\nIn your example the first \\t adds 8 spaces, then you print abhinav (7 characters), the next tab adds 1 space to make it a multiple... | [
0,
0
] | [] | [] | [
"printing",
"python",
"string",
"tabs"
] | stackoverflow_0074650572_printing_python_string_tabs.txt |
Q:
How to crack a cisco type 9 encryption password
I would like to decrypt an encrypted password in type 9 in a cisco device in python.
I do no have a code yet due to the reason I do not know where to start..
Thanks,
crack a cisco type 9 password in python
A:
These is no known vulnerability to decrypt type 9 cisco ... | How to crack a cisco type 9 encryption password | I would like to decrypt an encrypted password in type 9 in a cisco device in python.
I do no have a code yet due to the reason I do not know where to start..
Thanks,
crack a cisco type 9 password in python
| [
"These is no known vulnerability to decrypt type 9 cisco password, so the answer is that you can not decrypt it.\n"
] | [
0
] | [] | [] | [
"cisco",
"cracking",
"passwords",
"python",
"scrypt"
] | stackoverflow_0074597471_cisco_cracking_passwords_python_scrypt.txt |
Q:
discord.py - count how many times a user has bee mentioned in a specific channel
I'm coding a discord bot a for a friend using python (discord.py) and i've a specific task i want the bot to do that i can't figure out how to code (i'm kinda a newbie with py), so here it is: we use a specific text-channel to post wi... | discord.py - count how many times a user has bee mentioned in a specific channel | I'm coding a discord bot a for a friend using python (discord.py) and i've a specific task i want the bot to do that i can't figure out how to code (i'm kinda a newbie with py), so here it is: we use a specific text-channel to post wins of the games we play mentioning every partecipant, i want the bot to count every me... | [
"Maybe something like this, where it iterates over every message sent in the current channel?\n@bot.command()\nasync def some_command(ctx):\n mentions = 0\n\n async for message in ctx.channel.history(limit=10000000): # set limit to some big number\n if ctx.author in message.mentions:\n ment... | [
1
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0074646074_discord.py_python.txt |
Q:
Unable to play & convert .txt to mp3 using GTTS
I'm trying to read a .txt file using Google's text-to-speech API. But, when I try to run it, it gives an error that I can't quite fathom. So your help will be greatly appreciated!
My Python code:
#Import the required module for text
from gtts import gTTS
#requir... | Unable to play & convert .txt to mp3 using GTTS | I'm trying to read a .txt file using Google's text-to-speech API. But, when I try to run it, it gives an error that I can't quite fathom. So your help will be greatly appreciated!
My Python code:
#Import the required module for text
from gtts import gTTS
#required to play the converted file
import os
#The file yo... | [
"from gtts import gTTS\nfrom io import BytesIO\nfrom pygame import mixer\nimport time\n\ndef speak():\n mp3_fp = BytesIO()\n tts = gTTS('You need to read documetation properly', lang='en')\n tts.write_to_fp(mp3_fp)\n tts.save(\"Audio.mp3\")\n return mp3_fp\n\nmixer.init()\nsound = speak()\nsound.seek... | [
1,
0
] | [] | [] | [
"gtts",
"operating_system",
"python"
] | stackoverflow_0065981046_gtts_operating_system_python.txt |
Q:
How do I extract username from the json.loads object
I have a following block of code:
import json
from types import SimpleNamespace
data=json.dumps(
{
"update_id": 992108054,
"message": {
"delete_chat_photo": False,
"new_chat_members": [],
"date": 1669931418,
"photo": [],
"entities": [],
... | How do I extract username from the json.loads object | I have a following block of code:
import json
from types import SimpleNamespace
data=json.dumps(
{
"update_id": 992108054,
"message": {
"delete_chat_photo": False,
"new_chat_members": [],
"date": 1669931418,
"photo": [],
"entities": [],
"message_id": 110,
"group_chat_created": False,
... | [
"You can access the fields inside the from block by using square bracket notation instead of dot notation. Here is how your code would look with the changes:\n\ndata=json.dumps(\n{\n \"update_id\": 992108054,\n \"message\": {\n \"delete_chat_photo\": False,\n \"new_chat_members\": [],\n \"date\": 1669931... | [
0,
0
] | [] | [] | [
"json",
"python",
"telegram_bot"
] | stackoverflow_0074648762_json_python_telegram_bot.txt |
Q:
How to know embed's text and author in discord.py?
I was trying to find the way you can identify embed message text and author, but never found it. So is there any way to do that?
Googled through out of the Internet but not found it unfortunately.
A:
Take a look at the docs here
If you have an Embed object, obj ... | How to know embed's text and author in discord.py? | I was trying to find the way you can identify embed message text and author, but never found it. So is there any way to do that?
Googled through out of the Internet but not found it unfortunately.
| [
"Take a look at the docs here\nIf you have an Embed object, obj just use obj.author to get the author. The text I'm assuming you mean the title, which can be accessed by obj.title.\n",
"Assuming you have a Message object,\nFirst, to get message author:\nauthor = message.author\n\nTo get the embed from the message... | [
1,
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074646811_discord_discord.py_python.txt |
Q:
after installing panda while importing in python Error: module 'os' has no attribute 'add_dll_directory'
After installing panda while importing in python I got the following Error:
File "<stdin>", line 1, in <module>
File "C:\Users\ss\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\__init__.py",... | after installing panda while importing in python Error: module 'os' has no attribute 'add_dll_directory' | After installing panda while importing in python I got the following Error:
File "<stdin>", line 1, in <module>
File "C:\Users\ss\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\__init__.py", line 11, in <module>
__import__(dependency)
File "C:\Users\ss\AppData\Local\Programs\Python\Python38\li... | [
"Remove Numpy Package and install again. The error will go away.\n"
] | [
0
] | [] | [] | [
"importerror",
"pandas",
"python"
] | stackoverflow_0061318720_importerror_pandas_python.txt |
Q:
Conda cannot find package despite package being listed on anaconda.org
I am trying to install zipline-reloaded using conda but am encountering a PackagesNotFoundError—this despite running the install command for zipline-reloaded provided on the package's page on anaconda.org. What might be going wrong here, and ho... | Conda cannot find package despite package being listed on anaconda.org | I am trying to install zipline-reloaded using conda but am encountering a PackagesNotFoundError—this despite running the install command for zipline-reloaded provided on the package's page on anaconda.org. What might be going wrong here, and how can I resolve it?
My steps this far:
conda create -n zipline python=3.8
c... | [
"You are trying to install onto a mac with an arm processor (see platform : osx-arm64 in the output of conda info). But https://anaconda.org/ml4t/zipline-reloaded shows the channel you are attempting to install from does not have an osx-arm64 build.\n",
"Will Holtz was right in pointing out that the problem stems... | [
1,
0
] | [] | [] | [
"anaconda",
"conda",
"mini_forge",
"python"
] | stackoverflow_0074637834_anaconda_conda_mini_forge_python.txt |
Q:
list of dictionaries in another list and sort it according to date without using sort
I have a list of dictionaries in another list, I want sort those lists of dictionaries according to the date but I can't use sort function I don't know how to access in list (May be date it is not in correct way)
I WANT TO KNOW H... | list of dictionaries in another list and sort it according to date without using sort | I have a list of dictionaries in another list, I want sort those lists of dictionaries according to the date but I can't use sort function I don't know how to access in list (May be date it is not in correct way)
I WANT TO KNOW HOW TO SORT SOME THING LIKE THIS OR HOW TO GET ACCESS TO THE "DATE"
dr = [
[{"name": "Tom"... | [
"If the \"date\" key was actually a date (which currently isn't), this would have worked:\nfor j in range(len(dr)):\n for k in range(j + 1, len(dr)):\n if dr[j][0][\"date\"] < dr[k][0][\"date\"]:\n dr[j], dr[k] = dr[k], dr[j]\n\nYour problem is, because dr is a list of list of dictionaries (i.e... | [
0,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074650675_dictionary_list_python.txt |
Q:
Is there a way to print a list of online members of a channel with a Discord Bot?
I am trying to create a function of my discord bot where on a command it prints the names of online members in a specific channel to the chat. I can get the bot to print all members of a channel but cannot get it to isolate only the ... | Is there a way to print a list of online members of a channel with a Discord Bot? | I am trying to create a function of my discord bot where on a command it prints the names of online members in a specific channel to the chat. I can get the bot to print all members of a channel but cannot get it to isolate only the online members.
My current code is thus
linkchannel = int(message.channel.topic)
... | [
"You need member intents for this to function.\nFor more information on how to enable member intents, read the official documentation, or this answer that explains it quite clearly.\n"
] | [
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074540901_discord_discord.py_python.txt |
Q:
Initialize a superclass with an existing object (copy constructor)
Preface: From my understanding the existing answers to this question assume control over the source or work around the problem.
Given a Super class, and MyClass which derives from it: How can an existing instance of a Super class be used as a base?... | Initialize a superclass with an existing object (copy constructor) | Preface: From my understanding the existing answers to this question assume control over the source or work around the problem.
Given a Super class, and MyClass which derives from it: How can an existing instance of a Super class be used as a base? The goal is to not call super().__init__() with fields from existing_su... | [
"One way to approach it is to convert your instance of the super class into an instance of the subclass using the __class__ attribute.\nclass A:\n def __init__(self):\n self.A_attribute = 'from_A'\n\n\nclass B(A):\n def __init__(self):\n #Create an instance of B from scratch\n self.B_attr... | [
0
] | [] | [] | [
"constructor",
"inheritance",
"python",
"super"
] | stackoverflow_0071209560_constructor_inheritance_python_super.txt |
Q:
How do I divide the hourly data into 5 mininutes interval and ensure the records are same for each hour?
I received data similar to this format
Time Humidity Condition
2014-09-01 00:00:00 84 Cloudy
2014-09-01 01:00:00 94 Rainy
I tried to use df.resample('5T')
but it see... | How do I divide the hourly data into 5 mininutes interval and ensure the records are same for each hour? | I received data similar to this format
Time Humidity Condition
2014-09-01 00:00:00 84 Cloudy
2014-09-01 01:00:00 94 Rainy
I tried to use df.resample('5T')
but it seems the data cannot be replicated for the same hour and df.resample('5T') need the function like mean() but I d... | [
"Example\ndata = {'Time': {0: '2014-09-01 00:00:00', 1: '2014-09-01 01:00:00'},\n 'Humidity': {0: 84, 1: 94},\n 'Condition': {0: 'Cloudy', 1: 'Rainy'}}\ndf = pd.DataFrame(data)\n\ndf\n Time Humidity Condition\n0 2014-09-01 00:00:00 84 Cloudy\n1 2014-09-01 01:00:00 94 ... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074650541_dataframe_pandas_python.txt |
Q:
django.db.utils.IntegrityError: CHECK constraint failed
when I am migrating I am getting the error django.db.utils.IntegrityError: CHECK constraint failed. I am using django-cms. this error popped up after trying to add editor.js to the project
full Error:
Applying advita.0003_auto_20220615_1506...Traceback (mos... | django.db.utils.IntegrityError: CHECK constraint failed | when I am migrating I am getting the error django.db.utils.IntegrityError: CHECK constraint failed. I am using django-cms. this error popped up after trying to add editor.js to the project
full Error:
Applying advita.0003_auto_20220615_1506...Traceback (most recent call last):
File "C:\Users\mulla\AppData\Local\Pro... | [
"This is happening because field 'sub_title' has values earlier which are not valid json.\nTable probably already has values for 'sub_title' field and you are changing trying to change earlier fieldtype to jsonfield if this is the case, you should update all values to valid json first.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0072629593_django_python.txt |
Q:
Python: How to get attribute of attribute of an object with getattr?
How do I evaluate
a = myobject.id.number
and return None if it myobject is None
with built-in getattr? Maybe getattr(myobject, "id.number", None)?
A:
This should scale well to any depth:
reduce(lambda obj, attr : getattr(obj, attr, None), ("id... | Python: How to get attribute of attribute of an object with getattr? | How do I evaluate
a = myobject.id.number
and return None if it myobject is None
with built-in getattr? Maybe getattr(myobject, "id.number", None)?
| [
"This should scale well to any depth:\nreduce(lambda obj, attr : getattr(obj, attr, None), (\"id\",\"num\"), myobject)\n\n",
"getattr(getattr(myobject, \"id\", None), \"number\", None)\n\nshould work.\n",
"my favorites are\nfrom functools import reduce\ntry:\n a = reduce(getattr, (\"id\", \"number\"), myobject... | [
7,
6,
4,
1,
0,
0,
0
] | [] | [] | [
"attributes",
"object",
"python"
] | stackoverflow_0014925239_attributes_object_python.txt |
Q:
Create a Java UDF that uses geoip2 library with the database in a S3 bucket
Correct me if i'm wrong, but my understanding of the UDF function in Snowpark is that you can send the function UDF from your IDE and it will be executed inside Snowflake. I have a staged database called GeoLite2-City.mmdb inside a S3 buck... | Create a Java UDF that uses geoip2 library with the database in a S3 bucket | Correct me if i'm wrong, but my understanding of the UDF function in Snowpark is that you can send the function UDF from your IDE and it will be executed inside Snowflake. I have a staged database called GeoLite2-City.mmdb inside a S3 bucket on my Snowflake account and i would like to use it to retrieve informations ab... | [
"This will be more complicated that it looks:\n\nTo use session.add_packages('geoip2') in Snowflake you need to accept the Anaconda terms. This is easy if you can ask your account admin.\nBut then you can only get the packages that Anaconda has added to Snowflake in this way. The list is https://repo.anaconda.com/p... | [
0
] | [] | [] | [
"python",
"snowflake_cloud_data_platform",
"snowpark",
"user_defined_functions"
] | stackoverflow_0074649140_python_snowflake_cloud_data_platform_snowpark_user_defined_functions.txt |
Q:
Querying dynamodb returns "Can't Pick _thread.lock"?
I'm trying to make a general dynamodb query but keep getting a TypeError: can't pickle _thread.lock object.
response = table.query(
KeyConditionExpression=Key("Key").eq("Whatever")
)
Any possible pointers? I did some research prior and appar... | Querying dynamodb returns "Can't Pick _thread.lock"? | I'm trying to make a general dynamodb query but keep getting a TypeError: can't pickle _thread.lock object.
response = table.query(
KeyConditionExpression=Key("Key").eq("Whatever")
)
Any possible pointers? I did some research prior and apparently this error appears when trying to do multithreading,... | [
"try this:\ntable = boto3.resource(\"dynamodb\", \"region\").Table('table_name')\nresponse = table.query(KeyConditionExpression=Key(\"Key\").eq(\"Whatever\"))\n\n"
] | [
0
] | [] | [] | [
"boto3",
"dynamodb_queries",
"python"
] | stackoverflow_0069922193_boto3_dynamodb_queries_python.txt |
Q:
Pytest - how to skip tests unless you declare an option/flag?
I have some unit tests, but I'm looking for a way to tag some specific unit tests to have them skipped unless you declare an option when you call the tests.
Example:
If I call pytest test_reports.py, I'd want a couple specific unit tests to not be run.
... | Pytest - how to skip tests unless you declare an option/flag? | I have some unit tests, but I'm looking for a way to tag some specific unit tests to have them skipped unless you declare an option when you call the tests.
Example:
If I call pytest test_reports.py, I'd want a couple specific unit tests to not be run.
But if I call pytest -<something> test_reports, then I want all my ... | [
"We are using markers with addoption in conftest.py\ntestcase:\n@pytest.mark.no_cmd\ndef test_skip_if_no_command_line():\n assert True\n\nconftest.py:\nin function\ndef pytest_addoption(parser):\n parser.addoption(\"--no_cmd\", action=\"store_true\",\n help=\"run the tests only in case of ... | [
25,
23,
5,
3,
0
] | [] | [] | [
"pytest",
"python",
"unit_testing"
] | stackoverflow_0047559524_pytest_python_unit_testing.txt |
Q:
Telthon client Get link/url for all Groups or channel
Hello im try to find a solution to get for all groups i have in telgram app to save in one list
If is group i can generate a link
if is private channel can i generate join url
i get group id name and all info but i can get URL
Thanks
`
async for dialog in cli... | Telthon client Get link/url for all Groups or channel | Hello im try to find a solution to get for all groups i have in telgram app to save in one list
If is group i can generate a link
if is private channel can i generate join url
i get group id name and all info but i can get URL
Thanks
`
async for dialog in client.iter_dialogs():
if dialog.is_group: ... | [
"\"URL\" is \"https://t.me/username\". if an entity object has username attribute; it's public. else if you're an owner or admin (with needed permissions) you get the invite link by making a seperate request.\nimport telethon.tl.functions as _fn \n\nasync for d in client.iter_dialogs():\n if not d.is_group: contin... | [
0
] | [] | [] | [
"api",
"python",
"telegram",
"telethon"
] | stackoverflow_0074649844_api_python_telegram_telethon.txt |
Q:
OSMNX graph to torch_geometry Error: "Could not infer dtype of Point"
I am a freshman in graph neural networks. Recently I have been struggling with doing TGCN on the transportation network.
I have a lot of Geospatial data points with timestamps in one area. I want to map /summarize these data to node and edge fea... | OSMNX graph to torch_geometry Error: "Could not infer dtype of Point" | I am a freshman in graph neural networks. Recently I have been struggling with doing TGCN on the transportation network.
I have a lot of Geospatial data points with timestamps in one area. I want to map /summarize these data to node and edge features of a graph representing the transportation network.
What I have achie... | [
"I'm not familiar with OSMNX graphs but I just ran into a similar issue where the error message\n\nRuntimeError: Could not infer dtype of CLASS\n\ncomes from from_networkx() or more specifically, the convert() subroutine it called.\nI fixed the issue by creating a no-data networkx graph:\nno_data_graph = networkx.D... | [
0
] | [] | [] | [
"graph",
"osmnx",
"python",
"pytorch",
"pytorch_geometric"
] | stackoverflow_0073991516_graph_osmnx_python_pytorch_pytorch_geometric.txt |
Q:
Store Values generated in a while loop on a list in python
Just a simple example of what i want to do:
numberOfcalculations = 3
count = 1
while contador <= numberOfcalculations:
num = int(input(' number:'))
num2 = int(input(' other number:'))
calculate = num * num2
print(calculate)
count =... | Store Values generated in a while loop on a list in python | Just a simple example of what i want to do:
numberOfcalculations = 3
count = 1
while contador <= numberOfcalculations:
num = int(input(' number:'))
num2 = int(input(' other number:'))
calculate = num * num2
print(calculate)
count = count + 1
How do i store the 3 different values that "calculat... | [
"When you initialize calculate as list type you can append values with + operator:\nnumberOfcalculations = 3\ncount = 1\ncalculate = []\nwhile count <= numberOfcalculations:\n num = int(input(' number:'))\n num2 = int(input(' other number:'))\n \n calculate += [ num * num2 ]\n print(calculate)\n c... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074650866_python.txt |
Q:
Trying to print the die value
So as in the title Im trying to print the dice value when it runs but im not sure how to do it
from random import randint
class Die(object):
def __init__(self):
set.value=1
def roll(self):
self.value=randint(1,6)
def getvalue(self):
return s... | Trying to print the die value | So as in the title Im trying to print the dice value when it runs but im not sure how to do it
from random import randint
class Die(object):
def __init__(self):
set.value=1
def roll(self):
self.value=randint(1,6)
def getvalue(self):
return self.value
def __str__(self):
... | [
"First of all, there is a typo in your init. It should be self.value = 1\nTo print a dice value after a roll, you first need to create an object of your class Die.\nnew_dice = Die()\n\nThen, call method roll:\nnew_dice.roll()\n\nNow, the value after the roll is stored in the object. To print the dice value you can ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074650224_python.txt |
Q:
Content pulled via Headless Selenium Chromedriver does not reflect dynamically updating content on webpage (as it does in "headful" mode)
TL;DR: content from a webpage that is known to dynamically update over time only updates in the headful Chromedriver, but does not dynamically update if the Chromedriver is head... | Content pulled via Headless Selenium Chromedriver does not reflect dynamically updating content on webpage (as it does in "headful" mode) | TL;DR: content from a webpage that is known to dynamically update over time only updates in the headful Chromedriver, but does not dynamically update if the Chromedriver is headless. How can I preserve the headful updates in the headless driver condition?
I am using Python Selenium (version=3.141.0) Chromedriver (chrom... | [
"The Chromium developers recently added a 2nd headless mode that functions the same way as normal Chrome.\n--headless=chrome\n(the old way was: --headless or options.headless = True)\nThe New Headless Mode Usage:\noptions.add_argument(\"--headless=chrome\")\n\nYou should be able to use that mode and get the same re... | [
0,
0
] | [] | [] | [
"headless",
"python",
"selenium",
"selenium_chromedriver",
"selenium_webdriver"
] | stackoverflow_0073846185_headless_python_selenium_selenium_chromedriver_selenium_webdriver.txt |
Q:
What's wrong here and why is 'int' not "iterable"
I am making some type of "encoder" program which uses 16 'int' functions in total, but for some reason, they raise an error bcuz they are not "iterable"
This is the code(from text to numbers and from numbers to text aren't actual code lines):
from text to numbers
... | What's wrong here and why is 'int' not "iterable" | I am making some type of "encoder" program which uses 16 'int' functions in total, but for some reason, they raise an error bcuz they are not "iterable"
This is the code(from text to numbers and from numbers to text aren't actual code lines):
from text to numbers
chara=str(numbers[int(chara,36)-10])
charb=str(numbe... | [
"Your error comes from for x in n: in your num_to_let function. In Python, we can't use a for loop to traverse through an integer, because Python doesn't know how.\nInstead, you can iterate/traverse through a string. (it is a collection of characters, so Python knows how to traverse through it) Now you can actually... | [
1
] | [] | [] | [
"integer",
"iterable",
"python"
] | stackoverflow_0074647861_integer_iterable_python.txt |
Q:
List directory tree structure in python from a list of path file
The question is intended to broaden the scope of a question already answered on stackoverflow by the topic "List directory tree structure in python?".
The goal is to form a list of strings that visually represent a directory tree, with branchs.
But i... | List directory tree structure in python from a list of path file | The question is intended to broaden the scope of a question already answered on stackoverflow by the topic "List directory tree structure in python?".
The goal is to form a list of strings that visually represent a directory tree, with branchs.
But instead of the input being a valid directory path (as in the already an... | [
"Possible solution:\npaths = {\n 'main_folder': {\n 'file01.txt': 'txt',\n 'file02.txt': 'txt',\n 'folder_sub1': {\n 'file03.txt': 'txt',\n 'file04.txt': 'txt',\n 'file05.txt': 'txt',\n 'folder_sub1-1': {\n 'file06.txt': 'txt',\n ... | [
2,
1,
0
] | [] | [] | [
"directory_structure",
"python",
"tree",
"treeview"
] | stackoverflow_0072618673_directory_structure_python_tree_treeview.txt |
Q:
Python block/halt on importing torch
I have developed a deep-learning object-detect program based on pytorch and it works very well. Today I deploy this program on a PC, everything goes well, but the program cannot be launched. Debug and find out that, the program blocks, or halts, on importing pytorch.
Simply sta... | Python block/halt on importing torch | I have developed a deep-learning object-detect program based on pytorch and it works very well. Today I deploy this program on a PC, everything goes well, but the program cannot be launched. Debug and find out that, the program blocks, or halts, on importing pytorch.
Simply start a python prompt, type import torch and ... | [] | [] | [
"In my case, in my directory with the main python file, there was also a file named signal.py, when i renamed it to signal1.py everything started working. So try to find some other python files in your directory and try rename it.\n"
] | [
-1
] | [
"python",
"pytorch"
] | stackoverflow_0064278495_python_pytorch.txt |
Q:
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu, using Google Colab GPU environment
I'm working with this notebook right now, using Google Colab GPU environment. When I execute the block containing the following code
with torch.no_grad():
generated_im... | RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu, using Google Colab GPU environment | I'm working with this notebook right now, using Google Colab GPU environment. When I execute the block containing the following code
with torch.no_grad():
generated_images = vae.decode(generated_image_codes)
I got the following error:
---------------------------------------------------------------------------
Runt... | [
"If you executed the code blocks sequentially, both generated_image_codes and vae should be on the same device, i.e. CPU.\ngenerated_image_codes = torch.cat(generated_image_codes, axis=0).cpu()\n\nand\ntorch.cuda.empty_cache()\nvae.cpu()\n\nTo double check, you can run\nprint(generated_image_codes.device)\nprint(ne... | [
0
] | [] | [] | [
"python",
"pytorch"
] | stackoverflow_0074647808_python_pytorch.txt |
Q:
A problem with output of the program [estimated end of pandemic]
I used mathemetical formula to calculate estimated number of weeks for an end of pandemic with respect to countries' data. It was supposed to be harmonic sequence that accounts uncertainty, vaccinated people and vaccine per 100 people. The output for... | A problem with output of the program [estimated end of pandemic] | I used mathemetical formula to calculate estimated number of weeks for an end of pandemic with respect to countries' data. It was supposed to be harmonic sequence that accounts uncertainty, vaccinated people and vaccine per 100 people. The output for all countries is the same which concerns me. I understand that my for... | [
"There are a few errors in your code\n\nAs the comment mentioned, you are using “or” condition wrongly\nYour “if” and “elif” is not on the same indentation\nTo calculate harmonic mean, it would be better to collect a list of values (instead of a sum), and perform n divide by the sum of reciprocals\nRelating to your... | [
0
] | [] | [] | [
"add",
"formula",
"function",
"python",
"sequence"
] | stackoverflow_0074651044_add_formula_function_python_sequence.txt |
Q:
didn't recv UDP dgram socket
So. There is a server and a client. The client knows the address of the server based on UDP dgram and sends packets to the server. But strange thing. Packets seem to be leaving, but the server does not read them. That is, in the recv block, he does not see messages until a mutual packe... | didn't recv UDP dgram socket | So. There is a server and a client. The client knows the address of the server based on UDP dgram and sends packets to the server. But strange thing. Packets seem to be leaving, but the server does not read them. That is, in the recv block, he does not see messages until a mutual packet is sent back to the client (know... | [
"it was all because of NAT. if you interested in this topic, you can learn about ways to bypass NAT.\nThanks everyone for replies.\n"
] | [
0
] | [] | [] | [
"python",
"sockets",
"udp"
] | stackoverflow_0074634006_python_sockets_udp.txt |
Q:
Remove mode entirely
I am trying to write a method that removes the mode entirely from a list. I've looked up other articles to use a for loop but it doesn't entirely get rid of the mode from the list like it needs to.
this is what my list would look like before I get rid of the mode entirely from a list.
list = 1... | Remove mode entirely | I am trying to write a method that removes the mode entirely from a list. I've looked up other articles to use a for loop but it doesn't entirely get rid of the mode from the list like it needs to.
this is what my list would look like before I get rid of the mode entirely from a list.
list = 1,3,4,6,3,1,3,
I have alrea... | [
"mylist.remove(x) removes only the first occurrence of x from the list.\nIf you think there may be more than one, use a while loop:\nwhile 3 in mylist:\n mylist.remove(3)\n\nIf the list is long and/or there might be several 3s in the list, this approach would be more efficient, as it only iterates over the list ... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074651129_python.txt |
Q:
Fail to draw historical data from TWS API
def get_IB_historical_data(self, ibcontract, tickerid, durationStr, barSizeSetting):
historic_data_queue = finishableQueue(self.init_historicprices(tickerid))
self.reqHistoricalData(
tickerid, # tickerId,
ibcontract, # contract,
datetime... | Fail to draw historical data from TWS API | def get_IB_historical_data(self, ibcontract, tickerid, durationStr, barSizeSetting):
historic_data_queue = finishableQueue(self.init_historicprices(tickerid))
self.reqHistoricalData(
tickerid, # tickerId,
ibcontract, # contract,
datetime.datetime.today().strftime("%Y%m%d %H:%M:%S %Z"... | [
"ibcontract.includeExpired = True\ndatetime.datetime.today().strftime(\"%Y%m%d-%H:%M:%S\"), # endDateTime,\n"
] | [
0
] | [] | [] | [
"dataframe",
"historical_db",
"interactive_brokers",
"python",
"tws"
] | stackoverflow_0074290321_dataframe_historical_db_interactive_brokers_python_tws.txt |
Q:
How to use pd.apply() to instantiate new columns?
Instead of doing this:
df['A'] = df['A'] if 'A' in df else None
df['B'] = df['B'] if 'B' in df else None
df['C'] = df['C'] if 'C' in df else None
df['D'] = df['D'] if 'D' in df else None
...
I want to do this in one line or function. Below is what I tried:
def pop... | How to use pd.apply() to instantiate new columns? | Instead of doing this:
df['A'] = df['A'] if 'A' in df else None
df['B'] = df['B'] if 'B' in df else None
df['C'] = df['C'] if 'C' in df else None
df['D'] = df['D'] if 'D' in df else None
...
I want to do this in one line or function. Below is what I tried:
def populate_columns(df):
col_names = ['A', 'B', ... | [
"Looks like you can replace your whole code with a reindex:\nensure_cols = ['A', 'B', 'C', 'D']\ndf = df.reindex(columns=df.columns.union(ensure_cols))\n\nNB. By default the fill value is NaN, if you really want None use fill_value=None.\nIf you want to fix your code, just use a single loop:\ncol_names = ['A', 'B',... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074651065_dataframe_pandas_python.txt |
Q:
Python Correctly Parse a Complex Object into a JSON format
I have the following which I'd like to parse it into JSON. The class has a list of item object also
class Item(JSONEncoder):
def __init__(self):
self.Type = ''
self.Content = ''
self.N = None
self.Parent = None
... | Python Correctly Parse a Complex Object into a JSON format | I have the following which I'd like to parse it into JSON. The class has a list of item object also
class Item(JSONEncoder):
def __init__(self):
self.Type = ''
self.Content = ''
self.N = None
self.Parent = None
self.Items = []
def reprJSON(self):
d = dict()
... | [
"Looking at your code you can use this demo solution in your code as I'm storing objects of Demo class in the Items list. You need to write serialize() and dumper() methods in Items class, and also changes need to be done in reprJSON method for iteration on Items list.\nfrom json import JSONEncoder\n\nclass Demo():... | [
1,
0
] | [] | [] | [
"dictionary",
"json",
"parsing",
"python"
] | stackoverflow_0058180038_dictionary_json_parsing_python.txt |
Q:
how do I copy over a few folders from one directory into another folder in Linux using python
I'm trying to copy over a bunch of folders, read from a txt file into another folder . How do I do this? I'm using python in Linux
e.g this txt file has the following folder names
001YG
00HFP
00MFE
00N38
00NN7
0... | how do I copy over a few folders from one directory into another folder in Linux using python | I'm trying to copy over a bunch of folders, read from a txt file into another folder . How do I do this? I'm using python in Linux
e.g this txt file has the following folder names
001YG
00HFP
00MFE
00N38
00NN7
00SL4
00T1E
00T4B
00X3U
00YZL
00ZCA
01K8X
01KM1
01KML
01O27
01THT
01ZWG
and... | [
"use shutil.copytree(src, dest, ...) (https://docs.python.org/3/library/shutil.html#shutil.copytree) for directories (also copies subfiles and -directories. And also don't forget to give it the full path for file and dest (don't know which value your temp3 var holds). If you don't give it a full path, but only a f... | [
1
] | [] | [] | [
"file",
"io",
"linux",
"python"
] | stackoverflow_0074651147_file_io_linux_python.txt |
Q:
Removing a comma at end a each row in python
I have the below dataframe
After doing the below manipulations to the dataframe, I am getting the output in the Rule column with comma at the end which is expected .but I want to remove it .How to do it
df['Rule'] = df.State.apply(lambda x: str("'"+str(x)+"',"))
df['Ru... | Removing a comma at end a each row in python | I have the below dataframe
After doing the below manipulations to the dataframe, I am getting the output in the Rule column with comma at the end which is expected .but I want to remove it .How to do it
df['Rule'] = df.State.apply(lambda x: str("'"+str(x)+"',"))
df['Rule'] = df.groupby(['Description'])['Rule'].transfo... | [
"Try this:\ndf['Rule'] = df.State.apply(lambda x: str(\"'\"+str(x)+\"'\"))\ndf['Rule'] = df.groupby(['Description'])['Rule'].transform(lambda x: ', '.join(x))\ndf1 = df.drop_duplicates('Description', keep = 'first')\ndf1['Rule'] = df1['Rule'].apply(lambda x: str(\"(\"+str(x)+\")\"))\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074650804_dataframe_pandas_python.txt |
Q:
Finding Missing Quarters for last years in data
I have a pyspark dataframe with Quarterly data in that. The data is in the following format
2022-03-01 abc
2022-06-01 xyz
2000-03-01 abcd
Starting from the very first date (somewhere around 1960's) I need to find if there are any quarters missing from th... | Finding Missing Quarters for last years in data | I have a pyspark dataframe with Quarterly data in that. The data is in the following format
2022-03-01 abc
2022-06-01 xyz
2000-03-01 abcd
Starting from the very first date (somewhere around 1960's) I need to find if there are any quarters missing from the date. And for the current year, any quarters that h... | [
"Here is my solution:\nfrom pyspark.sql import functions as F\n\n# I purposely commented out some part of 2022 so you can see the result\n\ndata = [\n ['2020-03-01', 'x']\n, ['2020-04-01', 'y']\n, ['2020-05-01', 'x']\n, ['2020-06-01', 'x']\n, ['2020-01-01', 'y'] \n, ['2020-01-01', 'y']\n, ['2020-07-... | [
0,
0
] | [] | [] | [
"azure_databricks",
"pyspark",
"python"
] | stackoverflow_0074606200_azure_databricks_pyspark_python.txt |
Q:
Replace value of a column converted to day and month to a text using Python
how do I achieve this in Python? Source file is a CSV file, and value of one column in that file is converted from numeric to day and month. Thank you very much in advance.
Example below:
Picture of the column:
room column
In my python scr... | Replace value of a column converted to day and month to a text using Python | how do I achieve this in Python? Source file is a CSV file, and value of one column in that file is converted from numeric to day and month. Thank you very much in advance.
Example below:
Picture of the column:
room column
In my python script, value should look below:
1-Feb ---> 2-1
2-Feb ---> 2-2
3-Mar ---> 3-3
4-Mar ... | [
"If you want to convert the strings to dates to later get the values\nimport datetime\n# datetime.datetime(1900, 2, 1, 0, 0)\nd = datetime.datetime.strptime(\"1-Feb\", \"%d-%b\")\nprint(f'{d.month}-{d.day}')\n\nresult:\n2-1\n\n",
"You can use pandas.to_datetime :\nnew[\"Room\"]= (\n pd.to_datetime(... | [
1,
0
] | [] | [] | [
"csv",
"if_statement",
"python"
] | stackoverflow_0074638521_csv_if_statement_python.txt |
Q:
Boto3 SES Client gets SignatureDoesNotMatch error
I have the following setup:
Python Flask API with boto3 installed. I create a boto3 client like so:
client = boto3.client(
"ses",
region_name='eu-west-1',
aws_access_key_id='myAccessKeyID',
aws_secret_access_key='mySecretAccessKey'
)
Then I try to ... | Boto3 SES Client gets SignatureDoesNotMatch error | I have the following setup:
Python Flask API with boto3 installed. I create a boto3 client like so:
client = boto3.client(
"ses",
region_name='eu-west-1',
aws_access_key_id='myAccessKeyID',
aws_secret_access_key='mySecretAccessKey'
)
Then I try to send an email like so:
try:
client.send_email(
... | [
"From this answer:\n\nThe keys to be provided to send Emails are not \"SMTP Credentials\" .\nThe keys are instead Global access key which can be retrieved\nhttp://docs.amazonwebservices.com/ses/latest/GettingStartedGuide/GetAccessIDs.html.\n\n"
] | [
0
] | [] | [] | [
"amazon_ses",
"amazon_web_services",
"boto3",
"python",
"python_3.x"
] | stackoverflow_0072462576_amazon_ses_amazon_web_services_boto3_python_python_3.x.txt |
Q:
Custom pattern matching in python
I am trying to write a simple python program to read a log file and extract specific values
I have the following log line I want to look out for
2022-12-02 13:13:10.539 [metrics-writer-1] [INFO ] metrics - type=GAUGE, name=Topic.myTopic1.TotalIncomingBytes.Count, value=20725269
I... | Custom pattern matching in python | I am trying to write a simple python program to read a log file and extract specific values
I have the following log line I want to look out for
2022-12-02 13:13:10.539 [metrics-writer-1] [INFO ] metrics - type=GAUGE, name=Topic.myTopic1.TotalIncomingBytes.Count, value=20725269
I have many topics such as myTopic2, my... | [
"Maybe something like this:\nresultLines = []\nresultSums = {}\nwith open('recent.logs') as f:\n for idx, line in enumerate(f):\n pieces = line.rsplit('.TotalIncomingBytes.Count, value=', 1)\n if len(pieces) != 2: continue\n\n value = pieces[1]\n\n pieces = pieces[0].rsplit(' [metrics... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074651250_python.txt |
Q:
Discord.py channel.connect() never returns
I am currently working on a discord.py-rewrite (1.3.3) bot for my discord server. At the moment, I am trying to make the bot play music in the voice channels. According to the discord.py documentation, you would use the function channel.connect() to connect to a voice cha... | Discord.py channel.connect() never returns | I am currently working on a discord.py-rewrite (1.3.3) bot for my discord server. At the moment, I am trying to make the bot play music in the voice channels. According to the discord.py documentation, you would use the function channel.connect() to connect to a voice channel, which would return a VoiceClient object.
H... | [
"Here's a way to make your bot join a voice channel:\nasync def join(ctx):\n channel = ctx.message.author.voice.channel\n if not channel:\n await ctx.send(\"You're not connected to any voice channel !\")\n else:\n voice = get(self.bot.voice_clients, guild=ctx.guild)\n if voice and voic... | [
1,
0,
0,
0
] | [] | [] | [
"bots",
"discord",
"discord.py",
"python"
] | stackoverflow_0062557255_bots_discord_discord.py_python.txt |
Q:
Sort rows of curve shaped data in python
I have a dataset that consists of 5 rows that are formed like a curve. I want to separate the inner row from the other or if possible each row and store them in a separate array. Is there any way to do this, like somehow flatten the curved data and sorting it afterwards bas... | Sort rows of curve shaped data in python | I have a dataset that consists of 5 rows that are formed like a curve. I want to separate the inner row from the other or if possible each row and store them in a separate array. Is there any way to do this, like somehow flatten the curved data and sorting it afterwards based on the x and y values?
I would like to ass... | [
"It seems that your curves have a pattern, so you could select the curve of interest using splicing. I had the offset the selection slightly to get the five curves because the first 8 points are not in the same order as the rest of the data. So the initial 8 data points are discarded. But these could be added back ... | [
1
] | [] | [] | [
"data_analysis",
"python",
"scipy",
"sorting"
] | stackoverflow_0074651199_data_analysis_python_scipy_sorting.txt |
Q:
How to modify (flip sign) secondary y-axis tick labels
Data (this block of code is good; feel free to skip):
#Import statements
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
#Constants
start_date = "2018-01-01"
end_date = "2023-01-01"
#Pull in dat... | How to modify (flip sign) secondary y-axis tick labels | Data (this block of code is good; feel free to skip):
#Import statements
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
#Constants
start_date = "2018-01-01"
end_date = "2023-01-01"
#Pull in data
tenYear_master = yf.download('^TNX', start_date, end_date)... | [
"The problem here I think is, you change the y_ticks before you pass them to set_major_locator, but you don't want to change the ticks, you actually only want to change the label (as you did for the left y labels).\nChange that part to:\n\"\"\"Change right y-axis tick labels\"\"\"\n# Pull current right y-axis tick ... | [
0
] | [] | [] | [
"matplotlib",
"pandas",
"python",
"yticks"
] | stackoverflow_0074647364_matplotlib_pandas_python_yticks.txt |
Q:
TypeError: sequence item 1: expected str instance, int found (Python)
Seeking for your assistance regarding this issue and I'm trying to resolve it, tried so many syntax but still getting the same error. I got multiple csv files to be converted and I'm pulling the same data, the script works for 1 of my csv file b... | TypeError: sequence item 1: expected str instance, int found (Python) | Seeking for your assistance regarding this issue and I'm trying to resolve it, tried so many syntax but still getting the same error. I got multiple csv files to be converted and I'm pulling the same data, the script works for 1 of my csv file but not on the other. Looking forward to your feedback. Thank you very much.... | [
"It's hard to say what you're trying to achieve without showing a sample of your data. But anyway, to fix the error, you need to cast the values as a string with str when calling pandas.Series.apply :\nnew[merged_col] = new[merge_columns].apply(lambda x: '.'.join(str(x)), axis=1)\n\nOr, you can also use pandas.Seri... | [
0
] | [] | [] | [
"csv",
"join",
"python",
"string"
] | stackoverflow_0074651204_csv_join_python_string.txt |
Q:
How to use a condition inside a while loop?
I have a line of codes to check if the entered value exsist in the database
and will continue to loop but inside the while loop it also print the else statement which it shouldn't
cottageNotAvailable = False
mycursor.execute("SELECT * FROM reserved")
occupide = 0
name = ... | How to use a condition inside a while loop? | I have a line of codes to check if the entered value exsist in the database
and will continue to loop but inside the while loop it also print the else statement which it shouldn't
cottageNotAvailable = False
mycursor.execute("SELECT * FROM reserved")
occupide = 0
name = input("Enter Name: ")
cottage_row = int(input("Se... | [
"What is the value of cottage and users? What does allUser2[3] value return ? Based on the condition check the value of str(cottage) in str(allUser2[3])\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074651499_python.txt |
Q:
Must have equal len keys and value when setting with an iterable
I have two dataframes as follows:
leader:
0 11
1 8
2 5
3 9
4 8
5 6
[6065 rows x 2 columns]
```none
`DatasetLabel`:
```none
0 1 .... 7 8 9 10 11 12
0 A J .... 1 2 5 NaN NaN NaN
1 B K .... 3 4 NaN NaN NaN NaN
[... | Must have equal len keys and value when setting with an iterable | I have two dataframes as follows:
leader:
0 11
1 8
2 5
3 9
4 8
5 6
[6065 rows x 2 columns]
```none
`DatasetLabel`:
```none
0 1 .... 7 8 9 10 11 12
0 A J .... 1 2 5 NaN NaN NaN
1 B K .... 3 4 NaN NaN NaN NaN
[4095 rows x 14 columns]
The Information dataset column names 0 to 6 a... | [
"You can use apply to index into leader and exchange values with DatasetLabel, although it's not very pretty. \nOne issue is that Pandas won't let us index with NaN. Converting to str provides a workaround. But that creates a second issue, namely, column 9 is of type float (because NaN is float), so 5 becomes 5.... | [
10,
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"valueerror"
] | stackoverflow_0048000225_dataframe_pandas_python_valueerror.txt |
Q:
Chrome browser closes immediately after loading from selenium
I am running a basic python program to open the Chrome Window but as soon as the code executes, the window is there for a sec and then it closes immediately.
from selenium import webdriver
import time
browser = webdriver.Chrome(executable_path=r"C:\API... | Chrome browser closes immediately after loading from selenium | I am running a basic python program to open the Chrome Window but as soon as the code executes, the window is there for a sec and then it closes immediately.
from selenium import webdriver
import time
browser = webdriver.Chrome(executable_path=r"C:\APIR\chromedriver.exe")
browser.maximize_window()
browser.get("https:/... | [
"It closes because the program ends.\nYou can:\nWait with time.sleep, for example time.sleep(10) to keep the browser open for 10 seconds after everything is done\nHave the user press enter with input()\nOr detect when the browser is closed. Many ways to do that.\nExample: https://stackoverflow.com/a/52000037/899791... | [
3,
0
] | [] | [] | [
"chromium",
"google_chrome",
"python",
"selenium",
"selenium_chromedriver"
] | stackoverflow_0068543285_chromium_google_chrome_python_selenium_selenium_chromedriver.txt |
Q:
How to download .xlsm ,docx, png,jpg files using python from a http GET request
I am downloading content from a link using python GET request, there are certain content type headers which i am not able to save. The file types of pdf,csv,jpeg,xlsx are getting saved fine when i write the corressponding contents to t... | How to download .xlsm ,docx, png,jpg files using python from a http GET request | I am downloading content from a link using python GET request, there are certain content type headers which i am not able to save. The file types of pdf,csv,jpeg,xlsx are getting saved fine when i write the corressponding contents to the file types, but the jpg,png,xlsxm,docx contents not getting saved, though the cont... | [
"FOR DOC File (you can use different thing for download different type of File or USE same code)\ndef save_link(book_link, book_name):\n the_book = requests.get(book_link, stream=True)\n with open(book_name, 'wb') as f:\n for chunk in the_book.iter_content(1024 * 1024 * 2): # 2 MB chunks\n f.writ... | [
0
] | [] | [] | [
"http_headers",
"python",
"response_headers"
] | stackoverflow_0074651507_http_headers_python_response_headers.txt |
Q:
MongoDB change streams lead to COLLSCAN with getMore
I've been recently using the Change Stream framework in pymongo to update dynamically a collection.
My pipeline is quite simple and is the following :
pipeline = [
{"$match":
{"$and":
[{"updateDescription.updatedFiel... | MongoDB change streams lead to COLLSCAN with getMore | I've been recently using the Change Stream framework in pymongo to update dynamically a collection.
My pipeline is quite simple and is the following :
pipeline = [
{"$match":
{"$and":
[{"updateDescription.updatedFields.updated_data":
{"$exists": True}},
... | [
"According to the official document, we cannot avoid the COLLSCAN on oplog collection.\nSo, in my opinion, in order to reduce the performance impact, watch should be run on the secondary instead of the primary.\n"
] | [
0
] | [] | [] | [
"changestream",
"mongodb",
"pymongo",
"python"
] | stackoverflow_0060492783_changestream_mongodb_pymongo_python.txt |
Q:
How do I loop this webscrape/tweet script 24/7?
Just started learning Python. I am trying to gather data by webscraping and tweet out info. But everytime I rerun the code. I get
Forbidden: 403 Forbidden
187 - Status is a duplicate.
How do I loop this script without getting this error?
Here's my code :
def scrape ... | How do I loop this webscrape/tweet script 24/7? | Just started learning Python. I am trying to gather data by webscraping and tweet out info. But everytime I rerun the code. I get
Forbidden: 403 Forbidden
187 - Status is a duplicate.
How do I loop this script without getting this error?
Here's my code :
def scrape ():
page = requests.get("https://www.reuters.com/... | [
"The twitter api checks if the content is duplicate and if it is duplicate it returns:\n Request returned an error: 403 {\"detail\":\"You are not allowed to create a Tweet with duplicate content.\",\"type\":\"about:blank\",\"title\":\"Forbidden\",\"status\":403}\n\nI added an simple function to check if the previou... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"tweepy",
"twitter",
"web_scraping"
] | stackoverflow_0074651027_beautifulsoup_python_tweepy_twitter_web_scraping.txt |
Q:
Check Normal distribution with Kolmogorov test
I am a learning statistics using python, and I have a task to check that data have Normal Distribution with mean=10 and dispersion=5.5.
I've checked scipy.stats.kstest function, but I don't understand how to interpret the results, and where I should pass mean and dis... | Check Normal distribution with Kolmogorov test | I am a learning statistics using python, and I have a task to check that data have Normal Distribution with mean=10 and dispersion=5.5.
I've checked scipy.stats.kstest function, but I don't understand how to interpret the results, and where I should pass mean and dispersion args.
Thank you, for your help
| [
"Generate a dataset\nimport scipy\nimport matplotlib.pyplot as plt\n# generate data with norm(mean = 0,std = 15)\ndata = scipy.stats.norm.rvs(loc = 0,scale = 15,size = 1000,random_state = 0)\n\nPerfrom KS-test\n# perform KS test on your sample versus norm(10,5.5)\nD, p = scipy.stats.kstest(data, 'norm', args= (10,... | [
1,
0
] | [] | [] | [
"numpy",
"pandas",
"python",
"scipy",
"statistics"
] | stackoverflow_0059612155_numpy_pandas_python_scipy_statistics.txt |
Q:
Python LAB - Driving Costs (Functions)
When I run my program my output has the decimal in the wrong place. How would I move the decimal point over and round up? (EX. My output was 6.3198 but should be 63.2) Besides that the rest of my program does not work. Any help would be appreciated. Thank you!
DIRECTIONS
Writ... | Python LAB - Driving Costs (Functions) | When I run my program my output has the decimal in the wrong place. How would I move the decimal point over and round up? (EX. My output was 6.3198 but should be 63.2) Besides that the rest of my program does not work. Any help would be appreciated. Thank you!
DIRECTIONS
Write a function driving_cost() with input param... | [
"I believe you wrote your code wrongly, you want the gallon of gas, for 400 miles, 50 miles and 10 miles, and your function in main having the parameter in the wrong place.\nYour function:\ndriving_cost(miles_per_gallon, dollars_per_gallon, miles_driven)\n\nThe function in your main write:\ndriving_cost(miles_per_g... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074651530_python.txt |
Q:
How to download entire directory from azure file share
Not able to download entire directory from azure file share in python
I have used all basic stuffs available in google
A:
I tried in my environment and got below results:
Initially I tried with python,
Unfortunately, ShareServiceClient Class which Interact... | How to download entire directory from azure file share | Not able to download entire directory from azure file share in python
I have used all basic stuffs available in google
| [
"I tried in my environment and got below results:\nInitially I tried with python,\n\nUnfortunately, ShareServiceClient Class which Interacts with A client to interact with the File Share Service at the account level. does not yet support Download operation in the Azure Python SDK.\nShareClient Class which only inte... | [
0
] | [] | [] | [
"azure",
"azure_files",
"azure_storage",
"python"
] | stackoverflow_0074560083_azure_azure_files_azure_storage_python.txt |
Q:
Hatching the definition area of the matplotlib function
I want to make a hatching of the function definition area, something similar as in the example
fig, ax = plt.subplots()
plt.title('$f(x)= x^3 + x^2 + 17 $')
plt.minorticks_on()
plt.grid()
plt.xlabel('x')
plt.ylabel('y')... | Hatching the definition area of the matplotlib function | I want to make a hatching of the function definition area, something similar as in the example
fig, ax = plt.subplots()
plt.title('$f(x)= x^3 + x^2 + 17 $')
plt.minorticks_on()
plt.grid()
plt.xlabel('x')
plt.ylabel('y')
x = np.linspace(-100, 100)
y =... | [
"Hatches in combination with fill_between should to the trick:\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n#your code\nfig, ax = plt.subplots()\nplt.title('$f(x)= x^3 + x^2 + 17 $')\nplt.minorticks_on()\nplt.grid()\nplt.xlabel('x')\nplt.ylabel('y')\n\nx = np.linspace(-100, 100)\ny = lambda x: x ** 3 +... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074649138_python.txt |
Q:
Sum of value in a dictionary
I’m new here. I wanted to sum all the values inside a dictionary, but my values are all strings, I don’t know how to convert the strings to integers…
I really appreciate if anyone can help with it!
Here’s the dictionary with code:
dic1 = dict()
dic1 = {'2012-03-06':['1','4','5'],'2012-... | Sum of value in a dictionary | I’m new here. I wanted to sum all the values inside a dictionary, but my values are all strings, I don’t know how to convert the strings to integers…
I really appreciate if anyone can help with it!
Here’s the dictionary with code:
dic1 = dict()
dic1 = {'2012-03-06':['1','4','5'],'2012-03-12':['7','3','10']}
for i in d... | [
"1st Solution: you can do this using map\ndic1 = {'2012-03-06':['1','4','5'],'2012-03-12':['7','3','10']}\n\nresult_dict = {key: sum(map(int, value)) for key, value in dic1.items()}\nprint(result_dict)\n\nOutput:\n{'2012-03-06': 10, '2012-03-12': 20}\n\n2nd Solution: And convert into expected output easily\ndic1 = ... | [
2,
-2
] | [] | [] | [
"addition",
"dictionary",
"integer",
"python",
"string"
] | stackoverflow_0074651587_addition_dictionary_integer_python_string.txt |
Q:
Refit python's surprise recommedation system with new data
I've built a recommender system using Python Surprise library.
Next step is to update algorithm with new data. For example a new user or a new item was added.
I've digged into documentation and got nothing for this case. The only possible way is to train n... | Refit python's surprise recommedation system with new data | I've built a recommender system using Python Surprise library.
Next step is to update algorithm with new data. For example a new user or a new item was added.
I've digged into documentation and got nothing for this case. The only possible way is to train new model from time to time from scratch.
It looks like I missed ... | [
"Unfortunately Surprise doesn't support partial fit yet.\nIn this thread there are some workarounds and forks with implemented partial fit.\n"
] | [
0
] | [] | [] | [
"python",
"recommendation_engine"
] | stackoverflow_0072439952_python_recommendation_engine.txt |
Q:
Currently only multi-regression, multilabel and survival objectives work with multidimensional target
I used bayes_optto tunse hper-parameter of CatBoostRegressor (from catboost) for regression and got the following error:
CatBoostError: catboost/private/libs/target/data_providers.cpp:603: Currently only multi-reg... | Currently only multi-regression, multilabel and survival objectives work with multidimensional target | I used bayes_optto tunse hper-parameter of CatBoostRegressor (from catboost) for regression and got the following error:
CatBoostError: catboost/private/libs/target/data_providers.cpp:603: Currently only multi-regression, multilabel and survival objectives work with multidimensional target
Here is the code:
from sklear... | [
"if your target is multid- then you need to choose another loss function ex. MultiRMSE instead of the default function RMSE\n"
] | [
0
] | [] | [] | [
"catboost",
"catboostregressor",
"python"
] | stackoverflow_0073381894_catboost_catboostregressor_python.txt |
Q:
PySpark: How to create DataFrame containing date range
I am trying to create a PySpark data frame with a single column that contains the date range, but I keep getting this error. I also tried converting it to an int, but I am not sure if you are even supposed to do that.
# Gets an existing SparkSession or, if the... | PySpark: How to create DataFrame containing date range | I am trying to create a PySpark data frame with a single column that contains the date range, but I keep getting this error. I also tried converting it to an int, but I am not sure if you are even supposed to do that.
# Gets an existing SparkSession or, if there is no existing one, creates a new one
spark = SparkSessio... | [
"you can use the sequence sql function to create an array of dates using the start and end. this array can be exploded to get new rows.\nsee example below\nspark.sparkContext.parallelize([(start_date, end_date)]). \\\n toDF(['start', 'end']). \\\n withColumn('start', func.to_date('start')). \\\n withColumn... | [
0
] | [] | [] | [
"apache_spark_sql",
"dataframe",
"date",
"pyspark",
"python"
] | stackoverflow_0074649809_apache_spark_sql_dataframe_date_pyspark_python.txt |
Q:
GraphQL schema to python dataclasses codegen
I have a GraphQL schema defined from server and I'd like to write a nice Python GraphQL client for it. I'm looking for a way to transform my GraphQL schema into python classes with type hints such that I'll be able to see all available queries, mutations, their fields(n... | GraphQL schema to python dataclasses codegen | I have a GraphQL schema defined from server and I'd like to write a nice Python GraphQL client for it. I'm looking for a way to transform my GraphQL schema into python classes with type hints such that I'll be able to see all available queries, mutations, their fields(names & types) and return vals.
I cannot write manu... | [
"I am actually working on a code generator, as part of a library that has the objective of allowing a code-first approach when querying GraphQL API servers from python.\nTo give you a preview what will be the outcome:\nclass Book(GQLObject):\n title: str\n year: int\n\nclass Author(GQLObject):\n name: str\n boo... | [
0
] | [] | [] | [
"code_generation",
"graphql",
"python",
"type_hinting"
] | stackoverflow_0074326921_code_generation_graphql_python_type_hinting.txt |
Q:
How can she use the global variable without passing it in the function argument
Currently in day 15 of Angela's 100 days of python. What I understood from all the exercises and project is that variables outside the function cannot be used inside a function unless it is passed as an argument or you input "global" ... | How can she use the global variable without passing it in the function argument | Currently in day 15 of Angela's 100 days of python. What I understood from all the exercises and project is that variables outside the function cannot be used inside a function unless it is passed as an argument or you input "global" inside the function.
MENU = {
"espresso": {
"ingredients": {
... | [
"would like to add an answer here posted by John in the udemy QnA section:\nLists and dictionaries are mutable. That means that you can add and remove elements from the list/dictionary and it still remains the same list/dictionary object. It is not necessary to create a new list/dictionary in this case.\nAlmost all... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074648730_python.txt |
Q:
How to update rows in pandas dataframe from another dataframe on condition with diffrenet indexes?
I have two sample datasets
test1
ID Label Key
0 K1a89aKkkkkk 23 23_TAMPA
1 Ka18d8Kkkkkk 2 2_MIAMI
2 Kae851Kkkkkk 10 10_WEST PALM BEACH
3 Kf054cKkkkkk 27 27_JACKSONVILLE
4 Ka1... | How to update rows in pandas dataframe from another dataframe on condition with diffrenet indexes? | I have two sample datasets
test1
ID Label Key
0 K1a89aKkkkkk 23 23_TAMPA
1 Ka18d8Kkkkkk 2 2_MIAMI
2 Kae851Kkkkkk 10 10_WEST PALM BEACH
3 Kf054cKkkkkk 27 27_JACKSONVILLE
4 Ka1129Kkkkkk 2 2_MIAMI
5 Kae8e1Kkkkkk 10 10_WEST PALM BEACH
6 Ka9045Kkkkkk 50 50_ORLANDO
7... | [
"Convert values to numpy arrays, for improve solution remove nested ][:\ntest2.loc[test2[\"ID\"]==\"Ke2821Kkkkkk\",[\"Label\", \"Key\"]] = test1.loc[test1[\"ID\"]==\"Ka1129Kkkkkk\",[\"Label\", \"Key\"]].to_numpy()\ntest2.loc[test2[\"ID\"]==\"Ka83acKkkkkk\",[\"Label\", \"Key\"]] = test1.loc[test1[\"ID\"]==\"Ka9045Kk... | [
1
] | [] | [] | [
"data_manipulation",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074651798_data_manipulation_dataframe_pandas_python.txt |
Q:
Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters. new to programming
I have tried this solution. But I am not receiving any output. Can someone please point out my error.
def num_case(str):
z=0
j=0
for i in str:
if i.isupper():
... | Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters. new to programming | I have tried this solution. But I am not receiving any output. Can someone please point out my error.
def num_case(str):
z=0
j=0
for i in str:
if i.isupper():
z=z+1
return z
elif i.islower():
j=j+1
return j
else:
pass
... | [
"You are returning your function inside your loop. So once if finds a uppercase or lowercase it will directly return from the function. Just remove the return lines.\n",
"You should not put return statements inside the loop. The num_case function should look like this:\ndef num_case(str): ... | [
0,
0,
0
] | [] | [] | [
"lowercase",
"python",
"string",
"uppercase"
] | stackoverflow_0074651626_lowercase_python_string_uppercase.txt |
Q:
One Hot Encoder on columns
The data available is as follows:
bread milk butter jam nutella cheese chips
0 bread NaN butter jam nutella NaN NaN
1 NaN NaN butter jam nutella NaN chips
2 NaN milk NaN NaN NaN cheese NaN
3 bread milk butter... | One Hot Encoder on columns | The data available is as follows:
bread milk butter jam nutella cheese chips
0 bread NaN butter jam nutella NaN NaN
1 NaN NaN butter jam nutella NaN chips
2 NaN milk NaN NaN NaN cheese NaN
3 bread milk butter jam nutella cheese chips
... | [
"You can use a trick with pandas.Series.name to replace the column name with 1, then fillna(0).\nFirst make sure to clean up the column names with:\nbook_data.columns= book_data.columns.str.strip()\n\nAnd why not also the values of each row :\nbook_data= book_data.replace(\"\\s+\", \"\", regex=True)\n\nThen try thi... | [
0
] | [] | [] | [
"one_hot_encoding",
"python"
] | stackoverflow_0074651687_one_hot_encoding_python.txt |
Q:
Reshaping data in pandas by converting R code
Using the below R code, I could appropriately reshape my data from wide to long format. I wonder how I can replicate the below R code in pandas!
total_RACE_Reshape<-total_RACE %>% pivot_longer(cols=c('non_Hispanic_Black_65_percent', 'non_Hispanic_White_65_percent'),
... | Reshaping data in pandas by converting R code | Using the below R code, I could appropriately reshape my data from wide to long format. I wonder how I can replicate the below R code in pandas!
total_RACE_Reshape<-total_RACE %>% pivot_longer(cols=c('non_Hispanic_Black_65_percent', 'non_Hispanic_White_65_percent'),
names... | [
"The equivalent pandas method is melt(). Selecting columns, renaming columns etc. are very similar.\ntotal_RACE_Reshape = total_RACE.melt(\n value_vars=['non_Hispanic_Black_65_percent', 'non_Hispanic_White_65_percent'], \n value_name='Race', \n var_name='Percent'\n)\n\n"
] | [
0
] | [] | [] | [
"pandas",
"python",
"r"
] | stackoverflow_0074650141_pandas_python_r.txt |
Q:
How can I make a recurring async task (I don't control where asyncio.run() is called)
I'm using a library that itself makes the call to asyncio.run(internal_function) so I can't control that at all. I do however have access to the event loop, it's something that I pass into this library.
Given that, is there some ... | How can I make a recurring async task (I don't control where asyncio.run() is called) | I'm using a library that itself makes the call to asyncio.run(internal_function) so I can't control that at all. I do however have access to the event loop, it's something that I pass into this library.
Given that, is there some way I can set up an recurring async event that will execute every X seconds while the main ... | [
"You don't need to await on a created task.\nIt will run in the background as long as the event loop is active and is not stuck in a CPU bound operation.\nAccording to your comment, you don't have an access to the event loop. In this case you don't have many options other than running in a different thread (which w... | [
1,
1
] | [] | [] | [
"python",
"python_asyncio"
] | stackoverflow_0074649296_python_python_asyncio.txt |
Q:
How to check if a number is a np.float64 or np.float32 or np.float16?
Other than using a set of or statements
isinstance( x, np.float64 ) or isinstance( x, np.float32 ) or isinstance( np.float16 )
Is there a cleaner way to check of a variable is a floating type?
A:
You can use np.floating:
In [11]: isinstance(np... | How to check if a number is a np.float64 or np.float32 or np.float16? | Other than using a set of or statements
isinstance( x, np.float64 ) or isinstance( x, np.float32 ) or isinstance( np.float16 )
Is there a cleaner way to check of a variable is a floating type?
| [
"You can use np.floating:\nIn [11]: isinstance(np.float16(1), np.floating)\nOut[11]: True\n\nIn [12]: isinstance(np.float32(1), np.floating)\nOut[12]: True\n\nIn [13]: isinstance(np.float64(1), np.floating)\nOut[13]: True\n\nNote: non-numpy types return False:\nIn [14]: isinstance(1, np.floating)\nOut[14]: False\n\... | [
53,
3,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0028292542_numpy_python.txt |
Q:
Can I increase the decrease value from a for loop in python?
How do I increase the decrease value every loop in for loop ?.
Example:
from decrease by -7 -> -6 -> -4 -> -1.
current code:
for i in range(4,0,-1):
Dev.step(2)
if i == 1 or i == 3:
Dev.turnLeft()
Dev.step(i)
Dev.step(-i)... | Can I increase the decrease value from a for loop in python? | How do I increase the decrease value every loop in for loop ?.
Example:
from decrease by -7 -> -6 -> -4 -> -1.
current code:
for i in range(4,0,-1):
Dev.step(2)
if i == 1 or i == 3:
Dev.turnLeft()
Dev.step(i)
Dev.step(-i)
Dev.turnRight()
else:
Dev.turnRight()
... | [
"Updated based on comment not to use a separate variable\nYou can use the loop variable i to determine the current decrement value.\n# Loop from 4 to 0, using the current value of i as the decrement value\nfor i in range(4,0,-i):\n Dev.step(2)\n if i == 1 or i == 3:\n Dev.turnLeft()\n Dev.step(i... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074651826_python.txt |
Q:
Python Openpyxl - Modify excel file and its value
I get an exported Excel file displaying ProductItems, locations, and some sale numbers.
Now, the problem is that the ProductItems and Locations are all in one column, indented a bit, like this:
ProductItem_1
Location_a | Quantity | Price
Location_b | Quantit... | Python Openpyxl - Modify excel file and its value | I get an exported Excel file displaying ProductItems, locations, and some sale numbers.
Now, the problem is that the ProductItems and Locations are all in one column, indented a bit, like this:
ProductItem_1
Location_a | Quantity | Price
Location_b | Quantity | Price
Location_c | Quantity | Price
(110 lo... | [
"This example produces the requested format based on your before image and includes rows 1 -4 from the original sheet unchanged.\nBasically the code loops through the rows from row 5, the header row for the data in columns B, C, D, and E. It moves each range from A to E across by 1 so that column A is then empty, a... | [
0
] | [] | [] | [
"excel",
"openpyxl",
"python"
] | stackoverflow_0074647451_excel_openpyxl_python.txt |
Q:
how to calculate 256 bit number in numba on a CUDA GPU
I'm using python numba and when a number exceed 64 bit it will use cpu instead of gpu so i guess it only support up to 64 bit number. How to calculate 256 bit number in numba(like adding two 256 bit number)?
A:
Generally speaking, GPUs are 32-bit machines wi... | how to calculate 256 bit number in numba on a CUDA GPU | I'm using python numba and when a number exceed 64 bit it will use cpu instead of gpu so i guess it only support up to 64 bit number. How to calculate 256 bit number in numba(like adding two 256 bit number)?
| [
"\nGenerally speaking, GPUs are 32-bit machines with 64-bit addressing capability. All 64-bit integer operations are emulated. In the simplest case (logical operations, additions, subtractions) each 64-bit integer operation requires the execution of two 32-bit integer instructions. Very roughly, emulation of 64-bit... | [
1
] | [] | [] | [
"cuda",
"numba",
"python"
] | stackoverflow_0074651328_cuda_numba_python.txt |
Q:
full outer join in python without pandas
I'm trying to do a full outer join in python without using pandas, I already developed a code to an inner join but can't really edit it for the full outer join
here is my code for the inner join
import collections
import csv
import sys
def c_merge(f1,f2):
with open(f1,... | full outer join in python without pandas | I'm trying to do a full outer join in python without using pandas, I already developed a code to an inner join but can't really edit it for the full outer join
here is my code for the inner join
import collections
import csv
import sys
def c_merge(f1,f2):
with open(f1,'r') as infile:
obj=csv.reader(infile... | [
"Hi, Welcome to StackOverflow!\nBoth of these works:\nwith open('newfile.txt','w') as newfile:\n w=csv.writer(newfile)\n w.writerow(header_a+header_b[1:])\n\n for m in set(dict_a.keys()).union(dict_b.keys()):\n for n in dict_b.get(m, [[]]):\n w.writerow([m]+dict_a.get(m, [])+n)\n\nOR\nwit... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074651760_python.txt |
Q:
VS code: Updated PYTHONPATH in settings. Import autocomplete now works, but module not found when running program
I have been trying to fix a problem while running python files in VSCode. I have a directory with a program my_program.py that imports a module personal_functions.py from a folder packages_i_made.
proj... | VS code: Updated PYTHONPATH in settings. Import autocomplete now works, but module not found when running program | I have been trying to fix a problem while running python files in VSCode. I have a directory with a program my_program.py that imports a module personal_functions.py from a folder packages_i_made.
project
├── .env
└── folder_a
├── my_program.py
my_packages
├── __init__.py
└── packages_i_made
├── __init__.py
... | [
"The easiest way to solve the problem is to use the sys.path.append method above your import statement to indicate the path. For you, the code should look like this:\nimport sys\nsys.path.append(\"C:/Users/user_1/my_packages\")\n\nfrom packages_i_made import personal_functions as pf\n\nYou set the .env file just to... | [
1,
0
] | [] | [] | [
"path",
"python",
"python_import",
"visual_studio_code"
] | stackoverflow_0074651496_path_python_python_import_visual_studio_code.txt |
Q:
How to change instance type in EC2 Launch Template using AWS SDK?
I'm looking to change certain things in the launch template e.g. the instance type. Which means creating a new version while doing so.
I have gone through the SDK documentation for both Go and Python. Neither seem to have the paramenters that'd let ... | How to change instance type in EC2 Launch Template using AWS SDK? | I'm looking to change certain things in the launch template e.g. the instance type. Which means creating a new version while doing so.
I have gone through the SDK documentation for both Go and Python. Neither seem to have the paramenters that'd let me acheive the same.
I'm refering to these:
Go's function,
Python's fun... | [
"EC2 launch template is immutable. You must create a new version if you need to modify the current launch template version.\nHere is an example of creating a new version and then making it the default version using AWS SDK v2.\nInstall these two packages:\n\"github.com/aws/aws-sdk-go-v2/service/ec2\"\nec2types \"gi... | [
2
] | [] | [] | [
"amazon_ec2",
"amazon_web_services",
"go",
"python"
] | stackoverflow_0074650569_amazon_ec2_amazon_web_services_go_python.txt |
Q:
DateTime adjustment in pandas
I have a dataframe with thousands of rows, there is a column which is datetime:
I would like to adjust the time, a little like 00 ± 15 -> 00, and 30±15 ->30.
More precise saying is the minute within the range 46<->15 will change to 00, 16<->45 will change to 30, but it also needs ca... | DateTime adjustment in pandas | I have a dataframe with thousands of rows, there is a column which is datetime:
I would like to adjust the time, a little like 00 ± 15 -> 00, and 30±15 ->30.
More precise saying is the minute within the range 46<->15 will change to 00, 16<->45 will change to 30, but it also needs care ± 1 on the hour
datetime
2022/11... | [
"Use Series.dt.ceil by 15 minutes and then Series.dt.floor by 30:\ndf['datetime'] = pd.to_datetime(df['datetime']).dt.ceil('15Min').dt.floor('30Min')\nprint (df)\n datetime\n0 2022-11-15 00:30:00\n1 2022-11-15 00:30:00\n2 2022-11-15 00:30:00\n3 2022-11-15 01:00:00\n4 2022-11-15 01:00:00\n5 2022-1... | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074651895_pandas_python.txt |
Q:
discord.py embed help command with reaction pages
I'm trying to make a help command with multiple pages that you can go back and forth with using reactions. It works properly but when you get to page 2 and go forward again, Nothing happens.
Same when you go to page 1 and try to go back. How can I make it so when y... | discord.py embed help command with reaction pages | I'm trying to make a help command with multiple pages that you can go back and forth with using reactions. It works properly but when you get to page 2 and go forward again, Nothing happens.
Same when you go to page 1 and try to go back. How can I make it so when you try to go past the last page it goes back to the fir... | [
"Avoid repetition, in your loop:\nwhile True:\n\n try:\n reaction, user = await client.wait_for(\"reaction_add\", timeout=60, check=check)\n # waiting for a reaction to be added - times out after x seconds, 60 in this\n # example\n\n if str(reaction.emoji) == \"▶️\":\n cur_... | [
0
] | [] | [] | [
"discord",
"discord.py",
"python"
] | stackoverflow_0074648761_discord_discord.py_python.txt |
Q:
How to simultaneoulsy expand and shrink the dataframe as per some conditions?
i have a df as follows:
df = pd.DataFrame.from_dict({'Type': {0: 'A1', 1: 'A2', 2: 'A2', 3: 'A2', 4: 'A2', 5: 'A3', 6: 'A3', 7: 'A3', 8: 'A3', 9: 'A3', 10: 'A3', 11: 'A3', 12: 'A3', 13: 'A3', 14: 'A3', 15: 'A3... | How to simultaneoulsy expand and shrink the dataframe as per some conditions? | i have a df as follows:
df = pd.DataFrame.from_dict({'Type': {0: 'A1', 1: 'A2', 2: 'A2', 3: 'A2', 4: 'A2', 5: 'A3', 6: 'A3', 7: 'A3', 8: 'A3', 9: 'A3', 10: 'A3', 11: 'A3', 12: 'A3', 13: 'A3', 14: 'A3', 15: 'A3', 16: 'A3', 17: 'A3', 18: 'A3', 19: 'A3', 20: 'A3', 21: 'A3', 22: 'A... | [
"I think you need aggregate per 3 columns:\ndf1 = df.groupby(['Type','POS', 'FN'])[['VC','ID','DN']].agg(lambda x: '|'.join(x.unique()))\n\ndf2 = pd.get_dummies(df.set_index(['Type','POS', 'FN'])['Group']).sum(level=[0, 1, 2])\ndf = pd.concat([df1, df2], axis=1)\nprint (df.head(20))\n VC ID ... | [
1
] | [] | [] | [
"dataframe",
"group_by",
"pandas",
"python"
] | stackoverflow_0074651970_dataframe_group_by_pandas_python.txt |
Q:
Is there any way to make a program that runs again on the user inputs
I want to make a program that runs again or stops by the wish of the user, How do I do it?
I tried while true, while loop but nothing seems to work, Am i doing something wrong
Pictures of my attempt: https://imgur.com/a/vqupw3z
https://imgur.com... | Is there any way to make a program that runs again on the user inputs | I want to make a program that runs again or stops by the wish of the user, How do I do it?
I tried while true, while loop but nothing seems to work, Am i doing something wrong
Pictures of my attempt: https://imgur.com/a/vqupw3z
https://imgur.com/a/zq0HgKL
| [
"It sounds like you are looking for a way to create a program that can be controlled by the user at runtime. One way to do this is to use a loop that continues until the user specifies that they want to stop the program.\nOne common way to do this is to use a while loop that repeats until the user enters a specific... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074651986_python.txt |
Q:
python Ranking on rows having same value is giving random ranking not as ascending = False
Here is df, I want to Rank on value on group "Id" , ranking within class
df['Rank']=df.groupby(["Id"])[' value'].rank(ascending=0)
Sample df
Expected Result
Expected Result
Result what I get from above code
Result what I ge... | python Ranking on rows having same value is giving random ranking not as ascending = False | Here is df, I want to Rank on value on group "Id" , ranking within class
df['Rank']=df.groupby(["Id"])[' value'].rank(ascending=0)
Sample df
Expected Result
Expected Result
Result what I get from above code
Result what I get from above code
Above code works well if value are unique
Example
df
Example df
Result
| [
"IIUC, use a dense method on pandas.Series.rank with pandas.Series.astype :\ndf['Rank']= df.groupby('ID')['Value'].rank(ascending=False, method='dense').astype(int)\n\n# Output :\nprint(df)\n\n ID Class Value Rank\n0 US A 10 1\n1 US B 10 1\n2 US C 2 2\n3 US D 2 ... | [
0
] | [] | [] | [
"duplicates",
"python",
"rank",
"ranking_functions",
"unique_values"
] | stackoverflow_0074651668_duplicates_python_rank_ranking_functions_unique_values.txt |
Q:
How to print my calculations for even and odd integers?
The program instructions follow: Your program should calculate how many values in a list of randomly generated integers are odd and how many are even with the following requirements:
Get the number of values to be generated along with the range of values from... | How to print my calculations for even and odd integers? | The program instructions follow: Your program should calculate how many values in a list of randomly generated integers are odd and how many are even with the following requirements:
Get the number of values to be generated along with the range of values from the user. After calculating the total number of odd and even... | [
"\nThe range consists of two values, it doesn't have to start with 1.\n\nThe task is to make a list. You create a list1 variable and inside the loop ask for a range for each number\n\nYou don't call the functions you wrote\n import random\n play = True\n while play:\n print(\"Enter number of values needed: \", ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074651528_python.txt |
Q:
Copying a huge file using Python scripts
I am using below python function to make a copy of file, which I am processing as part of data ingestion in Azure datafactory pipelines . This works for for small files, but fails to process huge files without returning any errors .On calling this function for 2.2 GB file ,... | Copying a huge file using Python scripts | I am using below python function to make a copy of file, which I am processing as part of data ingestion in Azure datafactory pipelines . This works for for small files, but fails to process huge files without returning any errors .On calling this function for 2.2 GB file , it stops the execution after writing 107 KB o... | [
"You can use os and rsync\n--no-whole-file or --no-W parameters use the block-level sync instead of the file level syncing.\n--progress is used for getting the logs of file transfer\nYou can also use file_name.log for adding logs into that file instead of on terminal and that file will be saved at the current locat... | [
2,
0
] | [] | [] | [
"azure_blob_storage",
"python"
] | stackoverflow_0066675216_azure_blob_storage_python.txt |
Q:
When I scroll the table gets stick to the position and only the text gets scrolled. I want it to scroll with the text
When I scroll the table gets stick to the position and only the text gets scrolled. It should scroll with the text.
The table was created with entry widget. The code does not throw any error but th... | When I scroll the table gets stick to the position and only the text gets scrolled. I want it to scroll with the text | When I scroll the table gets stick to the position and only the text gets scrolled. It should scroll with the text.
The table was created with entry widget. The code does not throw any error but the scrolling is not working properly.
from tkinter import *
import tkinter as tk
from tkinter import scrolledtext
app = tk.T... | [
"It is because the frame fortable1 which holds the table is not part of the content of txtbox since it is just put on top of txtbox using .place(). You need to use txtbox.window_create() to insert the frame into the text box instead.\nBelow is the updated code:\n...\ntxtbox = scrolledtext.ScrolledText(app, width=50... | [
1
] | [] | [] | [
"python",
"tkinter",
"tkinter_layout",
"tkinter_text"
] | stackoverflow_0074651927_python_tkinter_tkinter_layout_tkinter_text.txt |
Q:
How to annotate seaborn pairplots
I have a collection of binned data from which I generate a series of seaborn pairplots. Since all of the bins have the same labels, but not bin names, I need to annotate the pairplots with the bin name 'n' below so that I can later associate them with their bins.
import seaborn a... | How to annotate seaborn pairplots | I have a collection of binned data from which I generate a series of seaborn pairplots. Since all of the bins have the same labels, but not bin names, I need to annotate the pairplots with the bin name 'n' below so that I can later associate them with their bins.
import seaborn as sns
groups = data.groupby(pd.cut(data... | [
"After following up on mwaskom's suggestion to use matplotlib.text() (thanks), I was able to get the following to work as expected:\np = sns.pairplot(data=g, hue=\"Label\", palette=\"Set2\", \n diag_kind=\"kde\", size=4, vars=labels)\n#bottom labels\np.fig.text(0.33, -0.01, \"Bin: %s\"%(n), ha ='left', ... | [
12,
0
] | [] | [] | [
"matplotlib",
"pairplot",
"plot_annotations",
"python",
"seaborn"
] | stackoverflow_0032481214_matplotlib_pairplot_plot_annotations_python_seaborn.txt |
Q:
I'm getting File format b'\x1aE\xdf\xa3' not understood. Only 'RIFF' and 'RIFX' supported error when I want to read a wav format audio file
I want to save the uploaded voice with wav format in FastAPI using the below code:
@router.post('/save')
async def save_audio(audio = Form()):
filename = str(uuid.uuid4(... | I'm getting File format b'\x1aE\xdf\xa3' not understood. Only 'RIFF' and 'RIFX' supported error when I want to read a wav format audio file | I want to save the uploaded voice with wav format in FastAPI using the below code:
@router.post('/save')
async def save_audio(audio = Form()):
filename = str(uuid.uuid4())
out_file_path = f"{filename}.wav"
with open(out_file_path, "wb") as buffer:
shutil.copyfileobj(audio.file, buffer)
Eve... | [
"I solved the problem with librosa package\ndata, sampleRate = await librosa.load(f'{filename}.wav')\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074651901_python.txt |
Q:
While trying to run cryptocode I get the error: "module 'hashlib' has no attribute 'scrypt'"
As I mentioned in the title Im trying to run the library cryptocode by using this simple code:
import cryptocode
password = "This is a test"
key = "My Key"
def encrypt(password, key):
return cryptocode.encrypt(passwo... | While trying to run cryptocode I get the error: "module 'hashlib' has no attribute 'scrypt'" | As I mentioned in the title Im trying to run the library cryptocode by using this simple code:
import cryptocode
password = "This is a test"
key = "My Key"
def encrypt(password, key):
return cryptocode.encrypt(password, key)
def decrypt(encryptetpass):
return cryptocode.decrypt(encryptetpass, key)
encryp... | [
"Did you try to build the latest OpenSSL? I see instructions here: https://www.howtoforge.com/tutorial/how-to-install-openssl-from-source-on-linux/\n(wasn't able to try this because I'm not running Linux). Please let us know if this worked.\n",
"check below points:\nTo check which all versions are installed\n\... | [
0,
0
] | [] | [] | [
"cryptography",
"hashlib",
"python"
] | stackoverflow_0069204547_cryptography_hashlib_python.txt |
Q:
Import models from different apps to admin Django
I'm trying to create an admin page for my project including app1 and app2
myproject
settings.py
urls.py
admin.py
app1
app2
In myproject/urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('app1/', include('app1.urls')),
path('app2... | Import models from different apps to admin Django | I'm trying to create an admin page for my project including app1 and app2
myproject
settings.py
urls.py
admin.py
app1
app2
In myproject/urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('app1/', include('app1.urls')),
path('app2/', include('app2.urls')),
]
In myproject/admin.... | [
"inside each app you must put admin file so can django track these files , so in your app1 in admin.py file related to app1 directory app1/admin.py , you need to put this code\nfrom django.contrib import admin\nfrom app1.models import User\n \nadmin.site.register(User)\n\nand in app2 in admin.py related to app2 dir... | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074651506_django_python.txt |
Q:
Filtering or Querying Pandas MultiIndex Dataframe based on column values
I have a multi-index pandas DataFrame such as below, primarily indexed with DateTime object.
>>> type(feed_tail)
<class 'pandas.core.frame.DataFrame'>
>>> feed_tail.index
DatetimeIndex(['2022-11-11', '2022-11-14', '2022-11-15', '2022-11-16',... | Filtering or Querying Pandas MultiIndex Dataframe based on column values | I have a multi-index pandas DataFrame such as below, primarily indexed with DateTime object.
>>> type(feed_tail)
<class 'pandas.core.frame.DataFrame'>
>>> feed_tail.index
DatetimeIndex(['2022-11-11', '2022-11-14', '2022-11-15', '2022-11-16',
'2022-11-17', '2022-11-18', '2022-11-21', '2022-11-22',
... | [
"Use DataFrame.loc with filter MTDPerf Series:\nfor dt in feed_tail.index:\n mmtd = feed_tail.loc[dt, 'MTDPerf']\n d = mmtd[feed_tail.loc[dt, 'Close'] > feed_tail.loc[dt, 'SMA13']]\n\n\n print (d)\n\nSeries([], Name: 2022-11-11 00:00:00, dtype: object)\nSeries([], Name: 2022-11-14 00:00:00, dtype: object)\... | [
1
] | [] | [] | [
"dataframe",
"multi_index",
"numpy",
"pandas",
"python"
] | stackoverflow_0074652085_dataframe_multi_index_numpy_pandas_python.txt |
Q:
How to install Talib (on windows machine) in colab (2022-12)?
Yesterday I tried to run a python code which contains a talib package. The package failed to run in colab, ModuleNotFoundError: No module named 'talib'
I used this code, which normally worked, but after yesterday it didn't.
url = 'https://anaconda.org/c... | How to install Talib (on windows machine) in colab (2022-12)? | Yesterday I tried to run a python code which contains a talib package. The package failed to run in colab, ModuleNotFoundError: No module named 'talib'
I used this code, which normally worked, but after yesterday it didn't.
url = 'https://anaconda.org/conda-forge/libta-lib/0.4.0/download/linux-64/libta-lib-0.4.0-h51690... | [
"Since Google Colab is a notebook, you can use the ! operator with pip to install the TA-Lib package.\nTry this :\n!pip install TA-Lib\n\nAs suggested by @DarknessPlusPlus, you can also use the magic command % :\n%pip install TA-Lib\n\nThis answer by @jakevdp explains the difference between the two commands.\n# Ed... | [
3
] | [] | [] | [
"python",
"ta_lib"
] | stackoverflow_0074652073_python_ta_lib.txt |
Q:
What are the valid values for --platform, --abi, and --implementation for pip download?
pip download has several flags that I would like to play with --platform, --abi, and --implementation.
Where can I find the complete list of valid values for these flags?
A:
I don't think there is one definitive list. You ha... | What are the valid values for --platform, --abi, and --implementation for pip download? | pip download has several flags that I would like to play with --platform, --abi, and --implementation.
Where can I find the complete list of valid values for these flags?
| [
"I don't think there is one definitive list. You have to collect it from different sources. Start with PEP 425: https://www.python.org/dev/peps/pep-0425/\npython tag: ‘py27’, ‘cp33’\nabi tag: ‘cp32dmu’, ‘none’\nplatform tag: ‘linux_x86_64’, ‘any’ \n--implementation:\ncp: CPython\nip: IronPython\npp: PyPy\njy: Jytho... | [
13,
4,
0
] | [] | [] | [
"pip",
"python"
] | stackoverflow_0049672621_pip_python.txt |
Q:
Looking for a Python editor that will let me collapse functions
I really loved this feature when I used Eclipse for Java programming, but I can't find the same functionality for a Python editor. IDLE and Pyscripter are nice, but they don't help in this area.
Basically, I just want the option to collapse or otherwi... | Looking for a Python editor that will let me collapse functions | I really loved this feature when I used Eclipse for Java programming, but I can't find the same functionality for a Python editor. IDLE and Pyscripter are nice, but they don't help in this area.
Basically, I just want the option to collapse or otherwise hide functions that I don't feel like looking at for a while. Know... | [
"In addition to the aforementioned (great) editors, you might want to give PyDev a shot as well.\n",
"Geany can do this.\n",
"Notepad++ has this feature.\n",
"Komodo Edit IDE, for Windows, Mac and Linux, for Python, PHP, Ruby, JavaScript, Perl and Web Dev.\n",
"I've used Komodo Edit and Notepad++ in the pas... | [
4,
3,
2,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0010394223_python.txt |
Q:
Derive path in nested list tree structure (python)
I have created a tree data structure using a nested list in python. I have code which works through the list and prints a list of of all nodes and their parent node:
def printParents(node,adj,parent):
if (parent == 0):
print(node, "-> root")
else:
... | Derive path in nested list tree structure (python) | I have created a tree data structure using a nested list in python. I have code which works through the list and prints a list of of all nodes and their parent node:
def printParents(node,adj,parent):
if (parent == 0):
print(node, "-> root")
else:
print(node, "->", parent)
for cur in adj[nod... | [
"You could use a generator, that builds the path when coming back from recursion:\ndef paths(adj, node, parent=None):\n yield [node]\n for child in adj[node]:\n if child != parent:\n for path in paths(adj, child, node):\n yield [*path, node]\n\nHere is how to call it:\n# examp... | [
1
] | [] | [] | [
"list",
"multidimensional_array",
"nested",
"python",
"tree"
] | stackoverflow_0074650373_list_multidimensional_array_nested_python_tree.txt |
Q:
How to get input from InputText() without a button press in PySimpleGui
Is there a way to be able to get the input from an InputText() without having to rely on a button press? I am trying to make a form where the submit button is only available when the input text is not empty, however the only way to get the inp... | How to get input from InputText() without a button press in PySimpleGui | Is there a way to be able to get the input from an InputText() without having to rely on a button press? I am trying to make a form where the submit button is only available when the input text is not empty, however the only way to get the input from InputText() that I have found is with a button which needs to be clic... | [
"Decide what event by yourself to send the content of the Input element.\n\nclick a button - Add one button into your layout.\n\nimport PySimpleGUI as sg\n\nlayout = [[sg.Input(key='-IN-'), sg.Button('Submit')]]\nwindow = sg.Window('Title', layout)\nevent, values = window.read()\nif event == 'Submit':\n print(va... | [
1
] | [] | [] | [
"pysimplegui",
"python"
] | stackoverflow_0074651936_pysimplegui_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.