text stringlengths 1 2.12k | source dict |
|---|---|
python, game, machine-learning, 2048
Please teach students good habits.
This should be a docstring.
And it should begin with a sentence which describes its
single responsibility,
before it goes on to helpfully explain the meaning of "target".
Similarly for most of the class Network methods.
Optional[reward]
value += (
reward * self.discount**i
) # pytype: disable=unsupported-operands
I imagine that reward can be None here?
Consider using a no-op filter or an assert to
convince mypy that you've already dealt with that case
by the time we start multiplying.
Tacking on linter comments is sometimes very useful,
but here it seems easier to just deal with
the type ambiguity up front.
Then students will have fewer things to scratch their heads about.
helpful comments
# States past the end of games are treated as absorbing states.
You included some insightful remarks such as this one,
for which I thank you.
the typing module is being phased out
class NetworkOutput(typing.NamedTuple):
Maybe there's a better way to phrase that annotation?
I honestly don't know.
So consider making this a
@dataclass,
just because they're easier to annotate.
(At a future time the typing module will be deleted
or at least it will become much much smaller.
It offered a good bridge to modern practice,
and now its days are numbered.)
env vars up front
Please use
$ isort *.py
in addition to black.
Pep-8
asks that you organize the following imports
in a different way.
I find it very helpful to know that e.g. import resource refers to
this and not
that
(which your source initially made me believe had been pip installed).
# Lint as: python3
"""Pseudocode description of the MuZero algorithm."""
# pylint: disable=unused-argument
# pylint: disable=missing-docstring
# pylint: disable=g-explicit-length-test
import collections
import typing
import os
from typing import Any, Dict, List, Optional | {
"domain": "codereview.stackexchange",
"id": 45591,
"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, game, machine-learning, 2048",
"url": null
} |
python, game, machine-learning, 2048
import collections
import typing
import os
from typing import Any, Dict, List, Optional
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"] = "1"
os.environ["OMP_NUM_THREADS"] = "1"
import numpy as np
import torch
from torch import optim, nn
from torch.nn import functional as F
import pickle as pkl
import os
import torch.multiprocessing as mp
import time
import resource
##########################
####### Helpers ##########
Alas, there is a fly in the ointment!
We need three assignments prior to importing,
and we can't have isort reorder them.
But why are we even doing it that way?
Please prefer the following shebang.
#! /usr/bin/env MKL_NUM_THREADS=1 NUMEXPR_NUM_THREADS=1 OMP_NUM_THREADS=1 python3
no ASCII art
https://github.com/fnclovers/Minimal-AlphaZero/blob/1d7232bcd/alpha_zero.py#L26
##########################
####### Helpers ##########
MAXIMUM_FLOAT_VALUE = ...
##### End Helpers ########
##########################
##################################
####### Part 1: Self-Play ########
# Each self-play job is independent ...
######### End Self-Play ##########
##################################
##################################
####### Part 2: Training #########
No, please do not train students to write
code that needs such visual decoration.
Rather, use the tools python gave you for
organizing sections of code.
Use modules, e.g. alphazero_p1_self_play,
alphazero_p2_training, etc.
Additionally, rather than # comments
it would be much better to introduce
a module with a module-level """docstring"""
before the first line of code.
Is the code simple enough for high school students to look at and easily understand the MuZero algorithm?
I believe so, yes.
I commented on the occasional rough edge which I feel could be smoothed off a bit to serve that goal.
Is the code flexible enough to allow students to add their own games to the project? | {
"domain": "codereview.stackexchange",
"id": 45591,
"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, game, machine-learning, 2048",
"url": null
} |
python, game, machine-learning, 2048
Is the code flexible enough to allow students to add their own games to the project?
I am not in high school.
Honestly, I think we need to perform the experiment,
observing how the first two or three students interact
with the project.
There will be lessons learned from that experience,
that will allow refining the codebase to make things
easier or more engaging for a subsequent cohort of students.
Qualifying participants with a simple prerequisite python
project, less ambitious than this one, might be helpful,
as would steering students toward specific OS platforms /
environments that have been well tested.
With all UX studies, we tend to learn a great deal
from the first handful of examples,
since those users are dissimilar from the authors
and will reveal hidden assumptions.
As we iterate, we tend to need larger and larger
cohorts to test the evolving system.
That is, our learning rate slows down
as the system matures.
Careful thought went into authoring this high-quality code.
It achieves its design goals.
I would be willing to delegate or accept maintenance tasks on it. | {
"domain": "codereview.stackexchange",
"id": 45591,
"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, game, machine-learning, 2048",
"url": null
} |
c, literate-programming
Title: Literate Programming in C
Question: Inspired from Literate programming in Haskell.
Below follows a Literate script filter. A literate script is a program in which comments are given the leading role, whilst program text must be explicitly flagged as such by placing it between \begin{code} and \end{code} in the first column of each line.
litc is a filter that can be used to strip away all of the comment lines out a literate script file.
The default code markers are \begin{code} and \end{code}, but they can be changed with command-line arguments, provided that the begin and end markers are nonsimilar.
The following is a valid literate script:
Some text speaking about the code:
\begin{code}
#include <stdio.h>
int main(void) {
puts("Hello World!");
}
\end{code}
Some more text..
and so is this:
Some text speaking about the code:
```c
#include <stdio.h>
int main(void) {
puts("Hello World!");
}
```
Some more text...
GHC itself uses a standalone C program called unlit to process .lhs files.
Code:
#undef _POSIX_C_SOURCE
#undef _XOPEN_SOURCE
#define _POSIX_C_SOURCE 200819L
#define _XOPEN_SOURCE 700
#define IO_IMPLEMENTATION
#define IO_STATIC
#include "io.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#include <unistd.h>
#include <getopt.h>
/* C2X/C23 or later? */
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 202000L
#include <stddef.h> /* nullptr_t */
#else
#include <stdbool.h> /* bool, true, false */
#define nullptr ((void *)0)
typedef void *nullptr_t;
#endif /* nullptr, nullptr_t */
#define SHORT_OP_LIST "b:e:o:h"
#define DEFAULT_BEGIN "\\begin{code}"
#define DEFAULT_END "\\end{code}"
/* Do we even need getopt? */
typedef struct {
const char *bflag; /* Begin flag. */
const char *eflag; /* End flag. */
FILE *output; /* Output to FILE. */
} flags; | {
"domain": "codereview.stackexchange",
"id": 45592,
"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, literate-programming",
"url": null
} |
c, literate-programming
static void help(void)
{
printf("Usage: litc [OPTIONS] SRC\n\n"
" litc - extract code from a LaTEX document.\n\n"
"Options:\n"
" -b, --begin Line that denotes the beginning of the code\n"
" block in the markup langugage. Default: %s.\n"
" -e, --end Line that denotes the end of the code block in\n"
" the markup language. Default: %s.\n"
" -h, --help Displays this message and exits.\n"
" -o, --output=FILE Writes result to FILE instead of standard output.\n\n"
"Note: The begin and end markers must be different.\n\n"
"For Markdown, they can be:\n"
" ```python\n"
" # Some code here\n"
" ```\n",
DEFAULT_BEGIN, DEFAULT_END);
exit(EXIT_SUCCESS);
}
static void err_and_fail(void)
{
fputs("The syntax of the command is incorrect.\n"
"Try litc -h for more information.\n", stderr);
exit(EXIT_FAILURE);
}
static void parse_options(const struct option long_options[static 1],
flags opt_ptr[static 1],
int argc,
char * argv[static argc])
{
while (true) {
const int c =
getopt_long(argc, argv, SHORT_OP_LIST, long_options, nullptr);
if (c == -1) {
break;
} | {
"domain": "codereview.stackexchange",
"id": 45592,
"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, literate-programming",
"url": null
} |
c, literate-programming
if (c == -1) {
break;
}
switch (c) {
case 'e':
case 'b':
if (optarg == nullptr) {
err_and_fail();
}
*(c == 'b' ? &opt_ptr->bflag : &opt_ptr->eflag) = optarg;
break;
case 'h':
help();
break;
case 'o':
/* If -o was provided more than once. */
if (opt_ptr->output != stdout) {
fprintf(stderr, "Error: Multiple -o flags provided.\n");
err_and_fail();
}
errno = 0;
opt_ptr->output = fopen(optarg, "a");
if (opt_ptr->output == nullptr) {
perror(optarg);
exit(EXIT_FAILURE);
}
break;
/* case '?' */
default:
err_and_fail();
break;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 45592,
"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, literate-programming",
"url": null
} |
c, literate-programming
static bool write_codelines(flags options[static 1],
size_t nlines,
char * lines[static nlines])
{
/* Would these 7 variables be better expressed as a struct? */
/* Perhaps:
*
* What would be a better name for this struct?
*
* struct {
* FILE *const f;
* const char *const begin_marker;
* const char *const end_marker;
* size_t ncodelines; // No. of lines seen so far.
* size_t curr_line;
* size_t last_begin_pos;
* bool code_mode;
* } code = {options->output,
* options->bflag ? options->bflag : DEFAULT_BEGIN,
* options->eflag ? options->eflag : DEFAULT_END,
* 1,
* 1,
* 0,
* false
* };
*/
const char *const begin_marker =
options->bflag ? options->bflag : DEFAULT_BEGIN;
const char *const end_marker =
options->eflag ? options->eflag : DEFAULT_END;
FILE *const f = options->output;
if (f != stdout && ftruncate(fileno(f), 0)) {
perror("seek()");
return false;
}
bool code_mode = false;
size_t ncodelines = 1;
size_t curr_line = 1;
size_t last_begin_pos = 0;
for (size_t i = 0; i < nlines; ++i, ++curr_line) {
if (code_mode) {
if (strcmp(lines[i], begin_marker) == 0) {
fprintf(stderr, "Error: %s missing, %s started at line: %zu.\n",
end_marker, begin_marker, last_begin_pos);
goto cleanup_and_fail;
} | {
"domain": "codereview.stackexchange",
"id": 45592,
"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, literate-programming",
"url": null
} |
c, literate-programming
if (strcmp(lines[i], end_marker) == 0) {
code_mode = false;
} else {
if (fprintf(f, "%s\n", lines[i]) < 0) {
perror("fprintf()");
goto cleanup_and_fail;
}
++ncodelines;
}
} else {
if (strcmp(lines[i], end_marker) == 0) {
fprintf(stderr, "Error: spurious %s at line: %zu.\n",
end_marker, curr_line);
goto cleanup_and_fail;
}
code_mode = strcmp(lines[i], begin_marker) == 0;
if (code_mode) {
/* Only print newlines after the first code block. */
if (ncodelines > 1) {
fputc('\n', f);
}
last_begin_pos = curr_line;
}
}
}
if (code_mode) {
fprintf(stderr, "Error: %s missing. %s started at line: %zu.\n",
end_marker, begin_marker, last_begin_pos);
goto cleanup_and_fail;
}
if (ncodelines == 0) {
fprintf(stderr, "Error: no code blocks were found in the file.\n");
goto cleanup_and_fail;
}
goto success;
cleanup_and_fail:
if (f != stdout) {
fclose(f);
}
return false;
success:
return f == stdout || !fclose(f);
}
int main(int argc, char *argv[])
{
/* Sanity check. POSIX requires the invoking process to pass a non-null
* argv[0].
*/
if (!argv) {
fputs("A NULL argv[0] was passed through an exec system call.\n",
stderr);
return EXIT_FAILURE;
} | {
"domain": "codereview.stackexchange",
"id": 45592,
"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, literate-programming",
"url": null
} |
c, literate-programming
static const struct option long_options[] = {
{ "begin", required_argument, nullptr, 'b' },
{ "end", required_argument, nullptr, 'e' },
{ "help", no_argument, nullptr, 'h' },
{ "output", required_argument, nullptr, 'o' },
{ nullptr, 0, nullptr, 0 },
};
FILE *in_file = stdin;
flags options = { nullptr, nullptr, stdout };
parse_options(long_options, &options, argc, argv);
if ((optind + 1) == argc) {
in_file = fopen(argv[optind], "r");
if (!in_file) {
perror(argv[optind]);
if (options.output) {
fclose(options.output);
}
return EXIT_FAILURE;
}
}
else if (optind > argc) {
err_and_fail();
}
size_t nbytes = 0;
char *const content = io_read_file(in_file, &nbytes);
size_t nlines = 0;
char **lines = io_split_lines(content, &nlines);
int status = EXIT_FAILURE;
if (!lines) {
perror("fread()");
goto cleanup_and_fail;
}
if (!write_codelines(&options, nlines, lines)) {
goto cleanup_and_fail;
}
status = EXIT_SUCCESS;
cleanup_and_fail:
/* As we're exiting, we don't need to free anything. */
/* free(lines); */
/* free(content); */
if (in_file != stdin) {
fclose(in_file);
}
return status;
}
#ifndef IO_H
#define IO_H
#include <stdio.h>
#include <stdbool.h>
#include <stdint.h> | {
"domain": "codereview.stackexchange",
"id": 45592,
"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, literate-programming",
"url": null
} |
c, literate-programming
#ifndef IO_H
#define IO_H
#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>
/*
* To use, do this:
* #define IO_IMPLEMENTATION
* before you include this file in *one* C to create the implementation.
*
* i.e. it should look like:
* #include ...
* #include ...
*
* #define IO_IMPLEMENTATION
* #include "io.h"
* ...
*
* To make all functions have internal linkage, i.e. be private to the source
* file, do this:
* #define `IO_STATIC`
* before including "io.h".
*
* i.e. it should look like:
* #define IO_IMPLEMENTATION
* #define IO_STATIC
* #include "io.h"
* ...
*
* You can #define IO_MALLOC, IO_REALLOC, and IO_FREE to avoid using malloc(),
* realloc(), and free(). Note that all three must be defined at once, or none.
*/
#ifndef IO_DEF
#ifdef IO_STATIC
#define IO_DEF static
#else
#define IO_DEF extern
#endif /* IO_STATIC */
#endif /* IO_DEF */
#if defined(__GNUC__) || defined(__clang__)
#define ATTRIB_NONNULL(...) __attribute__((nonnull (__VA_ARGS__)))
#define ATTRIB_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
#define ATTRIB_MALLOC __attribute__((malloc))
#else
#define ATTRIB_NONNULL(...) /* If only. */
#define ATTRIB_WARN_UNUSED_RESULT /* If only. */
#define ATTRIB_MALLOC /* If only. */
#endif /* defined(__GNUC__) || define(__clang__) */
/*
* Reads the file pointed to by `stream` to a buffer and returns it.
* The returned buffer is a nul-terminated string.
* If `nbytes` is not NULL, it shall hold the size of the file. Otherwise it
* shall hold 0.
*
* Returns NULL on memory allocation failure. The caller is responsible for
* freeing the returned pointer.
*/
IO_DEF char *io_read_file(FILE *stream, size_t *nbytes)
ATTRIB_NONNULL(1) ATTRIB_WARN_UNUSED_RESULT ATTRIB_MALLOC; | {
"domain": "codereview.stackexchange",
"id": 45592,
"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, literate-programming",
"url": null
} |
c, literate-programming
/*
* Splits a string into a sequence of tokens. The `delim` argument
* specifies a set of bytes that delimit the tokens in the parsed string.
* If `ntokens` is not NULL, it shall hold the amount of total tokens. Else it
* shall hold 0.
*
* Returns an array of pointers to the tokens, or NULL on memory allocation
* failure. The caller is responsible for freeing the returned pointer.
*/
IO_DEF char **io_split_by_delim(char *restrict s, const char *restrict delim,
size_t *ntokens)
ATTRIB_NONNULL(1, 2) ATTRIB_WARN_UNUSED_RESULT ATTRIB_MALLOC;
/*
* Splits a string into lines.
* A wrapper around `io_split_by_delim()`. It calls the function with "\n" as
* the delimiter.
*
* Returns an array of pointers to the tokens, or NULL on memory allocation
* failure. The caller is responsible for freeing the returned pointer.
*/
IO_DEF char **io_split_lines(char *s, size_t *nlines)
ATTRIB_NONNULL(1) ATTRIB_WARN_UNUSED_RESULT ATTRIB_MALLOC;
/*
* Reads the next chunk of data from the stream referenced to by `stream`.
* `chunk` must be a pointer to an array of at least size IO_CHUNK_SIZE.
*
* If `size` is a non-null pointer, it'd hold the size of the chunk, else it
* would hold 0 on failure.
*
* Returns a pointer to the chunk on success, or NULL elsewise. The returned
* chunk is null-terminated.
*
* `io_read_next_chunk()` does not distinguish between end-of-file and error; the
* routines `feof()` and `ferror()` must be used to determine which occured.
*/
IO_DEF char *io_read_next_chunk(FILE *restrict stream, char *restrict chunk, size_t *size)
ATTRIB_NONNULL(1, 2) ATTRIB_WARN_UNUSED_RESULT; | {
"domain": "codereview.stackexchange",
"id": 45592,
"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, literate-programming",
"url": null
} |
c, literate-programming
/*
* Reads the next line from the stream pointed to by `stream`. The returned line
* is terminated and does not contain a newline, if one was found.
*
* The memory pointed to by `size` shall contain the length of the
* line (including the terminating null character). Else it shall contain 0.
*
* Upon successful completion a pointer is returned and the size of the line is
* stored in the memory pointed to by `size`, otherwise NULL is returned and
* `size` holds 0.
*
* `io_read_line()` does not distinguish between end-of-file and error; the routines
* `feof()` and `ferror()` must be used to determine which occurred. The
* function also returns NULL on a memory-allocation failure.
*
* Although a null character is always supplied after the line, note that
* `strlen(line)` will always be smaller than the value is `size` if the line
* contains embedded null characters.
*/
IO_DEF char *io_read_line(FILE *stream, size_t *size)
ATTRIB_NONNULL(1, 2) ATTRIB_WARN_UNUSED_RESULT ATTRIB_MALLOC;
/*
* `size` should be a non-null pointer. On success, the function assigns `size`
* with the number of bytes read and returns true, or returns false elsewise.
* The function also returns false if the size of the file can not be
* represented.
*
* Note: The file can grow between io_fsize() and a subsequent read.
*/
IO_DEF bool io_fsize(FILE *stream, uintmax_t *size)
ATTRIB_NONNULL(1, 2) ATTRIB_WARN_UNUSED_RESULT;
/*
* Writes `lines` to the file pointed to by `stream`.
* A wrapper around
* On success, it returns true, or false elsewise.
*/
IO_DEF bool io_write_lines(FILE *stream, size_t nlines, char *lines[const static nlines])
ATTRIB_NONNULL(1, 3);
/*
* Writes nbytes from the buffer pointed to by `data` to the file pointed to
* by `stream`.
*
* On success, it returns true, or false elsewise.
*/
IO_DEF bool io_write_file(FILE *stream, size_t nbytes, const char data[static nbytes])
ATTRIB_NONNULL(1, 3); | {
"domain": "codereview.stackexchange",
"id": 45592,
"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, literate-programming",
"url": null
} |
c, literate-programming
#endif /* IO_H */
#ifdef IO_IMPLEMENTATION
#if defined(IO_MALLOC) != defined(IO_REALLOC) || defined(IO_REALLOC) != defined(IO_FREE)
#error "Must define all or none of IO_MALLOC, IO_REALLOC, and IO_FREE."
#endif
#ifndef IO_MALLOC
#define IO_MALLOC(sz) malloc(sz)
#define IO_REALLOC(p, sz) realloc(p, sz)
#define IO_FREE(p) free(p)
#endif
#undef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200809L
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#define IO_CHUNK_SIZE ((size_t)1024 * 8)
#define IO_TOKEN_CHUNK_SIZE ((size_t)1024 * 2)
#define GROW_CAPACITY(capacity, initial) \
((capacity) < initial ? initial : (capacity) * 2)
IO_DEF char *io_read_file(FILE *stream, size_t *nbytes)
{
char *content = NULL;
size_t len = 0;
size_t capacity = 0;
if (nbytes) {
*nbytes = 0;
}
for (size_t rcount = 1; rcount > 0; len += rcount) {
capacity = GROW_CAPACITY(capacity, IO_CHUNK_SIZE);
void *const tmp = IO_REALLOC(content, capacity + 1);
if (tmp == NULL) {
IO_FREE(content);
return NULL;
}
content = tmp;
rcount = fread(content + len, 1, capacity - len, stream);
if (rcount < capacity - len) {
if (!feof(stream)) {
IO_FREE(content);
return content = NULL;
}
/* If we break on the first iteration. */
len += rcount;
break;
}
}
if (nbytes) {
*nbytes = len;
}
content[len] = '\0';
return content;
}
IO_DEF char **io_split_by_delim(char *restrict s, const char *restrict delim,
size_t *ntokens)
{
char **tokens = NULL;
size_t capacity = 0;
size_t token_count = 0;
if (ntokens) {
*ntokens = 0;
} | {
"domain": "codereview.stackexchange",
"id": 45592,
"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, literate-programming",
"url": null
} |
c, literate-programming
if (ntokens) {
*ntokens = 0;
}
while (s != NULL && *s != '\0') {
if (token_count >= capacity) {
capacity = GROW_CAPACITY(capacity, IO_TOKEN_CHUNK_SIZE);
char **const tmp = IO_REALLOC(tokens, sizeof *tokens * capacity);
if (tmp == NULL) {
IO_FREE(tokens);
return NULL;
}
tokens = tmp;
}
tokens[token_count++] = s;
s = strpbrk(s, delim);
if (s) {
*s++ = '\0';
}
}
if (ntokens) {
*ntokens = token_count;
}
return tokens;
}
IO_DEF char **io_split_lines(char *s, size_t *nlines)
{
return io_split_by_delim(s, "\n", nlines);
}
IO_DEF char *io_read_next_chunk(FILE *stream, char *chunk, size_t *size)
{
if (size) {
*size = 0;
}
const size_t rcount = fread(chunk, 1, IO_CHUNK_SIZE, stream);
if (rcount < IO_CHUNK_SIZE) {
if (!feof(stream)) {
/* A read error occured. */
return NULL;
}
if (rcount == 0) {
return NULL;
}
}
chunk[rcount] = '\0';
if (size) {
*size = rcount;
}
return chunk;
}
IO_DEF char *io_read_line(FILE *stream, size_t *size)
{
size_t count = 0;
size_t capacity = 0;
char *line = NULL;
for (;;) {
if (count >= capacity) {
capacity = GROW_CAPACITY(capacity, BUFSIZ);
char *const tmp = realloc(line, capacity + 1);
if (tmp == NULL) {
free(line);
return NULL;
}
line = tmp;
}
const int c = getc(stream); | {
"domain": "codereview.stackexchange",
"id": 45592,
"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, literate-programming",
"url": null
} |
c, literate-programming
line = tmp;
}
const int c = getc(stream);
if (c == EOF || c == '\n') {
if (c == EOF) {
if (feof(stream)) {
if (!count) {
free(line);
return NULL;
}
/* Return what was read. */
break;
}
/* Read error. */
free(line);
return NULL;
} else {
break;
}
} else {
line[count] = (char) c;
}
++count;
}
/* Shrink line to size if possible. */
void *const tmp = realloc(line, count + 1);
if (tmp) {
line = tmp;
}
line[count] = '\0';
*size = ++count;
return line;
}
/*
* Reasons to not use `fseek()` and `ftell()` to compute the size of the file:
*
* Subclause 7.12.9.2 of the C Standard [ISO/IEC 9899:2011] specifies the
* following behavior when opening a binary file in binary mode:
*
* >> A binary stream need not meaningfully support fseek calls with a whence
* >> value of SEEK_END.
*
* In addition, footnote 268 of subclause 7.21.3 says:
*
* >> Setting the file position indicator to end-of-file, as with
* >> fseek(file, 0, SEEK_END) has undefined behavior for a binary stream.
*
* For regular files, the file position indicator returned by ftell() is useful
* only in calls to fseek. As such, the value returned may not be reflect the
* physical byte offset.
*
*/
bool io_fsize(FILE *stream, uintmax_t *size)
{
/*
* Windows supports fileno(), struct stat, and fstat() as _fileno(),
* _fstat(), and struct _stat.
*
* See: https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/fstat-fstat32-fstat64-fstati64-fstat32i64-fstat64i32?view=msvc-170
*/ | {
"domain": "codereview.stackexchange",
"id": 45592,
"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, literate-programming",
"url": null
} |
c, literate-programming
#ifdef _WIN32
#define fileno _fileno
#ifdef _WIN64
#define fstat _fstat64
#define stat __stat64
#else
/* Does this suffice for a 32-bit system? */
#define fstat _fstat
#define stat _stat
#endif /* WIN64 */
#endif /* _WIN32 */
/* According to https://web.archive.org/web/20191012035921/http://nadeausoftware.com/articles/2012/01/c_c_tip_how_use_compiler_predefined_macros_detect_operating_system
* __unix__ should suffice for IBM AIX, all distributions of BSD, and all
* distributions of Linux, and Hewlett-Packard HP-UX. __unix suffices for Oracle
* Solaris. Mac OSX and iOS compilers do not define the conventional __unix__,
* __unix, or unix macros, so they're checked for separately. WIN32 is defined
* on 64-bit systems too.
*/
#if defined(_WIN32) || defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))
struct stat st;
/* rewind() returns no value. */
rewind(stream);
if (fstat(fileno(stream), &st) == 0) {
*size = (uintmax_t) st.st_size;
return true;
}
return false;
#else
/* Fall back to the default and read it in chunks. */
uintmax_t rcount = 0;
char chunk[IO_CHUNK_SIZE];
/* rewind() returns no value. */
rewind(stream);
do {
rcount = fread(chunk, 1, IO_CHUNK_SIZE, stream);
if ((*size + rcount) < *size) {
/* Overflow. */
return false;
}
*size += rcount;
} while (rcount == IO_CHUNK_SIZE);
return !ferror(stream);
#endif /* defined(_WIN32) || defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__)) */
#undef fstat
#undef stat
#undef fileno
} | {
"domain": "codereview.stackexchange",
"id": 45592,
"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, literate-programming",
"url": null
} |
c, literate-programming
IO_DEF bool io_write_lines(FILE *stream, size_t nlines,
char *lines[const static nlines])
{
for (size_t i = 0; i < nlines; ++i) {
if (fprintf(stream, "%s\n", lines[i]) < 0) {
return false;
}
}
return true;
}
IO_DEF bool io_write_file(FILE *stream, size_t nbytes,
const char data[static nbytes])
{
return fwrite(data, 1, nbytes, stream) == nbytes;
}
#undef ATTRIB_NONNULL
#undef ATTRIB_WARN_UNUSED_RESULT
#undef ATTRIB_MALLOC
#undef TOKEN_IO_CHUNK_SIZE
#undef GROW_CAPACITY
#endif /* IO_IMPLEMENTATION */
#ifdef TEST_MAIN
#include <assert.h>
int main(int argc, char **argv)
{
if (argc != 2) {
fputs("Error: file argument missing.\n", stderr);
return EXIT_FAILURE;
}
FILE *fp = fopen(argv[1], "r");
if (!fp) {
perror(argv[1]);
return EXIT_FAILURE;
}
size_t nbytes = 0;
char *const fbuf = io_read_file(fp, &nbytes);
assert(fbuf && nbytes);
assert(io_write_file(stdout, nbytes, fbuf));
rewind(fp);
size_t size = 0;
bool rv = io_fsize(fp, &size);
assert(rv);
printf("Filesize: %zu.\n", size);
size_t nlines = 0;
char **lines = io_split_lines(fbuf, &nlines);
assert(lines && nlines);
assert(io_write_lines(stdout, nlines, lines));
printf("Lines read: %zu.\n", nlines);
for (size_t i = 0; i < nlines; ++i) {
if (lines[i][0]) {
size_t ntokens = 0;
char **tokens = io_split_by_delim(lines[i], " \t", &ntokens);
assert(tokens && ntokens);
assert(io_write_lines(stdout, ntokens, tokens));
free(tokens);
}
}
rewind(fp);
/* This can be allocated dynamically on the heap too. */
char chunk[IO_CHUNK_SIZE];
char *p = chunk;
size_t chunk_size = 0; | {
"domain": "codereview.stackexchange",
"id": 45592,
"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, literate-programming",
"url": null
} |
c, literate-programming
while ((p = io_read_next_chunk(fp, chunk, &chunk_size))) {
printf("Read a chunk of size: %zu.\n", chunk_size);
puts(chunk);
}
rewind(fp);
char *line = NULL;
size_t line_size = 0;
while ((line = io_read_line(fp, &line_size))) {
line[strcspn(line, "\n")] = '\0';
printf("Read a line of size: %zu.\n", line_size);
puts(line);
putchar('\n');
free(line);
}
free(fbuf);
free(lines);
fclose(fp);
return EXIT_SUCCESS;
}
#endif /* TEST_MAIN */
The programs need to be in the manner and order imposed by the relevant compiler, unlike Wikipedia's definition of Literate Programming.
Review Request:
General coding comments, style, et cetera.
Do you see any bugs or undefined/implementation-defined behavior?
As io.h has previously been reviewed (this is not to say that it must be bug-free now), I am mainly interested in getting the main program reviewed.
Answer: I'm going to ignore the larger questions about the history of Literate Programming and just address the issues behind "a program to delete commentary but preserve code blocks set off between specifiable marker lines". I made some of these observations in the comments to the question.
Using while (true) { earns several demerits. And using the const in const int c = … is pretty pointless too. In my opinion, it would be better and more idiomatic C to use:
int c;
while ((c = getopt_long(…)) != -1)
{
…
} | {
"domain": "codereview.stackexchange",
"id": 45592,
"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, literate-programming",
"url": null
} |
c, literate-programming
In the help message, you use -o, --output=FILE to describe the output file option. Why isn't a similar notation used for -b, --begin and -e, --end (e.g. -b, --begin=start-mark and -e, --end=end-mark)?
The indentation in the #ifndef IO_DEF block in io.h is erratic — the #else and the next line should be indented more. That assumes that the indentation of preprocessing directives is desirable; I am not convinced, but it is a valid choice when done consistently.
I'm also unconvinced about including both the function declarations and the implementation in a single file. I don't think this is a good design decision. It becomes awkward to create a library containing the I/O code; you need to create an io.c file with an appropriate set of #define lines before including io.h.
I won't critique (or analyze) the code in io.h further (in part because the question states,"io.h has previously been reviewed").
I don't think you need anywhere near as much I/O code. You simply need to read lines — POSIX getline() is appropriate since you already assume POSIX support — and look at one line at a time. You keep track of the state — either processing commentary or processing code.
If the input line is a begin marker line, then switch to code mode.
If the input line is an end marker line, switch to comment mode.
If you're in comment mode, skip the line.
If you're in code mode, print the line.
You have to worry about invalid transitions — reading a start marker while in code mode, or reading an end marker in comment mode. You also need to warn if you reach EOF in code mode.
This design avoids the need to store the whole file in memory.
I don't think the check on argv is sensible. You wrote:
if (!argv) {
fputs("A NULL argv[0] was passed through an exec system call.\n",
stderr);
return EXIT_FAILURE;
} | {
"domain": "codereview.stackexchange",
"id": 45592,
"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, literate-programming",
"url": null
} |
c, literate-programming
This checks whether the argv pointer is null (not whether the argv[0] pointer is null as the error message suggests).
The C standard guarantees that argv will not be null; even if the system cannot identify the program name, argv[0] must point to an empty string.
C11 §5.1.2.2.1 Program startup ¶2
If they are declared, the parameters to the main function shall obey the following constraints:
The value of argc shall be nonnegative.
argv[argc] shall be a null pointer.
If the value of argc is greater than zero, the array members argv[0] through argv[argc-1] inclusive shall contain pointers to strings, which are given implementation-defined values by the host environment prior to program startup. The intent is to supply to the program information determined prior to program startup from elsewhere in the hosted environment. If the host environment is not capable of supplying strings with letters in both uppercase and lowercase, the implementation shall ensure that the strings are received in lowercase.
If the value of argc is greater than zero, the string pointed to by argv[0] represents the program name; argv[0][0] shall be the null character if the program name is not available from the host environment. If the value of argc is greater than one, the strings pointed to by argv[1] through argv[argc-1] represent the program parameters.
The parameters argc and argv and the strings pointed to by the argv array shall be modifiable by the program, and retain their last-stored values between program startup and program termination. | {
"domain": "codereview.stackexchange",
"id": 45592,
"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, literate-programming",
"url": null
} |
c, literate-programming
Your check is pointless — even if argc is 0, argv will not be a null pointer. argv[0] might be a null pointer, but the only code that has to worry about that is code that stashes the program name away for error reporting. If you want to check that argv[0] is not null, you need to write the correct test: if (argv[0] != NULL).
I'm not yet ready to use C23 features in code that I need to be able to run on machines that only have support for older versions of the standard. YMMV on that score. I'll leave your conditional definition and uses of nullptr alone, but your code doesn't use nullptr_t, so that can be omitted.
I ended up removing all the Boolean variables. This evades problems with <stdbool.h>. In C23, bool is a built-in type, true and false are keywords, and the header is not needed. For C99 through C18, the header should be used. Prior to C99, there was no <stdbool.h> header, but that shouldn't be a concern — you shouldn't be using compilers that do not support at least C99 and preferably C11 or C18. As of March 2024, the C23 standard has not been released by ISO. It will probably be ISO 9899:2024, but will probably continue to be known as C23.
You asked about using a structure for the control variables. In a one-file program like this, it is legitimate to use static file scope ('global') variables to convey global state information to functions. If I kept the structure, I might use a name such as struct Control. Note that you cannot initialize file stream variables (such as output) at file scope with stdin in modern C libraries, though you'd find such code written for older systems. Note that the main() function is the only symbol defined by the code that is visible outside the object file. I wish that static was the default visibility and that you had to use an explicit notation to make symbols visible outside the source file. However, a language with those rules would not be C. | {
"domain": "codereview.stackexchange",
"id": 45592,
"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, literate-programming",
"url": null
} |
c, literate-programming
The long_options argument to parse_options() isn't needed if you either move the definition of the array into the function or make it a file scope 'variable' placed near the definition of the short options string. You don't pass the short options as a parameter to parse_options() — consistency suggests one or the other, not a mixture.
You've almost certainly used programs that match the 'filter' paradigm (e.g. cat or grep). If one or more file names are present on the command line, those files are processed; otherwise, standard input is processed. This program should probably follow that pattern too. Granted, it is unlikely that more than one file will be processed because concatenated C files are not usually a good idea.
You have the code:
if (f != stdout && ftruncate(fileno(f), 0)) {
perror("seek()"); | {
"domain": "codereview.stackexchange",
"id": 45592,
"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, literate-programming",
"url": null
} |
c, literate-programming
It is misleading to claim a seek error when ftruncate() fails. However, if you open the output file in "w" mode, the ftruncate() operation is superfluous.
If this were my code, I'd use the error reporting routines available in my SOQ (Stack Overflow Questions) repository on GitHub as files stderr.c and stderr.h in the src/libsoq sub-directory.
On Linux, you can find loosely similar functionality documented as err(3). Either package simplifies error reporting.
This version of the code continues processing files even if one cannot be opened. It terminates the processing of the current file on an error, but continues to the next file. It is perfectly reasonable to decide to terminate on any error — in fact, it is often better to do that ("fail fast"), in my opinion.
Here's what I think will do the job for you:
/* Code Review: CR 209-991 */
#undef _POSIX_C_SOURCE
#undef _XOPEN_SOURCE
#define _POSIX_C_SOURCE 200819L
#define _XOPEN_SOURCE 700
#include <assert.h>
#include <errno.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
/* In C2X/C23 or later, nullptr is a keyword. */
/* Patch up C18 (__STDC_VERSION__ == 201710L) and earlier versions. */
#if !defined(__STDC_VERSION__) || __STDC_VERSION__ <= 201710L
#define nullptr ((void *)0)
#endif
static const char short_options[] = "b:e:o:h";
static const struct option long_options[] =
{
{ "begin", required_argument, nullptr, 'b' },
{ "end", required_argument, nullptr, 'e' },
{ "help", no_argument, nullptr, 'h' },
{ "output", required_argument, nullptr, 'o' },
{ nullptr, 0, nullptr, 0 },
};
static const char *argv0 = "<unknown>";
#define DEFAULT_BEGIN "\\begin{code}"
#define DEFAULT_END "\\end{code}" | {
"domain": "codereview.stackexchange",
"id": 45592,
"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, literate-programming",
"url": null
} |
c, literate-programming
#define DEFAULT_BEGIN "\\begin{code}"
#define DEFAULT_END "\\end{code}"
static const char *bflag = DEFAULT_BEGIN; /* Begin flag */
static const char *eflag = DEFAULT_END; /* End flag */
static FILE *output = NULL; /* Output file stream */
static void help(void)
{
printf("Usage: %s [OPTIONS] SRC\n\n"
" %s - extract code from a LaTEX document.\n\n"
"Options:\n"
" -b, --begin=MARKER Line that denotes the beginning of the code\n"
" block in the markup language. Default: %s.\n"
" -e, --end=MARKER Line that denotes the end of the code block in\n"
" the markup language. Default: %s.\n"
" -h, --help Displays this message and exits.\n"
" -o, --output=FILE Writes result to FILE instead of standard output.\n\n"
"Note: The begin and end markers must be different.\n\n"
"For Markdown, they can be:\n"
" ```python\n"
" # Some code here\n"
" ```\n",
argv0, argv0, DEFAULT_BEGIN, DEFAULT_END);
exit(EXIT_SUCCESS);
}
static void err_and_fail(void)
{
fprintf(stderr, "The syntax of the command is incorrect.\n"
"Use: %s -h for more information.\n", argv0);
exit(EXIT_FAILURE);
}
static void parse_options(int argc, char **argv)
{
int c;
output = stdout; | {
"domain": "codereview.stackexchange",
"id": 45592,
"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, literate-programming",
"url": null
} |
c, literate-programming
static void parse_options(int argc, char **argv)
{
int c;
output = stdout;
while ((c = getopt_long(argc, argv, short_options, long_options, nullptr)) != -1)
{
switch (c)
{
case 'e':
eflag = optarg;
break;
case 'b':
bflag = optarg;
break;
case 'h':
help();
break;
case 'o':
/* If -o was provided more than once. */
if (output != stdout)
{
fprintf(stderr, "Error: Multiple -o flags provided.\n");
err_and_fail();
}
output = fopen(optarg, "w");
if (output == nullptr)
{
fprintf(stderr, "%s: failed to open file '%s' for writing: %d %s\n",
argv0, optarg, errno, strerror(errno));
exit(EXIT_FAILURE);
}
break;
default:
err_and_fail();
break;
}
}
if (strcmp(eflag, bflag) == 0)
{
fprintf(stderr, "%s: the start and end markers must be different (both are '%s')\n", eflag, bflag);
exit(EXIT_FAILURE);
}
}
static int process(FILE *fp, const char *fn)
{
size_t buflen = 0;
char *buffer = 0;
enum { COMMENT, CODE } mode = COMMENT;
size_t lineno = 0;
size_t num_code_blocks = 0; | {
"domain": "codereview.stackexchange",
"id": 45592,
"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, literate-programming",
"url": null
} |
c, literate-programming
ssize_t length;
while ((length = getline(&buffer, &buflen, fp)) > 0)
{
lineno++;
assert(buffer[length] == '\0' && buffer[length - 1] == '\n');
buffer[length - 1] = '\0';
if (mode == CODE)
{
if (strcmp(buffer, bflag) == 0)
{
fprintf(stderr, "%s: error: found begin marker '%s' in file '%s' line %zu while in code mode\n",
argv0, bflag, fn, lineno);
goto cleanup_and_fail;
}
else if (strcmp(buffer, eflag) == 0)
mode = COMMENT;
else if (fprintf(output, "%s\n", buffer) < 0)
{
fprintf(stderr, "%s: error: failed to write to output file while reading file '%s' line %zu\n",
argv0, fn, lineno);
goto cleanup_and_fail;
}
}
else
{
assert(mode == COMMENT);
if (strcmp(buffer, eflag) == 0)
{
fprintf(stderr, "%s: error: found end marker '%s' in file '%s' line %zu while in comment mode\n",
argv0, eflag, fn, lineno);
goto cleanup_and_fail;
}
else if (strcmp(buffer, bflag) == 0)
{
num_code_blocks++;
mode = CODE;
}
}
}
free(buffer);
if (mode != COMMENT)
{
fprintf(stderr, "%s: file '%s' is missing a code end marker '%s'\n", argv0, fn, eflag);
return EXIT_FAILURE;
}
if (num_code_blocks == 0)
{
fprintf(stderr, "%s: file '%s' contained zero code blocks\n", argv0, fn);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
cleanup_and_fail:
free(buffer);
return EXIT_FAILURE;
}
int main(int argc, char *argv[])
{
int status = EXIT_SUCCESS;
/* The test is superfluous */
if (argv[0])
argv0 = argv[0];
parse_options(argc, argv); | {
"domain": "codereview.stackexchange",
"id": 45592,
"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, literate-programming",
"url": null
} |
c, literate-programming
parse_options(argc, argv);
if (optind == argc)
status = process(stdin, "standard input");
else
{
for (int i = optind; i < argc; i++)
{
FILE *fp = fopen(argv[i], "r");
if (fp == NULL)
{
fprintf(stderr, "%s: failed to open file '%s' for reading: %d (%s)\n",
argv0, argv[i], errno, strerror(errno));
status = EXIT_FAILURE;
}
else
{
int rc = process(fp, argv[i]);
if (status == EXIT_SUCCESS)
status = rc;
fclose(fp);
}
}
}
if (fclose(output) != 0)
{
fprintf(stderr, "%s: failed to close output file\n", argv0);
status = EXIT_FAILURE;
}
return status;
}
I copied your sample inputs into files litc-1.script and litc-2.script. My program was called cr-290991. The outputs I got were:
$ cr-290991 litc-1.script
#include <stdio.h>
int main(void) {
puts("Hello World!");
}
$ cr-290991 -o litc-2.c -b '```c' -e '```' litc-2.script
$ cat litc-2.c
#include <stdio.h>
int main(void) {
puts("Hello World!");
}
$ | {
"domain": "codereview.stackexchange",
"id": 45592,
"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, literate-programming",
"url": null
} |
c++, console, classes, snake-game
Title: Terminal based game: Part 3 (Using templated game)
Question: Working from previous posts
In this post: Terminal based game: Part 2 I introduced the concept of a Game object. To build a game like Terminal Base Snake you could derive from Game and override 4 functions to get a simple terminal based game running.
But my thoughts are that for beginners they need to already be familiar with classes and would it be easier for them to pass a set of functions to a builder object. That way they could write the game as a set of four functions (that can be easily tested in step mode). Then you can create a game object by passing the functions.
So I would add the following code.
template<typename Display, typename Input, typename Logic, typename Timeout>
class GameTemplate: public ThorsAnvil::GameEngine::Game
{
Display displayFunc;
Input inputFunc;
Logic logicFunc;
Timeout timeoutFunc;
virtual int gameStepTimeMilliSeconds() override
{
return timeoutFunc();
}
virtual void drawFrame() override
{
displayFunc();
}
virtual void handleInput(char k) override
{
Game::handleInput(k);
inputFunc(k);
}
virtual void handleLogic() override
{
logicFunc();
}
public:
GameTemplate(Display&& display, Input&& input, Logic&& logic, Timeout&& timout)
: displayFunc(std::move(display))
, inputFunc(std::move(input))
, logicFunc(std::move(logic))
, timeoutFunc(std::move(timout))
{}
};
template<typename Display, typename Input, typename Logic, typename Timeout>
GameTemplate<Display, Input, Logic, Timeout> makeGame(Display&& display, Input&& input, Logic&& logic, Timeout&& timout)
{
return GameTemplate<Display, Input, Logic, Timeout>(std::move(display), std::move(input), std::move(logic), std::move(timout));
} | {
"domain": "codereview.stackexchange",
"id": 45593,
"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++, console, classes, snake-game",
"url": null
} |
c++, console, classes, snake-game
Main would now look like this:
int main()
{
auto snake = makeGame(drawFrame, handleInput, handleLogic, gameStepTimeMilliSeconds);
snake.run();
}
After this I could then introduce classes and show it tidy's up all the global variables.
Any thoughts?
Example of snake code.
Create snake game simply using functions and global variables (no advanced concepts like a class).
static constexpr int width = 20;
static constexpr int height = 20;
static constexpr double speedInceaseFactor = 0.92;
int score = 0;
char key = ' ';
Snake snake{{width/2, height/2}};
Location cherry{(rand() % (width - 2)) +1 , (rand() % (height - 2)) +1};
char getChar(Location const& pos)
{
if (pos.y == 0 || pos.y == height - 1 || pos.x == 0 || pos.x == width -1) {
return '#';
}
if (pos == cherry) {
return '%';
}
char s = snake.check(pos);
if (s != ' ') {
return s;
}
return ' ';
}
int gameStepTimeMilliSeconds()
{
return 500 * std::pow(speedInceaseFactor, snake.size());
}
void drawFrame()
{
std::cout << "Snake V1.0\n";
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
std::cout << getChar({x, y});
}
std::cout << "\n";
}
std::cout << "Score: " << score << " LastKey: " << key << "\n";
std::cout << "Step: " << gameStepTimeMilliSeconds() << " \n";
std::cout << std::flush;
}
void handleInput(char k)
{
switch (k)
{
case 'q': snake.changeDirection(Up); break;
case 'a': snake.changeDirection(Down); break;
case 'o': snake.changeDirection(Left); break;
case 'p': snake.changeDirection(Right); break;
default: break;
}
}
bool snakeHitWall()
{
Location const& head = snake.head();
return head.y == 0 || head.y == height -1 || head.x == 0 || head.x == width -1;
}
void handleLogic()
{
bool moveOk = snake.move(); | {
"domain": "codereview.stackexchange",
"id": 45593,
"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++, console, classes, snake-game",
"url": null
} |
c++, console, classes, snake-game
if (!moveOk || snakeHitWall()) {
std::cout << "Move: " << moveOk << "\n"
<< "Head: " << snake.head() << " \n"
<< "Wall: " << snakeHitWall() << "\n";
exit(1);
//setGameOver();
}
if (snake.head() == cherry) {
snake.grow();
score++;
cherry = {(rand() % (width - 2)) +1 , (rand() % (height - 2)) +1};
}
}
Answer: Just make a runGame() function
You want to avoid classes, but you are still introducing one here: a GameTemplate object is returned from makeGame(), and then you have to use the member function .run() to actually run the game.
Instead, just provide a function runGame(), so main() becomes:
int main()
{
runGame(drawFrame, handleInput, handleLogic, gameStepTimeMilliSeconds);
}
Internally that could still create an object and call run() on it. But you could even take this further, and make your game engine work with just regular functions. The advantage is that the beginner programmer can then more easily follow what is going on, if they are interested in looking at the implementation of your game engine.
Since you are stepping into the world of global variables and function anyway, also consider not providing any arguments to runGame(), and instead implement it like so:
void runGame() {
init();
while (!gameOver) {
input();
draw();
logic();
}
exit();
} | {
"domain": "codereview.stackexchange",
"id": 45593,
"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++, console, classes, snake-game",
"url": null
} |
c++, console, classes, snake-game
exit();
}
Where input() is just Game::input(), but calling the global handleInput() directly, and similar for draw() and logic(). init() and exit() just do what was in your constructor and destructor.
For the game programmer, this then becomes very much like how you would program an Arduino device; there you just have to implement the free functions setup() and loop(), and the Arduino framework takes care of calling them.
Don't use rand()
Use C++'s random number features instead of rand(). Yes, it's a bit more verbose to write, but it is more correct, and features like std::uniform_int_distribution are much easier than having to do modulo arithmetic. | {
"domain": "codereview.stackexchange",
"id": 45593,
"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++, console, classes, snake-game",
"url": null
} |
perl, geospatial
Title: Convert British and Irish National Grid references to or from WGS84 geodetic coordinates
Question: I've been using this wgs84togrid program for a few years. It converts in both directions between National Grid coordinates for GB or Ireland (beginning with a letter or letter-pair identifying the 100km square) and latitude/longitude positions (in decimal degrees, decimal minutes or decimal seconds) on a WGS84 ellipsoid.
It acts as a filter, expecting one point per line, copying unchanged any unrecognised parts of the line.
Program options (all may be shortened, provided that's unambiguous):
-grid: choose a grid: GB (default) or IE
-reverse: reverse direction - convert National Grid positions to WGS84
-lonlat: geodesic positions are longitude first
-datum: use alternative datum instead of WGS84 (National Grid coordinates are always on the appropriate fixed datum)
-precision: how many digits to include in northings and eastings (default: 5, which gives 1-metre resolution)
-verbose: extra output (to confirm that lat/lon are parsed as you expect).
Example use (in Bash):
$ wgs84togrid -p 3 <<<"55°56′55\″N 3°12′03\″W"
NT251734
$ wgs84togrid -r <<<NT251734
55.9482278708547 -3.20011121889597
The heavy work of coordinate transformation is performed by the PROJ.4 library; all I do is manage the grid letters and I/O formats.
I assume the presence of scotland.gsb and england-wales.gsb grid corrections files, but that option may be removed if you don't have them, at the cost of a few metres of accuracy (< 10m, I'm sure).
Specifically out of scope:
I don't check that the point is within the valid area of the chosen grid (and certainly don't think of auto-selecting the correct grid).
No plans to support any other grids elsewhere in the world.
#!/usr/bin/perl -w
use strict;
use Getopt::Long;
use Geo::Proj4; | {
"domain": "codereview.stackexchange",
"id": 45594,
"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": "perl, geospatial",
"url": null
} |
perl, geospatial
#!/usr/bin/perl -w
use strict;
use Getopt::Long;
use Geo::Proj4;
my %squares = (A=>'04', B=>'14', C=>'24', D=>'34', E=>'44',
F=>'03', G=>'13', H=>'23', J=>'33', K=>'43',
L=>'02', M=>'12', N=>'22', O=>'32', P=>'42',
Q=>'01', R=>'11', S=>'21', T=>'31', U=>'41',
V=>'00', W=>'10', X=>'20', Y=>'30', Z=>'40');
my %tosquare = map { ($squares{$_}, $_) } keys %squares;
my $grid = 'GB';
my $lonlat;
my $datum = 'WGS84';
my $precision = 5;
my $reverse;
my $verbose;
GetOptions('grid=s' => \$grid,
'reverse!' => \$reverse,
'lonlat!' => \$lonlat,
'datum=s' => \$datum,
'precision=i' => \$precision,
'verbose!' => \$verbose) or die "Option parsing failure\n";
sub any2xy($$$) {
my ($x, $y, $numbers) = @_;
my $len = length $numbers;
die "Odd gridref length - '$_' ($len)\n" if $len % 2;
$len /= 2;
$x = 100000 * ("$x.".substr($numbers, 0, $len).'5');
$y = 100000 * ("$y.".substr($numbers, $len).'5');
return [$x, $y];
}
sub osgb2xy($) {
local $_ = shift;
my ($letters, $numbers) = m/^(\D{2})(\d+)$/ or die "Malformed OSGB ref '$_'\n";
my $x = 0;
my $y = 0;
foreach (split '', $letters) {
my @sq = split '', $squares{$_} or die "Non-grid square '$_'\n";
$x = 5 * $x + $sq[0];
$y = 5 * $y + $sq[1];
}
$x -= 10;
$y -= 5;
return any2xy($x, $y, $numbers);
}
sub osi2xy($) {
$_ = shift;
my ($letters, $numbers) = m/^(\D)(\d+)$/ or die "Malformed OSI ref '$_'\n";
my ($x, $y) = split '', $squares{$letters} or die "Non-grid square '$_'\n";
return any2xy($x, $y, $numbers);
}
sub togrid($$$$) {
my ($sq, $x, $y, $prec) = @_;
return sprintf('%s%s%s', $sq, map { substr(100000 + $_%100000, 1, $prec) } ($x, $y));
} | {
"domain": "codereview.stackexchange",
"id": 45594,
"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": "perl, geospatial",
"url": null
} |
perl, geospatial
sub xy2osi($$$) {
my ($x, $y, $prec) = @_;
my $sq = $tosquare{int($x/100000) . int($y/100000)} or die "No square for $x,$y\n";
return togrid($sq, $x, $y, $prec);
}
sub xy2osgb($$$) {
my ($x, $y, $prec) = @_;
$x += 1000000;
$y += 500000;
my $sq = $tosquare{int($x/500000) . int($y/500000)} . $tosquare{int($x/100000)%5 . int($y/100000)%5} or die "No square for $x,$y\n";
return togrid($sq, $x, $y, $prec);
}
my $inputs;
sub getnext();
sub getnext() {
if ($inputs) {
$_ = <$inputs>;
return $_ if $_;
$inputs = undef;
}
if (@ARGV) {
$_ = shift @ARGV;
if ($_ eq '-') {
$inputs = \*STDIN;
return getnext();
}
return $_;
}
return undef;
}
my $wgs84 = Geo::Proj4->new(proj => 'latlon', datum => $datum) or die Geo::Proj4->error;
my ($proj, $xy2grid, $grid2xy);
if (uc $grid eq 'GB') {
$proj = Geo::Proj4->new(init => 'epsg:27700 +nadgrids=scotland.gsb,england-wales.gsb') or die Geo::Proj4->error;
$xy2grid = \&xy2osgb;
$grid2xy = \&osgb2xy;
} elsif (uc $grid eq 'IE') {
$proj = Geo::Proj4->new(init => 'epsg:29901') or die Geo::Proj4->error;
$xy2grid = \&xy2osi;
$grid2xy = \&osi2xy;
} else {
die "Unknown grid '$grid'\n";
}
my $numpat = '[+-]?\d+(?:\.\d+)?\s*'; | {
"domain": "codereview.stackexchange",
"id": 45594,
"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": "perl, geospatial",
"url": null
} |
perl, geospatial
my $numpat = '[+-]?\d+(?:\.\d+)?\s*';
@ARGV=('-') unless @ARGV;
while ($_ = getnext()) {
chomp;
if ($reverse) {
my $point = $grid2xy->($_);
my ($lon, $lat) = @{$proj->transform($wgs84, $point)};
print $lonlat ? "$lon $lat\n" : "$lat $lon\n";
} else {
tr/,'"/ ms/; # ' # for prettify
s/°/d/g; # UTF-8 multibyte chars don't work with 'tr'
s/′/m/g;
s/″/s/g;
s/($numpat)m\s*($numpat)s?/($1 + $2\/60.0) . "m"/oeg;
s/($numpat)d(?:eg)?\s*($numpat)(?:m\s*)?/($1 + $2\/60.0)/oeg;
tr/d//d;
s/\s*\b([nsew])\b\s*/$1/i;
tr!/,! !;
s/($numpat[ew ])\s*($numpat[ns]?)/$2 $1/oi;
s/($numpat)\s+($numpat[ns]|[ns]$numpat)/$2 $1/oi;
my ($lat, $ns, $lon, $ew) = m/^\s*($numpat)([ns ]?)\s*($numpat)([ew]?)\s*$/i
or die "Malformed input: $_\n";
$lat *= -1 if lc $ns eq 's';
$lon *= -1 if lc $ew eq 'w';
print STDERR "$lat, $lon\n" if $verbose;
my $point = ($ns || $ew || $lonlat) ? [$lon, $lat] : [$lat, $lon];
my ($x, $y) = @{$wgs84->transform($proj, $point)};
print $xy2grid->($x, $y, $precision), "\n";
}
}
Answer: NB: This review assumes Perl5, specifically the Unicode features in 5.12 (released 2010) and later. | {
"domain": "codereview.stackexchange",
"id": 45594,
"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": "perl, geospatial",
"url": null
} |
perl, geospatial
1. the parsing could be simpler and more featureful
Much code is devoted to handling delimiters that we're only going to throw away.
Explicit N/S/E/W should override -lonlat but don't.
The sole error message ("malformed input") is vague and happens at the very end, after a series of transformations on the input. The mangled string—which may not resemble original input much anymore—is included in the error message and only adds to the confusion.
In general: modifying an input string to impart meaning is usually a mistake. Modify to remove noise, extract the meaningful parts as structured data, and deal with them there.
2. there is a fair amount of duplicated or nearly-duplicated code
A dispatch table is the standard way to choose code based on data. Your "a2b" functions have a lot of common code, and can be merged once the unique parts are moved into a data structure.
3. the data representations could be more suitable
squares and tosquare use 2-digit values, but you never need values in that format. You always need a pair of single digits, and this complicates the conversion functions. Restructure to suit the need, such that $squares{A} == [ 0, 4 ] (hash of arrays) and $tosquare[0][4] == 'A' (array of arrays).
100000 is better written as 100_000 or 1e5.
$numpat can be simplified to qr/[+-]? \d+ \.?\d* \s* /x. Write regular expression pieces with the qr/REGEXP/ quoting construct, so that they are only compiled once; you then won't need /o modifiers when you reference them. The /x modifier allows the use of whitespace in regular expressions, and makes long expressions more readable. Space within [ ] is still recognized; other whitespace is ignored.
4. Unicode handling is haphazard
This is an artifact of writing in Perl4, which had no Unicode facilities. In Perl5, UTF-8 source code (s/°/d/g; etc.) should inform Perl of the source encoding via use utf8;. | {
"domain": "codereview.stackexchange",
"id": 45594,
"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": "perl, geospatial",
"url": null
} |
perl, geospatial
To accept UTF-8 input, STDIN should be placed in :utf8 mode, via binmode STDIN, ":utf8". As you're including user input in die messages, STDERR should get the same treatment.
5. tricks and minor stuff
getnext() is about three times longer and more confusing than it ought to be; see below for a revised version.
Every output ends in a newline; use the -l switch instead.
%tosquare = reverse %squares is the idiomatic version of %tosquare = map { ($squares{$_}, $_) } keys %squares.
local $_ = shift; is usually what you want when assigning to $_ in a sub, else it will be clobbered in the calling scope. (The rewrite contravenes this advice and clobbers $_ on purpose.)
nadgrids= can be adjusted at setup time to ignore missing files. Calls to ->transform() should print error on failure (due to, say, a missing nadgrids file :)
A long series of synonym-to-canonical-value substitutions, as you're doing with s/°/d/g, etc., can be replaced by a hash table where the keys combine into a regex, as in:
my %decoratives=(qw( ' m " s ° d ′ m ″ s ), ("," => " ") );
s/([@{[ join '', keys %decoratives ]}])/$decoratives{$1}/g; | {
"domain": "codereview.stackexchange",
"id": 45594,
"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": "perl, geospatial",
"url": null
} |
perl, geospatial
revision
Here's my response to my own criticisms. It's not much shorter—about 75% of the original's size—but does improve the error messages and is (perhaps) more clear in its intent.
#!/usr/bin/perl -wl
use strict;
use Getopt::Long;
use Geo::Proj4;
use utf8;
binmode STDIN, ":utf8";
binmode STDERR, ":utf8";
sub grid2xy(_);
sub xy2grid($$$);
sub getnext();
my %squares = qw(
A 04 B 14 C 24 D 34 E 44 F 03 G 13 H 23 J 33 K 43 L 02 M 12 N 22
O 32 P 42 Q 01 R 11 S 21 T 31 U 41 V 00 W 10 X 20 Y 30 Z 40
);
my @tosquare;
$tosquare[ int $squares{$_}/10 ][ $squares{$_}%10 ] = $_ for keys %squares;
$_ = [ split '' ] for values %squares;
my %howto=(
GB => {
setup => 'epsg:27700 +nadgrids=' . join(',' => grep { -f } qw( scotland.gsb england-wales.gsb )),
parse => qr/^(\D\D)(\d+)$/,
xy2os => sub { [ map { int($_[$_]/5e5) + 2 - $_ } 0..1 ], [ map { ($_[$_]/1e5) % 5 } 0..1 ] },
os2xy => sub { map { 5*$_[0][$_] + $_[1][$_] - 10 + 5*$_ } 0..1 }
},
IE => {
setup => 'epsg:29901',
parse => qr/^(\D)(\d+)$/,
xy2os => sub { [ map int($_/1e5) => @_ ] },
os2xy => sub { @{ $_[0] } }
}
);
my ($grid, $datum, $precision,$lonlat,$reverse,$verbose) = ('GB', 'WGS84', 5);
GetOptions(
'grid=s' => \$grid,
'reverse!' => \$reverse,
'lonlat!' => \$lonlat,
'datum=s' => \$datum,
'precision=i' => \$precision,
'verbose!' => \$verbose
) or die "Option parsing failure\n";
our %do=%{ $howto{$grid} or die "Unknown grid $grid\n" };
my $wgs84 = Geo::Proj4->new(proj => 'latlon', datum => $datum) or die Geo::Proj4->error;
my $proj = Geo::Proj4->new(init => $do{setup}) or die Geo::Proj4->error; | {
"domain": "codereview.stackexchange",
"id": 45594,
"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": "perl, geospatial",
"url": null
} |
perl, geospatial
@ARGV=('-') unless @ARGV;
while (getnext) {
if ($reverse) {
my @lola = @{ $proj->transform($wgs84, grid2xy) or die $proj->error };
local $,=" ";
print $lonlat ? @lola : reverse @lola;
} else {
my @tokens= map {uc} /( [+-]? \d+ \.?\d* | [NSEW] )/gix;
print "tokens: @tokens" if $verbose;
my @lalo=(0,0);
my @dms=( 1, 60, 3600 );
my ($unit,$ll,$seenNS, $seenEW)=(0,0,0,0);
my %seen=( N => \$seenNS, S => \$seenNS, E => \$seenEW, W => \$seenEW );
my %sign=( N => 1, S => -1, E => 1, W => -1 );
while (@tokens) {
my $tok=shift @tokens;
if ($sign{$tok}) {
die "Repeated or conflicting direction '$tok'\n" if ${ $seen{$tok} };
die "Directions come after the coordinates\n" unless $unit;
$lalo[$ll++] *= $sign{$tok};
${ $seen{$tok} } = $ll; # after the increment so that it's nonzero.
$unit=0;
} else {
if ($unit>$#dms) { $ll++; $unit=0; }
die "Too many coordinates in '$_'\n" if $ll>1;
$lalo[$ll] += $tok / $dms[$unit++];
}
}
@lalo=reverse @lalo if (!$seenNS && !$seenEW && $lonlat or $seenNS==1 or $seenEW==2);
print STDERR "lat/lon @lalo" if $verbose;
my ($x, $y) = @{ $wgs84->transform($proj, [ @lalo ]) or die $wgs84->error };
print xy2grid($x, $y, $precision);
}
}
exit 0;
sub grid2xy(_) {
local $_=shift;
my ($letters, $numbers) = /$do{parse}/ or die "Malformed ref '$_'\n";
my $len = length $numbers;
die "Odd gridref length - '$_' ($len)\n" if $len % 2;
$len /= 2;
my @sq = map { $squares{$_} or die "Non-grid square '$_'\n" } split '', $letters;
my ($x,$y) = $do{os2xy}(@sq);
$x = 100000 * ("$x.".substr($numbers, 0, $len).'5');
$y = 100000 * ("$y.".substr($numbers, $len).'5');
return [$x, $y];
} | {
"domain": "codereview.stackexchange",
"id": 45594,
"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": "perl, geospatial",
"url": null
} |
perl, geospatial
sub xy2grid($$$) {
my ($x, $y, $prec) = @_;
local $,=","; # for the die()
my $sq = join '', map { $tosquare[ $_->[0] ][ $_->[1] ] or die "No square for @$_\n" } $do{xy2os}($x,$y);
return sprintf('%s%s%s', $sq, map { substr(100000 + $_%100000, 1, $prec) } ($x, $y));
}
sub getnext() {
if (@ARGV and $ARGV[0] eq '-') {
if ($_ = <STDIN>) { chomp; return $_ }
else { shift @ARGV }
}
return $_=shift @ARGV;
} | {
"domain": "codereview.stackexchange",
"id": 45594,
"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": "perl, geospatial",
"url": null
} |
java, object-oriented, unit-testing, ascii-art
Title: simple Text Table utility
Question: A small utility to print data in an ascii table
TextTable
public class TextTable {
private TextTable(){ }
public static List<String> getLines(List<TableRow> items){
return new TextTableFormatter(items).createTableRows();
}
public static void print(List<TableRow> items, PrintStream stream){
getLines(items).forEach(stream::println);
}
public static void print(List<TableRow> items){
print(items, System.out);
}
}
TableRow
@FunctionalInterface
public interface TableRow {
Map<String, String> getCellDescriptions();
}
TextTableFormatter
public class TextTableFormatter {
private final Map<String, Integer> columnsWidths;
private final Set<String> columnNames;
private final List<TableRow> items;
//see https://en.wikipedia.org/wiki/Box-drawing_character for more characters
private static final String CROSS = "┼";
private static final String HORIZONTAL_LINE = "─";
private static final String VERTICAL_LINE = "│";
private static final String CORNER_TOP_LEFT = "┌";
private static final String CORNER_TOP_RIGHT = "┐";
private static final String JOIN_TOP = "┬";
private static final String JOIN_LEFT = "├";
private static final String JOIN_RIGHT = "┤";
private static final String CORNER_BOTTOM_LEFT = "└";
private static final String CORNER_BOTTOM_RIGHT = "┙";
private static final String JOIN_BOTTOM = "┴";
TextTableFormatter(List<TableRow> items) {
this.items = items;
columnNames = calculateColumnNames();
columnsWidths = calculateColumnWidths();
}
List<String> createTableRows() {
List<String> tableRows = new ArrayList<>();
//header rows
tableRows.add(createTopTableLine());
tableRows.add(createHeaderRow());
tableRows.add(createMiddleTableLine()); | {
"domain": "codereview.stackexchange",
"id": 45595,
"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, object-oriented, unit-testing, ascii-art",
"url": null
} |
java, object-oriented, unit-testing, ascii-art
//data rows
for (int i = 0; i < items.size(); i++) {
TableRow item = items.get(i);
tableRows.add(createDataRow(item));
tableRows.add(isLastItem(i) ? createBottomTableLine() : createMiddleTableLine());
}
return tableRows;
}
private String createDataRow(TableRow item) {
StringBuilder itemLine = new StringBuilder();
for (String columnName : columnNames) {
String cell = item.getCellDescriptions().getOrDefault(columnName, "");
itemLine.append(VERTICAL_LINE).append(fillCenter(cell, columnsWidths.get(columnName)));
}
itemLine.append(VERTICAL_LINE);
return itemLine.toString();
}
private String createHeaderRow() {
StringBuilder headerLine = new StringBuilder();
for (String columnName : columnNames) {
headerLine.append(VERTICAL_LINE).append(fillCenter(columnName, columnsWidths.get(columnName)));
}
headerLine.append(VERTICAL_LINE);
return headerLine.toString();
}
private Map<String, Integer> calculateColumnWidths() {
Map<String, Integer> columnWidths = new HashMap<>();
for (String columnName : columnNames) {
int width = items.stream()
.map(i -> i.getCellDescriptions().getOrDefault(columnName, ""))
.mapToInt(String::length)
.max().orElse(0);
width = Math.max(width, columnName.length());
columnWidths.put(columnName, width);
}
return columnWidths;
}
private Set<String> calculateColumnNames() {
return items.stream()
.flatMap(i -> i.getCellDescriptions().keySet().stream())
.collect(Collectors.toSet());
}
private String createTopTableLine() {
return createTableLine(CORNER_TOP_LEFT, JOIN_TOP, CORNER_TOP_RIGHT);
} | {
"domain": "codereview.stackexchange",
"id": 45595,
"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, object-oriented, unit-testing, ascii-art",
"url": null
} |
java, object-oriented, unit-testing, ascii-art
private String createMiddleTableLine() {
return createTableLine(JOIN_LEFT, CROSS, JOIN_RIGHT);
}
private String createBottomTableLine() {
return createTableLine(CORNER_BOTTOM_LEFT, JOIN_BOTTOM, CORNER_BOTTOM_RIGHT);
}
private String createTableLine(String startCharacter, String contentSeparator, String endCharacter) {
return startCharacter + columnNames.stream().map(c -> HORIZONTAL_LINE.repeat(columnsWidths.get(c))).collect(Collectors.joining(contentSeparator)) + endCharacter;
}
private String fillCenter(String input, int length) {
int numberOfMissing = length - input.length();
int lead = numberOfMissing / 2;
int trail = numberOfMissing - lead;
return " ".repeat(lead) + input + (" ".repeat(trail));
}
private boolean isLastItem(int i) {
return i == items.size()-1;
}
}
TextTableTest
class TextTableTest {
@Test
public void testTablePrintOutput(){
List<TableRow> items = List.of(
new TablePoint(1,2),
new TablePoint(1.2, 2.3),
new Person("peter", "parker"),
new Person("bruce", "waytoolongname"),
new NamedPoint(-2.44, 3.1415, "alfred"));
TextTable.print(items);
}
private record TablePoint (double x, double y) implements TableRow {
@Override
public Map<String, String> getCellDescriptions() {
Map<String,String> tableRow = new HashMap<>();
tableRow.put("x", Double.toString(x));
tableRow.put("y", Double.toString(y));
return tableRow;
}
} | {
"domain": "codereview.stackexchange",
"id": 45595,
"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, object-oriented, unit-testing, ascii-art",
"url": null
} |
java, object-oriented, unit-testing, ascii-art
private record Person (String name, String familyName) implements TableRow {
@Override
public Map<String, String> getCellDescriptions() {
Map<String,String> tableRow = new HashMap<>();
tableRow.put("first name", name);
tableRow.put("family", familyName);
return tableRow;
}
}
private record NamedPoint (double x, double y, String name) implements TableRow {
@Override
public Map<String, String> getCellDescriptions() {
Map<String,String> tableRow = new HashMap<>();
tableRow.put("x", Double.toString(x));
tableRow.put("y", Double.toString(y));
tableRow.put("first name", name);
return tableRow;
}
}
}
output testcase
┌──────────┬─────┬──────┬──────────────┐
│first name│ x │ y │ family │
├──────────┼─────┼──────┼──────────────┤
│ │ 1.0 │ 2.0 │ │
├──────────┼─────┼──────┼──────────────┤
│ │ 1.2 │ 2.3 │ │
├──────────┼─────┼──────┼──────────────┤
│ peter │ │ │ parker │
├──────────┼─────┼──────┼──────────────┤
│ bruce │ │ │waytoolongname│
├──────────┼─────┼──────┼──────────────┤
│ alfred │-2.44│3.1415│ │
└──────────┴─────┴──────┴──────────────┙
my challenges so far:
i am having trouble with the TableRow interface, i am not sure if that would be the proper approach
i am also having trouble with my test cases, how am i supposed to test the output?
open/closed, how easy could one extend the utility to provide more functionallity (eg. sorted columns names, different fill-blanks-behaviour, or adding a number column)
how much sense makes the TextTable class? is this really helpful for simplified access (see tests) or just a middle man antipattern?
of course any feedback is welcome!
note:
this code is not yet optimized, since the amount of data should be read by humans | {
"domain": "codereview.stackexchange",
"id": 45595,
"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, object-oriented, unit-testing, ascii-art",
"url": null
} |
java, object-oriented, unit-testing, ascii-art
Answer: I'll start with: I mostly like what you've done.
TableRow I think can be fine as is given your example usage and even advantageous if you have more complicated classes you want to add TableRow to. Since you hide getting the rows behind a function, you have control over the lifetime and caching of the underlying map if building it is expensive.
If your current approach feels repetitive because these records are just going to be simple, you do have some options. An alternative might be making a factory class with static functions like private TableRow buildPerson(String name, String, familyName) which can put all that code in one place. In any scenario, you could also consider typedef'ing Map<String,String> to TableRow directly which is more favoring "composition over inheritance" when handling it.
Testing around this I think is straightforward giving your small public interface: Something that takes an object conforming to TableRow (which produces a Map) and gives back a list of strings.
In general, when thinking about where to test, I usually start very broadly and work my way in to what may be practical (sometimes these are the same). In your case, that would mean starting with matching the list of full-table text output itself. If you wanted to focus on output tokens, you have a pretty regular structure where you could write some helper code to parse the table rows and columns and look at the output tokens. I've seen for larger text outputs to have sample tables stored as text files and directly comparing the whole output. That's good for comparing against known snaphots. | {
"domain": "codereview.stackexchange",
"id": 45595,
"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, object-oriented, unit-testing, ascii-art",
"url": null
} |
java, object-oriented, unit-testing, ascii-art
Narrowing in on tests I'm not sure I would consider going past that boundary for functionality. This is nice because you leave yourself a lot of room for refactoring. I'd just make sure I cover enough cases where you have a variety of different inputs. You could make your existing test a bit more simple by just starting with one type (like just Person), then the other, and then both which would be a bit more robust than all at once.
I think for open/closed, you've done pretty well given a Map is very flexible for your case. You are going to break this and have to change or extend TextTableFormatter in its current form if you want stuff like sorting and numbered columns.
I'd consider making an abstract base class or interface exposing createTableRows and the abstract base class having your character definitions (this may also be good to pull out into it's only class/namespace that you can reference in to keep things cleaner) and other common code you identify. Once you have that interface or base to build around, you can make variations of TextTableFormatter like SortedTextTableFormatter maybe where the constructor takes in some sorting options so everyone can keep the same createTableRows signature. I'd have to stumble through concrete examples before I could comment on how reusing code via inheritance might be optimized, but I'm sure there's opportunities there.
Your TextTable class is effectively a collection of helper functions since everything is static. I tend to go pretty sparse on these since they can quickly turn into a junk drawer. Since you're only using them in the test, I would have just added them as private functions to the test class (or at least in a separate helper class in the tests directory) to keep them where they're used. If it's not production code and not intended to be used by whomever is consuming this package I'd avoid putting it with the stuff that is. | {
"domain": "codereview.stackexchange",
"id": 45595,
"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, object-oriented, unit-testing, ascii-art",
"url": null
} |
javascript, game, html, css, mathematics
Title: Sine function guessing cognitive app
Question: Please help with improving this application. It is a guessing game, for learning the values of the sine function, and boosting brain power in the process.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simplified Example with Buttons and Multiple of 15 Angles</title>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
}
canvas {
border: 1px solid black;
}
#angleDisplay {
display: none;
}
</style>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<button id="refreshButton">Refresh</button>
<button id="toggleButton">Toggle Angle Display</button>
<p id="angleDisplay"></p>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
function drawLine() {
const angle = randomMultipleOf15(0, 24) * 15;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(canvas.width / 2, canvas.height / 2);
ctx.lineTo(
canvas.width / 2 + (canvas.width / 3) * Math.cos(angle * Math.PI / 180),
canvas.height / 2 - (canvas.width / 3) * Math.sin(angle * Math.PI / 180)
);
ctx.strokeStyle = "#ff1ac6";
ctx.stroke();
return { angle, sine: Math.sin(angle * Math.PI / 180) };
}
function randomMultipleOf15(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const refreshButton = document.getElementById("refreshButton");
const toggleButton = document.getElementById("toggleButton");
const angleDisplay = document.getElementById("angleDisplay"); | {
"domain": "codereview.stackexchange",
"id": 45596,
"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": "javascript, game, html, css, mathematics",
"url": null
} |
javascript, game, html, css, mathematics
refreshButton.addEventListener("click", () => {
const result = drawLine();
angleDisplay.textContent = `Angle: ${result.angle} degrees, Sine: ${result.sine.toFixed(2)}`;
if (angleDisplay.style.display === "block") {
angleDisplay.style.display = "none";
toggleButton.textContent = "Toggle Angle Display";
}
});
toggleButton.addEventListener("click", () => {
if (angleDisplay.style.display === "none" || angleDisplay.style.display === "") {
angleDisplay.style.display = "block";
toggleButton.textContent = "Toggle Angle Display (Hidden)";
} else {
angleDisplay.style.display = "none";
toggleButton.textContent = "Toggle Angle Display";
}
});
// Initial draw and display
drawLine();
angleDisplay.textContent = `Angle: ${drawLine().angle} degrees, Sine: ${drawLine().sine.toFixed(2)}`;
</script>
</body>
</html>
Sample output
Answer: Following function is repetitive can be simplified:
toggleButton.addEventListener("click", () => {
if (angleDisplay.style.display === "none" || angleDisplay.style.display === "") {
angleDisplay.style.display = "block";
toggleButton.textContent = "Toggle Angle Display (Hidden)";
} else {
angleDisplay.style.display = "none";
toggleButton.textContent = "Toggle Angle Display";
}
});
For one you can use classList.toggle() to add or remove a class from an element depending if the element already has that class or not.
Then you can use classList.contains() to check if an element has a class or not. That you can use within a ternary conditional operator to add the (Hidden) text to the button or not:
const toggleButton = document.querySelector('button');
const angleDisplay = document.querySelector('main'); | {
"domain": "codereview.stackexchange",
"id": 45596,
"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": "javascript, game, html, css, mathematics",
"url": null
} |
javascript, game, html, css, mathematics
toggleButton.addEventListener('click', function() {
angleDisplay.classList.toggle('d-none');
toggleButton.textContent = `Toggle Angle Display ${angleDisplay.classList.contains('d-none') ? '' : '(Hidden)'}`;
})
.d-none {
display: none;
}
<main>Display</main>
<button>Toggle Angle Display (Hidden)</button> | {
"domain": "codereview.stackexchange",
"id": 45596,
"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": "javascript, game, html, css, mathematics",
"url": null
} |
python, python-3.x
Title: Magic 8 Ball program
Question: I was doing the Magic 8 Ball project (its task is to read a user's question and output a prediction) on Python and wrote the following code:
from random import choice
from time import sleep
list_of_predictions = [
"Undoubtedly", "It seems to me - yes", "It is not clear yet, try again", "Do not even think", "A foregone conclusion", "Most likely", "Ask later", "My answer is no",
"No doubt", "Good prospects", "Better not to tell", "According to my information - no", "You can be sure of this", "Yes", "Concentrate and ask again", "Very doubtful"
]
print('I am a magic ball, and I know the answer to any of your questions.')
sleep(1)
n = input("What is your name?\n")
print(f'Greetings, {n}.')
sleep(1)
def is_question(question):
return q[-1] == '?'
def is_valid_question(question):
return ('When' or 'How' or 'Where') not in q
again = 'yes'
while again == 'yes':
print('Enter a question, it must end with a question mark.')
q = input()
if is_question(q) and is_valid_question(q):
sleep(2)
print(choice(list_of_predictions))
elif not is_question(q):
print('You entered not a question!')
continue
else:
print('You have entered a question that cannot be answered "yes" or "no"!')
continue
sleep(1)
again = input('Are there any other questions?\n')
sleep(1)
a = input('Come back if they arise!\n')
The main feature of my program is that it checks if the user has entered a question, which can be answered "yes" or "no". It also works with small delays in time (for realism). What do you think about my project implementation?
Answer: I'd like to address how you handle the yes/no question controlling the loop.
The relevant sections of your code are:
again = 'yes'
while again == 'yes':
# [...]
again = input('Are there any other questions?\n')
# [...] | {
"domain": "codereview.stackexchange",
"id": 45597,
"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",
"url": null
} |
python, python-3.x
while again == 'yes':
# [...]
again = input('Are there any other questions?\n')
# [...]
Almost all user input are interpreted as "no". However, the user has no information that they are supposed to enter the exact string yes for a positive answer. It is common for command line programs to accept y or n as an input, but neither of these will be treated as a positive answer in your code. Same for Yes, YES (different capitalization), yes, yes (leading/trailing white space), yeah, yep (different words), while all of these answer are clearly positives.
Similarly, inputs that are neither positive nor negative will be interpreted as negative, while the issue may be a typo or a misunderstanding of the answer expected. In this case, the input should be discarded, extra information given to the user on why, and the question asked again.
This makes handling this input much more complex, but as asking yes/no questions is very common in CLI programs, if you write a function that handles this, you only need to write it once and you are then free to reuse it many more times in the future.
My take on it is:
def get_yes_no_input(prompt):
POSITIVE_VALUES = ['yes',
'y',
'yeah',
'yep',
'true',
'1']
NEGATIVE_VALUES = ['no',
'n',
'nope',
'false',
'0']
while True:
print(prompt)
val = input('> ').strip().lower()
if val in POSITIVE_VALUES:
return True
if val in NEGATIVE_VALUES:
return False
print('Invalid answer. Please answer yes or no.')
Some comments on my code: | {
"domain": "codereview.stackexchange",
"id": 45597,
"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",
"url": null
} |
python, python-3.x
Some comments on my code:
since the function is meant to be reusable, it takes the question text as an argument (prompt)
it returns a boolean value, as it can be handled differently according to the use case, and they are easier to work with than strings
it uses constant lists for positive and negative answer, from which you can easily add or remove values
the input is stripped to handle potential leading/trailing white space
the input is lowered to handle capitalization issues
if the input is neither positive or negative, it is rejected and information about the expected answer is given
Use in your code would be something like this:
again = True
while again:
# [...]
again = get_yes_no_input('Are there any other questions?')
# [...] | {
"domain": "codereview.stackexchange",
"id": 45597,
"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",
"url": null
} |
performance, c, formatting, timer, time
Title: This is a simple stopwatch cli application with a few options
Question: My goal of this when I started writing it was simply that it be able to record thousandths of a second in a very performant and accurate way. I'm not sure I have achieved the performance aspect of that though, and I am not sure how to check the accuracy. I haven't done a lot of C programming before, but I feel like there is a lot wrong with this code. One thing I noticed is that my CPU usage spikes if I leave this running in the VSCode terminal with it open, but drops down when the terminal is hidden. Maybe I need to print to the screen less often. And I have successfully built this on both macos and Linux, but I know little about portability. Anyway, the code.
Here is my header:
#ifndef STOPWATCH_H
#define STOPWATCH_H
#include <stdio.h>
void set_canonical_mode(int enable);
void print_time(FILE *fd);
void clear_output();
FILE *get_saved_time_file(char *mode);
void save_time();
void restore_time();
void add_one_second();
void subtract_one_second();
void reset_time();
void cleanup();
void sigint_handler(int sig);
void* input_thread();
void print_help(FILE *out);
void print_short_help(FILE *out);
#endif
And here is the main file:
#include "sw.h"
#include <getopt.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>
#define ONE_MILLION_NSEC 1000000
#define ONE_BILLION_NSEC 1000000000
#define NSEC_TO_SLEEP ONE_MILLION_NSEC
#define HIDE_CURSOR printf("\e[?25l")
#define SHOW_CURSOR printf("\e[?25h")
#define OVER_HOUR_TEMPLATE "%2d:%02d:%02d.%02d"
#define UNDER_HOUR_TEMPLATE "%02d:%02d.%02d"
int paused = 0;
const struct timespec sleepduration = {0, NSEC_TO_SLEEP};
struct timespec starttime;
struct timespec currenttime;
struct timespec elapsedtime;
struct timespec restored_time;
struct timespec resumedtime;
char endchar = '\r'; | {
"domain": "codereview.stackexchange",
"id": 45598,
"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": "performance, c, formatting, timer, time",
"url": null
} |
performance, c, formatting, timer, time
char endchar = '\r';
int rflag = 0;
int sflag = 0;
int xflag = 0;
int pflag = 0;
int aflag = 0;
static char *program_name;
void set_raw_mode(int enable) {
struct termios term_settings;
tcgetattr(STDIN_FILENO, &term_settings);
if (enable) {
term_settings.c_lflag &= ~(ICANON | ECHO);
} else {
system("stty sane");
}
tcsetattr(STDIN_FILENO, TCSANOW, &term_settings);
}
void print_time(FILE *fd) {
if (elapsedtime.tv_sec < 3600) {
fprintf(fd, UNDER_HOUR_TEMPLATE, (int)(elapsedtime.tv_sec / 60),
(int)(elapsedtime.tv_sec % 60),
(int)(elapsedtime.tv_nsec / 10000000));
} else {
fprintf(fd, OVER_HOUR_TEMPLATE, (int)(elapsedtime.tv_sec / 3600),
(int)(elapsedtime.tv_sec % 3600 / 60),
(int)(elapsedtime.tv_sec % 60),
(int)(elapsedtime.tv_nsec / 10000000));
}
fprintf(fd, "%c", endchar);
fflush(stdout);
}
void pause_timer() {
paused = 1;
clock_gettime(CLOCK_MONOTONIC, ¤ttime);
if (xflag) {
cleanup();
exit(0);
}
}
void resume_timer() {
paused = 0;
clock_gettime(CLOCK_MONOTONIC, &resumedtime);
starttime.tv_sec += resumedtime.tv_sec - currenttime.tv_sec;
starttime.tv_nsec += resumedtime.tv_nsec - currenttime.tv_nsec;
if (starttime.tv_nsec < 0) {
starttime.tv_nsec += ONE_BILLION_NSEC;
--starttime.tv_sec;
} else if (starttime.tv_nsec >= ONE_BILLION_NSEC) {
starttime.tv_nsec -= ONE_BILLION_NSEC;
++starttime.tv_sec;
}
}
void clear_output() {
printf("\r");
fflush(stdout);
} | {
"domain": "codereview.stackexchange",
"id": 45598,
"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": "performance, c, formatting, timer, time",
"url": null
} |
performance, c, formatting, timer, time
void clear_output() {
printf("\r");
fflush(stdout);
}
FILE *get_saved_time_file(char *mode) {
FILE *savedtimef = NULL;
char file[256];
char *homedirectory = getenv("HOME");
if (homedirectory != NULL) {
strncpy(file, getenv("HOME"), 255);
file[255] = '\0';
strcat(file, "/.sw");
struct stat sb;
if (stat(file, &sb) == 0 && S_ISDIR(sb.st_mode)) {
strcat(file, "/savedtime");
savedtimef = fopen(file, mode);
} else if (strncmp(mode, "w", 1) == 0) {
mkdir(file, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
strcat(file, "/savedtime");
savedtimef = fopen(file, mode);
}
}
return savedtimef;
}
void save_time() {
FILE *savedtimef = get_saved_time_file("w");
if (savedtimef == NULL) {
perror("Could not save to file");
exit(1);
}
print_time(savedtimef);
}
void restore_time() {
int hours = 0;
int minutes = 0;
int seconds = 0;
int centiseconds = 0;
FILE *savedtimef = get_saved_time_file("r");
if (savedtimef == NULL) {
restored_time.tv_sec = 0;
restored_time.tv_nsec = 0;
return;
}
int bufsize = 32;
char *buf = malloc(bufsize * sizeof(char));
if (buf == NULL) {
perror("Could not allocate memory to restore previous time.\n");
}
memset(buf, 0, bufsize);
fgets(buf, bufsize, savedtimef);
if (strlen(buf) < 9) {
perror("Restore file unparsable.");
} else if (strlen(buf) == 9) {
sscanf(buf, UNDER_HOUR_TEMPLATE, &minutes, &seconds, ¢iseconds);
restored_time.tv_sec = (minutes * 60) + seconds;
restored_time.tv_nsec = (centiseconds * 10000000);
} else {
sscanf(buf, OVER_HOUR_TEMPLATE, &hours, &minutes, &seconds, ¢iseconds);
restored_time.tv_sec = (hours * 60 * 60) + (minutes * 60) + seconds;
restored_time.tv_nsec = (centiseconds * 10000000);
}
free(buf); | {
"domain": "codereview.stackexchange",
"id": 45598,
"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": "performance, c, formatting, timer, time",
"url": null
} |
performance, c, formatting, timer, time
starttime.tv_sec -= restored_time.tv_sec;
starttime.tv_nsec -= restored_time.tv_nsec;
if (starttime.tv_nsec < 0) {
starttime.tv_nsec += ONE_BILLION_NSEC;
--starttime.tv_sec;
}
clock_gettime(CLOCK_MONOTONIC, ¤ttime);
elapsedtime.tv_sec = currenttime.tv_sec - starttime.tv_sec;
elapsedtime.tv_nsec = currenttime.tv_nsec - starttime.tv_nsec;
if (elapsedtime.tv_nsec < 0) {
elapsedtime.tv_nsec += ONE_BILLION_NSEC;
--elapsedtime.tv_sec;
}
}
void add_one_second() {
starttime.tv_sec -= 1;
if (paused) {
elapsedtime.tv_sec = currenttime.tv_sec - starttime.tv_sec;
elapsedtime.tv_nsec = currenttime.tv_nsec - starttime.tv_nsec;
if (elapsedtime.tv_nsec < 0) {
elapsedtime.tv_nsec += ONE_BILLION_NSEC;
--elapsedtime.tv_sec;
}
print_time(stdout);
}
}
void subtract_one_second() {
starttime.tv_sec += 1;
if (starttime.tv_sec > currenttime.tv_sec ||
(starttime.tv_sec == currenttime.tv_sec &&
starttime.tv_nsec > currenttime.tv_nsec)) {
starttime.tv_sec = currenttime.tv_sec;
starttime.tv_nsec = currenttime.tv_nsec;
}
if (paused) {
elapsedtime.tv_sec = currenttime.tv_sec - starttime.tv_sec;
elapsedtime.tv_nsec = currenttime.tv_nsec - starttime.tv_nsec;
if (elapsedtime.tv_nsec < 0) {
elapsedtime.tv_nsec += ONE_BILLION_NSEC;
--elapsedtime.tv_sec;
}
print_time(stdout);
}
}
void reset_time() {
clock_gettime(CLOCK_MONOTONIC, &starttime);
if (paused) {
clock_gettime(CLOCK_MONOTONIC, ¤ttime);
elapsedtime.tv_sec = 0;
elapsedtime.tv_nsec = 0;
print_time(stdout);
}
}
void cleanup() {
paused = 1;
endchar = '\n';
clear_output();
print_time(stdout);
SHOW_CURSOR;
set_raw_mode(0);
if (sflag) {
save_time();
}
}
void sigint_handler(int sig) {
cleanup();
exit(sig);
} | {
"domain": "codereview.stackexchange",
"id": 45598,
"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": "performance, c, formatting, timer, time",
"url": null
} |
performance, c, formatting, timer, time
void sigint_handler(int sig) {
cleanup();
exit(sig);
}
void get_input() {
fd_set read_fds;
struct timeval timeout;
FD_ZERO(&read_fds);
FD_SET(STDIN_FILENO, &read_fds);
timeout.tv_sec = 0;
timeout.tv_usec = 1000; // Check every 1ms
if (select(STDIN_FILENO + 1, &read_fds, NULL, NULL, &timeout) == 1) {
char c;
read(STDIN_FILENO, &c, 1);
if (aflag) {
if (pflag) {
if (c == ' ') {
pflag = !pflag;
}
} else {
// exit upon any keypress
cleanup();
exit(0);
}
}
switch (c) {
case ' ':
// pause or resume stopwatch
if (paused)
resume_timer();
else
pause_timer();
break;
case 's':
save_time();
break;
case 'r':
reset_time();
break;
case '+':
add_one_second();
break;
case '-':
subtract_one_second();
break;
case 'q':
// quit
cleanup();
exit(0);
break;
default:
break;
}
}
}
void print_short_help(FILE *out) {
fprintf(out, "Usage: %s [-hsrxpa]\n", program_name);
}
void print_help(FILE *out) {
print_short_help(stdout);
fprintf(out, "\nOptions:\n");
fprintf(out, " -h, --help Show this help message and exit.\n");
fprintf(out, " -s, --save Save the final time to ~/.sw/savedtime\n");
fprintf(out, " -r, --restore Restore time from ~/.sw/savedtime\n");
fprintf(out, " -x, --exit Exit instead of pausing.\n");
fprintf(out, " -p, --paused Start in paused state.\n");
fprintf(out, " -a, --anykey Exit upon any keypress. With -p, will exit "
"upon any keypress after unpausing.\n"); | {
"domain": "codereview.stackexchange",
"id": 45598,
"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": "performance, c, formatting, timer, time",
"url": null
} |
performance, c, formatting, timer, time
fprintf(out, "\nControls:\n");
fprintf(out, " Space Pause or resume the stopwatch.\n");
fprintf(out, " s Save the current time to ~/.sw/savedtime.\n");
fprintf(out, " + Add one second to the time.\n");
fprintf(out, " - Subtract one second from the time.\n");
fprintf(out, " r Reset the stopwatch to zero.\n");
fprintf(out, " q Quit.\n");
}
int main(int argc, char *argv[]) {
signal(SIGINT, sigint_handler);
signal(SIGTERM, sigint_handler);
program_name = argv[0];
static struct option long_options[] = {
{"help", no_argument, 0, 'h'}, {"save", no_argument, 0, 's'},
{"restore", no_argument, 0, 'r'}, {"exit", no_argument, 0, 'x'},
{"paused", no_argument, 0, 'p'}, {"anykey", no_argument, 0, 'a'},
};
int opt;
int option_index = 0;
while ((opt = getopt_long(argc, argv, "hsrxpa", long_options,
&option_index)) != -1) {
switch (opt) {
case 'h':
print_help(stdout);
exit(0);
case 's':
sflag = 1;
break;
case 'r':
rflag = 1;
break;
case 'x':
xflag = 1;
break;
case 'p':
pflag = 1;
break;
case 'a':
aflag = 1;
break;
case '?':
print_short_help(stderr);
break;
default:
exit(1);
}
}
set_raw_mode(1);
HIDE_CURSOR;
clock_gettime(CLOCK_MONOTONIC, &starttime);
if (rflag) {
restore_time();
}
if (pflag) {
pause_timer();
print_time(stdout);
while (paused) {
get_input();
nanosleep(&sleepduration, NULL);
}
} | {
"domain": "codereview.stackexchange",
"id": 45598,
"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": "performance, c, formatting, timer, time",
"url": null
} |
performance, c, formatting, timer, time
while (1) {
if (!paused) {
clock_gettime(CLOCK_MONOTONIC, ¤ttime);
elapsedtime.tv_sec = currenttime.tv_sec - starttime.tv_sec;
elapsedtime.tv_nsec = currenttime.tv_nsec - starttime.tv_nsec;
if (elapsedtime.tv_nsec < 0) {
elapsedtime.tv_nsec += ONE_BILLION_NSEC;
--elapsedtime.tv_sec;
}
print_time(stdout);
}
get_input();
nanosleep(&sleepduration, NULL);
}
return 0;
}
Here are also some future features I'd like to add. Would welcome advice on implementation:
option to specify timer precision
option to specify time formatting (e.g., "01:23" vs "1m23s" vs "1 minute 23 seconds".)
option to give filepath to save to/restore from (should this be done with pipes/redirection?)
option to start timer on keyUP. If you've ever used a rubik's cube mat, they being timing when you hand leaves the mat.
option to set laps, and have them be saved/restored from file as well.
Answer: Check the return value of library functions
From the man page:
signal() returns the previous value of the signal handler. On failure, it returns SIG_ERR, and errno is set to indicate the error.
Neither of the calls to signal() are checked in your application.
The calls to clock_gettime(), system() read(), mkdir(), and fgets() et cetera also go unchecked.
Note that there is another way of setting the terminal back to cooked mode instead of calling system().
Calling async-signal-unsafe functions in signal handlers is undefined behavior
fflush(), fprintf(), printf(), exit(), and system() are not safe to call in a signal handler according to both the ISO C and POSIX standards. See: signal-safety(7) — Linux manual page.
The behavior is also undefined if the signal handler refers to any object other than errno with static storage duration other than by assigning a value to an object declared as volatile sig_atomic_t. The variable paused is of type int.
argv[0] can be NULL
program_name = argv[0]; | {
"domain": "codereview.stackexchange",
"id": 45598,
"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": "performance, c, formatting, timer, time",
"url": null
} |
performance, c, formatting, timer, time
This is risky. One can easily pass in argv[0] as a null pointer with an exec() syscall. Add a check for it, else a subsequent null pointer dereference would invoke undefined behavior.
Use the bool type to denote a binary state
case 's':
sflag = 1;
break;
case 'r':
rflag = 1;
break;
Include stdbool.h for bool, true, and false. This is not required in C2X, as they are keywords.
#define C2X_PLACEHOLDER 202000L
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= C2X_PLACEHOLDER
/* Coast is clear. */
#else
#include <stdbool.h> /* bool, true, and false. */
#endif
You could also make a struct containing all these flags and pass it around as an argument instead of making all the flags global. I'd also suggest moving this input parsing to a separate function.
Furthermore, consider using EXIT_FAILURE and EXIT_SUCCESS from stdlib.h instead of non-standard exit codes.
In main(), exit(EXIT_SUCCESS) is equivalent to return EXIT_SUCCESS
I suggest eliding the calls to exit().
The call to strcat() might write to out-of-bounds memory
strncpy(file, getenv("HOME"), 255);
file[255] = '\0';
strcat(file, "/.sw");
You failed to verify whether the string returned by getenv() was less than 255 characters. The subsequent calls to strcat() have the same problem. You're inviting a buffer overflow attack. I suggest using strncat(), or using one of the better alternatives to strcat()/strncat() that POSIX might provide.
The subsequent call to strncmp():
else if (strncmp(mode, "w", 1) == 0
can simply be:
else if (mode[0] == 'w') | {
"domain": "codereview.stackexchange",
"id": 45598,
"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": "performance, c, formatting, timer, time",
"url": null
} |
performance, c, formatting, timer, time
can simply be:
else if (mode[0] == 'w')
You also don't need separate invocations of fopen() in each branch. Move the call to the last line of the function and eliminate the unused variable (return fopen(...)).
Prior to C2X, a function with empty parentheses as the argument-list specifies an argument that takes a variadic number of arguments, not zero
Specify void wherever you are using empty parentheses.
I also do not see what the point of stopwatch.h is. I'd just elide it.
Consecutive string literals are concatenated
You can replace the 16 calls to fprintf() in the help message with:
fprintf(out, "\nOptions:\n"
" -h, --help Show this help message and exit.\n"
" -s, --save Save the final time to ~/.sw/savedtime\n"
" -r, --restore Restore time from ~/.sw/savedtime\n"
" -x, --exit Exit instead of pausing.\n"
" -p, --paused Start in paused state.\n"
" -a, --anykey Exit upon any keypress. With -p, will exit upon any keypress after unpausing.\n"
"\nControls:\n"
" Space Pause or resume the stopwatch.\n"
" s Save the current time to ~/.sw/savedtime.\n"
" + Add one second to the time.\n"
" - Subtract one second from the time.\n"
" r Reset the stopwatch to zero.\n"
" q Quit.\n"); | {
"domain": "codereview.stackexchange",
"id": 45598,
"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": "performance, c, formatting, timer, time",
"url": null
} |
performance, c, formatting, timer, time
The identifier fd is conventionally used for a file descriptor, and not a FILE *
Consider using fp or stream. Additionally, the arguments that are not modified in the function should be const-qualified. If you're using C99 or higher, you should also be using the ptr[static 1] notation for pointers that are expected to be non-null.
Do not use dynamic allocation when a fixed-size array would suffice
In here:
int bufsize = 32;
char *buf = malloc(bufsize * sizeof(char));
if (buf == NULL) {
perror("Could not allocate memory to restore previous time.\n");
}
memset(buf, 0, bufsize);
The size of the buffer is already known, and there's no reason to call malloc() for it. Simply do:
#define BUFSIZE 32
char buf[BUFSIZE];
To zero-initialize it, which I don't believe has any value here:
char buf[BUFSIZE] = {0};
// Or in C2X, like C++:
char buf[BUFSIZE] = {};
And malloc()+memset() should really be calloc().
Also note that sizeof(char) is defined by the standard to be 1. So it can be safely elided.
Additionally, use an extra variable to avoid the two calls to strlen(). | {
"domain": "codereview.stackexchange",
"id": 45598,
"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": "performance, c, formatting, timer, time",
"url": null
} |
python, api, flask
Title: URL shortener using Flask
Question: from flask import Flask, request, jsonify
import hashlib
import random
import string
app = Flask(__name__)
url_mapping = {}
def generate_short_url(url):
hash_object = hashlib.md5(url.encode())
return hash_object.hexdigest()[:6] # Shortened URL is the first 6 characters of the MD5 hash
def is_short_url_unique(short_url):
return short_url not in url_mapping
def generate_random_string(length):
characters = string.ascii_letters + string.digits
return ''.join(random.choice(characters) for i in range(length))
def generate_unique_short_url(url):
while True:
short_url = generate_short_url(url)
if is_short_url_unique(short_url):
return short_url
@app.route('/shorten', methods=['POST'])
def shorten_url():
data = request.get_json()
if 'url' not in data:
return jsonify({"error": "URL is required"}), 400
original_url = data['url']
short_url = generate_unique_short_url(original_url)
url_mapping[short_url] = original_url
return jsonify({
"original_url": original_url,
"shortened_url": f"https://{request.host}/{short_url}"
})
@app.route('/<short_url>')
def redirect_to_original_url(short_url):
if short_url in url_mapping:
original_url = url_mapping[short_url]
return jsonify({"original_url": original_url}), 302
else:
return jsonify({"error": "Shortened URL not found"}), 404
if __name__ == '__main__':
app.run(debug=True)
This is a URL shortener API. I am wondering if the algorithm for generating the hash can be improved. | {
"domain": "codereview.stackexchange",
"id": 45599,
"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, api, flask",
"url": null
} |
python, api, flask
Answer: I do have a few comments:
Handling Non-Unique Digests
It's good that you recognize that digests such as MD5 are not guaranteed to be unique. But, although you have a function generate_random_string, it does not appear to be used anywhere. Instead, if you find that in calling generate_short_url you have generated a non-unique digest for the URL, you just re-call the same function with the same URL argument. How would this not loop indefinitely if you did get a digest collision?
Here is an idea of how you might modify generate_short_url:
def short_url_generator():
from itertools import product
url_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
for n in range(1, 6):
for short_url in product(url_chars, repeat=n):
yield ''.join(short_url)
it = short_url_generator()
def generate_unique_short_url():
return next(it)
The above generate_unique_short_url function will first generate 62 unique urls of length 1, then 62 unique URLs of length 2, etc. This also provides for the generation of not only more URLs, but shorter ones as well.
Encapsulate in a Class For Greater Reusability and Data Hiding
class UrlGenerator:
"""Generate unique shortened URLs."""
def __init__(self,
url_chars: str='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
):
def generate_short_url():
from itertools import product
n = 1
while True:
for short_url in product(url_chars, repeat=n):
yield ''.join(short_url)
n += 1
self._it = generate_short_url()
def next_url(self) -> str:
"""Return the next URL."""
return next(self._it)
url_generator = UrlGenerator()
def get_unique_short_url():
return url_generator.next_url() | {
"domain": "codereview.stackexchange",
"id": 45599,
"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, api, flask",
"url": null
} |
python, api, flask
url_generator = UrlGenerator()
def get_unique_short_url():
return url_generator.next_url()
Note that I have added both docstrings and type hinting and removed any limit in the length of the generated URL so that an infinite number of URLs can be generated.
Update: Saving The Generator's State with Random Shuffling
The one potential problem with the above implementation is that it uses generator functions and as such cannot be "pickled". Being able to save and restore the state of the URL generator becomes necessary if you have to restart an application that uses it. The following code, though a bit more complicated, allows the current state of the generator to be serialized.
This class generates each character in the URL using a separate, randomly shuffled version of the input url_chars string. This makes it more difficult to guess what the next URL generated will be.
...
import string
import random
...
class UrlGenerator:
"""Generate unique shortened URLs."""
def __init__(self,
*,
url_chars: str=(string.digits +
string.ascii_lowercase +
string.ascii_uppercase
),
min_length: int=1
):
"""The intializer:
url_chars: Character set to be used for generating the URLs.
min_length: The minimum length of the generated URL."""
self._url_chars = list(url_chars)
self._url_chars_list = []
for _ in range(min_length):
self._new_random_chars()
self._indices = [0] * min_length
def _new_random_chars(self) -> None:
"""Append the _urls_char_list with the url_chars randomly shuffled."""
lst = self._url_chars.copy()
random.shuffle(lst)
self._url_chars_list.append(''.join(lst))
def next_url(self) -> str:
"""Generate the next URL.""" | {
"domain": "codereview.stackexchange",
"id": 45599,
"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, api, flask",
"url": null
} |
python, api, flask
def next_url(self) -> str:
"""Generate the next URL."""
current_index_index = len(self._indices) - 1
while True:
current_index = self._indices[current_index_index]
if current_index < len(self._url_chars):
break
self._indices[current_index_index] = 0
current_index_index -= 1
if current_index_index < 0:
self._indices.append(0)
self._new_random_chars()
break
self._indices[current_index_index] += 1
url = ''.join(
self._url_chars_list[list_index][char_index]
for list_index, char_index in enumerate(self._indices)
)
self._indices[-1] += 1
return url
url_generator = UrlGenerator()
urls = [url_generator.next_url() for _ in range(62 * 3)]
print(urls)
Prints:
['F', 'X', 'm', 'G', 'B', 'u', 'E', 'J', 'a', 'v', 'y', '3', 'i', 'K', 'C', 'W', 'e', 'Z', 'N', '0', 't', 'o', 's', 'S', 'k', '4', 'x', 'Y', 'c', 'T', 'Q', 'j', 'n', 'l', 'D', 'P', 'w', 'R', 'L', 'p', 'q', 'd', '5', '2', 'g', '9', '6', '1', 'U', 'M', '8', 'V', 'f', 'O', 'z', 'b', 'r', 'h', 'H', 'A', 'I', '7', 'Fe', 'F6', 'FB', 'Fq', 'FC', 'FW', 'Fo', 'FA', 'FE', 'FR', 'FN', 'Fd', 'Fh', 'Fs', 'FF', 'FM', 'F3', 'FY', 'FG', 'Fk', 'F9', 'FV', 'FK', 'FT', 'F1', 'Fb', 'FX', 'Fj', 'FI', 'Fw', 'Fz', 'FH', 'Fc', 'Fa', 'Ff', 'Fx', 'FO', 'Fp', 'Fi', 'Fu', 'Fy', 'F4', 'F7', 'Fg', 'F2', 'FJ', 'FZ', 'FQ', 'FU', 'F5', 'Ft', 'F0', 'FP', 'F8', 'FD', 'Fm', 'Fr', 'FS', 'Fn', 'FL', 'Fv', 'Fl', 'Xe', 'X6', 'XB', 'Xq', 'XC', 'XW', 'Xo', 'XA', 'XE', 'XR', 'XN', 'Xd', 'Xh', 'Xs', 'XF', 'XM', 'X3', 'XY', 'XG', 'Xk', 'X9', 'XV', 'XK', 'XT', 'X1', 'Xb', 'XX', 'Xj', 'XI', 'Xw', 'Xz', 'XH', 'Xc', 'Xa', 'Xf', 'Xx', 'XO', 'Xp', 'Xi', 'Xu', 'Xy', 'X4', 'X7', 'Xg', 'X2', 'XJ', 'XZ', 'XQ', 'XU', 'X5', 'Xt', 'X0', 'XP', 'X8', 'XD', 'Xm', 'Xr', 'XS', 'Xn', 'XL', 'Xv', 'Xl'] | {
"domain": "codereview.stackexchange",
"id": 45599,
"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, api, flask",
"url": null
} |
powershell
Title: Intune Remediation script to uninstall 7-Zip
Question: I just wanted to have some advice on those remediation scripts; what do you think?
The idea is to detect every 7-Zip installed on the computer and search for those not up to date and uninstall them.
Got some Struggle with placing correctly the exits code used by Intune.
Detection Script:
$64bits = Get-ItemProperty HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\* | Where-Object DisplayName -match "7-Zip"
$32bits = Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Where-Object DisplayName -match "7-Zip"
if (!($64bits) -and !($32bits)){
Write-Host "7-Zip isnt detected at all"
exit 0
}
if ($64bits){
foreach ($soft in $64bits){
Write-Host "7-Zip(x64) ver:" $soft.DisplayVersion "detected"
if ($soft.DisplayVersion -lt "23.01"){
exit 1
}
}
}
else {
Write-Host "7-Zip(x64) isnt detected"
}
if ($32bits){
foreach ($soft in $32bits){
Write-Host "7-Zip(x86) ver:" $soft.DisplayVersion "detected"
if ($soft.DisplayVersion -lt "23.01"){
exit 1
}
}
}
else {
Write-Host "7-Zip(x86) isnt detected"
}
Remediation Script:
$64bits = Get-ItemProperty HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\* | Where-Object DisplayName -match "7-Zip"
if ($64bits){
foreach ($soft in $64bits){
if ($soft.DisplayVersion -lt "23.01"){
Write-host "Uninstall" $soft.DisplayName $soft.DisplayVersion
Start-Process $soft.UninstallString -ArgumentList "/S"
}
}
}
$32bits = Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Where-Object DisplayName -match "7-Zip"
if ($32bits){
foreach ($soft in $32bits){
if ($soft.DisplayVersion -lt "23.01" -or $soft.DisplayVersion -eq $null){
Write-Host "7-Zip(x86) ver:" $soft.DisplayVersion "detected" | {
"domain": "codereview.stackexchange",
"id": 45600,
"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": "powershell",
"url": null
} |
powershell
Start-Process $soft.UninstallString -ArgumentList "/S"
Write-host "Uninstall" $soft.DisplayName $soft.DisplayVersion
}
}
}
exit 0 | {
"domain": "codereview.stackexchange",
"id": 45600,
"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": "powershell",
"url": null
} |
powershell
Answer: Some quick and superficial comments:
Some constants like $64bits and $32bits should be defined once. It makes sense to put them in a separate file and include the file in your script.
Here is an example of how you could load (include) files residing in your script directory.
Better yet, create a Powershell module. The script could be much more versatile and be used for other programs as well. Then, consider using a parameter to pass the program name from the command line.
In a corporate environment, I think a group policy of some sort would be the chosen route for maintaining software on the workstations. I noticed that you mentioned Intune.
The software version is hardcoded multiple times. It shouldn't. This should be a parameter, because the value will change over time. You don't want to change your code every time there is an upgrade.
There is unneeded duplication, the loops for $64bits and $32bits are functionally identical. You just need one additional nested ForEach loop and you can reduce the size of the code by an half.
exit 0 isn't really needed, it is implicit.
But it would really make sense to check the exit code after running Start-Process (with -Wait), because the uninstalling could indeed fail.
I have noticed minor discrepancies in spelling like Write-Host vs Write-host, which makes me think that maybe you are not using an IDE (eg Visual Studio Code) at the moment, but a generic editor. If that is not the case I would recommend using an IDE + some plugins for code completion, formatting, syntax checking etc.
I have not tested this script, being on Linux at the moment. | {
"domain": "codereview.stackexchange",
"id": 45600,
"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": "powershell",
"url": null
} |
powershell
I have not tested this script, being on Linux at the moment.
I think there is one thing that is problematic, it is that you are uninstalling software that is not up to date, which is bound to cause loss of functionality and frustration among end users. The proper remediation should be to upgrade the software to the latest stable release, not remove it unless it is not in your approved list. Or unless you can guarantee that another mechanism (Intune?) is already taking care of that. | {
"domain": "codereview.stackexchange",
"id": 45600,
"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": "powershell",
"url": null
} |
verilog, fpga, hdl, object-detection, system-verilog
Title: Detect when X-axis inputs and Y-axis inputs go high
Question: I am working on a module named PinCoordinates that detects when X-axis and Y-axis inputs go high. This will be programmed onto an Altera MAX V CPLD. I am constructing a laser grid array that has a total of 50 lasers. There are 25 X-axis lasers and 25 for the y-axis. On the opposite end of the array, there are photodiodes. I hope to be able to detect objects passing through the grid and return the coordinates.
For the code, pins 1-25 represent X axis lasers, and 26-50 are for the Y-axis. The code is as follows:
module PinCoordinates(
input wire [49:0] pins, // 50 pins input
output reg [4:0] x_coordinate, // Output X coordinate pins (1-25)
output reg [4:0] y_coordinate, // Output Y coordinate pins (26-50)
output reg output_valid // Output indicating valid coordinates
);
integer i;
reg x_detected, y_detected; // Flags to indicate detection of X and Y coordinates
always @* begin
// Reset detection flags at the beginning of each evaluation
x_detected = 1'b0;
y_detected = 1'b0;
output_valid = 1'b0;
// Check for high X coordinate
for (i = 0; i < 25; i = i + 1) begin
if (pins[i] == 1'b1) begin
x_coordinate = i + 1; // X coordinate pin numbering starts from 1
x_detected = 1'b1; // Set X coordinate detection flag
end
end
// Check for high Y coordinate
for (i = 25; i < 50; i = i + 1) begin
if (pins[i] == 1'b1) begin
y_coordinate = i - 24; // Y coordinate pin numbering starts from 26
y_detected = 1'b1; // Set Y coordinate detection flag
end
end
// Output is valid only if both X and Y coordinates are detected
if (x_detected && y_detected) begin
output_valid = 1'b1;
end
end
endmodule | {
"domain": "codereview.stackexchange",
"id": 45601,
"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": "verilog, fpga, hdl, object-detection, system-verilog",
"url": null
} |
verilog, fpga, hdl, object-detection, system-verilog
endmodule
I understand that one of the upgrades that I could make to this code is to include a break after either an X-pin or Y-pin is discovered to be high; however, since Verilog doesn't support break statements, I'm not sure how to implement this. Any more ideas in what I should do to the code? Any assistance or criticism would be very welcome.
Answer: Overview
You've done a good job with the following:
Code layout and use of indentation
Using compact ANSI-style module ports
Using the compact implicit sensitivity list @*
Using descriptive names for the module and the signals
Using descriptive comments
Latches
Using always @* implies that you intend to describe purely combinational
logic, but it simulates as a latch, which is a type of sequential logic.
This code will infer latches when it is synthesized. You will likely get
warning messages about that when you try to synthesize it.
The reason it behaves like a latch is because some signals are not assigned
under all conditions. Specifically, x_coordinate is not assigned when
i is in the range 25 to 49. In this case, x_coordinate retains its state,
inferring a latch.
You should be able to easily observe this behavior in simulations by looking
at waveforms of the pins and x_coordinate signals.
One way to avoid the unintended latches is to initialize the signal in the
always block, as you did for x_detected. For example:
always @* begin
// Reset detection flags at the beginning of each evaluation
x_detected = 1'b0;
x_coordinate = 0;
y_coordinate will also infer latches.
Simpler
In Verilog, it is customary to omit explicitly comparing a 1-bit signal to 1.
For example:
if (pins[i] == 1'b1) begin
is more simply written as:
if (pins[i]) begin | {
"domain": "codereview.stackexchange",
"id": 45601,
"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": "verilog, fpga, hdl, object-detection, system-verilog",
"url": null
} |
verilog, fpga, hdl, object-detection, system-verilog
is more simply written as:
if (pins[i]) begin
This is a matter of preference, not functionality.
Partitioning
With small designs, it is common to add all code to a single always block
as you have done. However, as people start adding more logic, they sometimes
fall into the trap of cramming everything into the same block.
Generally, it is easier to understand code which is split into multiple
blocks based on functionality. For example, the X and Y logic are really
independent of each other and can easily be partitioned into separate blocks.
Here is what the X logic would look like:
always @* begin
// Reset detection flags at the beginning of each evaluation
x_detected = 1'b0;
x_coordinate = 0;
// Check for high X coordinate
for (i = 0; i < 25; i = i + 1) begin
if (pins[i]) begin
x_coordinate = i + 1; // X coordinate pin numbering starts from 1
x_detected = 1'b1; // Set X coordinate detection flag
end
end
end
There would be another always block for just the Y logic.
Since the valid signal depends on both X and Y, it would be outside of
both blocks. It can also be simplified by using a continuous assignment
instead of a procedural assignment (one inside an always block):
output output_valid // Output indicating valid coordinates
// ...
assign output_valid = (x_detected && y_detected);
Note that I removed the reg keyword from the output port declaration.
Another simplification is to factor the x_detected logic out of the block as well. You could use a "reduction-OR" operator to do a bitwise OR of pins 0 to 24. If any of the pins is set, then it is detected; otherwise, if all pins are 0, it is not detected:
wire x_detected = |pins[24:0]; | {
"domain": "codereview.stackexchange",
"id": 45601,
"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": "verilog, fpga, hdl, object-detection, system-verilog",
"url": null
} |
verilog, fpga, hdl, object-detection, system-verilog
The same could be done for Y.
SystemVerilog
SystemVerilog (SV) features were added to the language nearly 20 years ago, and
all tool chains support these features to some degree. Annoyingly,
many tools have these features disabled by default, which means you
may need enable the features with some sort of tool settings. Refer to
your simulation/synthesis documentation.
Using SV syntax has its advantages.
You can replace always @* with always_comb. Not only does it
convey the design intent better, but it also provides built-in checking
if your tool has the capability to do so.
Code can be simpler to understand using the terse int keyword and ++
operator in the for loop:
for (int i = 0; i < 25; i++) begin
This has the advantage of declaring the i variable closer to where it is
used.
The compact syntax, '0, can be used to set all bits of a signal to 0.
break
Verilog doesn't support break statements
SV does have a break keyword, but there is no need to use it here.
Here is the code with the suggestions above:
module PinCoordinates (
input wire [49:0] pins,
output reg [4:0] x_coordinate, // Output X coordinate pins (1-25)
output reg [4:0] y_coordinate, // Output Y coordinate pins (26-50)
output output_valid // Output indicating valid coordinates
);
// Flags to indicate detection of X and Y coordinates
wire x_detected = |pins[24:0];
wire y_detected = |pins[49:25];
assign output_valid = (x_detected && y_detected);
always_comb begin
// Reset at the beginning of each evaluation
x_coordinate = '0;
// Check for high X coordinate
for (int i = 0; i < 25; i++) begin
if (pins[i]) begin
x_coordinate = i + 1; // X coordinate pin numbering starts from 1
end
end
end
always_comb begin
// Reset at the beginning of each evaluation
y_coordinate = '0; | {
"domain": "codereview.stackexchange",
"id": 45601,
"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": "verilog, fpga, hdl, object-detection, system-verilog",
"url": null
} |
verilog, fpga, hdl, object-detection, system-verilog
always_comb begin
// Reset at the beginning of each evaluation
y_coordinate = '0;
// Check for high Y coordinate
for (int i = 25; i < 50; i++) begin
if (pins[i]) begin
y_coordinate = i + 1; // Y coordinate pin numbering starts from 1
end
end
end
endmodule | {
"domain": "codereview.stackexchange",
"id": 45601,
"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": "verilog, fpga, hdl, object-detection, system-verilog",
"url": null
} |
performance, beginner, sql, sqlite
Title: Improving efficiency of database searches under SQLite (SpatiaLite - QGIS)
Question: I'm new to SQL, but I've always heard that it's a very efficient way of searching databases. For the same task, in VBA I get a result in a few seconds for 1000 queries. In SQL it takes several minutes.
I've tried going back and forth between my databases and my code to try and improve the execution speed of my triggers, without success.
Here's how my project looks (I work on QGIS, with SpatiaLite (SQLite) layers):
I have SpatiaLite layers :
ESPECES_PT (point geometry layer) [Important fields : ESPECE ; COMPART ; REGION]
ESPECES_ATTRIBUTS (no geometry) [Important fields : ESPECE ; COMPART ; REGION]
When a name is entered in "ESPECE", the table ESPECES_ATTRIBUTS is updated with the same "ESPECE", "REGION" and "COMPART" (if it does not already exist) and triggers are executed to search in several databases, a list of information. *I use 2 layers because the 1rst one can contain multiple identical names (not the second one)
There are 2 kinds of databases
TAXREF_
BDC_ | {
"domain": "codereview.stackexchange",
"id": 45602,
"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": "performance, beginner, sql, sqlite",
"url": null
} |
performance, beginner, sql, sqlite
All these databases are fragmented into 7 "compartments" [TAXREF_FLORE ; TAXREF_ENTOMO ; TAXREF_MAMMIFERES ; etc.] [BDC_FLORE ; BDC_ENTOMO ; BDC_MAMMIFERES ; etc.]
According to the contents of REGION and COMPART, the value of ESPECE will be searched in different databases. [For example: If COMPART = 'Flore' and REGION = 'Occitanie' then ESPECE will be searched into TAXREF_FLORE and in BDC_FLORE (in BDC_, the query will then look for "REGION" to get the correspondances)
The picture after shows (with the utmost clarity) how it work:
[On table ESPECES_PT : ESPECE = 'Ophrys provincialis' ; REGION = 'Occitanie' ; COMPART = 'Flore'] [On table ESPECES_ATTRIBUTS : ESPECE = 'Ophrys provincialis' ; REGION = 'Occitanie' ; COMPART = 'Flore' ; NOM_SCIENT_VALIDE is updated to the current valid name]
[On ESPECES_ATTRIBUTS : the query is performed from TAXREF_FLORE AND BDC_FLORE where several data are retrieved (in yellow) according to the value in NOM_VALIDE (table TAXREF) and REGION (table BDC).
This process is quite long and I'm wondering if you would have some tips and improvement to propose in order to improve it.
Here are the different important triggers :
When I add features on table ESPECES_PT (more or less the same for updates)
CREATE TRIGGER A_insert_esp
AFTER INSERT ON ESPECES_PT
BEGIN
UPDATE ESPECES_PT
SET "COMPART" = COALESCE(ESPECES_PT.COMPART, (SELECT "COMPART" FROM ZONE_ETUDE_POLY), '[Voir Table ESPECES_ATTRIBUTS]'),
"REGION" = COALESCE(ESPECES_PT.REGION, (SELECT "REGION" FROM ZONE_ETUDE_POLY), '[Voir Table ESPECES_ATTRIBUTS]'),
"DATA_PROP" = (SELECT "Company" FROM C_copyright)
WHERE pkuid = NEW.pkuid; | {
"domain": "codereview.stackexchange",
"id": 45602,
"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": "performance, beginner, sql, sqlite",
"url": null
} |
performance, beginner, sql, sqlite
INSERT INTO ESPECES_ATTRIBUTS (ESPECE, Visibilite, ENJEU_SPE, IMPORT_ZE, ENJEU_ZE, COMPART, REGION)
SELECT DISTINCT
NEW.ESPECE,
NEW.Visibilite,
CASE
WHEN NEW.ENJEU_SPE LIKE '%1%' THEN 'Très fort'
WHEN NEW.ENJEU_SPE LIKE '%2%' THEN 'Fort'
WHEN NEW.ENJEU_SPE LIKE '%3%' THEN 'Modéré'
WHEN NEW.ENJEU_SPE LIKE '%4%' THEN 'Faible'
WHEN NEW.ENJEU_SPE LIKE '%5%' THEN 'Très faible'
WHEN NEW.ENJEU_SPE LIKE '%6%' THEN NULL
ELSE coalesce(NEW.ENJEU_SPE <> '[Voir Table ESPECES_ATTRIBUTS]',NULL)
END,
CASE
WHEN NEW.IMPORT_ZE LIKE '%1%' THEN 'Très fort'
WHEN NEW.IMPORT_ZE LIKE '%2%' THEN 'Fort'
WHEN NEW.IMPORT_ZE LIKE '%3%' THEN 'Modéré'
WHEN NEW.IMPORT_ZE LIKE '%4%' THEN 'Faible'
WHEN NEW.IMPORT_ZE LIKE '%5%' THEN 'Très faible'
WHEN NEW.IMPORT_ZE LIKE '%6%' THEN NULL
ELSE coalesce(NEW.IMPORT_ZE <> '[Voir Table ESPECES_ATTRIBUTS]',NULL)
END,
CASE
WHEN NEW.ENJEU_ZE LIKE '%1%' THEN 'Très fort'
WHEN NEW.ENJEU_ZE LIKE '%2%' THEN 'Fort'
WHEN NEW.ENJEU_ZE LIKE '%3%' THEN 'Modéré'
WHEN NEW.ENJEU_ZE LIKE '%4%' THEN 'Faible'
WHEN NEW.ENJEU_ZE LIKE '%5%' THEN 'Très faible'
WHEN NEW.ENJEU_ZE LIKE '%6%' THEN NULL
ELSE coalesce(NEW.ENJEU_ZE <> '[Voir Table ESPECES_ATTRIBUTS]',NULL)
END,
CASE
WHEN ESPECES_PT.COMPART <> '[Voir Table ESPECES_ATTRIBUTS]' AND ESPECES_PT.COMPART IS NOT NULL THEN ESPECES_PT.COMPART
END,
CASE
WHEN ESPECES_PT.REGION <> '[Voir Table ESPECES_ATTRIBUTS]' AND ESPECES_PT.REGION IS NOT NULL THEN ESPECES_PT.REGION
END
FROM ESPECES_PT
WHERE ESPECES_PT.pkuid = NEW.pkuid
AND NEW.ESPECE IS NOT NULL
AND NEW.ESPECE NOT IN (SELECT ESPECE FROM ESPECES_ATTRIBUTS); | {
"domain": "codereview.stackexchange",
"id": 45602,
"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": "performance, beginner, sql, sqlite",
"url": null
} |
performance, beginner, sql, sqlite
UPDATE ESPECES_ATTRIBUTS
SET NOM_SIMPLE = (
WITH RECURSIVE split(value, str) AS (
SELECT null, NEW.ESPECE || ' ' FROM ESPECES_ATTRIBUTS WHERE ESPECES_ATTRIBUTS.rowid = last_insert_rowid()
UNION ALL
SELECT substr(str, 0, instr(str, ' ')), substr(str, instr(str, ' ')+1) FROM split WHERE str != ''
)
SELECT
CASE
WHEN NEW.ESPECE LIKE '%var.%' OR NEW.ESPECE LIKE '%subsp.%' THEN
COALESCE((SELECT value || ' ' FROM split WHERE value IS NOT NULL LIMIT 1), '')
|| COALESCE((SELECT value || ' ' FROM split WHERE value IS NOT NULL LIMIT 1 OFFSET 1), '' )
|| COALESCE((SELECT value || ' ' FROM split WHERE value IS NOT NULL LIMIT 1 OFFSET 2), '')
|| TRIM(COALESCE((SELECT value || ' ' FROM split WHERE value IS NOT NULL LIMIT 1 OFFSET 3), ''))
ELSE
COALESCE((SELECT value || ' ' FROM split WHERE value IS NOT NULL LIMIT 1), '')
|| TRIM(COALESCE((SELECT value || ' ' FROM split WHERE value IS NOT NULL LIMIT 1 OFFSET 1), '' ))
END
)
WHERE ESPECES_ATTRIBUTS.rowid = last_insert_rowid(); | {
"domain": "codereview.stackexchange",
"id": 45602,
"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": "performance, beginner, sql, sqlite",
"url": null
} |
performance, beginner, sql, sqlite
UPDATE ESPECES_ATTRIBUTS
SET NOM_SCIENT_VALIDE =
CASE
WHEN ESPECES_ATTRIBUTS.COMPART = 'Flore' THEN
COALESCE(
(SELECT "NOM_VALIDE" FROM TAXREF_FLORE WHERE "NOM_VALIDE_SIMPLE" = ESPECES_ATTRIBUTS.NOM_SIMPLE),
CASE
WHEN (SELECT COUNT(*) FROM TAXREF_FLORE WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE) = 1 THEN (SELECT "NOM_VALIDE" FROM TAXREF_FLORE WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE)
WHEN (SELECT COUNT(*) FROM TAXREF_FLORE WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE) = 0 THEN 'Absent'
ELSE
'(Synonymes)'
END)
WHEN ESPECES_ATTRIBUTS.COMPART = 'Amphibiens' THEN
COALESCE(
(SELECT "NOM_VALIDE" FROM TAXREF_AMPHIBIENS WHERE "NOM_VALIDE_SIMPLE" = ESPECES_ATTRIBUTS.NOM_SIMPLE),
CASE
WHEN (SELECT COUNT(*) FROM TAXREF_AMPHIBIENS WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE) = 1 THEN (SELECT "NOM_VALIDE" FROM TAXREF_AMPHIBIENS WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE)
WHEN (SELECT COUNT(*) FROM TAXREF_AMPHIBIENS WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE) = 0 THEN 'Absent'
ELSE
'(Synonymes)'
END)
WHEN ESPECES_ATTRIBUTS.COMPART = 'Arthropodes' THEN
COALESCE(
(SELECT "NOM_VALIDE" FROM TAXREF_ENTOMO WHERE "NOM_VALIDE_SIMPLE" = ESPECES_ATTRIBUTS.NOM_SIMPLE),
CASE
WHEN (SELECT COUNT(*) FROM TAXREF_ENTOMO WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE) = 1 THEN (SELECT "NOM_VALIDE" FROM TAXREF_ENTOMO WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE)
WHEN (SELECT COUNT(*) FROM TAXREF_ENTOMO WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE) = 0 THEN 'Absent' | {
"domain": "codereview.stackexchange",
"id": 45602,
"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": "performance, beginner, sql, sqlite",
"url": null
} |
performance, beginner, sql, sqlite
ELSE
'(Synonymes)'
END)
WHEN ESPECES_ATTRIBUTS.COMPART = 'Avifaune' THEN
COALESCE(
(SELECT "NOM_VALIDE" FROM TAXREF_OISEAUX WHERE "NOM_VALIDE_SIMPLE" = ESPECES_ATTRIBUTS.NOM_SIMPLE),
CASE
WHEN (SELECT COUNT(*) FROM TAXREF_OISEAUX WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE) = 1 THEN (SELECT "NOM_VALIDE" FROM TAXREF_OISEAUX WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE)
WHEN (SELECT COUNT(*) FROM TAXREF_OISEAUX WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE) = 0 THEN 'Absent'
ELSE
'(Synonymes)'
END)
WHEN ESPECES_ATTRIBUTS.COMPART = 'Mammifères' THEN
COALESCE(
(SELECT "NOM_VALIDE" FROM TAXREF_MAMMIFERES WHERE "NOM_VALIDE_SIMPLE" = ESPECES_ATTRIBUTS.NOM_SIMPLE),
CASE
WHEN (SELECT COUNT(*) FROM TAXREF_MAMMIFERES WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE) = 1 THEN (SELECT "NOM_VALIDE" FROM TAXREF_MAMMIFERES WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE)
WHEN (SELECT COUNT(*) FROM TAXREF_MAMMIFERES WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE) = 0 THEN 'Absent'
ELSE
'(Synonymes)'
END)
WHEN ESPECES_ATTRIBUTS.COMPART = 'Poissons' THEN
COALESCE(
(SELECT "NOM_VALIDE" FROM TAXREF_POISSONS WHERE "NOM_VALIDE_SIMPLE" = ESPECES_ATTRIBUTS.NOM_SIMPLE),
CASE
WHEN (SELECT COUNT(*) FROM TAXREF_POISSONS WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE) = 1 THEN (SELECT "NOM_VALIDE" FROM TAXREF_POISSONS WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE) | {
"domain": "codereview.stackexchange",
"id": 45602,
"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": "performance, beginner, sql, sqlite",
"url": null
} |
performance, beginner, sql, sqlite
WHEN (SELECT COUNT(*) FROM TAXREF_POISSONS WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE) = 0 THEN 'Absent'
ELSE
'(Synonymes)'
END)
WHEN ESPECES_ATTRIBUTS.COMPART = 'Reptiles' THEN
COALESCE(
(SELECT "NOM_VALIDE" FROM TAXREF_REPTILES WHERE "NOM_VALIDE_SIMPLE" = ESPECES_ATTRIBUTS.NOM_SIMPLE),
CASE
WHEN (SELECT COUNT(*) FROM TAXREF_REPTILES WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE) = 1 THEN (SELECT "NOM_VALIDE" FROM TAXREF_REPTILES WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE)
WHEN (SELECT COUNT(*) FROM TAXREF_REPTILES WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE) = 0 THEN 'Absent'
ELSE
'(Synonymes)'
END)
ELSE 'Nouveau compartiment'
END
WHERE ESPECES_ATTRIBUTS.rowid = last_insert_rowid(); | {
"domain": "codereview.stackexchange",
"id": 45602,
"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": "performance, beginner, sql, sqlite",
"url": null
} |
performance, beginner, sql, sqlite
UPDATE ESPECES_ATTRIBUTS
SET "CHOIX_ESPECE" = 'Voir liste'
WHERE ESPECES_ATTRIBUTS.rowid = last_insert_rowid() AND NOM_SCIENT_VALIDE = '(Synonymes)';
INSERT INTO SYNONYMES (ID, ESPECE, NOM_SCIENT_VALIDE)
SELECT DISTINCT
EA.ID,
EA.ESPECE,
T.NOM_VALIDE
FROM ESPECES_ATTRIBUTS EA
JOIN TAXREF_FLORE T ON T.LB_NOM = EA.NOM_SIMPLE
WHERE EA.ID = last_insert_rowid()
AND EA.NOM_SCIENT_VALIDE = '(Synonymes)'
AND EA.COMPART IS NOT NULL
AND NOT EXISTS (
SELECT 1
FROM SYNONYMES S
WHERE S.ESPECE = EA.ESPECE
AND S.NOM_SCIENT_VALIDE = T.NOM_VALIDE
)
AND (
(EA.COMPART = 'Flore' AND EXISTS (SELECT 1 FROM TAXREF_FLORE WHERE LB_NOM = EA.NOM_SIMPLE))
OR (EA.COMPART = 'Amphibiens' AND EXISTS (SELECT 1 FROM TAXREF_AMPHIBIENS WHERE LB_NOM = EA.NOM_SIMPLE))
OR (EA.COMPART = 'Arthropodes' AND EXISTS (SELECT 1 FROM TAXREF_ENTOMO WHERE LB_NOM = EA.NOM_SIMPLE))
OR (EA.COMPART = 'Avifaune' AND EXISTS (SELECT 1 FROM TAXREF_OISEAUX WHERE LB_NOM = EA.NOM_SIMPLE))
OR (EA.COMPART = 'Mammifères' AND EXISTS (SELECT 1 FROM TAXREF_MAMMIFERES WHERE LB_NOM = EA.NOM_SIMPLE))
OR (EA.COMPART = 'Poissons' AND EXISTS (SELECT 1 FROM TAXREF_POISSONS WHERE LB_NOM = EA.NOM_SIMPLE))
OR (EA.COMPART = 'Reptiles' AND EXISTS (SELECT 1 FROM TAXREF_REPTILES WHERE LB_NOM = EA.NOM_SIMPLE))
);
END | {
"domain": "codereview.stackexchange",
"id": 45602,
"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": "performance, beginner, sql, sqlite",
"url": null
} |
performance, beginner, sql, sqlite
The code to update "ESPECE" into "NOM_SCIENT_VALIDE" (in table ESPECES_ATTRIBUTS)
CREATE TRIGGER B_update_nom_scient
AFTER UPDATE OF COMPART, REGION, ESPECE ON ESPECES_ATTRIBUTS
FOR EACH ROW
BEGIN
UPDATE ESPECES_ATTRIBUTS
SET NOM_SIMPLE = (
WITH RECURSIVE split(value, str) AS (
SELECT null, NEW.ESPECE || ' '
FROM ESPECES_ATTRIBUTS
WHERE ID = NEW.ID
UNION ALL
SELECT substr(str, 0, instr(str, ' ')), substr(str, instr(str, ' ')+1)
FROM split
WHERE str != ''
)
SELECT
CASE
WHEN NEW.ESPECE LIKE '%var.%' OR NEW.ESPECE LIKE '%subsp.%' THEN
COALESCE((SELECT value || ' ' FROM split WHERE value IS NOT NULL LIMIT 1), '') ||
COALESCE((SELECT value || ' ' FROM split WHERE value IS NOT NULL LIMIT 1 OFFSET 1), '' ) ||
COALESCE((SELECT value || ' ' FROM split WHERE value IS NOT NULL LIMIT 1 OFFSET 2), '') ||
TRIM(COALESCE((SELECT value || ' ' FROM split WHERE value IS NOT NULL LIMIT 1 OFFSET 3), ''))
ELSE
COALESCE((SELECT value || ' ' FROM split WHERE value IS NOT NULL LIMIT 1), '') ||
TRIM(COALESCE((SELECT value || ' ' FROM split WHERE value IS NOT NULL LIMIT 1 OFFSET 1), '' ))
END
)
WHERE ID = NEW.ID; | {
"domain": "codereview.stackexchange",
"id": 45602,
"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": "performance, beginner, sql, sqlite",
"url": null
} |
performance, beginner, sql, sqlite
UPDATE ESPECES_ATTRIBUTS
SET NOM_SCIENT_VALIDE =
CASE
WHEN ESPECES_ATTRIBUTS.COMPART = 'Flore' THEN
COALESCE(
(SELECT "NOM_VALIDE" FROM TAXREF_FLORE WHERE "NOM_VALIDE_SIMPLE" = ESPECES_ATTRIBUTS.NOM_SIMPLE),
CASE
WHEN (SELECT COUNT(*) FROM TAXREF_FLORE WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE) = 1 THEN (SELECT "NOM_VALIDE" FROM TAXREF_FLORE WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE)
WHEN (SELECT COUNT(*) FROM TAXREF_FLORE WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE) = 0 THEN 'Absent'
ELSE
'(Synonymes)'
END)
WHEN ESPECES_ATTRIBUTS.COMPART = 'Amphibiens' THEN
COALESCE(
(SELECT "NOM_VALIDE" FROM TAXREF_AMPHIBIENS WHERE "NOM_VALIDE_SIMPLE" = ESPECES_ATTRIBUTS.NOM_SIMPLE),
CASE
WHEN (SELECT COUNT(*) FROM TAXREF_AMPHIBIENS WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE) = 1 THEN (SELECT "NOM_VALIDE" FROM TAXREF_AMPHIBIENS WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE)
WHEN (SELECT COUNT(*) FROM TAXREF_AMPHIBIENS WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE) = 0 THEN 'Absent'
ELSE
'(Synonymes)'
END)
WHEN ESPECES_ATTRIBUTS.COMPART = 'Entomofaune' THEN
COALESCE(
(SELECT "NOM_VALIDE" FROM TAXREF_ENTOMO WHERE "NOM_VALIDE_SIMPLE" = ESPECES_ATTRIBUTS.NOM_SIMPLE),
CASE
WHEN (SELECT COUNT(*) FROM TAXREF_ENTOMO WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE) = 1 THEN (SELECT "NOM_VALIDE" FROM TAXREF_ENTOMO WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE) | {
"domain": "codereview.stackexchange",
"id": 45602,
"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": "performance, beginner, sql, sqlite",
"url": null
} |
performance, beginner, sql, sqlite
WHEN (SELECT COUNT(*) FROM TAXREF_ENTOMO WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE) = 0 THEN 'Absent'
ELSE
'(Synonymes)'
END)
WHEN ESPECES_ATTRIBUTS.COMPART = 'Oiseaux' THEN
COALESCE(
(SELECT "NOM_VALIDE" FROM TAXREF_OISEAUX WHERE "NOM_VALIDE_SIMPLE" = ESPECES_ATTRIBUTS.NOM_SIMPLE),
CASE
WHEN (SELECT COUNT(*) FROM TAXREF_OISEAUX WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE) = 1 THEN (SELECT "NOM_VALIDE" FROM TAXREF_OISEAUX WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE)
WHEN (SELECT COUNT(*) FROM TAXREF_OISEAUX WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE) = 0 THEN 'Absent'
ELSE
'(Synonymes)'
END)
WHEN ESPECES_ATTRIBUTS.COMPART = 'Mammifères' THEN
COALESCE(
(SELECT "NOM_VALIDE" FROM TAXREF_MAMMIFERES WHERE "NOM_VALIDE_SIMPLE" = ESPECES_ATTRIBUTS.NOM_SIMPLE),
CASE
WHEN (SELECT COUNT(*) FROM TAXREF_MAMMIFERES WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE) = 1 THEN (SELECT "NOM_VALIDE" FROM TAXREF_MAMMIFERES WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE)
WHEN (SELECT COUNT(*) FROM TAXREF_MAMMIFERES WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE) = 0 THEN 'Absent'
ELSE
'(Synonymes)'
END)
WHEN ESPECES_ATTRIBUTS.COMPART = 'Reptiles' THEN
COALESCE(
(SELECT "NOM_VALIDE" FROM TAXREF_REPTILES WHERE "NOM_VALIDE_SIMPLE" = ESPECES_ATTRIBUTS.NOM_SIMPLE),
CASE | {
"domain": "codereview.stackexchange",
"id": 45602,
"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": "performance, beginner, sql, sqlite",
"url": null
} |
performance, beginner, sql, sqlite
CASE
WHEN (SELECT COUNT(*) FROM TAXREF_REPTILES WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE) = 1 THEN (SELECT "NOM_VALIDE" FROM TAXREF_REPTILES WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE)
WHEN (SELECT COUNT(*) FROM TAXREF_REPTILES WHERE "LB_NOM" = ESPECES_ATTRIBUTS.NOM_SIMPLE) = 0 THEN 'Absent'
ELSE
'(Synonymes)'
END)
ELSE NULL
END | {
"domain": "codereview.stackexchange",
"id": 45602,
"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": "performance, beginner, sql, sqlite",
"url": null
} |
performance, beginner, sql, sqlite
WHERE ID = NEW.ID AND ESPECES_ATTRIBUTS.COMPART is not NULL;
END;
The code for searching the databases
CREATE TRIGGER B_update_spe_stat
AFTER UPDATE OF NOM_SCIENT_VALIDE ON ESPECES_ATTRIBUTS
FOR EACH ROW
BEGIN
UPDATE ESPECES_ATTRIBUTS
SET "CHOIX_ESPECE" = 'Voir liste'
WHERE ID = NEW.ID AND NOM_SCIENT_VALIDE = '(Synonymes)'; | {
"domain": "codereview.stackexchange",
"id": 45602,
"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": "performance, beginner, sql, sqlite",
"url": null
} |
performance, beginner, sql, sqlite
UPDATE ESPECES_ATTRIBUTS
SET
NOM_VERN =
CASE
WHEN "COMPART" = 'Flore' THEN (SELECT "NOM_VERN" FROM TAXREF_FLORE WHERE "NOM_VALIDE" = ESPECES_ATTRIBUTS.NOM_SCIENT_VALIDE)
WHEN "COMPART" = 'Amphibiens' THEN (SELECT "NOM_VERN" FROM TAXREF_AMPHIBIENS WHERE "NOM_VALIDE" = ESPECES_ATTRIBUTS.NOM_SCIENT_VALIDE)
WHEN "COMPART" = 'Entomofaune' THEN (SELECT "NOM_VERN" FROM TAXREF_ENTOMO WHERE "NOM_VALIDE" = ESPECES_ATTRIBUTS.NOM_SCIENT_VALIDE)
WHEN "COMPART" = 'Oiseaux' THEN (SELECT "NOM_VERN" FROM TAXREF_OISEAUX WHERE "NOM_VALIDE" = ESPECES_ATTRIBUTS.NOM_SCIENT_VALIDE)
WHEN "COMPART" = 'Mammifères' THEN (SELECT "NOM_VERN" FROM TAXREF_MAMMIFERES WHERE "NOM_VALIDE" = ESPECES_ATTRIBUTS.NOM_SCIENT_VALIDE)
WHEN "COMPART" = 'Reptiles' THEN (SELECT "NOM_VERN" FROM TAXREF_REPTILES WHERE "NOM_VALIDE" = ESPECES_ATTRIBUTS.NOM_SCIENT_VALIDE)
END,
(CHOROLOGIE, FLORAISON, HABIT_S, CARAC_ECO, INDIC_PHYTO, TYPE_BIOLOGIQUE, FORMATION_VEGETALE, ENJEU_paca, ZH, MESSICOLE) =
(SELECT
"CHOROLOGIE",
"floraison",
"HABITAT SIMPLE",
"CARACTERISATION_ECOLOGIQUE_(HABITAT_OPTIMAL)",
"INDICATION_PHYTOSOCIOLOGIQUE_CARACTERISTIQUE",
"TYPE_BIOLOGIQUE",
"FORMATION_VEGETALE",
"ENJEU PACA",
"Statut ZH",
"Statut messicole"
FROM TAXREF_FLORE
WHERE "COMPART" = 'Flore' AND "NOM_VALIDE" = ESPECES_ATTRIBUTS.NOM_SCIENT_VALIDE)
WHERE ID = NEW.ID; | {
"domain": "codereview.stackexchange",
"id": 45602,
"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": "performance, beginner, sql, sqlite",
"url": null
} |
performance, beginner, sql, sqlite
WHERE ID = NEW.ID;
INSERT INTO SYNONYMES (ID, ESPECE, NOM_SCIENT_VALIDE)
SELECT DISTINCT
EA.ID,
EA.ESPECE,
T.NOM_VALIDE
FROM
ESPECES_ATTRIBUTS EA
JOIN
TAXREF_FLORE T ON T.LB_NOM = EA.NOM_SIMPLE
WHERE
EA.ID = NEW.ID
AND EA.NOM_SCIENT_VALIDE = '(Synonymes)'
AND NOT EXISTS (
SELECT 1
FROM SYNONYMES S
WHERE S.ESPECE = EA.ESPECE AND S.NOM_SCIENT_VALIDE = T.NOM_VALIDE
)
AND (
(EA.COMPART = 'Flore' AND EXISTS (SELECT 1 FROM TAXREF_FLORE WHERE LB_NOM = EA.NOM_SIMPLE))
OR (EA.COMPART = 'Amphibiens' AND EXISTS (SELECT 1 FROM TAXREF_AMPHIBIENS WHERE LB_NOM = EA.NOM_SIMPLE))
OR (EA.COMPART = 'Arthropodes' AND EXISTS (SELECT 1 FROM TAXREF_ENTOMO WHERE LB_NOM = EA.NOM_SIMPLE))
OR (EA.COMPART = 'Avifaune' AND EXISTS (SELECT 1 FROM TAXREF_OISEAUX WHERE LB_NOM = EA.NOM_SIMPLE))
OR (EA.COMPART = 'Mammifères' AND EXISTS (SELECT 1 FROM TAXREF_MAMMIFERES WHERE LB_NOM = EA.NOM_SIMPLE))
OR (EA.COMPART = 'Reptiles' AND EXISTS (SELECT 1 FROM TAXREF_REPTILES WHERE LB_NOM = EA.NOM_SIMPLE))
); | {
"domain": "codereview.stackexchange",
"id": 45602,
"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": "performance, beginner, sql, sqlite",
"url": null
} |
performance, beginner, sql, sqlite
UPDATE ESPECES_ATTRIBUTS
SET PN =
CASE
WHEN COMPART = 'Flore' THEN (SELECT CODE_STATUT FROM BDC_FLORE WHERE NOM_VALIDE_COMPLET = NOM_SCIENT_VALIDE AND CD_TYPE_STATUT = 'PN')
WHEN COMPART = 'Amphibiens' THEN (SELECT CODE_STATUT FROM BDC_AMPHIBIENS WHERE NOM_VALIDE_COMPLET = NOM_SCIENT_VALIDE AND CD_TYPE_STATUT = 'PN')
WHEN COMPART = 'Entomofaune' THEN (SELECT CODE_STATUT FROM BDC_ENTOMO WHERE NOM_VALIDE_COMPLET = NOM_SCIENT_VALIDE AND CD_TYPE_STATUT = 'PN')
WHEN COMPART = 'Oiseaux' THEN (SELECT CODE_STATUT FROM BDC_OISEAUX WHERE NOM_VALIDE_COMPLET = NOM_SCIENT_VALIDE AND CD_TYPE_STATUT = 'PN')
WHEN COMPART = 'Mammifères' THEN (SELECT CODE_STATUT FROM BDC_MAMMIFERES WHERE NOM_VALIDE_COMPLET = NOM_SCIENT_VALIDE AND CD_TYPE_STATUT = 'PN')
WHEN COMPART = 'Reptiles' THEN (SELECT CODE_STATUT FROM BDC_REPTILES WHERE NOM_VALIDE_COMPLET = NOM_SCIENT_VALIDE AND CD_TYPE_STATUT = 'PN')
ELSE NULL
END,
PR =
CASE
WHEN COMPART = 'Flore' THEN (SELECT CODE_STATUT FROM BDC_FLORE WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CORRESPONDANCE_REGION = NEW.REGION AND CD_TYPE_STATUT = 'PR')
WHEN COMPART = 'Amphibiens' THEN (SELECT CODE_STATUT FROM BDC_AMPHIBIENS WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CORRESPONDANCE_REGION = NEW.REGION AND CD_TYPE_STATUT = 'PR')
WHEN COMPART = 'Entomofaune' THEN (SELECT CODE_STATUT FROM BDC_ENTOMO WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CORRESPONDANCE_REGION = NEW.REGION AND CD_TYPE_STATUT = 'PR')
WHEN COMPART = 'Oiseaux' THEN (SELECT CODE_STATUT FROM BDC_OISEAUX WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CORRESPONDANCE_REGION = NEW.REGION AND CD_TYPE_STATUT = 'PR') | {
"domain": "codereview.stackexchange",
"id": 45602,
"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": "performance, beginner, sql, sqlite",
"url": null
} |
performance, beginner, sql, sqlite
WHEN COMPART = 'Mammifères' THEN (SELECT CODE_STATUT FROM BDC_MAMMIFERES WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CORRESPONDANCE_REGION = NEW.REGION AND CD_TYPE_STATUT = 'PR')
WHEN COMPART = 'Poissons' THEN (SELECT CODE_STATUT FROM BDC_POISSONS WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CORRESPONDANCE_REGION = NEW.REGION AND CD_TYPE_STATUT = 'PR')
WHEN COMPART = 'Reptiles' THEN (SELECT CODE_STATUT FROM BDC_REPTILES WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CORRESPONDANCE_REGION = NEW.REGION AND CD_TYPE_STATUT = 'PR')
ELSE NULL
END,
ListeRN =
CASE
WHEN COMPART = 'Flore' THEN (SELECT CODE_STATUT FROM BDC_FLORE WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CD_TYPE_STATUT = 'LRN')
WHEN COMPART = 'Amphibiens' THEN (SELECT CODE_STATUT FROM BDC_AMPHIBIENS WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CD_TYPE_STATUT = 'LRN')
WHEN COMPART = 'Entomofaune' THEN (SELECT CODE_STATUT FROM BDC_ENTOMO WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CD_TYPE_STATUT = 'LRN')
WHEN COMPART = 'Oiseaux' THEN (SELECT CODE_STATUT FROM BDC_OISEAUX WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CD_TYPE_STATUT = 'LRN')
WHEN COMPART = 'Mammifères' THEN (SELECT CODE_STATUT FROM BDC_MAMMIFERES WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CD_TYPE_STATUT = 'LRN')
WHEN COMPART = 'Poissons' THEN (SELECT CODE_STATUT FROM BDC_POISSONS WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CD_TYPE_STATUT = 'LRN')
WHEN COMPART = 'Reptiles' THEN (SELECT CODE_STATUT FROM BDC_REPTILES WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CD_TYPE_STATUT = 'LRN')
ELSE NULL
END,
ListeRR =
CASE | {
"domain": "codereview.stackexchange",
"id": 45602,
"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": "performance, beginner, sql, sqlite",
"url": null
} |
performance, beginner, sql, sqlite
ELSE NULL
END,
ListeRR =
CASE
WHEN COMPART = 'Flore' THEN (SELECT CODE_STATUT FROM BDC_FLORE WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CORRESPONDANCE_REGION = NEW.REGION AND CD_TYPE_STATUT = 'LRR')
WHEN COMPART = 'Amphibiens' THEN (SELECT CODE_STATUT FROM BDC_AMPHIBIENS WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CORRESPONDANCE_REGION = NEW.REGION AND CD_TYPE_STATUT = 'LRR')
WHEN COMPART = 'Entomofaune' THEN (SELECT CODE_STATUT FROM BDC_ENTOMO WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CORRESPONDANCE_REGION = NEW.REGION AND CD_TYPE_STATUT = 'LRR')
WHEN COMPART = 'Oiseaux' THEN (SELECT CODE_STATUT FROM BDC_OISEAUX WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CORRESPONDANCE_REGION = NEW.REGION AND CD_TYPE_STATUT = 'LRR')
WHEN COMPART = 'Mammifères' THEN (SELECT CODE_STATUT FROM BDC_MAMMIFERES WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CORRESPONDANCE_REGION = NEW.REGION AND CD_TYPE_STATUT = 'LRR')
WHEN COMPART = 'Poissons' THEN (SELECT CODE_STATUT FROM BDC_POISSONS WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CORRESPONDANCE_REGION = NEW.REGION AND CD_TYPE_STATUT = 'LRR')
WHEN COMPART = 'Reptiles' THEN (SELECT CODE_STATUT FROM BDC_REPTILES WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CORRESPONDANCE_REGION = NEW.REGION AND CD_TYPE_STATUT = 'LRR')
ELSE NULL
END,
ZNIEFF =
CASE
WHEN COMPART = 'Flore' THEN 'Déterminante ZNIEFF - ' || (SELECT CORRESPONDANCE_REGION FROM BDC_FLORE WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CORRESPONDANCE_REGION = NEW.REGION AND CD_TYPE_STATUT = 'ZDET')
WHEN COMPART = 'Amphibiens' THEN 'Déterminante ZNIEFF - ' || (SELECT CORRESPONDANCE_REGION FROM BDC_AMPHIBIENS WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CORRESPONDANCE_REGION = NEW.REGION AND CD_TYPE_STATUT = 'ZDET') | {
"domain": "codereview.stackexchange",
"id": 45602,
"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": "performance, beginner, sql, sqlite",
"url": null
} |
performance, beginner, sql, sqlite
WHEN COMPART = 'Entomofaune' THEN 'Déterminante ZNIEFF - ' || (SELECT CORRESPONDANCE_REGION FROM BDC_ENTOMO WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CORRESPONDANCE_REGION = NEW.REGION AND CD_TYPE_STATUT = 'ZDET')
WHEN COMPART = 'Oiseaux' THEN 'Déterminante ZNIEFF - ' || (SELECT CORRESPONDANCE_REGION FROM BDC_OISEAUX WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CORRESPONDANCE_REGION = NEW.REGION AND CD_TYPE_STATUT = 'ZDET')
WHEN COMPART = 'Mammifères' THEN 'Déterminante ZNIEFF - ' || (SELECT CORRESPONDANCE_REGION FROM BDC_MAMMIFERES WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CORRESPONDANCE_REGION = NEW.REGION AND CD_TYPE_STATUT = 'ZDET')
WHEN COMPART = 'Poissons' THEN 'Déterminante ZNIEFF - ' || (SELECT CORRESPONDANCE_REGION FROM BDC_POISSONS WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CORRESPONDANCE_REGION = NEW.REGION AND CD_TYPE_STATUT = 'ZDET')
WHEN COMPART = 'Reptiles' THEN 'Déterminante ZNIEFF - ' || (SELECT CORRESPONDANCE_REGION FROM BDC_REPTILES WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CORRESPONDANCE_REGION = NEW.REGION AND CD_TYPE_STATUT = 'ZDET')
ELSE NULL
END,
EXO_INV =
CASE
WHEN COMPART = 'Flore' THEN (SELECT STATUT_EXOTIQUE FROM BDC_FLORE WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CORRESPONDANCE_REGION = NEW.REGION)
WHEN COMPART = 'Amphibiens' THEN (SELECT CD_TYPE_STATUT FROM BDC_AMPHIBIENS WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CORRESPONDANCE_REGION = NEW.REGION AND (CD_TYPE_STATUT = 'REGLII' OR CD_TYPE_STATUT = 'REGLLUTTE'))
WHEN COMPART = 'Entomofaune' THEN (SELECT CD_TYPE_STATUT FROM BDC_ENTOMO WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CORRESPONDANCE_REGION = NEW.REGION AND (CD_TYPE_STATUT = 'REGLII' OR CD_TYPE_STATUT = 'REGLLUTTE')) | {
"domain": "codereview.stackexchange",
"id": 45602,
"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": "performance, beginner, sql, sqlite",
"url": null
} |
performance, beginner, sql, sqlite
WHEN COMPART = 'Oiseaux' THEN (SELECT CD_TYPE_STATUT FROM BDC_OISEAUX WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CORRESPONDANCE_REGION = NEW.REGION AND (CD_TYPE_STATUT = 'REGLII' OR CD_TYPE_STATUT = 'REGLLUTTE'))
WHEN COMPART = 'Mammifères' THEN (SELECT CD_TYPE_STATUT FROM BDC_MAMMIFERES WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CORRESPONDANCE_REGION = NEW.REGION AND (CD_TYPE_STATUT = 'REGLII' OR CD_TYPE_STATUT = 'REGLLUTTE'))
WHEN COMPART = 'Poissons' THEN (SELECT CD_TYPE_STATUT FROM BDC_POISSONS WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CORRESPONDANCE_REGION = NEW.REGION AND (CD_TYPE_STATUT = 'REGLII' OR CD_TYPE_STATUT = 'REGLLUTTE'))
WHEN COMPART = 'Reptiles' THEN (SELECT CD_TYPE_STATUT FROM BDC_REPTILES WHERE NOM_VALIDE_COMPLET = NEW.NOM_SCIENT_VALIDE AND CORRESPONDANCE_REGION = NEW.REGION AND (CD_TYPE_STATUT = 'REGLII' OR CD_TYPE_STATUT = 'REGLLUTTE'))
ELSE NULL
END
WHERE ESPECES_ATTRIBUTS.ID = NEW.ID;
END; | {
"domain": "codereview.stackexchange",
"id": 45602,
"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": "performance, beginner, sql, sqlite",
"url": null
} |
performance, beginner, sql, sqlite
EDIT1: EXPLAIN QUERY PLAN
To reply to the last message:
EXPLAIN SELECT * FROM ESPECES_PT WHERE ESPECE = 'Ophrys provincialis';
Returns :
EXPLAIN SELECT * FROM ESPECES_ATTRIBUTS WHERE ESPECE = 'Ophrys provincialis';
Returns
EXPLAIN QUERY PLAN SELECT * FROM ESPECES_PT WHERE ESPECE = 'Ophrys provincialis';
Answer: It took me some time because I had to reassess my approach and revisit my project from the ground up. Additionally, I had to overhaul the databases, which involved revising all the code for database creation
However, I now have a more streamlined database and have reorganized my triggers, allowing me to achieve the same results in around 5 seconds (and the code now accomplishes even more than before). I've identified further potential improvements for the future, but it is already quite good. | {
"domain": "codereview.stackexchange",
"id": 45602,
"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": "performance, beginner, sql, sqlite",
"url": null
} |
c
Title: C - Pattern To Initialize Values From Saved Data -- If It Exists | {
"domain": "codereview.stackexchange",
"id": 45603,
"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",
"url": null
} |
c
Question: Background
Here is an awkward pattern I've come up with to handle initializing the ID of an MPU for an embedded system based on the fairly unique factory self-test values stored in the MPU registers. (the MPU is the Inversense MPU-9250). The code will eventually be put on github/gitlab so the goal was to move all chip-unique configuration values to a separate source and header that the user can fill in (or leave with the pointer to the lookup set to 0 default).
If the user has saved self-test values to allow the individual chip to be ID'ed, then the ID is assigned and all other stored data that requires calibration by moving the chip through the full-range of all 3-axis can be applied from data provided in the source without having to go though the calibration sequence each time any program is run that uses the chip. (not really something that can be done reliably by simply moving the device in figure-eights, etc..) The additional saved configurations for gyro and accel axis-scale and magnetometer hard/soft iron corrections are done with simple functions and a switch (mpu->id) { ... }, just standard setup.
The source and header caldata.[ch] have the pattern I'm concerned with. The other two short sources are just additional source and header files that are involved in the calibration which have MCREs included below to demonstrate the actual program flow (and for comment if what is being done is ill-advised for some reason) The mpucaldata.c is just the MCRE for a driver to put it altogether and a Makefile is provided for convenience (with the command line option BLDOPT=-DCHECKNULL triggering the alternative test of a user with no saved self-test data.
Short Version | {
"domain": "codereview.stackexchange",
"id": 45603,
"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",
"url": null
} |
c
Short Version
The basic approach is to provide a lookup table of factory self-test values in caldata.c with the values exposed via a pointer that is provided extern in caldata.h. If the user has no data, the pointer is simply initialized 0. To provide the number of rows in the lookup table, the function get_mpu_st_list_sz() is simply used as a getter to make that available. Since this part of the configuration will occur early as part of startup and weaves in and out of several additional source files, I would like feedback on whether there may be a better way of doing this or if there is anything out of the ordinary in the approach. I can't see anything wrong with this approach, but sometimes you miss the forest for the trees.
The Code
The user data MCRE header:
#ifndef caldata_h
#define caldata_h 1 | {
"domain": "codereview.stackexchange",
"id": 45603,
"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",
"url": null
} |
c
#include <stdint.h>
/**
* pointer for extern of self-test data in header
*/
extern const uint8_t (*mpu_st_data)[6];
/**
* getter to provide size of mpu_st_list
*/
int get_mpu_st_list_sz (void);
#endif
source:
#include "caldata.h"
/**
* saved factory self-test values for each unique MPU chip.
* used as a fingerprint to ID which chip is attached allowing
* saved accel/gyro scale and magnetometer bias and scale values
* to be automatically applied from saved data avoiding repeated
* movement of MPU through the full range of all 3 axis on every
* program start.
*/
const uint8_t mpu_st_list[][6] = { { 93, 88, 115, 191, 198, 225 },
{ 104, 94, 122, 199, 207, 226 },
{ 94, 95, 120, 198, 215, 219 } };
/**
* pointer for extern of self-test data in header
* NOTE: must be initialize to data, as above, or
* set 0 (NULL) if no saved data exists so a check of
* if (mpu_st_data) validates the presence or absence
* of saved self-test values.
*/
#ifndef CHECKNULL
const uint8_t (*mpu_st_data)[6] = mpu_st_list;
#else
const uint8_t (*mpu_st_data)[6] = 0;
#endif
/**
* getter to provide size of mpu_st_list
*/
int get_mpu_st_list_sz (void)
{
return sizeof mpu_st_list / sizeof *mpu_st_list;
}
The main calibration MCRE header:
#ifndef calibrate_h
#define calibrate_h 1
#include "mpu.h"
#include "caldata.h"
/**
* compare mpu->self-test for current mpu to the self-test results
* in mpu_st_list. if matched, the self-test can serve as a
* fingerprint to set the mpu->id.
*/
uint8_t get_id_from_factory_st (mpu_t *mpu);
#endif
source:
#include "calibrate.h" | {
"domain": "codereview.stackexchange",
"id": 45603,
"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",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.