Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Posts tagged python
Suppose I have some code in a file myscript.py like: def my_function(): print("Test") What steps do I need to take in order to make my_function run? That is to say: how do I get Python to ...
Sometimes when I try to install a third-party library for Python, I get an error saying that either distutils, or some part of it like distutils.core or distutils.util, could not be found. It's sho...
I have to modify a legacy Django web application where there are 2 tables to store the same information using the same database structure, and the only difference is the names of the tables (and th...
When you try to do a privileged systemd operation without the privilege, you get an escalation prompt: $ systemctl stop docker ==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-units ==== ...
A jinja template expression starts and ends with double curly brackets, which the templating engine consumes. But what if you need a single pair of curly brackets left in the output? Something lik...
I have a flat list where each item is the key and value for an attribute. I want to transform this into a nested list where each attribute is a sublist. Example input: [ "attr1 apple 1", "a...
Suppose I have some code like: filename = "bad_dir" print(f"File not found: {filename}.") raise(FileNotFoundError) When the exception isn't caught, the stack trace is printed at the end of ...
I have a Python script that needs to access some data (or configuration) file in its very own folder. For example, say script.py does something like this: with open('data.txt') as file: data ...
The problem Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets are closed by ...
Here's a JSON log formatter for Python. I want to be able to log details of exceptions (and have some capability to debug-by-logs). I want to be able to log extra data in JSON format (in addition...
I ran some Python code and it crashed with ModuleNotFoundError. What is the general approach for dealing with these situations?
--- Here is the error message. Traceback (most recent call last): File "c:\Users\19185\Documents\GitHub\Chatty\Chatty\one_.py", line 3, in import azure.cognitiveservices.speech as speechsdk Mo...
I need to use azure.cognitiveservices.speech. However I am getting this error: Here is code on replit it produces the same error. https://replit.com/@mystickain420/Chatty main -- https://githu...
PEP20 aka the Zen of Python has a statement: Namespaces are one honking great idea -- let's do more of those! What exactly are we supposed to "do" according to this? Is it saying we should h...
Sometimes code needs to assign (or otherwise use) a value that depends on some condition. The naive approach is to use explicit branching, which in Python would look like: if some_condition(): ...
Consider this code example: def example(param=[]): param.append('value') print(param) When example is repeatedly called with an existing list, it repeatedly appends to the list, as ...
The following list comprehension worked when I tried it: [num for num in hand if num != 11] But this doesn't work: [num for num in hand if num != 11 else 22] It gives a SyntaxError, highlightin...
Suppose you have a jinja template like this: I am going to {{ foo }} to get some {{ bar }}. I hope I can find: {% for i in baz %} - {{i}} {% endfor %} This template will require you to pass ...
print() normally adds text to STDOUT, it does not erase existing text. https://linux.codidact.com/posts/289869 describes various ways of doing the overwrite in shell scripts. How can you do this ...
In VS Code, is it possible to run Python code on the text being edited? I realize that I can save my text, create a .py file, switch to a terminal (including VS Code's own terminal) and run the .p...
MWE import random import pandas as pd from itertools import product random.seed(12345) dies = [1, 2] cells = list(range(10)) currents = [100, 200, 300] dcc = list(product(dies, ce...
Is there a Python serialization format that has capabilities similar to Pickle, but is text based? The problem I always have with pickle is that it's binary, so I can't manually view or edit the d...
Background Many Python programs now recommend installing with pipx, and there is a sense that you shouldn't install with pip anymore, you should use tools like pipx. Main Question However, what ...
I regularly run into the problem that I have a Python function that I want to use in both, eager and graph execution mode. I therefore have to adjust the code so that it can handle both situations....
TL;DR Is (a and b) equivalent to tf.logical_and(a, b) in terms of optimization and performance? (a and b are tensorflow tensors) Details I use Python with Tensorflow. My priorities are Make t...
I have a Python program like this: done = False while u and not done: i = u.pop() print(f"Processing {i}") do_big_task(i) finish_up() Since this takes a long time, the user m...
I would like to use tf.timestamp() when it is available (eager mode and graph mode without XLA), and use 0. (or a better fallback if there is one) when it is not available (with XLA; @tf.function(j...
When running various Python scripts, I often need to do this annoying dance: $ python script.py ... ModuleNotFoundError: No module named 'foo' $ pip install foo $ python script.py ... Module...
I want my CLI Python program to schedule a task, and then exit. After some times has passed (say 10 minutes) the task should execute. The task can be a Python method or a shell command, whatever i...
I am writing a Python package where I have two classes in different files that (indirectly) depend on each other. If I wouldn't care about type-hints, there would be no problem, but unfortunately,...
Is it possible for a Python program to send itself in the background? For example, on Linux you can do nohup some_cmd & and any program will run in the background. Some programs also support s...
I have the following xarray Dataset: d: <xarray.Dataset> Dimensions: (x: 79, y: 63, t: 1) Coordinates: * x (x) float64 0.9412 1.882 2.824 3.765 ... 71.53 72.47 73.41 74.35 * ...
In Python, multiprocessing is easy to do if you follow a "list projection" paradigm. Say you want to take a list of inputs X and apply some function f to every x_i, such that y_i = f(x_i) and the y...
Suppose I have some variables like: >>> count = 8 >>> status = 'off' I want to combine them with some hard-coded text, to get a single string like 'I have 8 cans of Spam®; b...
I know that I can display a single string in the terminal window like print("example") (or similarly with a string in a variable), and I know how to open text files and write to them. I also know ...
Suppose I have two variables that are called animal and age, and print them as a string in the console like so: animal = "giraffe" age = 25 print("A %s can live up to %d years" %(animal,age)) ...
Problem How can I compress each column of a dataframe to the output of a function (i.e., mean), preserving columns? MWE import pandas as pd data = {"A": [1, 2, 3, 4], "B": [5, 6, 7, 8]} ...
I have a function that loads JSON data and is declared to return a dictionary with string keys and values of any type (Dict[str, Any]). However, mypy is raising an error stating that I am returning...
Is there a way to add support for "move symbol" in Python code for VS Codium? PyCharm can do this, but I am looking for a VSC solution. PyLance can do this, but PyLance itself is closed source, a...
In the last few months, AI has advanced considerably, notably in the area of generating images. We now have powerful models like DALL-E, Stable Diffusion, etc. These are quite competent at generati...
I am working on adding uncertainty to some of my dynamics within a larger Monte Carlo simulation. As a way to perform multiple operations on each value, I decided to make and use a new function to ...
I'm experiencing an issue where my program appears to freeze when executing the post_comments_to_lemmy function. This function fetches comments from the GitHub API and posts them to a Lemmy instanc...
I want a way to make it so that I can use list B to find out if a copy of itself exists in list A. listA = ['1', '1', '0', '1', '0', '1', 'down'] 2 ['0', '0', '1', '1', '1', '1', 'up'] 2 ['1', '...
Question What is the current state of the art database app? How does it compare to SQL? Can pandas be used in place of either? If not, is there something that bridges the gap between SQL and pand...
I have a dataset of car bookings like this: car_id user_id 1 1 2 1 1 2 3 3 1 2 3 3 In this dataset, two separate groups/sets of cars and users...
When I run pip install foo, pip looks for foo in PyPi. I want it to look for it first in a private repo, let's say pypi.bar.com. Only if foo cannot be found in pypi.bar.com, should pip then look f...
When I set up my object mappings with SQLalchemy, everything works well enough. It even creates the tables for me if they don't exist. However, if I decide to add/remove columns (aka fields) from ...
I'm trying to subclass pdb to have a debugger that, in case of a call to a decorated function, can "step in" the decorated function directly and skip the decorator content altogether. A well-behave...
Using parentheses in Javascript is always needed when you want to create functions, if/else statements and for/while loops. But in Python it has a function that is called tuples. When using an if s...
The dictionary methods .keys(), .values(), and .items() all return view objects. Said objects reflect any changes to the underlying dictionary. This is often useful. Is there a way to get such a v...