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 the function doesn't sucsses to sort the list right?
I try to built a function that detact an anagrams is a list of word, and gave back a list of all the anagrams by their location in the first list.
for example:
input: ['deltas', 'retainers', 'desalt', 'pants', 'slated', 'generating', 'ternaries', 'smelters'... | Why the function doesn't sucsses to sort the list right? | I try to built a function that detact an anagrams is a list of word, and gave back a list of all the anagrams by their location in the first list.
for example:
input: ['deltas', 'retainers', 'desalt', 'pants', 'slated', 'generating', 'ternaries', 'smelters', 'termless', 'salted', 'staled', 'greatening', 'lasted', 'res... | [
"This was the problematic code:\n local_list = sorted(local_list)\n if sorted(local_list) in sorted(sorted_list_of_anagrams):\n\nBeing that sorted_list_of_anagrams is a list of lists when you sort it it doesn't sort every inner list individually only the outer list. This should work:\nif sorted(local_... | [
1
] | [] | [] | [
"python",
"python_2.7"
] | stackoverflow_0074534014_python_python_2.7.txt |
Q:
What is the reason of this error I'm getting when using tkinter for a math app
Im making a program that will do most of my homework. Im trying to add some ui and it gives errors in my code. Please tell what's wrong. Make it easy enough for a 13 year old to understand because I'm new to python. This gives an error ... | What is the reason of this error I'm getting when using tkinter for a math app | Im making a program that will do most of my homework. Im trying to add some ui and it gives errors in my code. Please tell what's wrong. Make it easy enough for a 13 year old to understand because I'm new to python. This gives an error only when i use canvas. If i use window, then it doesn't but i want to use canvas be... | [
"On line 19-21, I added float. Line 22, I removed float. Also for LABEL widget I I changed x, y location. in line 23, I also place LABEL below ENTRY\nHere is code:\nfrom tkinter import *\n\nroot=Tk()\nroot.title('Math')\n\ncanvas1 = Canvas(root, width = 400, height = 320)\ncanvas1.pack()\n\nentry1 = Entry (root) \... | [
1
] | [] | [] | [
"python",
"python_3.x",
"tkinter"
] | stackoverflow_0072149050_python_python_3.x_tkinter.txt |
Q:
Python bind Dataclass and TypedDict (Inherit Dataclass from TypedDict)
I want to bind somehow my TypedDict (which I'm using for database results type hints) and my Dataclass.
I'm not that it may be hard to implement and TypedDict is just a dict in run-time, but anyway.
Logically, in point of design and architectur... | Python bind Dataclass and TypedDict (Inherit Dataclass from TypedDict) | I want to bind somehow my TypedDict (which I'm using for database results type hints) and my Dataclass.
I'm not that it may be hard to implement and TypedDict is just a dict in run-time, but anyway.
Logically, in point of design and architecture, it sounds sensible, more consistent, and neat.
Well, the implementation s... | [
"A typing.TypedDict is something fundamentally different from a dataclass - to start, at runtime, it does absolutely nothing, and behaves just as a plain dictionary (but provide the metainformation used to create it).\nIt will accept unknown fields and not-valid types, it works only with the item getting [ ] synt... | [
1
] | [] | [] | [
"python",
"python_dataclasses",
"typeddict"
] | stackoverflow_0074507348_python_python_dataclasses_typeddict.txt |
Q:
Failed to install package python-ldap
I am installing package for odoo15 on windows 11, when i install python-ldap package 3.4.0, I am getting an error and I tried to upgrade pip to the latest version but I can't install it. Can anyone help me install ?
I tried very hard but I can't install ldap package on window... | Failed to install package python-ldap | I am installing package for odoo15 on windows 11, when i install python-ldap package 3.4.0, I am getting an error and I tried to upgrade pip to the latest version but I can't install it. Can anyone help me install ?
I tried very hard but I can't install ldap package on windows 11
| [
"As per python-ldap documentation, there is Unofficial package for Windows are available on Christoph Gohlke’s page.\nYou can download .whl package file for your python version and then install it as below:\n pip install path_to_downloaded_whl/file_name.whl\n"
] | [
0
] | [] | [] | [
"odoo_15",
"python"
] | stackoverflow_0074472077_odoo_15_python.txt |
Q:
How to sync slash command globally discord.py
I want to sync all slash commands with all guilds in discord.py
My code
import discord
from discord import app_commands
from discord.ext import commands
intents = discord.Intents.default()
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(clien... | How to sync slash command globally discord.py | I want to sync all slash commands with all guilds in discord.py
My code
import discord
from discord import app_commands
from discord.ext import commands
intents = discord.Intents.default()
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)
@client.event
async def on_ready():
... | [
"You shouldn't sync your commands in on_ready because it's unnecessary and can get you ratelimited. You should create a owner-only command to sync the command tree instead.\n@tree.command(name='sync', description='Owner only')\nasync def sync(interaction: discord.Interaction):\n if interaction.user.id == YOUR_ID... | [
0
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0074413367_discord.py_python.txt |
Q:
Run python script that interact word (pywin32) in the batch mode (Task Scheduler/Windows Service)
I have written a python script that takes RTF files that my system is creating and converting it in to DOCX format.
I accomplished this with pywin32 library. By this library I'm able to open Word and save as DOCX.
def... | Run python script that interact word (pywin32) in the batch mode (Task Scheduler/Windows Service) | I have written a python script that takes RTF files that my system is creating and converting it in to DOCX format.
I accomplished this with pywin32 library. By this library I'm able to open Word and save as DOCX.
def ConvertRtfToDocx(path, file):
word = win32com.client.Dispatch("Word.Application")
wdFormatDocu... | [
"Its turnout that the problem wasn't about the virtual display. The problem is that Microsoft does not allow use of Office applications in batch mode, by default. That why in 2008 they change the windows in the way that just logon regular users can make a use of Office and Office objects.\nBut there are a few ways ... | [
0
] | [] | [] | [
"batch_processing",
"ms_word",
"python",
"pywin32",
"windows_server_2012_r2"
] | stackoverflow_0074224332_batch_processing_ms_word_python_pywin32_windows_server_2012_r2.txt |
Q:
EKS/AKS cluster name convention
I am writing a script that receives a Kubernetes context name as an input and outputs the different elements of the cluster ->
class GKE:
def __init__(self, context):
s = context.split("_")
self.provider: str = s[0]
self.project: str = s[1]
self.d... | EKS/AKS cluster name convention | I am writing a script that receives a Kubernetes context name as an input and outputs the different elements of the cluster ->
class GKE:
def __init__(self, context):
s = context.split("_")
self.provider: str = s[0]
self.project: str = s[1]
self.data_center: GKE.DataCenter = GKE.Data... | [
"You need to differentiate between the correct name of the cluster and the naming schema of a resource.\nWhen I run kubectl config get-contexts on the clusters Aks, Eks, and Gke I get the following results:\nNAME AUTHINFO\ngke_project-1234_us-central1-c_myGKECluster ... | [
1
] | [] | [] | [
"amazon_eks",
"azure_aks",
"kubernetes",
"naming_conventions",
"python"
] | stackoverflow_0074516648_amazon_eks_azure_aks_kubernetes_naming_conventions_python.txt |
Q:
Idle3 editor fail to open in Fedora 36
I am currently unable to open Idle3 editor. I am running Linux Fedora 36, when idle3 command is issued I get this:
Traceback (most recent call last):
File "/usr/bin/idle3", line 3, in <module> from idlelib.pyshell import main
File "/usr/lib64/python3.10/idlelib/pyshell.py", l... | Idle3 editor fail to open in Fedora 36 | I am currently unable to open Idle3 editor. I am running Linux Fedora 36, when idle3 command is issued I get this:
Traceback (most recent call last):
File "/usr/bin/idle3", line 3, in <module> from idlelib.pyshell import main
File "/usr/lib64/python3.10/idlelib/pyshell.py", line 53, in <module> from idlelib import debu... | [
"Fortunatelly the trouble with Idle3 was solved in the recent update of Fedora 36, I think the missing file was inserted.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074526000_python.txt |
Q:
How to fit an image into a larger image? Python, pillow
I have an image that I want to fit into another bigger image, so the smaller image is as big as possible. Is there a possible way to do that? It's like resizing without deforming the ratio.
I have tried this code:
image = Image.open(input_path)
x, y = image.... | How to fit an image into a larger image? Python, pillow | I have an image that I want to fit into another bigger image, so the smaller image is as big as possible. Is there a possible way to do that? It's like resizing without deforming the ratio.
I have tried this code:
image = Image.open(input_path)
x, y = image.size
offset_x = math.floor((512 - x) / 2)
offset_y = math.ce... | [
"Ok, so the answer is the ImageOps.pad() function. I didn't know it existed, so yeah.\n"
] | [
0
] | [] | [] | [
"image",
"python",
"python_imaging_library"
] | stackoverflow_0074533695_image_python_python_imaging_library.txt |
Q:
RuntimeError: DataLoader worker (pid(s) 15876, 2756) exited unexpectedly
I am compiling some existing examples from the PyTorch tutorial website. I am working especially on the CPU device no GPU.
When running a program the type of error below is shown. Does it become I'm working on the CPU device or setup issue? r... | RuntimeError: DataLoader worker (pid(s) 15876, 2756) exited unexpectedly | I am compiling some existing examples from the PyTorch tutorial website. I am working especially on the CPU device no GPU.
When running a program the type of error below is shown. Does it become I'm working on the CPU device or setup issue? raise RuntimeError('DataLoader worker (pid(s) {}) exited unexpectedly'.format(p... | [
"set num_workers=0\nOn Windows, due to multiprocessing restrictions, setting num_workers to > 0 leads to errors. This is expected.\nThere is an issue on Github too:\n",
"You need to first figure out why the dataLoader worker crashed. A common reason is out of memory. You can check this by running dmesg -T after y... | [
2,
0,
0
] | [] | [] | [
"python",
"pytorch",
"pytorch_dataloader"
] | stackoverflow_0071713719_python_pytorch_pytorch_dataloader.txt |
Q:
How do I split a list into equally-sized chunks?
How do I split a list of arbitrary length into equal sized chunks?
See How to iterate over a list in chunks if the data result will be used directly for a loop, and does not need to be stored.
For the same question with a string input, see Split string every nth ch... | How do I split a list into equally-sized chunks? | How do I split a list of arbitrary length into equal sized chunks?
See How to iterate over a list in chunks if the data result will be used directly for a loop, and does not need to be stored.
For the same question with a string input, see Split string every nth character?. The same techniques generally apply, though ... | [
"Here's a generator that yields evenly-sized chunks:\ndef chunks(lst, n):\n \"\"\"Yield successive n-sized chunks from lst.\"\"\"\n for i in range(0, len(lst), n):\n yield lst[i:i + n]\n\nimport pprint\npprint.pprint(list(chunks(range(10, 75), 10)))\n[[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],\n [20, 21... | [
4228,
651,
389,
341,
284,
120,
85,
65,
64,
63,
56,
51,
40,
28,
26,
26,
23,
20,
19,
16,
13,
13,
13,
12,
11,
11,
8,
8,
7,
6,
6,
5,
5,
5,
5,
5,
5,
4,
4,
4,
4,
4,
4,
4,
3,
3,
3,
2,
2,
2,
2,
2,
1,
1,
1,
1,
1,
... | [
"Lazy loading version\n\nimport pprint\npprint.pprint(list(chunks(range(10, 75), 10)))\n[range(10, 20),\n range(20, 30),\n range(30, 40),\n range(40, 50),\n range(50, 60),\n range(60, 70),\n range(70, 75)]\n\n Confer this implementation's result with the example usage result of the accepted answer. \n\nMany of the ... | [
-1,
-1,
-1,
-1,
-1,
-1,
-2,
-2
] | [
"chunks",
"list",
"python",
"split"
] | stackoverflow_0000312443_chunks_list_python_split.txt |
Q:
Apply NumPy repeat only on elements that are contained in a secondary list
I'm trying to repeat certain elements within a list n-times and so far I've come to this solution:
_base = ["a", "z", "c", "c", "e"]
for bump_element in ["a", "b", "c"]:
_base = np.repeat(... | Apply NumPy repeat only on elements that are contained in a secondary list | I'm trying to repeat certain elements within a list n-times and so far I've come to this solution:
_base = ["a", "z", "c", "c", "e"]
for bump_element in ["a", "b", "c"]:
_base = np.repeat(
np.array(_base),
np.where(np.ar... | [
"To avoid the for loop over the possible values in 'bump_element', you can use numpy isin.\n_base = np.array([\"a\", \"z\", \"c\", \"c\", \"e\"])\nbump = np.array([\"a\", \"b\", \"c\"])\nnp.repeat(_base, np.where(np.isin(_base, bump), 2, 1))\n\n"
] | [
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074534130_numpy_python.txt |
Q:
Extract nodes from json based on user input preserveing a portion of the higher level object as well
need to extract object from the given json based on the node chain passed by user and neglect those which are not in
user input, then create a new json object
my master json is :
{
"menustructure":
[
{
... | Extract nodes from json based on user input preserveing a portion of the higher level object as well | need to extract object from the given json based on the node chain passed by user and neglect those which are not in
user input, then create a new json object
my master json is :
{
"menustructure":
[
{
"node":"Admin",
"path":"admin",
"child":[
{
... | [
"Here is my solution. The idea is to traverse the structure recursively and remove nodes that don't match user input. The algorithm does not mutate the input data, but creates a shallow copy of the subtree only when the child attribute is changed.\ndef extract(data, query):\n return {\n \"menustructure\":... | [
1
] | [] | [] | [
"glom",
"json",
"python",
"python_3.x",
"python_jsons"
] | stackoverflow_0074506548_glom_json_python_python_3.x_python_jsons.txt |
Q:
Create two columns from the same columns but in different ways
From the table below, I would like to create two columns that aggregate 'amount' depending on the value of 'number' and 'type'.
number
type
amount
1
A
10
1
A
20
2
A
10
3
B
20
2
B
10
1
B
20
Here's the table I would like to get.
The first column ... | Create two columns from the same columns but in different ways | From the table below, I would like to create two columns that aggregate 'amount' depending on the value of 'number' and 'type'.
number
type
amount
1
A
10
1
A
20
2
A
10
3
B
20
2
B
10
1
B
20
Here's the table I would like to get.
The first column I want to create is 'amount A', which is the aggregati... | [
"You can try this:\nout = (\n df.astype({'number': 'category'})\n .query('type == \"A\"')\n .groupby(['number'])['amount'].sum()\n .to_frame('amount A')\n)\n\nout['amount A+B'] = df.groupby('number')['amount'].sum()\n\nprint(out)\n amount A amount A+B\nnumber \n1 ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074534236_python.txt |
Q:
Django form is not saving when I have action = to desired url
If I use action="" in my django form, the form works properly but sends the user to the wrong page. I want the user to go back to the macro/ page upon form submission, but when I add that url to action (like action="{% url 'macro' %}", it goes to the pa... | Django form is not saving when I have action = to desired url | If I use action="" in my django form, the form works properly but sends the user to the wrong page. I want the user to go back to the macro/ page upon form submission, but when I add that url to action (like action="{% url 'macro' %}", it goes to the page but the form doesn't save. Any suggestion on how to handle this?... | [
"\nI want the user to go back to the macro/ page upon form submission, but when I add that url to action (like action=\"{% url 'macro' %}\", it goes to the page but the form doesn't save.\n\nIt is because form data must go to macroUpdate view to save not macroPage, to redirect on macro page after form submission yo... | [
2
] | [] | [] | [
"django",
"django_forms",
"django_templates",
"django_urls",
"python"
] | stackoverflow_0074534273_django_django_forms_django_templates_django_urls_python.txt |
Q:
Comparing next element in a list Python
I'm trying to figure out how to make sure that the consecutive values are not the same in a list. Expected output: [1, 2, 3]
Actual output: [1, 1, 3, 3]
I also tried using next() but that gave me "list object is not an iterator"
What is best practices here and what am I doin... | Comparing next element in a list Python | I'm trying to figure out how to make sure that the consecutive values are not the same in a list. Expected output: [1, 2, 3]
Actual output: [1, 1, 3, 3]
I also tried using next() but that gave me "list object is not an iterator"
What is best practices here and what am I doing wrong?
def unique_in_order(iterable):
... | [
"Do it without list comprehensions. Create a list with the first element and iterate over the following pairs\ndef unique_in_order(iterable):\n lst = [iterable[0]]\n for x in range(len(iterable) - 1):\n if iterable[x] != iterable[x + 1]:\n lst.append(iterable[x + 1])\n return lst\n\nyou c... | [
2,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074533740_python.txt |
Q:
Python selenium and captcha
I have a scraping bot which I want to stop whenever it encounters a captcha, so not to annoy the websites. But selenium can't find it
driver.find_element_by_xpath("//*[@id='recaptcha-anchor']")
This is the xpath chrome gave me.
ERROR
NoSuchElementException: Unable to locate element: {... | Python selenium and captcha | I have a scraping bot which I want to stop whenever it encounters a captcha, so not to annoy the websites. But selenium can't find it
driver.find_element_by_xpath("//*[@id='recaptcha-anchor']")
This is the xpath chrome gave me.
ERROR
NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"//*[... | [
"AFAIK, captcha usually located inside an iframe, so you can try to switch to iframe before searching for required element:\nframe = driver.find_element_by_xpath('//iframe[contains(@src, \"recaptcha\")]')\ndriver.switch_to.frame(frame)\ndriver.find_element_by_xpath(\"//*[@id='recaptcha-anchor']\")\n\nIf you need to... | [
13,
0
] | [] | [] | [
"python",
"selenium",
"xpath"
] | stackoverflow_0044187909_python_selenium_xpath.txt |
Q:
Extendable way to select nth lowest/highest members of a list in python when there is a rank tie
Working on a hacker rank challenge and feel like I really hacked it. Need to select the second lowest members of a list, and return both if there's a tie. Here's what I did:
if __name__ == '__main__':
names = []
... | Extendable way to select nth lowest/highest members of a list in python when there is a rank tie | Working on a hacker rank challenge and feel like I really hacked it. Need to select the second lowest members of a list, and return both if there's a tie. Here's what I did:
if __name__ == '__main__':
names = []
scores = []
names_scores = []
for _ in range(int(input())):
name = input()
... | [
"Use itertools.groupby to group the identical scores:\n>>> from itertools import groupby\n>>> def second_lowest(scores):\n... ranks = (g for _, g in groupby(sorted(scores)))\n... first = list(next(ranks))\n... if len(first) >= 2:\n... return first # second lowest is also tied for first lowest\n... | [
1,
0
] | [] | [] | [
"list",
"python",
"rank"
] | stackoverflow_0074484169_list_python_rank.txt |
Q:
Why can’t I find a token count of a specific Solana address?
I've been trying to work on a Solana program in Python using the solana.py framework. However, I've run into a bit of a problem while trying to find the amount of USDC tokens designated to a specific wallet. I've been brewing in the Solana Cookbook for h... | Why can’t I find a token count of a specific Solana address? | I've been trying to work on a Solana program in Python using the solana.py framework. However, I've run into a bit of a problem while trying to find the amount of USDC tokens designated to a specific wallet. I've been brewing in the Solana Cookbook for hours but still haven't found anything. My code can be found below.... | [
"the fcn youre calling expects TokenAccountOpts to define the mint of the token to get from, so your code should be\nfrom solana.rpc.types import TokenAccountOpts\nusdc_balance = client.get_token_accounts_by_owner_json_parsed(sol_address, TokenAccountOpts(mint=usdc_key))\n\n\n"
] | [
1
] | [] | [] | [
"attributeerror",
"python",
"solana"
] | stackoverflow_0074512870_attributeerror_python_solana.txt |
Q:
Fish weird endline character at end / Fish shell outputs ⏎
I have a Python script that prints some numbers, like this:
results = [42, 21, 64, 32, 16, 8, 4, 2]
for number in results:
print(number, end=' ')
In the console, the output of this script is:
42 21 64 32 16 8 4 2 ⏎
Why is there a weird character at ... | Fish weird endline character at end / Fish shell outputs ⏎ | I have a Python script that prints some numbers, like this:
results = [42, 21, 64, 32, 16, 8, 4, 2]
for number in results:
print(number, end=' ')
In the console, the output of this script is:
42 21 64 32 16 8 4 2 ⏎
Why is there a weird character at the end?
My IDE is LunarVim. My shell is Fish.
| [
"Fish shell outputs ⏎ \nThis is essentially fish's way of telling you that there is no trailing newline or \"\\n\". Using print() will probably not result in this. In bash, the terminal may start after the output, instead of the next line.\n"
] | [
0
] | [] | [] | [
"console",
"fish",
"python",
"stdout",
"terminal"
] | stackoverflow_0074531603_console_fish_python_stdout_terminal.txt |
Q:
Reason: a bytes-like object is required, not 'str'
I want to write the content:
sample = {'Details': [{'user1': '{"d8": "X121", "d0": "NIL", "d4": false, "d3": false, "d2": false}', 'name': 'set a sample'}], 'person1': 1}
using code:
s1 = json.dumps(sample).replace('"', '"').replace("'", "'")
ftp = ssh.open_sft... | Reason: a bytes-like object is required, not 'str' | I want to write the content:
sample = {'Details': [{'user1': '{"d8": "X121", "d0": "NIL", "d4": false, "d3": false, "d2": false}', 'name': 'set a sample'}], 'person1': 1}
using code:
s1 = json.dumps(sample).replace('"', '"').replace("'", "'")
ftp = ssh.open_sftp()
ftp.putfo(BytesIO(s1), 'newfile.txt')
But getting er... | [
"Part of your JSON is still a string.\nThis should do the trick\ns1 = json.dumps(sample).replace('}\"', \"}\").replace('\"{', \"{\").replace('\\\\\"', '\"')\n\nParsing s1 using json.loads(s1) returns the following JSON\n{'Details': [{'user1': {'d8': 'X121',\n 'd0': 'NIL',\n 'd4': False,\n 'd3': False,\n ... | [
0
] | [] | [] | [
"json",
"python"
] | stackoverflow_0074534034_json_python.txt |
Q:
can only concatenate str (not "tuple") to str? How to get rid of tuple?
while True:
time.sleep(SLEEP_BETWEEN_ACTIONS)
input_1 = input("\n" + player1_name + ": " + random.choice(player_turn_text) + " Hit the enter to roll dice: ")
print("\nRolling dice...")
dice_value = get_dice_valu... | can only concatenate str (not "tuple") to str? How to get rid of tuple? | while True:
time.sleep(SLEEP_BETWEEN_ACTIONS)
input_1 = input("\n" + player1_name + ": " + random.choice(player_turn_text) + " Hit the enter to roll dice: ")
print("\nRolling dice...")
dice_value = get_dice_value()
time.sleep(SLEEP_BETWEEN_ACTIONS)
print(player1_name + " ... | [
"I don't know the signatures of the function you use, and that are not present in the attached code. But it seems, one of the elements here:\n+ player1_name + \": \" + random.choice(player_turn_text) +\n\nReturns tuple.\nThe simplest solution to that, would be to call it like str(player1_name) - and the same with t... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074534456_python.txt |
Q:
writing a program for finding nth prime term to find 10001st prime
i have actually written my nth term function, which takes in n and compiles all prime numbers in the list "primes", and return the indexed position -1 of primes which is 10001st prime:
please if someone can improve my code or write a better code fo... | writing a program for finding nth prime term to find 10001st prime | i have actually written my nth term function, which takes in n and compiles all prime numbers in the list "primes", and return the indexed position -1 of primes which is 10001st prime:
please if someone can improve my code or write a better code for this problem.
def nthprime(n):
primes = [2]
attempt = 3
w... | [
"Your code is absolutely fine, and quite pythonic :)\nThe algorithm you are implementing could be optimized, though, because you don't need to check every prime number as a factor for the new attempted number; for example numbers ending in a '5' are trivially not prime (I'm sure you can see why).\nI suggest you che... | [
1
] | [] | [] | [
"primes",
"python",
"python_3.x",
"while_loop"
] | stackoverflow_0074533784_primes_python_python_3.x_while_loop.txt |
Q:
why does pyspark filter a string column work with integers? And why does pandas behave the other way around?
When I have a pyspark dataframe with a column of numbers as strings and filter it using an integer the filter applies to the strings:
df = spark.createDataFrame([
("a", "1"),
("a", "2"),
("b", "1"),
... | why does pyspark filter a string column work with integers? And why does pandas behave the other way around? | When I have a pyspark dataframe with a column of numbers as strings and filter it using an integer the filter applies to the strings:
df = spark.createDataFrame([
("a", "1"),
("a", "2"),
("b", "1"),
("b", "2"),
], ["id", "number"])
df.filter(col('number')==1)
results in
id number
a 1
b 1
c 1
wheareas,... | [
"This is the physical plan of your query:\n\n== Physical Plan ==\n*(1) Filter (isnotnull(number#18) AND (cast(number#18 as int) = 1))\n+- *(1) Scan ExistingRDD[id#17,number#18]\n\nAs you can see, spark is casting the column to integer cast(number#18 as int) = 1\nYou can access logical and physical plans with .expla... | [
2
] | [] | [] | [
"apache_spark",
"dataframe",
"pandas",
"pyspark",
"python"
] | stackoverflow_0074533560_apache_spark_dataframe_pandas_pyspark_python.txt |
Q:
Update value within nested dict of arbitrary depth without changing the rest of the dict in Python
So I have a nested dictionary in Python:
{'entry': {'definition': 'str',
'endTime': 'str',
'entryID': {'identifierType': 'str', 'identifierValue': 'str'},
'instrument': {'FIB': {'FIBSpotSize': {'... | Update value within nested dict of arbitrary depth without changing the rest of the dict in Python | So I have a nested dictionary in Python:
{'entry': {'definition': 'str',
'endTime': 'str',
'entryID': {'identifierType': 'str', 'identifierValue': 'str'},
'instrument': {'FIB': {'FIBSpotSize': {'notes': 'str',
'qualifier': 'str',
... | [
"JMESPath is a powerful solution for querying a nested dict, but unfortunately doesn't seem to offer lvalue options (modification).\nIn the end, here is something built from first principles:\ndef xupdate(dct, path, value, createkeys=False):\n if path:\n k, *path = path\n subdct = dct.get(k, {}) if... | [
0
] | [] | [] | [
"dictionary",
"json",
"nested",
"python"
] | stackoverflow_0074533006_dictionary_json_nested_python.txt |
Q:
Threading and Tkinter - How to use the threading module with my simple example?
I don't understand how to use the threading module properly. In this example I have two tkinter widgets, a button and a progress bar. The progress bar (configured in indeterminate mode) has to be active when the user pushes the button,... | Threading and Tkinter - How to use the threading module with my simple example? | I don't understand how to use the threading module properly. In this example I have two tkinter widgets, a button and a progress bar. The progress bar (configured in indeterminate mode) has to be active when the user pushes the button, and when the task is completed, the progress bar has to be stopped.
import tkinter a... | [
"You can add a method to the class\ndef Get_Input(self):\n message = input(\">\")\n if message:\n send_message(message)\n\nand add in init class\nthreading.Thread(target=self.Get_Input, args=(,)).start()\n\nPlease note :\nIf you passing one argument, you need to use\nthreading.Thread(target=self.Get_In... | [
0,
0,
0
] | [] | [] | [
"multithreading",
"python",
"tkinter"
] | stackoverflow_0072147490_multithreading_python_tkinter.txt |
Q:
how do i replace a string in a list
Im trying to change a string in a list called lista composed by n times |_|, in a function I'm trying to change one specific place of the list with "X" but nothing is working
lista=["|_|","|_|","|_|","|_|","|_|","|_|","|_|","|_|","|_|","|_|"]
i want to change only the middle on... | how do i replace a string in a list | Im trying to change a string in a list called lista composed by n times |_|, in a function I'm trying to change one specific place of the list with "X" but nothing is working
lista=["|_|","|_|","|_|","|_|","|_|","|_|","|_|","|_|","|_|","|_|"]
i want to change only the middle one to |X|
I already tried different method... | [
"Use len(lista) // 2 to get the middle index.\nShould there be an un-even number, // 2 will 'round' it to the previous integer, so 9 --> 4\nlista = [ \"|_|\",\"|_|\",\"|_|\",\"|_|\",\"|_|\",\"|_|\",\"|_|\",\"|_|\",\"|_|\",\"|_|\" ]\nmiddle = len(lista) // 2\n\nlista[middle] = '|X|'\n\nprint(lista)\n\n['|_|', '|_|',... | [
1,
1,
1
] | [] | [] | [
"python",
"replace",
"string"
] | stackoverflow_0074534094_python_replace_string.txt |
Q:
Python3 check if exact string match in the event dictionary
I have the following event body (dictionary) coming in to the lambda function and I do something like the below:
{
"test-report": {
"url": "http://example.com",
"original-policy": "default-src 'none'; style-src example.com; report-uri /_/test-re... | Python3 check if exact string match in the event dictionary | I have the following event body (dictionary) coming in to the lambda function and I do something like the below:
{
"test-report": {
"url": "http://example.com",
"original-policy": "default-src 'none'; style-src example.com; report-uri /_/test-reports"
}
}
if 'test-report' in event['body']:
try:
... | [
"Well, i asume, that by first objet you mean the key in the dictionary, as they are not ordered.\nIf so, try :\n if 'test-report' in event['body'].keys():\n try:\ndo something here\n\n"
] | [
0
] | [] | [] | [
"lambda",
"python",
"python_3.x"
] | stackoverflow_0074534525_lambda_python_python_3.x.txt |
Q:
Flask object has no attribute get while following linode tutorial
Good morning,
Following the linode tutorial here to create a RESTful API
https://www.linode.com/docs/guides/create-restful-api-using-python-and-flask/
I keep getting an attribute error 'Flask' object has no attribute 'get'
Not sure what's going on b... | Flask object has no attribute get while following linode tutorial | Good morning,
Following the linode tutorial here to create a RESTful API
https://www.linode.com/docs/guides/create-restful-api-using-python-and-flask/
I keep getting an attribute error 'Flask' object has no attribute 'get'
Not sure what's going on because I'm following the tutorial precisely.
from flask import Flask
a... | [
"You're probably running an older version of Flask (v2.0.x or below).\nFlask added @application.get feature in v2.1.x branch (check documentation here).\nFor older flask versions use @application.route('/programming_languages', methods=['GET']). Documentation here.\n"
] | [
1
] | [] | [] | [
"flask",
"python"
] | stackoverflow_0074534406_flask_python.txt |
Q:
Python create secret with tags in Google Secret manager
I am using Google Cloud run for my applications.
I am storing all my secrets in Google Cloud Secret Manager.
To read secrets I do the following:
from google.cloud import secretmanager
import hashlib
def access_secret_version(secret_id, version_id="latest"):
... | Python create secret with tags in Google Secret manager | I am using Google Cloud run for my applications.
I am storing all my secrets in Google Cloud Secret Manager.
To read secrets I do the following:
from google.cloud import secretmanager
import hashlib
def access_secret_version(secret_id, version_id="latest"):
# Create the Secret Manager client.
client = secretm... | [
"One method to determine if feature is available is to study the REST API. Secrets do not support tags.\n\nMethod: projects.secrets.create\nResource: Secret\n\nSecrets support labels, annotations and versionAliases.\nDepending on your use case, versionAliases might be work instead of tags.\n\nOptional. Mapping from... | [
0,
0
] | [] | [] | [
"google_cloud_platform",
"google_secret_manager",
"python"
] | stackoverflow_0074517584_google_cloud_platform_google_secret_manager_python.txt |
Q:
How to find an alphabet and extract the alphabet and the number tagged along with it in Pandas?
I would like to create a new column in the data frame that will search for the alphabet in a column. Based on it, it will then search for the next number and copy the alphabet and number into newly extracted column. Exa... | How to find an alphabet and extract the alphabet and the number tagged along with it in Pandas? | I would like to create a new column in the data frame that will search for the alphabet in a column. Based on it, it will then search for the next number and copy the alphabet and number into newly extracted column. Example:
Month
Sem_Year
2020-04-01
H1 2020
2020-05-01
2020 H1
2020-06-01
H1 2020
2020-07-0... | [
"For the varied formats you have defined you need to use a Regex expression. Note that H\\d means H followed by a digit. This regex could be modified for other requirements.\ndf['Sem'] = df['Sem_year'].str.extract(\"(H\\d)\")\n\n",
"You can use df.insert() to add a new column. For extracting the alphabet, loop th... | [
1,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074534517_dataframe_pandas_python.txt |
Q:
Python key, value and increment in for loop with dictionary.items()
I am looking for a way to get the current loop iteration while looping though a key, value pair of dictionary items.
currently i am using enumerate() to split it into iteration, tuple(key, value) however this requires using tuple indexes to split ... | Python key, value and increment in for loop with dictionary.items() | I am looking for a way to get the current loop iteration while looping though a key, value pair of dictionary items.
currently i am using enumerate() to split it into iteration, tuple(key, value) however this requires using tuple indexes to split it back out.
mydict = {'fruit':'apple', 'veg':'potato', 'sweet':'haribo'}... | [
"Just put the (key, value) in brackets:\nmydict = {'fruit':'apple', 'veg':'potato', 'sweet':'haribo'}\n\nfor i, (key, value) in enumerate(mydict.items()):\n print(f\"iteration={i}, key={key}, value={value}\")\n\n"
] | [
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074534522_dictionary_python.txt |
Q:
How to fix Python import google API error
from googleapiclient.discovery import build
After pip installing google api for python google tells me to use this command however the command doesn't work!
Can anyone help?
https://developers.google.com/docs/api/quickstart/python
Traceback (most recent call last):
File... | How to fix Python import google API error | from googleapiclient.discovery import build
After pip installing google api for python google tells me to use this command however the command doesn't work!
Can anyone help?
https://developers.google.com/docs/api/quickstart/python
Traceback (most recent call last):
File "C:\Users\M1\PycharmProjects\YouTube\main.py",... | [
"I have installed the libraries using the following command:\npip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib\n\nThen, you can check that the library has been installed properly by running:\npip show google-api-python-client\n\nNow, you should be able to import the libraries... | [
0
] | [] | [] | [
"google_api_python_client",
"python"
] | stackoverflow_0074534568_google_api_python_client_python.txt |
Q:
Failed in nopython mode pipeline (step: nopython frontend) No implementation of function Function
TypingError
During: typing of setitem
def calc_ppr_topk_parallel(indptr, indices, deg, alpha, epsilon, nodes, topk):
<source elided>
idx_topk = np.argsort(val_np)[-topk:]
js[i] = j_np[idx_topk]
... | Failed in nopython mode pipeline (step: nopython frontend) No implementation of function Function | TypingError
During: typing of setitem
def calc_ppr_topk_parallel(indptr, indices, deg, alpha, epsilon, nodes, topk):
<source elided>
idx_topk = np.argsort(val_np)[-topk:]
js[i] = j_np[idx_topk]
^
import numba
import numpy as np
import scipy.sparse as sp
@numba.njit(cache=True, locals={'... | [
"You are using a dictionairy inside of a numba function. As numba only has very limited support for dictionaries, the code crashes. The error message implies that there is another problem with the code aswell, but without any input given I am not going to bother trying to find it.\nIt looks like you have also tried... | [
0
] | [] | [] | [
"numba",
"python"
] | stackoverflow_0074530680_numba_python.txt |
Q:
CNN model for timeseries prediction
I want to build a CNN model. I have x_train=8000000x7, y_train=8000000x2.
Since it is a multivariant time series. How can feed the input with window size of 160 and stride=1.
what should be the input for cnn model?
I used timeseriesgenerator for creating a dataset as follows
tra... | CNN model for timeseries prediction | I want to build a CNN model. I have x_train=8000000x7, y_train=8000000x2.
Since it is a multivariant time series. How can feed the input with window size of 160 and stride=1.
what should be the input for cnn model?
I used timeseriesgenerator for creating a dataset as follows
train_gen = tf.keras.preprocessing.sequence.... | [
"First, TimeseriesGenerator is deprecated and do not take tensorflow tensor as input so I discourage to use it. Instead you can use timeseries_dataset_from_array (doc here) from keras utils. It also generate sliding windows.\nFor time serie prediction, you should use 1-D CNN. They take a sequence as input exactly l... | [
1
] | [] | [] | [
"conv_neural_network",
"lstm",
"python",
"tensorflow"
] | stackoverflow_0074532559_conv_neural_network_lstm_python_tensorflow.txt |
Q:
In this program i want to extract the date in YYYY-MM-DD format from mysql database using python
CODE:
cur = sqlCon.cursor()
cur.execute("select datedue from library where member=%s ", Member.get())
row = cur.fetchone()
print(datetime.date.today())
for x in row:
print(row)
But the result is in (datetime.da... | In this program i want to extract the date in YYYY-MM-DD format from mysql database using python | CODE:
cur = sqlCon.cursor()
cur.execute("select datedue from library where member=%s ", Member.get())
row = cur.fetchone()
print(datetime.date.today())
for x in row:
print(row)
But the result is in (datetime.date(2022, 12, 6),) fromat
What should I do?????
| [
"You may use the strftime() function:\ncur.execute(\"SELECT datedue FROM library WHERE member = %s\", Member.get())\nrow = cur.fetchone()\ndate_str = row[\"datedue\"].strftime(\"%Y-%m-%d\")\nprint(date_str)\n\nYou could also handle this on the MySQL side by using the STR_TO_DATE() function:\nsql = \"SELECT STR_TO_D... | [
0
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0074534660_mysql_python.txt |
Q:
Local variable 'result' might be referenced before assignment
With a flow like this:
def func():
try:
result = calculate()
finally:
try:
cleanup()
except Exception:
pass
return result
There is a warning about Local variable 'result' might be referenced b... | Local variable 'result' might be referenced before assignment | With a flow like this:
def func():
try:
result = calculate()
finally:
try:
cleanup()
except Exception:
pass
return result
There is a warning about Local variable 'result' might be referenced before assignment:
But I can't really see how that's possible. One ... | [
"This is a false positive of PyCharms warning heuristics. As per the Python specification, the code behaves as you describe and result can only be reached when set.\n\nAccording to 8.4 in the Python documentation:\n\nIf the finally clause executes a return, break or continue statement, the saved exception is discar... | [
1
] | [] | [] | [
"exception",
"function",
"pycharm",
"python",
"scope"
] | stackoverflow_0069845686_exception_function_pycharm_python_scope.txt |
Q:
Problem by installing pygame on cmd and visual studio
Basically I'm trying to install pygame on my pc and the installation doesn't work, I already installed pygame on another pc and didn't have any problem.
All solutions appreciated
Output:
C:\Users\Station>pip install pygame
Defaulting to user installation becaus... | Problem by installing pygame on cmd and visual studio | Basically I'm trying to install pygame on my pc and the installation doesn't work, I already installed pygame on another pc and didn't have any problem.
All solutions appreciated
Output:
C:\Users\Station>pip install pygame
Defaulting to user installation because normal site-packages is not writeable
WARNING: Retrying (... | [
"there are some ways to fix this:\n1 - update pip to newest version\n2 - you can type this in python code to install any library\nimport pip \npip.main([\"install\", \"pygame\"])\n\n3 - you can install pygame from github with typing in command prompt:\npip install git+https://github.com/pygame/pygame\n\n"
] | [
0
] | [] | [] | [
"pip",
"pygame",
"python"
] | stackoverflow_0074534416_pip_pygame_python.txt |
Q:
How can I fix: 'KeyError [x] not found in axis' when filtering dataframe
I am trying to filter my dataframe based on IQR for a few selected features. The code I use is the following:
import pandas as pd
import numpy as np
# Load data
df = pd.read_csv("dataframe.csv")
features = df.loc[:, ('col1, col2, col3, col4,... | How can I fix: 'KeyError [x] not found in axis' when filtering dataframe | I am trying to filter my dataframe based on IQR for a few selected features. The code I use is the following:
import pandas as pd
import numpy as np
# Load data
df = pd.read_csv("dataframe.csv")
features = df.loc[:, ('col1, col2, col3, col4, col5')]
print("Old Shape: ", df.shape)
def filtering(column_name):
pri... | [
"Without the dataframe and line in which the error occurs its not that clear what happens\nBut in case you just want your script to run you could wrap it with a try/except block - like so:\ntry:\n # Your code\nexcept KeyError:\n # Do what you want to do in case a KeyError occurs e.g. log something or print so... | [
1,
0
] | [] | [] | [
"dataframe",
"filtering",
"python"
] | stackoverflow_0074533385_dataframe_filtering_python.txt |
Q:
Request Line is too large - Gunicorn
I have been using Flask for over a year, I used deploy my Flask app into production using Gunicorn WSGI server. Recently I encountered a weird error that,
<html>
<head>
<title>Bad Request</title>
</head>
<body>
<h1><p>Bad Request</p></h1>
Request Line is too l... | Request Line is too large - Gunicorn | I have been using Flask for over a year, I used deploy my Flask app into production using Gunicorn WSGI server. Recently I encountered a weird error that,
<html>
<head>
<title>Bad Request</title>
</head>
<body>
<h1><p>Bad Request</p></h1>
Request Line is too large (4269 > 4094)
</body>
</html>
I... | [
"Set --limit-request-line to 0. This will allow unlimited request length. However, add a request size validation inside code to avoid any security risks.\n"
] | [
0
] | [] | [] | [
"backend",
"flask",
"gunicorn",
"python",
"rest"
] | stackoverflow_0072129004_backend_flask_gunicorn_python_rest.txt |
Q:
Python/django : Cannot import GeoIP
I cannot import GeoIP in django. I searched and tested this error two days, but still could not know problem.
Surely, I installed GeoDjango. I'm on MacOS 10.8
following is log by tested by django shell
from django.contrib.gis import geoip
module 'django.contrib.gis.geoip' from ... | Python/django : Cannot import GeoIP | I cannot import GeoIP in django. I searched and tested this error two days, but still could not know problem.
Surely, I installed GeoDjango. I'm on MacOS 10.8
following is log by tested by django shell
from django.contrib.gis import geoip
module 'django.contrib.gis.geoip' from '/Library/Python/2.7/site-packages/djang... | [
"It appears you need to install a C library in order to use GeoIP. \nHere is a snippet from the file that is throwing that error.\n# The shared library for the GeoIP C API. May be downloaded\n# from http://www.maxmind.com/download/geoip/api/c/\nif lib_path:\n lib_name = None\nelse:\n # TODO: Is this really ... | [
1,
1,
0
] | [] | [] | [
"django",
"geodjango",
"geoip",
"python"
] | stackoverflow_0012761932_django_geodjango_geoip_python.txt |
Q:
Selenium executable_path has been deprecated
When running my code I get the below error string,
<string>:36: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
What could possibly be the issue? Below is the Selenium setup,
options = webdriver.ChromeOptions()
prefs = {"downloa... | Selenium executable_path has been deprecated | When running my code I get the below error string,
<string>:36: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
What could possibly be the issue? Below is the Selenium setup,
options = webdriver.ChromeOptions()
prefs = {"download.default_directory" : wd}
options.add_experimenta... | [
"This error message\n\nDeprecationWarning: executable_path has been deprecated, please pass in a Service object\n\nmeans that the key executable_path will be deprecated in the upcoming releases.\nOnce the key executable_path is deprecated you have to use an instance of the Service() class as follows:\nfrom selenium... | [
2,
0
] | [] | [] | [
"python",
"selenium",
"selenium_chromedriver",
"selenium_webdriver",
"web_scraping"
] | stackoverflow_0071482512_python_selenium_selenium_chromedriver_selenium_webdriver_web_scraping.txt |
Q:
Sphinx autodoc : show-inheritance full name
I have a hierarchy of modules with classes of the same name that subclass each other, e.g.
# foo.py
class Box: ...
# bar.py
class Box: ...
# foobar.py
import foo, bar
class Box(foo.Box, bar.Box): ...
My template for classes is setup with objname as title so that links... | Sphinx autodoc : show-inheritance full name | I have a hierarchy of modules with classes of the same name that subclass each other, e.g.
# foo.py
class Box: ...
# bar.py
class Box: ...
# foobar.py
import foo, bar
class Box(foo.Box, bar.Box): ...
My template for classes is setup with objname as title so that links remain short.
{{ objname | escape | underline}}
... | [
"The autodoc-process-bases hook can in fact use strings rather than classes themselves. I found a solution defining my own sphinx extension:\ndef process_bases(app, name, obj, options, bases):\n ambiguity = getattr(obj, \"__ambiguous_inheritance__\", ())\n for i, base in enumerate(bases):\n if base in ... | [
0
] | [] | [] | [
"autodoc",
"python",
"python_sphinx"
] | stackoverflow_0074534143_autodoc_python_python_sphinx.txt |
Q:
CreateProcessW failed error:2 ssh_askpass: posix_spawn: No such file or directory Host key verification failed, jupyter notebook on remote server
So I was following a tutorial to connect to my jupyter notebook which is running on my remote server so that I can access it on my local windows machine.
These were the ... | CreateProcessW failed error:2 ssh_askpass: posix_spawn: No such file or directory Host key verification failed, jupyter notebook on remote server | So I was following a tutorial to connect to my jupyter notebook which is running on my remote server so that I can access it on my local windows machine.
These were the steps that I followed.
On my remote server :
jupyter notebook --no-browser --port=8889
Then on my local machine
ssh -N -f -L localhost:8888:localhost:... | [
"If you need the DISPLAY variable set because you want to use VcXsrc or another X-Server in Windows 10 the workaround is to add the host you want to connect to your known_hosts file.\nThis can be done by calling\nssh-keyscan -t rsa host.example.com | Out-File ~/.ssh/known_hosts -Append -Encoding ASCII;\n\n",
"Acc... | [
6,
4,
0,
0,
0,
0,
0
] | [] | [] | [
"jupyter",
"jupyter_notebook",
"localhost",
"python",
"remote_server"
] | stackoverflow_0060107347_jupyter_jupyter_notebook_localhost_python_remote_server.txt |
Q:
How to get Non-contextual Word Embeddings in BERT?
I am already installed BERT, But I don't know how to get Non-contextual word embeddings.
For example:
input: 'Apple'
output: [1,2,23,2,13,...] #embedding of 'Apple'
How can i get these word embeddings?
Thank you.
I search some method, but no blogs have written t... | How to get Non-contextual Word Embeddings in BERT? | I am already installed BERT, But I don't know how to get Non-contextual word embeddings.
For example:
input: 'Apple'
output: [1,2,23,2,13,...] #embedding of 'Apple'
How can i get these word embeddings?
Thank you.
I search some method, but no blogs have written the way.
| [
"BERT uses static subword embeddings in its first layer, where they get summed with learned position embeddings. You can get the embeddings layer by calling model.embeddings.word_embeddings. You should be able to pass the indices that you get from a BertTokenizer to this layer and get the subword embeddings.\nThere... | [
1,
0
] | [] | [] | [
"bert_language_model",
"nlp",
"python",
"pytorch"
] | stackoverflow_0074527928_bert_language_model_nlp_python_pytorch.txt |
Q:
Generate list of days for each employee
EDIT: This solution worked for me
I have the following dataframe in Python:
Name
days
Start Date
End Date
EMP1
15
8/8/22
8/26/22
EMP2
3
6/9/22
6/13/22
EMP3
5
8/22/22
8/26/22
EMP3
5
8/1/22
8/5/22
EMP3
6
6/17/22
6/24/22
EMP4
4.5
7/18/22
7/22/22
EMP5
5
7/18/22
7/22/22
... | Generate list of days for each employee | EDIT: This solution worked for me
I have the following dataframe in Python:
Name
days
Start Date
End Date
EMP1
15
8/8/22
8/26/22
EMP2
3
6/9/22
6/13/22
EMP3
5
8/22/22
8/26/22
EMP3
5
8/1/22
8/5/22
EMP3
6
6/17/22
6/24/22
EMP4
4.5
7/18/22
7/22/22
EMP5
5
7/18/22
7/22/22
EMP6
5
8/15/22
8/19/22
EMP7
9
... | [
"well, convert the start date ,enddate to date range then explode using that\ncolumns :\ndf['Date'] = df.apply(lambda x: pd.date_range(start=x['Start Date'], end=x['End Date']), axis=1)\noutput = df.explode('Date').drop(columns = ['days','Start Date','End Date'])\n\noutput :\n>>\n Name Date\n0 EMP1 2022-... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074534590_pandas_python.txt |
Q:
average of the sum outputted in while loop with python
I don't know why I'm having so much trouble with this. I need to get the average of the sum that is outputted from def main():. I have tried to put the average within the def main and tried to use a separate def. both ways do not come out as expected.
Below is... | average of the sum outputted in while loop with python | I don't know why I'm having so much trouble with this. I need to get the average of the sum that is outputted from def main():. I have tried to put the average within the def main and tried to use a separate def. both ways do not come out as expected.
Below is where I am at currently.
def main():
totalMiles = 0
... | [
"after I posted this question I tried a different path which work.\n'''\ndef main():\n totalMiles = 0\n dayTotal = 0\n mileageGoal = eval(\n input(\"How many miles would you like to run this week? \"))\n while totalMiles != mileageGoal:\n dailyTotal = eval(\n input(f\"How many m... | [
0,
0
] | [] | [] | [
"python",
"while_loop"
] | stackoverflow_0074534869_python_while_loop.txt |
Q:
Python subprocess can't find Pythonpath module
I am trying to use subprocess.run(['python3.9', "scripts/example.py"], check=True).
example.py uses a module, that I have added to the PYTHONPATH.
However,
whenever I run the above line, the module is not found.
The confusing part for me is, that printing sys.path ins... | Python subprocess can't find Pythonpath module | I am trying to use subprocess.run(['python3.9', "scripts/example.py"], check=True).
example.py uses a module, that I have added to the PYTHONPATH.
However,
whenever I run the above line, the module is not found.
The confusing part for me is, that printing sys.path inside of example.py I do see the path to my module.
Bu... | [
"Looks like you need to check the doc for the env parameter of subprocess.run and set it appropriately.\nSide note: typically you would want to use the exact same Python interpreter for the sub-process call, so you would write: subprocess.run([sys.executable, 'scripts/example.py'], ...), unless of course you really... | [
1
] | [] | [] | [
"python",
"pythonpath",
"subprocess"
] | stackoverflow_0074532093_python_pythonpath_subprocess.txt |
Q:
Check when a columns value changes by a large amount in pandas
I am looking to write some code to check when a columns value changes by more than a specific amount, for example more than 20%
eg:
# | A |
--+------+
1 | 20 |
2 | 21 |
3 | 20 |
4 | 22 |
5 | 35 |
6 | 25 |
it would flag row 5
... | Check when a columns value changes by a large amount in pandas | I am looking to write some code to check when a columns value changes by more than a specific amount, for example more than 20%
eg:
# | A |
--+------+
1 | 20 |
2 | 21 |
3 | 20 |
4 | 22 |
5 | 35 |
6 | 25 |
it would flag row 5
| [
"you can use something like this:\ndf=pd.DataFrame(data={'id':[1,2,3,4,5,6],'A':[20,21,20,22,35,25]})\n'''\n id A\n0 1 20\n1 2 21\n2 3 20\n3 4 22\n4 5 35\n5 6 25\n'''\ndf['percent'] = (df['A'] / df['A'].shift(1) - 1).fillna(0) * 100 #calculate percentage\n\nprint(df)\n'''\n id A percent... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074534797_dataframe_pandas_python.txt |
Q:
Python Class private attribute created inside an exec function in __init__ method becomes public attribute instead of private attribute
I am trying to creating a class Customer which creates it's attribute from sqlalchemy query object.
data = {'Name':'John Doe','Age':67} #in the real code , data is a not a diction... | Python Class private attribute created inside an exec function in __init__ method becomes public attribute instead of private attribute | I am trying to creating a class Customer which creates it's attribute from sqlalchemy query object.
data = {'Name':'John Doe','Age':67} #in the real code , data is a not a dictionary but an object.
class Customer:
def __init__(self,data) -> None:
assert type(data) == Customers
for key in data.... | [
"You don' need exec here. Use setattr.\nfor key in data:\n setattr(self, key[1:] if key.startswith('_') else key, data[key])\n\nAlso, use isinstance, not type comparison.\nassert isinstance(data, Customers)\n\nthough in your example, data is not an instance of Customers; it's an ordinary dict passed to Customer.... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074535070_python_python_3.x.txt |
Q:
502 Bad Gateway nginx/1.18.0 (Ubuntu) Django Digital ocean
I want to deploy my django project with Ubuntu and Digital Ocean. It's not the first time I do it but now I keep getting this error and I don't know what's causing it. I used this video as guide for the process: https://www.youtube.com/watch?v=US9BkvzuIxw.... | 502 Bad Gateway nginx/1.18.0 (Ubuntu) Django Digital ocean | I want to deploy my django project with Ubuntu and Digital Ocean. It's not the first time I do it but now I keep getting this error and I don't know what's causing it. I used this video as guide for the process: https://www.youtube.com/watch?v=US9BkvzuIxw. It's really annoying because the only message that I get is "50... | [
"I faced the same issue and nothing worked but then I killed the previous port in my case was 8080 and installed nginx and pm2 again and everything worked fine.\n"
] | [
0
] | [] | [] | [
"bad_gateway",
"django",
"nginx",
"python"
] | stackoverflow_0071609299_bad_gateway_django_nginx_python.txt |
Q:
tkinter tab width incorrect
When creating text on a canvas using the create_text method the width of a tab is not what it should be, as indicated by font.measure.
import tkinter as tk
from tkinter.font import Font
root = tk.Tk()
canvas = tk.Canvas(root, width=300, height=300)
canvas.pack()
font = Font(family='A... | tkinter tab width incorrect | When creating text on a canvas using the create_text method the width of a tab is not what it should be, as indicated by font.measure.
import tkinter as tk
from tkinter.font import Font
root = tk.Tk()
canvas = tk.Canvas(root, width=300, height=300)
canvas.pack()
font = Font(family='Arial', size=12)
s1 = "a\tb"
s2 =... | [
"The problem you've highlighted is due to the Canvas text object not having a tabs attribute.\nMaybe someone knows how to work around that but usually when displaying tabulation a tk.Text object is used which has font and tabs attributes.\nSo the easiest solution is to make a tk.Text object T, define font and tabs,... | [
1,
0
] | [] | [] | [
"canvas",
"fonts",
"python",
"tkinter"
] | stackoverflow_0072148360_canvas_fonts_python_tkinter.txt |
Q:
how to stop the automatic tab closing in selenium?
from selenium import webdriver
driver=webdriver.Chrome(executable_path="C:\\Users\\DELL\\PycharmProjects\\drivers\\chromedriver.exe")
driver.get("http://www.letskodeit.com")
i had written the code like this and the code was executed without any errors ,but the co... | how to stop the automatic tab closing in selenium? | from selenium import webdriver
driver=webdriver.Chrome(executable_path="C:\\Users\\DELL\\PycharmProjects\\drivers\\chromedriver.exe")
driver.get("http://www.letskodeit.com")
i had written the code like this and the code was executed without any errors ,but the concern is the website which it was opening automatically ... | [
"If you want to keep the driver to stay open, you have to use the detach option when creating the driver instance.\nAs following:\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nchrome_options = Options()\nchrome_options.add_experimental_option(\"detach\", True)\ndriver = web... | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_chromedriver",
"selenium_webdriver"
] | stackoverflow_0074535111_python_selenium_selenium_chromedriver_selenium_webdriver.txt |
Q:
How to write to an abstract property in Python 3.4+
In Python 3.6, Let's say I have an abstract class MyAbstractClass
from abc import ABC, abstractmethod
class MyAbstractClass(ABC):
@property
@abstractmethod
def myProperty(self):
pass
and a class MyInstantiatableClass inherit from it. So how... | How to write to an abstract property in Python 3.4+ | In Python 3.6, Let's say I have an abstract class MyAbstractClass
from abc import ABC, abstractmethod
class MyAbstractClass(ABC):
@property
@abstractmethod
def myProperty(self):
pass
and a class MyInstantiatableClass inherit from it. So how do I write to the property myProperty on instantiation o... | [
"It seems there's a discrepancy here; using @property along with @abstractmethod doesn't seem to enforce classes that inherit from your abc to need to define both setter and getter. Using this:\n@property\n@abstractmethod\ndef myProperty(self):\n pass\n\n@myProperty.setter\n@abstractmethod\ndef myProperty(self):... | [
6,
0
] | [] | [] | [
"abstract_class",
"inheritance",
"python",
"python_3.x"
] | stackoverflow_0044376851_abstract_class_inheritance_python_python_3.x.txt |
Q:
Discord.py not excecuting
This is my code in python whenever I click the start button it automatically stops by the way I am using replit IDE.
import discord
class MyClient(discord.Client):
async def on_ready(self):
print(f'Logged on as {self.user}!')
async def on_message(self, message):
... | Discord.py not excecuting | This is my code in python whenever I click the start button it automatically stops by the way I am using replit IDE.
import discord
class MyClient(discord.Client):
async def on_ready(self):
print(f'Logged on as {self.user}!')
async def on_message(self, message):
print(f'Message from {message... | [
"You need to start a server, otherwise, it won't keep running.\nTry this:\nhttps://github.com/sdrrv/Fate-Wielding-Bot/blob/master/keep_alive.py\n",
"You're never starting it. You created a client_start() function, but you're not using it so all this script does is create some variables & then exit.\nNext, your co... | [
1,
0
] | [] | [] | [
"discord",
"discord.py",
"python",
"replit"
] | stackoverflow_0074534560_discord_discord.py_python_replit.txt |
Q:
Is it safe to create a Python class which is simultaneously sync and async iterator?
Is it safe/bad practice to make a class both iterator and async iterator? Example:
import asyncio
class Iter:
def __init__(self):
self.i = 0
self.elems = list(range(10))
def __iter__(self):
re... | Is it safe to create a Python class which is simultaneously sync and async iterator? | Is it safe/bad practice to make a class both iterator and async iterator? Example:
import asyncio
class Iter:
def __init__(self):
self.i = 0
self.elems = list(range(10))
def __iter__(self):
return self
def __aiter__(self):
return self
def __next__(self):
... | [
"The problem there is not the sync iterator: unless used in multi-threaded code it should be ok (but not otherwise).\nYour async code, however, keeps the state in a single instance, and if it is ever used in more than a task at once, the states will mix up.\n(Also, if you have a single task using it, but nests ite... | [
0
] | [] | [] | [
"async_iterator",
"iterator",
"python",
"python_3.x",
"python_asyncio"
] | stackoverflow_0074510953_async_iterator_iterator_python_python_3.x_python_asyncio.txt |
Q:
invert binary tree in python with recursion
I looked into the code of inverting binary tree in the internet. But I couldnt what it is doing. Its written in Python. I am a python programmer myself but couldnt understand it.
The snippet is as follows:
def invertTree(root):
if root:
root.left, root.right ... | invert binary tree in python with recursion | I looked into the code of inverting binary tree in the internet. But I couldnt what it is doing. Its written in Python. I am a python programmer myself but couldnt understand it.
The snippet is as follows:
def invertTree(root):
if root:
root.left, root.right = invertTree(root.right), invertTree(root.left)
... | [
"First understand the problem with a diagram..!\nQ:- Given binary tree you have to convert binary tree into invert binary tree.\nDiagram\nClass TreeNode: {Initialization of the binary tree}\nThe key insight here is to realize that in order to invert a binary tree we only need to recursively swap the children. To av... | [
1,
1
] | [] | [] | [
"binary_tree",
"data_structures",
"python",
"recursion"
] | stackoverflow_0074514686_binary_tree_data_structures_python_recursion.txt |
Q:
Treverse list of tuples to compare and report min, max
My previous question was not understood, so I rephrase and post this one.
I have a list of tuple for (class, n_class_examples) like this:
my_list = (0, 126), (1, 192), (2, 330), (3, 952) ]
So I am interested in generating a function, that takes in such a list... | Treverse list of tuples to compare and report min, max | My previous question was not understood, so I rephrase and post this one.
I have a list of tuple for (class, n_class_examples) like this:
my_list = (0, 126), (1, 192), (2, 330), (3, 952) ]
So I am interested in generating a function, that takes in such a list, compare each tuple against all others, and in each case re... | [
"Iterate over the list of pairs generated by itertools.combintions, the process each pair individually using min and max.\nfrom itertools import combinations\nfrom operator import itemgetter\n\nfirst = itemgetter(0)\nsecond = itemgetter(1)\n\ndef get_min_max_class(current_list):\n for pair in combinations(curren... | [
1,
0
] | [] | [] | [
"list",
"python",
"python_3.x"
] | stackoverflow_0074534955_list_python_python_3.x.txt |
Q:
Keras backend switch combined with tf.where not working as intended
I have a custom loss function where I want to change values from a one-hot based encoding to values in a certain range to calculate an IOU.
Part of this code is to look at where I have a one in a tensor that has zeros otherwise. For this I am usin... | Keras backend switch combined with tf.where not working as intended | I have a custom loss function where I want to change values from a one-hot based encoding to values in a certain range to calculate an IOU.
Part of this code is to look at where I have a one in a tensor that has zeros otherwise. For this I am using tf.where which returns me the location. I have a vector of shape [batch... | [
"So I found a workaround, maybe this is helpful for someone else:\nwhere_box1_temp = tf.where(y_pred[...,C+1:C+13],[1,2,3,4,5,6,7,8,9,10,11,12],0)\n\nwhere_box1 = tf.reshape(K.sum(where_box1_temp,axis=3),[batch_size,5,5])\n\nThis allows me to have a tensor of my desired shape where all background/zero prediction va... | [
0
] | [] | [] | [
"keras",
"python",
"tensorflow"
] | stackoverflow_0074530610_keras_python_tensorflow.txt |
Q:
How to check if the parentheses and brackets are balanced?
I need to write a function that given a string with parenthesis and/or square brackets it is able to evaluate if they appear in the correct order. For example, in this string '([b])(aa)' you can see that every time a parenthesis or square bracket is open, ... | How to check if the parentheses and brackets are balanced? | I need to write a function that given a string with parenthesis and/or square brackets it is able to evaluate if they appear in the correct order. For example, in this string '([b])(aa)' you can see that every time a parenthesis or square bracket is open, it is closed in the correct position. However, a string like '[(... | [
"This is one of the stack implementations I know:\ndef is_balanced(s):\n stack = []\n for char in s:\n if char == \"(\" or char == \"{\" or char == \"[\":\n stack.append(char) \n elif len(stack) <= 0:\n return False\n elif char == \")\" and stack.pop() != \"(\":\n ... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0072250748_python.txt |
Q:
Move surface with mouse motion in pygame
I'm trying to move a surface represented by an image on disk with mouse motion in pygame, here's my code :
import sys
import pygame
from pygame.locals import *
WINDOW_SIZE = (600, 400)
FPS = 60
class System:
def __init__(self, screen, surface):
self.screen = s... | Move surface with mouse motion in pygame | I'm trying to move a surface represented by an image on disk with mouse motion in pygame, here's my code :
import sys
import pygame
from pygame.locals import *
WINDOW_SIZE = (600, 400)
FPS = 60
class System:
def __init__(self, screen, surface):
self.screen = screen
self.surface = pygame.transform... | [
"I found my mistake :\nReplace :\noffset_x = event.rel[0]\noffset_y = event.rel[1]\n\nWith :\noffset_x += event.rel[0]\noffset_y += event.rel[1]\n\n"
] | [
0
] | [] | [] | [
"motion",
"mouse",
"pygame",
"python"
] | stackoverflow_0074534425_motion_mouse_pygame_python.txt |
Q:
How to use MINOS or SNOPT with GEKKO
I am working on an optimization problem and I want to use MINOS or SNOPT solvers to find a solution to it.
In the GEKKO website https://gekko.readthedocs.io/en/latest/overview.html
, they mentioned that MINOS and SNOPT are available but with a commercial License
how could I get... | How to use MINOS or SNOPT with GEKKO | I am working on an optimization problem and I want to use MINOS or SNOPT solvers to find a solution to it.
In the GEKKO website https://gekko.readthedocs.io/en/latest/overview.html
, they mentioned that MINOS and SNOPT are available but with a commercial License
how could I get this License?
Now, I am using APOPT, but ... | [
"Licenses for SNOPT and MINOS are available from Stanford Business Software, Inc. If you share benchmark information with your manager or professor, you may not need SNOPT. Testing on 494 benchmark problem shows that APOPT (MINLP) and IPOPT (NLP) beat the performance of SNOPT and MINOS. APOPT and IPOPT are freely a... | [
0
] | [] | [] | [
"gekko",
"python"
] | stackoverflow_0074526311_gekko_python.txt |
Q:
How do i extract this object from his background in opencv?
For my internship, I am trying to extract this type of aluminum wires of the acquired vision camera footage. The purpose is to extract those connections and classify them with machine learning. My idea is to extract those connections to remove all the noi... | How do i extract this object from his background in opencv? | For my internship, I am trying to extract this type of aluminum wires of the acquired vision camera footage. The purpose is to extract those connections and classify them with machine learning. My idea is to extract those connections to remove all the noise (background) and analyze the gray value density of the bond, a... | [
"As noted in the comments, this is a tricky problem, because the image has lots of edges that you don't care about, and it's hard to filter by color, either. However, there is one feature which I think could be helpful, which is the blur. Specifically, the wire is focus, and the rest of the shot is not.\nYou could ... | [
1
] | [] | [] | [
"canny_operator",
"computer_vision",
"extract",
"opencv",
"python"
] | stackoverflow_0074531551_canny_operator_computer_vision_extract_opencv_python.txt |
Q:
Guys, can someone give a hand how could I change this to a For loop, please?
MyList = [tuple(i for i in j if type(i) != str ) for j in MyList]
result is a tuple inside list, for example:
[(X,Y), (X2,Y2)]
A:
What is relevant here is understanding list comprehension, which you want to reverse.
This sounds to me ... | Guys, can someone give a hand how could I change this to a For loop, please? | MyList = [tuple(i for i in j if type(i) != str ) for j in MyList]
result is a tuple inside list, for example:
[(X,Y), (X2,Y2)]
| [
"What is relevant here is understanding list comprehension, which you want to reverse.\nThis sounds to me like some form of course homework to make sure you understand what's going on in that line ;-)\nMyList = [(1,2,3,(1,2), \"hello world\"),(\"hello\"),(3,4,1),\"world\"]\n\ncomp = [tuple(i for i in j if type(i) !... | [
0
] | [] | [] | [
"for_loop",
"list",
"list_comprehension",
"python",
"tuples"
] | stackoverflow_0074535056_for_loop_list_list_comprehension_python_tuples.txt |
Q:
How create a unittest that will test if method was called for specific class with specific argument?
Here is my code
module_a.py
class Parent(object):
def __init__(self) -> None:
pass
def send(self):
print('We send some message here')
# send self.message
class Child(Parent):
... | How create a unittest that will test if method was called for specific class with specific argument? | Here is my code
module_a.py
class Parent(object):
def __init__(self) -> None:
pass
def send(self):
print('We send some message here')
# send self.message
class Child(Parent):
def __init__(self, message):
self.message = message
super(Child, self).__init__()
module... | [
"Sure. You can check the Type of self (your Object)\neg:\n class Parent(object):\n def __init__(self) -> None:\n pass\n\n def send(self):\n print(type(self))\n # send self.message\n\nclass Child(Parent):\n def __init__(self, message):\n self.message = message\n super(C... | [
1,
1,
0
] | [] | [] | [
"mocking",
"python",
"python_unittest"
] | stackoverflow_0074530758_mocking_python_python_unittest.txt |
Q:
How do I change directory back to my original working directory with Python?
I have a function that resembles the one below. I'm not sure how to use the os module to get back to my original working directory at the conclusion of the jar's execution.
def run():
owd = os.getcwd()
#first change dir to build... | How do I change directory back to my original working directory with Python? | I have a function that resembles the one below. I'm not sure how to use the os module to get back to my original working directory at the conclusion of the jar's execution.
def run():
owd = os.getcwd()
#first change dir to build_dir path
os.chdir(testDir)
#run jar from test directory
os.system(cmd... | [
"A context manager is a very appropriate tool for this job:\nfrom contextlib import contextmanager\n\n@contextmanager\ndef cwd(path):\n oldpwd = os.getcwd()\n os.chdir(path)\n try:\n yield\n finally:\n os.chdir(oldpwd)\n\n...used as:\nos.chdir('/tmp') # for testing purposes, be in a known ... | [
64,
34,
16,
3,
2,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0000299446_python.txt |
Q:
TypeError: __init__() got an unexpected keyword argument 'model_list'
Getting the error like TypeError: init() got an unexpected keyword argument 'model_list'
When I am running following script:
from autots import AutoTS
model_list = ['LastValueNaive','GLS','ETS','AverageValueNaive',]
model = AutoTS(\
forecast_l... | TypeError: __init__() got an unexpected keyword argument 'model_list' | Getting the error like TypeError: init() got an unexpected keyword argument 'model_list'
When I am running following script:
from autots import AutoTS
model_list = ['LastValueNaive','GLS','ETS','AverageValueNaive',]
model = AutoTS(\
forecast_length=49,\
frequency='infer',\
prediction_interval=0.95,\
ensemble=\['simpl... | [
"Try without making strings in model_list like so:\nmodel_list = [LastValueNaive,GLS,ETS,AverageValueNaive]\n\nThis approach worked for me when using neuralforecast, mlforecast from Nixtla. Maybe it works for you too.\n"
] | [
0
] | [] | [] | [
"forecasting",
"python"
] | stackoverflow_0071672448_forecasting_python.txt |
Q:
Separate text in cells and decompose into different columns depending on the content
how can i take date from rec event and from visit event and put it in different columns?
as you can see, there can be more than 2 events (not only rec and visit). Moreover, they can be interchanged
i have DF
df = pd.DataFrame({'ev... | Separate text in cells and decompose into different columns depending on the content | how can i take date from rec event and from visit event and put it in different columns?
as you can see, there can be more than 2 events (not only rec and visit). Moreover, they can be interchanged
i have DF
df = pd.DataFrame({'event': ['rec - 2022-11-13 21:07:51, visit - 2022-11-16 10:01:01',
... | [
"Here is what worked for me, I needed to apply several splits given the input data:\nimport pandas as pd\n\n\ndf = pd.DataFrame({'event': ['rec - 2022-11-13 21:07:51, visit - 2022-11-16 10:01:01',\n 'visit - 2022-11-14 15:34:28, rec - 2022-11-12 09:03:58',\n 'rec ... | [
0
] | [] | [] | [
"pandas",
"python",
"split"
] | stackoverflow_0074535072_pandas_python_split.txt |
Q:
Multiprocessing messes up logging to file
Issue
Multiprocessing messes up logging to file:
Lines already written may be removed
New lines may not be written
Order of lines may be incorrect
Logging works fine if I don't use multiprocessing.
I read that I can use a QueueHandler, but I want to understand why writin... | Multiprocessing messes up logging to file | Issue
Multiprocessing messes up logging to file:
Lines already written may be removed
New lines may not be written
Order of lines may be incorrect
Logging works fine if I don't use multiprocessing.
I read that I can use a QueueHandler, but I want to understand why writing logging to some handler still messes up anoth... | [
"\nI want to understand why writing logging to some handler still messes up another handler.\n\nIt's explained here in the Python documentation, assuming that you're talking about file-related handlers. You can use QueueHandler with a QueueListener, or you can use a SocketHandler with a suitable listener. The docum... | [
0
] | [] | [] | [
"logging",
"multiprocessing",
"python",
"python_3.x"
] | stackoverflow_0074530205_logging_multiprocessing_python_python_3.x.txt |
Q:
merge rows with reversed columns
I have dataframe, and I would like to merge the rows that has the same value in reversed columns. An example as below:
Column1 Column2
A B
B A
C D
D C
E F
Expected results:
Column1 Column2
A B
C D
E F
As the file has less than 50 li... | merge rows with reversed columns | I have dataframe, and I would like to merge the rows that has the same value in reversed columns. An example as below:
Column1 Column2
A B
B A
C D
D C
E F
Expected results:
Column1 Column2
A B
C D
E F
As the file has less than 50 lines (though I have 1000 files), I tri... | [
"Change\nrow_rev_index = df[(df['Column1'] == row['Column2']) & (df['Column2'] == row['Column1'])].index()\n\nto\nrow_rev_index = df[(df['Column1'] == row['Column2']) & (df['Column2'] == row['Column1'])].index\n\nor even shorter\nrow_rev_index = row_rev.index\n\n",
"This may be what you are looking for:\ndf = df.... | [
0,
0
] | [] | [] | [
"dataframe",
"python"
] | stackoverflow_0074535305_dataframe_python.txt |
Q:
cannot import name 'pad_sequences' from 'keras.preprocessing.sequence'
i'm trying to import these :
from numpy import array
from keras.preprocessing.text import one_hot
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers.core import Activation, Dropout, De... | cannot import name 'pad_sequences' from 'keras.preprocessing.sequence' | i'm trying to import these :
from numpy import array
from keras.preprocessing.text import one_hot
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers.core import Activation, Dropout, Dense
from keras.layers import Flatten, LSTM
from keras.layers import GlobalM... | [
"Replace:\nfrom keras.preprocessing.sequence import pad_sequences\n\nWith:\nfrom keras_preprocessing.sequence import pad_sequences\n\n",
"you can use this. It is worked for me.\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\n\n",
"According to the TensorFlow v2.10.0 doc, the correct path to ... | [
34,
5,
4,
2,
1,
1,
0
] | [] | [] | [
"keras",
"python",
"python_import"
] | stackoverflow_0072326025_keras_python_python_import.txt |
Q:
Using plt.savefig over a for loop of iterated plots returns blank image
Ok, so I apologize if this has been asked before, but I am running into some issues with trying to execute plt.savefig on some plots I want to save to a certain directory on my computer.
I currently have 481 plots that I generated through the... | Using plt.savefig over a for loop of iterated plots returns blank image | Ok, so I apologize if this has been asked before, but I am running into some issues with trying to execute plt.savefig on some plots I want to save to a certain directory on my computer.
I currently have 481 plots that I generated through the following code:
ID=np.array(table['ID'])
My ID array comes from an isolat... | [
"You shoud try to add plt.close() the line after plt.savefig(outfilename+str(ID[i])+'.pdf')\n"
] | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0062037161_matplotlib_python.txt |
Q:
why is iterating over a Numpy array faster than direct operations
I wanted to find out if it is significantly slower to iterate over the first two dimensions of an array in comparison to doing the operations columnwise. To my surprise if found out that its actually faster to do the operations elementwise. Can some... | why is iterating over a Numpy array faster than direct operations | I wanted to find out if it is significantly slower to iterate over the first two dimensions of an array in comparison to doing the operations columnwise. To my surprise if found out that its actually faster to do the operations elementwise. Can someone explain?
Here is the code:
def row_by_row(arr, cop):
for i in ... | [
"Short Answer:\nMemory Allocation\nLong Answer:\nAs the commenters in the question point out, the measure results seem very unreliable. Increasing the number of operations for the measurement to 2000 gives more steady results\n\nRow: 3.519135099995765\n\n\nAll: 5.321293300003163\n\nOne thing which certainly impacts... | [
2,
2
] | [] | [] | [
"algorithm",
"arrays",
"numpy",
"python"
] | stackoverflow_0074534076_algorithm_arrays_numpy_python.txt |
Q:
`staticmethod` and `abc.abstractmethod`: Will it blend?
In my Python app I want to make a method that is both a staticmethod and an abc.abstractmethod. How do I do this?
I tried applying both decorators, but it doesn't work. If I do this:
import abc
class C(object):
__metaclass__ = abc.ABCMeta
@abc.abstr... | `staticmethod` and `abc.abstractmethod`: Will it blend? | In my Python app I want to make a method that is both a staticmethod and an abc.abstractmethod. How do I do this?
I tried applying both decorators, but it doesn't work. If I do this:
import abc
class C(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
@staticmethod
def my_function(): pass
... | [
"Starting with Python 3.3, it is possible to combine @staticmethod and @abstractmethod, so none of the other suggestions are necessary anymore:\n@staticmethod\n@abstractmethod\ndef my_abstract_staticmethod(...):\n\nFurther @abstractstatic is deprecated since version 3.3.\n",
"class abstractstatic(staticmethod):\n... | [
348,
40,
16,
5,
0
] | [] | [] | [
"abstract_class",
"python",
"static_methods"
] | stackoverflow_0004474395_abstract_class_python_static_methods.txt |
Q:
Find the difference between two columns in a dataframe but keeping the row index avaiable
I have two dataframes:
df1 = pd.DataFrame({"product":['apples', 'bananas', 'oranges', 'kiwi']})
df2 = pd.Dataframe({"product":['apples', 'aples', 'appples', 'banans', 'oranges', 'kiwki'], "key": [1, 2, 3, 4, 5, 6]})
I want t... | Find the difference between two columns in a dataframe but keeping the row index avaiable | I have two dataframes:
df1 = pd.DataFrame({"product":['apples', 'bananas', 'oranges', 'kiwi']})
df2 = pd.Dataframe({"product":['apples', 'aples', 'appples', 'banans', 'oranges', 'kiwki'], "key": [1, 2, 3, 4, 5, 6]})
I want to use something like a set(df2).difference(df1) to find the difference between the product colu... | [
"I guess you are trying to do a left anti join, which means you only want to keep the rows in df2 that aren't present in df1. In that case:\ndf1 = pd.DataFrame({\"product\":['apples', 'bananas', 'oranges', 'kiwi']})\ndf2 = pd.DataFrame({\"product\":['apples', 'aples', 'appples', 'banans', 'oranges', 'kiwki'], \"key... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"set"
] | stackoverflow_0074535375_dataframe_pandas_python_set.txt |
Q:
Class that holds variables and has methods?
I have a class like this:
class ErrorMessages(object):
"""a class that holds all error messages and then presents them to the user)"""
messages= []
userStrMessages= ""
def newError(self, Error):
self.userStrMessages+= Error
def __str__(sel... | Class that holds variables and has methods? | I have a class like this:
class ErrorMessages(object):
"""a class that holds all error messages and then presents them to the user)"""
messages= []
userStrMessages= ""
def newError(self, Error):
self.userStrMessages+= Error
def __str__(self):
if self.messages.count() != 0:
... | [
"If you want to call a method directly without making an object first then you'll have to make your method newError() a class method and then call it as you mentioned above.\n@classmethod\ndef newError(self, Error): \n self.userStrMessages+= Error\n\nErrorMessages.newError(errormessage)\n\nOtherwise you can crea... | [
-1
] | [
"newError is an instance method. You'd need to instantiate it and then call it:\nmyMessage = ErrorMessage()\nmyMessage.newError(\"important error message\")\n\nSee this question about making it a static/class method, which would let you call it on the class without instantiation.\n"
] | [
-2
] | [
"class",
"object",
"python"
] | stackoverflow_0074535599_class_object_python.txt |
Q:
How to use dot notation for dict in python?
I'm very new to python and I wish I could do . notation to access values of a dict.
Lets say I have test like this:
>>> test = dict()
>>> test['name'] = 'value'
>>> print(test['name'])
value
But I wish I could do test.name to get value. Infact I did it by overriding th... | How to use dot notation for dict in python? | I'm very new to python and I wish I could do . notation to access values of a dict.
Lets say I have test like this:
>>> test = dict()
>>> test['name'] = 'value'
>>> print(test['name'])
value
But I wish I could do test.name to get value. Infact I did it by overriding the __getattr__ method in my class like this:
class... | [
"This functionality already exists in the standard libraries, so I recommend you just use their class. \n>>> from types import SimpleNamespace\n>>> d = {'key1': 'value1', 'key2': 'value2'}\n>>> n = SimpleNamespace(**d)\n>>> print(n)\nnamespace(key1='value1', key2='value2')\n>>> n.key2\n'value2'\n\nAdding, modifyin... | [
246,
55,
17,
11,
6,
4,
3,
3,
2,
1,
1,
1,
0,
0,
0
] | [
"Add a __repr__() method to the class so that you can customize the text to be shown on \nprint text\n\nLearn more here: https://web.archive.org/web/20121022015531/http://diveintopython.net/object_oriented_framework/special_class_methods2.html\n"
] | [
-1
] | [
"dictionary",
"nested",
"nested_properties",
"python"
] | stackoverflow_0016279212_dictionary_nested_nested_properties_python.txt |
Q:
How to read a text file and make it a dataframe using pandas
I want to read the files present in this folder - uwyo and read this as a data frame while skipping the rows in between the observation data. I want to read every observation where it starts from the keyword- pressure.
For that I thought of using pandas ... | How to read a text file and make it a dataframe using pandas | I want to read the files present in this folder - uwyo and read this as a data frame while skipping the rows in between the observation data. I want to read every observation where it starts from the keyword- pressure.
For that I thought of using pandas and then start searching for the word 'pressure', but I got the fo... | [
"Try it as: pd.read_csv(fname, sep='\\s+', on_bad_lines='skip', skiprows=4)\nThis will read the file with a lot of trash though. Also, missing values in the txt file would appear in the wrong column.\nI would recommend trying to identify the timestamps you have available and add a column for them, as well as identi... | [
1
] | [] | [] | [
"csv",
"dataframe",
"pandas",
"python",
"text"
] | stackoverflow_0074535453_csv_dataframe_pandas_python_text.txt |
Q:
Dropping rows that contains a specific condition
I got a dataset and I want to drop a few unusable rows. I used a filter to the specific condition in which i want the rows to be dropped
filter = df.groupby(['Bairro'], group_keys=False, sort=True).size() > 1 print(filter.to_string())
Bairro
01
True
02
False
Al... | Dropping rows that contains a specific condition | I got a dataset and I want to drop a few unusable rows. I used a filter to the specific condition in which i want the rows to be dropped
filter = df.groupby(['Bairro'], group_keys=False, sort=True).size() > 1 print(filter.to_string())
Bairro
01
True
02
False
All the data in which the condition is false ... | [
"It seems like the df.loc method could help you in this instance. In your example:\nnew_df = df.loc[df['col2'] == \"True\"]\n\nOr if you would like to use multiple conditions:\nnew_df = df.loc[(df['col1'] == \"True\") & (df['col2'] == \"True\")]\n\n",
"I think you're over-engineering your solution therefore I've ... | [
2,
1
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074534991_dataframe_pandas_python.txt |
Q:
How to designate unreachable python code
What's the pythonic way to designate unreachable code in python as in:
gender = readFromDB(...) # either 'm' or 'f'
if gender == 'm':
greeting = 'Mr.'
elif gender == 'f':
greeting = 'Ms.'
else:
# What should this line say?
A:
raise ValueError('invalid gender %... | How to designate unreachable python code | What's the pythonic way to designate unreachable code in python as in:
gender = readFromDB(...) # either 'm' or 'f'
if gender == 'm':
greeting = 'Mr.'
elif gender == 'f':
greeting = 'Ms.'
else:
# What should this line say?
| [
"raise ValueError('invalid gender %r' % gender)\n\n",
"You could raise an exception:\nraise ValueError(\"Unexpected gender; expected 'm' or 'f', got %s\" % gender)\n\nor use an assert False if you expect the database to return only 'm' or 'f':\nassert False, \"Unexpected gender; expected 'm' or 'f', got %s\" % ge... | [
30,
9,
6,
4,
4,
4,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0000815310_python.txt |
Q:
Global Variable Scope in python
Should I need to Global everything Global? Considering scope?
I keep randomly running into this problem, Im gonna assume its some how a syntax problem on myside. But variables out side of a scope in python seems to be inconsistent... my situation is
libFound=False
def Setup():
_... | Global Variable Scope in python | Should I need to Global everything Global? Considering scope?
I keep randomly running into this problem, Im gonna assume its some how a syntax problem on myside. But variables out side of a scope in python seems to be inconsistent... my situation is
libFound=False
def Setup():
_setup_import()
print('booting:',li... | [
"A global variable is, by definition, bound in the global scope. But assignments to names in a function always define a new local variable, unless you declare the name as global or non-local using global or nonlocal, respectively. –\nchepner\n10 mins ago\nBoom... inside the scope of _setup_libraries() I made it glo... | [
0,
0
] | [] | [] | [
"global_variables",
"python",
"scope",
"types",
"variable_assignment"
] | stackoverflow_0074535376_global_variables_python_scope_types_variable_assignment.txt |
Q:
Selenium 4 (python): stale element reference during table web scraping
I am web scraping a web table that looks like the follow:
| A | B | C | D |
1| Name | Surname| Route | href="link with more info"|
2| Name | Surname| Route | href="link with more info"|
3| Name | Surname| ... | Selenium 4 (python): stale element reference during table web scraping | I am web scraping a web table that looks like the follow:
| A | B | C | D |
1| Name | Surname| Route | href="link with more info"|
2| Name | Surname| Route | href="link with more info"|
3| Name | Surname| Route | href="link with more info"|
links = driver.find_elements(by='xpath... | [
"By navigating to another page all previously collected by Selenium web elements (they are actually references to a physical web elements) become no more valid since the web page is re-built when you open it again.\nTo make your code working you need to collect the links list again on the main page when you getting... | [
2
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver",
"staleelementreferenceexception",
"web_scraping"
] | stackoverflow_0074535525_python_selenium_selenium_webdriver_staleelementreferenceexception_web_scraping.txt |
Q:
How to get count of bar plot with non-count axis?
Below is my datasheet and sample graph
As you can above x-axis is consist of day and y-axis is consist of tip and hue is set to sex.
I want the count of bar i.e for (Male)light pink number should be 8 because there are 8 male who gave tip on sunday and likewise Fe... | How to get count of bar plot with non-count axis? | Below is my datasheet and sample graph
As you can above x-axis is consist of day and y-axis is consist of tip and hue is set to sex.
I want the count of bar i.e for (Male)light pink number should be 8 because there are 8 male who gave tip on sunday and likewise Female should be 1. I know how to display number on the t... | [
"The following seems to work:\nlabels = df.groupby(['sex', 'day']).size()\nax = sns.barplot(x='day', y='tip',hue='sex', data=df, palette='tab20_r')\nfor p, value in zip(ax.patches, labels):\n x = p.get_x() + p.get_width() / 2\n y = p.get_y() + p.get_height() / 2\n ax.annotate(value, (x, y), ha='center')\n\... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074534223_python.txt |
Q:
How to set different values of the elements of a np.arrays to different values in Python 3.8?
Let I have the following np.array:
>>>a=np.array([20, 10,5,10,5,10])
>>>array([20, 10, 5, 10, 5, 10])
Now, I want to replace 20 and 10 by 1 and 5 by 0.
Is there a function that can do that in one step?
Here is what I h... | How to set different values of the elements of a np.arrays to different values in Python 3.8? | Let I have the following np.array:
>>>a=np.array([20, 10,5,10,5,10])
>>>array([20, 10, 5, 10, 5, 10])
Now, I want to replace 20 and 10 by 1 and 5 by 0.
Is there a function that can do that in one step?
Here is what I have tried:
>>>a[a==10]=1
>>>a[a==10]=1
>>>a[a==5]=0
and I am getting my desired output, which is:
... | [
"You can use the map function.\nlist(map(lambda x: int(x in [10,20]),a))\n\nThe map function will apply the function in the first argument to all the elements in the list given as the second argument.\nHere the lambda function returns 0 if the element is not 10 or 20, and 1 if the element is 10 or 20.\nEDIT FOLLOW... | [
2,
2
] | [] | [] | [
"numpy",
"numpy_ndarray",
"python",
"python_2.7",
"python_3.x"
] | stackoverflow_0074533939_numpy_numpy_ndarray_python_python_2.7_python_3.x.txt |
Q:
Find overlapping numeric ranges between 2 columns pandas and subtract difference of another column
This is a toy dataset:
df = pd.DataFrame({'ID': ['A','A','A','A'],
'target': ['B','B','B','B'],
'length':[208,315,1987,3775],
'start':[139403,140668,1417... | Find overlapping numeric ranges between 2 columns pandas and subtract difference of another column | This is a toy dataset:
df = pd.DataFrame({'ID': ['A','A','A','A'],
'target': ['B','B','B','B'],
'length':[208,315,1987,3775],
'start':[139403,140668,141726,143705],
'end':[139609,140982,143711,147467]})
ID target length start end
... | [
"A possible solution:\n(df.assign(length=\n df['start'].lt(df['end'].shift())\n .mul(df['start']-df['end'].shift(fill_value=0))\n .add(df['length'])))\n\nOutput:\n ID target length start end\n0 A B 208 139403 139609\n1 A B 315 140668 140982\n2 A B ... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074535386_pandas_python.txt |
Q:
Cannot find reference 'pack' in 'None'
I'm trying to make a basic pong game and starting by drawing a rectangle on the left side of the screen. When I run it i get the error of Cannot find reference 'pack' in 'None'. Thoughts?
import tkinter as tk
window = tk.Tk()
window.geometry('600x600')
canvas_width, canvas_... | Cannot find reference 'pack' in 'None' | I'm trying to make a basic pong game and starting by drawing a rectangle on the left side of the screen. When I run it i get the error of Cannot find reference 'pack' in 'None'. Thoughts?
import tkinter as tk
window = tk.Tk()
window.geometry('600x600')
canvas_width, canvas_height = 10,100
x1, y1 = canvas_width // 2, ... | [
"Remove place from your canvas. The issue is that place() returns None, so your canvas object evaluates to None. You don't need place() if you're going to use pack().\nUse one or the other (I prefer pack()) - and it's always a good idea to declare your widgets on one line, then add them to a geometry manager on ano... | [
2
] | [] | [] | [
"python",
"tkinter",
"tkinter_canvas"
] | stackoverflow_0074535832_python_tkinter_tkinter_canvas.txt |
Q:
How do I convert this list of dictionaries to a csv file?
I have a list of dictionaries that looks something like this:
toCSV = [{'name':'bob','age':25,'weight':200},{'name':'jim','age':31,'weight':180}]
What should I do to convert this to a csv file that looks something like this:
name,age,weight
bob,25,200
jim,... | How do I convert this list of dictionaries to a csv file? | I have a list of dictionaries that looks something like this:
toCSV = [{'name':'bob','age':25,'weight':200},{'name':'jim','age':31,'weight':180}]
What should I do to convert this to a csv file that looks something like this:
name,age,weight
bob,25,200
jim,31,180
| [
"import csv\n\nto_csv = [\n {'name': 'bob', 'age': 25, 'weight': 200},\n {'name': 'jim', 'age': 31, 'weight': 180},\n]\n\nkeys = to_csv[0].keys()\n\nwith open('people.csv', 'w', newline='') as output_file:\n dict_writer = csv.DictWriter(output_file, keys)\n dict_writer.writeheader()\n dict_writer.wri... | [
440,
35,
18,
9,
2,
2,
1,
1
] | [] | [] | [
"csv",
"data_conversion",
"dictionary",
"python"
] | stackoverflow_0003086973_csv_data_conversion_dictionary_python.txt |
Q:
Vectors and Matrices from the NumPy Module
In python, how to write program that create two 4 * 4 matrices A and B whose elements are random numbers. Then create a matrix C that looks like
C = ⎡A B⎤
⎣B A⎦
Find the diagonal of the matrix C. The diagonal elements are to be presented in a 4 * 2 matrix.
import num... | Vectors and Matrices from the NumPy Module | In python, how to write program that create two 4 * 4 matrices A and B whose elements are random numbers. Then create a matrix C that looks like
C = ⎡A B⎤
⎣B A⎦
Find the diagonal of the matrix C. The diagonal elements are to be presented in a 4 * 2 matrix.
import numpy as np
matrix_A = np.random.randint(10, size=... | [
"The construction\nmatrix_C = np.array([[matrix_A, matrix_B], [matrix_B, matrix_A]])\n\ndoes not concatenate matrices, but creates 4th order tensor (put matrices inside matrix). You can check that by\nprint(matrix_C.shape) # (2, 2, 4, 4)\n\nTo lay out blocks call np.block, then all other parts of your code should... | [
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074534575_numpy_python.txt |
Q:
Logging setLevel is being ignored
The below code is copied from the documentation. I am supposed to be able to see all the info logs. But I don't. I am only able to see the warn and above even though I've set setLevel to INFO.
Why is this happening? foo.py:
import logging
logger = logging.getLogger(__name__)
logg... | Logging setLevel is being ignored | The below code is copied from the documentation. I am supposed to be able to see all the info logs. But I don't. I am only able to see the warn and above even though I've set setLevel to INFO.
Why is this happening? foo.py:
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.debu... | [
"Replace the line\nlogger.setLevel(logging.DEBUG)\n\nwith\nlogging.basicConfig(level=logging.DEBUG, format='%(message)s')\n\nand it should work as expected. If you don't configure logging with any handlers (as in your post - you only configure a level for your logger, but no handlers anywhere), you'll get an intern... | [
68,
49,
40,
5,
3,
2,
1,
1,
1,
0
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0043109355_logging_python.txt |
Q:
How do I sort a class with multiple attributes?
Suppose I have a class named Fish. now I would ask for a user input to give the name and the size of the fish. now, How can I sort those input values by the size attribute(in decreasing order) and then the name attribute(alphabetically)?
class Fish:
def __init__(s... | How do I sort a class with multiple attributes? | Suppose I have a class named Fish. now I would ask for a user input to give the name and the size of the fish. now, How can I sort those input values by the size attribute(in decreasing order) and then the name attribute(alphabetically)?
class Fish:
def __init__(self, size, name):
self.size:int = int(size)
... | [
"In order to override or declare sorting for an object, you should override the comparison operators. You need to specify one of (=, !=) and one of (>, <).\nclass Fish:\n def __init__(self, size, name):\n self.size = int(size)\n self.name = name\n\n def __eq__(self,other):\n return self.siz... | [
0
] | [] | [] | [
"class",
"object",
"python"
] | stackoverflow_0074535681_class_object_python.txt |
Q:
I want to create a code in python or Matlab to divide a sequence into pairs and give the values to these pairs
I want to create a program in python or Matlab to divide a sequence into pairs such that first letter pairs with all other letters and give the values to these pairs. Example
"ABCBADD"
AB=1
AC=1/2
AB=1/3
... | I want to create a code in python or Matlab to divide a sequence into pairs and give the values to these pairs | I want to create a program in python or Matlab to divide a sequence into pairs such that first letter pairs with all other letters and give the values to these pairs. Example
"ABCBADD"
AB=1
AC=1/2
AB=1/3
AA=1/4
AD=1/5
AD=1/6
Now skip first letter of sequence
"BCBADD"
BC=1
BB=1/2
BA=1/3
BD=1/4
BD=1/5
Now skip first and ... | [
"you could do with two loop:\ns = \"ABCBADD\" \noutput = [(s[i] + c, 1 /(idx + 1)) for i in range(len(s) -1) for idx, c in enumerate(s[i+1:])]\n\noutput:\nprint(output)\n\n[('AB', 1.0),\n ('AC', 0.5),\n ('AB', 0.3333333333333333),\n ('AA', 0.25),\n ('AD', 0.2),\n ('AD', 0.16666666666666666),\n ('BC', 1.0),\n ('... | [
1
] | [] | [] | [
"function",
"loops",
"matlab",
"python",
"python_3.x"
] | stackoverflow_0074535788_function_loops_matlab_python_python_3.x.txt |
Q:
Deploy a flask app in using Cloudera Application
I have been using the following python 3 script in a CDSW session which run just fine as long as the session is not killed.
I am able to click on the top-right grid and select my app
hello.py
from flask import Flask
import os
app = Flask(__name__)
@app.route('/')... | Deploy a flask app in using Cloudera Application | I have been using the following python 3 script in a CDSW session which run just fine as long as the session is not killed.
I am able to click on the top-right grid and select my app
hello.py
from flask import Flask
import os
app = Flask(__name__)
@app.route('/')
def index():
return 'Web App with Python Flask!'
... | [
"As it mentions here maybe you need to change this line of code\napp.run(host=os.getenv(\"CDSW_IP_ADDRESS\"), port=int(os.getenv('CDSW_PUBLIC_PORT')))\n\nto this\napp.run(host=\"127.0.0.1\", port=int(os.environ['CDSW_APP_PORT']))\n\nHope it works!\n"
] | [
0
] | [] | [] | [
"cdsw",
"cloudera",
"flask",
"python"
] | stackoverflow_0072126030_cdsw_cloudera_flask_python.txt |
Q:
How to remove excess whitespaces in entire python dataframe columns
What is the pythonic way of removing all excess whitespaces in a dateframe(all the columns). I know the method .str.strip() can be used for single column or for each column. The dataframe as many columns as such I would like to apply the method on... | How to remove excess whitespaces in entire python dataframe columns | What is the pythonic way of removing all excess whitespaces in a dateframe(all the columns). I know the method .str.strip() can be used for single column or for each column. The dataframe as many columns as such I would like to apply the method on the entire dataframe.
The whitespaces occur at different points, beginni... | [
"You could use apply:\ndf = df.applymap(lambda x: \" \".join(x.split()) if isinstance(x, str) else x)\n\n",
"An idea would be to do a combination of:\n\nregex to remove duplicate spaces (e.g \" James Bond\" to \" James Bond\")\nstr.strip to remove leading/trailing spaces (e.g \" James Bond\" to \"James Bond\"... | [
2,
0
] | [
"This works for me, seems shorter and cleaner:\ndf[col] = df[col].str.replace(' ','')\n\nYou can use it to replace any string items in the column values.\n"
] | [
-1
] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0070770016_dataframe_pandas_python.txt |
Q:
penalty in multitrip vrp if different vehicle visits a destination in 2nd trip ORTOOLS
I have implemented multitrip (Allow vehicles to visit a destination more than once) VRP using ortools. This has been done by duplicating nodes for destinations and introducing virtual depots with negative loads.
I want same vehi... | penalty in multitrip vrp if different vehicle visits a destination in 2nd trip ORTOOLS | I have implemented multitrip (Allow vehicles to visit a destination more than once) VRP using ortools. This has been done by duplicating nodes for destinations and introducing virtual depots with negative loads.
I want same vehicle to visit destinations in 2nd trip which visited that destination in 1st trip. This is a ... | [
" /// Adds a soft constraint to force a set of variable indices to be on the\n /// same vehicle. If all nodes are not on the same vehicle, each extra vehicle\n /// used adds 'cost' to the cost function.\n void AddSoftSameVehicleConstraint(const std::vector<int64_t>& indices,\n ... | [
1
] | [] | [] | [
"or_tools",
"python",
"vehicle_routing"
] | stackoverflow_0074531066_or_tools_python_vehicle_routing.txt |
Q:
Change default constructor argument value (inherited from parent class) in subclass
I have a Parent class with a default value for the attribute arg2. I want to create a subclass Child which has a different default value for the same attribute.
I need to use *args and **kwargs in Child.
I tried the following, but ... | Change default constructor argument value (inherited from parent class) in subclass | I have a Parent class with a default value for the attribute arg2. I want to create a subclass Child which has a different default value for the same attribute.
I need to use *args and **kwargs in Child.
I tried the following, but it is not working:
class Parent(object):
def __init__(self, arg1='something', arg2='o... | [
"You need to set the default in kwargs before passing it on to super(); this is tricky as you need to ensure that the same value is not already in args too:\nclass Child(Parent):\n def __init__(self, *args, **kwargs):\n if len(args) < 2 and 'arg2' not in kwargs:\n kwargs['arg2'] = 'new value'\n... | [
3,
2,
0
] | [] | [] | [
"arguments",
"constructor",
"python",
"subclass"
] | stackoverflow_0041623464_arguments_constructor_python_subclass.txt |
Q:
How to select a subset of rows based on a specific range in Python
I have a dataset that contains information about commits.
The dataset is quite similar to this:
commit
bug
sha_1
Stable
sha_2
Stable
sha_3
Stable
sha_4
Increase
sha_5
Stable
sha_6
Stable
sha_7
Decrease
sha_8
Stable
sha_9
Decrease
sha_10
... | How to select a subset of rows based on a specific range in Python | I have a dataset that contains information about commits.
The dataset is quite similar to this:
commit
bug
sha_1
Stable
sha_2
Stable
sha_3
Stable
sha_4
Increase
sha_5
Stable
sha_6
Stable
sha_7
Decrease
sha_8
Stable
sha_9
Decrease
sha_10
Decrease
sha_11
Increase
sha_12
Stable
I need to ... | [
"Let's suppose I read the data from my csv file:\nimport pandas as pd\n\ndf = pd.read_excel('C:\\\\Users\\\\...\\\\Desktop\\\\Workbook1.xlsx')\n\nkeep = []\nfor i in range(1, len(df) - 1):\n previous = df.loc[i-1, \"bug\"]\n current = df.loc[i, \"bug\"]\n next = df.loc[i+1, \"bug\"]\n\n if previous != \... | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074535224_dataframe_pandas_python.txt |
Q:
Invalid Syntax jose.py
I was trying to use jose library for authentication for one of my flask apps.
using the import statement as follows
from jose import jwt
But it throws following An error,
Traceback (most recent call last):
File "F:/XXX_XXX/xxxx-services-web/src/auth.py", line 6, in <module>
from jo... | Invalid Syntax jose.py | I was trying to use jose library for authentication for one of my flask apps.
using the import statement as follows
from jose import jwt
But it throws following An error,
Traceback (most recent call last):
File "F:/XXX_XXX/xxxx-services-web/src/auth.py", line 6, in <module>
from jose import jwt
File "F:\Us... | [
"installing python-jose instead of jose fixed my problem.\nhttps://pypi.org/project/python-jose/\n",
"One solution is to install python-jose instead of installing jose.\nApart from that you can use import python_jwt as jwt instead of from jose import jwt and install the package via pip install python-jwt\n"
] | [
20,
0
] | [] | [] | [
"jose",
"python"
] | stackoverflow_0065102969_jose_python.txt |
Q:
How to start another thread without waiting for function to finish?
Hey I am making a telegram bot and I need it to be able to run the same command multiple times at once.
dispatcher.add_handler(CommandHandler("send", send))
This is the command ^
And inside the command it starts a function:
sendmail(email, amount... | How to start another thread without waiting for function to finish? | Hey I am making a telegram bot and I need it to be able to run the same command multiple times at once.
dispatcher.add_handler(CommandHandler("send", send))
This is the command ^
And inside the command it starts a function:
sendmail(email, amount, update, context)
This function takes around 5seconds to finish. I want... | [
"This is my first attempt at threading, but maybe try this:\nimport threading\nx1 = threading.Thread(target=sendmail, args=(email, amount, update, context))\nx1.start()\n\nYou can just put the x1 = threading... and x1.start() in a loop to have it run multiple times\nHope this helps\n",
"It's not waiting for one f... | [
1,
0
] | [] | [] | [
"multithreading",
"python",
"telegram"
] | stackoverflow_0074535815_multithreading_python_telegram.txt |
Q:
How to enable autoscrolling to bottom for wx.html.HtmlWindow
I am using wxPython and want my HtmlWindow to scroll down automatically after adding new content. I am using it as a log window inside my app. Unfortunately, I am struggling to get it working. Here is my sample with lacks the functionality:
import wx
imp... | How to enable autoscrolling to bottom for wx.html.HtmlWindow | I am using wxPython and want my HtmlWindow to scroll down automatically after adding new content. I am using it as a log window inside my app. Unfortunately, I am struggling to get it working. Here is my sample with lacks the functionality:
import wx
import wx.html
class GUI(wx.Frame):
def __init__(self, parent)... | [
"Arguably wx.html.HtmlWindow is the wrong tool to use.\nYou'd have to insert Anchors and then leap to each Anchor.\nFor a log, it's better to use a wx.TextCtrl e.g.\nimport wx\nimport time\n\nclass GUI(wx.Frame):\n\n def __init__(self, parent):\n super().__init__(parent)\n self.log = wx.TextCtrl(se... | [
0
] | [] | [] | [
"python",
"wxhtmlwindow",
"wxpython"
] | stackoverflow_0074534631_python_wxhtmlwindow_wxpython.txt |
Q:
When trying to position elements in tkinter all elements are moved
I'm using tkinter to create a very simple GUI just to start learning how to use the module. However I'm trying to position two elements (a button and a text box). To position the elements I'm using the grid function, however I have used grid for bo... | When trying to position elements in tkinter all elements are moved | I'm using tkinter to create a very simple GUI just to start learning how to use the module. However I'm trying to position two elements (a button and a text box). To position the elements I'm using the grid function, however I have used grid for both the button and the textbox and it seems that both elements are affect... | [
"Does this help? You used too many namespace tkinter. I added gui widget for Button I also added tb.grid for row and column.\nCode:\nimport tkinter as tk\nfrom tkinter import ttk\ngui = tk.Tk()\ngui.geometry(\"600x800\")\nbutton = ttk.Button(gui, text=\"button\")\nbutton.grid(row=1, column=1,ipady=30, ipadx=30)\nlo... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0072139023_python_tkinter.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.