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 does my log message not execute first?
Lately I have been working on building a GUI for my python script with PySide6 (Qt). I added a button that executes my script when pushed:
def button_start_collecting(self):
if not self.input_src.text():
self.log_message("Please add the missing source ... | Why does my log message not execute first? | Lately I have been working on building a GUI for my python script with PySide6 (Qt). I added a button that executes my script when pushed:
def button_start_collecting(self):
if not self.input_src.text():
self.log_message("Please add the missing source path")
if not self.input_dest.text():
... | [
"The problem could be resolved by executing execute_pvt() on a different thread.\n"
] | [
0
] | [] | [] | [
"pyside",
"pyside6",
"python",
"qt"
] | stackoverflow_0073731988_pyside_pyside6_python_qt.txt |
Q:
No module named rest_auth
Getting the error:
"ImportError: No module named rest_auth"
Full trace: https://dpaste.de/UHyx
When I try to run the server using 'python2.7 manage.py runserver'
My partner is working off the same venv as me but is able to run the server successfully when he runs 'python2.7 manage.py ru... | No module named rest_auth | Getting the error:
"ImportError: No module named rest_auth"
Full trace: https://dpaste.de/UHyx
When I try to run the server using 'python2.7 manage.py runserver'
My partner is working off the same venv as me but is able to run the server successfully when he runs 'python2.7 manage.py runserver'. We both have identica... | [
"You have to install django-rest-auth :\npip install django-rest-auth\n\nYou may encounter some problems on MacOS which it seems you can fix following this : \n\nUnable to install nltk on Mac OS El Capitan\n\nOr this :\n\n\"OSError: [Errno 1] Operation not permitted\" when installing Scrapy in OSX 10.11 (El Capitan... | [
19,
0,
0
] | [] | [] | [
"django",
"django_rest_framework",
"python",
"python_2.7"
] | stackoverflow_0033972587_django_django_rest_framework_python_python_2.7.txt |
Q:
Maya: How do I get the filepath of a script that is loaded into the script editor?
Hi fellow Maya Programmers!
I need some help figuring out a script's filepath from within maya using python. I have a certain script file located somewhere on my harddrive. Let's assume the file is called "C:/Users/Username/Desktop/... | Maya: How do I get the filepath of a script that is loaded into the script editor? | Hi fellow Maya Programmers!
I need some help figuring out a script's filepath from within maya using python. I have a certain script file located somewhere on my harddrive. Let's assume the file is called "C:/Users/Username/Desktop/test.py". In Maya's Script Editor I open the script file using "File" -> "Open Script...... | [
"No. This does not work like this. You open the script and the script is copied into the maya python script tab. So it is now inside maya, not a textfile any more, even if the content is linked to the file and the file will be updated if you close the tab. What you can do is to import the script with\nimport yoursc... | [
0
] | [] | [] | [
"maya",
"python"
] | stackoverflow_0074316782_maya_python.txt |
Q:
Python conversion from JSON to JSONL
I wish to manipulate a standard JSON object to an object where each line must contain a separate, self-contained valid JSON object. See JSON Lines
JSON_file =
[{u'index': 1,
u'no': 'A',
u'met': u'1043205'},
{u'index': 2,
u'no': 'B',
u'met': u'000031043206'},
{u'index... | Python conversion from JSON to JSONL | I wish to manipulate a standard JSON object to an object where each line must contain a separate, self-contained valid JSON object. See JSON Lines
JSON_file =
[{u'index': 1,
u'no': 'A',
u'met': u'1043205'},
{u'index': 2,
u'no': 'B',
u'met': u'000031043206'},
{u'index': 3,
u'no': 'C',
u'met': u'0031043207... | [
"Your input appears to be a sequence of Python objects; it certainly is not valid a JSON document.\nIf you have a list of Python dictionaries, then all you have to do is dump each entry into a file separately, followed by a newline:\nimport json\n\nwith open('output.jsonl', 'w') as outfile:\n for entry in JSON_f... | [
72,
45,
7,
0,
0
] | [] | [] | [
"json",
"python"
] | stackoverflow_0038915183_json_python.txt |
Q:
Replace variables in a document with arguments - python
I want to replace variables in a .docx with arguments python. I got the script for replacement working but I don't know how to correctly print the arguments. I run my python script like:
$ python var-replace.py cat fish dog
var-replace.py looks like:
`
impor... | Replace variables in a document with arguments - python | I want to replace variables in a .docx with arguments python. I got the script for replacement working but I don't know how to correctly print the arguments. I run my python script like:
$ python var-replace.py cat fish dog
var-replace.py looks like:
`
import sys
arg1, arg2, arg3 = sys.argv[1], sys.argv[2], sys.argv[3... | [
"Are you sure that you need to pass the values in as strings instead of calling them?\nimport sys\narg1, arg2, arg3 = sys.argv[1], sys.argv[2], sys.argv[3]\n\n\nfrom docx import Document\ndoc = Document('test.docx')\n\n#current - wrong approach\nreplacements = {\n '${replace_me_1}': \"print(arg1)\",\n '${repl... | [
1
] | [] | [] | [
"docx",
"python",
"python_3.x",
"replace",
"text_processing"
] | stackoverflow_0074317577_docx_python_python_3.x_replace_text_processing.txt |
Q:
For loop does not continue after exception occurs on Python
This piece of code runs on different threads for connected clients. When a client disconnects, the try-except block should raise an exception, and remove the client from the clients list (connectClients is also a list, I used this to prevent the error tha... | For loop does not continue after exception occurs on Python | This piece of code runs on different threads for connected clients. When a client disconnects, the try-except block should raise an exception, and remove the client from the clients list (connectClients is also a list, I used this to prevent the error that occurs when the size of the iterable changes during the iterati... | [
"\nI'm not removing items from the list I'm iterating on (clients)\n\nBut you actually removing them, with self.connectedClients = self.clients you are creating a reference to the self.clients (so you are modifying the same object) so you need a new list:\nself.connectedClients = self.clients.copy()\n\nAlso I can't... | [
1
] | [] | [] | [
"for_loop",
"multithreading",
"python",
"try_except"
] | stackoverflow_0074317602_for_loop_multithreading_python_try_except.txt |
Q:
Copy the row in pandas from the nearest year
Lets say that I have the following datasets.
import numpy as np
import pandas as pd
d = {'name': ['a', 'a', 'a'], 'year': [2000, 2001, 2002], 'value': [10, 17, 22] }
data_frame = pd.DataFrame(data=d)
data_frame
d1 = {'name': ['a', 'a', 'a'], 'year': [2001, 2002, 2003... | Copy the row in pandas from the nearest year | Lets say that I have the following datasets.
import numpy as np
import pandas as pd
d = {'name': ['a', 'a', 'a'], 'year': [2000, 2001, 2002], 'value': [10, 17, 22] }
data_frame = pd.DataFrame(data=d)
data_frame
d1 = {'name': ['a', 'a', 'a'], 'year': [2001, 2002, 2003], 'value': [10, 17, 22] }
data_frame1 = pd.DataF... | [
"Use DataFrame.reindex with all years with parameter method='nearest', but for data_frame2 is used next year:\ndfs = [data_frame,data_frame1, data_frame2]\n\nfor df in dfs:\n df = df.set_index('year').reindex(range(2000, 2004), method='nearest')\n print (df)\n name value\n year \n 20... | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074317603_pandas_python.txt |
Q:
Could not import 'rosidl_typesupport_c' for package 'sensor_msgs' ROS2 python NavSatFix
I'm trying to make a publisher for a Ublox GPS sensor, but I'm getting this ROS error:
ubuntu@fieldrover:~/field-rover-gps/gps/gps_pkg$ cd
~/field-rover-gps/gps/gps_pkg/ && colcon build && . install/setup.bash
&& ros2 run gps_... | Could not import 'rosidl_typesupport_c' for package 'sensor_msgs' ROS2 python NavSatFix | I'm trying to make a publisher for a Ublox GPS sensor, but I'm getting this ROS error:
ubuntu@fieldrover:~/field-rover-gps/gps/gps_pkg$ cd
~/field-rover-gps/gps/gps_pkg/ && colcon build && . install/setup.bash
&& ros2 run gps_pkg gps
Starting >>> gps_pkg Finished <<< gps_pkg [2.98s]
Summary: 1 package finished [3.49s]... | [
"Ended up just using the nmea_navsat_driver found here\n",
"I had the same error and I forgot to add the dependency of the message type I was using in a service in the CMakeLists.txt\nThe dependency was missing in the rosidl_generate_interfaces\n"
] | [
0,
0
] | [] | [] | [
"python",
"ros2"
] | stackoverflow_0072452208_python_ros2.txt |
Q:
Alternative for python shutils.copytree?
recently i built a tool, which is able to copy files and directories to a selected location. I used the shutil.copy function for copying files and the shutil.copytree function for copying directories. It all worked fine until i stumbled upon the following problem:
shutil.co... | Alternative for python shutils.copytree? | recently i built a tool, which is able to copy files and directories to a selected location. I used the shutil.copy function for copying files and the shutil.copytree function for copying directories. It all worked fine until i stumbled upon the following problem:
shutil.copytree function takes two arguments: src and d... | [
"The parameter \"dirs_exist_ok=\" should be set to \"True\" this allows for the existance of Directories at the desired location.\n"
] | [
0
] | [] | [] | [
"copying",
"copytree",
"python",
"python_3.x",
"shutil"
] | stackoverflow_0074288236_copying_copytree_python_python_3.x_shutil.txt |
Q:
Converting PDF page to JPG returns blank
I have a function that asks the user for a PDF file and receive the page number the user wish to convert into an image. The function usually works fine however with a few PDFs it does not work, the image that is returned is blank and it has 4 mega bytes. Apparently it has s... | Converting PDF page to JPG returns blank | I have a function that asks the user for a PDF file and receive the page number the user wish to convert into an image. The function usually works fine however with a few PDFs it does not work, the image that is returned is blank and it has 4 mega bytes. Apparently it has something to do with the size of the file. Is t... | [
"The solution to this problem was to change the DPI parameter of convert_from_path function. It is important to leave the DPI as it is, since I found that certain images become really small, and therefore unreadable.\n try:\n pages = convert_from_path(nome, poppler_path=r'C:\\Program Files\\poppler-0.68.0\\b... | [
1
] | [] | [] | [
"pdf2image",
"python",
"python_imaging_library"
] | stackoverflow_0074304749_pdf2image_python_python_imaging_library.txt |
Q:
How to use Coingecko Python wrapper with proxy?
A CoinGecko service has a Python wrapper that can be connected like this:
from pycoingecko import CoinGeckoAPI
cg = CoinGeckoAPI()
price = cg.get_coin_by_id('tether')
I have a python code that parses а free proxy site and returns random proxy dict like {'https': '18... | How to use Coingecko Python wrapper with proxy? | A CoinGecko service has a Python wrapper that can be connected like this:
from pycoingecko import CoinGeckoAPI
cg = CoinGeckoAPI()
price = cg.get_coin_by_id('tether')
I have a python code that parses а free proxy site and returns random proxy dict like {'https': '187.62.191.3:61256'}
import requests
from bs4 import Be... | [
"You can set your proxies after initializing CoinGeckoAPI() using directly the session attribute and then call any API endpoints.\nFor example:\nimport pycoingecko\ncg=pycoingecko.CoinGeckoAPI()\n\n# set up a proxy (or any other dictionary with proxies)\ncg.session.proxies['https']='http://10.10.1.10:1080'\n\n# you... | [
0
] | [] | [] | [
"proxy",
"python"
] | stackoverflow_0070783198_proxy_python.txt |
Q:
ERROR: Could not install packages due to an OSError: [WinError 5] Access denied
I installed the package matplotlib for a project and everything worked fine.
After a pull from github i got introduced with the following error: ModuleNotFoundError: No module named 'matplotlib.artist'.
I then tried to reinstall matplo... | ERROR: Could not install packages due to an OSError: [WinError 5] Access denied | I installed the package matplotlib for a project and everything worked fine.
After a pull from github i got introduced with the following error: ModuleNotFoundError: No module named 'matplotlib.artist'.
I then tried to reinstall matplotlib with this code in the terminal : python3 -m pip install matplotlib.
I tried pip ... | [
"Do this first if second step throws error\npython3 -m pip install matplotlib --user\n\n"
] | [
0
] | [] | [] | [
"matplotlib",
"oserror",
"python"
] | stackoverflow_0074317687_matplotlib_oserror_python.txt |
Q:
How to correctly use JOINs with SQLModel
I have two models - User and UserRole. I want to be able to get the user role together with the related user model.
I managed to do it like this:
@staticmethod
async def get_users(session: AsyncSession):
users = await session.execute(
select(User, UserRole).join... | How to correctly use JOINs with SQLModel | I have two models - User and UserRole. I want to be able to get the user role together with the related user model.
I managed to do it like this:
@staticmethod
async def get_users(session: AsyncSession):
users = await session.execute(
select(User, UserRole).join(UserRole, UserRole.role_id == User.role_id)
... | [
"Relationship attributes do in fact make these sorts of operations much simpler and more readable IMHO. One thing you can configure about your relationships is their loading behavior with regards to database queries. Since SQLModel is essentially a wrapper around SQLAlchemy, configuration is very similar.\nCurrentl... | [
1
] | [] | [] | [
"pydantic",
"python",
"sqlalchemy",
"sqlmodel"
] | stackoverflow_0074273829_pydantic_python_sqlalchemy_sqlmodel.txt |
Q:
Indexing: Presenting integer values in a 'n' bit string, turning on bits according to integer value
I have a list of numbers. Each index has 3 values.
[{24, 17, 22}, {16, 4, 38}, {25, 13, 38}, {32, 18, 15}, {8, 10, 18}]
I am trying to convert them into 39 bit string and turning on bits according to integer values.... | Indexing: Presenting integer values in a 'n' bit string, turning on bits according to integer value | I have a list of numbers. Each index has 3 values.
[{24, 17, 22}, {16, 4, 38}, {25, 13, 38}, {32, 18, 15}, {8, 10, 18}]
I am trying to convert them into 39 bit string and turning on bits according to integer values.
For example, {24, 17, 22} means that I should turn on bits 24, 17, 22 among 39 bits.
Sample Code:
p1='00... | [
"It sounds like you bit indices start at 1, but the string indices start at 0. You could check for i+1 in a to shift them all left by one:\nmylist=[{16, 4, 38}]\np1='000000000000000000000000000001011000000'\nfor x in range(0, len(mylist), 1):\n a = mylist[x]\n a = ''.join('1' if i+1 in a else '0' for i in ran... | [
1,
1
] | [] | [] | [
"genetic_algorithm",
"genetic_programming",
"python"
] | stackoverflow_0074317344_genetic_algorithm_genetic_programming_python.txt |
Q:
Python / smallest positive integer
I took following codility demo task
Write a function:
def solution(A)
that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.
For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
Given A = [1, 2, ... | Python / smallest positive integer | I took following codility demo task
Write a function:
def solution(A)
that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.
For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
Given A = [1, 2, 3], the function should return 4.
Given ... | [
"Python solution with O(N) time complexity and O(N) space complexity:\ndef solution(A):\n arr = [0] * 1000001\n for a in A:\n if a>0:\n arr[a] = 1\n for i in range(1, 1000000+1):\n if arr[i] == 0:\n return i\n\nMy main idea was to:\n\ncreat a zero-initialized \"buckets\"... | [
8,
1,
1,
1,
0,
0,
0,
0,
0
] | [
"Try this, I am assuming the list is not sorted but if it is sorted you can remove the number_list = sorted(number_list) to make it a little bit faster.\ndef get_smallest_positive_integer(number_list):\n if all(number < 0 for number in number_list) or 1 not in number_list:\n #checks if numbers in list are... | [
-1,
-1
] | [
"python",
"python_3.x"
] | stackoverflow_0060584052_python_python_3.x.txt |
Q:
How to send optional parameters using HTML checkboxes when uploading file to FastAPI?
I would like to upload a file that is going to be analyzed with a package that can have multiple parameters. For instance, I would like to upload the audio file, and then check some optional parameters to analyze this audio. Here... | How to send optional parameters using HTML checkboxes when uploading file to FastAPI? | I would like to upload a file that is going to be analyzed with a package that can have multiple parameters. For instance, I would like to upload the audio file, and then check some optional parameters to analyze this audio. Here is an example of how the frontend should look like:
However, I don't quite understand how... | [
"Please have a look at Method 1 of this answer, which provides an example on how to submit both Form and File data together.\nIn your example, you have to make sure to include the action attribute (which specifies the URL that processes the form submission) in the HTML <form>, as well as define the name attribute... | [
2
] | [] | [] | [
"checkbox",
"fastapi",
"html",
"python"
] | stackoverflow_0074307876_checkbox_fastapi_html_python.txt |
Q:
Artifactory: Download and unzip zip file using pip install
I created a repository, on Artifactory, which includes a zip containing 2 folders.
https://artifactory.healthcareit.net:443/artifactory/pi-generic-local/paymentintegrity-airflow-lib-plugins/paymentintegrity-airflow-libs-plugins-202211031330.zip
Is there a ... | Artifactory: Download and unzip zip file using pip install | I created a repository, on Artifactory, which includes a zip containing 2 folders.
https://artifactory.healthcareit.net:443/artifactory/pi-generic-local/paymentintegrity-airflow-lib-plugins/paymentintegrity-airflow-libs-plugins-202211031330.zip
Is there a way to download that zip and extract the directories during a pi... | [
"You can abuse the install command in the setup.py to call any arbitrary code, such as a one that unzips the assets and install it at the right place. I have seen this being done to package c++ binaries using python pypi in a place I worked for. See Post-install script with Python setuptools for hints on how to o... | [
0,
0
] | [] | [] | [
"artifactory",
"python"
] | stackoverflow_0074309110_artifactory_python.txt |
Q:
Plotting Boolean Data and Categories aren't Appearing
I have a column, TFColumn in a Pandas data frame with Boolean values (i.e., TRUE or FALSE). I am trying to plot the number of TRUE and FALSE values using a bar plot.
However, instead of displaying the values TRUE or FALSE on the x-axis under the bars, numeric v... | Plotting Boolean Data and Categories aren't Appearing | I have a column, TFColumn in a Pandas data frame with Boolean values (i.e., TRUE or FALSE). I am trying to plot the number of TRUE and FALSE values using a bar plot.
However, instead of displaying the values TRUE or FALSE on the x-axis under the bars, numeric values are displayed. What can I do to remove the numeric ax... | [
"I wonder if your task could be simpler w/o Pandas:\n\nIn [4]: from numpy import random\n ...: from matplotlib.pyplot import show, subplots\n ...: random.seed(20221104)\n ...: TFColumn = random.choice((False, True, True), 18000)\n ...: true = sum(TFColumn) ; false = len(TFColumn)-true\n ...: \n ...: fi... | [
0
] | [] | [] | [
"boolean",
"matplotlib",
"python"
] | stackoverflow_0074317206_boolean_matplotlib_python.txt |
Q:
Is it possible to create an artificial model in FactoryBoy?
I wanted to know if in the tests it is possible to somehow create an "artificial" model using FactoryBoy without touching models.py
I mean a simple model such as:
class SomeMod(models.Model):
title = models.CharField(max_length=255, blank=True, null=T... | Is it possible to create an artificial model in FactoryBoy? | I wanted to know if in the tests it is possible to somehow create an "artificial" model using FactoryBoy without touching models.py
I mean a simple model such as:
class SomeMod(models.Model):
title = models.CharField(max_length=255, blank=True, null=True)
description = models.CharField(max_length=255, blank=Tru... | [
"You may be looking for the attribute abstract in the Meta options of the factory class, which is mentioned here in Factory Boy documentation.\nfrom factory.django import DjangoModelFactory\nfrom factory import Faker\n\nclass MyAbstractFactory(DjangoModelFactory):\n title = Faker(\"last_name\") # could be \"comp... | [
0
] | [] | [] | [
"django",
"django_models",
"django_unittest",
"factory_boy",
"python"
] | stackoverflow_0074263446_django_django_models_django_unittest_factory_boy_python.txt |
Q:
How can I bypass the 429-error from www.instagram.com?
i'm solliciting you today because i've a problem with selenium.
my goal is to make a full automated bot that create an account with parsed details (mail, pass, birth date...) So far, i've managed to almost create the bot (i just need to access to gmail and get... | How can I bypass the 429-error from www.instagram.com? | i'm solliciting you today because i've a problem with selenium.
my goal is to make a full automated bot that create an account with parsed details (mail, pass, birth date...) So far, i've managed to almost create the bot (i just need to access to gmail and get the confirmation code).
My problem is here, because i've tr... | [
"The answer is in the description of the HTTP error code. You are being blocked because you made too many requests in a short time.\nReduce the rate at which your bot makes requests and see if that helps. As far as I know there's no way to \"bypass\" this check by the server.\nCheck if the response header has a Ret... | [
0,
0,
0
] | [] | [] | [
"http_status_code_429",
"instagram",
"python",
"selenium"
] | stackoverflow_0064769138_http_status_code_429_instagram_python_selenium.txt |
Q:
Poetry install equivalent for -f flag in pip
I need to install packages with poetry (add them to pyproject.toml). I have to translate this to poetry. But in the documentation I did not find something similar to the -f flag. This is the command:
pip install torch==1.8.1+cu111 torchvision==0.9.1+cu111 torchaudio==0.... | Poetry install equivalent for -f flag in pip | I need to install packages with poetry (add them to pyproject.toml). I have to translate this to poetry. But in the documentation I did not find something similar to the -f flag. This is the command:
pip install torch==1.8.1+cu111 torchvision==0.9.1+cu111 torchaudio==0.8.1 -f https://download.pytorch.org/whl/torch_stab... | [
"Even though this question already aged a bit, it ended up quite high in my google search. Since I think I found a quite useable solution to this problem I wanted to share it here:\nSince Poetry still can't resolve pytorch+cuda bundles you have to specify the path to its specific wheel. Since that broke my use case... | [
1
] | [] | [] | [
"python",
"python_poetry"
] | stackoverflow_0072260326_python_python_poetry.txt |
Q:
ImportError: cannot import name 'TagHelperNode' from 'django.template.base'
I'm facing the error of cannot import name 'TagHelperNode' from 'django.template.base' while im trying to migrate to django 3.2
I know that the problem will be solved if I downgrad django but I can't do that
A:
You can import TagHelperNo... | ImportError: cannot import name 'TagHelperNode' from 'django.template.base' | I'm facing the error of cannot import name 'TagHelperNode' from 'django.template.base' while im trying to migrate to django 3.2
I know that the problem will be solved if I downgrad django but I can't do that
| [
"You can import TagHelperNode by :\nfrom django.template.library import TagHelperNode\n\n"
] | [
0
] | [] | [] | [
"django",
"django_3.2",
"python",
"python_3.8"
] | stackoverflow_0074315724_django_django_3.2_python_python_3.8.txt |
Q:
Python Firebird WinError 193 connection error
import fdb
def main():
con = fdb.connect(dsn='C:\AKINSOFT\Wolvox8\Database_FB\SIRKET.FDB', user='sysdba', password='masterkey')
if __name__ == '__main__':
main()
I wrote a simple code for connecting a Firebird database with Python and fdb. When I run this, I... | Python Firebird WinError 193 connection error | import fdb
def main():
con = fdb.connect(dsn='C:\AKINSOFT\Wolvox8\Database_FB\SIRKET.FDB', user='sysdba', password='masterkey')
if __name__ == '__main__':
main()
I wrote a simple code for connecting a Firebird database with Python and fdb. When I run this, I get an winerror 193
Traceback (most recent call la... | [
"The English error is \"[WinError 193] %1 is not a valid Win32 application\", and it means you're trying to load a 32-bit DLL in a 64-bit process (or a 64-bit DLL in a 32-bit process). This means that you don't have a valid fbclient.dll on the PATH that matches the bitness of your Python process, but do have one of... | [
1
] | [] | [] | [
"firebird",
"python",
"python_3.x"
] | stackoverflow_0074317821_firebird_python_python_3.x.txt |
Q:
Calculate the VWAP indicator on a daily basis from a pandas df
I have stocks data in a Dataframe ( Example below)
I'm used to calculate the VWAP (volume weighted average price with this formula) in this way:
v = df['Volume'].values
tp = (df['Low'] + df['Close'] + df['High']).div(3).values
df = df.assign(vwap=((tp... | Calculate the VWAP indicator on a daily basis from a pandas df | I have stocks data in a Dataframe ( Example below)
I'm used to calculate the VWAP (volume weighted average price with this formula) in this way:
v = df['Volume'].values
tp = (df['Low'] + df['Close'] + df['High']).div(3).values
df = df.assign(vwap=((tp * v).cumsum() / v.cumsum()))
Problem is this formula calculation t... | [
"You first group by day, df.Date.dt.date will give you the day. Then you just apply your vwap function to the daily group you just created. I corrected your vwap function so it is more elegant (and efficient).\ndef vwap(g):\n g['vwap'] = (g.tp * g.Volume).cumsum() / g.Volume.cumsum()\n return g\n\ndf['tp'] = (d... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074317525_dataframe_pandas_python.txt |
Q:
TypeError: Function missing 1 required positional argument: 'self'
I have a function in GCP that I have working on my local machine, but when i push it onto GCP Cloud Functions I keep getting an error.
the function collects a message from PubSub and then uses the IDs collected for an API call.
the code for the fun... | TypeError: Function missing 1 required positional argument: 'self' | I have a function in GCP that I have working on my local machine, but when i push it onto GCP Cloud Functions I keep getting an error.
the function collects a message from PubSub and then uses the IDs collected for an API call.
the code for the function is:
from concurrent.futures import TimeoutError
from google.cloud ... | [
"The missing 1 required positional argument:self error is usually raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class.\nTo solve this error, make sure that you first instantiate an object of a class before you try ... | [
0
] | [] | [] | [
"google_cloud_functions",
"google_cloud_platform",
"google_cloud_pubsub",
"python"
] | stackoverflow_0074285768_google_cloud_functions_google_cloud_platform_google_cloud_pubsub_python.txt |
Q:
How to trim a string inside a query string passed to the Pandas query function?
I need to trim the 'My Pet' column inside the query string. How can that be done?
# Note that one cat literal has a trailing space.
testDF = pd.DataFrame([{"My Pet":"cat ", "Cost":"$10 ", "Weight":"10 pounds", "Name":"Violet"},
... | How to trim a string inside a query string passed to the Pandas query function? | I need to trim the 'My Pet' column inside the query string. How can that be done?
# Note that one cat literal has a trailing space.
testDF = pd.DataFrame([{"My Pet":"cat ", "Cost":"$10 ", "Weight":"10 pounds", "Name":"Violet"},
{"My Pet":"cat", "Cost":"$10 ", "Weight":"15 pounds", "Name":"Si... | [
"Use Series.str.strip, but need engine=\"python\":\ncatDF = testDF.query(\"`My Pet`.str.strip() == 'cat'\", engine=\"python\")\nprint (catDF)\n My Pet Cost Weight Name\n0 cat $10 10 pounds Violet\n1 cat $10 15 pounds Sirius\n\n",
"You can access string methods on string series. This means t... | [
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074317958_dataframe_pandas_python.txt |
Q:
how can I optimize this code? fliping all the vowels in a string
This code takes all the vowels in a string and flip thier positions.
class Solution:
def reverseVowels(self, s: str) -> str:
list_vowels= [x for x in s if x in 'aeiouAEIOU'][::-1]
list=[x for x in s]
... | how can I optimize this code? fliping all the vowels in a string | This code takes all the vowels in a string and flip thier positions.
class Solution:
def reverseVowels(self, s: str) -> str:
list_vowels= [x for x in s if x in 'aeiouAEIOU'][::-1]
list=[x for x in s]
z=0
for number in range(0,len(s)):
... | [
"The code can be simplified as follows.\n\nuse reverse iterator reversed to get successive elements of vowels in reverse order as needed\nUse Python PEP 8 Style Guide for naming functions and variables\nMaking use of a 'constant' rather than defining vowels multiple times (aids code maintainability)\nIn Python it's... | [
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0074317617_python_string.txt |
Q:
How to create a nested dictionary with csv file
I want to create a nested dictionary. From a csv file (see pic) where i want to keep keys same
e.g
{'name':'john' , 'sname':'doe' , 'address':'120 Jefferson st'} ,
{'name':'jack' , 'sname':'McGinnis', 'address':'202 hobo'}}
all the row data in one dictionay with k... | How to create a nested dictionary with csv file | I want to create a nested dictionary. From a csv file (see pic) where i want to keep keys same
e.g
{'name':'john' , 'sname':'doe' , 'address':'120 Jefferson st'} ,
{'name':'jack' , 'sname':'McGinnis', 'address':'202 hobo'}}
all the row data in one dictionay with keys as their column name.
stuck here
| [
"I understand you want a list of dictionaries.\nimport pandas as pd\n\ndata = pd.read_csv(\"dataset.csv\")\n\ndict_list = []\nfor i in range (len(data)):\n dict = {}\n for col in data.columns :\n dict[col] = data[col].iloc[i]\n dict_list.append(dict)\n\nprint(dict_list)\n\n"
] | [
2
] | [] | [] | [
"dictionary",
"list",
"mongodb",
"python"
] | stackoverflow_0074316235_dictionary_list_mongodb_python.txt |
Q:
How to add and subtract the matrix index values in a function?
Let's say I have a 3x3 matrix. In a function, I want to define two variables m , n as index numbers of the matrix dimensions.
I want to subtract all possible combinations. How would I define that in a function?
I.e.: (m-n) should do = (1-1), (1-2), (1-... | How to add and subtract the matrix index values in a function? | Let's say I have a 3x3 matrix. In a function, I want to define two variables m , n as index numbers of the matrix dimensions.
I want to subtract all possible combinations. How would I define that in a function?
I.e.: (m-n) should do = (1-1), (1-2), (1-3), (2-1), (2-2), (2-3), (3-1), (3,2), (3,3). Not the matrix cell va... | [
"Even simpler, without loops, you can do (M is your m x n matrix):\nm = np.arange(M.shape[0]) #List of indexes of the first dimension (lines) \nm = m.reshape((M.shape[0], 1)) #transpose to obtain a vertical matrix \nn=np.arange(M.shape[1]) #List of indexes of second dimensions (columns) \nS = np.sum(M * (m-n)**2) ... | [
1
] | [] | [] | [
"matrix",
"numpy",
"pandas",
"python"
] | stackoverflow_0074317992_matrix_numpy_pandas_python.txt |
Q:
A Python function that returns the number of k permutations of n items
At first, I was asked to implement the number P(n) of of (n-) permutations of n items satisfies the following recurrence:
I did so successfully (num_permutation_v1):
Now, I am asked to extend the function num_permutation_v1, to num_permutatio... | A Python function that returns the number of k permutations of n items | At first, I was asked to implement the number P(n) of of (n-) permutations of n items satisfies the following recurrence:
I did so successfully (num_permutation_v1):
Now, I am asked to extend the function num_permutation_v1, to num_permutation_v2, to allow for an optional argument "k":
Here is the function that I wr... | [
"Here's what the revised function could be (you could tweak it to send an error if there are more than 2 arguments, but I decided to simply ignore arguments after the 2nd one); note that I didn't do exactly what I said in my comment, in order to reduce the code:\ndef num_permutations_v2(n,*k):\n if n < 0 or (k a... | [
1
] | [] | [] | [
"permutation",
"python"
] | stackoverflow_0074317747_permutation_python.txt |
Q:
PyLint message: logging-format-interpolation
For the following code:
logger.debug('message: {}'.format('test'))
pylint produces the following warning:
logging-format-interpolation (W1202):
Use % formatting in logging functions and pass the % parameters as
arguments Used when a logging statement has a call form... | PyLint message: logging-format-interpolation | For the following code:
logger.debug('message: {}'.format('test'))
pylint produces the following warning:
logging-format-interpolation (W1202):
Use % formatting in logging functions and pass the % parameters as
arguments Used when a logging statement has a call form of
“logging.(format_string.format(format_args..... | [
"It is not true for logger statement because it relies on former \"%\" format like string to provide lazy interpolation of this string using extra arguments given to the logger call. For instance instead of doing:\nlogger.error('oops caused by %s' % exc)\n\nyou should do\nlogger.error('oops caused by %s', exc)\n\ns... | [
346,
77,
35,
0
] | [
"Might be several years after but having to deal with this the other day, I made simple; just formatted the string before logger.\nmessage = 'message: {}'.format('test')\nlogger.debug(message)\n\nThat way there was no need to change any of the settings from log, if later on desire to change to a normal print there... | [
-1
] | [
"pylint",
"python",
"python_3.x"
] | stackoverflow_0034619790_pylint_python_python_3.x.txt |
Q:
why QTableWidget does not refresh after closing tab in pyqt5?
the below example is my problem which can not figure it out! i appreciate if anyone can help on this problem. i have set of data which in this example i am reading from csv file. in next step i am filling my QTableWidget with the data. The problem is wh... | why QTableWidget does not refresh after closing tab in pyqt5? | the below example is my problem which can not figure it out! i appreciate if anyone can help on this problem. i have set of data which in this example i am reading from csv file. in next step i am filling my QTableWidget with the data. The problem is when i change data and close the tab and open it, the data does not r... | [
"You're assigning a single QWidget instance at MainWindow.setup_ui, right here:\n\ndef setup_ui(self):\n # toolbar\n self.toolbar = self.addToolBar('Tool Bar')\n self.test_btn = QAction('Test', self)\n # .\n # .\n\n # tab\n self.tabs = QTabWidget() # <--\n # .\n # .\n # .\n self.set... | [
1
] | [] | [] | [
"pyqt",
"pyqt5",
"python"
] | stackoverflow_0074317176_pyqt_pyqt5_python.txt |
Q:
How can I check if static file exists or not from url_for() in Flask?
Is there is way I can check the static file from url_for() is really exist or not? Because I would like to check that if the first file does not exists, I would like to replace it with another file just like this in my html file:
{% set IconPng ... | How can I check if static file exists or not from url_for() in Flask? | Is there is way I can check the static file from url_for() is really exist or not? Because I would like to check that if the first file does not exists, I would like to replace it with another file just like this in my html file:
{% set IconPng = url_for('static', filename="images/favo.png") %}
{% set IconIco = url_for... | [
"In my opinion it is rather task for javascript than your backend.\nYou can check if image exist using function like this one, and then change image src accordingly:\nfunction file_exists(url){\n var http = new XMLHttpRequest();\n\n http.open('HEAD', url, false);\n http.send();\n\n return http.status !=... | [
2,
0
] | [] | [] | [
"flask",
"jinja2",
"python"
] | stackoverflow_0062790012_flask_jinja2_python.txt |
Q:
How can I see the number of duplicate elements in python array?
I want to write a function that returns the number of duplicate items in an array.
For example:
arr = [2,4,6,3,2,2,4,6]
# this should return 3 since (2,4,6) are repeated in the list
A:
Something like this should work:
def duplicate_in_array(array):
... | How can I see the number of duplicate elements in python array? | I want to write a function that returns the number of duplicate items in an array.
For example:
arr = [2,4,6,3,2,2,4,6]
# this should return 3 since (2,4,6) are repeated in the list
| [
"Something like this should work:\ndef duplicate_in_array(array):\narray_len = len(array)\nduplicate_set = set()\n\nfor i in range(array_len):\n for y in range(i + 1,array_len):\n if array[i] == array[y]:\n duplicate_set.add(array[i])\n\nreturn len(duplicate_set)\n\nWith a double for-loop, you ... | [
1,
1
] | [] | [] | [
"arrays",
"count",
"duplicates",
"list",
"python"
] | stackoverflow_0074315480_arrays_count_duplicates_list_python.txt |
Q:
Why is my variables not being added to my 2 list?
Even and odd list
import random
even_numbers = []
odd_numbers = []
def oddandeven (numbers_list):
original_list = [random.randint (1,10) for x in range(0,10)]
print ('Original list:',original_list)
for numbers_list in original_list:
if num... | Why is my variables not being added to my 2 list? | Even and odd list
import random
even_numbers = []
odd_numbers = []
def oddandeven (numbers_list):
original_list = [random.randint (1,10) for x in range(0,10)]
print ('Original list:',original_list)
for numbers_list in original_list:
if numbers_list % 2 == 0:
even_numbers.append(num... | [
"One way to solve it\nimport random\neven_numbers = []\nodd_numbers = []\noriginal_list = [random.randint (1,10) for x in range(0,10)]\n\ndef oddandeven ():\n print (f'Original list: {original_list}')\n \n for a in original_list:\n if a % 2 == 0:\n even_numbers.append(a)\n even... | [
0
] | [] | [] | [
"function",
"list",
"new_operator",
"python",
"return"
] | stackoverflow_0074317742_function_list_new_operator_python_return.txt |
Q:
Checking if XML have some elements
For example I have this XML file:
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
... | Checking if XML have some elements | For example I have this XML file:
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapo... | [
"Not sure about the dataframe part, but the general direction would be something like this:\nfrom lxml import etree\ncountries = \"\"\"[your xml above]\"\"\"\ndoc = etree.XML(countries)\ntarget= \"Liechtenstein\" #or whatever other country you specify\nneighbors = [\"Austria\",\"Germany\"] #same here\ninfo = doc.xp... | [
0
] | [] | [] | [
"for_loop",
"if_statement",
"loops",
"python",
"xml"
] | stackoverflow_0074317259_for_loop_if_statement_loops_python_xml.txt |
Q:
Which Python versions do I need to support as the upstream author of a Python library for Debian?
I'm the upstream- and Debian maintainer of a Python library which is installed as a dependency of a required package in the Debian ecosystem, so this library is pretty much installed on every Debian system. I'm trying... | Which Python versions do I need to support as the upstream author of a Python library for Debian? | I'm the upstream- and Debian maintainer of a Python library which is installed as a dependency of a required package in the Debian ecosystem, so this library is pretty much installed on every Debian system. I'm trying to support older Python versions as long as possible and my rule of thumb for this package is to suppo... | [
"As far as Debian is concerned, the package you publish should support the currently supported Python versions. So if you published a package when oldstable was still stable, the package you published then should have supported the oldstable Python versions. When you publish something now, the current stable is you... | [
1
] | [] | [] | [
"debian",
"python"
] | stackoverflow_0074318110_debian_python.txt |
Q:
Counting the most frequent sequence occurring in a string
Full Code is here: https://nekobin.com/yehukomiya
(Don't mind the computeFile() function)
Hi, I've got a text file with repeating chars in binary string like "0101001001111000010010011110010000000" I already got the KMPSearch() function that I use to count ... | Counting the most frequent sequence occurring in a string | Full Code is here: https://nekobin.com/yehukomiya
(Don't mind the computeFile() function)
Hi, I've got a text file with repeating chars in binary string like "0101001001111000010010011110010000000" I already got the KMPSearch() function that I use to count how many times a given sequence occurs in my string. I also cou... | [
"A rather straightforward, unoptimized way to approach this is in 2 steps could be (explanation below):\nfrom collections import defaultdict\n\ns = \"01010010010001000111101100001010011001111000010010011110010000000\"\n\nmin_seq_length = 2\n\n# 1. Count recurring sequences\nsequence_dict = defaultdict(lambda: 0)\nf... | [
0
] | [] | [] | [
"find_occurrences",
"list",
"python",
"sequence",
"tuples"
] | stackoverflow_0074316506_find_occurrences_list_python_sequence_tuples.txt |
Q:
Add parameter within SQL Query - Python
I have defined a parameter called CODE.
CODE is a list of strings, for instance 'Car', 'Bike', 'Boat' and so on.
I need to execute SQL Querys that have the following pattern:
Select * from Table when CODE=Car
Or
Select * from Table when CODE=Bike
and so on.
Is it posible t... | Add parameter within SQL Query - Python | I have defined a parameter called CODE.
CODE is a list of strings, for instance 'Car', 'Bike', 'Boat' and so on.
I need to execute SQL Querys that have the following pattern:
Select * from Table when CODE=Car
Or
Select * from Table when CODE=Bike
and so on.
Is it posible to use the parameter directly in the Query?
Li... | [
"If it isn't a long list of values in CODE, then you can do the following:\nselect * from Table where CODE IN ('Car', 'Bike', 'Boat', 'Motor', ...);\n\n",
"You can use Python string formatting to replace the value. One type of formatting is the f-string syntax\n#OLD (your approach)\nsql=\"SELECT * FROM DATABASE ... | [
1,
1
] | [] | [] | [
"python",
"sql"
] | stackoverflow_0074317356_python_sql.txt |
Q:
Why dict.get(key) instead of dict[key]?
Today, I came across the dict method get which, given a key in the dictionary, returns the associated value.
For what purpose is this function useful? If I wanted to find a value associated with a key in a dictionary, I can just do dict[key], and it returns the same thing:
d... | Why dict.get(key) instead of dict[key]? | Today, I came across the dict method get which, given a key in the dictionary, returns the associated value.
For what purpose is this function useful? If I wanted to find a value associated with a key in a dictionary, I can just do dict[key], and it returns the same thing:
dictionary = {"Name": "Harry", "Age": 17}
dict... | [
"It allows you to provide a default value if the key is missing:\ndictionary.get(\"bogus\", default_value)\n\nreturns default_value (whatever you choose it to be), whereas\ndictionary[\"bogus\"]\n\nwould raise a KeyError. \nIf omitted, default_value is None, such that\ndictionary.get(\"bogus\") # <-- No default s... | [
1480,
224,
37,
29,
25,
20,
11,
9,
5,
5,
4,
1,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0011041405_dictionary_python.txt |
Q:
How can I label a row with a keyword if another columns value contains a string from a list?
I am working on a dataframe that has a category of challenges for a class. I need to be able to identify them as either being 'linux','window' or 'primer' based. I have created a dictionary as so:
import pandas as pd
topi... | How can I label a row with a keyword if another columns value contains a string from a list? | I am working on a dataframe that has a category of challenges for a class. I need to be able to identify them as either being 'linux','window' or 'primer' based. I have created a dictionary as so:
import pandas as pd
topic_keywords_dict = {
'Linux':
{
'identification':['linux'],
't... | [
"I would recommend just making a function: it's a little much for a one-liner. Try something like this:\ndef func(category):\n for platform, data in topic_keywords_dict.items():\n if any(x in category for x in data['identification']:\n return platform\n return None\n\ndf['key_dict'] = df['C... | [
1,
1
] | [] | [] | [
"lambda",
"pandas",
"python"
] | stackoverflow_0074318195_lambda_pandas_python.txt |
Q:
Calculate correlation between different datasets of dict object
I currently have a dict Object called xrz_data comprised of different stock data (around 100 different tickers). The structure is as following:
xrz_data
{'AAPL': Open High Low Close Adj Close \
Date ... | Calculate correlation between different datasets of dict object | I currently have a dict Object called xrz_data comprised of different stock data (around 100 different tickers). The structure is as following:
xrz_data
{'AAPL': Open High Low Close Adj Close \
Date
2021-12... | [
"In your call to np.corrcoef, you are comparing temp_data, which is a dictionary, with temp_data_2, which is a Series.\nMinimal change here:\nresults = {}\n\nfor ticker1 in xrz_data:\n for ticker2 in xrz_data:\n corr = np.corrcoef(xrz_data[ticker1].Close, xrz_data[ticker2].Close)[0, 1]\n print(f\"C... | [
2
] | [] | [] | [
"correlation",
"dictionary",
"pandas",
"python"
] | stackoverflow_0074317952_correlation_dictionary_pandas_python.txt |
Q:
How to show Company CI icon useing MarkerCluster in Folium
from folium.plugins import MarkerCluster
import folium
from folium.features import CustomIcon
import pandas as pd
import folium.plugins as plug
df = pd.read_excel('store.xlsx')
df1 = df[['대리점명','Latitude','Longitude']]
df1.rename(columns= {'대리점명':'Store'... | How to show Company CI icon useing MarkerCluster in Folium | from folium.plugins import MarkerCluster
import folium
from folium.features import CustomIcon
import pandas as pd
import folium.plugins as plug
df = pd.read_excel('store.xlsx')
df1 = df[['대리점명','Latitude','Longitude']]
df1.rename(columns= {'대리점명':'Store'}, inplace=True)
df1.head()
x = []
y = []
name = []
for i in ra... | [
"The point is that each marker must be set to belong to a marker cluster. Latitude and longitude and store name are created randomly. Also, the logo is a stack overflow logo.\nimport numpy as np\nimport pandas as pd\nimport folium\nfrom folium.plugins import MarkerCluster\nfrom folium.features import CustomIcon\n\n... | [
0
] | [] | [] | [
"folium",
"python"
] | stackoverflow_0074300951_folium_python.txt |
Q:
How to substract from each element in a matrix, with a condition
I have a matrix, and i don't know the size, because the matrix was created from a dataframe. I have 2 arrays, min_cols and max_cols, first one is for each minimum from each column, and same with the max_cols.
I want to recalculate each element from t... | How to substract from each element in a matrix, with a condition | I have a matrix, and i don't know the size, because the matrix was created from a dataframe. I have 2 arrays, min_cols and max_cols, first one is for each minimum from each column, and same with the max_cols.
I want to recalculate each element from the columns, with this formula:
Element[line][column] = Element - min_... | [
"If I understand correctly, you have a 2d numpy array called Elements, that you want to recalculate using the min and max of each column stored in their respective numpy arrays. You could simply do something like:\nElements += - min/(max - min)\n\n",
"I think it's more like this (numpy will do exactly what you im... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074318158_python.txt |
Q:
convert 24 hour time (in string format) to time format
The time is given in string for eg "23:20". However in my function I need to compare times for which I gotta convert these to time format
I tried strptime() and it works with 12 hour format for eg when I enter "12:00PM"
A:
Possible Duplicate of [https://stac... | convert 24 hour time (in string format) to time format | The time is given in string for eg "23:20". However in my function I need to compare times for which I gotta convert these to time format
I tried strptime() and it works with 12 hour format for eg when I enter "12:00PM"
| [
"Possible Duplicate of [https://stackoverflow.com/questions/19229190/how-to-convert-am-pm-timestmap-into-24hs-format-in-python]\nCode that works from there\n%H is the 24 hour clock, %I is the 12 hour clock and when using the 12 hour clock, %p qualifies if it is AM or PM.\n from datetime import datetime\n m2 = '... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074318140_python.txt |
Q:
Unable to Deploy Django App to Heroku because of PyWin32
So I have gone through the forums in search for an answer but haven't found one that works for me.
I am using Windows machine and my Django application works on Localhost but when I try to deploy the same application to Heroku it gives me this error.
INFO: p... | Unable to Deploy Django App to Heroku because of PyWin32 | So I have gone through the forums in search for an answer but haven't found one that works for me.
I am using Windows machine and my Django application works on Localhost but when I try to deploy the same application to Heroku it gives me this error.
INFO: pip is looking at multiple versions of anyio to determine which... | [
"In your current requirements.txt you marked pywin32 with environment marker platform_system == \"Windows\". I think the syntax is wrong. The correct syntax from PEP 496 is:\npywin32==223; sys_platform == \"win32\"\n\n",
"I had the same issue while trying to deploy my Django project to Heroku. The reason for this... | [
2,
1,
0,
0
] | [] | [] | [
"django",
"git",
"heroku",
"pip",
"python"
] | stackoverflow_0069958591_django_git_heroku_pip_python.txt |
Q:
How do I access and read the CSV files created by my python code?
How do I extract/view the csv files created by this block of code? What the code does is pull data from a table and extract the json elements. I am running this code on Jupyter notebook but I can't figure out how to view the csv file.
print('Conduct... | How do I access and read the CSV files created by my python code? | How do I extract/view the csv files created by this block of code? What the code does is pull data from a table and extract the json elements. I am running this code on Jupyter notebook but I can't figure out how to view the csv file.
print('Conducting ETL for all events data')
class CsvBuilder:
def __init__(self,... | [
"You can add a current working directory to your paths, pathlib module is a good choice for that:\nimport pathlib\nCWD = pathlib.Path().resolve()\n...\nCsvBuilder(CWD / 'open.csv')\n...\npd.read_csv(CWD / 'open.csv')\n\n\n",
"Doesn't this work?\npd.read_csv(csvBuilderProvider.getBuilderForEvent(\"open\")._fileNam... | [
0,
0
] | [
"Lambda stores files locally on the /tmp folder.\nSo in order to open the file, you would need to do something like this:\nimport os\nos.chdir('/tmp')\npd.read_csv('open.csv')\n\n"
] | [
-1
] | [
"amazon_redshift",
"amazon_web_services",
"python"
] | stackoverflow_0074316890_amazon_redshift_amazon_web_services_python.txt |
Q:
How to tune extended kalman filter on PyKalman?
I would like to correct some predicted vehicular variables: latitude, longitude, speed, heading and acceleration. Inside the following code, there are the values of those variables. There are 20 samples, the first 10 samples are the original data and the last 10 samp... | How to tune extended kalman filter on PyKalman? | I would like to correct some predicted vehicular variables: latitude, longitude, speed, heading and acceleration. Inside the following code, there are the values of those variables. There are 20 samples, the first 10 samples are the original data and the last 10 samples the predicted ones. I expected EKF to denoise tho... | [
"Actually, your Kalman is linear, not extended Kalman Filter.\nYour problem is in the function ekf when you define the variable state_estimate_k.\nThe formula should be x(estimate) = F*x + B*u. Just change your code to this :\nstate_estimate_k = A_k_minus_1 @ (\n state_estimate_k_minus_1) + (\n ... | [
2
] | [] | [] | [
"coordinates",
"kalman_filter",
"pykalman",
"python"
] | stackoverflow_0074318200_coordinates_kalman_filter_pykalman_python.txt |
Q:
Decision Boundary will not overlay all scatter plot
I am developing a Knn model with Decision Boundary on normalised data. I wanted to separate each species of the iris dataset based on additional column values (reproducible example). The extra column is supposed to represent colours for the species.
Here is what ... | Decision Boundary will not overlay all scatter plot | I am developing a Knn model with Decision Boundary on normalised data. I wanted to separate each species of the iris dataset based on additional column values (reproducible example). The extra column is supposed to represent colours for the species.
Here is what I have tried, sample data:
import matplotlib.pyplot as pl... | [
"Turns out the\nscalex and scaley values in the scatterplot meant the points were re-scaled. Therefore, removing this I get the correct plot:\n\n"
] | [
0
] | [] | [] | [
"knn",
"machine_learning",
"plot",
"python",
"scikit_learn"
] | stackoverflow_0074302681_knn_machine_learning_plot_python_scikit_learn.txt |
Q:
OS_Access_Violation
I am taking filename in put from environment variable for my python app and when I ran checkmarx validation tool I am seeing that we can not and should not pass unvalidated user input to os module.
I have added how I am getting value from user and how I am using it in os module. I know the issu... | OS_Access_Violation | I am taking filename in put from environment variable for my python app and when I ran checkmarx validation tool I am seeing that we can not and should not pass unvalidated user input to os module.
I have added how I am getting value from user and how I am using it in os module. I know the issue can arise as user might... | [
"This is a true-positive result given that it is generally a bad idea to allow an unknown user to specify values passed to OS operations. In this case, it could be something simple like your program is running as a user that symlinks to a file that an attacker can't normally see. There are all sorts of fun things... | [
0
] | [] | [] | [
"checkmarx",
"input",
"python"
] | stackoverflow_0073986628_checkmarx_input_python.txt |
Q:
I recieve an "OSError: [Errno 22] Invalid argument" when I'm trying to change a time format
When i use %H:%M:%S i get this Error. if im using it with dots everything is fine. Can someone explain why? and how to use colons?
import os, time, zipfile
source = ["C:\\Users\\Daniel\\Documents\\Projects", "C:\\Users\\Da... | I recieve an "OSError: [Errno 22] Invalid argument" when I'm trying to change a time format | When i use %H:%M:%S i get this Error. if im using it with dots everything is fine. Can someone explain why? and how to use colons?
import os, time, zipfile
source = ["C:\\Users\\Daniel\\Documents\\Projects", "C:\\Users\\Daniel\\Pictures\\pics"]
target_dir = 'D:\\Backup'
today = target_dir + os.sep + time.strftime('%Y... | [
"The use of : on Windows is restricted. Also, the following are reserved characters:\n\n< (less than)\n> (greater than)\n\" (double quote)\n/ (forward slash)\n\\ (backslash)\n| (vertical bar or pipe)\n? (question mark)\n* (asterisk)\n\nYou can read more here\n"
] | [
0
] | [] | [] | [
"python",
"strftime"
] | stackoverflow_0074318450_python_strftime.txt |
Q:
How to use DeepDiff with custom_operators and iterable_compare_func altogether?
I have to use DeepDiff to compare two lists of dictionaries with metrics of some variables. The comparison should be done in such a way that if the new metrics are equal to or greater than the previous ones, no difference between the d... | How to use DeepDiff with custom_operators and iterable_compare_func altogether? | I have to use DeepDiff to compare two lists of dictionaries with metrics of some variables. The comparison should be done in such a way that if the new metrics are equal to or greater than the previous ones, no difference between the dictionaries should be shown, but if the new metrics are smaller, the difference shoul... | [
"Have you tried the 'ignore_order' parameter?\n"
] | [
0
] | [] | [] | [
"compare",
"deep_diff",
"dictionary",
"python",
"regression_testing"
] | stackoverflow_0074308995_compare_deep_diff_dictionary_python_regression_testing.txt |
Q:
When using env.yml with conda whats the difference between dependencies and pip dependencies?
I am creating a .SH script for setting up automatically my dev environment in Azure ML, according to this:
https://learn.microsoft.com/en-gb/azure/machine-learning/how-to-customize-compute-instance
The script looks like t... | When using env.yml with conda whats the difference between dependencies and pip dependencies? | I am creating a .SH script for setting up automatically my dev environment in Azure ML, according to this:
https://learn.microsoft.com/en-gb/azure/machine-learning/how-to-customize-compute-instance
The script looks like this:
#!/bin/bash
set -e
# https://pypi.org/project/azure-ai-ml/
# Requires: Python <4.0, >=3.7
#... | [
"dependencies are conda dependencies; listing them is equivalent to run conda install <deps>. For example conda installs numpy from https://anaconda.org/conda-forge/numpy .\npip means pip dependencies for pip install command; pip installs them from PyPI.org. For example, https://pypi.org/project/numpy/\nThe same fo... | [
1
] | [] | [] | [
"conda",
"pip",
"python"
] | stackoverflow_0074318473_conda_pip_python.txt |
Q:
Writing into a file Python
I am trying to get user input into a text file on different lines. The user input is stored in a list then the list is appended. I realize you are not suppose to use quotes since that will act as your own input. How could I go about using the user input?
def userfile():
text = []
s... | Writing into a file Python | I am trying to get user input into a text file on different lines. The user input is stored in a list then the list is appended. I realize you are not suppose to use quotes since that will act as your own input. How could I go about using the user input?
def userfile():
text = []
s1 = input("Enter sentence #1 ")
... | [
"I think your error is in userfile(): you write both inputs into the same variable s1. And then you don't even use the text array you just created.\nTry this:\ndef userfile():\n text = []\n text.append(input(\"Enter sentence #1 \"))\n text.append(input(\"Enter sentence #2 \"))\n # ...\n userfile.wri... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074317867_python.txt |
Q:
How to return an unpacked list in Python?
I'm trying to do something like this in python:
def f():
b = ['c', 8]
return 1, 2, b*, 3
Where I want f to return the tuple (1, 2, 'c', 8, 3). I found a way to do this using itertools followed by tuple, but this is not very nice, and I was wondering whether there ... | How to return an unpacked list in Python? | I'm trying to do something like this in python:
def f():
b = ['c', 8]
return 1, 2, b*, 3
Where I want f to return the tuple (1, 2, 'c', 8, 3). I found a way to do this using itertools followed by tuple, but this is not very nice, and I was wondering whether there exists an elegant way to do this.
| [
"The unpacking operator * appears before the b, not after it. \nreturn (1, 2, *b, 3)\n# ^ ^^ ^\n\nHowever, this will only work on Python 3.5+ (PEP 448), and also you need to add parenthesis to prevent SyntaxError. In the older versions, use + to concatenate the tuples:\nreturn (1, 2) + tuple(b) + (3,)\n... | [
19,
4
] | [] | [] | [
"python",
"return",
"tuples",
"unpack"
] | stackoverflow_0037732050_python_return_tuples_unpack.txt |
Q:
Can I make conda solve this environment faster?
I am using geopandas in a module that is run through GitLab CI... and the environment solving step takes forever. Like, around 30 minutes of solving for 2 minutes of running the job.
At each CI job
a container with the ad hoc image is started
a conda environment is ... | Can I make conda solve this environment faster? | I am using geopandas in a module that is run through GitLab CI... and the environment solving step takes forever. Like, around 30 minutes of solving for 2 minutes of running the job.
At each CI job
a container with the ad hoc image is started
a conda environment is created with the dependencies needed for the package
... | [
"There are a few paths to solve this. What you could do is have the CI pipeline run 3 steps\n\nstep a: load custom image and install dependencies\nstep b: create a new image with the new dependencies\nstep c: run your tests\n\nAs long as step b and c run in parallel, the image creation won't hinder your tests, and ... | [
1,
1,
0
] | [] | [] | [
"conda",
"geopandas",
"python"
] | stackoverflow_0071393065_conda_geopandas_python.txt |
Q:
Spliting nested date lists in DF columns and calculate AVG hour
Lets say i have this DF
ID
date_time
1
2020-03-13 21:10:56, 2020-06-02 22:18:06, 2020-04-14 22:10:56, 2021-06-02 22:18:06
2
2010-09-13 21:43:09, 2011-05-04 23:08:15,2012-06-04 23:08:16
3
2013-06-14 23:29:17, 2014-08-13 23:20:22,2014-08-13 23:20:22... | Spliting nested date lists in DF columns and calculate AVG hour | Lets say i have this DF
ID
date_time
1
2020-03-13 21:10:56, 2020-06-02 22:18:06, 2020-04-14 22:10:56, 2021-06-02 22:18:06
2
2010-09-13 21:43:09, 2011-05-04 23:08:15,2012-06-04 23:08:16
3
2013-06-14 23:29:17, 2014-08-13 23:20:22,2014-08-13 23:20:22
I want to remove YYYYMMDD string at the first position a... | [
"here is one way to do it\n# Split on comma, convert each value to date time and then to time delta\n# take the total seconds and convert to hours\n# np.mean to take average and then round the result\n\ndf['Avg_hour']=df['date_time'].str.split(',').apply(lambda x: round(np.mean([ pd.to_timedelta((pd.to_datetime(i))... | [
1
] | [] | [] | [
"dataframe",
"json",
"numpy",
"pandas",
"python"
] | stackoverflow_0074317877_dataframe_json_numpy_pandas_python.txt |
Q:
How to count number of times we can halve a number until it reaches 1?
I want to have a number that halves until it reaches 1, then it should return a count of how many times it halved.
example:
halve(4)
2
halve(11)
3
since 4/2 = 2 and 2/2= 1, hence it halved twice before reaching 1, and this is what I want it to ... | How to count number of times we can halve a number until it reaches 1? | I want to have a number that halves until it reaches 1, then it should return a count of how many times it halved.
example:
halve(4)
2
halve(11)
3
since 4/2 = 2 and 2/2= 1, hence it halved twice before reaching 1, and this is what I want it to return but my code isn't working, why? Can a modification be made ?
Here's m... | [
"It seems to me you can employ some math and just write:\nimport math\n\ndef halve(n):\n return math.floor(math.log(n, 2))\n\nYou attempt is wrong for three reasons.\n\nYou are returning from within the loop. Thus it will never execute more than once.\nYour loop will never execute unless n is 0 because range needs... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074318501_python.txt |
Q:
How to ignore deprecation warnings in Python
I keep getting this :
DeprecationWarning: integer argument expected, got float
How do I make this message go away? Is there a way to avoid warnings in Python?
A:
You should just fix your code but just in case,
import warnings
warnings.filterwarnings("ignore", categor... | How to ignore deprecation warnings in Python | I keep getting this :
DeprecationWarning: integer argument expected, got float
How do I make this message go away? Is there a way to avoid warnings in Python?
| [
"You should just fix your code but just in case,\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning) \n\n",
"I had these:\n/home/eddyp/virtualenv/lib/python2.6/site-packages/Twisted-8.2.0-py2.6-linux-x86_64.egg/twisted/persisted/sob.py:12:\nDeprecationWarning: the md5 module is depr... | [
278,
220,
142,
52,
32,
10,
7,
5,
4,
4,
3,
2,
1,
0,
0
] | [
"Not to beat you up about it but you are being warned that what you are doing will likely stop working when you next upgrade python. Convert to int and be done with it.\nBTW. You can also write your own warnings handler. Just assign a function that does nothing.\nHow to redirect python warnings to a custom stream?\... | [
-3,
-9
] | [
"deprecated",
"python",
"warnings"
] | stackoverflow_0000879173_deprecated_python_warnings.txt |
Q:
debug Flask server inside Jupyter Notebook
I want to debug small flask server inside jupyter notebook for demo.
I created virtualenv on latest Ubuntu and Python2 (on Mac with Python3 this error occurs as well), pip install flask jupyter.
However, when I create a cell with helloworld script it does not run inside n... | debug Flask server inside Jupyter Notebook | I want to debug small flask server inside jupyter notebook for demo.
I created virtualenv on latest Ubuntu and Python2 (on Mac with Python3 this error occurs as well), pip install flask jupyter.
However, when I create a cell with helloworld script it does not run inside notebook.
from flask import Flask
app = Flask(__... | [
"I installed Jupyter and Flask and your original code works.\n\nThe flask.Flask object is a WSGI application, not a server. Flask uses Werkzeug's development server as a WSGI server when you call python -m flask run in your shell. It creates a new WSGI server and then passes your app as paremeter to werkzeug.servin... | [
25,
3,
0
] | [] | [] | [
"flask",
"jupyter_notebook",
"python"
] | stackoverflow_0041831929_flask_jupyter_notebook_python.txt |
Q:
pytz.timezone error converting because of change in when chile change the hour
I am using the pytz python library.
It usually converts well from "America/Santiago" to "UTC.
The problem is that usually chile change its hour on the first saturday of september but this year it does it on the second saturday of septem... | pytz.timezone error converting because of change in when chile change the hour | I am using the pytz python library.
It usually converts well from "America/Santiago" to "UTC.
The problem is that usually chile change its hour on the first saturday of september but this year it does it on the second saturday of september because there were elections.
The problem is that the pytz library did not under... | [
"You likely need to update pytz to use the latest version.\nCheck out their changelog here: https://github.com/stub42/pytz/blob/master/tz/NEWS#L174 - it looks like in August they updated the library to support this change in Chile's daylight savings.\n"
] | [
3
] | [] | [] | [
"python",
"pytz",
"timezone",
"utc"
] | stackoverflow_0074318689_python_pytz_timezone_utc.txt |
Q:
Cannot set side_effect on a mocked method
I'm trying to write a test for a function that uses a class as a dependency and calls this class method(s).
Let's assume the function is
def store_username_and_password(**kwargs) -> Tuple[str, StorageResult]:
storage = MyDependency(param1, param2)
try:
stor... | Cannot set side_effect on a mocked method | I'm trying to write a test for a function that uses a class as a dependency and calls this class method(s).
Let's assume the function is
def store_username_and_password(**kwargs) -> Tuple[str, StorageResult]:
storage = MyDependency(param1, param2)
try:
storage.read_data(mountpoint, path)
except Inva... | [
"Anthony's comment helped me but I thought I'd add an explanation...\nmock_storage.read_data.side_effect will work, but only if you call MyDependency.read_data(). What happens is the call to MyDependency(param1, param2) creates a new MagicMock that doesn't have the side_effect set on it. The new mock can be acces... | [
1
] | [] | [] | [
"mocking",
"monkeypatching",
"pytest",
"python"
] | stackoverflow_0068693796_mocking_monkeypatching_pytest_python.txt |
Q:
Extract data using nth-child / css_selector in selenium with python
I am fairly new to python and selenium and am trying to extract data from https://crypto.com/price/bitcoin, in particular the market cap and 24H volume. The HTML for the market cap ($395.33) and 24H volume ($47.03 B) are below.
<div id="__next">
... | Extract data using nth-child / css_selector in selenium with python | I am fairly new to python and selenium and am trying to extract data from https://crypto.com/price/bitcoin, in particular the market cap and 24H volume. The HTML for the market cap ($395.33) and 24H volume ($47.03 B) are below.
<div id="__next">
<style>...</style>
<nopscript>...</noscript>
<div class="css-b14fde"... | [
"To get the 'Market Cap (USD)' value, use the below css locator:\n\".css-1y4us2f div:nth-of-type(1) p\"\n\nTo get the '24H VOLUME (USD)' value, use the below css locator:\n\".css-1y4us2f div:nth-of-type(2) p\"\n\n"
] | [
1
] | [] | [] | [
"css_selectors",
"html",
"python",
"selenium"
] | stackoverflow_0074316128_css_selectors_html_python_selenium.txt |
Q:
Pyinotify / Watchdog triggers a modify event twice on one edit
I am trying to start a python script everytime is a certain file modified. To be accurate, I have a device on Raspberry Pi's serial ports which writes data into a text file (test.txt) . I have tried both tools - Watchdog / Pyinotify. Everytime the file... | Pyinotify / Watchdog triggers a modify event twice on one edit | I am trying to start a python script everytime is a certain file modified. To be accurate, I have a device on Raspberry Pi's serial ports which writes data into a text file (test.txt) . I have tried both tools - Watchdog / Pyinotify. Everytime the file is modified (triggers event Watchdog: on_modified / Pyinotify: IN_M... | [
"I was facing the same issue while using pyinotify. But changing IN_MODIFY to IN_CLOSE_WRITE solved the issue. You can get more info from this answer\n",
"This probably because of the text editor which was used for editing your source code.\nsolution: calculate the time between 2 events, for example, If the event... | [
1,
0,
0
] | [] | [] | [
"pyinotify",
"python",
"watchdog"
] | stackoverflow_0037768601_pyinotify_python_watchdog.txt |
Q:
How delete files with condition: files created in "yyyy-mm-dd" at "yyyy-mm-dd" in python?
I wanna deleted files in directory, but necessarily created in X date at Y date.
I think used the library os but idk how to specify a date condition.
import os
import pandas as pd
path = 'directory'
dir = os.listdir(path)
f... | How delete files with condition: files created in "yyyy-mm-dd" at "yyyy-mm-dd" in python? | I wanna deleted files in directory, but necessarily created in X date at Y date.
I think used the library os but idk how to specify a date condition.
import os
import pandas as pd
path = 'directory'
dir = os.listdir(path)
for file in dir:
if file ... in dir:
os.remove(file)
| [
"You can get the last accessed time with os.path.getatime('/path/to/your/file'). Also, last modification time (os.path.getmtime) and creation time (os.path.getctime). More on those here. But these are in UNIX epoch format. So you should first convert the time you want to UNIX epoch format with the following command... | [
0
] | [] | [] | [
"date",
"delete_file",
"file",
"operating_system",
"python"
] | stackoverflow_0074318142_date_delete_file_file_operating_system_python.txt |
Q:
Merge First Row with the second row of column C if columns A & B are null only
Need to Merge the second row values with the first row of column C if the rows in columns A&B are null only. If the continuous 2rows are not null then skip it
DATA:
A B C
12525 1FWE23 1H654D
14654 ... | Merge First Row with the second row of column C if columns A & B are null only | Need to Merge the second row values with the first row of column C if the rows in columns A&B are null only. If the continuous 2rows are not null then skip it
DATA:
A B C
12525 1FWE23 1H654D
14654
24798 14654 S56E82
65116 63546 38945
46456 46485 R... | [
"Assumption: the empty values under A and B are null\nand A & B are unique\n\n# ffill the null values\n# groupby and aggregate\n\nout=df.ffill().groupby(['A','B'], as_index=False)['C'].agg(' '.join)\nout\n\n A B C\n0 12525 1FWE23 1H654D 14654\n1 24798 14654 S56E82\n2 46456 46485 R68R... | [
0
] | [] | [] | [
"dataframe",
"python"
] | stackoverflow_0074318537_dataframe_python.txt |
Q:
Merge multiple excel files via python while keeping VBA and the Sheet structure intact
I have multiple xlsm Excel files I want to combine. All of them have multiple sheets and formulas and VBA Code. I want to merge all of those files into one big excel sheet, where I keep all of the sheets with all of the vba code... | Merge multiple excel files via python while keeping VBA and the Sheet structure intact | I have multiple xlsm Excel files I want to combine. All of them have multiple sheets and formulas and VBA Code. I want to merge all of those files into one big excel sheet, where I keep all of the sheets with all of the vba code and the excel formulas. All of this I want to do in python.
I tried to google some solution... | [
"I came across this a while back, and saved it for sometime in the future.\nimport pandas as pd\nimport numpy as np\n\nimport glob\nglob.glob(\"C:\\\\Merge Multiple Excel Files Into One File\\\\*.xlsx\")\n\nall_data = pd.DataFrame()\nfor f in glob.glob(\"C:\\\\Merge Multiple Excel Files Into One File\\\\*.xlsx\"):\... | [
0
] | [] | [] | [
"excel",
"openpyxl",
"python",
"vba",
"xlwings"
] | stackoverflow_0074314208_excel_openpyxl_python_vba_xlwings.txt |
Q:
How to run custom code in IntEnum class body
I'm trying to generate the values that will go into a custom enum instead of using literals:
from enum import IntEnum
class Test(IntEnum):
for i in range(3):
locals()['ABC'[i]] = i
del i
My desired output is three attributes, named A, B, C, with values... | How to run custom code in IntEnum class body | I'm trying to generate the values that will go into a custom enum instead of using literals:
from enum import IntEnum
class Test(IntEnum):
for i in range(3):
locals()['ABC'[i]] = i
del i
My desired output is three attributes, named A, B, C, with values 0, 1, 2, respectively. This is based on two expec... | [
"First, an explanation of what is happening. Before executing the class body, the metaclass's __prepare__ method is used to create the namespace. Normally, this is just a dict. However, enum.EnumType uses a enum._EnumDict class, which specifically prevents duplicate names from being added to the namespace. While th... | [
2
] | [] | [] | [
"enums",
"python"
] | stackoverflow_0074317892_enums_python.txt |
Q:
view.showMaximised() not working in PyQt5
I am making a web browser using PyQt5. I am using the following code:
import PyQt5
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtWebKitWidgets import QWebView , QWebPage
from PyQt5.QtWebKit import QWebSettings
from PyQt5.QtNet... | view.showMaximised() not working in PyQt5 | I am making a web browser using PyQt5. I am using the following code:
import PyQt5
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtWebKitWidgets import QWebView , QWebPage
from PyQt5.QtWebKit import QWebSettings
from PyQt5.QtNetwork import *
import sys
from optparse import O... | [
"In case you want fullscreen, you have to use:\nclass Browser(QWebView):\n def __init__(self):\n # QWebView\n self.view = QWebView.__init__(self)\n #self.view.setPage(MyBrowser())\n self.setWindowTitle('Loading...')\n self.titleChanged.connect(self.adjustTitle)\n self.sh... | [
3,
0,
0
] | [] | [] | [
"pyqt",
"pyqt5",
"python",
"python_3.x"
] | stackoverflow_0057505915_pyqt_pyqt5_python_python_3.x.txt |
Q:
Python: How to sort elements of a set in column value
I have a pandas dataframe, in which one of the column (status) has set as a value.
box_name scheduled_time status
0 FIN_D1_BATCH_JOB 21:00:00 {'NOT_STAR... | Python: How to sort elements of a set in column value | I have a pandas dataframe, in which one of the column (status) has set as a value.
box_name scheduled_time status
0 FIN_D1_BATCH_JOB 21:00:00 {'NOT_STARTED'}
1 FIN_CREDIT_BATCH_PHIL_JOB 01:10:00 ... | [
"Set is an unordered kind of collection.\ndf[\"status\"] = df[\"status\"].apply(lambda x: sorted(list(x)))\n\n"
] | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074318806_pandas_python.txt |
Q:
Matplotlib plots not showing up in Mac OSX?
I am running Mac OSX 10.5.8. I installed matplotlib using macports. I get some examples from the matplotlib gallery like this one, without modification:
http://matplotlib.sourceforge.net/examples/api/unicode_minus.html
I run it, get no error, but the picture does not sho... | Matplotlib plots not showing up in Mac OSX? | I am running Mac OSX 10.5.8. I installed matplotlib using macports. I get some examples from the matplotlib gallery like this one, without modification:
http://matplotlib.sourceforge.net/examples/api/unicode_minus.html
I run it, get no error, but the picture does not show up. In Linux Ubuntu I get it.
Do you know what ... | [
"I had the same problem, even I could see how a new application window was created and immediately disappeared.\nSimple solution - just check if you have\n# Assumes you have imported \"matplotlib.pyplot\" as \"plt\"\nplt.show()\n\nafter the plot\n",
"I can verify this on my end as well. To fix, here's what I did\... | [
145,
50,
48,
12,
7,
4,
3,
3,
2,
2,
0,
0,
0,
0
] | [] | [] | [
"macos",
"matplotlib",
"plot",
"python"
] | stackoverflow_0002512225_macos_matplotlib_plot_python.txt |
Q:
Installing private GitHub repositories on DataBricks
I'm running Python wheels on Azure Databricks job. One of the wheel imports private repository from GitHub. Installation of wheel on Databricks cluster fails, as there is no SSH on Databricks.
What is the most elegant way of providing Databricks environment with... | Installing private GitHub repositories on DataBricks | I'm running Python wheels on Azure Databricks job. One of the wheel imports private repository from GitHub. Installation of wheel on Databricks cluster fails, as there is no SSH on Databricks.
What is the most elegant way of providing Databricks environment with SSH private Key?
| [
"Here the sample procedure of installation of Git repo on databricks.\nUse a tool like pip to install wheels. Leave it to the tool to discover and download the file if this is for a project hosted on PyPI.\npip install wheel\n\n\nYou can then tell pip to install the project (and it'll download the wheel if availa... | [
1
] | [] | [] | [
"azure_databricks",
"python",
"python_wheel",
"ssh_keys"
] | stackoverflow_0074184160_azure_databricks_python_python_wheel_ssh_keys.txt |
Q:
DataFrame returns empty after .update()
I am trying to create a new DataFrame which contains a calculation from an original DF.
To that purpose, I run a for loop with the calc for each column, but I am still getting the empty original DF and I don't see where is the source of the error.
May I ask for some help her... | DataFrame returns empty after .update() | I am trying to create a new DataFrame which contains a calculation from an original DF.
To that purpose, I run a for loop with the calc for each column, but I am still getting the empty original DF and I don't see where is the source of the error.
May I ask for some help here?
import yfinance as yf
import pandas as pd
... | [
"I think this is what you are looking to do:\nimport yfinance as yf\nimport pandas as pd\n\ndf = yf.download([\"YPFD.BA\", \"GGAL.BA\"], period='6mo')\n \ndf2 = pd.DataFrame()\n\nfor i in [\"YPFD.BA\", \"GGAL.BA\"]:\n df2[i] = df[\"Volume\"][i] * df[\"Close\"][i]\n\ndf2\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"yfinance"
] | stackoverflow_0074318466_dataframe_pandas_python_yfinance.txt |
Q:
Using python inside of Nuke to close Nuke
so I'm working in a project that requires running several things one after the other.
I'm stuck at the moment because I've managed through python (outside of Nuke) to open Nuke, load a file, run a script to update and render what I need, and now I need Nuke to save and clo... | Using python inside of Nuke to close Nuke | so I'm working in a project that requires running several things one after the other.
I'm stuck at the moment because I've managed through python (outside of Nuke) to open Nuke, load a file, run a script to update and render what I need, and now I need Nuke to save and close so the process can be marked as completed. H... | [
"I found the solution. Thanks\nnuke.scriptExit()\n"
] | [
1
] | [] | [] | [
"nuke",
"python"
] | stackoverflow_0074315319_nuke_python.txt |
Q:
tkinter movement object by mouse
I’m trying to get the object to move in the direction of the mouse, but I’m not out of line, but I must have written something wrong.
from tkinter import *
def MouseMove(event):
x1, y1, x2, y2 = canvas.bbox(square)
canvas.move(square, event.x - x2, event.y - y2)
window =... | tkinter movement object by mouse | I’m trying to get the object to move in the direction of the mouse, but I’m not out of line, but I must have written something wrong.
from tkinter import *
def MouseMove(event):
x1, y1, x2, y2 = canvas.bbox(square)
canvas.move(square, event.x - x2, event.y - y2)
window = Tk()
window.geometry('800x600')
can... | [
"Тему можно закрывать, сам решил. Спасибо за намек relent95\nfrom tkinter import *\n\ndef MouseMove(event):\n x1,y1,x2,y2 = canvas.bbox(square)\n c_x = x1+((x2-x1)/2)+200\n c_y = y1+((y2-y1)/2)+50\n pos_x = event.x\n pos_y = event.y\n if c_x != event.x and c_y != event.y:\n i=0\n j=0... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074313213_python_tkinter.txt |
Q:
Sort objects by a substring of a model field in django
Im trying to find best solution to sort through all Machine objects in my db and find last deviceSerialNo used.
deviceSerialNo is a character field and has a structure like this: AB12-12344.
My task is to sort all Machine objects by a substring of deviceSeria... | Sort objects by a substring of a model field in django | Im trying to find best solution to sort through all Machine objects in my db and find last deviceSerialNo used.
deviceSerialNo is a character field and has a structure like this: AB12-12344.
My task is to sort all Machine objects by a substring of deviceSerialNo field(everything after '-' in deviceSerialNo.
My current... | [
"You can order by a field created with annotate:\nfrom django.db.models import IntegerField, Value as V\nfrom django.db.models.functions import Cast, StrIndex, Substr\n\nlast = (\n Machine.objects.annotate(\n part=Cast(Substr(\"deviceSerialNo\", StrIndex(\"deviceSerialNo\", V(\"-\"))), IntegerField())\n ... | [
7,
0,
0
] | [] | [] | [
"django",
"django_queryset",
"python"
] | stackoverflow_0055062939_django_django_queryset_python.txt |
Q:
Filtering a dataframe and isin worked but double-equals did not, why?
So I have two DataFrames, one called dates that contains "Observation dates" with the data type DateTime. The other being a DataFrame of hourly weather observations called metar.
This is what dates looks like:
In[6]: dates.head()
Out[6]:
Ob... | Filtering a dataframe and isin worked but double-equals did not, why? | So I have two DataFrames, one called dates that contains "Observation dates" with the data type DateTime. The other being a DataFrame of hourly weather observations called metar.
This is what dates looks like:
In[6]: dates.head()
Out[6]:
ObservationDate
0 2021-09-11
1 2021-09-10
2 2021-09-05
3 2021-09-04
4... | [
"In the example using isin, you are looking for all of the values of metar['valid'] that exist anywhere in dates['ObservationDate] (with the supplied formatting). That makes sense.\nIn the example using == you are looking for a all values in metar['valid'] that are equivalent to the whole series dates['ObservationD... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074318874_dataframe_pandas_python.txt |
Q:
How do you achieve in Selenium what you achieve with BeautifulSoup's prettify()?
You can run .prettify() method on BeautifulSoup object to get a full, formated version of your fetched HTML.
I realized that Selenium doesn't have this particular method or anything similarly worded method.
How do you print a prittifi... | How do you achieve in Selenium what you achieve with BeautifulSoup's prettify()? | You can run .prettify() method on BeautifulSoup object to get a full, formated version of your fetched HTML.
I realized that Selenium doesn't have this particular method or anything similarly worded method.
How do you print a prittified version of your HTML for debugging purposes in Selenium?
| [
"Use browser.page_source.\nFor example:\nfrom selenium import webdriver\nimport time\n\nbrowser=webdriver.Firefox()\nbrowser.get(\"https://en.wikipedia.org\")\nhtml = browser.page_source\ntime.sleep(2)\nprint(html)\n\nbrowser.close()\n\nBut... to beautify it you'd still need e.g. BeautifulSoup as selenium doesn't h... | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"selenium"
] | stackoverflow_0074317688_beautifulsoup_python_selenium.txt |
Q:
Django create an object that has a reference to another object using serializers
I want to create an order that has multiple ads and each ad must have a reference to a display object. I did this kind of thing previously just by setting the object's id in the put method and it worked well.
models.py
class OrdersDj(... | Django create an object that has a reference to another object using serializers | I want to create an order that has multiple ads and each ad must have a reference to a display object. I did this kind of thing previously just by setting the object's id in the put method and it worked well.
models.py
class OrdersDj(models.Model):
id = models.CharField(primary_key=True, max_length=32, default=gene... | [
"Hopefully it is been solved.\nAdSerializer has a nested DisplaySerializer that is why it expects the input to be display data(all mandatory attributes on the Display model).\nBy declaring a nested DisplaySerializer you are announcing that it expects data to create Display object and won't be using an existing Disp... | [
1
] | [] | [] | [
"django",
"django_rest_framework",
"django_serializer",
"python",
"serialization"
] | stackoverflow_0070124273_django_django_rest_framework_django_serializer_python_serialization.txt |
Q:
Search in List of dict Python
I have a list with some dicts inside. The list looks like this:
files = [
{'name': "text.txt", 'size': 10, 'location': "cloud", 'info': "Nothing"},
{'name': "img.jpg", 'size': 200, 'location': "local", 'info': "private"},
{'name': "cars.txt", 'size': 109, 'location': "cloud", 'info': ... | Search in List of dict Python | I have a list with some dicts inside. The list looks like this:
files = [
{'name': "text.txt", 'size': 10, 'location': "cloud", 'info': "Nothing"},
{'name': "img.jpg", 'size': 200, 'location': "local", 'info': "private"},
{'name': "cars.txt", 'size': 109, 'location': "cloud", 'info': "private"}
]
I also have a folder ... | [
"One of the way will be this\nlist(filter(lambda x: x[\"location\"]==\"cloud\" and x[\"info\"]==\"Nothing\",files))\n# [{'name': 'text.txt', 'size': 10, 'location': 'cloud', 'info': 'Nothing'}]\n\nIf you just want the names:\nlist(map(lambda x: x[\"name\"], filter(lambda x: x[\"location\"]==\"cloud\" and x[\"info\"... | [
3,
1,
1
] | [] | [] | [
"dictionary",
"list",
"python",
"sorting"
] | stackoverflow_0074316939_dictionary_list_python_sorting.txt |
Q:
How to get the gloss given sense key using Nltk WordNet?
I got a set of sense key such as "long%3:00:02::" from SemCor+OMSTI. How can I get the glosses? Is there a map file? Or using Nltk WordNet?
A:
TL;DR
import re
from nltk.corpus import wordnet as wn
sense_key_regex = r"(.*)\%(.*):(.*):(.*):(.*):(.*)"
synset... | How to get the gloss given sense key using Nltk WordNet? | I got a set of sense key such as "long%3:00:02::" from SemCor+OMSTI. How can I get the glosses? Is there a map file? Or using Nltk WordNet?
| [
"TL;DR\nimport re\nfrom nltk.corpus import wordnet as wn\n\nsense_key_regex = r\"(.*)\\%(.*):(.*):(.*):(.*):(.*)\"\nsynset_types = {1:'n', 2:'v', 3:'a', 4:'r', 5:'s'}\n\ndef synset_from_sense_key(sense_key):\n lemma, ss_type, lex_num, lex_id, head_word, head_id = re.match(sense_key_regex, sense_key).groups()\n ... | [
4,
0,
0
] | [] | [] | [
"nltk",
"python",
"wordnet"
] | stackoverflow_0048170666_nltk_python_wordnet.txt |
Q:
Multiply part of a dataframe by a series conditionally
I have a dataframe containing hard (USD) and soft currency (non-USD) financial data, and a dataframe containing exchange rate time series. I want to convert everything in USD.
EDIT: removed the DATES field for more clarity. Also, notice that 43646, etc. are da... | Multiply part of a dataframe by a series conditionally | I have a dataframe containing hard (USD) and soft currency (non-USD) financial data, and a dataframe containing exchange rate time series. I want to convert everything in USD.
EDIT: removed the DATES field for more clarity. Also, notice that 43646, etc. are dates.
TimeSerieLCY = pd.DataFrame({'ISIN':['ISIN1', 'ISIN2', ... | [
"I think this solves your problem\n# First, rename the columns of FXRatesSeries dataframes. \nFXRatesSeries.columns = ['FX', 'DATES', '43646_rate', '43676_rate', '43707_rate']\n# The column \"FX\" and \"DATES\" will be the keys to merge the two dataframes (left join to have for each column the rate associated depen... | [
2
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074318741_pandas_python.txt |
Q:
Python Selenium, edge browser, I dont see Inspect Element on every element
I am trying to get data from a Power Bi table. There are some elements that appear when hovering over a table. When I right click on ... I don't see Inspect Element. However, when I left click on this element, I can see a menu, and if I rig... | Python Selenium, edge browser, I dont see Inspect Element on every element |
I am trying to get data from a Power Bi table. There are some elements that appear when hovering over a table. When I right click on ... I don't see Inspect Element. However, when I left click on this element, I can see a menu, and if I right click on any items, I can see Inspect element.
My first question, is why I d... | [
"1.1 why I don't see Inspect Element in the right click menu for all elements:\nPowerBi has its own context menu so they suppress the browsers context menu. If the element is tricky to find the dev tools, you can press Ctrl + Shift + C (while dev tools is open) and then click the desired element. Your mouse needs t... | [
3,
1
] | [] | [] | [
"html",
"powerbi",
"python",
"selenium",
"windows"
] | stackoverflow_0074200390_html_powerbi_python_selenium_windows.txt |
Q:
Encode/ decode exercise
I am doing a encode/ decode exercise where I have list which is every letter of the alphabet. I prepared a function where I want to shift letters of a word. For example if I chose "hello" and I shift by 1 position I get "ifmmp"
My question comes when I am out of the alphabet. For example If... | Encode/ decode exercise | I am doing a encode/ decode exercise where I have list which is every letter of the alphabet. I prepared a function where I want to shift letters of a word. For example if I chose "hello" and I shift by 1 position I get "ifmmp"
My question comes when I am out of the alphabet. For example If I chose "xyz" and shift by 3... | [
"You can use a deque for this and skip worrying about clamping your indexes. Actually, with this method you don't have to worry about indexes, at all. It's all built-in to key. Let's say you wanted to encode \"abc\". key is going to give you 0,1,2, but when the deque has been rotated, the values at 0,1,2 will no lo... | [
3
] | [] | [] | [
"encode",
"python"
] | stackoverflow_0074318835_encode_python.txt |
Q:
How does the pandas Compare function work?
Can someone explain the detailed implementation of the Pandas Compare() function that compares two dataframes?
Code Implementation:
def compare(
self,
other,
align_axis: Axis = 1,
keep_shape: bool_t = False,
keep_equal: bool_t = Fal... | How does the pandas Compare function work? | Can someone explain the detailed implementation of the Pandas Compare() function that compares two dataframes?
Code Implementation:
def compare(
self,
other,
align_axis: Axis = 1,
keep_shape: bool_t = False,
keep_equal: bool_t = False,
):
from pandas.core.reshape.conc... | [
"If you haven't read the documentation yet, I'd start there.\nTo hopefully shed some light on the high-level use, we can use some examples.\ne.g. 1 -- All the same\nimport numpy as np # 1.23.3\nimport pandas as pd # 1.5.1\n\nnp.random.seed(0)\n\ns0 = pd.Series(np.random.random(size=(5)))\ns1 = s0.copy()\n\nprint(... | [
0
] | [] | [] | [
"comparison",
"dataframe",
"pandas",
"python"
] | stackoverflow_0072861634_comparison_dataframe_pandas_python.txt |
Q:
Pandas: Convert Timestamp to datetime.date
I have a pandas column of Timestamp data
In [27]: train["Original_Quote_Date"][6]
Out[27]: Timestamp('2013-12-25 00:00:00')
How can check equivalence of these objects to datetime.date objects of the type
datetime.date(2013, 12, 25)
A:
Use the .date method:
In [11]: t ... | Pandas: Convert Timestamp to datetime.date | I have a pandas column of Timestamp data
In [27]: train["Original_Quote_Date"][6]
Out[27]: Timestamp('2013-12-25 00:00:00')
How can check equivalence of these objects to datetime.date objects of the type
datetime.date(2013, 12, 25)
| [
"Use the .date method:\nIn [11]: t = pd.Timestamp('2013-12-25 00:00:00')\n\nIn [12]: t.date()\nOut[12]: datetime.date(2013, 12, 25)\n\nIn [13]: t.date() == datetime.date(2013, 12, 25)\nOut[13]: True\n\n\nTo compare against a DatetimeIndex (i.e. an array of Timestamps), you'll want to do it the other way around:\nIn... | [
109,
28,
7,
6,
4,
2
] | [
"If I have a pandas DataFrame with timestamp column (1546300800000, 1546301100000, 1546301400000, 1546301700000, 1546302000000) and I want to convert this into date time format\nimport datetime\n\ndf['date'] = df['date'].apply(lambda x: datetime.datetime.fromtimestamp(x/1000.0))\n\nThis will return a column with th... | [
-1
] | [
"datetime",
"pandas",
"python",
"timestamp"
] | stackoverflow_0034386751_datetime_pandas_python_timestamp.txt |
Q:
Specify multiple pytest configurations
I'm using pytest to run some tests. Is there a way to specify multiple configurations through the pytest.ini?
The reason I need this is that when testing a locally running Lambda, I require some slightly different options than when running in CI pipeline.
For example, to chec... | Specify multiple pytest configurations | I'm using pytest to run some tests. Is there a way to specify multiple configurations through the pytest.ini?
The reason I need this is that when testing a locally running Lambda, I require some slightly different options than when running in CI pipeline.
For example, to check if tests are being run against a locally r... | [
"You can create two separate ini files, then pass them with the -c arg\n\n-c file\nLoad configuration from file instead of trying to locate one of the implicit configuration files\n\nFor example:\n\npytest -c lambda-pytest.ini\npytest -c ci-pytest.ini\n\n"
] | [
0
] | [] | [] | [
"pytest",
"python",
"python_3.8"
] | stackoverflow_0071515440_pytest_python_python_3.8.txt |
Q:
My game has a problem where it draws moves after 3 cliks
I'm trying to make a tic-tac-toe game in pygame but I have a problem where it will only draw the moves after 3 cliks. here's the code:
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUT... | My game has a problem where it draws moves after 3 cliks | I'm trying to make a tic-tac-toe game in pygame but I have a problem where it will only draw the moves after 3 cliks. here's the code:
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
x, y = pygame.mouse.get_pos()
... | [
"The problem is in the loops where you loop over all coordinates of the lists. The condition, while n < len(circle_cord_x) - 1, makes the loop end when n reaches len(circle_cord_x) - 1. However, this number is still the last index of the list. By consequence, the last element is skipped. This means that you will on... | [
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0074309476_pygame_python.txt |
Q:
convert time to UTC in pandas
I have multiple csv files, I've set DateTime as the index.
df6.set_index("gmtime", inplace=True)
#correct the underscores in old datetime format
df6.index = [" ".join( str(val).split("_")) for val in df6.index]
df6.index = pd.to_datetime(df6.index)
The time was put in GMT, but I thin... | convert time to UTC in pandas | I have multiple csv files, I've set DateTime as the index.
df6.set_index("gmtime", inplace=True)
#correct the underscores in old datetime format
df6.index = [" ".join( str(val).split("_")) for val in df6.index]
df6.index = pd.to_datetime(df6.index)
The time was put in GMT, but I think it's been saved as BST (British ... | [
"Given a column that contains date/time info as string, you would convert to datetime, localize to a time zone (here: Europe/London), then convert to UTC. You can do that before you set as index.\nEx:\nimport pandas as pd\n\ndti = pd.to_datetime([\"2021-09-01\"]).tz_localize(\"Europe/London\").tz_convert(\"UTC\")\n... | [
2,
2
] | [] | [] | [
"datetime",
"pandas",
"python",
"timestamp",
"utc"
] | stackoverflow_0069657464_datetime_pandas_python_timestamp_utc.txt |
Q:
Python group by row and string topics to create new columns with binary value
I have a large csv where each row is a separate school course, each of which is tagged with one or more topics, like so:
school name
department
course name
topics
A
A1
X
fruit; vegetable
A
A1
Y
fruit; grains
B
B1
Z
fruit; vegetable; ... | Python group by row and string topics to create new columns with binary value | I have a large csv where each row is a separate school course, each of which is tagged with one or more topics, like so:
school name
department
course name
topics
A
A1
X
fruit; vegetable
A
A1
Y
fruit; grains
B
B1
Z
fruit; vegetable; sweets
C
C1
XX
fruit; poultry
I need to calculate the presence of eac... | [
"# form a list by splitting the topics\ndf['topics']=df['topics'].str.split(';')\n\n# explode to turn list values into rows\ndf=df.explode('topics')\n\n# use get_dummies to get indicators for the value\n# and then groupby and sum\n\nout=(pd.concat([df , # merge the DF with \n ... | [
0
] | [] | [] | [
"concatenation",
"pandas",
"pivot_table",
"python"
] | stackoverflow_0074319141_concatenation_pandas_pivot_table_python.txt |
Q:
Convert a dataframe to an array
I have a dataframe like the following.
i
j
element
0
0
1
0
1
2
0
2
3
1
0
4
1
1
5
1
2
6
2
0
7
2
1
8
2
2
9
How can I convert it to the 3*3 array below?
1
2
3
4
5
6
7
8
9
A:
Assuming that the dataframe is called df, one can use pandas.DataFrame.pivot as follows, with .t... | Convert a dataframe to an array | I have a dataframe like the following.
i
j
element
0
0
1
0
1
2
0
2
3
1
0
4
1
1
5
1
2
6
2
0
7
2
1
8
2
2
9
How can I convert it to the 3*3 array below?
1
2
3
4
5
6
7
8
9
| [
"Assuming that the dataframe is called df, one can use pandas.DataFrame.pivot as follows, with .to_numpy() (recommended) or .values as follows\narray = df.pivot(index='i', columns='j', values='element').to_numpy()\n\n# or\n\narray = df.pivot(index='i', columns='j', values='element').values\n\n[Out]:\n\narray([[1, 2... | [
2,
0
] | [] | [] | [
"arrays",
"dataframe",
"numpy",
"pandas",
"python"
] | stackoverflow_0074319213_arrays_dataframe_numpy_pandas_python.txt |
Q:
sorting output order same as input string order
I have two strings, an input and an output, when it's passed to my required algorithm I get a qualified string as an output. But the order of words don't match with the input. How can I sort output order same as input order?
> def keyword_exctraction(self,new_text):
... | sorting output order same as input string order | I have two strings, an input and an output, when it's passed to my required algorithm I get a qualified string as an output. But the order of words don't match with the input. How can I sort output order same as input order?
> def keyword_exctraction(self,new_text):
> eng_stopwords = stopwords.words('english')
... | [
"This is the long version of my original comment:\nFirst, let me ignore the extraction details by just hardcoding that data here:\ntext = 'i want to buy samsung smart tv 32 inch'\nkeyword_extraction = [\n ('samsung', 0.587), \n ('tv', 0.3726), \n ('32', 0.3405), \n ('inch', 0.291), \n ('buy', 0.288),... | [
0
] | [] | [] | [
"nlp",
"python",
"sorting",
"string"
] | stackoverflow_0074302294_nlp_python_sorting_string.txt |
Q:
Insert Excel file data in Word document using Python-Docx?
I am working on some algorithm using Python-Docx Library to insert an excel file data in the word document. I will read that file from a location in my project and then will have to insert it as an Object to the word docx.
How do I achieve it? Is there an... | Insert Excel file data in Word document using Python-Docx? | I am working on some algorithm using Python-Docx Library to insert an excel file data in the word document. I will read that file from a location in my project and then will have to insert it as an Object to the word docx.
How do I achieve it? Is there any sample code snippet of doing this that I can make use of?
| [
"One way to do it is use pandas and python-docx libraries. Pandas to read the excel and then docx to write iteratively to docx file\nimport docx\nimport pandas as pd\n\ndf = pd.read_excel(\"test.xlsx\")\n\ndoc = docx.Document()\nt = doc.add_table(df.shape[0]+1, df.shape[1])\nfor j in range(df.shape[-1]):\n t.cell... | [
0
] | [] | [] | [
"python",
"python_docx"
] | stackoverflow_0049926444_python_python_docx.txt |
Q:
.ipynb file not displaying properly in GitHub
I've uploaded a .ipynb jupyter notebook in GitHub but it doesn't display the exact same output as I've written in jupyter notebook.
Here's the link to my repo: ipynb file
A:
You need to view the notebook as "rendered blob" not as "source blob". In GitHub, this is don... | .ipynb file not displaying properly in GitHub | I've uploaded a .ipynb jupyter notebook in GitHub but it doesn't display the exact same output as I've written in jupyter notebook.
Here's the link to my repo: ipynb file
| [
"You need to view the notebook as \"rendered blob\" not as \"source blob\". In GitHub, this is done by selecting the second rendering option in the top right:\n\n",
"It is mostly issue with Github backend. Try this way instead uploading directly\nGo to --> https://nbviewer.org/\nPaste your .ipynb github link here... | [
0,
0
] | [] | [] | [
"github",
"jupyter",
"jupyter_notebook",
"python",
"repository"
] | stackoverflow_0074319233_github_jupyter_jupyter_notebook_python_repository.txt |
Q:
How to convert this file-reading function into a class
I have this code:
username = str(input("Enter Username: "))
password = str(input("Enter Password: "))
def search_username(file_path, username, password):
usernameTruthValue = False
passwordTruthValue = False
with open(file_path, 'r') as file:
... | How to convert this file-reading function into a class | I have this code:
username = str(input("Enter Username: "))
password = str(input("Enter Password: "))
def search_username(file_path, username, password):
usernameTruthValue = False
passwordTruthValue = False
with open(file_path, 'r') as file:
# read all content of a file
content = file.read(... | [
"At the very core, you should probably read up on what a Class method looks like, specifically the inferred self reference:\nclass Login():\n def __init__(self, file_path, username, password):\n self.file_path = file_path\n self.username = username\n self.password = password\n\n def searc... | [
2
] | [] | [] | [
"authentication",
"class",
"python",
"python_class"
] | stackoverflow_0074319371_authentication_class_python_python_class.txt |
Q:
I want to get 2 points that have the closest distance to the value entered by the user
Hope you are doing well. Here is one problem needs your help.
I am working with some data on pandas.
I want to get 2 points that have the closest distance to the value entered by the user.
For example, if I input d=4, I want to... | I want to get 2 points that have the closest distance to the value entered by the user | Hope you are doing well. Here is one problem needs your help.
I am working with some data on pandas.
I want to get 2 points that have the closest distance to the value entered by the user.
For example, if I input d=4, I want to get the fastest way to output the result ((C:18 and F:14) or (B:3 and D:7)). The method I ... | [
"We could try with merge\ninput = 4 \nout = df.assign(key = df['Value']-input).merge(df.assign(key=df['Value']),on='key')\nOut[59]: \n Name_x Value_x key Name_y Value_y\n0 C 18 14 F 14\n1 D 7 3 B 3\n2 E 11 7 D 7\n\n",
"It's a bit com... | [
2,
1
] | [] | [] | [
"algorithm",
"dataframe",
"pandas",
"pyspark",
"python"
] | stackoverflow_0074311676_algorithm_dataframe_pandas_pyspark_python.txt |
Q:
Dictionary items are not being all stored as expected
I have a dictionary that is mapping one value to another value and it has multiple keys.
replace_dict={
"key1":
{"abc": "ABCDE", "XYZ": "WXYZ"},
"key2":
{"Alabama": "AL", "Alaska": "AK"}}
when I run the code
print(replace_dict.items())
... | Dictionary items are not being all stored as expected | I have a dictionary that is mapping one value to another value and it has multiple keys.
replace_dict={
"key1":
{"abc": "ABCDE", "XYZ": "WXYZ"},
"key2":
{"Alabama": "AL", "Alaska": "AK"}}
when I run the code
print(replace_dict.items())
the output is:
dict_items([('key1', {'abc': 'ABCDE', 'XYZ':... | [
"You can do the following formatting by using for loop in replace_dict.items()\nHere are the few formatting examples\nExample 1\nfor key, value in replace_dict.items():\n print(key)\n\nOutput:\nkey1\nkey2\n\nExample 2\nfor key, value in replace_dict.items():\n print(value)\n\nOutput:\n{'abc': 'ABCDE', 'XYZ': ... | [
0
] | [] | [] | [
"dictionary",
"pandas",
"python"
] | stackoverflow_0074319244_dictionary_pandas_python.txt |
Q:
How to get the vector representation of a polynomial in GF(2)[x]?
I tried to multiply two polynomials g(x), h(x) ∈ GF(2)[x]. And I got the result as c(x). I would like to get the vector representation of c(x).
Here is the code I am sharing.
import galois
GF = galois.GF(2)
g = galois.Poly([1, 0, 1, 1], field=GF)
h... | How to get the vector representation of a polynomial in GF(2)[x]? | I tried to multiply two polynomials g(x), h(x) ∈ GF(2)[x]. And I got the result as c(x). I would like to get the vector representation of c(x).
Here is the code I am sharing.
import galois
GF = galois.GF(2)
g = galois.Poly([1, 0, 1, 1], field=GF)
h = galois.Poly([1, 1, 0], field=GF)
c = g * h
print(c)
The output I am... | [
"Use c.coeffs. This gives:\nGF([1, 1, 1, 0, 1, 0], order=2)\n\nThis form may be satisfactory for whatever you are trying to do.\nIf not, you can (among other things) turn it into a normal Python list[int] with [int(i) for i in c.coeffs], yielding:\n[1, 1, 1, 0, 1, 0]\n\n"
] | [
1
] | [] | [] | [
"galois_field",
"polynomials",
"python",
"python_3.x",
"vector"
] | stackoverflow_0074319297_galois_field_polynomials_python_python_3.x_vector.txt |
Q:
Is there a way to check if elements in sub list are equall in any of the other sublists
So i have a list with 1000 sub-list where the sub-lists have a date in this format "2022-01-01" and an index to another list. So the list loks like this [["2022-01-01", 3], ["2010-01-01", 1], ["2022-01-01", 12]] with 1000 eleme... | Is there a way to check if elements in sub list are equall in any of the other sublists | So i have a list with 1000 sub-list where the sub-lists have a date in this format "2022-01-01" and an index to another list. So the list loks like this [["2022-01-01", 3], ["2010-01-01", 1], ["2022-01-01", 12]] with 1000 elements.
What i would like to get is a new list with sub-list that have the index of the dates th... | [
"You can use a defaultdict to create a data structure keyed by the dates and whose values are the indices where those dates occur. Once you create such a thing, you can iterate over its values, selecting the ones which have more than one entry:\nfrom collections import defaultdict\n\ndate_list = [[\"2022-01-01\", 3... | [
2
] | [] | [] | [
"list",
"python"
] | stackoverflow_0074319210_list_python.txt |
Q:
while replacing the input string spaces with underscore and then checking it it does not replaces
game=input("enter student name to update report card: ")
nn=game.replace(" ", "_")
mycursor.execute("show tables")
klm = mycursor.fetchall()
if (nn,) in klm:
b=int(input("enter sno: "))
... | while replacing the input string spaces with underscore and then checking it it does not replaces | game=input("enter student name to update report card: ")
nn=game.replace(" ", "_")
mycursor.execute("show tables")
klm = mycursor.fetchall()
if (nn,) in klm:
b=int(input("enter sno: "))
mycursor.execute("select * from {} where sno='{}'".format(nn,b))
xer=mycursor.fetchall()
... | [
"You are searching for the tuple (nn,) in your table names. Just try searching for the string itself like this:\nif nn in klm:\n\n",
"nn=game.replace(\" \", \"_\") has 2 spaces in your code\nTry with\nnn=game.replace(\" \", \"_\") has one space\ngame=input(\"enter student name to update report card: \")\nnn=gam... | [
0,
0
] | [] | [] | [
"python",
"python_3.x",
"replace"
] | stackoverflow_0074319342_python_python_3.x_replace.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.