text stringlengths 1 2.12k | source dict |
|---|---|
java, dice
}
Dice class:
import java.util.Random;
public class Dice {
private final static int numberOfSides = 6;
int rollDice() {
int result;
Random randomNumberGenerator = new Random();
result = randomNumberGenerator.nextInt(numberOfSides) + 1;
return result;
}
} | {
"domain": "codereview.stackexchange",
"id": 43290,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, dice",
"url": null
} |
java, dice
Program specification:
For this assignment you will write a program that simulates a rather
simplistic Dice Throwing Game. This section specifies the required
functionality of the program. Only a text interface is required for
this program; however, more marks will be gained for a program that is
easy/intuitive to use, with clear information/error messages to the
user.
The aim of the Dice Throwing Game is to simulate a simple game
for 2 players, where they take turn to each roll a dice twice, and
score points according to the results of the dice rolls. The winner is
the one who accumulates a pre-defined maximum score first. Your
program will display a menu which allows the user of the program to
select various options to simulate the various operations. Results of
all the operations will be printed on the screen as plain text only
(eg. “Andy rolled 5 + 3, and scored 8 points”).
The “dice rolls” are
simulated by the program, using some random number generator. The
program will update each player's current score accordingly. For this
assignment, the program will only handle TWO players. It will keep
track of the current score of the players until one, or both, reaches
the pre-defined maximum score, agreed upon at the start of the game.
Program Logic:
The Dice Throwing Game begins with a welcome message followed by a
menu with the following options :
Option (1) asks the 2 players to
enter their names. A player’s name must not be blank (or consists of
only spaces and nothing else), but may contain spaces between the
characters. If this option is chosen again after the players have
already been set up, 2 "new" players are set up (ie. with 2 new names,
and both their starting scores set to 0). Note that the new players
replace the previous players – there are only ever two players at any
one time.
After the names are set up, the game asks for a maximum
score. The default maximum score should be set to 200 points. Each
player’s initial score is set to 0. | {
"domain": "codereview.stackexchange",
"id": 43290,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, dice",
"url": null
} |
java, dice
player’s initial score is set to 0.
Option (2) simulates the “dice
roll” operations for both players. When this option is chosen, the
computer generates 4 random numbers between 1-6 (ie. simulating a
6-sided dice), representing 2 dice rolls for each player. It then
updates both players' scores accordingly. The scoring rules for each
"round" are as follows : | {
"domain": "codereview.stackexchange",
"id": 43290,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, dice",
"url": null
} |
java, dice
if the 2 dice rolls have the same value
(ie. 1&1, 2&2, …, 6x6), the player scores 2 times the sum of that
value (eg. 1&1 scores 4 points, 2&2 scores 8 points, etc)
if the 2
dice rolls have different values, the player simply scores the sum of
that value (eg. 1&4 scores 5 points, 5&2 scores 7 points, etc)
if
both players reaches a score which is more than the pre-defined
maximum, the game’s result is a Draw. note that both players can
reach over that score at the same time, since for each round, 2 dice
rolls are performed for each player, before a winner is decided
a
player is considered a winner if he accumulates a score which is more
than the pre-defined maximum, and the other player has not reached
that score
Option (3) shows the players current scores, including who
is leading the game.
Option (4) displays some brief instructions
regarding how to play the game.
Option (5) exits the whole program.
All player statistics should be cleared.
Additional Notes :
The menu must be displayed repeatedly after each operation, until the
user chooses Option (5). Inputs other than 1-5 should be rejected,
with appropriate error messages printed.
If the user chooses Option
(2)/(3), before a game has been set up (Option (1)), an appropriate
error message should be printed, and the operation aborted.
Your
program must deal with invalid values entered by the user in a
sensible manner.
Answer: Awkward split of responsibilities
The displayGameMenu method prints a list of options.
This method is called from the main method,
which is also in charge of validating the input.
There are some issues with this: | {
"domain": "codereview.stackexchange",
"id": 43290,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, dice",
"url": null
} |
java, dice
The code of displayGameMenu and main are far away from each other: I have to scroll to see both. This is a problem because when I look at main it's not obvious what number 5 is. And when adding a new menu option, it's easily possible to forget to update one of the relevant locations.
The main method should simply call other methods, and have no logic of its own. The main method is designed for execution, not really a functional part of a class. As such, it is awkward that the responsibility of handling the menu is split between a member method (displayGameMenu) and a static method (main)
I suggest to reduce main to something like this:
public static void main(String[] args) {
new Game().run();
}
And I suggest to eliminate displayGameMenu, the code will be easier to understand if the menu options are easily visible next to the input validation code.
Limit the scope
In this code:
int optionSelected;
while (true) {
// ...
optionSelected = sc.nextInt();
The variable optionSelected is not needed outside of the loop.
So it's better to declare it inside:
while (true) {
// ...
int optionSelected = sc.nextInt();
Similarly, in playOneRound, you don't need to declare the result variable at the top, it's better to declare it in each of the branches of if-else.
Declare variables right before you need them
In startNewGame you declare p1Name and p2Name at the top.
That's unnecessary. It's better to declare them when you assign them,
for example:
String p1Name = sc.nextLine(); | {
"domain": "codereview.stackexchange",
"id": 43290,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, dice",
"url": null
} |
java, dice
It's ok to reuse Random
In Dice.rollDice, you recreate an instance of Random on every call.
This is unnecessary.
It would be more efficient to store a single instance in private final Random random and reuse it across calls to rollDice.
Naming
A name like setTotalScore(int score) sounds like a classic setter that sets the value of a field to the given value. But this method in Player doesn't set to this value, it appends this to the current value. So addScore would be more natural.
The convention for naming constants is SHOUT_CASE in Java. So numberOfSides in Dice should be named NUMBER_OF_SIDES. Actually I'd just call it simply SIDES.
The word "Dice" in the rollDice method of the Dice class is redundant:
the name of the class already implies that you're rolling a dice, not your eyes.
Pointless local variables
The result variable in Dice.rollDice is really unnecessary and tedious.
The method could be reduced to a single line:
int roll() {
return random.nextInt(SIDES) + 1;
}
Order of conditions
Instead of this:
while (optionSelected > 5 || optionSelected < 0) {
It might be slightly more readable if the terms are in a consistent order:
while (optionSelected < 0 || 5 < optionSelected) {
Another alternative:
while (!(0 <= optionSelected && optionSelected <= 5)) {
Order of modifiers
In private final static int numberOfSides the modifiers are not in the conventional order. The recommended ordering is private static final. | {
"domain": "codereview.stackexchange",
"id": 43290,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, dice",
"url": null
} |
c, lexical-analysis
Title: Simple tokenizer in C
Question: I implemented a simple tokenizer. Would love to hear your feedback on code style, best practices:
#include <stdio.h>
#include "lexer.h"
#include "mem.h"
static inline int delimiter(char c);
char **lexer_tokenize(const char *s) {
char **rv, **tmp;
int i, j, k, len, cap;
cap = 4;
rv = mem_malloc(sizeof(char *) * cap);
for (i = 0, j = 0, len = 0;; j++) {
if (delimiter(s[j]) && i < j) {
if (len == cap - 1) {
cap <<= 1;
if ((tmp = mem_realloc(rv, sizeof(char *) * cap))) {
mem_free(rv);
rv = tmp;
} else {
mem_free(rv);
rv = 0;
fprintf(stderr, "tokenize: error resizing result array.\n");
break;
}
}
rv[len] = mem_malloc(sizeof(char) * (j - i + 1));
for (k = 0; (rv[len][k++] = s[i++]) != s[j];)
;
rv[len++][k] = 0;
if (!s[j])
break;
i = j + 1;
}
}
rv[len] = 0;
return rv;
}
static inline int delimiter(char c) {
return c == ' ' || c == '\n' || c == 0 || c == EOF;
}
Would also love to hear tips on performance improvements.
Answer: Apparent uniform formatting - good
Hope OP is using an auto-formatter.
Bug?
mem_free(rv) is suspicious. Is a free needed on successful re-allocation?
if ((tmp = mem_realloc(rv, sizeof(char *) * cap))) {
mem_free(rv); | {
"domain": "codereview.stackexchange",
"id": 43291,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, lexical-analysis",
"url": null
} |
c, lexical-analysis
Insufficient documentation
"a simple tokenizer" is insufficient to describe lexer_tokenize() functionality. I'd hope to see that in the not-included "lexer.h".
Sample usage would have been informative.
OP comments about punctuation symbols yet nothing in code suggests anything dealing with punctuation symbols.
O(n*n) vs. O(n)
With the nested loops code looks O(n*n). I'd expect a tokenizer to be O(n). As is, code is unclear to me.
EOF is not a character of a string
// return c == ' ' || c == '\n' || c == 0 || c == EOF;
return c == ' ' || c == '\n' || c == 0;
Consider any whitespace
'\t', '\r', '\f', '\v' are white-spaces too.
#include <ctype.h>
static inline int delimiter(char c) {
// return c == ' ' || c == '\n' || c == 0;
return isspace((unsigned char) c) || c == 0;
}
No checking for allocation failure
As mem_malloc() can return a failure indication, NULL, check for that and handle appropriately.
Declare objects when needed
// char **rv;
// ...
// rv = mem_malloc(sizeof(char *) * cap);
char **rv = mem_malloc(sizeof(char *) * cap);
Allocate to the refenced object, not the type
It is easier to code right, review and maintain.
// rv = mem_malloc(sizeof(char *) * cap);
char **rv = mem_malloc(sizeof rv[0] * cap);
// rv[len] = mem_malloc(sizeof(char) * (j - i + 1));
rv[len] = mem_malloc(sizeof rv[len][0] * (j - i + 1));
Validate "lexer.h" independence
I assume this code is in "lexer.c" and the lexer_tokenize() declaration is in "lexer.h".
Rather than include #include <stdio.h>, then #include "lexer.h", reverse that to test "lexer.h" has no need for prior includes.
int vs. size_t
int is not certainly wide enough. size_t is the type for any sizeof of an object or indexing. Note that size_t is an unsigned type.
// int i, j, k, len, cap;
size_t i, j, k, len, cap;
Informative names
i, j, k are not informative object names other than they are indexes - but how to they differ? What are they for? | {
"domain": "codereview.stackexchange",
"id": 43291,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, lexical-analysis",
"url": null
} |
algorithm, typescript, palindrome
Title: isPalindrom-function in TypeScript
Question: I have written an isPalindrom-Function in TypeScript.
const isPalindrom = (word: String): boolean => {
const mid = Math.floor(word.length / 2);
for (let i = 0; i < mid; i++) {
const left = word[i].toLocaleLowerCase();
const right = word[word.length - 1 - i]
.toLocaleLowerCase();
if (left != right) {
return false;
}
}
return true
}
["Anna", "AXnna",
"Kayak", "kayakx",
"LEVEL", "LEVExL",
"rotor", "roxtor",
"wow", "wxow",
"mom", "Ymom",
"rEpaPer", "repXaper"]
.forEach(word => {
console.log(`Is ${word} a Palindrom?
=> ${isPalindrom(word)}`);
});
Is my TypeScript-usage correct?
What could be improved concerning the algorithmic-approach?
I have used the double-equals operator, because the values can't be something else then strings. Is it still necessary to use the triple-equals operator in TypeScript?
Answer:
I have used the double-equals operator, because the values can't be something else then strings. Is it still necessary to use the triple-equals operator in TypeScript? | {
"domain": "codereview.stackexchange",
"id": 43292,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, typescript, palindrome",
"url": null
} |
algorithm, typescript, palindrome
This is backwards. Necessary? No. Recommended? Yes.
If you know the type is always going to be the same, you should use the triple-equals so as to save the extra checks to see if they are the same. I.e. the triple-equals is simpler than double-equals. Both have to check if the types are the same. With triple-equals, you can stop processing if not. With double-equals, differing types starts a more complicated round of type coercion.
More discussion: You Don't Know JS: Loose vs. Strict Equals
You use the double-equals when the types can be different but you want to coerce them into the same type for equality testing. For example, if 1 == '1'.
All that said, this is not a requirement. Functionally, your code will work with the double-equals. But if you're asking about best practices, then best practice is to use the triple-equals whenever you don't need the type-coercion. It's the double-equals that you should only use when needed. You should default to triple-equals unless it won't work for your use case (because you require type coercion).
Note that even if you do require type coercion, sometimes it is better to do the type coercion explicitly rather than use the loose rules of double-equals. But that won't make a difference here.
Personally, I would prefer to use two index variables rather than calculate one index value from the other.
const normalized = word.toLocaleLowerCase();
for (let left = 0, right = normalized.length - 1; left < right; left++, right--) {
if (normalized[left] !== normalized[right]) {
return false;
}
}
return true;
I find this simpler and easier to follow. Also, it is more easily expandable to cover more complicated normalization. E.g. the removal of punctuation and spaces. | {
"domain": "codereview.stackexchange",
"id": 43292,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, typescript, palindrome",
"url": null
} |
beginner, rust, tic-tac-toe
Title: Tic Tac Toe Module in Rust: Implementing "new"
Question: Intro
In order to get familiar with and improve my Rust skills I coded Tic-Tac-Toe. I want to write good Rust code, any feedback regarding why my code isn't in a Rust style or improvements that could be made would be very helpful.
Question
Is there a better way to implement my "new" method for the Ttt struct? I don't particularly like manually passing the array ['0', '1', '2', '3', '4', '5', '6', '7', '8'] to both board and options: Ttt::create_options(), but I haven't seen a way around doing it like that.
Code
lib.rs
pub mod tictactoe {
use std::collections::HashMap;
use std::io;
const BOARD_SIZE: usize = 9;
const P1: char = 'X';
const P2: char = 'O';
pub struct Ttt {
pub board: [char; BOARD_SIZE],
pub options: HashMap<usize, char>,
pub active_player: char,
pub game_over: bool,
pub winner: char,
}
impl Ttt {
fn create_options(board: [char; BOARD_SIZE]) -> HashMap<usize, char> {
let mut options = HashMap::new();
for space in 0..board.len() {
options.insert(space, board[space]);
}
return options;
}
// I feel like this needs improvement
pub fn new() -> Ttt {
Ttt {
board: ['0', '1', '2', '3', '4', '5', '6', '7', '8'],
options: Ttt::create_options(['0', '1', '2', '3', '4', '5', '6', '7', '8']),
active_player: P1,
game_over: false,
winner: ' ',
}
}
pub fn play(&mut self) -> char {
while !self.game_over {
self.print_board();
let pick = self.get_input();
self.options.remove(&pick);
self.board[pick] = self.active_player;
self.game_over = self.is_game_over(); | {
"domain": "codereview.stackexchange",
"id": 43293,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust, tic-tac-toe",
"url": null
} |
beginner, rust, tic-tac-toe
self.game_over = self.is_game_over();
if self.game_over {
self.winner = self.active_player;
} else {
self.switch_player();
}
}
self.print_board();
println!("\n{} is the winner!", self.winner);
return self.winner;
}
pub fn is_game_over(&self) -> bool {
if self.options.len() < 1 {
println!("It's a tie!");
return true;
}
if self.board[0] == self.board[1] && self.board[0] == self.board[2] {
println!("Top row win!");
return true;
}
if self.board[3] == self.board[4] && self.board[3] == self.board[5] {
println!("Middle row win!");
return true;
}
if self.board[6] == self.board[7] && self.board[6] == self.board[8] {
println!("Bottom row win!");
return true;
}
if self.board[0] == self.board[3] && self.board[0] == self.board[6] {
println!("Left column win!");
return true;
}
if self.board[1] == self.board[4] && self.board[1] == self.board[7] {
println!("Center column win!");
return true;
}
if self.board[2] == self.board[5] && self.board[2] == self.board[8] {
println!("Right column win!");
return true;
}
if self.board[0] == self.board[4] && self.board[0] == self.board[8] {
println!("Backslash win!");
return true;
}
if self.board[2] == self.board[4] && self.board[2] == self.board[6] {
println!("Forwardslash win!");
return true;
}
return false;
} | {
"domain": "codereview.stackexchange",
"id": 43293,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust, tic-tac-toe",
"url": null
} |
beginner, rust, tic-tac-toe
return false;
}
pub fn switch_player(&mut self) {
if self.active_player == P1 {
self.active_player = P2;
} else {
self.active_player = P1;
}
}
pub fn print_board(&self) {
println!(
" {} | {} | {} ",
self.board[0], self.board[1], self.board[2]
);
println!("-----------");
println!(
" {} | {} | {} ",
self.board[3], self.board[4], self.board[5]
);
println!("-----------");
println!(
" {} | {} | {} ",
self.board[6], self.board[7], self.board[8]
);
}
pub fn get_options(&self) -> &HashMap<usize, char> {
return &self.options;
}
pub fn get_input_ML(&self, choice: usize) -> usize {
return choice;
}
pub fn get_input(&self) -> usize {
println!("Choose a selection from the grid.");
loop {
let mut coord = String::new();
io::stdin()
.read_line(&mut coord)
.expect("Failed to read line");
let coord: usize = match coord.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("Please enter a valid selection.");
continue;
}
};
if !self.options.contains_key(&coord) {
println!("Please enter a valid selection.");
continue;
}
return coord;
}
}
}
}
main.rs
use ttt::tictactoe::Ttt;
fn main() {
let mut g = Ttt::new();
g.play();
}
Cargo.toml
[package]
name = "ttt"
version = "0.1.0"
edition = "2021" | {
"domain": "codereview.stackexchange",
"id": 43293,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust, tic-tac-toe",
"url": null
} |
beginner, rust, tic-tac-toe
Cargo.toml
[package]
name = "ttt"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
Any feedback is much appreciated. Thank you.
Answer: Just put it in a local value for brevity. That's it.
pub fn new() -> Ttt {
let board = ['0', '1', '2', '3', '4', '5', '6', '7', '8'];
Ttt {
board,
options: Ttt::create_options(board),
active_player: P1,
game_over: false,
winner: ' ',
}
}
Edit: and this looks fine to me, I'm not sure what kind of improvement you're looking for. I can't see any potential for clear improvement here. You may intialize options to an empty HashMap and update it after you construct the Ttt. That way, you wouldn't pass anything explicitly.
You may determine whether the game is a tie earlier, when there is one vacant square rather than with no remaining vacant squares. I leave that as a potential exercise for you.
I feel like you should abandon this implementation of options and use board as the only source of info about the board.
I would do vacant_coords.
fn vacant_coords(&self) -> impl Iterator<Item=usize> + '_ {
self.board.iter().enumerate().filter_map(|(i, &ch)| {
if ch == P1 || ch == P2 {
None
} else {
Some(i)
}
})
}
Use that to check for number of vacant coords
if self.vacant_coords().count() == 0 {
println!("It's a tie!");
return true;
}
Use that to check whether input is a vacant coord
if !self.vacant_coords().find(|&i| i == coord).is_some() {
println!("Please enter a valid selection.");
continue;
} | {
"domain": "codereview.stackexchange",
"id": 43293,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust, tic-tac-toe",
"url": null
} |
python, python-3.x, object-oriented
Title: Class to calculate values of equation ρ = m / v
Question: Function:
This is to calculate the values for the equation:
$$\rho = \frac{m}{v} = \frac{mass}{volume}$$
what I need help with:
I still can’t get my head around classes and want to know if I’m doing them right any suggestions are most welcome.
Code:
from decimal import Decimal
from dataclasses import dataclass
@dataclass
class Pmv:
den: float
vol: float
mass: float
def get_vol(self) -> Decimal:
return round(
Decimal(
self.mass
) /
Decimal(
self.den
), 2
)
def get_den(self) -> Decimal:
return round(
Decimal(
self.mass
) *
Decimal(
self.vol
), 2
)
def get_mass(self) -> Decimal:
return round(
Decimal(
self.den
) /
Decimal(
self.vol
), 2
)
vol = Pmv(6.2, 0, 2.1)
print(vol.get_vol())
den = Pmv(0, 3.1, 4.8)
print(den.get_den())
mass = Pmv(8.9, 2.2, 0)
print(mass.get_mass())
Output:
0.34
14.88
4.05
Goal:
If I have gotten this right I’m going to make a class for a lot of chemistry equations which would simplify my calculations for me. | {
"domain": "codereview.stackexchange",
"id": 43294,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, object-oriented",
"url": null
} |
python, python-3.x, object-oriented
Answer: This is not a good application of a class. You will never have all three members to initialise the class, so they all have to be marked Optional. Your class does nothing to stop someone from making an "overdetermined" instance where all three members are set and one of them is wrong. And once you do have an instance, you'll have three different members where you only care about two, and three different methods when you only care about one.
Don't round() in the middle of calculations. Only do that upon presentation, as implied by the decimal precision field in a formatting call.
A function that fills in the gap could look like
from decimal import Decimal
from typing import Optional
def solve_density(
density: Optional[Decimal] = None,
volume: Optional[Decimal] = None,
mass: Optional[Decimal] = None,
) -> Decimal:
# density = mass / volume
if density is None:
return mass / volume
if volume is None:
return mass / density
if mass is None:
return density * volume
def test() -> None:
volume = solve_density(density=Decimal('0.02'), mass=Decimal('0.1'))
print(f'volume = {volume:.2f}')
if __name__ == '__main__':
test()
This still has the over-determined problem. It doesn't offer any advantages over just having three separate, purpose-built functions, each accepting only two parameters.
There is a very different approach that:
requires installing and importing Sympy;
does not require that you re-express the equation for every output;
is a slightly better use-case for a class;
captures some of the physical constraints of your variables - they're non-negative, real, and finite; and
is overkill for some applications but convenient for others: | {
"domain": "codereview.stackexchange",
"id": 43294,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, object-oriented",
"url": null
} |
python, python-3.x, object-oriented
Define a class that holds a dictionary of symbols, and the equation in question. At solution time, call a single method passing in your knowns as kwargs and getting back your unknown as a float.
This has a certain amount of in-built validation - it will bomb out if you pass unknown variables, the wrong number of variables, or variables that produce a mathematical domain problem.
from sympy import Equality, solve, Symbol
def real(name: str) -> Symbol:
return Symbol(name=name, real=True, finite=True, nonnegative=True)
class DensitySystem:
def __init__(self) -> None:
p = real('p')
m = real('m')
v = real('v')
self.symbols = {s.name: s for s in (p, m, v)}
self.equation = Equality(p, m*v)
def solve(self, **kwargs: float) -> float:
unknown, = self.symbols.keys() - kwargs.keys()
solved, = solve(self.equation, self.symbols[unknown])
value = solved.subs({
self.symbols[k]: known
for k, known in kwargs.items()
})
return float(value)
def test() -> None:
system = DensitySystem()
v = system.solve(p=1, m=2)
print(f'v={v:.2f}')
if __name__ == '__main__':
test() | {
"domain": "codereview.stackexchange",
"id": 43294,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, object-oriented",
"url": null
} |
python, python-3.x, parsing, regex, pandas
Title: Regex and pandas to read forecast sky condition string
Question: DataFrame methods to parse the sky condition from a terminal aerodrome forecast.
A line in a taf can report zero-eight cloud layers. Cloud layers are required in predominate lines, and optional in temporary ones. Cloud cover SKC|FEW|SCT|BKN|OVC is associated to an octave value. 1, 3, 5, 8 as the min sky coverage for reporting a layer.
I struggled to find a pure regex solution to generate the the pattern I needed for repeating capture groups. Hence the _unpack_setup function
from typing import Iterable
import re
import pandas as pd
import numpy as np
TAF = """
KGCC 282320Z 2900/2924 09010KT P6SM -SHRA BKN070 OVC250
FM290300 24011KT P6SM OVC040
TEMPO 2903/2906 4SM -SHRA FEW010 FEW015 BKN020TCU OVC025
FM291000 18009KT 3SM -TSRA BR OVC004CB
FM291900 31022G33KT 6SM -SHRA OVC011
"""
OCTAVE_INDEX = pd.Series(
(np.inf, 1, 3, 5, 8, np.nan), index=["SKC", "FEW", "SCT", "BKN", "OVC", np.nan]
)
def _unpack_setup():
base = r"(SKC|FEW|SCT|BKN|OVC)(\d{3})?(CB|TCU)?\s?"
layers = f"(?:{base})?" * 7
columns = pd.Series(["CloudCover", "CloudBase", "Flags"])
return (
re.compile(base + layers, re.VERBOSE),
pd.concat(columns + str(i) for i in range(1, 9)),
)
celestial_dome, cloud_columns = _unpack_setup()
def unpack_index(index: pd.Index, *args: str) -> Iterable[pd.Index]:
for col in args:
yield index[index.str.contains(col)]
def octave(sky_coverage: pd.Series) -> np.ndarray:
"""octave indexer"""
return OCTAVE_INDEX[sky_coverage].values
def get_sky_condition():
"""creates sky condtion dataframe"""
series = pd.Series(re.split(r"(?:\s(?=BECMG|TEMPO|FM))", TAF.strip())).str.strip()
sky_condition: pd.DataFrame = (
series.str.extract(celestial_dome)
.set_axis(cloud_columns, axis=1)
.dropna(axis=1, how="all")
) | {
"domain": "codereview.stackexchange",
"id": 43295,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, parsing, regex, pandas",
"url": null
} |
python, python-3.x, parsing, regex, pandas
column_base, column_cover = unpack_index(
sky_condition.columns, "CloudBase", "CloudCover"
)
sky_condition[column_base] = sky_condition[column_base].astype(float) * 100
sky_condition[column_cover] = sky_condition[column_cover].apply(octave)
print(sky_condition)
if __name__ == "__main__":
get_sky_condition()
results
CloudCover1 CloudBase1 Flags1 CloudCover2 CloudBase2 CloudCover3 CloudBase3 Flags3 CloudCover4 CloudBase4
0 5.0 7000.0 NaN 8.0 25000.0 NaN NaN NaN NaN NaN
1 8.0 4000.0 NaN NaN NaN NaN NaN NaN NaN NaN
2 2.0 1000.0 NaN 2.0 1500.0 5.0 2000.0 TCU 8.0 2500.0
3 8.0 400.0 CB NaN NaN NaN NaN NaN NaN NaN
4 8.0 1100.0 NaN NaN NaN NaN NaN NaN NaN NaN
Answer: At the start of get_sky_condition(), I don't see why you do a .str.strip() when defining series:
series = pd.Series(re.split(r"(?:\s(?=BECMG|TEMPO|FM))", TAF.strip())).str.strip()
I think that this should suffice?
series = pd.Series(re.split(r"(?:\s(?=BECMG|TEMPO|FM))", TAF.strip()))
For the regular expression, you could take advantage of named capture groups to avoid having to call .set_axis(cloud_columns, axis=1) to name the columns.
def cloud_layers_re() -> re:
layer_re_fmt = \
r"(?P<CloudCover{0}>SKC|FEW|SCT|BKN|OVC)" \
r"(?P<CloudBase{0}>\d{{3}})?" \
r"(?P<Flags{0}>CB|TCU)?"
return re.compile(
layer_re_fmt.format(1) +
"".join("(?:\s+" + layer_re_fmt.format(i) + ")?" for i in range(2, 9))
)
⋮
def get_sky_condition():
"""creates sky condtion dataframe"""
series = pd.Series(re.split(r"(?:\s(?=BECMG|TEMPO|FM))", TAF.strip())) | {
"domain": "codereview.stackexchange",
"id": 43295,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, parsing, regex, pandas",
"url": null
} |
python, python-3.x, parsing, regex, pandas
sky_condition: pd.DataFrame = (
series.str.extract(cloud_layers_re())
.dropna(axis=1, how="all")
)
⋮
Since get_sky_condition() is named like a getter function, I'd expect that it returns its result rather than printing it. | {
"domain": "codereview.stackexchange",
"id": 43295,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, parsing, regex, pandas",
"url": null
} |
vba, file-system, ms-access
Title: Recursive function designed to ensure that full folder path exists before copying a file to the location
Question: My recursive function works, but I feel it could be improved... suggestions? The code ensures that a given folder path exists by checking its validity or creating them if they don't already exist, so that afterwards I can, for example copy a file to the location.
Function EnsureFolderPath(strP As String) As Boolean
On Error GoTo EnsureFolderPath_Error
Dim strParent As String
Dim fso As FileSystemObject
Set fso = New FileSystemObject
If Len(fso.GetFileName(strP)) > 0 Then
strP = fso.GetParentFolderName(strP)
End If
If fso.FolderExists(strP) Then 'folder exist
EnsureFolderPath = True
ElseIf fso.FolderExists(fso.GetParentFolderName(strP)) Then 'parent folder exist
fso.CreateFolder strP 'create new subfolder and exit
Else 'parentfolder doesn't exist, go one level higher
EnsureFolderPath fso.GetParentFolderName(strP)
'now that parent folder path has been created
fso.CreateFolder strP
End If
If fso.FolderExists(strP) Then EnsureFolderPath = True 'ok and exit
End Function
Answer: If fso.FolderExists(strP) Then 'folder exist
This comment isn't needed because it states the obvious. Comments shouldn't be written to tell what the code is doing but rather why something is done the way it is done.
That beeing said, I would expect a comment here:
If Len(fso.GetFileName(strP)) > 0 Then
strP = fso.GetParentFolderName(strP)
End If | {
"domain": "codereview.stackexchange",
"id": 43296,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "vba, file-system, ms-access",
"url": null
} |
vba, file-system, ms-access
stating that the code checks wether the passed strP is a filename instead of a foldername.
While we are at this, strP isn't a very good name, because at first glance you can't tell what te variable/argument should stay for.
Dim strParent As String isn't used and should be removed.
For each entry in the recursive method a FileSystemObject is created which isn't ressource-friendly. Either you should have one FileSystemObject on class-level, or cretae a second (overloaded) method where you pass a FileSystemObject along with the file/foldername.
If fso.FolderExists(strP) Then EnsureFolderPath = True 'ok and exit isn't needed because that is done at the beginning of the method.
Function EnsureFolderPath(path As String) As Boolean
On Error GoTo EnsureFolderPath_Error
Dim fso As FileSystemObject
Set fso = New FileSystemObject
If IsFileName(path, fso) Then
path = fso.GetParentFolderName(path)
End If
EnsureFolderPath = EnsureFolderPathExists(path, fso)
End Function
Function IsFileName(path As String, fso As FileSystemObject) as Boolean
IsFileName = (fso.GetFileName(path) <> "")
End Function
Function EnsureFolderPathExists(path As String, fso As FileSystemObject) as Boolean
If fso.FolderExists(path) Then
EnsureFolderPathExists = True
Exit Function
End If
Dim parentPath as String
parentPath = fso.GetParentFolderName(path)
If EnsureFolderPathExists(parentPath, fso) Then
fso.CreateFolder path
EnsureFolderPathExists = True
Exit Function
End If
EnsureFolderPathExists = False
End Function
Be aware this is not tested but it should work. | {
"domain": "codereview.stackexchange",
"id": 43296,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "vba, file-system, ms-access",
"url": null
} |
array, vba
Title: Populate array using elements from four source arrays
Question: Long piece of code, I hope it is readable.
The code is basically if statements looking at 4 arrays: ArrPnLDataD1, PricingDatesArr, ArrForwardCurves and ArrHistoricalPrices.
I thought that having gone with arrays, the code would run quite fast but due to the size of the arrays and the number of loops it is running for too long. Any suggestions on how to optimize?
For k = LBound(ArrPnLDataD1, 1) To UBound(ArrPnLDataD1, 1)
For j = LBound(PricingDatesArr, 1) To UBound(PricingDatesArr, 1)
If ArrPnLDataD1(k, 158) <> "N/A Bio Element" Then
If ArrPnLDataD1(k, 43) = "Phys - Time Based - Fixed Forward Price" Or ArrPnLDataD1(k, 43) = "Phys - Movement Based - Fixed Forward Price" Then 'If FWD Fixed price case
For n = 2 To UBound(ArrForwardCurves, 2)
If ArrPnLDataD1(k, 77) = ArrForwardCurves(1, n) And PricingDatesArr(j, 4) = ArrForwardCurves(3, n) Then 'Curve 1
For x = 8 To UBound(ArrForwardCurves, 1)
If ArrPnLDataD1(k, 158) = ArrForwardCurves(x, 1) Then
PricingDatesArr(j, 10) = ArrForwardCurves(x, n) 'Populate curve 1 Price
End If
Next x
ElseIf ArrPnLDataD1(k, 83) = ArrForwardCurves(1, n) And PricingDatesArr(j, 4) = ArrForwardCurves(3, n) Then 'Curve 2
For x = 8 To UBound(ArrForwardCurves, 1)
If ArrPnLDataD1(k, 158) = ArrForwardCurves(x, 1) Then
PricingDatesArr(j, 11) = ArrForwardCurves(x, n) 'Populate curve 2 Price
End If
Next x
ElseIf ArrPnLDataD1(k, 89) = ArrForwardCurves(1, n) And PricingDatesArr(j, 4) = ArrForwardCurves(3, n) Then 'Curve 3 | {
"domain": "codereview.stackexchange",
"id": 43297,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "array, vba",
"url": null
} |
array, vba
For x = 8 To UBound(ArrForwardCurves, 1)
If ArrPnLDataD1(k, 158) = ArrForwardCurves(x, 1) Then
PricingDatesArr(j, 12) = ArrForwardCurves(x, n) 'Populate curve 3 Price
End If
Next x
ElseIf ArrPnLDataD1(k, 95) = ArrForwardCurves(1, n) And PricingDatesArr(j, 4) = ArrForwardCurves(3, n) Then 'Curve 4
For x = 8 To UBound(ArrForwardCurves, 1)
If ArrPnLDataD1(k, 158) = ArrForwardCurves(x, 1) Then
PricingDatesArr(j, 13) = ArrForwardCurves(x, n) 'Populate curve 4 Price
End If
Next x
ElseIf ArrPnLDataD1(k, 101) = ArrForwardCurves(1, n) And PricingDatesArr(j, 4) = ArrForwardCurves(3, n) Then 'Curve 5
For x = 8 To UBound(ArrForwardCurves, 1)
If ArrPnLDataD1(k, 158) = ArrForwardCurves(x, 1) Then
PricingDatesArr(j, 14) = ArrForwardCurves(x, n) 'Populate curve 5 Price
End If
Next x
End If
Next n
Else ' not forward fixed price
If PricingDatesArr(j, 2) > ReportDate Then 'Pricing dates is in the future
For n = 2 To UBound(ArrForwardCurves, 2)
If ArrPnLDataD1(k, 77) = ArrForwardCurves(1, n) And PricingDatesArr(j, 3) = ArrForwardCurves(3, n) Then 'Curve 1
For x = 8 To UBound(ArrForwardCurves, 1)
If PricingDatesArr(j, 2) = ArrForwardCurves(x, 1) Then
PricingDatesArr(j, 10) = ArrForwardCurves(x, n) 'Populate curve 1 Price
End If
Next x | {
"domain": "codereview.stackexchange",
"id": 43297,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "array, vba",
"url": null
} |
array, vba
End If
Next x
ElseIf ArrPnLDataD1(k, 83) = ArrForwardCurves(1, n) And PricingDatesArr(j, 3) = ArrForwardCurves(3, n) Then 'Curve 2
For x = 8 To UBound(ArrForwardCurves, 1)
If PricingDatesArr(j, 2) = ArrForwardCurves(x, 1) Then
PricingDatesArr(j, 11) = ArrForwardCurves(x, n) 'Populate curve 2 Price
End If
Next x
ElseIf ArrPnLDataD1(k, 89) = ArrForwardCurves(1, n) And PricingDatesArr(j, 3) = ArrForwardCurves(3, n) Then 'Curve 3
For x = 8 To UBound(ArrForwardCurves, 1)
If PricingDatesArr(j, 2) = ArrForwardCurves(x, 1) Then
PricingDatesArr(j, 12) = ArrForwardCurves(x, n) 'Populate curve 3 Price
End If
Next x
ElseIf ArrPnLDataD1(k, 95) = ArrForwardCurves(1, n) And PricingDatesArr(j, 3) = ArrForwardCurves(3, n) Then 'Curve 4
For x = 8 To UBound(ArrForwardCurves, 1)
If PricingDatesArr(j, 2) = ArrForwardCurves(x, 1) Then
PricingDatesArr(j, 13) = ArrForwardCurves(x, n) 'Populate curve 4 Price
End If
Next x
ElseIf ArrPnLDataD1(k, 101) = ArrForwardCurves(1, n) And PricingDatesArr(j, 3) = ArrForwardCurves(3, n) Then 'Curve 5
For x = 8 To UBound(ArrForwardCurves, 1)
If PricingDatesArr(j, 2) = ArrForwardCurves(x, 1) Then
PricingDatesArr(j, 14) = ArrForwardCurves(x, n) 'Populate curve 5 Price
End If
Next x
End If
Next n
ElseIf PricingDatesArr(j, 2) <= ReportDate Then 'Pricing dates is in the past
For n = 2 To UBound(ArrHistoricalPrices, 2)
If ArrPnLDataD1(k, 77) = ArrHistoricalPrices(1, n) Then 'Curve 1
For x = 6 To UBound(ArrHistoricalPrices, 1) | {
"domain": "codereview.stackexchange",
"id": 43297,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "array, vba",
"url": null
} |
array, vba
For x = 6 To UBound(ArrHistoricalPrices, 1)
If PricingDatesArr(j, 2) = ArrHistoricalPrices(x, 1) Then
PricingDatesArr(j, 10) = ArrForwardCurves(x, n) 'Populate curve 1 Price
End If
Next x
ElseIf ArrPnLDataD1(k, 83) = ArrHistoricalPrices(1, n) Then 'Curve 2
For x = 6 To UBound(ArrHistoricalPrices, 1)
If PricingDatesArr(j, 2) = ArrHistoricalPrices(x, 1) Then
PricingDatesArr(j, 11) = ArrForwardCurves(x, n) 'Populate curve 2 Price
End If
Next x
ElseIf ArrPnLDataD1(k, 89) = ArrHistoricalPrices(1, n) Then 'Curve 3
For x = 6 To UBound(ArrHistoricalPrices, 1)
If PricingDatesArr(j, 2) = ArrHistoricalPrices(x, 1) Then
PricingDatesArr(j, 12) = ArrForwardCurves(x, n) 'Populate curve 3 Price
End If
Next x
ElseIf ArrPnLDataD1(k, 95) = ArrHistoricalPrices(1, n) Then 'Curve 4
For x = 6 To UBound(ArrHistoricalPrices, 1)
If PricingDatesArr(j, 2) = ArrHistoricalPrices(x, 1) Then
PricingDatesArr(j, 13) = ArrForwardCurves(x, n) 'Populate curve 4 Price
End If
Next x
ElseIf ArrPnLDataD1(k, 101) = ArrHistoricalPrices(1, n) Then 'Curve 5
For x = 6 To UBound(ArrHistoricalPrices, 1)
If PricingDatesArr(j, 2) = ArrHistoricalPrices(x, 1) Then
PricingDatesArr(j, 14) = ArrForwardCurves(x, n) 'Populate curve 5 Price
End If
Next x
End If
Next n
End If
End If
End If
Next j
Next k | {
"domain": "codereview.stackexchange",
"id": 43297,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "array, vba",
"url": null
} |
array, vba
Answer: Unsure how many rows are in PricingDatesArr, but I would start by moving If ArrPnLDataD1(k, 158) <> "N/A Bio Element" Then outside the For j loop. This will prevent iterating through all rows of the PricingDatesArr without doing any work.
And PricingDatesArr(j, 4) = ArrForwardCurves(3, n) and And PricingDatesArr(j, 3) = ArrForwardCurves(3, n) are listed in each of their respective If Then statements, so that can be moved to it's own outer If Then statement (although this creates another layer of nested If statements).
For k = LBound(ArrPnLDataD1, 1) To UBound(ArrPnLDataD1, 1)
If ArrPnLDataD1(k, 158) <> "N/A Bio Element" Then
For j = LBound(PricingDatesArr, 1) To UBound(PricingDatesArr, 1)
If ArrPnLDataD1(k, 43) = "Phys - Time Based - Fixed Forward Price" Or ArrPnLDataD1(k, 43) = "Phys - Movement Based - Fixed Forward Price" Then 'If FWD Fixed price case
For n = 2 To UBound(ArrForwardCurves, 2)
If PricingDatesArr(j, 4) = ArrForwardCurves(3, n) Then
If ArrPnLDataD1(k, 77) = ArrForwardCurves(1, n) Then 'Curve 1
For x = 8 To UBound(ArrForwardCurves, 1)
If ArrPnLDataD1(k, 158) = ArrForwardCurves(x, 1) Then
PricingDatesArr(j, 10) = ArrForwardCurves(x, n) 'Populate curve 1 Price
End If
Next x
ElseIf ArrPnLDataD1(k, 83) = ArrForwardCurves(1, n) Then 'Curve 2
For x = 8 To UBound(ArrForwardCurves, 1)
If ArrPnLDataD1(k, 158) = ArrForwardCurves(x, 1) Then
PricingDatesArr(j, 11) = ArrForwardCurves(x, n) 'Populate curve 2 Price
End If
Next x
ElseIf ArrPnLDataD1(k, 89) = ArrForwardCurves(1, n) Then 'Curve 3 | {
"domain": "codereview.stackexchange",
"id": 43297,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "array, vba",
"url": null
} |
array, vba
ElseIf ArrPnLDataD1(k, 89) = ArrForwardCurves(1, n) Then 'Curve 3
For x = 8 To UBound(ArrForwardCurves, 1)
If ArrPnLDataD1(k, 158) = ArrForwardCurves(x, 1) Then
PricingDatesArr(j, 12) = ArrForwardCurves(x, n) 'Populate curve 3 Price
End If
Next x
ElseIf ArrPnLDataD1(k, 95) = ArrForwardCurves(1, n) Then 'Curve 4
For x = 8 To UBound(ArrForwardCurves, 1)
If ArrPnLDataD1(k, 158) = ArrForwardCurves(x, 1) Then
PricingDatesArr(j, 13) = ArrForwardCurves(x, n) 'Populate curve 4 Price
End If
Next x
ElseIf ArrPnLDataD1(k, 101) = ArrForwardCurves(1, n) Then 'Curve 5
For x = 8 To UBound(ArrForwardCurves, 1)
If ArrPnLDataD1(k, 158) = ArrForwardCurves(x, 1) Then
PricingDatesArr(j, 14) = ArrForwardCurves(x, n) 'Populate curve 5 Price
End If
Next x
End If
End If
Next n
Else ' not forward fixed price
If PricingDatesArr(j, 2) > ReportDate Then 'Pricing dates is in the future
For n = 2 To UBound(ArrForwardCurves, 2)
If PricingDatesArr(j, 3) = ArrForwardCurves(3, n) Then
If ArrPnLDataD1(k, 77) = ArrForwardCurves(1, n) Then 'Curve 1
For x = 8 To UBound(ArrForwardCurves, 1)
If PricingDatesArr(j, 2) = ArrForwardCurves(x, 1) Then | {
"domain": "codereview.stackexchange",
"id": 43297,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "array, vba",
"url": null
} |
array, vba
If PricingDatesArr(j, 2) = ArrForwardCurves(x, 1) Then
PricingDatesArr(j, 10) = ArrForwardCurves(x, n) 'Populate curve 1 Price
End If
Next x
ElseIf ArrPnLDataD1(k, 83) = ArrForwardCurves(1, n) Then 'Curve 2
For x = 8 To UBound(ArrForwardCurves, 1)
If PricingDatesArr(j, 2) = ArrForwardCurves(x, 1) Then
PricingDatesArr(j, 11) = ArrForwardCurves(x, n) 'Populate curve 2 Price
End If
Next x
ElseIf ArrPnLDataD1(k, 89) = ArrForwardCurves(1, n) Then 'Curve 3
For x = 8 To UBound(ArrForwardCurves, 1)
If PricingDatesArr(j, 2) = ArrForwardCurves(x, 1) Then
PricingDatesArr(j, 12) = ArrForwardCurves(x, n) 'Populate curve 3 Price
End If
Next x
ElseIf ArrPnLDataD1(k, 95) = ArrForwardCurves(1, n) Then 'Curve 4
For x = 8 To UBound(ArrForwardCurves, 1)
If PricingDatesArr(j, 2) = ArrForwardCurves(x, 1) Then
PricingDatesArr(j, 13) = ArrForwardCurves(x, n) 'Populate curve 4 Price
End If
Next x
ElseIf ArrPnLDataD1(k, 101) = ArrForwardCurves(1, n) Then 'Curve 5
For x = 8 To UBound(ArrForwardCurves, 1)
If PricingDatesArr(j, 2) = ArrForwardCurves(x, 1) Then | {
"domain": "codereview.stackexchange",
"id": 43297,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "array, vba",
"url": null
} |
array, vba
If PricingDatesArr(j, 2) = ArrForwardCurves(x, 1) Then
PricingDatesArr(j, 14) = ArrForwardCurves(x, n) 'Populate curve 5 Price
End If
Next x
End If
End If
Next n
ElseIf PricingDatesArr(j, 2) <= ReportDate Then 'Pricing dates is in the past
For n = 2 To UBound(ArrHistoricalPrices, 2)
If ArrPnLDataD1(k, 77) = ArrHistoricalPrices(1, n) Then 'Curve 1
For x = 6 To UBound(ArrHistoricalPrices, 1)
If PricingDatesArr(j, 2) = ArrHistoricalPrices(x, 1) Then
PricingDatesArr(j, 10) = ArrForwardCurves(x, n) 'Populate curve 1 Price
End If
Next x
ElseIf ArrPnLDataD1(k, 83) = ArrHistoricalPrices(1, n) Then 'Curve 2
For x = 6 To UBound(ArrHistoricalPrices, 1)
If PricingDatesArr(j, 2) = ArrHistoricalPrices(x, 1) Then
PricingDatesArr(j, 11) = ArrForwardCurves(x, n) 'Populate curve 2 Price
End If
Next x
ElseIf ArrPnLDataD1(k, 89) = ArrHistoricalPrices(1, n) Then 'Curve 3
For x = 6 To UBound(ArrHistoricalPrices, 1)
If PricingDatesArr(j, 2) = ArrHistoricalPrices(x, 1) Then
PricingDatesArr(j, 12) = ArrForwardCurves(x, n) 'Populate curve 3 Price
End If
Next x
ElseIf ArrPnLDataD1(k, 95) = ArrHistoricalPrices(1, n) Then 'Curve 4 | {
"domain": "codereview.stackexchange",
"id": 43297,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "array, vba",
"url": null
} |
array, vba
ElseIf ArrPnLDataD1(k, 95) = ArrHistoricalPrices(1, n) Then 'Curve 4
For x = 6 To UBound(ArrHistoricalPrices, 1)
If PricingDatesArr(j, 2) = ArrHistoricalPrices(x, 1) Then
PricingDatesArr(j, 13) = ArrForwardCurves(x, n) 'Populate curve 4 Price
End If
Next x
ElseIf ArrPnLDataD1(k, 101) = ArrHistoricalPrices(1, n) Then 'Curve 5
For x = 6 To UBound(ArrHistoricalPrices, 1)
If PricingDatesArr(j, 2) = ArrHistoricalPrices(x, 1) Then
PricingDatesArr(j, 14) = ArrForwardCurves(x, n) 'Populate curve 5 Price
End If
Next x
End If
Next n
End If
End If
Next j
End If
Next k | {
"domain": "codereview.stackexchange",
"id": 43297,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "array, vba",
"url": null
} |
array, vba
``` | {
"domain": "codereview.stackexchange",
"id": 43297,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "array, vba",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
Title: Newspaper Bill Calculator CLI with Python (1 of 3, Core)
Question: Code is posted after explanation.
Due to the size of the project, this is being posted in three separate posts. This also ensures each post is more focused.
Post 2 of 3, CLI: Newspaper Bill Calculator CLI with Python (2 of 3, CLI)
Post 3 of 3, Database: Newspaper Bill Calculator CLI with Python (3 of 3, Database)
What is this?
This application helps you calculate monthly newspaper bills. The goal is to generate a message that I can paste into WhatsApp and send to my newspaper vendor. The end result here is a CLI tool that will be later used as a back-end to build GUIs (hence learn about: C#, HTML/CSS/JS, Flutter). In its current form, everything will be "compiled" by PyInstaller into one-file stand-alone executables for the end-user using GitHub Actions.
The other important goal was to be a testbed for learning a bunch of new tools: more Python libraries, SQL connectors, GitHub Actions (CI/CD, if I understand correctly), unit tests, CLI libraries, type-hinting, regex. I had earlier built this on a different platform, so I now have a solid idea of how this application is used.
Key concepts
Each newspaper has a certain cost per day of the week
Each newspaper may or may not be delivered on a given day
Each newspaper has a name, and a number called a key
You may register any dates when you didn't receive a paper in advance using the addudl command
Once you calculate, the results are displayed and copied to your clipboard
What files exist?
(ignoring conventional ones like README and requirements.txt)
File
Purpose/Description
Review
npbc_core.py
Provide the core functionality: the calculation, parsing and validation of user input, interaction with the DB etc. Later on, some functionality from this will be extracted to create server-side code that can service more users, but I have to learn a lot more before getting there.
Please review this. | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
npbc_cli.py
Import functionality from npbc_core.py and wrap a CLI layer on it using argparse. Also provide some additional validation.
Please review this.
npbc_updater.py
Provide a utility to update the application on the user's end.
Don't bother reviewing this (code not included).
test_core.py
Test the functionality of the core file (pytest). This isn't as exhaustive as I'd like, but it did a good job of capturing many of my mistakes.
Please review this.
data/schema.sql
Database schema. In my local environment, the data folder also has a test database file (but I don't want to upload this online).
Please review this if you can (not high priority).
Known problems
Tests are not exhaustive (please suggest anything you think of).
Tests are not well commented (working on this right now in a local branch).
SQL injection is possible in some cases by -k/--key CLI parameters, if you can figure out a way to insert a semicolon in an integer. I will remove this in a future version, once I find a way to improve or remove the generate_sql_query() function.
A lot of documentation is tied up in the CLI UI and comments, and is not an explicit document.
npbc_core.py
from sqlite3 import connect
from calendar import day_name as weekday_names_iterable
from calendar import monthrange, monthcalendar
from datetime import date as date_type, datetime, timedelta
from pathlib import Path
from re import compile as compile_regex
## paths for the folder containing schema and database files
# during normal use, the DB will be in ~/.npbc (where ~ is the user's home directory) and the schema will be bundled with the executable
# during development, the DB and schema will both be in "data"
DATABASE_DIR = Path().home() / '.npbc' # normal use path
# DATABASE_DIR = Path('data') # development path
DATABASE_PATH = DATABASE_DIR / 'npbc.db'
SCHEMA_PATH = Path(__file__).parent / 'schema.sql' # normal use path
# SCHEMA_PATH = DATABASE_DIR / 'schema.sql' # development path | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
## list constant for names of weekdays
WEEKDAY_NAMES = list(weekday_names_iterable)
## regex for validating user input
VALIDATE_REGEX = {
# match for a list of comma separated values. each value must be/contain digits, or letters, or hyphens. spaces are allowed between values and commas. any number of values are allowed, but at least one must be present.
'CSVs': compile_regex(r'^[-\w]+( *, *[-\w]+)*( *,)?$'),
# match for a single number. must be one or two digits
'number': compile_regex(r'^[\d]{1,2}?$'),
# match for a range of numbers. each number must be one or two digits. numbers are separated by a hyphen. spaces are allowed between numbers and the hyphen.
'range': compile_regex(r'^\d{1,2} *- *\d{1,2}$'),
# match for weekday name. day must appear as "daynames" (example: "mondays"). all lowercase.
'days': compile_regex(f"^{'|'.join([day_name.lower() + 's' for day_name in WEEKDAY_NAMES])}$"),
# match for nth weekday name. day must appear as "n-dayname" (example: "1-monday"). all lowercase. must be one digit.
'n-day': compile_regex(f"^\\d *- *({'|'.join([day_name.lower() for day_name in WEEKDAY_NAMES])})$"),
# match for real values, delimited by semicolons. each value must be either an integer or a float with a decimal point. spaces are allowed between values and semicolons, and up to 7 (but at least 1) values are allowed.
'costs': compile_regex(r'^\d+(\.\d+)?( *; *\d+(\.\d+)?){0,6} *;?$'),
# match for seven values, each of which must be a 'Y' or an 'N'. there are no delimiters.
'delivery': compile_regex(r'^[YN]{7}$')
}
## regex for splitting strings
SPLIT_REGEX = {
# split on hyphens. spaces are allowed between hyphens and values.
'hyphen': compile_regex(r' *- *'),
# split on semicolons. spaces are allowed between hyphens and values.
'semicolon': compile_regex(r' *; *'),
# split on commas. spaces are allowed between commas and values.
'comma': compile_regex(r' *, *')
} | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
## ensure DB exists and it's set up with the schema
def setup_and_connect_DB() -> None:
DATABASE_DIR.mkdir(parents=True, exist_ok=True)
DATABASE_PATH.touch(exist_ok=True)
with connect(DATABASE_PATH) as connection:
connection.executescript(SCHEMA_PATH.read_text())
connection.commit()
## generate a "SELECT" SQL query
# use params to specify columns to select, and "WHERE" conditions
def generate_sql_query(table_name: str, conditions: dict[str, int | str] | None = None, columns: list[str] | None = None) -> str:
sql_query = f"SELECT"
if columns:
sql_query += f" {', '.join(columns)}"
else:
sql_query += f" *"
sql_query += f" FROM {table_name}"
if conditions:
conditions_segment = ' AND '.join([
f"{parameter_name} = {parameter_value}"
for parameter_name, parameter_value in conditions.items()
])
sql_query += f" WHERE {conditions_segment}"
return f"{sql_query};"
## execute a "SELECT" SQL query and return the results
def query_database(query: str) -> list[tuple]:
with connect(DATABASE_PATH) as connection:
return connection.execute(query).fetchall()
return []
## generate a list of number of times each weekday occurs in a given month
# the list will be in the same order as WEEKDAY_NAMES (so the first day should be Monday)
def get_number_of_days_per_week(month: int, year: int) -> list[int]:
main_calendar = monthcalendar(year, month)
number_of_weeks = len(main_calendar)
number_of_weekdays = []
for i, _ in enumerate(WEEKDAY_NAMES):
number_of_weekday = number_of_weeks
if main_calendar[0][i] == 0:
number_of_weekday -= 1
if main_calendar[-1][i] == 0:
number_of_weekday -= 1
number_of_weekdays.append(number_of_weekday)
return number_of_weekdays | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
number_of_weekdays.append(number_of_weekday)
return number_of_weekdays
## validate a string that specifies when a given paper was not delivered
# first check to see that it meets the comma-separated requirements
# then check against each of the other acceptable patterns in the regex dictionary
def validate_undelivered_string(string: str) -> bool:
if VALIDATE_REGEX['CSVs'].match(string):
for section in SPLIT_REGEX['comma'].split(string.rstrip(',')):
section_validity = False
for pattern, regex in VALIDATE_REGEX.items():
if (not section_validity) and (pattern not in ["CSVs", "costs", "delivery"]) and (regex.match(section)):
section_validity = True
if not section_validity:
return False
return True
return False
## parse a string that specifies when a given paper was not delivered
# each CSV section states some set of dates
# this function will return a set of dates that uniquely identifies each date mentioned across all the CSVs
def parse_undelivered_string(string: str, month: int, year: int) -> set[date_type]:
dates = set()
for section in SPLIT_REGEX['comma'].split(string.rstrip(',')):
# if the date is simply a number, it's a single day. so we just identify that date
if VALIDATE_REGEX['number'].match(section):
date = int(section)
if date > 0 and date <= monthrange(year, month)[1]:
dates.add(date_type(year, month, date))
# if the date is a range of numbers, it's a range of days. we identify all the dates in that range, bounds inclusive
elif VALIDATE_REGEX['range'].match(section):
start, end = [int(date) for date in SPLIT_REGEX['hyphen'].split(section)] | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
if (0 < start) and (start <= end) and (end <= monthrange(year, month)[1]):
dates.update(
date_type(year, month, day)
for day in range(start, end + 1)
)
# if the date is the plural of a weekday name, we identify all dates in that month which are the given weekday
elif VALIDATE_REGEX['days'].match(section):
weekday = WEEKDAY_NAMES.index(section.capitalize().rstrip('s'))
dates.update(
date_type(year, month, day)
for day in range(1, monthrange(year, month)[1] + 1)
if date_type(year, month, day).weekday() == weekday
)
# if the date is a number and a weekday name (singular), we identify the date that is the nth occurrence of the given weekday in the month
elif VALIDATE_REGEX['n-day'].match(section):
n, weekday = SPLIT_REGEX['hyphen'].split(section)
n = int(n)
if n > 0 and n <= get_number_of_days_per_week(month, year)[WEEKDAY_NAMES.index(weekday.capitalize())]:
weekday = WEEKDAY_NAMES.index(weekday.capitalize())
valid_dates = [
date_type(year, month, day)
for day in range(1, monthrange(year, month)[1] + 1)
if date_type(year, month, day).weekday() == weekday
]
dates.add(valid_dates[n - 1])
# bug report :)
else:
print("Congratulations! You broke the program!")
print("You managed to write a string that the program considers valid, but isn't actually.")
print("Please report it to the developer.")
print(f"\nThe string you wrote was: {string}")
print("This data has not been counted.")
return dates | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
return dates
## get the cost and delivery data for a given paper from the DB
# each of them are converted to a dictionary, whose index is the day_id
# the two dictionaries are then returned as a tuple
def get_cost_and_delivery_data(paper_id: int) -> tuple[dict[int, float], dict[int, bool]]:
cost_query = generate_sql_query(
'papers_days_cost',
columns=['day_id', 'cost'],
conditions={'paper_id': paper_id}
)
delivery_query = generate_sql_query(
'papers_days_delivered',
columns=['day_id', 'delivered'],
conditions={'paper_id': paper_id}
)
with connect(DATABASE_PATH) as connection:
cost_tuple = connection.execute(cost_query).fetchall()
delivery_tuple = connection.execute(delivery_query).fetchall()
cost_dict = {
day_id: cost
for day_id, cost in cost_tuple # type: ignore
}
delivery_dict = {
day_id: delivery
for day_id, delivery in delivery_tuple # type: ignore
}
return cost_dict, delivery_dict
## calculate the cost of one paper for the full month
# any dates when it was not delivered will be removed
def calculate_cost_of_one_paper(number_of_days_per_week: list[int], undelivered_dates: set[date_type], cost_and_delivered_data: tuple[dict[int, float], dict[int, bool]]) -> float:
cost_data, delivered_data = cost_and_delivered_data
# initialize counters corresponding to each weekday when the paper was not delivered
number_of_days_per_week_not_received = [0] * len(number_of_days_per_week) | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
# for each date that the paper was not delivered, we increment the counter for the corresponding weekday
for date in undelivered_dates:
number_of_days_per_week_not_received[date.weekday()] += 1
# calculate the total number of each weekday the paper was delivered (if it is supposed to be delivered)
number_of_days_delivered = [
number_of_days_per_week[day_id] - number_of_days_per_week_not_received[day_id] if delivered else 0
for day_id, delivered in delivered_data.items()
]
# calculate the total cost of the paper for the month
return sum(
cost * number_of_days_delivered[day_id]
for day_id, cost in cost_data.items()
)
## calculate the cost of all papers for the full month
# return data about the cost of each paper, the total cost, and dates when each paper was not delivered
def calculate_cost_of_all_papers(undelivered_strings: dict[int, str], month: int, year: int) -> tuple[dict[int, float], float, dict[int, set[date_type]]]:
NUMBER_OF_DAYS_PER_WEEK = get_number_of_days_per_week(month, year)
# get the IDs of papers that exist
with connect(DATABASE_PATH) as connection:
papers = connection.execute(
generate_sql_query(
'papers',
columns=['paper_id']
)
).fetchall()
# get the data about cost and delivery for each paper
cost_and_delivery_data = [
get_cost_and_delivery_data(paper_id)
for paper_id, in papers # type: ignore
]
# initialize a "blank" dictionary that will eventually contain any dates when a paper was not delivered
undelivered_dates: dict[int, set[date_type]] = {
paper_id: {}
for paper_id, in papers # type: ignore
}
# calculate the undelivered dates for each paper
for paper_id, undelivered_string in undelivered_strings.items(): # type: ignore
undelivered_dates[paper_id] = parse_undelivered_string(undelivered_string, month, year) | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
# calculate the cost of each paper
costs = {
paper_id: calculate_cost_of_one_paper(
NUMBER_OF_DAYS_PER_WEEK,
undelivered_dates[paper_id],
cost_and_delivery_data[index]
)
for index, (paper_id,) in enumerate(papers) # type: ignore
}
# calculate the total cost of all papers
total = sum(costs.values())
return costs, total, undelivered_dates
## save the results of undelivered dates to the DB
# save the dates any paper was not delivered
def save_results(undelivered_dates: dict[int, set[date_type]], month: int, year: int) -> None:
TIMESTAMP = datetime.now().strftime(r'%d/%m/%Y %I:%M:%S %p')
with connect(DATABASE_PATH) as connection:
for paper_id, undelivered_date_instances in undelivered_dates.items():
connection.execute(
"INSERT INTO undelivered_dates (timestamp, month, year, paper_id, dates) VALUES (?, ?, ?, ?, ?);",
(
TIMESTAMP,
month,
year,
paper_id,
','.join([
undelivered_date_instance.strftime(r'%d')
for undelivered_date_instance in undelivered_date_instances
])
)
)
## format the output of calculating the cost of all papers
def format_output(costs: dict[int, float], total: float, month: int, year: int) -> str:
papers = {
paper_id: name
for paper_id, name in query_database(
generate_sql_query('papers')
)
}
format_string = f"For {date_type(year=year, month=month, day=1).strftime(r'%B %Y')}\n\n"
format_string += f"*TOTAL*: {total}\n"
format_string += '\n'.join([
f"{papers[paper_id]}: {cost}" # type: ignore
for paper_id, cost in costs.items()
])
return f"{format_string}\n" | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
return f"{format_string}\n"
## add a new paper
# do not allow if the paper already exists
def add_new_paper(name: str, days_delivered: list[bool], days_cost: list[float]) -> tuple[bool, str]:
with connect(DATABASE_PATH) as connection:
# get the names of all papers that already exist
paper = connection.execute(
generate_sql_query('papers', columns=['name'], conditions={'name': f"\"{name}\""})
).fetchall()
# if the proposed paper already exists, return an error message
if paper:
return False, "Paper already exists. Please try editing the paper instead."
# otherwise, add the paper name to the database
connection.execute(
"INSERT INTO papers (name) VALUES (?);",
(name, )
)
# get the ID of the paper that was just added
paper_id = connection.execute(
"SELECT paper_id FROM papers WHERE name = ?;",
(name, )
).fetchone()[0]
# add the cost and delivery data for the paper
for day_id, (cost, delivered) in enumerate(zip(days_cost, days_delivered)):
connection.execute(
"INSERT INTO papers_days_cost (paper_id, day_id, cost) VALUES (?, ?, ?);",
(paper_id, day_id, cost)
)
connection.execute(
"INSERT INTO papers_days_delivered (paper_id, day_id, delivered) VALUES (?, ?, ?);",
(paper_id, day_id, delivered)
)
connection.commit()
return True, f"Paper {name} added."
return False, "Something went wrong."
## edit an existing paper
# do not allow if the paper does not exist
def edit_existing_paper(paper_id: int, name: str | None = None, days_delivered: list[bool] | None = None, days_cost: list[float] | None = None) -> tuple[bool, str]:
with connect(DATABASE_PATH) as connection: | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
# get the IDs of all papers that already exist
paper = connection.execute(
generate_sql_query('papers', columns=['paper_id'], conditions={'paper_id': paper_id})
).fetchone()
# if the proposed paper does not exist, return an error message
if not paper:
return False, f"Paper {paper_id} does not exist. Please try adding it instead."
# if a name is proposed, update the name of the paper
if name is not None:
connection.execute(
"UPDATE papers SET name = ? WHERE paper_id = ?;",
(name, paper_id)
)
# if delivery data is proposed, update the delivery data of the paper
if days_delivered is not None:
for day_id, delivered in enumerate(days_delivered):
connection.execute(
"UPDATE papers_days_delivered SET delivered = ? WHERE paper_id = ? AND day_id = ?;",
(delivered, paper_id, day_id)
)
# if cost data is proposed, update the cost data of the paper
if days_cost is not None:
for day_id, cost in enumerate(days_cost):
connection.execute(
"UPDATE papers_days_cost SET cost = ? WHERE paper_id = ? AND day_id = ?;",
(cost, paper_id, day_id)
)
connection.commit()
return True, f"Paper {paper_id} edited."
return False, "Something went wrong."
## delete an existing paper
# do not allow if the paper does not exist
def delete_existing_paper(paper_id: int) -> tuple[bool, str]:
with connect(DATABASE_PATH) as connection:
# get the IDs of all papers that already exist
paper = connection.execute(
generate_sql_query('papers', columns=['paper_id'], conditions={'paper_id': paper_id})
).fetchone() | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
# if the proposed paper does not exist, return an error message
if not paper:
return False, f"Paper {paper_id} does not exist. Please try adding it instead."
# delete the paper from the names table
connection.execute(
"DELETE FROM papers WHERE paper_id = ?;",
(paper_id, )
)
# delete the paper from the delivery data table
connection.execute(
"DELETE FROM papers_days_delivered WHERE paper_id = ?;",
(paper_id, )
)
# delete the paper from the cost data table
connection.execute(
"DELETE FROM papers_days_cost WHERE paper_id = ?;",
(paper_id, )
)
connection.commit()
return True, f"Paper {paper_id} deleted."
return False, "Something went wrong."
## record strings for date(s) paper(s) were not delivered
def add_undelivered_string(paper_id: int, undelivered_string: str, month: int, year: int) -> tuple[bool, str]:
# if the string is not valid, return an error message
if not validate_undelivered_string(undelivered_string):
return False, f"Invalid undelivered string."
with connect(DATABASE_PATH) as connection:
# check if given paper exists
paper = connection.execute(
generate_sql_query(
'papers',
columns=['paper_id'],
conditions={'paper_id': paper_id}
)
).fetchone()
# if the paper does not exist, return an error message
if not paper:
return False, f"Paper {paper_id} does not exist. Please try adding it instead." | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
# check if a string with the same month and year, for the same paper, already exists
existing_string = connection.execute(
generate_sql_query(
'undelivered_strings',
columns=['string'],
conditions={
'paper_id': paper_id,
'month': month,
'year': year
}
)
).fetchone()
# if a string with the same month and year, for the same paper, already exists, concatenate the new string to it
if existing_string:
new_string = f"{existing_string[0]},{undelivered_string}"
connection.execute(
"UPDATE undelivered_strings SET string = ? WHERE paper_id = ? AND month = ? AND year = ?;",
(new_string, paper_id, month, year)
)
# otherwise, add the new string to the database
else:
connection.execute(
"INSERT INTO undelivered_strings (string, paper_id, month, year) VALUES (?, ?, ?, ?);",
(undelivered_string, paper_id, month, year)
)
connection.commit()
return True, f"Undelivered string added."
## delete an existing undelivered string
# do not allow if the string does not exist
def delete_undelivered_string(paper_id: int, month: int, year: int) -> tuple[bool, str]:
with connect(DATABASE_PATH) as connection:
# check if a string with the same month and year, for the same paper, exists
existing_string = connection.execute(
generate_sql_query(
'undelivered_strings',
columns=['string'],
conditions={
'paper_id': paper_id,
'month': month,
'year': year
}
)
).fetchone() | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
# if it does, delete it
if existing_string:
connection.execute(
"DELETE FROM undelivered_strings WHERE paper_id = ? AND month = ? AND year = ?;",
(paper_id, month, year)
)
connection.commit()
return True, f"Undelivered string deleted."
# if the string does not exist, return an error message
return False, f"Undelivered string does not exist."
return False, "Something went wrong."
## get the previous month, by looking at 1 day before the first day of the current month (duh)
def get_previous_month() -> date_type:
return (datetime.today().replace(day=1) - timedelta(days=1)).replace(day=1)
## extract delivery days and costs from user input
def extract_days_and_costs(days_delivered: str | None, prices: str | None, paper_id: int | None = None) -> tuple[list[bool], list[float]]:
days = []
costs = []
# if the user has provided delivery days, extract them
if days_delivered is not None:
days = [
bool(int(day == 'Y')) for day in str(days_delivered).upper()
]
# if the user has not provided delivery days, fetch them from the database
else:
if isinstance(paper_id, int):
days = [
(int(day_id), bool(delivered))
for day_id, delivered in query_database(
generate_sql_query(
'papers_days_delivered',
columns=['day_id', 'delivered'],
conditions={
'paper_id': paper_id
}
)
)
]
days.sort(key=lambda x: x[0])
days = [delivered for _, delivered in days]
# if the user has provided prices, extract them
if prices is not None: | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
# if the user has provided prices, extract them
if prices is not None:
costs = []
encoded_prices = [float(price) for price in SPLIT_REGEX['semicolon'].split(prices.rstrip(';')) if float(price) > 0]
day_count = -1
for day in days:
if day:
day_count += 1
cost = encoded_prices[day_count]
else:
cost = 0
costs.append(cost)
return days, costs
## validate month and year
def validate_month_and_year(month: int | None = None, year: int | None = None) -> tuple[bool, str]:
if ((month is None) or (isinstance(month, int) and (0 < month) and (month <= 12))) and ((year is None) or (isinstance(year, int) and (year >= 0))):
return True, ""
return False, "Invalid month and/or year."
test_core.py
from datetime import date as date_type
from npbc_core import (SPLIT_REGEX, VALIDATE_REGEX,
calculate_cost_of_one_paper, extract_days_and_costs,
generate_sql_query, get_number_of_days_per_week,
parse_undelivered_string, validate_month_and_year)
def test_regex_number():
assert VALIDATE_REGEX['number'].match('') is None
assert VALIDATE_REGEX['number'].match('1') is not None
assert VALIDATE_REGEX['number'].match('1 2') is None
assert VALIDATE_REGEX['number'].match('1-2') is None
assert VALIDATE_REGEX['number'].match('11') is not None
assert VALIDATE_REGEX['number'].match('11-12') is None
assert VALIDATE_REGEX['number'].match('11-12,13') is None
assert VALIDATE_REGEX['number'].match('11-12,13-14') is None
assert VALIDATE_REGEX['number'].match('111') is None
assert VALIDATE_REGEX['number'].match('a') is None
assert VALIDATE_REGEX['number'].match('1a') is None
assert VALIDATE_REGEX['number'].match('1a2') is None
assert VALIDATE_REGEX['number'].match('12b') is None | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
def test_regex_range():
assert VALIDATE_REGEX['range'].match('') is None
assert VALIDATE_REGEX['range'].match('1') is None
assert VALIDATE_REGEX['range'].match('1 2') is None
assert VALIDATE_REGEX['range'].match('1-2') is not None
assert VALIDATE_REGEX['range'].match('11') is None
assert VALIDATE_REGEX['range'].match('11-') is None
assert VALIDATE_REGEX['range'].match('11-12') is not None
assert VALIDATE_REGEX['range'].match('11-12-1') is None
assert VALIDATE_REGEX['range'].match('11 -12') is not None
assert VALIDATE_REGEX['range'].match('11 - 12') is not None
assert VALIDATE_REGEX['range'].match('11- 12') is not None
assert VALIDATE_REGEX['range'].match('11-2') is not None
assert VALIDATE_REGEX['range'].match('11-12,13') is None
assert VALIDATE_REGEX['range'].match('11-12,13-14') is None
assert VALIDATE_REGEX['range'].match('111') is None
assert VALIDATE_REGEX['range'].match('a') is None
assert VALIDATE_REGEX['range'].match('1a') is None
assert VALIDATE_REGEX['range'].match('1a2') is None
assert VALIDATE_REGEX['range'].match('12b') is None
assert VALIDATE_REGEX['range'].match('11-a') is None
assert VALIDATE_REGEX['range'].match('11-12a') is None | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
def test_regex_CSVs():
assert VALIDATE_REGEX['CSVs'].match('') is None
assert VALIDATE_REGEX['CSVs'].match('1') is not None
assert VALIDATE_REGEX['CSVs'].match('a') is not None
assert VALIDATE_REGEX['CSVs'].match('adcef') is not None
assert VALIDATE_REGEX['CSVs'].match('-') is not None
assert VALIDATE_REGEX['CSVs'].match(' ') is None
assert VALIDATE_REGEX['CSVs'].match('1,2') is not None
assert VALIDATE_REGEX['CSVs'].match('1-3') is not None
assert VALIDATE_REGEX['CSVs'].match('monday') is not None
assert VALIDATE_REGEX['CSVs'].match('monday,tuesday') is not None
assert VALIDATE_REGEX['CSVs'].match('mondays') is not None
assert VALIDATE_REGEX['CSVs'].match('tuesdays') is not None
assert VALIDATE_REGEX['CSVs'].match('1,2,3') is not None
assert VALIDATE_REGEX['CSVs'].match('1-3') is not None
assert VALIDATE_REGEX['CSVs'].match('monday,tuesday') is not None
assert VALIDATE_REGEX['CSVs'].match('mondays,tuesdays') is not None
assert VALIDATE_REGEX['CSVs'].match(';') is None
assert VALIDATE_REGEX['CSVs'].match(':') is None
assert VALIDATE_REGEX['CSVs'].match(':') is None
assert VALIDATE_REGEX['CSVs'].match('!') is None
assert VALIDATE_REGEX['CSVs'].match('1,2,3,4') is not None
def test_regex_days():
assert VALIDATE_REGEX['days'].match('') is None
assert VALIDATE_REGEX['days'].match('1') is None
assert VALIDATE_REGEX['days'].match('1,2') is None
assert VALIDATE_REGEX['days'].match('1-3') is None
assert VALIDATE_REGEX['days'].match('monday') is None
assert VALIDATE_REGEX['days'].match('monday,tuesday') is None
assert VALIDATE_REGEX['days'].match('mondays') is not None
assert VALIDATE_REGEX['days'].match('tuesdays') is not None | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
def test_regex_n_days():
assert VALIDATE_REGEX['n-day'].match('') is None
assert VALIDATE_REGEX['n-day'].match('1') is None
assert VALIDATE_REGEX['n-day'].match('1-') is None
assert VALIDATE_REGEX['n-day'].match('1,2') is None
assert VALIDATE_REGEX['n-day'].match('1-3') is None
assert VALIDATE_REGEX['n-day'].match('monday') is None
assert VALIDATE_REGEX['n-day'].match('monday,tuesday') is None
assert VALIDATE_REGEX['n-day'].match('mondays') is None
assert VALIDATE_REGEX['n-day'].match('1-tuesday') is not None
assert VALIDATE_REGEX['n-day'].match('11-tuesday') is None
assert VALIDATE_REGEX['n-day'].match('111-tuesday') is None
assert VALIDATE_REGEX['n-day'].match('11-tuesdays') is None
assert VALIDATE_REGEX['n-day'].match('1 -tuesday') is not None
assert VALIDATE_REGEX['n-day'].match('1- tuesday') is not None
assert VALIDATE_REGEX['n-day'].match('1 - tuesday') is not None | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
def test_regex_costs():
assert VALIDATE_REGEX['costs'].match('') is None
assert VALIDATE_REGEX['costs'].match('a') is None
assert VALIDATE_REGEX['costs'].match('1') is not None
assert VALIDATE_REGEX['costs'].match('1.') is None
assert VALIDATE_REGEX['costs'].match('1.5') is not None
assert VALIDATE_REGEX['costs'].match('1.0') is not None
assert VALIDATE_REGEX['costs'].match('16.0') is not None
assert VALIDATE_REGEX['costs'].match('16.06') is not None
assert VALIDATE_REGEX['costs'].match('1;2') is not None
assert VALIDATE_REGEX['costs'].match('1 ;2') is not None
assert VALIDATE_REGEX['costs'].match('1; 2') is not None
assert VALIDATE_REGEX['costs'].match('1 ; 2') is not None
assert VALIDATE_REGEX['costs'].match('1;2;') is not None
assert VALIDATE_REGEX['costs'].match('1;2 ;') is not None
assert VALIDATE_REGEX['costs'].match('1:2') is None
assert VALIDATE_REGEX['costs'].match('1,2') is None
assert VALIDATE_REGEX['costs'].match('1-2') is None
assert VALIDATE_REGEX['costs'].match('1;2;3') is not None
assert VALIDATE_REGEX['costs'].match('1;2;3;4') is not None
assert VALIDATE_REGEX['costs'].match('1;2;3;4;5') is not None
assert VALIDATE_REGEX['costs'].match('1;2;3;4;5;6') is not None
assert VALIDATE_REGEX['costs'].match('1;2;3;4;5;6;7;') is not None
assert VALIDATE_REGEX['costs'].match('1;2;3;4;5;6;7') is not None
assert VALIDATE_REGEX['costs'].match('1;2;3;4;5;6;7;8') is None | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
def test_delivery_regex():
assert VALIDATE_REGEX['delivery'].match('') is None
assert VALIDATE_REGEX['delivery'].match('a') is None
assert VALIDATE_REGEX['delivery'].match('1') is None
assert VALIDATE_REGEX['delivery'].match('1.') is None
assert VALIDATE_REGEX['delivery'].match('1.5') is None
assert VALIDATE_REGEX['delivery'].match('1,2') is None
assert VALIDATE_REGEX['delivery'].match('1-2') is None
assert VALIDATE_REGEX['delivery'].match('1;2') is None
assert VALIDATE_REGEX['delivery'].match('1:2') is None
assert VALIDATE_REGEX['delivery'].match('1,2,3') is None
assert VALIDATE_REGEX['delivery'].match('Y') is None
assert VALIDATE_REGEX['delivery'].match('N') is None
assert VALIDATE_REGEX['delivery'].match('YY') is None
assert VALIDATE_REGEX['delivery'].match('YYY') is None
assert VALIDATE_REGEX['delivery'].match('YYYY') is None
assert VALIDATE_REGEX['delivery'].match('YYYYY') is None
assert VALIDATE_REGEX['delivery'].match('YYYYYY') is None
assert VALIDATE_REGEX['delivery'].match('YYYYYYY') is not None
assert VALIDATE_REGEX['delivery'].match('YYYYYYYY') is None
assert VALIDATE_REGEX['delivery'].match('NNNNNNN') is not None
assert VALIDATE_REGEX['delivery'].match('NYNNNNN') is not None
assert VALIDATE_REGEX['delivery'].match('NYYYYNN') is not None
assert VALIDATE_REGEX['delivery'].match('NYYYYYY') is not None
assert VALIDATE_REGEX['delivery'].match('NYYYYYYY') is None
assert VALIDATE_REGEX['delivery'].match('N,N,N,N,N,N,N') is None
assert VALIDATE_REGEX['delivery'].match('N;N;N;N;N;N;N') is None
assert VALIDATE_REGEX['delivery'].match('N-N-N-N-N-N-N') is None
assert VALIDATE_REGEX['delivery'].match('N N N N N N N') is None
assert VALIDATE_REGEX['delivery'].match('YYYYYYy') is None
assert VALIDATE_REGEX['delivery'].match('YYYYYYn') is None | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
def test_regex_hyphen():
assert SPLIT_REGEX['hyphen'].split('1-2') == ['1', '2']
assert SPLIT_REGEX['hyphen'].split('1-2-3') == ['1', '2', '3']
assert SPLIT_REGEX['hyphen'].split('1 -2-3') == ['1', '2', '3']
assert SPLIT_REGEX['hyphen'].split('1 - 2-3') == ['1', '2', '3']
assert SPLIT_REGEX['hyphen'].split('1- 2-3') == ['1', '2', '3']
assert SPLIT_REGEX['hyphen'].split('1') == ['1']
assert SPLIT_REGEX['hyphen'].split('1-') == ['1', '']
assert SPLIT_REGEX['hyphen'].split('1-2-') == ['1', '2', '']
assert SPLIT_REGEX['hyphen'].split('1-2-3-') == ['1', '2', '3', '']
assert SPLIT_REGEX['hyphen'].split('1,2-3') == ['1,2', '3']
assert SPLIT_REGEX['hyphen'].split('1,2-3-') == ['1,2', '3', '']
assert SPLIT_REGEX['hyphen'].split('1,2, 3,') == ['1,2, 3,']
assert SPLIT_REGEX['hyphen'].split('') == ['']
def test_regex_comma():
assert SPLIT_REGEX['comma'].split('1,2') == ['1', '2']
assert SPLIT_REGEX['comma'].split('1,2,3') == ['1', '2', '3']
assert SPLIT_REGEX['comma'].split('1 ,2,3') == ['1', '2', '3']
assert SPLIT_REGEX['comma'].split('1 , 2,3') == ['1', '2', '3']
assert SPLIT_REGEX['comma'].split('1, 2,3') == ['1', '2', '3']
assert SPLIT_REGEX['comma'].split('1') == ['1']
assert SPLIT_REGEX['comma'].split('1,') == ['1', '']
assert SPLIT_REGEX['comma'].split('1, ') == ['1', '']
assert SPLIT_REGEX['comma'].split('1,2,') == ['1', '2', '']
assert SPLIT_REGEX['comma'].split('1,2,3,') == ['1', '2', '3', '']
assert SPLIT_REGEX['comma'].split('1-2,3') == ['1-2', '3']
assert SPLIT_REGEX['comma'].split('1-2,3,') == ['1-2', '3', '']
assert SPLIT_REGEX['comma'].split('1-2-3') == ['1-2-3']
assert SPLIT_REGEX['comma'].split('1-2- 3') == ['1-2- 3']
assert SPLIT_REGEX['comma'].split('') == [''] | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
def test_regex_semicolon():
assert SPLIT_REGEX['semicolon'].split('1;2') == ['1', '2']
assert SPLIT_REGEX['semicolon'].split('1;2;3') == ['1', '2', '3']
assert SPLIT_REGEX['semicolon'].split('1 ;2;3') == ['1', '2', '3']
assert SPLIT_REGEX['semicolon'].split('1 ; 2;3') == ['1', '2', '3']
assert SPLIT_REGEX['semicolon'].split('1; 2;3') == ['1', '2', '3']
assert SPLIT_REGEX['semicolon'].split('1') == ['1']
assert SPLIT_REGEX['semicolon'].split('1;') == ['1', '']
assert SPLIT_REGEX['semicolon'].split('1; ') == ['1', '']
assert SPLIT_REGEX['semicolon'].split('1;2;') == ['1', '2', '']
assert SPLIT_REGEX['semicolon'].split('1;2;3;') == ['1', '2', '3', '']
assert SPLIT_REGEX['semicolon'].split('1-2;3') == ['1-2', '3']
assert SPLIT_REGEX['semicolon'].split('1-2;3;') == ['1-2', '3', '']
assert SPLIT_REGEX['semicolon'].split('1-2-3') == ['1-2-3']
assert SPLIT_REGEX['semicolon'].split('1-2- 3') == ['1-2- 3']
assert SPLIT_REGEX['semicolon'].split('') == ['']
def test_undelivered_string_parsing():
MONTH = 5
YEAR = 2017
assert parse_undelivered_string('', MONTH, YEAR) == set([])
assert parse_undelivered_string('1', MONTH, YEAR) == set([
date_type(year=YEAR, month=MONTH, day=1)
])
assert parse_undelivered_string('1-2', MONTH, YEAR) == set([
date_type(year=YEAR, month=MONTH, day=1),
date_type(year=YEAR, month=MONTH, day=2)
]) | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
assert parse_undelivered_string('5-17', MONTH, YEAR) == set([
date_type(year=YEAR, month=MONTH, day=5),
date_type(year=YEAR, month=MONTH, day=6),
date_type(year=YEAR, month=MONTH, day=7),
date_type(year=YEAR, month=MONTH, day=8),
date_type(year=YEAR, month=MONTH, day=9),
date_type(year=YEAR, month=MONTH, day=10),
date_type(year=YEAR, month=MONTH, day=11),
date_type(year=YEAR, month=MONTH, day=12),
date_type(year=YEAR, month=MONTH, day=13),
date_type(year=YEAR, month=MONTH, day=14),
date_type(year=YEAR, month=MONTH, day=15),
date_type(year=YEAR, month=MONTH, day=16),
date_type(year=YEAR, month=MONTH, day=17)
])
assert parse_undelivered_string('5-17,19', MONTH, YEAR) == set([
date_type(year=YEAR, month=MONTH, day=5),
date_type(year=YEAR, month=MONTH, day=6),
date_type(year=YEAR, month=MONTH, day=7),
date_type(year=YEAR, month=MONTH, day=8),
date_type(year=YEAR, month=MONTH, day=9),
date_type(year=YEAR, month=MONTH, day=10),
date_type(year=YEAR, month=MONTH, day=11),
date_type(year=YEAR, month=MONTH, day=12),
date_type(year=YEAR, month=MONTH, day=13),
date_type(year=YEAR, month=MONTH, day=14),
date_type(year=YEAR, month=MONTH, day=15),
date_type(year=YEAR, month=MONTH, day=16),
date_type(year=YEAR, month=MONTH, day=17),
date_type(year=YEAR, month=MONTH, day=19)
]) | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
assert parse_undelivered_string('5-17,19-21', MONTH, YEAR) == set([
date_type(year=YEAR, month=MONTH, day=5),
date_type(year=YEAR, month=MONTH, day=6),
date_type(year=YEAR, month=MONTH, day=7),
date_type(year=YEAR, month=MONTH, day=8),
date_type(year=YEAR, month=MONTH, day=9),
date_type(year=YEAR, month=MONTH, day=10),
date_type(year=YEAR, month=MONTH, day=11),
date_type(year=YEAR, month=MONTH, day=12),
date_type(year=YEAR, month=MONTH, day=13),
date_type(year=YEAR, month=MONTH, day=14),
date_type(year=YEAR, month=MONTH, day=15),
date_type(year=YEAR, month=MONTH, day=16),
date_type(year=YEAR, month=MONTH, day=17),
date_type(year=YEAR, month=MONTH, day=19),
date_type(year=YEAR, month=MONTH, day=20),
date_type(year=YEAR, month=MONTH, day=21)
])
assert parse_undelivered_string('5-17,19-21,23', MONTH, YEAR) == set([
date_type(year=YEAR, month=MONTH, day=5),
date_type(year=YEAR, month=MONTH, day=6),
date_type(year=YEAR, month=MONTH, day=7),
date_type(year=YEAR, month=MONTH, day=8),
date_type(year=YEAR, month=MONTH, day=9),
date_type(year=YEAR, month=MONTH, day=10),
date_type(year=YEAR, month=MONTH, day=11),
date_type(year=YEAR, month=MONTH, day=12),
date_type(year=YEAR, month=MONTH, day=13),
date_type(year=YEAR, month=MONTH, day=14),
date_type(year=YEAR, month=MONTH, day=15),
date_type(year=YEAR, month=MONTH, day=16),
date_type(year=YEAR, month=MONTH, day=17),
date_type(year=YEAR, month=MONTH, day=19),
date_type(year=YEAR, month=MONTH, day=20),
date_type(year=YEAR, month=MONTH, day=21),
date_type(year=YEAR, month=MONTH, day=23)
]) | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
assert parse_undelivered_string('mondays', MONTH, YEAR) == set([
date_type(year=YEAR, month=MONTH, day=1),
date_type(year=YEAR, month=MONTH, day=8),
date_type(year=YEAR, month=MONTH, day=15),
date_type(year=YEAR, month=MONTH, day=22),
date_type(year=YEAR, month=MONTH, day=29)
])
assert parse_undelivered_string('mondays, wednesdays', MONTH, YEAR) == set([
date_type(year=YEAR, month=MONTH, day=1),
date_type(year=YEAR, month=MONTH, day=8),
date_type(year=YEAR, month=MONTH, day=15),
date_type(year=YEAR, month=MONTH, day=22),
date_type(year=YEAR, month=MONTH, day=29),
date_type(year=YEAR, month=MONTH, day=3),
date_type(year=YEAR, month=MONTH, day=10),
date_type(year=YEAR, month=MONTH, day=17),
date_type(year=YEAR, month=MONTH, day=24),
date_type(year=YEAR, month=MONTH, day=31)
])
assert parse_undelivered_string('2-monday', MONTH, YEAR) == set([
date_type(year=YEAR, month=MONTH, day=8)
])
assert parse_undelivered_string('2-monday, 3-wednesday', MONTH, YEAR) == set([
date_type(year=YEAR, month=MONTH, day=8),
date_type(year=YEAR, month=MONTH, day=17)
])
def test_sql_query():
assert generate_sql_query(
'test'
) == "SELECT * FROM test;"
assert generate_sql_query(
'test',
columns=['a']
) == "SELECT a FROM test;"
assert generate_sql_query(
'test',
columns=['a', 'b']
) == "SELECT a, b FROM test;"
assert generate_sql_query(
'test',
conditions={'a': '\"b\"'}
) == "SELECT * FROM test WHERE a = \"b\";"
assert generate_sql_query(
'test',
conditions={
'a': '\"b\"',
'c': '\"d\"'
}
) == "SELECT * FROM test WHERE a = \"b\" AND c = \"d\";" | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
assert generate_sql_query(
'test',
conditions={
'a': '\"b\"',
'c': '\"d\"'
},
columns=['a', 'b']
) == "SELECT a, b FROM test WHERE a = \"b\" AND c = \"d\";"
def test_number_of_days_per_week():
assert get_number_of_days_per_week(1, 2022) == [5, 4, 4, 4, 4, 5, 5]
assert get_number_of_days_per_week(2, 2022) == [4, 4, 4, 4, 4, 4, 4]
assert get_number_of_days_per_week(3, 2022) == [4, 5, 5 ,5, 4, 4, 4]
assert get_number_of_days_per_week(2, 2020) == [4, 4, 4, 4, 4, 5, 4]
assert get_number_of_days_per_week(12, 1954) == [4, 4, 5, 5, 5, 4, 4]
def test_calculating_cost_of_one_paper():
DAYS_PER_WEEK = [5, 4, 4, 4, 4, 5, 5]
COST_PER_DAY: dict[int, float] = {
0: 0,
1: 0,
2: 2,
3: 2,
4: 5,
5: 0,
6: 1
}
DELIVERY_DATA: dict[int, bool] = {
0: False,
1: False,
2: True,
3: True,
4: True,
5: False,
6: True
}
assert calculate_cost_of_one_paper(
DAYS_PER_WEEK,
set([]),
(
COST_PER_DAY,
DELIVERY_DATA
)
) == 41
assert calculate_cost_of_one_paper(
DAYS_PER_WEEK,
set([]),
(
COST_PER_DAY,
{
0: False,
1: False,
2: True,
3: True,
4: True,
5: False,
6: False
}
)
) == 36
assert calculate_cost_of_one_paper(
DAYS_PER_WEEK,
set([
date_type(year=2022, month=1, day=8)
]),
(
COST_PER_DAY,
DELIVERY_DATA
)
) == 41 | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
assert calculate_cost_of_one_paper(
DAYS_PER_WEEK,
set([
date_type(year=2022, month=1, day=8),
date_type(year=2022, month=1, day=8)
]),
(
COST_PER_DAY,
DELIVERY_DATA
)
) == 41
assert calculate_cost_of_one_paper(
DAYS_PER_WEEK,
set([
date_type(year=2022, month=1, day=8),
date_type(year=2022, month=1, day=17)
]),
(
COST_PER_DAY,
DELIVERY_DATA
)
) == 41
assert calculate_cost_of_one_paper(
DAYS_PER_WEEK,
set([
date_type(year=2022, month=1, day=2)
]),
(
COST_PER_DAY,
DELIVERY_DATA
)
) == 40
assert calculate_cost_of_one_paper(
DAYS_PER_WEEK,
set([
date_type(year=2022, month=1, day=2),
date_type(year=2022, month=1, day=2)
]),
(
COST_PER_DAY,
DELIVERY_DATA
)
) == 40
assert calculate_cost_of_one_paper(
DAYS_PER_WEEK,
set([
date_type(year=2022, month=1, day=6),
date_type(year=2022, month=1, day=7)
]),
(
COST_PER_DAY,
DELIVERY_DATA
)
) == 34
assert calculate_cost_of_one_paper(
DAYS_PER_WEEK,
set([
date_type(year=2022, month=1, day=6),
date_type(year=2022, month=1, day=7),
date_type(year=2022, month=1, day=8)
]),
(
COST_PER_DAY,
DELIVERY_DATA
)
) == 34 | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
assert calculate_cost_of_one_paper(
DAYS_PER_WEEK,
set([
date_type(year=2022, month=1, day=6),
date_type(year=2022, month=1, day=7),
date_type(year=2022, month=1, day=7),
date_type(year=2022, month=1, day=7),
date_type(year=2022, month=1, day=8),
date_type(year=2022, month=1, day=8),
date_type(year=2022, month=1, day=8)
]),
(
COST_PER_DAY,
DELIVERY_DATA
)
) == 34
def test_extracting_days_and_costs():
assert extract_days_and_costs(None, None) == ([], [])
assert extract_days_and_costs('NNNNNNN', None) == (
[False, False, False, False, False, False, False],
[]
)
assert extract_days_and_costs('NNNYNNN', '7') == (
[False, False, False, True, False, False, False],
[0, 0, 0, 7, 0, 0, 0]
)
assert extract_days_and_costs('NNNYNNN', '7;7') == (
[False, False, False, True, False, False, False],
[0, 0, 0, 7, 0, 0, 0]
)
assert extract_days_and_costs('NNNYNNY', '7;4') == (
[False, False, False, True, False, False, True],
[0, 0, 0, 7, 0, 0, 4]
)
assert extract_days_and_costs('NNNYNNY', '7;4.7') == (
[False, False, False, True, False, False, True],
[0, 0, 0, 7, 0, 0, 4.7]
) | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
def test_validate_month_and_year():
assert validate_month_and_year(1, 2020)[0]
assert validate_month_and_year(12, 2020)[0]
assert validate_month_and_year(1, 2021)[0]
assert validate_month_and_year(12, 2021)[0]
assert validate_month_and_year(1, 2022)[0]
assert validate_month_and_year(12, 2022)[0]
assert not validate_month_and_year(-54, 2020)[0]
assert not validate_month_and_year(0, 2020)[0]
assert not validate_month_and_year(13, 2020)[0]
assert not validate_month_and_year(45, 2020)[0]
assert not validate_month_and_year(1, -5)[0]
assert not validate_month_and_year(12, -5)[0]
assert not validate_month_and_year(1.6, 10)[0] # type: ignore
assert not validate_month_and_year(12.6, 10)[0] # type: ignore
assert not validate_month_and_year(1, '10')[0] # type: ignore
assert not validate_month_and_year(12, '10')[0] # type: ignore
If you need it, here is a link to the GitHub repo for this project. It's at the same commit as the code above, and I won't edit this so that any discussion is consistent.
https://github.com/eccentricOrange/npbc/tree/6020a4f5db0bf40f54e35b725b305cfeafdd8f2b
Answer:
Once you calculate, the results are displayed and copied to your clipboard
This is not a good idea for a CLI. It may be a reasonable (opt-in!) option for a GUI, but for a CLI the overwhelming expectation is that the results are printed to stdout, and the user can copy from there if they want. You say
I will be the sole user of this app until it's converted into a server thing as stated in the table. But you're not expected to know that, and it's probably a bad idea for me to learn non-standard practices. | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
Indeed. For us to get better as practitioners, even if our programs are only intended for us, best practice is to make it approachable for everyone.
Overall this code is pretty good! There are type hints, you're using pathlib, you have reasonable data directories, you have tests, etc.
Don't represent VALIDATE_REGEX as a dictionary where all of the keys are referenced statically. A saner option is to move this to a different file, which will still offer scope but not require the machinery of a dictionary. SPLIT_REGEX is probably best as three separate regex variables.
Having a regex validator for CSV content is concerning. You shouldn't be parsing CSV content yourself. You say:
This refers to user input, not a "data" file
CSV is vaguely a machine-legible format and not expected to be a user-legible format. So if it doesn't come from a file, then it's probably not an appropriate choice for user input of your undelivered string. Your other post shows that you're accepting this as one argument. Instead, consider using argparse and its nargs='+' support to accumulate multiple arguments to a list, which will not require a comma separator.
generate_sql_query is attempting to be too clever. Don't construct your queries like this; just write them out.
What's with query_database returning []? That statement will never be executed, so remove it.
get_number_of_days_per_week is a good candidate for being converted from returning a list to yielding an iterator. You ask:
it's called only once and the value is saved to a constant. So, why does list vs generator matter? | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
it's called only once and the value is saved to a constant. So, why does list vs generator matter?
It doesn't matter how many times it's called, and it doesn't matter whether it's saved to a constant. An iterator function offers "streamed" calculation instead of in-memory calculation to any callers that want it, and if a caller does actually want a list or tuple, they can cast to it there. Other than the memory representation flexibility, this is mostly a matter of syntactic sugar since no return is necessary and no inner list variable is needed.
Your "bug report" here:
print("Congratulations! You broke the program!")
print("You managed to write a string that the program considers valid, but isn't actually.")
print("Please report it to the developer.")
print(f"\nThe string you wrote was: {string}")
print("This data has not been counted.")
is well-intended, but would be better-represented by
refactoring out the contents of the loop to its own function;
in that function, throwing an exception at this scope - likely a custom exception subclass that can accept your invalid string as a member;
back in the loop that calls that function, wrap it in a try/except that catches your (specific) exception and prints something like what you've already shown.
Similar for return False, "Something went wrong." which should be replaced with proper exception handling rather than a boolean return.
(0 < start) and (start <= end)
is better-represented as
0 < start <= end
. Similar for 0 < n <= get_number_of_days_per_week(month, year)[WEEKDAY_NAMES.index(weekday.capitalize())].
TIMESTAMP should not be capitalised, since it's a local.
Your ','.join([ should not have an inner list and should pass the generator directly.
This formatting block:
format_string = f"For {date_type(year=year, month=month, day=1).strftime(r'%B %Y')}\n\n"
format_string += f"*TOTAL*: {total}\n" | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, unit-testing, functional-programming, regex, validation
format_string += '\n'.join([
f"{papers[paper_id]}: {cost}" # type: ignore
for paper_id, cost in costs.items()
])
return f"{format_string}\n"
is... fine? Other than the last f-string, which - since you've already iteratively concatenated, should just have a + '\n'. If you're concerned about the O(n^2) cost of successive string concatenation (which you probably shouldn't need to be), then either use StringIO, or do '\n'.join(). The latter option would be nice as an iterator function, something like
def format_total() -> Iterator[str]:
# ...
date_type_str = date_type(year=year, month=month, day=1).strftime(r'%B %Y')
yield f"For {date_type_str}"
yield f"*TOTAL*: {total}"
for paper_id, cost in costs.items():
yield f"{papers[paper_id]}: {cost}"
# ...
'\n'.join(format_total())
bool(int(day == 'Y')) should just be day == 'Y' which is already a boolean. | {
"domain": "codereview.stackexchange",
"id": 43298,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, unit-testing, functional-programming, regex, validation",
"url": null
} |
python, console, validation, user-interface
Title: Newspaper Bill Calculator CLI with Python (2 of 3, CLI)
Question: Code is posted after explanation.
Due to the size of the project, this is being posted in three separate posts. This also ensures each post is more focused.
Post 1 of 3, Core: Newspaper Bill Calculator CLI with Python (1 of 3, Core)
Post 3 of 3, Database: Newspaper Bill Calculator CLI with Python (3 of 3, Database)
What is this?
This application helps you calculate monthly newspaper bills. The goal is to generate a message that I can paste into WhatsApp and send to my newspaper vendor. The end result here is a CLI tool that will be later used as a back-end to build GUIs (hence learn about: C#, HTML/CSS/JS, Flutter). In its current form, everything will be "compiled" by PyInstaller into one-file stand-alone executables for the end-user using GitHub Actions.
The other important goal was to be a testbed for learning a bunch of new tools: more Python libraries, SQL connectors, GitHub Actions (CI/CD, if I understand correctly), unit tests, CLI libraries, type-hinting, regex. I had earlier built this on a different platform, so I now have a solid idea of how this application is used.
Key concepts
Each newspaper has a certain cost per day of the week
Each newspaper may or may not be delivered on a given day
Each newspaper has a name, and a number called a key
You may register any dates when you didn't receive a paper in advance using the addudl command
Once you calculate, the results are displayed and copied to your clipboard
What files exist?
(ignoring conventional ones like README and requirements.txt)
File
Purpose/Description
Review
npbc_core.py
Provide the core functionality: the calculation, parsing and validation of user input, interaction with the DB etc. Later on, some functionality from this will be extracted to create server-side code that can service more users, but I have to learn a lot more before getting there.
Please review this. | {
"domain": "codereview.stackexchange",
"id": 43299,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, console, validation, user-interface",
"url": null
} |
python, console, validation, user-interface
npbc_cli.py
Import functionality from npbc_core.py and wrap a CLI layer on it using argparse. Also provide some additional validation.
Please review this.
npbc_updater.py
Provide a utility to update the application on the user's end.
Don't bother reviewing this (code not included).
test_core.py
Test the functionality of the core file (pytest). This isn't as exhaustive as I'd like, but it did a good job of capturing many of my mistakes.
Please review this.
data/schema.sql
Database schema. In my local environment, the data folder also has a test database file (but I don't want to upload this online).
Please review this if you can (not high priority).
Known problems
Tests are not exhaustive (please suggest anything you think of).
Tests are not well commented (working on this right now in a local branch).
SQL injection is possible in some cases by -k/--key CLI parameters, if you can figure out a way to insert a semicolon in an integer. I will remove this in a future version, once I find a way to improve or remove the generate_sql_query() function.
A lot of documentation is tied up in the CLI UI and comments, and is not an explicit document.
npbc_cli.py
from argparse import ArgumentParser
from argparse import Namespace as arg_namespace
from datetime import datetime
from colorama import Fore, Style
from pyperclip import copy as copy_to_clipboard
from npbc_core import (VALIDATE_REGEX, WEEKDAY_NAMES, add_new_paper,
add_undelivered_string, calculate_cost_of_all_papers,
delete_existing_paper, delete_undelivered_string,
edit_existing_paper, extract_days_and_costs,
format_output, generate_sql_query, get_previous_month,
query_database, save_results, setup_and_connect_DB,
validate_month_and_year, validate_undelivered_string)
## setup parsers
def define_and_read_args() -> arg_namespace: | {
"domain": "codereview.stackexchange",
"id": 43299,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, console, validation, user-interface",
"url": null
} |
python, console, validation, user-interface
## setup parsers
def define_and_read_args() -> arg_namespace:
# main parser for all commands
main_parser = ArgumentParser(
prog="npbc",
description="Calculates your monthly newspaper bill."
)
functions = main_parser.add_subparsers(required=True)
# calculate subparser
calculate_parser = functions.add_parser(
'calculate',
help="Calculate the bill for one month. Previous month will be used if month or year flags are not set."
)
calculate_parser.set_defaults(func=calculate)
calculate_parser.add_argument('-m', '--month', type=int, help="Month to calculate bill for. Must be between 1 and 12.")
calculate_parser.add_argument('-y', '--year', type=int, help="Year to calculate bill for. Must be between 1 and 9999.")
calculate_parser.add_argument('-c', '--nocopy', help="Don't copy the result of the calculation to the clipboard.", action='store_true')
calculate_parser.add_argument('-l', '--nolog', help="Don't log the result of the calculation.", action='store_true')
# add undelivered string subparser
addudl_parser = functions.add_parser(
'addudl',
help="Store a date when paper(s) were not delivered. Previous month will be used if month or year flags are not set."
)
addudl_parser.set_defaults(func=addudl)
addudl_parser.add_argument('-m', '--month', type=int, help="Month to register undelivered incident(s) for. Must be between 1 and 12.")
addudl_parser.add_argument('-y', '--year', type=int, help="Year to register undelivered incident(s) for. Must be between 1 and 9999.")
addudl_parser.add_argument('-k', '--key', type=str, help="Key of paper to register undelivered incident(s) for.", required=True)
addudl_parser.add_argument('-u', '--undelivered', type=str, help="Dates when you did not receive any papers.", required=True) | {
"domain": "codereview.stackexchange",
"id": 43299,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, console, validation, user-interface",
"url": null
} |
python, console, validation, user-interface
# delete undelivered string subparser
deludl_parser = functions.add_parser(
'deludl',
help="Delete a stored date when paper(s) were not delivered. Previous month will be used if month or year flags are not set."
)
deludl_parser.set_defaults(func=deludl)
deludl_parser.add_argument('-k', '--key', type=str, help="Key of paper to unregister undelivered incident(s) for.", required=True)
deludl_parser.add_argument('-m', '--month', type=int, help="Month to unregister undelivered incident(s) for. Must be between 1 and 12.", required=True)
deludl_parser.add_argument('-y', '--year', type=int, help="Year to unregister undelivered incident(s) for. Must be between 1 and 9999.", required=True)
# get undelivered string subparser
getudl_parser = functions.add_parser(
'getudl',
help="Get a list of all stored date strings when paper(s) were not delivered."
)
getudl_parser.set_defaults(func=getudl)
getudl_parser.add_argument('-k', '--key', type=str, help="Key for paper.")
getudl_parser.add_argument('-m', '--month', type=int, help="Month. Must be between 1 and 12.")
getudl_parser.add_argument('-y', '--year', type=int, help="Year. Must be between 1 and 9999.")
getudl_parser.add_argument('-u', '--undelivered', type=str, help="Dates when you did not receive any papers.")
# edit paper subparser
editpaper_parser = functions.add_parser(
'editpaper',
help="Edit a newspaper\'s name, days delivered, and/or price."
) | {
"domain": "codereview.stackexchange",
"id": 43299,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, console, validation, user-interface",
"url": null
} |
python, console, validation, user-interface
editpaper_parser.set_defaults(func=editpaper)
editpaper_parser.add_argument('-n', '--name', type=str, help="Name for paper to be edited.")
editpaper_parser.add_argument('-d', '--days', type=str, help="Number of days the paper to be edited is delivered. Monday is the first day, and all seven weekdays are required. A 'Y' means it is delivered, and an 'N' means it isn't. No separator required.")
editpaper_parser.add_argument('-p', '--price', type=str, help="Daywise prices of paper to be edited. Monday is the first day. Values must be separated by semicolons, and 0s are ignored.")
editpaper_parser.add_argument('-k', '--key', type=str, help="Key for paper to be edited.", required=True)
# add paper subparser
addpaper_parser = functions.add_parser(
'addpaper',
help="Add a new newspaper to the list of newspapers."
)
addpaper_parser.set_defaults(func=addpaper)
addpaper_parser.add_argument('-n', '--name', type=str, help="Name for paper to be added.", required=True)
addpaper_parser.add_argument('-d', '--days', type=str, help="Number of days the paper to be added is delivered. Monday is the first day, and all seven weekdays are required. A 'Y' means it is delivered, and an 'N' means it isn't. No separator required.", required=True)
addpaper_parser.add_argument('-p', '--price', type=str, help="Daywise prices of paper to be added. Monday is the first day. Values must be separated by semicolons, and 0s are ignored.", required=True)
# delete paper subparser
delpaper_parser = functions.add_parser(
'delpaper',
help="Delete a newspaper from the list of newspapers."
)
delpaper_parser.set_defaults(func=delpaper)
delpaper_parser.add_argument('-k', '--key', type=str, help="Key for paper to be deleted.", required=True)
# get paper subparser
getpapers_parser = functions.add_parser(
'getpapers',
help="Get all newspapers."
) | {
"domain": "codereview.stackexchange",
"id": 43299,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, console, validation, user-interface",
"url": null
} |
python, console, validation, user-interface
getpapers_parser.set_defaults(func=getpapers)
getpapers_parser.add_argument('-n', '--names', help="Get the names of the newspapers.", action='store_true')
getpapers_parser.add_argument('-d', '--days', help="Get the days the newspapers are delivered. Monday is the first day, and all seven weekdays are required. A 'Y' means it is delivered, and an 'N' means it isn't.", action='store_true')
getpapers_parser.add_argument('-p', '--prices', help="Get the daywise prices of the newspapers. Monday is the first day. Values must be separated by semicolons.", action='store_true')
# get undelivered logs subparser
getlogs_parser = functions.add_parser(
'getlogs',
help="Get the log of all undelivered dates."
)
getlogs_parser.set_defaults(func=getlogs)
getlogs_parser.add_argument('-m', '--month', type=int, help="Month. Must be between 1 and 12.")
getlogs_parser.add_argument('-y', '--year', type=int, help="Year. Must be between 1 and 9999.")
getlogs_parser.add_argument('-k', '--key', type=str, help="Key for paper.", required=True)
# update application subparser
update_parser = functions.add_parser(
'update',
help="Update the application."
)
update_parser.set_defaults(func=update)
return main_parser.parse_args()
## print out a coloured status message using Colorama
def status_print(status: bool, message: str) -> None:
if status:
print(f"{Fore.GREEN}{Style.BRIGHT}{message}{Style.RESET_ALL}\n")
else:
print(f"{Fore.RED}{Style.BRIGHT}{message}{Style.RESET_ALL}\n")
## calculate the cost for a given month and year
# default to the previous month if no month and no year is given
# default to the current month if no month is given and year is given
# default to the current year if no year is given and month is given
def calculate(args: arg_namespace) -> None:
# deal with month and year
if args.month or args.year: | {
"domain": "codereview.stackexchange",
"id": 43299,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, console, validation, user-interface",
"url": null
} |
python, console, validation, user-interface
# deal with month and year
if args.month or args.year:
feedback = validate_month_and_year(args.month, args.year)
if not feedback[0]:
status_print(*feedback)
return
if args.month:
month = args.month
else:
month = datetime.now().month
if args.year:
year = args.year
else:
year = datetime.now().year
else:
previous_month = get_previous_month()
month = previous_month.month
year = previous_month.year
# look for undelivered strings in the database
existing_strings = query_database(
generate_sql_query(
'undelivered_strings',
columns=['paper_id', 'string'],
conditions={
'month': month,
'year': year
}
)
)
# associate undelivered strings with their paper_id
undelivered_strings: dict[int, str] = {
paper_id: undelivered_string
for paper_id, undelivered_string in existing_strings
}
# calculate the cost for each paper, as well as the total cost
costs, total, undelivered_dates = calculate_cost_of_all_papers(
undelivered_strings,
month,
year
)
# format the results
formatted = format_output(costs, total, month, year)
# unless the user specifies so, copy the results to the clipboard
if not args.nocopy:
copy_to_clipboard(formatted)
formatted += '\nSummary copied to clipboard.'
# unless the user specifies so, log the results to the database
if not args.nolog:
save_results(undelivered_dates, month, year)
formatted += '\nLog saved to file.'
# print the results
status_print(True, "Success!")
print(f"SUMMARY:\n{formatted}")
## add undelivered strings to the database
# default to the current month if no month and/or no year is given
def addudl(args: arg_namespace): | {
"domain": "codereview.stackexchange",
"id": 43299,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, console, validation, user-interface",
"url": null
} |
python, console, validation, user-interface
# validate the month and year
feedback = validate_month_and_year(args.month, args.year)
if feedback[0]:
# if no month is given, default to the current month
if args.month:
month = args.month
else:
month = datetime.now().month
# if no year is given, default to the current year
if args.year:
year = args.year
else:
year = datetime.now().year
# add the undelivered strings to the database
feedback = add_undelivered_string(
args.key,
str(args.undelivered).lower().strip(),
month,
year
)
status_print(*feedback)
## delete undelivered strings from the database
def deludl(args: arg_namespace) -> None:
# validate the month and year
feedback = validate_month_and_year(args.month, args.year)
# delete the undelivered strings from the database
if feedback[0]:
feedback = delete_undelivered_string(
args.key,
args.month,
args.year
)
status_print(*feedback)
## get undelivered strings from the database
# filter by whichever parameter the user provides. they as many as they want.
# available parameters: month, year, key, string
def getudl(args: arg_namespace) -> None:
# validate the month and year
feedback = validate_month_and_year(args.month, args.year)
if not feedback[0]:
status_print(*feedback)
return
conditions = {}
if args.key:
conditions['paper_id'] = args.key
if args.month:
conditions['month'] = args.month
if args.year:
conditions['year'] = args.year
if args.undelivered:
conditions['strings'] = str(args.undelivered).lower().strip()
if not validate_undelivered_string(conditions['strings']):
status_print(False, "Invalid undelivered string.")
return | {
"domain": "codereview.stackexchange",
"id": 43299,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, console, validation, user-interface",
"url": null
} |
python, console, validation, user-interface
# if the undelivered strings exist, fetch them
undelivered_strings = query_database(
generate_sql_query(
'undelivered_strings',
conditions=conditions
)
)
# if there were undelivered strings, print them
if undelivered_strings:
status_print(True, 'Found undelivered strings.')
print(f"{Fore.YELLOW}entry_id{Style.RESET_ALL} | {Fore.YELLOW}year{Style.RESET_ALL} | {Fore.YELLOW}month{Style.RESET_ALL} | {Fore.YELLOW}paper_id{Style.RESET_ALL} | {Fore.YELLOW}string{Style.RESET_ALL}")
for string in undelivered_strings:
print('|'.join([str(item) for item in string]))
# otherwise, print that there were no undelivered strings
else:
status_print(False, 'No undelivered strings found.')
## edit the data for one paper
def editpaper(args: arg_namespace) -> None:
feedback = True, ""
days, costs = "", ""
# validate the string for delivery days
if args.days:
days = str(args.days).lower().strip()
if not VALIDATE_REGEX['delivery'].match(days):
feedback = False, "Invalid delivery days."
# validate the string for costs
if args.costs:
costs = str(args.costs).lower().strip()
if not VALIDATE_REGEX['prices'].match(costs):
feedback = False, "Invalid prices."
# if the string for delivery days and costs are valid, edit the paper
if feedback[0]:
feedback = edit_existing_paper(
args.key,
args.name,
*extract_days_and_costs(days, costs)
)
status_print(*feedback)
## add a new paper to the database
def addpaper(args: arg_namespace) -> None:
feedback = True, ""
days, costs = "", ""
# validate the string for delivery days
if args.days:
days = str(args.days).lower().strip()
if not VALIDATE_REGEX['delivery'].match(days):
feedback = False, "Invalid delivery days." | {
"domain": "codereview.stackexchange",
"id": 43299,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, console, validation, user-interface",
"url": null
} |
python, console, validation, user-interface
# validate the string for costs
if args.costs:
costs = str(args.costs).lower().strip()
if not VALIDATE_REGEX['prices'].match(costs):
feedback = False, "Invalid prices."
# if the string for delivery days and costs are valid, add the paper
if feedback[0]:
feedback = add_new_paper(
args.name,
*extract_days_and_costs(days, costs)
)
status_print(*feedback)
## delete a paper from the database
def delpaper(args: arg_namespace) -> None:
# attempt to delete the paper
feedback = delete_existing_paper(
args.key
)
status_print(*feedback)
## get a list of all papers in the database
# filter by whichever parameter the user provides. they may use as many as they want (but keys are always printed)
# available parameters: name, days, costs
# the output is provided as a formatted table, printed to the standard output
def getpapers(args: arg_namespace) -> None:
headers = ['paper_id']
# fetch a list of all papers' IDs
papers_id_list = [
paper_id
for paper_id, in query_database(
generate_sql_query(
'papers',
columns=['paper_id']
)
)
]
# initialize lists for the data
paper_name_list, paper_days_list, paper_costs_list = [], [], []
# sort the papers' IDs (for the sake of consistency)
papers_id_list.sort()
# if the user wants names, fetch that data and add it to the list
if args.names:
# first get a dictionary of {paper_id: paper_name}
papers_names = {
paper_id: paper_name
for paper_id, paper_name in query_database(
generate_sql_query(
'papers',
columns=['paper_id', 'name']
)
)
} | {
"domain": "codereview.stackexchange",
"id": 43299,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, console, validation, user-interface",
"url": null
} |
python, console, validation, user-interface
# then use the sorted IDs list to create a sorted names list
paper_name_list = [
papers_names[paper_id]
for paper_id in papers_id_list
]
headers.append('name')
# if the user wants delivery days, fetch that data and add it to the list
if args.days:
# initialize a dictionary of {paper_id: {day_id: delivery}}
papers_days = {
paper_id: {}
for paper_id in papers_id_list
}
# then get the data for each paper
for paper_id, day_id, delivered in query_database(
generate_sql_query(
'papers_days_delivered',
columns=['paper_id', 'day_id', 'delivered']
)
):
papers_days[paper_id][day_id] = delivered
# format the data so that it matches the regex pattern /^[YN]{7}$/, the same way the user must input this data
paper_days_list = [
''.join([
'Y' if int(papers_days[paper_id][day_id]) == 1 else 'N'
for day_id, _ in enumerate(WEEKDAY_NAMES)
])
for paper_id in papers_id_list
]
headers.append('days')
# if the user wants costs, fetch that data and add it to the list
if args.prices:
# initialize a dictionary of {paper_id: {day_id: price}}
papers_costs = {
paper_id: {}
for paper_id in papers_id_list
}
# then get the data for each paper
for paper_id, day_id, cost in query_database(
generate_sql_query(
'papers_days_cost',
columns=['paper_id', 'day_id', 'cost']
)
):
papers_costs[paper_id][day_id] = cost | {
"domain": "codereview.stackexchange",
"id": 43299,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, console, validation, user-interface",
"url": null
} |
python, console, validation, user-interface
# format the data so that it matches the regex pattern /^[x](;[x]){6}$/, where /x/ is a number that may be either a floating point or an integer, the same way the user must input this data.
paper_costs_list = [
';'.join([
str(papers_costs[paper_id][day_id])
for day_id, _ in enumerate(WEEKDAY_NAMES)
])
for paper_id in papers_id_list
]
headers.append('costs')
# print the headers
print(' | '.join([
f"{Fore.YELLOW}{header}{Style.RESET_ALL}"
for header in headers
]))
# print the data
for index, paper_id in enumerate(papers_id_list):
print(f"{paper_id}: ", end='')
values = []
if args.names:
values.append(paper_name_list[index])
if args.days:
values.append(paper_days_list[index])
if args.prices:
values.append(paper_costs_list[index])
print(', '.join(values))
## get a log of all deliveries for a paper
# the user may specify parameters to filter the output by. they may use as many as they want, or none
# available parameters: paper_id, month, year
def getlogs(args: arg_namespace) -> None:
# validate the month and year
feedback = validate_month_and_year(args.month, args.year)
if not feedback[0]:
status_print(*feedback)
return
conditions = {}
# if the user specified a particular paper, add it to the conditions
if args.key:
conditions['paper_id'] = args.key
if args.month:
conditions['month'] = args.month
if args.year:
conditions['year'] = args.year
# fetch the data
undelivered_dates = query_database(
generate_sql_query(
'undelivered_dates',
conditions=conditions
)
)
# if data was found, print it
if undelivered_dates:
status_print(True, 'Success!') | {
"domain": "codereview.stackexchange",
"id": 43299,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, console, validation, user-interface",
"url": null
} |
python, console, validation, user-interface
# if data was found, print it
if undelivered_dates:
status_print(True, 'Success!')
print(f"{Fore.YELLOW}entry_id{Style.RESET_ALL} | {Fore.YELLOW}year{Style.RESET_ALL} | {Fore.YELLOW}month{Style.RESET_ALL} | {Fore.YELLOW}paper_id{Style.RESET_ALL} | {Fore.YELLOW}dates{Style.RESET_ALL}")
for date in undelivered_dates:
print(', '.join(date))
# if no data was found, print an error message
else:
status_print(False, 'No results found.')
## update the application
# under normal operation, this function should never run
# if the update CLI argument is provided, this script will never run and the updater will be run instead
def update(args: arg_namespace) -> None:
status_print(False, "Update failed.")
## run the application
def main() -> None:
setup_and_connect_DB()
args = define_and_read_args()
args.func(args)
if __name__ == '__main__':
main()
If you need it, here is a link to the GitHub repo for this project. It's at the same commit as the code above, and I won't edit this so that any discussion is consistent.
https://github.com/eccentricOrange/npbc/tree/6020a4f5db0bf40f54e35b725b305cfeafdd8f2b
Answer: The apostrophe here:
"Edit a newspaper\'s name, days delivered, and/or price."
does not need escaping since the string is double-quoted.
This branching code:
if status:
print(f"{Fore.GREEN}{Style.BRIGHT}{message}{Style.RESET_ALL}\n")
else:
print(f"{Fore.RED}{Style.BRIGHT}{message}{Style.RESET_ALL}\n")
should instead conditionally initialise a colour string, and then unconditionally pass that to a single format-and-print call.
addudl needs a -> None. mypy will warn you about this when correctly configured.
'|'.join([ should not use an inner list and should pass the generator directly. Similar cases elsewhere in the code. | {
"domain": "codereview.stackexchange",
"id": 43299,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, console, validation, user-interface",
"url": null
} |
python, sql, database, sqlite
Title: Newspaper Bill Calculator CLI with Python (3 of 3, Database)
Question: Code is posted after explanation.
Due to the size of the project, this is being posted in three separate posts. This also ensures each post is more focused.
Post 1 of 3, Core: Newspaper Bill Calculator CLI with Python (1 of 3, Core)
Post 2 of 3, CLI: Newspaper Bill Calculator CLI with Python (2 of 3, CLI)
What is this?
This application helps you calculate monthly newspaper bills. The goal is to generate a message that I can paste into WhatsApp and send to my newspaper vendor. The end result here is a CLI tool that will be later used as a back-end to build GUIs (hence learn about: C#, HTML/CSS/JS, Flutter). In its current form, everything will be "compiled" by PyInstaller into one-file stand-alone executables for the end-user using GitHub Actions.
The other important goal was to be a testbed for learning a bunch of new tools: more Python libraries, SQL connectors, GitHub Actions (CI/CD, if I understand correctly), unit tests, CLI libraries, type-hinting, regex. I had earlier built this on a different platform, so I now have a solid idea of how this application is used.
Key concepts
Each newspaper has a certain cost per day of the week
Each newspaper may or may not be delivered on a given day
Each newspaper has a name, and a number called a key
You may register any dates when you didn't receive a paper in advance using the addudl command
Once you calculate, the results are displayed and copied to your clipboard
What files exist?
(ignoring conventional ones like README and requirements.txt)
File
Purpose/Description
Review
npbc_core.py
Provide the core functionality: the calculation, parsing and validation of user input, interaction with the DB etc. Later on, some functionality from this will be extracted to create server-side code that can service more users, but I have to learn a lot more before getting there.
Please review this. | {
"domain": "codereview.stackexchange",
"id": 43300,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sql, database, sqlite",
"url": null
} |
python, sql, database, sqlite
npbc_cli.py
Import functionality from npbc_core.py and wrap a CLI layer on it using argparse. Also provide some additional validation.
Please review this.
npbc_updater.py
Provide a utility to update the application on the user's end.
Don't bother reviewing this (code not included).
test_core.py
Test the functionality of the core file (pytest). This isn't as exhaustive as I'd like, but it did a good job of capturing many of my mistakes.
Please review this.
data/schema.sql
Database schema. In my local environment, the data folder also has a test database file (but I don't want to upload this online).
Please review this if you can (not high priority).
Known problems
Tests are not exhaustive (please suggest anything you think of).
Tests are not well commented (working on this right now in a local branch).
SQL injection is possible in some cases by -k/--key CLI parameters, if you can figure out a way to insert a semicolon in an integer. I will remove this in a future version, once I find a way to improve or remove the generate_sql_query() function.
A lot of documentation is tied up in the CLI UI and comments, and is not an explicit document. | {
"domain": "codereview.stackexchange",
"id": 43300,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sql, database, sqlite",
"url": null
} |
python, sql, database, sqlite
data/schema.sql (SQLite 3)
CREATE TABLE IF NOT EXISTS papers (
paper_id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
CONSTRAINT unique_paper_name UNIQUE (name)
);
CREATE TABLE IF NOT EXISTS papers_days_delivered (
paper_id INTEGER NOT NULL,
day_id INTEGER NOT NULL,
delivered INTEGER NOT NULL,
FOREIGN KEY(paper_id) REFERENCES papers(paper_id),
CONSTRAINT unique_paper_day UNIQUE (paper_id, day_id)
);
CREATE TABLE IF NOT EXISTS papers_days_cost(
paper_id INTEGER NOT NULL,
day_id INTEGER NOT NULL,
cost INTEGER,
FOREIGN KEY(paper_id) REFERENCES papers(paper_id),
CONSTRAINT unique_paper_day UNIQUE (paper_id, day_id)
);
CREATE TABLE IF NOT EXISTS undelivered_strings (
entry_id INTEGER PRIMARY KEY AUTOINCREMENT,
year INTEGER NOT NULL,
month INTEGER NOT NULL,
paper_id INTEGER NOT NULL,
string TEXT NOT NULL,
FOREIGN KEY (paper_id) REFERENCES papers(paper_id)
);
CREATE TABLE IF NOT EXISTS undelivered_dates (
entry_id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT NOT NULL,
year INTEGER NOT NULL,
month INTEGER NOT NULL,
paper_id INTEGER NOT NULL,
dates TEXT NOT NULL,
FOREIGN KEY (paper_id) REFERENCES papers(paper_id)
);
CREATE INDEX IF NOT EXISTS search_strings ON undelivered_strings(year, month);
CREATE INDEX IF NOT EXISTS paper_names ON papers(name);
All code where a query/call to DB is made
This is provided for context, and is duplicated from the other posts.
npbc_core.py
Setup
from sqlite3 import connect
from pathlib import Path
## paths for the folder containing schema and database files
# during normal use, the DB will be in ~/.npbc (where ~ is the user's home directory) and the schema will be bundled with the executable
# during development, the DB and schema will both be in "data"
DATABASE_DIR = Path().home() / '.npbc' # normal use path
# DATABASE_DIR = Path('data') # development path
DATABASE_PATH = DATABASE_DIR / 'npbc.db' | {
"domain": "codereview.stackexchange",
"id": 43300,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sql, database, sqlite",
"url": null
} |
python, sql, database, sqlite
DATABASE_PATH = DATABASE_DIR / 'npbc.db'
SCHEMA_PATH = Path(__file__).parent / 'schema.sql' # normal use path
# SCHEMA_PATH = DATABASE_DIR / 'schema.sql' # development path
## ensure DB exists and it's set up with the schema
def setup_and_connect_DB() -> None:
DATABASE_DIR.mkdir(parents=True, exist_ok=True)
DATABASE_PATH.touch(exist_ok=True)
with connect(DATABASE_PATH) as connection:
connection.executescript(SCHEMA_PATH.read_text())
connection.commit()
Query generator
## generate a "SELECT" SQL query
# use params to specify columns to select, and "WHERE" conditions
def generate_sql_query(table_name: str, conditions: dict[str, int | str] | None = None, columns: list[str] | None = None) -> str:
sql_query = f"SELECT"
if columns:
sql_query += f" {', '.join(columns)}"
else:
sql_query += f" *"
sql_query += f" FROM {table_name}"
if conditions:
conditions_segment = ' AND '.join([
f"{parameter_name} = {parameter_value}"
for parameter_name, parameter_value in conditions.items()
])
sql_query += f" WHERE {conditions_segment}"
return f"{sql_query};"
Query (call to DB)
## execute a "SELECT" SQL query and return the results
def query_database(query: str) -> list[tuple]:
with connect(DATABASE_PATH) as connection:
return connection.execute(query).fetchall()
return []
Fetching data about a given paper, used in calculation
## get the cost and delivery data for a given paper from the DB
# each of them are converted to a dictionary, whose index is the day_id
# the two dictionaries are then returned as a tuple
def get_cost_and_delivery_data(paper_id: int) -> tuple[dict[int, float], dict[int, bool]]:
cost_query = generate_sql_query(
'papers_days_cost',
columns=['day_id', 'cost'],
conditions={'paper_id': paper_id}
) | {
"domain": "codereview.stackexchange",
"id": 43300,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sql, database, sqlite",
"url": null
} |
python, sql, database, sqlite
delivery_query = generate_sql_query(
'papers_days_delivered',
columns=['day_id', 'delivered'],
conditions={'paper_id': paper_id}
)
with connect(DATABASE_PATH) as connection:
cost_tuple = connection.execute(cost_query).fetchall()
delivery_tuple = connection.execute(delivery_query).fetchall()
cost_dict = {
day_id: cost
for day_id, cost in cost_tuple # type: ignore
}
delivery_dict = {
day_id: delivery
for day_id, delivery in delivery_tuple # type: ignore
}
return cost_dict, delivery_dict
Main calculation function
## calculate the cost of all papers for the full month
# return data about the cost of each paper, the total cost, and dates when each paper was not delivered
def calculate_cost_of_all_papers(undelivered_strings: dict[int, str], month: int, year: int) -> tuple[dict[int, float], float, dict[int, set[date_type]]]:
NUMBER_OF_DAYS_PER_WEEK = get_number_of_days_per_week(month, year)
# get the IDs of papers that exist
with connect(DATABASE_PATH) as connection:
papers = connection.execute(
generate_sql_query(
'papers',
columns=['paper_id']
)
).fetchall()
# get the data about cost and delivery for each paper
cost_and_delivery_data = [
get_cost_and_delivery_data(paper_id)
for paper_id, in papers # type: ignore
]
# initialize a "blank" dictionary that will eventually contain any dates when a paper was not delivered
undelivered_dates: dict[int, set[date_type]] = {
paper_id: {}
for paper_id, in papers # type: ignore
}
# calculate the undelivered dates for each paper
for paper_id, undelivered_string in undelivered_strings.items(): # type: ignore
undelivered_dates[paper_id] = parse_undelivered_string(undelivered_string, month, year) | {
"domain": "codereview.stackexchange",
"id": 43300,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sql, database, sqlite",
"url": null
} |
python, sql, database, sqlite
# calculate the cost of each paper
costs = {
paper_id: calculate_cost_of_one_paper(
NUMBER_OF_DAYS_PER_WEEK,
undelivered_dates[paper_id],
cost_and_delivery_data[index]
)
for index, (paper_id,) in enumerate(papers) # type: ignore
}
# calculate the total cost of all papers
total = sum(costs.values())
return costs, total, undelivered_dates
Save results
## save the results of undelivered dates to the DB
# save the dates any paper was not delivered
def save_results(undelivered_dates: dict[int, set[date_type]], month: int, year: int) -> None:
TIMESTAMP = datetime.now().strftime(r'%d/%m/%Y %I:%M:%S %p')
with connect(DATABASE_PATH) as connection:
for paper_id, undelivered_date_instances in undelivered_dates.items():
connection.execute(
"INSERT INTO undelivered_dates (timestamp, month, year, paper_id, dates) VALUES (?, ?, ?, ?, ?);",
(
TIMESTAMP,
month,
year,
paper_id,
','.join([
undelivered_date_instance.strftime(r'%d')
for undelivered_date_instance in undelivered_date_instances
])
)
)
Add, edit, or delete papers
## add a new paper
# do not allow if the paper already exists
def add_new_paper(name: str, days_delivered: list[bool], days_cost: list[float]) -> tuple[bool, str]:
with connect(DATABASE_PATH) as connection:
# get the names of all papers that already exist
paper = connection.execute(
generate_sql_query('papers', columns=['name'], conditions={'name': f"\"{name}\""})
).fetchall() | {
"domain": "codereview.stackexchange",
"id": 43300,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sql, database, sqlite",
"url": null
} |
python, sql, database, sqlite
# if the proposed paper already exists, return an error message
if paper:
return False, "Paper already exists. Please try editing the paper instead."
# otherwise, add the paper name to the database
connection.execute(
"INSERT INTO papers (name) VALUES (?);",
(name, )
)
# get the ID of the paper that was just added
paper_id = connection.execute(
"SELECT paper_id FROM papers WHERE name = ?;",
(name, )
).fetchone()[0]
# add the cost and delivery data for the paper
for day_id, (cost, delivered) in enumerate(zip(days_cost, days_delivered)):
connection.execute(
"INSERT INTO papers_days_cost (paper_id, day_id, cost) VALUES (?, ?, ?);",
(paper_id, day_id, cost)
)
connection.execute(
"INSERT INTO papers_days_delivered (paper_id, day_id, delivered) VALUES (?, ?, ?);",
(paper_id, day_id, delivered)
)
connection.commit()
return True, f"Paper {name} added."
return False, "Something went wrong."
## edit an existing paper
# do not allow if the paper does not exist
def edit_existing_paper(paper_id: int, name: str | None = None, days_delivered: list[bool] | None = None, days_cost: list[float] | None = None) -> tuple[bool, str]:
with connect(DATABASE_PATH) as connection:
# get the IDs of all papers that already exist
paper = connection.execute(
generate_sql_query('papers', columns=['paper_id'], conditions={'paper_id': paper_id})
).fetchone()
# if the proposed paper does not exist, return an error message
if not paper:
return False, f"Paper {paper_id} does not exist. Please try adding it instead." | {
"domain": "codereview.stackexchange",
"id": 43300,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sql, database, sqlite",
"url": null
} |
python, sql, database, sqlite
# if a name is proposed, update the name of the paper
if name is not None:
connection.execute(
"UPDATE papers SET name = ? WHERE paper_id = ?;",
(name, paper_id)
)
# if delivery data is proposed, update the delivery data of the paper
if days_delivered is not None:
for day_id, delivered in enumerate(days_delivered):
connection.execute(
"UPDATE papers_days_delivered SET delivered = ? WHERE paper_id = ? AND day_id = ?;",
(delivered, paper_id, day_id)
)
# if cost data is proposed, update the cost data of the paper
if days_cost is not None:
for day_id, cost in enumerate(days_cost):
connection.execute(
"UPDATE papers_days_cost SET cost = ? WHERE paper_id = ? AND day_id = ?;",
(cost, paper_id, day_id)
)
connection.commit()
return True, f"Paper {paper_id} edited."
return False, "Something went wrong."
## delete an existing paper
# do not allow if the paper does not exist
def delete_existing_paper(paper_id: int) -> tuple[bool, str]:
with connect(DATABASE_PATH) as connection:
# get the IDs of all papers that already exist
paper = connection.execute(
generate_sql_query('papers', columns=['paper_id'], conditions={'paper_id': paper_id})
).fetchone()
# if the proposed paper does not exist, return an error message
if not paper:
return False, f"Paper {paper_id} does not exist. Please try adding it instead."
# delete the paper from the names table
connection.execute(
"DELETE FROM papers WHERE paper_id = ?;",
(paper_id, )
) | {
"domain": "codereview.stackexchange",
"id": 43300,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sql, database, sqlite",
"url": null
} |
python, sql, database, sqlite
# delete the paper from the delivery data table
connection.execute(
"DELETE FROM papers_days_delivered WHERE paper_id = ?;",
(paper_id, )
)
# delete the paper from the cost data table
connection.execute(
"DELETE FROM papers_days_cost WHERE paper_id = ?;",
(paper_id, )
)
connection.commit()
return True, f"Paper {paper_id} deleted."
return False, "Something went wrong."
Add or delete undelivered strings
## record strings for date(s) paper(s) were not delivered
def add_undelivered_string(paper_id: int, undelivered_string: str, month: int, year: int) -> tuple[bool, str]:
# if the string is not valid, return an error message
if not validate_undelivered_string(undelivered_string):
return False, f"Invalid undelivered string."
with connect(DATABASE_PATH) as connection:
# check if given paper exists
paper = connection.execute(
generate_sql_query(
'papers',
columns=['paper_id'],
conditions={'paper_id': paper_id}
)
).fetchone()
# if the paper does not exist, return an error message
if not paper:
return False, f"Paper {paper_id} does not exist. Please try adding it instead."
# check if a string with the same month and year, for the same paper, already exists
existing_string = connection.execute(
generate_sql_query(
'undelivered_strings',
columns=['string'],
conditions={
'paper_id': paper_id,
'month': month,
'year': year
}
)
).fetchone() | {
"domain": "codereview.stackexchange",
"id": 43300,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sql, database, sqlite",
"url": null
} |
python, sql, database, sqlite
# if a string with the same month and year, for the same paper, already exists, concatenate the new string to it
if existing_string:
new_string = f"{existing_string[0]},{undelivered_string}"
connection.execute(
"UPDATE undelivered_strings SET string = ? WHERE paper_id = ? AND month = ? AND year = ?;",
(new_string, paper_id, month, year)
)
# otherwise, add the new string to the database
else:
connection.execute(
"INSERT INTO undelivered_strings (string, paper_id, month, year) VALUES (?, ?, ?, ?);",
(undelivered_string, paper_id, month, year)
)
connection.commit()
return True, f"Undelivered string added."
## delete an existing undelivered string
# do not allow if the string does not exist
def delete_undelivered_string(paper_id: int, month: int, year: int) -> tuple[bool, str]:
with connect(DATABASE_PATH) as connection:
# check if a string with the same month and year, for the same paper, exists
existing_string = connection.execute(
generate_sql_query(
'undelivered_strings',
columns=['string'],
conditions={
'paper_id': paper_id,
'month': month,
'year': year
}
)
).fetchone()
# if it does, delete it
if existing_string:
connection.execute(
"DELETE FROM undelivered_strings WHERE paper_id = ? AND month = ? AND year = ?;",
(paper_id, month, year)
)
connection.commit()
return True, f"Undelivered string deleted."
# if the string does not exist, return an error message
return False, f"Undelivered string does not exist."
return False, "Something went wrong." | {
"domain": "codereview.stackexchange",
"id": 43300,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sql, database, sqlite",
"url": null
} |
python, sql, database, sqlite
return False, "Something went wrong."
Extract data from user input
## extract delivery days and costs from user input
def extract_days_and_costs(days_delivered: str | None, prices: str | None, paper_id: int | None = None) -> tuple[list[bool], list[float]]:
days = []
costs = []
# if the user has provided delivery days, extract them
if days_delivered is not None:
days = [
bool(int(day == 'Y')) for day in str(days_delivered).upper()
]
# if the user has not provided delivery days, fetch them from the database
else:
if isinstance(paper_id, int):
days = [
(int(day_id), bool(delivered))
for day_id, delivered in query_database(
generate_sql_query(
'papers_days_delivered',
columns=['day_id', 'delivered'],
conditions={
'paper_id': paper_id
}
)
)
]
days.sort(key=lambda x: x[0])
days = [delivered for _, delivered in days]
# if the user has provided prices, extract them
if prices is not None:
costs = []
encoded_prices = [float(price) for price in SPLIT_REGEX['semicolon'].split(prices.rstrip(';')) if float(price) > 0]
day_count = -1
for day in days:
if day:
day_count += 1
cost = encoded_prices[day_count]
else:
cost = 0
costs.append(cost)
return days, costs
npbc_cli.py
Calculate the costs
## calculate the cost for a given month and year
# default to the previous month if no month and no year is given
# default to the current month if no month is given and year is given
# default to the current year if no year is given and month is given
def calculate(args: arg_namespace) -> None: | {
"domain": "codereview.stackexchange",
"id": 43300,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sql, database, sqlite",
"url": null
} |
python, sql, database, sqlite
# deal with month and year
if args.month or args.year:
feedback = validate_month_and_year(args.month, args.year)
if not feedback[0]:
status_print(*feedback)
return
if args.month:
month = args.month
else:
month = datetime.now().month
if args.year:
year = args.year
else:
year = datetime.now().year
else:
previous_month = get_previous_month()
month = previous_month.month
year = previous_month.year
# look for undelivered strings in the database
existing_strings = query_database(
generate_sql_query(
'undelivered_strings',
columns=['paper_id', 'string'],
conditions={
'month': month,
'year': year
}
)
)
# associate undelivered strings with their paper_id
undelivered_strings: dict[int, str] = {
paper_id: undelivered_string
for paper_id, undelivered_string in existing_strings
}
# calculate the cost for each paper, as well as the total cost
costs, total, undelivered_dates = calculate_cost_of_all_papers(
undelivered_strings,
month,
year
)
# format the results
formatted = format_output(costs, total, month, year)
# unless the user specifies so, copy the results to the clipboard
if not args.nocopy:
copy_to_clipboard(formatted)
formatted += '\nSummary copied to clipboard.'
# unless the user specifies so, log the results to the database
if not args.nolog:
save_results(undelivered_dates, month, year)
formatted += '\nLog saved to file.'
# print the results
status_print(True, "Success!")
print(f"SUMMARY:\n{formatted}") | {
"domain": "codereview.stackexchange",
"id": 43300,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sql, database, sqlite",
"url": null
} |
python, sql, database, sqlite
# print the results
status_print(True, "Success!")
print(f"SUMMARY:\n{formatted}")
Get undelivered strings, paper data, or logs
## get undelivered strings from the database
# filter by whichever parameter the user provides. they as many as they want.
# available parameters: month, year, key, string
def getudl(args: arg_namespace) -> None:
# validate the month and year
feedback = validate_month_and_year(args.month, args.year)
if not feedback[0]:
status_print(*feedback)
return
conditions = {}
if args.key:
conditions['paper_id'] = args.key
if args.month:
conditions['month'] = args.month
if args.year:
conditions['year'] = args.year
if args.undelivered:
conditions['strings'] = str(args.undelivered).lower().strip()
if not validate_undelivered_string(conditions['strings']):
status_print(False, "Invalid undelivered string.")
return
# if the undelivered strings exist, fetch them
undelivered_strings = query_database(
generate_sql_query(
'undelivered_strings',
conditions=conditions
)
)
# if there were undelivered strings, print them
if undelivered_strings:
status_print(True, 'Found undelivered strings.')
print(f"{Fore.YELLOW}entry_id{Style.RESET_ALL} | {Fore.YELLOW}year{Style.RESET_ALL} | {Fore.YELLOW}month{Style.RESET_ALL} | {Fore.YELLOW}paper_id{Style.RESET_ALL} | {Fore.YELLOW}string{Style.RESET_ALL}")
for string in undelivered_strings:
print('|'.join([str(item) for item in string]))
# otherwise, print that there were no undelivered strings
else:
status_print(False, 'No undelivered strings found.') | {
"domain": "codereview.stackexchange",
"id": 43300,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sql, database, sqlite",
"url": null
} |
python, sql, database, sqlite
## get a list of all papers in the database
# filter by whichever parameter the user provides. they may use as many as they want (but keys are always printed)
# available parameters: name, days, costs
# the output is provided as a formatted table, printed to the standard output
def getpapers(args: arg_namespace) -> None:
headers = ['paper_id']
# fetch a list of all papers' IDs
papers_id_list = [
paper_id
for paper_id, in query_database(
generate_sql_query(
'papers',
columns=['paper_id']
)
)
]
# initialize lists for the data
paper_name_list, paper_days_list, paper_costs_list = [], [], []
# sort the papers' IDs (for the sake of consistency)
papers_id_list.sort()
# if the user wants names, fetch that data and add it to the list
if args.names:
# first get a dictionary of {paper_id: paper_name}
papers_names = {
paper_id: paper_name
for paper_id, paper_name in query_database(
generate_sql_query(
'papers',
columns=['paper_id', 'name']
)
)
}
# then use the sorted IDs list to create a sorted names list
paper_name_list = [
papers_names[paper_id]
for paper_id in papers_id_list
]
headers.append('name')
# if the user wants delivery days, fetch that data and add it to the list
if args.days:
# initialize a dictionary of {paper_id: {day_id: delivery}}
papers_days = {
paper_id: {}
for paper_id in papers_id_list
} | {
"domain": "codereview.stackexchange",
"id": 43300,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sql, database, sqlite",
"url": null
} |
python, sql, database, sqlite
# then get the data for each paper
for paper_id, day_id, delivered in query_database(
generate_sql_query(
'papers_days_delivered',
columns=['paper_id', 'day_id', 'delivered']
)
):
papers_days[paper_id][day_id] = delivered
# format the data so that it matches the regex pattern /^[YN]{7}$/, the same way the user must input this data
paper_days_list = [
''.join([
'Y' if int(papers_days[paper_id][day_id]) == 1 else 'N'
for day_id, _ in enumerate(WEEKDAY_NAMES)
])
for paper_id in papers_id_list
]
headers.append('days')
# if the user wants costs, fetch that data and add it to the list
if args.prices:
# initialize a dictionary of {paper_id: {day_id: price}}
papers_costs = {
paper_id: {}
for paper_id in papers_id_list
}
# then get the data for each paper
for paper_id, day_id, cost in query_database(
generate_sql_query(
'papers_days_cost',
columns=['paper_id', 'day_id', 'cost']
)
):
papers_costs[paper_id][day_id] = cost
# format the data so that it matches the regex pattern /^[x](;[x]){6}$/, where /x/ is a number that may be either a floating point or an integer, the same way the user must input this data.
paper_costs_list = [
';'.join([
str(papers_costs[paper_id][day_id])
for day_id, _ in enumerate(WEEKDAY_NAMES)
])
for paper_id in papers_id_list
]
headers.append('costs')
# print the headers
print(' | '.join([
f"{Fore.YELLOW}{header}{Style.RESET_ALL}"
for header in headers
])) | {
"domain": "codereview.stackexchange",
"id": 43300,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sql, database, sqlite",
"url": null
} |
python, sql, database, sqlite
# print the data
for index, paper_id in enumerate(papers_id_list):
print(f"{paper_id}: ", end='')
values = []
if args.names:
values.append(paper_name_list[index])
if args.days:
values.append(paper_days_list[index])
if args.prices:
values.append(paper_costs_list[index])
print(', '.join(values))
## get a log of all deliveries for a paper
# the user may specify parameters to filter the output by. they may use as many as they want, or none
# available parameters: paper_id, month, year
def getlogs(args: arg_namespace) -> None:
# validate the month and year
feedback = validate_month_and_year(args.month, args.year)
if not feedback[0]:
status_print(*feedback)
return
conditions = {}
# if the user specified a particular paper, add it to the conditions
if args.key:
conditions['paper_id'] = args.key
if args.month:
conditions['month'] = args.month
if args.year:
conditions['year'] = args.year
# fetch the data
undelivered_dates = query_database(
generate_sql_query(
'undelivered_dates',
conditions=conditions
)
)
# if data was found, print it
if undelivered_dates:
status_print(True, 'Success!')
print(f"{Fore.YELLOW}entry_id{Style.RESET_ALL} | {Fore.YELLOW}year{Style.RESET_ALL} | {Fore.YELLOW}month{Style.RESET_ALL} | {Fore.YELLOW}paper_id{Style.RESET_ALL} | {Fore.YELLOW}dates{Style.RESET_ALL}")
for date in undelivered_dates:
print(', '.join(date))
# if no data was found, print an error message
else:
status_print(False, 'No results found.') | {
"domain": "codereview.stackexchange",
"id": 43300,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sql, database, sqlite",
"url": null
} |
python, sql, database, sqlite
If you need it, here is a link to the GitHub repo for this project. It's at the same commit as the code above, and I won't edit this so that any discussion is consistent.
https://github.com/eccentricOrange/npbc/tree/6020a4f5db0bf40f54e35b725b305cfeafdd8f2b
Answer: SQLite supports check constraints. You should use them to ensure that
delivered is only 0 or 1 (since booleans are not supported directly)
cost is greater than 0
year is between perhaps 2000 and 2100
month is between 0 and 11
Inline foreign key clauses are supported which are nicer to read than table-level clauses, so consider switching to them.
Compound primary keys are also supported. Isn't this:
CONSTRAINT unique_paper_day UNIQUE (paper_id, day_id)
really just your primary key?
day_id isn't particularly an ID. It's a day integer, similar to your year and month (so long as I understand your schema). A rename is in order, and this should also receive a check constraint.
You already use the connection as a context manager, which is good; but that implies a commit. That means that you should not need to commit manually.
I've said as much in your other question, but you shouldn't be dynamically generating queries as you are in generate_sql_query, and you need to delete return [].
This is problematic:
cost_and_delivery_data = [
get_cost_and_delivery_data(paper_id)
for paper_id, in papers # type: ignore
] | {
"domain": "codereview.stackexchange",
"id": 43300,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sql, database, sqlite",
"url": null
} |
python, sql, database, sqlite
because get_cost_and_delivery_data will open and close the connection on every iteration. Instead, pass a connection in.
undelivered_dates.dates is a classic normalisation error. Newcomers to RDBMS often say "I want to store an array", and if they're determined enough (as you are), they might even succeed. But this is not a good idea. There should be a separate row in this table for each date.
get the names of all papers that already exist is a lie. That query doesn't fetch all names of papers that exist; it fetches the name of all existing papers whose name matches the given name. But more importantly, you don't actually care about the name; you only care about the existence of the row, so write
select exists(
select 1 from papers where name=?
)
Further to that, your select exists and insert should not be separated, but should be in the same query. After executing it, check rowcount to see if anything was successfully inserted.
Even more combination: do not have a separate select for get the ID of the paper that was just added; that should also be in the same statement using a returning clause.
paper_days_cost and paper_days_delivered appear to have the same keys. If they have the same existence characteristics, they should be merged into one table.
I encourage you to work on the above, and (after some time has passed and you've gathered enough feedback from the community) post a new question with your updated code. | {
"domain": "codereview.stackexchange",
"id": 43300,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sql, database, sqlite",
"url": null
} |
python, python-3.x, image, pygame
Title: Weird things to do to an image
Question: Here is a program I wrote to take an image and do weird things to it. Is there any more weird things I can add?
Right now I have:
Chop the image
Flip the image (up/down and left/right)
Rotate the image by a random amount of degrees
Roll the image by a random offset
Negate the image
Add a randomly colored border around the image
Add a random line to the image
Copy a part of the image to another part
Negate the red values of the image
Negate the green values of the image
Negate the blue values of the image
import pygame
import random
import subprocess
import sys
inputfilename = sys.argv[1]
outputfilename = "weird.png"
def chop(i: pygame.Surface):
r = i.get_rect()
return pygame.transform.chop(i, pygame.Rect(random.randint(0, r.right // 2), random.randint(0, r.bottom // 2), random.randint(0, r.right // 2), random.randint(0, r.bottom // 2)))
def flip(i: pygame.Surface):
return pygame.transform.flip(i, True, True)
def rotate(i: pygame.Surface):
b = i.copy()
b.set_at((0, 0), (0, 0, 0))
r = pygame.transform.rotate(b, random.randint(0, 360))
b = pygame.Surface(r.get_size())
b.fill((0, 0, 0))
b.blit(r, (0, 0))
return b
def roll(i: pygame.Surface):
r = pygame.Surface(i.get_size())
offset = (random.randint(0, i.get_width() // 2), random.randint(0, i.get_height() // 2))
r.blit(i, offset)
r.blit(i, (offset[0] - i.get_width(), offset[1]))
r.blit(i, (offset[0], offset[1] - i.get_height()))
r.blit(i, (offset[0] - i.get_width(), offset[1] - i.get_height()))
return r.copy()
def negate(i: pygame.Surface):
r = pygame.Surface(i.get_size())
r.fill((255, 255, 255))
r.blit(i, (0, 0), special_flags=pygame.BLEND_SUB)
return r | {
"domain": "codereview.stackexchange",
"id": 43301,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, image, pygame",
"url": null
} |
python, python-3.x, image, pygame
def addborder(i: pygame.Surface):
s = random.randint(2, 20)
r = pygame.Surface((i.get_width() + s + s, i.get_height() + s + s))
r.fill((random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
r.blit(i, (s, s))
return r
def addline(i: pygame.Surface):
r = i.copy()
frompos = (random.randint(0, r.get_width()), random.randint(0, r.get_height()))
topos = (random.randint(0, r.get_width()), random.randint(0, r.get_height()))
pygame.draw.line(r, (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)), frompos, topos, random.randint(1, 20))
return r
def addcopy(i: pygame.Surface):
r = i.copy()
cropped = pygame.Surface((random.randint(0, r.get_width() // 2), random.randint(0, r.get_height() // 2)))
cropped.blit(r, (random.randint(0, r.get_width() // 2), random.randint(0, r.get_height() // 2)))
r.blit(cropped, (random.randint(0, r.get_width() // 2), random.randint(0, r.get_height() // 2)))
return r
def negate_red(i: pygame.Surface):
r = i.copy()
for x in range(r.get_width()):
for y in range(r.get_height()):
this = r.get_at((x, y))
r.set_at((x, y), (255 - this[0], this[1], this[2]))
return r
def negate_green(i: pygame.Surface):
r = i.copy()
for x in range(r.get_width()):
for y in range(r.get_height()):
this = r.get_at((x, y))
r.set_at((x, y), (this[0], 255 - this[1], this[2]))
return r
def negate_blue(i: pygame.Surface):
r = i.copy()
for x in range(r.get_width()):
for y in range(r.get_height()):
this = r.get_at((x, y))
r.set_at((x, y), (this[0], this[1], 255 - this[2]))
return r | {
"domain": "codereview.stackexchange",
"id": 43301,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, image, pygame",
"url": null
} |
python, python-3.x, image, pygame
print()
img = pygame.image.load(inputfilename)
after = img.copy()
transforms = [chop, flip, rotate, roll, negate, addborder, addline, addcopy, negate_red, negate_green, negate_blue]
for f in range(len(transforms)):
after = random.choice(transforms)(after)
# Progress bar
print(u"\u001b[1A\r\u001b[0K" + str(f + 1) + "/" + str(len(transforms)))
pygame.image.save(after, outputfilename)
subprocess.run(["xdg-open", outputfilename])
Answer: You should bypass pygame and go straight to Pillow which is more narrowly targeted at image manipulation.
It's good that you have type hints, but your functions are all missing a -> return hint.
You can factor out a common function from your negate_ methods that accepts a channel index between 0 and 2. The Pillow version will not need a double-loop (or indeed any loops at all), and should be able to do a vectorised subtraction using a Numpy array.
Everything from print() onward should be moved to a main() method, in turn called from an if __name__ == '__main__' guard.
startfile tragically has not been made portable, but neither is xdg-open. For this application to be portable it needs to switch between the two based on OS.
When you call subprocess, strongly prefer shell=False; this will require using the absolute path of /usr/bin/xdg-open.
transforms should be a tuple () and not a list [].
Rather than a fixed output filename of weird.png, consider adding that as a suffix on the original filename. | {
"domain": "codereview.stackexchange",
"id": 43301,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, image, pygame",
"url": null
} |
beginner, sorting, rust
Title: Partitioning a list so that even numbers appear before odd numbers
Question: I started learning Rust today and figured, I could ask for some code reviews to learn to make my code idiomatic and learn about its code generation. I spend my days writing highly optimized Java and C++, so interested in Rust from that perspective.
This is the first problem from leetcode:
// Sorts a vector, so that even numbers appear first.
fn sort_array_by_parity(nums: Vec<i32>) -> Vec<i32> {
let mut res = nums.clone();
let mut even = 0; // index of first element of unknown parity
for (i, n) in nums.iter().enumerate() {
if n % 2 == 0 {
res.swap(even, i);
even = even + 1;
}
}
res
}
The code takes as input a list of numbers and sorts them so that even numbers are first, i.e. [3,2,4,1] -> [2,4,3,1]. I'm using a pointer into the list keeping track of a boundary on which we have on the left side stuff that is known to be even (similar to the typical implement of the partition function in quicksort).
I'm interested in a few things:
Is there a more idiomatic way of writing the loop?
Is there a more efficient way of writing the equivalent code?
For (2), so I was mainly wondering if there are ways to make Rust's compiler figure out that it doesn't have to make a range check on every access, but can instead reason that it only needs to check the bound once outside a loop. The generated assembly code shown by compiler explorer shows that it's not smart enough to avoid bounds checks on every iteration, i.e. the main loop generates the following code:
.LBB1_13:
testb $1, (%r12,%rax,4)
jne .LBB1_23
cmpq %r13, %rdi
jae .LBB1_21
cmpq %r13, %rax
jb .LBB1_22
leaq .L__unnamed_1(%rip), %rdx
movq %rax, %rdi
movq %r13, %rsi
callq *core::panicking::panic_bounds_check@GOTPCREL(%rip)
jmp .LBB1_2 | {
"domain": "codereview.stackexchange",
"id": 43302,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, sorting, rust",
"url": null
} |
beginner, sorting, rust
Answer: welcome to the Rust community!
Your code is already quite idiomatic. You may use an unsafe and unstable feature to improve efficiency, swap_unchecked. It's only available with the nightly compiler, so make sure you enable it if you wish to try this code.
#![feature(slice_swap_unchecked)]
// ...
for (i, n) in nums.iter().enumerate() {
if n % 2 == 0 {
// this is safe because `even` never exceeds `res` length
// and `i` is an index into `even`
unsafe {
res.swap_unchecked(even, i);
}
even += 1;
}
}
But why reinvent the wheel when itertools has partition?
use itertools::partition;
// Sorts a vector, so that even numbers appear first.
fn sort_array_by_parity(mut nums: Vec<i32>) -> Vec<i32> {
partition(&mut nums, |n| n % 2 == 0);
nums
}
Itertools partition is different in that it grabs elements from the back of the array, so your even elements are placed in reverse order. Partition is implemented like this:
pub fn partition<'a, A: 'a, I, F>(iter: I, mut pred: F) -> usize
where I: IntoIterator<Item = &'a mut A>,
I::IntoIter: DoubleEndedIterator,
F: FnMut(&A) -> bool
{
let mut split_index = 0;
let mut iter = iter.into_iter();
'main: while let Some(front) = iter.next() {
if !pred(front) {
loop {
match iter.next_back() {
Some(back) => if pred(back) {
std::mem::swap(front, back);
break;
},
None => break 'main,
}
}
}
split_index += 1;
}
split_index
} | {
"domain": "codereview.stackexchange",
"id": 43302,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, sorting, rust",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.