text stringlengths 1 2.12k | source dict |
|---|---|
json, go, mongodb
Title: Change interface depending on if statement
Question: I'm using fiber and mongodb. Field "field" is needed to obtain certain data to unload the load on the database. If field "field" is empty, then needs to output all the data from the database to make work easier to frontend. I don't like this crutch. Is there a much better solution?
func GetUserById(c *fiber.Ctx) error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
var userId = c.Params("userId")
defer cancel()
objId, _ := primitive.ObjectIDFromHex(userId)
// Creates options for search.
opts, err := search.GetOneOptions(c, models.UserModel{})
if err != nil {
return responses.Response(c, http.StatusBadRequest, err.Error())
}
if c.Query("field") != "" {
var user models.UserModelOmitempty
err = usersCollection.FindOne(ctx, bson.M{"_id": objId}, opts).Decode(&user)
if err != nil {
return responses.Response(c, http.StatusBadRequest, "user not found")
}
return responses.ResponseWithData(c, http.StatusOK, "success", user)
} else {
var user models.UserModel
err = usersCollection.FindOne(ctx, bson.M{"_id": objId}, opts).Decode(&user)
if err != nil {
return responses.Response(c, http.StatusBadRequest, "user not found")
}
return responses.ResponseWithData(c, http.StatusOK, "success", user)
}
} | {
"domain": "codereview.stackexchange",
"id": 43518,
"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": "json, go, mongodb",
"url": null
} |
json, go, mongodb
return responses.ResponseWithData(c, http.StatusOK, "success", user)
}
}
models.UserModel
type UserModel struct {
Id primitive.ObjectID `json:"id" bson:"_id" query:"string"`
Name string `json:"name" bson:"name" validate:"required" query:"string"`
Email string `json:"email" bson:"email" validate:"required" query:"string"`
Password string `json:"-" bson:"password" validate:"required"`
CreatedAt int64 `json:"createdAt" bson:"createdAt" query:"int"`
Rights string `json:"rights" bson:"rights" query:"string"`
PhotoUrl string `json:"photoUrl" bson:"photoUrl"`
Sex string `json:"sex" bson:"sex" query:"string"`
BirthDate int64 `json:"birthDate" bson:"birthDate" query:"int"`
Country string `json:"country" bson:"country" query:"string"`
EmailSubscribe bool `json:"emailSubscribe" bson:"emailSubscribe" query:"bool"`
AccountConfirmed bool `json:"accountConfirmed" bson:"accountConfirmed" query:"bool"`
} | {
"domain": "codereview.stackexchange",
"id": 43518,
"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": "json, go, mongodb",
"url": null
} |
json, go, mongodb
models.UserModelOmitempty
type UserModelOmitempty struct {
Id primitive.ObjectID `json:"id" bson:"_id" query:"string"`
Name string `json:"name,omitempty" bson:"name" validate:"required" query:"string"`
Email string `json:"email,omitempty" bson:"email" validate:"required" query:"string"`
Password string `json:"-" bson:"password" validate:"required"`
CreatedAt int64 `json:"createdAt,omitempty" bson:"createdAt" query:"int"`
Rights string `json:"rights,omitempty" bson:"rights" query:"string"`
PhotoUrl string `json:"photoUrl,omitempty" bson:"photoUrl"`
Sex string `json:"sex,omitempty" bson:"sex" query:"string"`
BirthDate int64 `json:"birthDate,omitempty" bson:"birthDate" query:"int"`
Country string `json:"country,omitempty" bson:"country" query:"string"`
EmailSubscribe bool `json:"emailSubscribe,omitempty" bson:"emailSubscribe" query:"bool"`
AccountConfirmed bool `json:"accountConfirmed,omitempty" bson:"accountConfirmed" query:"bool"`
}
Result in postman:
Answer: Since the types seem to be identical except for the JSON tags, you could use either models.UserModel or models.UserModelOmitempty for most of code, until the point where serialization comes into play, which will be when you call responses.Response(...) and then convert to the correct type:
var user
err = usersCollection.FindOne(ctx, bson.M{"_id": objId}, opts).Decode(&user)
if err != nil {
return responses.Response(c, http.StatusBadRequest, "user not found")
}
if c.Query("field") != "" {
// No field specified, so omitting empty fields
return responses.ResponseWithData(c, http.StatusOK, "success", models.UserModelOmitempty(user))
}
return responses.ResponseWithData(c, http.StatusOK, "success", user) | {
"domain": "codereview.stackexchange",
"id": 43518,
"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": "json, go, mongodb",
"url": null
} |
python, image
Title: Resize image, blur image and overlay image
Question: This code has the function of removing worthless borders from the original image and then:
Generate a 1080x1080 image (Instagram default) to be used as a
blurred background.
Generate an image with a width of 1080 and the height adjusted
accordingly to maintain the correct aspect ratio.
Superimpose 2. on the blurred background (1.)
I would like a review of the quality of the methods I used to reach the final result.
Original image example:
Code to Review:
from PIL import Image, ImageFilter, ImageChops
import numpy
import cv2
def remove_border(file_img):
im = Image.open(file_img)
bg = Image.new("RGB", im.size, im.getpixel((0,0)))
diff = ImageChops.difference(im.convert("RGB"), bg)
diff = ImageChops.add(diff, diff, 2.0, -30)
bbox = diff.getbbox()
if bbox:
return im.crop(bbox)
def resize_blur(img_blur,sizers):
img_blur = img_blur.resize(sizers, resample=Image.Resampling.LANCZOS)
img_blur = img_blur.filter(ImageFilter.GaussianBlur(10))
return img_blur
def resize_width_main(img_border,size_width):
img_width = img_border
basewidth = size_width
wpercent = (basewidth/float(img_width.size[0]))
hsize = int((float(img_width.size[1])*float(wpercent)))
img_width = img_width.resize((basewidth,hsize), Image.Resampling.LANCZOS)
return img_width
def center_overlay(name_file,overlay,background):
img = numpy.asarray(overlay)
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
h, w = img.shape[:2]
back = numpy.asarray(background)
back = cv2.cvtColor(back, cv2.COLOR_RGB2BGR)
hh, ww = back.shape[:2]
yoff = round((hh-h)/2)
xoff = round((ww-w)/2)
result = back.copy()
result[yoff:yoff+h, xoff:xoff+w] = img
cv2.imwrite(name_file, result) | {
"domain": "codereview.stackexchange",
"id": 43519,
"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, image",
"url": null
} |
python, image
def main():
img_border = remove_border('resized_download.png')
img_blur = resize_blur(img_border, (1080,1080))
img_width = resize_width_main(img_border, 1080)
center_overlay('resized.png', img_width, img_blur)
if __name__ == '__main__':
main()
Final image example:
Answer: After upgrading to Pillow 9.1.1: I still think your imports could use some love, because there's ambiguity between Image the submodule and Image the class. (PIL chose poorly when naming the submodule.)
By convention Numpy is imported by import numpy as np. However, I am going to suggest that you not drop down to Numpy or cv at all: instead stay in Pillow and use .paste().
Add PEP484 type hints.
I suggest that you decouple your processing methods from file I/O so that they only operate on in-memory images and arrays.
This:
if bbox:
return im.crop(bbox)
implicitly returns None if the condition is not met, but your upper code is not written to handle that. Either just drop the if and bear the consequences, or check if bbox is None and raise.
It's important for many of your function calls such as add() that you pass arguments by name, particularly for bare-literal numbers such as scale=2, offset=-30.
img_width = img_border is confusing. First of all it's an unneeded alias, and second of all it isn't a width: it's an image ("wide image", not "image width"). I would just remove this and use the original variable.
Float promotion is automatic, so this:
int((float(img_width.size[1])*float(wpercent)))
doesn't need the float() casts. You would benefit from tuple-unpacking the size here similar to what you do elsewhere.
Suggested
from PIL import ImageChops, ImageFilter
from PIL.Image import Image, Resampling
import PIL.Image | {
"domain": "codereview.stackexchange",
"id": 43519,
"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, image",
"url": null
} |
python, image
def remove_border(image: Image) -> Image:
bg = PIL.Image.new(mode="RGB", size=image.size, color=image.getpixel((0, 0)))
diff = ImageChops.difference(image, bg)
diff = ImageChops.add(image1=diff, image2=diff, scale=2, offset=-30)
bbox = diff.getbbox()
return image.crop(bbox)
def resize_blur(blur_img: Image, sizers: tuple[int, int]) -> Image:
return (
blur_img
.resize(sizers, resample=Resampling.LANCZOS)
.filter(ImageFilter.GaussianBlur(10))
)
def resize_width_main(border_img: Image, size_width: int) -> Image:
width, height = border_img.size[:2]
w_percent = size_width / width
h_size = round(height * w_percent)
return border_img.resize((size_width, h_size), Resampling.LANCZOS)
def center_overlay(overlay_img: Image, blur_img: Image) -> None:
box = [
round((xb - xo)/2)
for xb, xo in zip(blur_img.size, overlay_img.size)
][:2]
blur_img.paste(im=overlay_img, box=box)
def main() -> None:
image = PIL.Image.open('resized_download.png')
border_img = remove_border(image)
blur_img = resize_blur(border_img, (1080, 1080))
overlay_img = resize_width_main(border_img, 1080)
center_overlay(overlay_img, blur_img)
blur_img.save('resized.png')
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 43519,
"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, image",
"url": null
} |
javascript, beginner, event-handling, dom, animation
Title: Animating GIF on hover in Javascript
Question: I don't know JavaScript and it's safe to say this is my first code ever written in JS.
I just needed to animate my GIFs when user hovers over them only.
Googling separate concepts such as "string functions", "catch element mouse hover", "set element attribute", "get element attribute", "get elements by class", "var vs let" and so on, I came up with this:
var contentClass = document.getElementsByClassName("gifclass");
for(var i = 0; i < contentClass.length; i++)
{
let iElement = contentClass.item(i);
iElement.addEventListener("mouseenter", function(event)
{
const srcAtt = iElement.getAttribute('src');
let result = srcAtt.slice(0, srcAtt.length - 3);
iElement.setAttribute("src", result + 'gif');
}, false);
iElement.addEventListener("mouseleave", function(event)
{
const srcAtt = iElement.getAttribute('src');
let result = srcAtt.slice(0, srcAtt.length - 3);
iElement.setAttribute("src", result + 'png');
}, false);
}
}
Prerequisites:
You need to have a static version of the GIF that ends in png (I did that with MS Paint).
It works so long as the GIFs are within the same class
Example:
{
var contentClass = document.getElementsByClassName("gifclass");
for(var i = 0; i < contentClass.length; i++)
{
let iElement = contentClass.item(i);
iElement.addEventListener("mouseenter", function( event )
{
const srcAtt = iElement.getAttribute('src');
let result = srcAtt.slice(0, srcAtt.length - 3);
iElement.setAttribute("src", result + 'gif'); | {
"domain": "codereview.stackexchange",
"id": 43520,
"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, beginner, event-handling, dom, animation",
"url": null
} |
javascript, beginner, event-handling, dom, animation
}, false);
iElement.addEventListener("mouseleave", function( event )
{
const srcAtt = iElement.getAttribute('src');
let result = srcAtt.slice(0, srcAtt.length - 3);
iElement.setAttribute("src", result + 'png');
}, false);
}
}
Hover me:
<img class="gifclass" src="https://gameeditor2.sirv.com/website/GIFs/game-mode.png" alt="" data-image-width="320" data-image-height="240">
All in all, my initial research on how to do that only pointed out examples where I had to do plenty of code for all of my 20+ GIFs and handle them separately.
It works, but considering that I don't know JS I was thinking it might be useful to share it for a review | {
"domain": "codereview.stackexchange",
"id": 43520,
"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, beginner, event-handling, dom, animation",
"url": null
} |
javascript, beginner, event-handling, dom, animation
Answer: You can swap out document.getElementsByClassName() with document.querySelectorAll(). One reason is that you can use a selector and not just classes. The other reason is that it returns a NodeList, a different kind of array-like structure that conveniently has a forEach() method which can replace your loop.
You can also replace function declarations function() {} with the shorter arrow functions () => {}. There are technical differences between the two. But in this case, we're just after making the function a bit more concise.
Element attributes often map to DOM object properties (with some exceptions). Because of this, you can just access/assign the value to the HTML attribute directly like an object property, no need to getAttribute() or setAttribute().
You can use Regular Expressions and string.replace() to find the extension of the src. RegEx is a more advanced topic, but it gives you a lot of power when it comes to string matching. In this case, we're looking for the extension of the image and RegEx conveniently has the $ symbol which denotes the end of the string.
Lastly, if you decide to use different paths for your pngs and gifs (i.e. more than just an extension swap), then consider using data attributes to hold your paths. You can then rewrite your JS to swap the src to one of two data attributes, one holding the png path and the other the gif path.
That said, your code could be as short as:
document.querySelectorAll('img.gif-class').forEach(element => {
element.addEventListener('mouseenter', event => {
element.src = element.src.replace(/\.png$/, '.gif')
})
element.addEventListener('mouseleave', event => {
element.src = element.src.replace(/\.gif$/, '.png')
})
}) | {
"domain": "codereview.stackexchange",
"id": 43520,
"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, beginner, event-handling, dom, animation",
"url": null
} |
c#, beginner, finance
Title: Parse the weekly menus of a German delivery service
Question: I am a C# beginner, and I wrote a program that parses the weekly menu of a German delivery service. It works fine and I think the code quality is okay. Can anyone with more experience than me review my code?
using HtmlAgilityPack;
namespace FMReader
{
internal class Program
{
static void Main(string[] args)
{
HtmlWeb htmlweb = new HtmlWeb();
var webpage = htmlweb.Load(@"https://bestellung.fm-teistungen.de/de/menu/56/2022-06-20/2022-06-26/");
List<Menu> menus1OfTheWeek = new List<Menu>();
List<Menu> menus2OfTheWeek = new List<Menu>();
List<string> weekdays = new List<string>() { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };
foreach (var menu1 in webpage.DocumentNode.SelectNodes("//td[@mealid='11']"))
{
var currentMenuAsString = menu1.InnerText.Trim();
Menu currentMenu = new Menu() { Description = currentMenuAsString, MenuType = MenuType.Menu1, Price = 1.5 };
menus1OfTheWeek.Add(currentMenu);
}
foreach (var menu2 in webpage.DocumentNode.SelectNodes("//td[@mealid='12']"))
{
var currentMenuAsString = menu2.InnerText.Trim();
Menu currentMenu = new Menu() { Description = currentMenuAsString, MenuType = MenuType.Menu2, Price = 1.5 };
menus2OfTheWeek.Add(currentMenu);
}
foreach (var day in weekdays)
{
Console.WriteLine($"{day}");
var index = weekdays.IndexOf(day);
menus1OfTheWeek[index].PrintProperties();
menus2OfTheWeek[index].PrintProperties();
Console.WriteLine();
Console.WriteLine();
}
}
}
}
Related classes are:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; | {
"domain": "codereview.stackexchange",
"id": 43521,
"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#, beginner, finance",
"url": null
} |
c#, beginner, finance
namespace FMReader
{
public class Menu
{
public MenuType MenuType { get; set; }
public double Price { get; set; }
public string? Description { get; set; }
public void PrintProperties()
{
Console.WriteLine($"{Description} {Environment.NewLine} Price: {Price} EUR {Environment.NewLine} Menu: {MenuType}");
}
}
}
and
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FMReader
{
public enum MenuType
{
Menu1,
Menu2
}
}
Answer:
var webpage = htmlweb.Load(@"https://bestellung.fm-teistungen.de/de/menu/56/2022-06-20/2022-06-26/"); <- That will only works for this specific date. Try to figure out, how to make it more generic.
foreach (var menu1 in webpage.DocumentNode.SelectNodes("//td[@mealid='11']")) <- You are using "magic strings". Save the string in a const and give it a meaningful name.
foreach (var menu2 in webpage.DocumentNode.SelectNodes("//td[@mealid='12']")) <- same here
You're code is redudant. It does many things double. For example: 2 foreach loops with exact the same code.
2 times Console.WriteLine(); <- better: Console.WriteLine("\n");
PrintProperties() <- That's a bad name for a function. PrintMenuDescriptionWithPrice() would be more meaningful.
public string? Description { get; set; } <- Why is that not in the constructor, if it shouldn't be null?
If you print doubles, you should use padding.
Never ever use doubles or floats for currencies.
The price is again a magic number. Use allways const for constant numbers.
The keynames in MenuType are meaningless. How to figure out what is the difference between them? I have problems to understand why you use enum for the menus.
Why is weekdays a list? Did you plan to add some new weekdays? This would be a good enum. | {
"domain": "codereview.stackexchange",
"id": 43521,
"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#, beginner, finance",
"url": null
} |
haskell, hangman, monads
Title: Hangman game in Haskell, written using a state monad
Question: I recently made a simple hangman game in Haskell but soon wanted to explore the state monad, since it could possibly simplify the code. The result was this (see below), which is exactly 30% more lines than not using the monad. My question is therefore: am I using the feature correctly?
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# HLINT ignore "Eta reduce" #-}
{-# HLINT ignore "Use fmap" #-}
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
import Control.Monad (replicateM_, (>>))
import Control.Monad.State
import Data.Functor
import Data.List (elemIndices, sort)
import System.IO (BufferMode (NoBuffering), hFlush, hSetBuffering, stdin)
pictures :: Int
pictures = 9
data Phase = Continue | Win | Loss
instance Show Phase where
show Loss = "You lost!"
show Win = "You won!"
show _ = "Keep going!"
data GameVars = GameVars
{ word :: String,
rights :: [Char],
wrongs :: [Char],
lives :: Int
}
instance Show GameVars where
show g@GameVars {word, rights, wrongs, lives} = unlines [renderHangman g, renderLives g, renderWrongs g, renderWord g]
type GameState a = StateT GameVars IO a
main :: IO ()
main = do
w <- getWord
clearScreen
void $ execStateT hang (GameVars {word = w, rights = [], wrongs = [], lives = pictures})
hang :: GameState ()
hang = do
st <- get
lift $ print st
next >>= \case
Win -> announce Win
Loss -> announce Loss
Continue -> again
isLoss :: GameState Bool
isLoss = gets ((== 0) . lives)
announce :: Phase -> GameState ()
announce p = do
s <- get
let hangman = renderHangman s
lift clearScreen
lift $ putStrLn hangman
lift $ print p
lift $ putStrLn ("The correct word was " ++ word s ++ "\n") | {
"domain": "codereview.stackexchange",
"id": 43522,
"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": "haskell, hangman, monads",
"url": null
} |
haskell, hangman, monads
again :: GameState ()
again = do
guess <- lift getGuess
isCorrect <- correctGuess guess
lift clearScreen
st <- get
let st'
| guess `elem` (rights st ++ wrongs st) = st
| isCorrect = st {rights = guess : rights st}
| otherwise = st {wrongs = guess : wrongs st, lives = lives st - 1}
put st'
hang
next :: GameState Phase
next = do
w <- isWin
l <- isLoss
let n
| w = Win
| l = Loss
| otherwise = Continue
return n
isWin :: GameState Bool
isWin = get >>= \s -> return $ all (`elem` rights s) (word s)
win :: GameState ()
win = do
s <- get
put $ s {rights = word s}
clearScreen :: IO ()
clearScreen = replicateM_ 40 (putStrLn "")
correctGuess :: Char -> GameState Bool
correctGuess guess = get <&> ((guess `elem`) . word)
getGuess :: IO Char
getGuess = putStrLn "Guess a letter!" >> getChar
getWord :: IO String
getWord = clearScreen >> putStrLn "Give a secret word!" >> getLine
renderWord :: GameVars -> String
renderWord GameVars {word, rights} = map (\c -> if c `elem` rights then c else '_') word
renderWrongs :: GameVars -> String
renderWrongs GameVars {wrongs = []} = ""
renderWrongs GameVars {wrongs} = "Wrong guesses: " ++ sort wrongs
renderHangman :: GameVars -> String
renderHangman GameVars {lives} = unlines . hangmanpics $ lives
renderLives :: GameVars -> String
renderLives GameVars {lives} = show lives ++ " guesses left!" | {
"domain": "codereview.stackexchange",
"id": 43522,
"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": "haskell, hangman, monads",
"url": null
} |
haskell, hangman, monads
renderLives :: GameVars -> String
renderLives GameVars {lives} = show lives ++ " guesses left!"
hangmanpics :: Int -> [String]
hangmanpics 9 = [" ", " ", " ", " ", " ", " ", "========="]
hangmanpics 8 = [" ", " |", " |", " |", " |", " |", "========="]
hangmanpics 7 = [" +---+", " |", " |", " |", " |", " |", "========="]
hangmanpics 6 = [" +---+", " | |", " |", " |", " |", " |", "========="]
hangmanpics 5 = [" +---+", " | |", " O |", " |", " |", " |", "========="]
hangmanpics 4 = [" +---+", " | |", " O |", " | |", " |", " |", "========="]
hangmanpics 3 = [" +---+", " | |", " O |", " /| |", " |", " |", "========="]
hangmanpics 2 = [" +---+", " | |", " O |", " /|\\ |", " |", " |", "========="]
hangmanpics 1 = [" +---+", " | |", " O |", " /|\\ |", " / |", " |", "========="]
hangmanpics 0 = [" +---+", " | |", " O |", " /|\\ |", " / \\ |", " |", "========="]
hangmanpics _ = [" +---+", " | |", " O |", " /|\\ |", " / \\ |", " |", "========="]
Answer: The below is pretty casual, sorry it's not better organized or cited. | {
"domain": "codereview.stackexchange",
"id": 43522,
"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": "haskell, hangman, monads",
"url": null
} |
haskell, hangman, monads
You're not using the bound attribute values in instance Show GameVars.
Instead of void $ execStateT ..., just use evalStateT.
Your implementation of clearScreen is not really good UX design, but building good shell UX is outside the scope of a hangman game :)
Using >>= explicitly is often less readable than just using do. In hang it makes sense; in isWin a do would be better.
An instance of GameVars is the state of a game; that's ok. But an instance of GameState _ is not the state of a game; it's not even primarily a functor of such; it's a description of arbitrary behavior in the IO monad involving game state. I suggest renaming these.
You've broken out a lot of little functions into the top level namespace. This feels like clutter. If a thing fit's inline, put it inline until there's a reason to move it (it gets big enough or you want to share it across locations). The first place to move it is usually a where clause, so it's still clear what it's for when someone finds it. As an example, if we inline isWin and isLoss, the whole logic of next becomes clearer. (You don't have to like the way I got rid on n.) (yes, you will sometimes want to put something in the top namespace just to help you debug it, that's fine.)
you can often avoid using lift so much by leveraging the MonadIO class.
single-character variable names are ok when they are in some sense "fully general", it's kinda a haskell idiom to use them for stuff that's arbitrary vis a vis the function. When there's a reasonable word-sized name for a variable, use it.
With the current logic, you could leave lives out of the record, and just have lives gs = length (rights gs) + length (wrongs gs), but it'd make the whole thing more fragile than it needs to be.
win is unused. | {
"domain": "codereview.stackexchange",
"id": 43522,
"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": "haskell, hangman, monads",
"url": null
} |
haskell, hangman, monads
win is unused.
Using a Show instance to UI stuff is a normal mistake people make; Show is better reserved for debugging purposes, where the resulting string looks basically like the code that created the instance. For UI purposes it's better to have a dedicated function.
Finding a good abstraction and learning to use it is hard. I'm not super fond of monad transformers, but they're an appropriate choice for the task at hand. In this context, prefer gets over get and modify over put.
hangmanpics is going to be ugly no matter what you do, don't fight it.
Is the user supposed to have 9 lives, or 10? I may have an off-by-one mistake in my version. | {
"domain": "codereview.stackexchange",
"id": 43522,
"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": "haskell, hangman, monads",
"url": null
} |
haskell, hangman, monads
I need to go do actual work now, so let me know if anything in this version doesn't make sense. We should not assume it's "better".
{-# LANGUAGE NamedFieldPuns #-}
{-# HLINT ignore "Eta reduce" #-}
{-# HLINT ignore "Use fmap" #-}
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
module CR277633
( main
, hang
) where
import Control.Monad (replicateM_, (>>))
import Control.Monad.State
import Data.Functor
import Data.Function (on)
import Data.List (nub, sort)
import Data.Maybe (fromMaybe)
import System.IO (BufferMode (NoBuffering), hFlush, hSetBuffering, stdin)
data Phase = Continue | Win | Loss
data GameState = GameState
{ word :: String,
rights :: [Char],
wrongs :: [Char],
lives :: Int
}
type Gameplay a = StateT GameState IO a
printString :: (MonadIO m) => String -> m ()
printString = liftIO . putStrLn
main :: IO ()
main = do
clearScreen
printString "Give a secret word!"
secretWord <- liftIO getLine
clearScreen
evalStateT hang (GameState {word = secretWord,
rights = [],
wrongs = [],
lives = length hangmanpics})
hang :: Gameplay ()
hang = do
gamestate <- get
printString $ render gamestate
result <- next
handleNext result
where render GameState{word, rights, wrongs, lives} = unlines [ renderHangman lives
, show lives ++ " guesses left!"
, case wrongs of
[] -> ""
_ -> "Wrong guesses: " ++ sort wrongs
, mask rights <$> word
]
mask known secret = if secret `elem` known then secret else '_' | {
"domain": "codereview.stackexchange",
"id": 43522,
"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": "haskell, hangman, monads",
"url": null
} |
haskell, hangman, monads
next :: Gameplay Phase
next = do
gamestate <- get
let won = all (`elem` rights gamestate) (word gamestate)
lost = 0 == lives gamestate
return $ case () of
_ | won -> Win
_ | lost -> Loss
_ -> Continue
handleNext :: Phase -> Gameplay ()
handleNext Continue = do
printString "Guess a letter!"
guess <- liftIO getChar
clearScreen
rights' <- gets $ nub . (guess :) . rights
wrongs' <- gets $ nub . (guess :) . wrongs
lives' <- gets $ newLives guess
modify (\s -> s {rights = rights', wrongs = wrongs', lives = lives'})
hang
handleNext winLose = do
gamestate <- get
clearScreen
(printString . renderHangman) =<< gets lives
printString $ announcementFor winLose
(printString . ("The correct word was " ++)) =<< gets word
printString ""
announcementFor Loss = "You lost!"
announcementFor Win = "You won!"
announcementFor Continue = "Keep going!" -- unused
newLives guess GameState{word, rights, wrongs, lives}
| guess `elem` rights = lives
| guess `elem` wrongs = lives
| guess `elem` word = lives
| otherwise = lives - 1
clearScreen :: (MonadIO m) => m ()
clearScreen = replicateM_ 40 (printString "")
renderHangman :: Int -> String
renderHangman lives = if len <= lives then last pics else pics !! lives
where len = length hangmanpics
pics = reverse hangmanpics | {
"domain": "codereview.stackexchange",
"id": 43522,
"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": "haskell, hangman, monads",
"url": null
} |
haskell, hangman, monads
hangmanpics :: [String]
hangmanpics = [" \n\
\ \n\
\ \n\
\ \n\
\ \n\
\ \n\
\========="
," \n\
\ | \n\
\ | \n\
\ | \n\
\ | \n\
\ | \n\
\========="
," +---+ \n\
\ | \n\
\ | \n\
\ | \n\
\ | \n\
\ | \n\
\========="
," +---+ \n\
\ | | \n\
\ | \n\
\ | \n\
\ | \n\
\ | \n\
\========="
," +---+ \n\
\ | | \n\
\ O | \n\
\ | \n\
\ | \n\
\ | \n\
\========="
," +---+ \n\
\ | | \n\
\ O | \n\
\ | | \n\
\ | \n\
\ | \n\
\========="
," +---+ \n\
\ | | \n\
\ O | \n\
\ /| | \n\
\ | \n\
\ | \n\
\========="
," +---+ \n\
\ | | \n\
\ O | \n\
\ /|\\ | \n\
\ | \n\
\ | \n\
\========="
," +---+ \n\
\ | | \n\
\ O | \n\
\ /|\\ | \n\
\ / | \n\
\ | \n\
\========="
," +---+ \n\
\ | | \n\
\ O | \n\
\ /|\\ | \n\
\ / \\ | \n\ | {
"domain": "codereview.stackexchange",
"id": 43522,
"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": "haskell, hangman, monads",
"url": null
} |
haskell, hangman, monads
\ O | \n\
\ /|\\ | \n\
\ / \\ | \n\
\ | \n\
\========="
] | {
"domain": "codereview.stackexchange",
"id": 43522,
"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": "haskell, hangman, monads",
"url": null
} |
bash, openssl, automation, nginx
Title: bash script to setup a digitalocean webserver (apache2, nginx, PHP7.4, fastcgi, SSL)
Question: The following bash script is intended to be run on a freshly installed digitaloceans ubuntu 20.04 droplet by root in its home dir.
The purpose is to setup a ready to use webserver with SSL (certbot), PHP 7.4 support (fastcgi), an Apache2 fileserver and nginx as reverse proxy. DNS is managed by Cloudflare.
My main questions are if the settings for apache2, nginx and fastcgi are justifiable and if there are recommendations to improve the script.
#!/bin/bash
set -e # Terminate if script has error
####################################################################
# Variables used
####################################################################
sitedir=""
fqn=""
sdub=""
myip=""
cftoken=""
cfmail=""
webmail=""
servername=""
vhostserver=""
myip="$(curl ipecho.net/plain; echo)"
####################################################################
# Query for location
####################################################################
printf "
####################################################################
# Enter location on disk for site (Default: /var/www/\$fqn):
####################################################################\n
dir: "
read -rp "" sitedir
####################################################################
# Query for FQN
####################################################################
printf "
####################################################################
# Enter FQN for website:
####################################################################\n
fqn: "
read -rp "" fqn
####################################################################
# Query for subdomain
####################################################################
printf "
####################################################################
# Enter subdomain for FQN:
####################################################################\n
sub: "
read -rp "" sub | {
"domain": "codereview.stackexchange",
"id": 43523,
"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": "bash, openssl, automation, nginx",
"url": null
} |
bash, openssl, automation, nginx
####################################################################
# Query for webmaster mail address
####################################################################
printf "
####################################################################
# Enter webmaster mail address for site: (Default: webmaster@\$fqn)
####################################################################\n
webmaster: "
read -rp "" webmail
####################################################################
# Query non-root user credentials
####################################################################
printf "
####################################################################
# Enter CLOUDFLARE-TOKEN:
####################################################################\n
cftoken: "
read -rp "" cftoken
####################################################################
# Query non-root user credentials
####################################################################
printf "
####################################################################
# Enter CLOUDFLARE-mail:
####################################################################\n
cfmail: "
read -rp "" cfmail
####################################################################
# setting defaults
####################################################################
# sitedir
if [ -n "$sitedir" ]; then
if [ ${sitedir:+1} ]
then
echo "yes"
fi
else
sitedir="/var/www/$fqn"
fi
# webmaster mail
if [ -n "$webmail" ]; then
if [ ${webmail:+1} ]
then
echo "yes"
fi
else
webmail=webmaster@$fqn
fi
# servername
if [ -n "$sub" ]; then
servername="server_name $sub.$fqn www.$sub.$fqn;"
vhostserver="ServerName $sub.$fqn
ServerAlias www.$sub.$fqn"
else
servername="server_name $fqn www.$fqn;"
vhostserver="ServerName $fqn
ServerAlias www.$fqn"
fi | {
"domain": "codereview.stackexchange",
"id": 43523,
"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": "bash, openssl, automation, nginx",
"url": null
} |
bash, openssl, automation, nginx
####################################################################
# Enable basic firewall rules
####################################################################
ufw allow OpenSSH
ufw enable
####################################################################
# Install required software
####################################################################
apt update
apt -y upgrade
# EXA
wget -c http://old-releases.ubuntu.com/ubuntu/pool/universe/r/rust-exa/exa_0.9.0-4_amd64.deb
apt-get install ./exa_0.9.0-4_amd64.deb
# basics
apt -y install tree gnupg2 git net-tools original-awk fzf silversearcher-ag unzip pkg-config \
openssl apache2 php-fpm php-xml libtool
# fastcgi for apache2
wget https://mirrors.edge.kernel.org/ubuntu/pool/multiverse/liba/libapache-mod-fastcgi/libapache2-mod-fastcgi_2.4.7~0910052141-1.2_amd64.deb
dpkg -i libapache2-mod-fastcgi_2.4.7~0910052141-1.2_amd64.deb
####################################################################
# setup of apache2
####################################################################
# set apache listening on loopback for ipv4 only
mv /etc/apache2/ports.conf /etc/apache2/ports.conf.default
echo "Listen 0.0.0.0:8080" | tee /etc/apache2/ports.conf
# make working dir for server
mkdir -p $sitedir
# disable factory defaults
a2dissite 000-default
# configure apache for use of mod_fastcgi
a2enmod actions
a2enmod proxy_fcgi setenvif
systemctl restart apache2
a2enconf php7.4-fpm
systemctl reload apache2
# backup default fastcgi.conf
mv /etc/apache2/mods-enabled/fastcgi.conf /etc/apache2/mods-enabled/fastcgi.conf.default | {
"domain": "codereview.stackexchange",
"id": 43523,
"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": "bash, openssl, automation, nginx",
"url": null
} |
bash, openssl, automation, nginx
# setting new defaults for fastcgi
cat << EOF > /etc/apache2/mods-enabled/fastcgi.conf
<IfModule mod_fastcgi.c>
AddHandler fastcgi-script .fcgi
FastCgiIpcDir /var/lib/apache2/fastcgi
AddType application/x-httpd-fastphp .php
Action application/x-httpd-fastphp /php-fcgi
Alias /php-fcgi /usr/lib/cgi-bin/php-fcgi
FastCgiExternalServer /usr/lib/cgi-bin/php-fcgi -socket /run/php/php7.4-fpm.sock -pass-header Authorization
<Directory /usr/lib/cgi-bin>
Require all granted
</Directory>
</IfModule>
EOF
systemctl restart apache2
# create a php-info page - to be removed before production
echo "<?php phpinfo(); ?>" | tee /var/www/$fqn/info.php
# adjust ufw
ufw allow 8080
ufw allow "Apache Full"
# mod_rpaf to get visitors real IP through cloudflare and reverse proxy
apt -y install build-essential apache2-dev libtool-bin
wget https://github.com/gnif/mod_rpaf/archive/stable.zip
unzip stable.zip && cd mod_rpaf-stable
make && make install && libtool --finish /usr/lib/apache2/modules
touch /etc/apache2/mods-available/rpaf.load
echo 'LoadModule rpaf_module /usr/lib/apache2/modules/mod_rpaf.so' >> /etc/apache2/mods-available/rpaf.load
a2enmod rpaf
systemctl restart apache2 | {
"domain": "codereview.stackexchange",
"id": 43523,
"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": "bash, openssl, automation, nginx",
"url": null
} |
bash, openssl, automation, nginx
# Set defaults for virtual host
cat << EOF > /etc/apache2/sites-available/$fqn.conf
<VirtualHost *:8080>
$vhostserver
ServerAdmin $webmail
DocumentRoot $sitedir
<IfModule mod_ssl.c>
SSLEngine On
SSLHonorCipherOrder On
SSLCompression Off
SSLSessionTickets Off
SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1
SSLCipherSuite EECDH+CHACHA20:EECDH+AES
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} =on
RewriteRule ^ - [E=PROTO:https]
RewriteCond %{HTTPS} !=on
RewriteRule ^ - [E=PROTO:http]
# RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ %{ENV:PROTO}://%1%{REQUEST_URI} [R=301,L]
</IfModule>
<IfModule mod_headers.c>
Header always set Referrer-Policy "strict-origin-when-cross-origin" "expr=%{CONTENT_TYPE} =~ m#text\/(css|html|javascript)|application\/pdf|xml#i"
</IfModule>
<IfModule mod_headers.c>
Header always set X-Content-Type-Options "nosniff"
</IfModule>
<IfModule mod_headers.c>
Header always set X-Frame-Options "DENY" "expr=%{CONTENT_TYPE} =~ m#text/html#i"
</IfModule>
<IfModule mod_setenvif.c>
<IfModule mod_headers.c>
<FilesMatch "\.(avifs?|bmp|cur|gif|ico|jpe?g|jxl|a?png|svgz?|webp)$">
SetEnvIf Origin ":" IS_CORS
Header set Access-Control-Allow-Origin "*" env=IS_CORS
</FilesMatch>
</IfModule>
</IfModule>
<IfModule mod_headers.c>
<FilesMatch "\.(eot|otf|tt[cf]|woff2?)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>
<IfModule rpaf_module>
RPAF_Enable On
RPAF_SetHostName On
RPAF_ProxyIPs $myip
RPAF_Header CF-CONNECTING-IP
</IfModule>
# Log format config
LogFormat "%{CF-CONNECTING-IP}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" forwarded | {
"domain": "codereview.stackexchange",
"id": 43523,
"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": "bash, openssl, automation, nginx",
"url": null
} |
bash, openssl, automation, nginx
CustomLog "/var/log/apache2/$fqn.access.log" forwarded
ErrorLog /var/log/apache2/$fqn.error.log
<Directory $sitedir>
AllowOverride All
</Directory>
</VirtualHost>
EOF | {
"domain": "codereview.stackexchange",
"id": 43523,
"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": "bash, openssl, automation, nginx",
"url": null
} |
bash, openssl, automation, nginx
a2ensite $fqn.conf
systemctl restart apache2
# get SSL certificates by certbot
apt-get -y install python3-certbot-dns-cloudflare
# setup CF credentials
mkdir /root/.secrets/ && touch /root/.secrets/cloudflare.ini
echo "dns_cloudflare_email=$cfmail" >> /root/.secrets/cloudflare.ini
echo "dns_cloudflare_api_key=$cftoken" >> /root/.secrets/cloudflare.ini
chmod 0700 /root/.secrets/
chmod 0400 /root/.secrets/cloudflare.ini
# go
certbot certonly --agree-tos --no-eff-email --email \
$webmail --dns-cloudflare --dns-cloudflare-credentials \
/root/.secrets/cloudflare.ini -d $fqn,*.$fqn --preferred-challenges dns-01
####################################################################
# nginx setup
####################################################################
apt -y install nginx
# remove default
rm /etc/nginx/sites-enabled/default | {
"domain": "codereview.stackexchange",
"id": 43523,
"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": "bash, openssl, automation, nginx",
"url": null
} |
bash, openssl, automation, nginx
# setup new defaults
cat << EOF > /etc/nginx/sites-available/apache
server {
listen 80;
$servername
location / {
return 301 https://\$host\$request_uri;
}
}
server {
listen [::]:443 ssl http2;
listen 443 ssl http2;
$servername
ssl_session_timeout 24h;
ssl_session_cache shared:SSL:10m;
keepalive_timeout 300s;
# ssl_buffer_size 1400;
ssl_session_tickets off;
ssl_prefer_server_ciphers on;
ssl_certificate /etc/letsencrypt/live/$fqn/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/$fqn/privkey.pem;
ssl_dhparam /usr/lib/python3/dist-packages/certbot/ssl-dhparams.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers EECDH+CHACHA20:EECDH+AES;
ssl_ecdh_curve X25519:prime256v1:secp521r1:secp384r1;
return 301 $scheme://www.$fqn$request_uri;
}
server {
listen [::]:443 ssl http2;
listen 443 ssl http2;
server_name www.$fqn
ssl_session_timeout 24h;
ssl_session_cache shared:SSL:10m;
keepalive_timeout 300s;
# ssl_buffer_size 1400;
ssl_session_tickets off;
ssl_prefer_server_ciphers on;
ssl_certificate /etc/letsencrypt/live/$fqn/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/$fqn/privkey.pem;
ssl_dhparam /usr/lib/python3/dist-packages/certbot/ssl-dhparams.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers EECDH+CHACHA20:EECDH+AES;
ssl_ecdh_curve X25519:prime256v1:secp521r1:secp384r1;
location / {
proxy_pass http://$myip:8080;
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto \$scheme;
proxy_read_timeout 600;
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
client_max_body_size 100M;
}
location ~ /\.ht {
deny all;
}
# add_header Referrer-Policy $referrer_policy always;
add_header X-Content-Type-Options nosniff always;
# add_header X-Frame-Options $x_frame_options always; | {
"domain": "codereview.stackexchange",
"id": 43523,
"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": "bash, openssl, automation, nginx",
"url": null
} |
bash, openssl, automation, nginx
# add_header X-Frame-Options $x_frame_options always;
location ~* /\.(?!well-known\/) {
deny all;
}
location ~* (?:#.*#|\.(?:bak|conf|dist|fla|in[ci]|log|orig|psd|sh|sql|sw[op])|~)$ {
deny all;
}
# add_header Access-Control-Allow-Origin $cors;
access_log /var/log/nginx/$fqn.access.log;
error_log /var/log/nginx/$fqn.error.log;
}
EOF | {
"domain": "codereview.stackexchange",
"id": 43523,
"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": "bash, openssl, automation, nginx",
"url": null
} |
bash, openssl, automation, nginx
# activate new settings
ln -s /etc/nginx/sites-available/apache /etc/nginx/sites-enabled/apache
systemctl restart nginx
Answer:
set -e # Terminate if script has error
The comment doesn't add value - assume that anybody reading either knows what the flag means or can read the Bash manual.
Consider adding -u and -o pipefail as other useful settings.
printf "
####################################################################
# Enter location on disk for site (Default: /var/www/\$fqn):
####################################################################\n
dir: "
read -rp "" sitedir
That's a bit odd. I recommend using %s rather than interpolating a variable directly into the printf format string. Also, printing a partial line will confuse read (which assumes that it begins at start of line). Even more strangely, you specifically pass -p "". I'd replace that with read -rp 'dir: ' sitedir.
if [ -n "$sitedir" ]; then
if [ ${sitedir:+1} ]
then
echo "yes"
fi
else
sitedir="/var/www/$fqn"
fi
What's going on here? Just use the usual parameter defaulting:
echo "sitedir=${sitedir:=/var/www/$fqn}"
# servername
if [ -n "$sub" ]; then
servername="server_name $sub.$fqn www.$sub.$fqn;"
vhostserver="ServerName $sub.$fqn
ServerAlias www.$sub.$fqn"
else
servername="server_name $fqn www.$fqn;"
vhostserver="ServerName $fqn
ServerAlias www.$fqn"
fi
Could be simplified if we create a variable:
hostname=${sub:+$sub.}$fqn
servername="server_name $hostname www.$hostname;"
vhostserver="ServerName $hostname
ServerAlias www.$hostname | {
"domain": "codereview.stackexchange",
"id": 43523,
"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": "bash, openssl, automation, nginx",
"url": null
} |
c++
Title: A uniform interface for storing data by fd or container
Question: I need to store the data in three different ways:
storing the data to a std::string
writing the data to a given file descriptor
both of the above
And I hope to use a uniform interface for these three different methods.
How to make it better?
Here is the code snippet:
#include <memory>
#include <string>
#include <iostream>
#include <unistd.h>
class DataStorage {
public:
DataStorage()=default;
DataStorage(const DataStorage&) = default;
DataStorage(DataStorage&&) = default;
DataStorage& operator(const DataStorage&) = default;
DataStorage& operator(DataStorage&&) = default;
virtual int Store(const char *buffer, int count) = 0;
virtual ~DataStorage(){};
};
class DataStorageByStr : virtual public DataStorage {
public:
DataStorageByStr(std::string &str) : str_(str), total_count_{0}{};
DataStorageByStr()=delete;
DataStorageByStr(const DataStorageByStr&) = default;
DataStorageByStr(DataStorageByStr&&) = default;
DataStorageByStr& operator(const DataStorageByStr&) = default;
DataStorageByStr& operator(DataStorageByStr&&) = default;
int Store(const char *buffer, int count)
{
str_ += std::string(buffer, count);
total_count_ += count;
return 0;
};
int GetTotalWritten() const {return total_count_;};
private:
std::string &str_;
int total_count_;
};
class DataStorageByFd : virtual public DataStorage {
public:
DataStorageByFd(int &fd):fd_(fd), total_count_{0}{};
int Store(const char *buffer, int count)
{
int ret = write(fd_, buffer, count);
if(ret > 0)
{
total_count_ += ret;
}
return ret;
};
int GetTotalWritten() const {return total_count_;};
private:
int &fd_;
int total_count_;
}; | {
"domain": "codereview.stackexchange",
"id": 43524,
"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++
private:
int &fd_;
int total_count_;
};
class DataStorageByStrAndFd : public DataStorageByStr, public DataStorageByFd {
public:
DataStorageByStrAndFd(std::string &str, int &fd):DataStorageByStr(str), DataStorageByFd(fd){}
DataStorageByStrAndFd()=default;
DataStorageByStrAndFd(const DataStorageByStrAndFd&) = default;
DataStorageByStrAndFd(DataStorageByStrAndFd&&) = default;
DataStorageByStrAndFd& operator(const DataStorageByStrAndFd&) = default;
DataStorageByStrAndFd& operator(DataStorageByStrAndFd&&) = default;
int Store(const char *buffer, int count)
{
int ret1 = DataStorageByStr::Store(buffer, count);
int ret2 = DataStorageByFd::Store(buffer, count);
return ((0==ret1) && (0==ret2))?0:-1;
}
int GetWrittenByStr() const {return DataStorageByStr::GetTotalWritten();}
int GetWrittenByFd() const {return DataStorageByFd::GetTotalWritten();}
};
int StoreSomeData(DataStorage &storage, const std::string data_to_store)
{
return storage.Store(data_to_store.data(), data_to_store.length());
}
int main()
{
{
std::cout << "==============1=============" <<std::endl;
std::string str{"storing the string to std::string works !"};
std::string data;
DataStorageByStr storage_by_str = DataStorageByStr(data);
DataStorage &storage = storage_by_str;
StoreSomeData(storage, str);
std::cout << data << std::endl;
std::cout << "total written by str:" << storage_by_str.GetTotalWritten() << std::endl;
}
{
std::cout << "==============2=============" <<std::endl;
std::string str{"storing the string to fd works !"};
int fd = 1;
DataStorageByFd storage_by_fd = DataStorageByFd(fd);
DataStorage &storage = storage_by_fd;
StoreSomeData(storage, str);
std::cout << std::endl << "total written by fd:" << storage_by_fd.GetTotalWritten() << std::endl;
} | {
"domain": "codereview.stackexchange",
"id": 43524,
"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++
{
std::cout << "==============3=============" <<std::endl;
std::string str{"thanks for your attention for this matter!"};
std::string data;
int fd = 1;
DataStorageByStrAndFd storage_by_str_and_fd = DataStorageByStrAndFd(data, fd);
StoreSomeData(storage_by_str_and_fd, str);
std::cout << std::endl;
std::cout << "string length:" << str.length() << std::endl;
std::cout << "total written by string:" << storage_by_str_and_fd.GetWrittenByStr() << std::endl;
std::cout << "total written by fd:" << storage_by_str_and_fd.GetWrittenByFd() << std::endl;
}
}
```
Answer: Simplify the design
Unless you plan to add many more storage options in the future, I would apply the KISS and YAGNI principles, and just create one single class that can write to both a string and a file descriptor, and which keeps track somehow of which ones to write to. Something like:
class DataStorage {
public:
DataStorage(std::string &str, int fd = -1): str_{&str}, fd_{fd} {}
DataStorage(int fd): fd_{fd} {}
std::size_t Store(const char *buffer, std::size_t count);
std::size_t GetTotalWritten() const { return total_count_; }
private:
std::string *str_ = {};
int fd = -1;
std::size_t total_count_ = {};
};
Since -1 is guaranteed to be an invalid filedescriptor, and by storing the string as a pointer instead of a reference so it can be nullptr, we can check which of those to write to in Store():
std::size_t DataStorage::Store(const char *buffer, std::size_t count) {
if (str_) {
str_->append(buffer, count);
}
if (fd != -1) {
::write(fd_, buffer, count);
}
total_count_ += count;
return count;
} | {
"domain": "codereview.stackexchange",
"id": 43524,
"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++
total_count_ += count;
return count;
}
Use the correct types
You are using int everywhere you want a number, but there are different types of integers, and by not using the right ones you might introduce bugs (or even security issues) in your code. In particular, use std::size_t for most things that are sizes, counts and indices. It is guaranteed to be big enough to be able to address everything that fits in memory, whereas int is not.
Also be sure to store the return values from functions into a properly typed variable. In particular, write() returns a ssize_t. Note that you could also use auto to avoid having to specify the right type up front, for example like so:
auto ret = ::write(fd, buffer, count); | {
"domain": "codereview.stackexchange",
"id": 43524,
"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++
Missing error handling
You are not handling errors when writing to a file descriptor. ret can be negative for various reasons, some are recoverable (like if errno == EAGAIN), some are fatal. Also, write() might not write everything you want it to write, and can return a value that is less than count even if there is no error. If you want your code to be robust and not spuriously lose data you want to store, you have to handle all this, or alternatively return a proper error code to the caller so they can decide what to do.
Now you might think; I am returning something from Store() that can be used to check if there is an error, but unfortunately what you return is inconsistent between the different classes, and sometimes is not precise enough for the caller to see what went wrong. For example, DataStorageByFd::Store() returns the return value of write(), where a return value that is not the same as count means the caller has to do something about it, but DataStorageByStrAndFd::Store() just returns 0 or -1, but 0 is also returned if not all data was written to the file descriptor.
Ownership
Your data storage classes just store references to the file descriptor and the string. For the file descriptor, just store it by value; there is no point in storing it by reference. As for the string, it might be useful to store a reference, but it comes with a risk: what if the string you have a reference to goes out of scope before your data storage class? Consider storing the string by value in the class, and add a GetString() member function to get a reference to the string stored in your class.
Scalability | {
"domain": "codereview.stackexchange",
"id": 43524,
"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++
Scalability
The approach you have taken does not scale well if you want to add other storage options. For just strings and file descriptors you needed four different classes, if you add one other storage option you need to add four more classes for all the combinations this adds. Basically, for \$N\$ storage methods you need \$2^N\$ classes, which is a maintainability nightmare. If you want this to be able to scale up, you need to find another way to do this, which brings me to the following:
Consider using C++'s file I/O
Instead of using POSIX functions to write to a file, consider using standard C++ functionality to write to files if that is possible. This will make your program more portable. For example:
class DataStorage {
public:
DataStorage(std::ostream &os): os_(os) {}
...
private:
std::ostream &os_;
}; | {
"domain": "codereview.stackexchange",
"id": 43524,
"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++
std::size_t DataStorage::Store(const char *buffer, std::size_t count) {
os_.write(buffer, count);
...
}
This is much more flexible, as now you can write to anything which is an ostream, which includes files, std::cout, and even std::stringstreams. If you want to support writing to multiple streams, you could consider storing the ostream references in a std::vector. Now, storing references in a container requires you to use std::reference_wrapper, and to allow you to pass an arbitrary number of references to the constructor of DataStorage you can use something like a std::initializer_list, which might look a little daunting if you haven't used those before, but it actually results in quite simple and concise code:
class DataStorage {
public:
using ostream_ref = std::reference_wrapper<std::ostream>;
DataStorage(std::initializer_list<ostream_ref> streams): streams_(streams) {}
...
private:
std::vector<ostream_ref> streams_;
};
std::size_t DataStorage::Store(const char *buffer, std::size_t count) {
for (auto& stream: streams_) {
stream.get().write(buffer, count);
...
}
...
}
With this, you can use it like so:
std::ofstream file("log.txt");
std::stringstream ss;
DataStorage ds({file, std::cout, ss});
ds.Store("Hello, world!\n", 14);
std::cout << "ss contains: " << ss.str();
Note that with this approach, you again only store references in the DataStorage class, making it store the concrete stream objects by value is more complicated, involving templates. It would look something like this:
template<typename... Ts>
class DataStorage {
public:
DataStorage(Ts&&... streams): streams_(std::move(streams)...) {}
void Store(const char *buffer, std::size_t count) {
std::apply([=](Ts&... streams) {
(streams.write(buffer, count), ...);
}, streams_);
}
template<std::size_t I>
auto& Get() {
return std::get<I>(streams_);
}
private:
std::tuple<Ts...> streams_;
} | {
"domain": "codereview.stackexchange",
"id": 43524,
"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++
private:
std::tuple<Ts...> streams_;
}
An issue here is that you cannot copy C++ IO streams, you can only take a reference or move them. The above will work when you pass in new objects:
DataStorage ds(std::ofstream("log.txt"), std::stringstream{});
ds.write("Hello, world!\n", 14);
std::cout << "ss contains: " << ds.Get<1>().str();
But you cannot do this:
DataStorage ds(std::cout, ...);
At least not without adding further complications to the code.
Going further
The above code works with all the stream types the standard library provides. But what if you need something not provided by the standard library, like writing to a POSIX file descriptor? In that case, you can implement your own custom stream class (see this question for some links). As long as it is or derives from std::ostream, it will then work with anything that can take a std::ostream.
It is also possible to turn your DataStorage class into something that inherits from std::ostream, so that you can do things like:
DataStorage ds(...);
ds << "Hello, world!\n";
And if the DataStorage class takes a list of std::ostreams in its constructor, but also is a std::ostream itself, you can write things like:
DataStorage ds1(...);
DataStorage ds2(...);
DataStorage ds({ds1, ds2}); | {
"domain": "codereview.stackexchange",
"id": 43524,
"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
} |
html, typescript, dom, to-do-list
Title: Created a todo list in TS
Question: I am learning Typescript and created a straightforward to-do list project to practice some basic concepts.
I am able to
Edit the todo
Delete the todo
Mark the todo as completed
I want to how can I better structure my code and what typescript best practices I am not using.
index.ts
import { v4 as uuidv4 } from 'uuid';
const ul = document.querySelector("#todo")as HTMLUListElement
const addTaskBtn = document.querySelector('#add-btn') as HTMLButtonElement
const input = document.querySelector("#input") as HTMLInputElement
// array which stores the object
let todos:Array<Todo> = []
let id: string;
interface Todo {
id: string;
todo: string;
completed: boolean;
createdDate: Date;
updatedDate?: Date;
}
// How do I create objects that are stored on the array?
type storeObject = (a: string) => void;
const storeObject = (todo: string)=>{
const item: Todo = {
id: uuidv4(),
todo: todo,
completed: false ,
createdDate: new Date,
}
todos.push(item)
}
const renderTodos = ()=> {
todos.forEach((obj)=>{
const div = document.createElement("div");
div.classList.add("item")
const li = document.createElement("li");
li.classList.add("todo")
const checkbox = document.createElement("input")
checkbox.type = "checkbox"
checkbox.id = `${obj.id}`
if(obj.completed) checkbox.checked = true
const label = document.createElement("label")
label.textContent = obj.todo
label.htmlFor = `${obj.id}` | {
"domain": "codereview.stackexchange",
"id": 43525,
"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": "html, typescript, dom, to-do-list",
"url": null
} |
html, typescript, dom, to-do-list
const btns = document.createElement("div");
const editBtn = document.createElement("button") as HTMLButtonElement
editBtn.textContent = "Edit "
editBtn.classList.add("editBtn")
const deleteBtn = document.createElement("button") as HTMLButtonElement
deleteBtn.textContent = "Delete"
deleteBtn.classList.add("deleteBtn")
btns.appendChild(editBtn)
btns.appendChild(deleteBtn)
li.appendChild(checkbox)
li.appendChild(label)
div.appendChild(li);
div.appendChild(btns);
ul.appendChild(div);
})
}
const updateTodo = (id:string)=>{
// Updating todo after finding todo using id
todos.map((item)=>{
if(item.id == id) item.todo = input.value;
return
})
}
addTaskBtn.addEventListener("click",(e)=>{
if(input.value == "") return
(e.target as HTMLElement).textContent == "Update" ?
updateTodo(id) :
storeObject(input.value);
input.value = ""
// dom should be cleared and painted according to new data in array
ul.innerHTML = ""
addTaskBtn.textContent = "Add Task"
renderTodos()
});
document.addEventListener("click", (e)=>{
// getting the clicked todo's id
if((e.target as Element).classList.contains("editBtn")){
id = ((e.target as HTMLElement).parentNode.parentNode.childNodes[0].childNodes[0] as HTMLElement).id
let todo:string = ((e.target as HTMLElement).parentNode.parentNode.childNodes[0].childNodes[1] as HTMLElement).innerText
// populate input with the value
input.value = todo;
addTaskBtn.textContent = "Update"
}else if((e.target as HTMLElement).classList.contains("deleteBtn")){
// deleting todo
id = ((e.target as HTMLElement).parentNode.parentNode.childNodes[0].childNodes[0] as HTMLElement).id | {
"domain": "codereview.stackexchange",
"id": 43525,
"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": "html, typescript, dom, to-do-list",
"url": null
} |
html, typescript, dom, to-do-list
let values = todos.filter((item)=>{
if(item.id !== id) return item
})
todos = []
todos = [...values]
ul.innerHTML = ''
renderTodos()
}else if (((e.target as HTMLElement).parentNode as HTMLElement).classList.contains("todo")){
// checking if checkbox clicked
id = ((e.target as HTMLElement).parentNode.parentNode.childNodes[0].childNodes[0] as HTMLElement).id;
let values;
if(((e.target as HTMLElement).parentNode.childNodes[0] as HTMLInputElement).checked) {
values = todos.map((item)=>{
if(item.id == id) {
item.completed = true
return item
}
return item
})
}else{
values = todos.map((item)=>{
if(item.id == id) {
item.completed = false
return item
}
return item
})
}
todos = []
todos = [...values]
ul.innerHTML = ""
renderTodos()
}
})
index.html
<main>
<div class="top">
<input type="text" name="todo-input" id="input" value="" placeholder="TODO" >
<button id="add-btn" class="add-btn">Add Task</button>
</div>
<ul id="todo">
</ul>
</main>
Working example of todolist: https://codesandbox.io/s/condescending-newton-b7ljoz?file=/src/index.ts
Answer:
storeObject cannot be both a type and a function. Remove the type storeObject... statement
new Date needs parentheses, e.g. new Date()
storeObject does not need the variable item, the object can be inlined, e.g.
todos.push({
id: uuidv4(),
todo,
completed: false,
createdDate: new Date(),
}) | {
"domain": "codereview.stackexchange",
"id": 43525,
"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": "html, typescript, dom, to-do-list",
"url": null
} |
html, typescript, dom, to-do-list
Don't use type assertions (e.g. ... as SomeType), use type guards and narrowing. For example, In addTaskBtn event listener, use:
if (e.target instanceof HTMLElement) {
if (e.target.textContent === "Update") {
updateTodo(id)
} else {
storeObject(input.value);
}
}
Alternatively, check at the start of the method that you have the prerequsites and bail as appropriate:
if(input.value === "" || !(e.target instanceof HTMLElement)) {
return
}
if (e.target.textContent === "Update") {
updateTodo(id)
} else {
storeObject(input.value);
}
if (e.target.textContent === "Update") {
updateTodo(id)
} else {
storeObject(input.value);
}
Use strict equality === instead of == or type coercion can lead to unexpected results.
Don't use ternary expressions with side effects, use a full if/then/else expression.
Use optional chaining operator (?.) to avoid needing to check for null, or type assertions to override the possibility of null. If your DOM does not match the expected, you should probably bail in the event that DOM queries return NULL. Alternatively, put the DOM setup into the code, and only require a container element to be passed to the setup method.
updateTodo: todos.map's callback should return a value (e.g. return item)
You're creating a lot of work for yourself to add an event listener to the document that then has to disambiguate which element is firing the event. Instead, add event handlers to the specific element they serve.
Instead of inlining the event handler, take advantage of the fact that this is the event target (you'll need to use a fat function rather than an arrow function). e.g.
function editBtnHandler(this: HTMLButtonElement, ev: Event) {
// this === ev.target
// it's also correctly typed, so we don't need type assertions or null checks
}
editBtn.addEventListener('click', editBtnHandler) | {
"domain": "codereview.stackexchange",
"id": 43525,
"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": "html, typescript, dom, to-do-list",
"url": null
} |
html, typescript, dom, to-do-list
editBtn.addEventListener('click', editBtnHandler)
Wrap the whole shebang in a class. Pass to the constructor either a container element, or validated list, button and input elements so that you can lose the type assertions and optional chaining.
class TodoApp {
private todos: Todo[] = []
constructor(container: HTMLElement) {
const ul = document.createElement(...)
//...
container.appendChild(ul)
//...
}
renderTodos() {
this.todos.forEach(todo => {
//...
})
}
}
const container = document.querySelector('#todoApp')
const todoApp = new TodoApp(container)
Reconsider how you do the DOM traversal to get to elements containing id and label text. If you are adding a dedicated handler you could bind those values when the handler is created, so you have them to hand when handling the event.
Rather than redefining the functionality of the button/input element depending on add/update, you could use CSS classes to show/hide elements dedicated to those tasks (or update the DOM to add/remove). This way you lower the risk of keeping track of which state any element is in, and the code will read more clearly.
There is a lot there for you to do, and rather than just providing a rewrite with all of those suggestions, its probably better that you work through them and see how they apply. Come back when you have a revision, perhaps as a new post. Feel free to ask for clarifications if not sure. | {
"domain": "codereview.stackexchange",
"id": 43525,
"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": "html, typescript, dom, to-do-list",
"url": null
} |
python, multithreading, thread-safety, cache, memoization
Title: Thread-safe memoizer
Question: I have searched around but I was not able to find a complete implementation of the memoize pattern in a multithreaded context. It's the first time playing with thread synchronization. The code seems to works, but I am not able to test it extensively, in particular to find if there are race conditions. Do you think there is a better implementation, maybe using more advanced synchronization mechanism?
from threading import Thread, Lock, current_thread
import thread
def memoize(obj):
import functools
cache = obj.cache = {}
lock_cache = obj.lock_cache = Lock()
@functools.wraps(obj)
def memoizer(*args, **kwargs):
key = str(args) + str(kwargs)
cached_result = None
item_lock = None
with lock_cache:
# do the minimal needed things here: just look inside the cache,
# return if present, otherwise create and acquire lock specific to a
# particular computation. Postpone the actual computation, do not
# block other computation.
cached_result = cache.get(key, None)
if cached_result is not None:
if type(cached_result) is not thread.LockType:
return cached_result
else:
item_lock = Lock()
item_lock.acquire()
cache[key] = item_lock
if item_lock is not None:
# if we are here it means we have created the lock: do the
# computation, return and release.
result = obj(*args, **kwargs)
with lock_cache:
cache[key] = result
item_lock.release()
return result
if type(cached_result) is thread.LockType:
# if we are here it means that other thread have created the
# locks and are doing the computation, just wait
with cached_result:
return cache[key]
return memoizer | {
"domain": "codereview.stackexchange",
"id": 43526,
"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, multithreading, thread-safety, cache, memoization",
"url": null
} |
python, multithreading, thread-safety, cache, memoization
Here a little test:
import time
@memoize
def f(x):
time.sleep(2)
return x * 10
lock_write = Lock()
def worker(x):
result = f(x)
with lock_write:
print current_thread(), x, result
threads = []
start = time.time()
for i in (0, 1, 1, 2, 0, 0, 0, 1, 3):
t = Thread(target=worker, args=(i,))
threads.append(t)
t.start()
time.sleep(1)
for i in (0, 1, 1, 2, 0, 0, 0, 1, 3):
t = Thread(target=worker, args=(i,))
threads.append(t)
t.start()
for t in threads:
t.join()
print time.time() - start
I get the correct results and it runs in 2 seconds, as expected.
Answer: 1. Review
There's no docstring. What does memoize do, and how do I use it?
The code uses str(args) + str(kwargs) as the cache key. But this means that, for example, the number 1 and the string "1" will collide.
The code is not portable to Python 3, where there's no thread module.
It's not clear to me why functools is only imported inside memoize, but threading is imported at top level.
It's not clear to me why the code assigns to obj.cache and obj.lock_cache. What if obj already has a cache property?
The locking logic is hard to follow and needs comments. As far as I can see, lock_cache protects the cache dictionary; and item_cache protects the cache slot that is currently being computed. Its necessary to have two locks because the call to obj might be recursive and so need to re-enter memoizer.
The code uses three states for each key: (i) not present in the cache; (ii) currently being computed; (iii) present in the cache. The way it distinguishes between (ii) and (iii) is by checking to see if the type is thread.LockType. But this means that you can't use memoize on a function that might return a lock. It would be better to have a more robust mechanism for distinguishing these cases.
The naming is inconsistent: lock_cache versus item_lock.
key is looked up in cache multiple times on some code paths. | {
"domain": "codereview.stackexchange",
"id": 43526,
"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, multithreading, thread-safety, cache, memoization",
"url": null
} |
python, multithreading, thread-safety, cache, memoization
2. Revised code
from functools import wraps
from threading import Lock
class CacheEntry: pass
def memoized(f):
"""Decorator that caches a function's result each time it is called.
If called later with the same arguments, the cached value is
returned, and not re-evaluated. Access to the cache is
thread-safe.
"""
cache = {} # Map from key to CacheEntry
cache_lock = Lock() # Guards cache
@wraps(f)
def memoizer(*args, **kwargs):
key = args, tuple(kwargs.items())
result_lock = None
with cache_lock:
try:
entry = cache[key]
except KeyError:
entry = cache[key] = CacheEntry()
result_lock = entry.lock = Lock() # Guards entry.result
result_lock.acquire()
if result_lock:
# Compute the new entry without holding cache_lock, to avoid
# deadlock if the call to f is recursive (in which case
# memoizer is re-entered).
result = entry.result = f(*args, **kwargs)
result_lock.release()
return result
else:
# Wait on entry.lock without holding cache_lock, to avoid
# blocking other threads that need to use the cache.
with entry.lock:
return entry.result
return memoizer
Notes:
This is untested.
This doesn't delete result_lock after the result is computed. This simplifies the logic (for example, there's no need to take cache_lock again and no need for a type check) at the cost of 40 bytes to keep the Lock object around. | {
"domain": "codereview.stackexchange",
"id": 43526,
"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, multithreading, thread-safety, cache, memoization",
"url": null
} |
beginner, c, brainfuck
Title: Simple Brainfuck interpreter in C with support for nested subroutines
Question: Wrote a simple brainfuck interpreter that supports nested subroutines ([ ] commands).
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <assert.h>
#define MIN_MEMORY_SIZE 30000
typedef struct
{
uint8_t *memory;
size_t pointer;
} BrainfuckState;
static void init(BrainfuckState *bf, size_t size)
{
assert(size <= MIN_MEMORY_SIZE);
bf->memory = calloc(size, 1);
assert(!(bf == NULL));
bf->pointer = 0;
}
static void deinit(BrainfuckState *bf)
{
free(bf->memory);
bf->pointer = 0;
}
static void interpret(BrainfuckState *bf, const char* source, size_t sourceSize)
{
size_t unmatchedBracketCount = 0;
for (size_t i = 0; i < sourceSize; i++)
{
switch (source[i])
{
case '.':
printf("%c", bf->memory[bf->pointer]);
break;
case ',':
scanf("%c", &(bf->memory[bf->pointer]));
break;
case '+':
bf->memory[bf->pointer]++;
break;
case '-':
bf->memory[bf->pointer]--;
break;
case '>':
bf->pointer++;
break;
case '<':
bf->pointer--;
break;
case '[':
if (bf->memory[bf->pointer] == 0)
{
unmatchedBracketCount++;
while (source[i] != ']' || unmatchedBracketCount)
{
i++;
if (source[i] == '[')
unmatchedBracketCount++;
else if (source[i] == ']')
unmatchedBracketCount--;
}
}
break; | {
"domain": "codereview.stackexchange",
"id": 43527,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, brainfuck",
"url": null
} |
beginner, c, brainfuck
case ']':
if (bf->memory[bf->pointer])
{
unmatchedBracketCount++;
while (source[i] != '[' || unmatchedBracketCount)
{
i--;
if (source[i] == ']')
unmatchedBracketCount++;
else if (source[i] == '[')
unmatchedBracketCount--;
}
}
break;
}
}
}
int main(int argc, char** argv)
{
if (argc < 2)
fprintf(stderr, "Pass a filename as a command line arguement.\n");
else
{
FILE *fp = fopen(argv[1], "r");
assert(fp);
fseek(fp, 0, SEEK_END);
size_t sourceSize = ftell(fp);
char *source = malloc(sourceSize);
assert(source);
rewind(fp);
for (size_t i = 0; i < sourceSize; i++)
source[i] = fgetc(fp);
fclose(fp);
BrainfuckState bf;
init(&bf, MIN_MEMORY_SIZE);
interpret(&bf, source, sourceSize);
deinit(&bf);
free(source);
}
return EXIT_SUCCESS;
}
My goal was to keep it as simple and short as possible.
Answer: Advice 1
#define MIN_MEMORY_SIZE 30000
Later...
static void init(BrainfuckState *bf, size_t size)
{
assert(size <= MIN_MEMORY_SIZE);
...
}
Actually, it's a maximum memory size. I would rename it to MAX_TAPE_LENGTH.
Advice 2
typedef struct
{
uint8_t *memory;
size_t pointer;
} BrainfuckState;
I would add a memory capacity and rename memory to tape, since, in Brainfuck, the "memory" is not random-access, but rather access data sequentially.
Advice 3
static void init(BrainfuckState *bf, size_t size)
{
assert(size <= MIN_MEMORY_SIZE);
bf->memory = calloc(size, 1);
assert(!(bf == NULL));
bf->pointer = 0;
} | {
"domain": "codereview.stackexchange",
"id": 43527,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, brainfuck",
"url": null
} |
beginner, c, brainfuck
I would move the check assert(!(bf == NULL)); to the first statement in init and change it to assert(bf).
Advice 4
static void deinit(BrainfuckState *bf)
{
free(bf->memory);
bf->pointer = 0;
}
I would change it to
static void deinit(BrainfuckState* bf)
{
free(bf->tape);
bf->tape = NULL;
bf->tape_length = 0;
bf->pointer = 0;
}
Advice 5
case '>':
bf->pointer++;
break;
case '<':
bf->pointer--;
break;
May overflow. I would protect like this:
case '>':
if (bf->pointer < bf->tape_length - 1) {
bf->pointer++;
}
break;
case '<':
if (bf->pointer > 0) {
bf->pointer--;
}
break;
Advice 6
Before executing some Brainfuck code, I would check that the square brackets are balanced. For example,
++[[>][>]]
is balanced. And
++][]]
is not. For that end, you need a stack data structure. The check algorithm looks like:
stack st;
for ch in source:
switch ch {
case '[':
st.push(ch)
break
case ']':
if st is empty:
return false
st.pop()
break
}
return st is empty
Summa summarum
All in all, I had this rewrite in mind:
#define _CRT_SECURE_NO_WARNINGS /* Visual Studio 2022 specific */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <assert.h>
#define MAX_TAPE_LENGTH 30000
typedef struct char_stack_node {
struct char_stack_node* prev;
char ch;
} char_stack_node;
typedef struct char_stack {
char_stack_node* top;
size_t size;
} char_stack;
void char_stack_init(char_stack* st) {
st->size = 0;
st->top = NULL;
}
void char_stack_push(char_stack* st, char ch) {
char_stack_node* node = malloc(sizeof *node);
node->ch = ch;
node->prev = st->top;
st->top = node;
st->size++;
}
int char_stack_is_empty(char_stack* st) {
return st->size == 0;
} | {
"domain": "codereview.stackexchange",
"id": 43527,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, brainfuck",
"url": null
} |
beginner, c, brainfuck
int char_stack_is_empty(char_stack* st) {
return st->size == 0;
}
char char_stack_pop(char_stack* st) {
char datum;
char_stack_node* old_top = st->top;
datum = old_top->ch;
st->top = st->top->prev;
st->size--;
free(old_top);
return datum;
}
static int check_is_parentheses_balanced(const char *const source,
size_t source_length) {
char_stack st;
char_stack_init(&st);
for (size_t i = 0; i < source_length; ++i) {
char ch = source[i];
switch (ch) {
case '[':
char_stack_push(&st, ch);
break;
case ']':
if (char_stack_is_empty(&st)) {
return 0;
}
char_stack_pop(&st);
break;
}
}
return char_stack_is_empty(&st) ? 1 : 0;
}
typedef struct
{
uint8_t* tape;
size_t pointer;
size_t tape_length;
} BrainfuckState;
static void init(BrainfuckState* bf, size_t tape_length)
{
assert(bf);
assert(tape_length <= MAX_TAPE_LENGTH);
bf->tape = calloc(tape_length, sizeof *bf->tape);
bf->tape_length = tape_length;
bf->pointer = 0;
}
static void deinit(BrainfuckState* bf)
{
free(bf->tape);
bf->tape = NULL;
bf->tape_length = 0;
bf->pointer = 0;
}
static void interpret(BrainfuckState* bf, const char* source, size_t source_length)
{
size_t unmatchedBracketCount = 0;
if (!check_is_parentheses_balanced(source, source_length)) {
fprintf(stderr, "Error: unbalanced square brackets.\n");
exit(EXIT_FAILURE);
}
for (size_t i = 0; i < source_length; i++)
{
switch (source[i])
{
case '.':
printf("%c", bf->tape[bf->pointer]);
break;
case ',':
scanf("%c", &(bf->tape[bf->pointer]));
break;
case '+':
bf->tape[bf->pointer]++;
break; | {
"domain": "codereview.stackexchange",
"id": 43527,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, brainfuck",
"url": null
} |
beginner, c, brainfuck
case '+':
bf->tape[bf->pointer]++;
break;
case '-':
bf->tape[bf->pointer]--;
break;
case '>':
if (bf->pointer < bf->tape_length - 1) {
bf->pointer++;
}
break;
case '<':
if (bf->pointer > 0) {
bf->pointer--;
}
break;
case '[':
if (bf->tape[bf->pointer] == 0)
{
unmatchedBracketCount++;
while (source[i] != ']' || unmatchedBracketCount)
{
i++;
if (source[i] == '[')
unmatchedBracketCount++;
else if (source[i] == ']')
unmatchedBracketCount--;
}
}
break;
case ']':
if (bf->tape[bf->pointer])
{
unmatchedBracketCount++;
while (source[i] != '[' || unmatchedBracketCount)
{
i--;
if (source[i] == ']')
unmatchedBracketCount++;
else if (source[i] == '[')
unmatchedBracketCount--;
}
}
break;
}
}
}
int main(int argc, char** argv)
{
if (argc < 2)
fprintf(stderr, "Pass a filename as a command line arguement.\n");
else
{
FILE* fp = fopen(argv[1], "r");
assert(fp);
fseek(fp, 0, SEEK_END);
size_t sourceSize = ftell(fp);
char* source = malloc(sourceSize);
assert(source);
rewind(fp);
for (size_t i = 0; i < sourceSize; i++)
source[i] = fgetc(fp);
fclose(fp);
BrainfuckState bf;
init(&bf, MAX_TAPE_LENGTH);
interpret(&bf, source, sourceSize);
deinit(&bf); | {
"domain": "codereview.stackexchange",
"id": 43527,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, brainfuck",
"url": null
} |
beginner, c, brainfuck
free(source);
}
return EXIT_SUCCESS;
}
``` | {
"domain": "codereview.stackexchange",
"id": 43527,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, brainfuck",
"url": null
} |
java, object-oriented
Title: Using methods to get and display userInput
Question: Would like to know if I could have done anything better with the code that I wrote. Want to also know if I could have avoided using a static variable.
private static int numberEntered;
public static void main(String[] args) {
int quit = 0;
int sum = 0;
userPrompt();
while(numberEntered != quit){
sum += numberEntered;
userPrompt();
}
printTotal(sum);
}
public static int userPrompt(){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number or 0 to quit: ");
numberEntered = scanner.nextInt();
return numberEntered;
}
public static void printTotal(int total){
System.out.println("The sum of all the entered numbers is: " + total);
}
Answer: numberEntered should not be static and should not be a member.
It's good that you made a variable for quit, but it should be made final and probably pulled out to the class. It should be used for your prompt instead of the prompt hard-coding 0.
You should not be re-instantiating a scanner on every call to userPrompt; store this as a member instead.
Consider using a simple stream to sum all of the numbers entered.
Suggested
import java.util.Scanner;
import java.util.stream.IntStream;
public class Main {
private static final int QUIT = 0;
private final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int sum = new Main().sum();
System.out.printf("The sum of all the entered numbers is: %d%n", sum);
}
public int sum() {
return IntStream
.generate(this::userPrompt)
.takeWhile(x -> x != QUIT)
.sum();
}
private int userPrompt(){
System.out.printf("Enter number or %d to quit: ", QUIT);
return scanner.nextInt();
}
} | {
"domain": "codereview.stackexchange",
"id": 43528,
"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",
"url": null
} |
java, object-oriented
Output
Enter number or 0 to quit: 1
Enter number or 0 to quit: 2
Enter number or 0 to quit: 3
Enter number or 0 to quit: 0
The sum of all the entered numbers is: 6 | {
"domain": "codereview.stackexchange",
"id": 43528,
"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",
"url": null
} |
javascript, google-apps-script
Title: List with values not found in another list when each index has two objects
Question: As the question already says, my code returns a list with the index's that don't exist inside another list.
For this I currently create two lists joining the objects of each index, then filter the values not found and finally I do a loop searching in which index I will find this value within the initial list:
function notfind() {
const history = [['a','b'],['c','d']]
const history_join = [];
var i=0;
var max = history.length;
for(i; i<max; i++){
history_join.push(history[i][0] + history[i][1]);
}
const new_values = [['c','d'],['e','f']]
const new_values_join = [];
var i=0;
var max = new_values.length;
for(i; i<max; i++){
new_values_join.push([new_values[i][0] + new_values[i][1]]);
}
const not_match = new_values_join.filter(x => !history_join.includes(x[0]));
var not_contains = [];
var i=0;
var max = new_values_join.length;
for(i; i<max; i++) {
if (not_match.includes(new_values_join[i])) {
not_contains.push(new_values[i])
}
}
console.log(not_contains);
}
Output:
[['e','f']]
I would like a review of the method to improve the execution time and number of tasks until reaching the desired result.
Additional information of a method security flaw found by @DaveMeehan:
What if history was [‘a’,’b’] and new values was [‘ab’,’’]
Answer: Your solution can be simplified to a few lines.
This peice of code is written twice in your function and simply creates a list of "keys" to identify each sub array of your list.
for(i; i<max; i++){
history_join.push(history[i][0] + history[i][1]);
}
You could create a function that handles building the key and call it whenever you want.
const buildKey = arr => arr.join('');
The advantage of that is, you won't be limitted to two items of your sub array. | {
"domain": "codereview.stackexchange",
"id": 43529,
"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, google-apps-script",
"url": null
} |
javascript, google-apps-script
The advantage of that is, you won't be limitted to two items of your sub array.
You're also playing around with multiple lists within your function but that seems to overly complicate your end goal.
You should instead:
Build keys from your history list and store efficient Set object.
Build keys from your new_values list and see if it exists in the Set object.
If the new_value key doesn't exist in Set well you can filter it out.
Full solution:
const buildKey = arr => arr.join(':');
const notFound = (input, history) => {
const historySet = new Set(history.map(buildKey));
return input.filter((arr) => !historySet.has(buildKey(arr)))
}
const history = [['a','b'],['c','d']];
const input = [['c','d'],['e','f'], ['ab', '']];
const result = notFound(input, history);
console.log(result) | {
"domain": "codereview.stackexchange",
"id": 43529,
"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, google-apps-script",
"url": null
} |
python, beginner, game
Title: A simple spaceship game
Question: How could I improve this code? It's a little game. If you run it, instructions will appear.
In particular, I'd like to know whether I can
make it considerably shorter
any trick :) ?
whether I can get rid of the repetition in 130-150.
import keyboard
import random
from threading import Thread
from time import sleep
# PARAMETERS #
score = 3 # initial lives
lenght = 10 # this for the arena
width = 10
# VARIABLE DECLARATION #
runner = True
ast_x_coord = []
ast_y_coord = []
# CLASSES DECLARATION #
# it's the starship that the user moves to kill asteroids
class Spaceship:
def __init__(self):
self.x_coord = 0
def move_right(self): # moves the ship to the right
if self.x_coord <= (width - 2):
self.x_coord += 1
def move_left(self): # moves the ship to the left
if self.x_coord >= 1:
self.x_coord -= 1
# it's the projectile emitted by the ship. it kills asterodids
class Projectile:
def __init__(self):
global lenght
self.x_coord = 0
self.y_coord = lenght
self.stop = False # am i moving? and do i like pizza?
def fire(self): # this dictates the movement of the projectile once fired
global lenght, spaceship, runner
self.x_coord = spaceship.x_coord
self.y_coord = 0 # initial position
for _i in range(lenght + 1): # move!
if runner and not self.stop: # helps for "fast" shut off
self.y_coord += 1
sleep(0.05)
self.stop = False # ah you hit it!
self.y_coord = lenght
# so that it is back in its neutral position once fired
# i like to be killed by spaceships
class Asteroid(object):
def __init__(self, name):
self.name = name # so there can be many of mee!
self.x_coord = width
self.y_coord = lenght - 1
self.life = True # am i alive? and do i like pizza? | {
"domain": "codereview.stackexchange",
"id": 43530,
"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, beginner, game",
"url": null
} |
python, beginner, game
def go(self): # this dictates how the asteroid moves
global ast_x_coord, ast_y_coord, score, projectile, runner
self.x_coord = random.randint(0, width - 1)
self.y_coord = lenght
for i in range(lenght + 1):
if runner: # so the programm shuts off rapidly
if (self.life):
# so that we do not get errors once the asteroid is killed
self.y_coord -= 1
if self.y_coord == 0:
score -= 1 # if at the end, we lose on score
try: # its coordinates may not be in the lists
ast_x_coord.pop(self.name)
ast_y_coord.pop(self.name)
except:
pass
finally:
ast_y_coord.insert(self.name, self.y_coord)
ast_x_coord.insert(self.name, self.x_coord)
# add or add back the coordinates
for i in range(29):
# 30 small delays to check often because of thread
if (self.y_coord == projectile.y_coord and
self.x_coord == projectile.x_coord
): # checks for collisions projectile - asteroid
ast_x_coord.pop(self.name)
ast_y_coord.pop(self.name)
# asteroid have saved them already at least once
ast_y_coord.insert(self.name, lenght)
ast_x_coord.insert(self.name, width)
# getting rid of the shadow remaining on screen
projectile.stop = (True)
# signaling to the projectile to stop
self.life = False # you die!
break # exit the loop for no delay | {
"domain": "codereview.stackexchange",
"id": 43530,
"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, beginner, game",
"url": null
} |
python, beginner, game
break # exit the loop for no delay
sleep(0.01)
elif not self.life:
del self # we do not want a ton of objects laying around
break | {
"domain": "codereview.stackexchange",
"id": 43530,
"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, beginner, game",
"url": null
} |
python, beginner, game
spaceship = Spaceship() # the ship is being built
projectile = Projectile() # the projectile is alive
# FUNCTIONS #
def manager(): # this manages base functions
global score, ast_y_coord, runner
while runner: # so we can shut it off
sleep(0.005) # refresh rate
refresh_display()
if score <= 0: # in case we lost
stop() | {
"domain": "codereview.stackexchange",
"id": 43530,
"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, beginner, game",
"url": null
} |
python, beginner, game
def refresh_display(): # refreshes the frame
global projectile, spaceship, score, lenght, width, runner
if runner: # so we can shut it off rapidly
os.system('cls') # blank paper sheet
print('you have to kill all the asteroids') # instructions
print('if you fail 3 times, your game is over\n')
print('to allign the ship with the asteroid use right/left arrow')
print('fire with "f". if you want to quit use "q"\n')
print('you can only fire when the past projectile has disappeared')
print(f'>>> ONLY {int(score)} HITS LEFT <<<') # score line
frame = '' # temporary variable
for y in range(lenght):
# we build the screen by coordinates, assigning the right item
for x in range(width):
try:
if x == ast_x_coord[ast_y_coord.index(y)]:
frame += ' ●'
elif (y, x) == (0, spaceship.x_coord):
frame += ' Ħ'
elif (y, x) == (projectile.y_coord, projectile.x_coord):
frame += ' ⁞'
elif (y-1, x) == (projectile.y_coord, projectile.x_coord):
frame += ' ˘'
else:
frame += ' '
except:
if (y, x) == (0, spaceship.x_coord):
frame += ' Ħ'
elif (y, x) == (projectile.y_coord, projectile.x_coord):
frame += ' ⁞'
elif (y-1, x) == (projectile.y_coord, projectile.x_coord):
frame += ' ˘'
else:
frame += ' '
frame += '|\n' # so we can move to the next row
print(frame) | {
"domain": "codereview.stackexchange",
"id": 43530,
"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, beginner, game",
"url": null
} |
python, beginner, game
def asteroid_generator(): # generates asteroid at random intervals
id_name = 0
global runner
while runner: # so everything shuts when we want
asteroid = Asteroid(id_name)
# new pizza-eater i.e. astroid with name 'id_name'
ast_go = Thread(target=asteroid.go) # its own thread of movement
ast_go.start()
sleep(random.uniform(1, 2.5)) # time before the next spawns
id_name += 1 # change the name of the next
def fire(): # fires the projectile if possible
global lenght, life
if projectile.y_coord == lenght:
# which means 'neutral state'. i.e not fired
proj_fire = Thread(target=projectile.fire) # fires the projectile
proj_fire.start() # in its own thread
def stop(): # ends the programm
global runner # shut it off
runner = False
os.system('cls')
print('goodbye')
# SPACESHIP CONTROL #
keyboard.add_hotkey('right', spaceship.move_right)
keyboard.add_hotkey('left', spaceship.move_left)
keyboard.add_hotkey('f', fire)
# GAME CONTROLS #
keyboard.add_hotkey('q', stop)
# MANAGER #
# starts manager and asteroid generator
manager = Thread(target=manager)
manager.start()
sleep(5) # you have to read instructions at the start
ast_generator = Thread(target=asteroid_generator)
ast_generator.start()
Answer: # PARAMETERS #
score = 3 # initial lives
lenght = 10 # this for the arena
width = 10
The names you have given to these variables are bad.
The name score contradicts the comment lives.
The name length is too broad. Length of what? It should be arena_length instead.
The name width should be arena_width. I'm assuming that it is related to the arena as well.
When the arena is displayed, it's more common to talk about width and height than about width and length, as the length does not specify any direction.
# VARIABLE DECLARATION #
runner = True
ast_x_coord = []
ast_y_coord = [] | {
"domain": "codereview.stackexchange",
"id": 43530,
"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, beginner, game",
"url": null
} |
python, beginner, game
# VARIABLE DECLARATION #
runner = True
ast_x_coord = []
ast_y_coord = []
So something can be a runner or not. When I read this name without having any further context, I'm clueless about its intention. Maybe it's something like game_still_running, but at this point, I cannot know.
Instead of ast_x_coord, I'd rather name the variable asteroid_x. The x and y already suggest that these two variables form coordinates, so there is no need to repeat that in the variable name.
def move_right(self): # moves the ship to the right
if self.x_coord <= (width - 2):
self.x_coord += 1
From this code, I guess the spaceship has a width of 3. That guess was wrong though, which makes the code confusing.
A more common way to express the same thought is:
if self.x + self.width + 1 <= arena_width:
self.x += 1
The expression x + width is common for getting the right edge of an object. The + 1 is the planned movement to the right. If after that movement, the right edge of the spaceship is still within the arena, moving the spaceship is possible.
self.stop = False # am i moving? and do i like pizza?
I have no idea how a projectile is related to pizza.
Naming the variable stop is confusing, it contradicts the comment "am I moving". You should probably call that variable moving instead.
self.stop = False # ah you hit it!
See how confusing this is? The code says "don't stop", the comment says "you hit it", which implies that the projectile stops at this point.
self.name = name # so there can be many of mee!
I suppose that mee is a simple typo. Or is there any deeper meaning to it?
self.life = True # am i alive? and do i like pizza?
I'd name that variable alive instead of life. | {
"domain": "codereview.stackexchange",
"id": 43530,
"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, beginner, game",
"url": null
} |
python, beginner, game
I'd name that variable alive instead of life.
I quickly read through the actual code, and it was OK. But since the variable names were so misleading, that's the one point I'm focusing on in this review. Naming things well is one of the hard problems in computer science, so it's good to practice it from the beginning. | {
"domain": "codereview.stackexchange",
"id": 43530,
"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, beginner, game",
"url": null
} |
c++, performance, eigen, rcpp, linear-algebra
Title: Coordinate Descent Non-negative Least Squares optimization
Question: In my fast implementation of Non-negative Matrix Factorization (Rcpp Machine Learning Library, RcppML), about 40% of the runtime is spent solving Non-negative Least Squares (NNLS) systems (the rest of the runtime is spent calculating the left and right sides of the NNLS systems, a and b, simple cross-products). I'd like to reduce NNLS runtime, if possible.
I'm using stochastic coordinate descent to solve least squares equations. Since I'm not expecting any theoretical improvements here, what computational approaches can I use to speed up this function? I am open to absolutely anything.
//[[Rcpp::export]]
Eigen::VectorXd nnls(const Eigen::MatrixXd& a, Eigen::VectorXd& b, double tol = 1e-8, size_t maxit = 100) {
Eigen::VectorXd x = Eigen::VectorXd::Zero(b.size());
tol *= b.size();
while(maxit-- > 0) {
double tol_ = 0;
for (size_t i = 0; i < b.size(); ++i) {
double diff = b(i) / a(i, i);
if (-diff > x(i)) {
if (x(i) != 0) {
b -= a.col(i) * -x(i);
tol_ = 1;
x(i) = 0;
}
} else if (diff != 0) {
x(i) += diff;
b -= a.col(i) * diff;
tol_ += std::abs(diff / x(i));
}
}
if (tol_ < tol) break;
}
return x;
}
EDIT in response to Rainer P.
Thank you for taking the time to thoroughly understand the problem and for your great suggestions! I did a lot of benchmarking while incorporating your suggestions on a variety of test cases including different ranks and well-conditioned or random systems: | {
"domain": "codereview.stackexchange",
"id": 43531,
"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++, performance, eigen, rcpp, linear-algebra",
"url": null
} |
c++, performance, eigen, rcpp, linear-algebra
Your code "as is" was around 30% slower than my code "as is" for small ranks, but was nearly break-even for ranks > 100. For random systems (which rarely occur in NMF) your code was likely to break even with mine. For L1-regularized systems, your code was significantly slower (1.5-2x slower).
Removing the if(diff != 0) logical check: another 10% slower
Modularizing the code was helpful for benchmarking. nnls_iteration is the bottleneck, but not as much as it might seem. The percentage of time spent solving nnls_iteration/x += diff/nnls_mean_error for a 20-, 40-, or 100-variable system is 40/30/30%, 50/25/25%, and 70/15/15%, respectively.
I struggled to understand why your code was slightly slower for many test cases, until I realized that cases where x(i) is to be set to zero require first diff(i) = -x(i) and then x(i) += diff(i). Thus, there is assignment to a temporary, then floating point addition, instead of a logical check and assignment to zero if true.
Chunking up the solving step would make sense if ranks were very large, but typically an NMF model is rarely larger than a rank of 100 or so. Impressive work! | {
"domain": "codereview.stackexchange",
"id": 43531,
"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++, performance, eigen, rcpp, linear-algebra",
"url": null
} |
c++, performance, eigen, rcpp, linear-algebra
EDIT in response to G. Sliepen:
Thanks G. Sliepen for the thoughtful and sensible answer. I wish I could say your ideas inspired a faster version, but not so.
Logical branching/vectorization: Performance of vectorization and logical branching in coordinate descent NNLS is a bit noncanonical. NNLS can contain a significant proportion of zero-valued indices, particularly with L1 regularization. If I take out any one of the logical branches (e.g. diff == 0 or x(i) == 0) the processor does not know that a zero is a no-op, and so the code is executed regardless, taking time to do nothing. By my benchmarks, both logical checks provide speedups 10-80% in real life (k = 10 to 100, for real datasets). Ditto with vectorization, because if the gradient b is computed for all indices, it must then be corrected with a second calculation for indices where x == 0, which is highly inefficient. I'm not sure if some form of conditional vectorization could be used that would have an advantage over an element-wise loop.
Division: This is interesting, one I hadn't thought much about. But passing the const inverse diagonal vector of a to avoid division actually slowed down the function ~10% generally. This inspired an idea where a and b are "normalized" (similar to "anti-lop NNLS") such that the diagonal of a is all ones, with the caveat that x must then be "un-normalized". This was marginally faster for massively parallel NNLS where a is constant, but doesn't hold true for cases where a is variable (i.e. NMF with masking).
Warm-start initialization: Spot on, and I do this in my NMF implementation with great results.
Answer: If I understand your code correctly, you subtract the columns of the matrix a from vector b, each column multiplied by a different scalar diff. You also add diff to an element of vector x. Basically:
loop until convergence:
for each column i:
diff = ...
b -= a.col(i) * diff
x(i) += diff | {
"domain": "codereview.stackexchange",
"id": 43531,
"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++, performance, eigen, rcpp, linear-algebra",
"url": null
} |
c++, performance, eigen, rcpp, linear-algebra
As a first improvement, I suggest to simplify and modularize the code to make it more readable and to identify the bottleneck. You can get rid of
if (-diff > x(i)) if you use diff = std::max(... instead. If you make diff a vector, you can separate the convergence check from the main loop. The result is more readable and maintainable, but we haven't improved performance yet. Here it is:
Eigen::VectorXd nnls(const Eigen::MatrixXd& a, Eigen::VectorXd& b, double tol = 1e-8, size_t maxit = 100) {
Eigen::VectorXd x = Eigen::VectorXd::Zero(b.size());
Eigen::VectorXd diff = Eigen::VectorXd::Zero(b.size());
while(maxit-- > 0) {
nnls_iteration(a, b, x, diff);
x += diff;
if (nnls_mean_error(x, diff) < tol) {
break;
}
}
return x;
}
void nnls_iteration(const Eigen::MatrixXd& a, Eigen::VectorXd& b, const Eigen::VectorXd& x, Eigen::VectorXd& diff) {
for (size_t i = 0; i < diff.size(); i++) {
diff(i) = std::max(b(i) / a(i, i), -x(i));
if (diff(i) != 0) { // optimization if zero is common
b -= a.col(i) * diff(i); // critical inner loop
}
}
}
double nnls_mean_error(const Eigen::VectorXd& x, const Eigen::VectorXd& diff) {
double error = 0;
for (size_t = 0; i < diff.size(); i++) {
if (x(i) != 0) {
error += std::abs(diff(i) / x(i));
}
}
return error / diff.size();
} | {
"domain": "codereview.stackexchange",
"id": 43531,
"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++, performance, eigen, rcpp, linear-algebra",
"url": null
} |
c++, performance, eigen, rcpp, linear-algebra
After modularization, it is obvious that nnls_iteration is the bottleneck and we cannot do much about it. We read each matrix element exactly once and this is a tight lower bound. The code in nnls_iteration is so simple that performance will be limited by memory bandwidth on most platforms. If the vector b is small enough to fit into L1 cache, the code is indeed optimal and cannot be improved further, assuming the compiler performs the vector-scale-and-add operation in a single pass over the vectors. With the Eigen library, this can be taken for granted (it's somewhere in the documentation).
A more interesting case arises when b is too large to fit into L1 cache. In this case, we perform two memory reads and one write per matrix element because we save and restore b once for each column of a. We can bring it back to roughly one read by processing the matrix in blocks, in this order (shown for 6 chunks of rows):
| 1| 12 |
| 2| 3| 13 |
| 4 | 5| 14 |
| 6 | 7| 15 |
| 8 | 9|16|
| 10 |11|
To make this work, we use the basic nnls_iteration for the on-diagonal blocks but we only update some rows of the b vector. We then apply the resulting diff vector to the bottom rows of b using a simplified nnls_iteration_off_diagonal before moving to the next on-diagonal block. In the end, we process the upper triangular matrix that we ignored until now and update the top rows of b that we didn't need for the on-diagonal blocks.
void nnls_iteration_off_diagonal(const Eigen::MatrixXd& a, Eigen::VectorXd& b, const Eigen::VectorXd& diff) {
for (size_t i = 0; i < diff.size(); i++) {
if (diff(i) != 0) { // optimization if zero is common
b -= a.col(i) * diff(i); // critical inner loop
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43531,
"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++, performance, eigen, rcpp, linear-algebra",
"url": null
} |
c++, performance, eigen, rcpp, linear-algebra
void nnls_iteration_chunked(const Eigen::MatrixXd& a, Eigen::VectorXd& b, const Eigen::VectorXd& x, Eigen::VectorXd& diff) {
size_t total_size = diff.size();
size_t chunk_size = 100;
// Process the below-diagonal block and then the on-diagonal block on the same row.
for (size_t begin = 0; begin < total_size; begin += chunk_size) {
size_t end = std::min(total_size, begin + chunk_size);
auto left = Eigen::seq(0, begin - 1);
auto middle = Eigen::seq(begin, end - 1);
nnls_iteration_off_diagonal(a(middle, left), b(middle), diff(left));
nnls_iteration(a(middle, middle), b(middle), x(middle), diff(middle));
}
// Process above-diagonal blocks after all on-diagonal blocks have been processed.
for (size_t begin = 0; begin < total_size; begin += chunk_size) {
size_t end = std::min(total_size, begin + chunk_size);
auto middle = Eigen::seq(begin, end - 1);
auto right = Eigen::seq(end, total_size - 1);
nnls_iteration_off_diagonal(a(middle, right), b(middle), diff(right));
}
} | {
"domain": "codereview.stackexchange",
"id": 43531,
"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++, performance, eigen, rcpp, linear-algebra",
"url": null
} |
c#, cache, asp.net-core, redis
Title: Asp.Net Core CacheKey Management
Question: I created cache management structure for Asp.Net Core and Redis. But i dont know is this best practices or bad.
My Github Repo
First one is Store my entity keys class is
public class CacheKeys
{
#region User Cache Keys
public const string GetUserKey = "user__{0}";
public const string GetUserListKey = "user__list";
#endregion
}
Second one is Create Cache Key String utility class is
public class CacheKeyUtility
{
private readonly string EnvironmentName;
public CacheKeyUtility(string environmentName)
{
EnvironmentName = environmentName ?? throw new ArgumentNullException(nameof(environmentName));
}
public string GetUserCacheKey(UserCacheType userCacheType, object? id = null) =>
userCacheType switch
{
UserCacheType.One => GetCacheKey(CacheKeys.GetUserKey, id.ToString()),
_ => GetCacheKey(CacheKeys.GetUserListKey)
};
private string GetCacheKey(string keyFormat, params string[]? formatParameters)
{
string result = $"{EnvironmentName.ToLower()}__{keyFormat.ToLower()}";
if (formatParameters != null)
{
result = string.Format(result, formatParameters);
}
return result;
}
} | {
"domain": "codereview.stackexchange",
"id": 43532,
"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#, cache, asp.net-core, redis",
"url": null
} |
c#, cache, asp.net-core, redis
}
CacheKeyUtility class has Singleton DI and EnvironmentName value in appsetting.json. DI Code is
public static IServiceCollection AddMyServiceLifeCycles(this IServiceCollection services, IConfiguration Configuration)
{
string environmentName = Configuration["Environment:EnvironmentName"];
services.AddSingleton(new CacheKeyUtility(environmentName));
services.AddScoped<IRedisCacheService, RedisCacheService>();
services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
services.AddScoped<IUserRepository, UserRepository>();
services.AddTransient<CustomExceptionHandler>();
services.AddTransient<IHashService, HashService>();
services.AddTransient<ITokenService, TokenService>();
services.AddTransient(typeof(ILogHelper<>), typeof(LogHelper<>));
return services;
}
Usage Example is
public class GetAllUserHandler : BaseHandler<GetAllUserRequest, GenericResponse<GetAllUserResponse>, GetAllUserHandler>, IRequestHandler<GetAllUserRequest, GenericResponse<GetAllUserResponse>>
{
private readonly IUserRepository _userRepository;
private readonly IRedisCacheService _redisCacheService;
private readonly CacheKeyUtility CacheKeyUtility;
public GetAllUserHandler(IHttpContextAccessor httpContextAccessor, IEnumerable<FluentValidation.IValidator<GetAllUserRequest>> validators, ILogHelper<GetAllUserHandler> logHelper, IUserRepository userRepository, IRedisCacheService redisCacheService, CacheKeyUtility cacheKeyUtility) : base(httpContextAccessor, validators, logHelper)
{
_userRepository = userRepository;
_redisCacheService = redisCacheService;
CacheKeyUtility = cacheKeyUtility;
} | {
"domain": "codereview.stackexchange",
"id": 43532,
"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#, cache, asp.net-core, redis",
"url": null
} |
c#, cache, asp.net-core, redis
public async Task<GenericResponse<GetAllUserResponse>> Handle(GetAllUserRequest request, CancellationToken cancellationToken)
{
await CheckValidate(request);
try
{
var response = new GetAllUserResponse();
string cacheKey = CacheKeyUtility.GetUserCacheKey(Shared.Enums.CacheEnums.UserCacheType.List);
var cacheUserList= await _redisCacheService.GetAsync<IEnumerable<UserDataModel>>(cacheKey);
if (cacheUserList != null && cacheUserList.Any())
{
response.UserList = cacheUserList;
response.TotalCount = cacheUserList.Count();
return GenericResponse<GetAllUserResponse>.Success(200, response);
}
var query = _userRepository.GetUserList(request.Query);
var data = await query.Select(x => new UserDataModel
{
FirstName = x.FirstName,
LastName = x.LastName,
Gsm = x.Gsm,
Id = x.Id,
Mail = x.Mail,
}).TryPagination(request.PageCount, request.PageNumber).ToListWithNoLockAsync();
await _redisCacheService.SetAsync(cacheKey, data);
response.TotalCount = await query.CountAsync();
response.UserList = data;
return GenericResponse<GetAllUserResponse>.Success(200, response);
}
catch (Exception ex)
{
_logHelper.LogError(ex);
return GenericResponse<GetAllUserResponse>.Error(500, ex.Message);
}
}
}
I think this structure is good. My question is "What are the bad points of this structure?" | {
"domain": "codereview.stackexchange",
"id": 43532,
"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#, cache, asp.net-core, redis",
"url": null
} |
c#, cache, asp.net-core, redis
I think this structure is good. My question is "What are the bad points of this structure?"
Answer: you can always use nameof to get the class name, for instance nameof(User) will return User string. So, you can depend on System.Type.Name and suffix to it the other values if you will. This would be better to avoid magic strings, and also it's supported by intellisense, and also is generics friendly, so you could do typeof(T).Name.
If you have an idea of unifying the key name of all keys by using the templates, then you could also work a way to unify the Key Format of all keys, so you have a template design that all keys will be applied on, no matter what custom template was provided, it will always have the same positions of all arguments, this would give a better handling for the key and add more customization without losing the key template maintainability.
Anyhow, for the implementation, you can use abstractions and inheritance to give more options, and free room to adopt and expand if necessary.
We can finalize CacheKeys and CacheKeyUtility into one abstraction, and then from this abstraction we can implement the concrete classes as much as needed. one way of doing it is combining them into CacheKey and use generics. here is an example :
public interface ICacheKey
{
string EnvironmentName { get; }
object Value { get; }
string FormatTemplate { get; }
IEnumerable<string> Parameters { get; }
}
public abstract class CacheKey<T> : ICacheKey
{
private const string _defaultTemplate = "{0}__{1}";
public string EnvironmentName { get; }
public string FormatTemplate { get; }
public object Value { get; }
public IEnumerable<string> Parameters { get; }
public CacheKey(string environmentName, object value, IEnumerable<string> parameters) : this(environmentName, _defaultTemplate, value, parameters) { } | {
"domain": "codereview.stackexchange",
"id": 43532,
"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#, cache, asp.net-core, redis",
"url": null
} |
c#, cache, asp.net-core, redis
public CacheKey(string environmentName, string formatTemplate, object value, IEnumerable<string> parameters)
{
EnvironmentName = environmentName ?? throw new ArgumentNullException(nameof(environmentName));
Value = value ?? string.Empty;
FormatTemplate = formatTemplate ?? _defaultTemplate;
Parameters = parameters;
}
/// <summary>
/// When called, it will return the formatted key
/// </summary>
/// <returns></returns>
public override string ToString()
{
var result = string.Format(FormatTemplate, typeof(T).Name, Value);
if (Parameters != null)
{
result = string.Format(result, Parameters);
}
return result.ToLowerInvariant();
}
}
having this base abstraction, we can do this :
public class UserCacheKey : CacheKey<User>
{
private const string _defaultEnvironmentName = "ExampleEnvironment";
public UserCacheKey(object value) : this(value, null) { }
public UserCacheKey(object value, IEnumerable<string> parameters) : base(_defaultEnvironmentName, value, parameters) { }
}
from there we can use ICacheKey on other caches and use ToString to get the formatted key. You can then extend it as needed. | {
"domain": "codereview.stackexchange",
"id": 43532,
"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#, cache, asp.net-core, redis",
"url": null
} |
haskell, ascii-art
Title: Rendering a cross in ASCII art
Question: I've recently tried to write my functions by using composition. But this one, renderCross' is especially difficult to convert fully. How would I write this composition point free? It's the n that I'm trying to make disappear. I've tried using <*>, and pointfree.io uses liftA2 (but this results in very ugly code) so I would believe I'm at least somewhat close.
Maybe I could use the Reader monad, but would that be too complicated?
renderCross :: Int -> String
renderCross = spread . unlines . flip renderCross' [""]
where
renderCross' :: Int -> [String] -> [String]
renderCross' n = edge n . vert n . horiz n . mid n . horiz n . vert n . edge n
edge :: Int -> [String] -> [String]
edge i s = s ++ [space i ++ "ooo"]
vert :: Int -> [String] -> [String]
vert i s = s ++ replicate (i - 2) (space i ++ "o|o")
horiz :: Int -> [String] -> [String]
horiz i s = s ++ [horiz' ++ "|" ++ horiz']
where
horiz' = replicate i 'o'
mid :: Int -> [String] -> [String]
mid i s = s ++ [intercalate (replicate (i - 1) '-') ["o", "o", "o"]]
space :: Int -> String
space n = replicate (n - 1) ' '
EDIT:
-- spread out word, i.e. add a space between each character
spread = intersperse ' '
Answer: Yes, you could use the Reader monad to get a pointfree version of renderCross', like this:
renderCross :: Int -> String
renderCross = spread . unlines . renderCross' [""]
where
renderCross' :: [String] -> Int -> [String]
renderCross' = runReader . (edge >=> vert >=> horiz >=> mid >=> horiz >=> vert >=> edge)
edge :: [String] -> Reader Int [String]
edge s = asks (\i -> s ++ [space i ++ "ooo"])
vert :: [String] -> Reader Int [String]
vert s = asks (\i -> s ++ replicate (i - 2) (space i ++ "o|o"))
horiz :: [String] -> Reader Int [String]
horiz s = asks (\i -> let horiz' = replicate i 'o' in s ++ [horiz' ++ "|" ++ horiz']) | {
"domain": "codereview.stackexchange",
"id": 43533,
"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": "haskell, ascii-art",
"url": null
} |
haskell, ascii-art
mid :: [String] -> Reader Int [String]
mid s = asks (\i -> s ++ [intercalate (replicate (i - 1) '-') ["o", "o", "o"]])
space :: Int -> String
space n = replicate (n - 1) ' '
This does the following:
The functions edge, vert, horiz, and mid now return a Reader Int [String], their implementations use ask to access the Int instead of using a plain function argument
renderCross' doesn't use function composition anymore, but (>=>), aka Kleisli composition. It's basically the same, but since you have functions that have a monadic return value, the simple function composition doesn't work anymore. Note that the order of composition is reversed compared to (.). You just don't see it in this example because it's the same forwards or backwards.
renderCross' uses runReader to feed in the argument to the composed function. Text-book application of the reader monad.
the type of renderCross' is different to your example. I switched the two arguments, to simplify the pointfree implementation. This has the additional benefit that you don't need to flip it in the implementation of renderCross.
So yes, it's possible to write a pointfree version of the function by using Reader. Is it better than the original version? I'm not sure. It's definitely cool to have a pointfree implementation but you have to pay the price of more concepts that are used (Reader, (>=>)). Plus, in my experience, pointfree functions tend to be harder to understand than equivalent implementations with explicit arguments. | {
"domain": "codereview.stackexchange",
"id": 43533,
"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": "haskell, ascii-art",
"url": null
} |
c++
Title: A C++ Job Manager Class
Question: I've created a JobManager class that manages the execution of submitted Jobs on periodic intervals. While the JobManager is running, the API allows the user to:
Add or Remove a Job to/from the JobManager
Change a Job's interval, function parameter, and function
Signal a Job to run if it is waiting
The testing I have done seems to denote that the class is working correctly. What stands out to you as a bad practice and or an inefficiency here? What potential problems do you see with using this? The Job could be used by itself but I haven't implemented the rule of 5 with it.
// The Job class
#pragma once
#include <chrono>
#include <any>
#include <thread>
#include <functional>
#include <condition_variable>
#include <mutex>
#include <algorithm>
#include <list>
namespace engine {
using job_clock = std::chrono::system_clock;
using job_func = std::function<void(const std::any &, bool)>;
using job_interval = std::chrono::system_clock::duration;
using job_time = std::chrono::system_clock::time_point;
class Job {
public:
Job(uint32_t job_id, job_func &&func, const job_interval &interval,
const std::any ¶m)
: id(job_id), m_func(func), m_interval(interval), m_param(param),
m_lock(std::make_shared<std::mutex>()),
m_cv(std::make_shared<std::condition_variable>())
{
}
void Start(bool now)
{
if (!m_thread) {
m_thread = std::make_unique<std::thread>(
[this](bool now) { Monitor(now); }, now);
}
}
void Stop()
{
if (m_thread) {
m_quit = true;
if (m_waiting && m_cv) {
m_cv->notify_one();
}
m_thread->join();
m_thread = nullptr;
}
} | {
"domain": "codereview.stackexchange",
"id": 43534,
"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++
void SetParam(const std::any ¶m)
{
if (m_thread && m_lock) {
std::lock_guard<std::mutex> lk(*m_lock);
m_param = param;
}
else {
m_param = param;
}
}
void SetInterval(job_interval interval)
{
if (m_thread && m_lock) {
std::lock_guard<std::mutex> lk(*m_lock);
m_interval = interval;
}
else {
m_interval = interval;
}
}
void SetFunc(job_func &&func)
{
if (m_thread && m_lock) {
std::lock_guard<std::mutex> lk(*m_lock);
m_func = func;
}
else {
m_func = func;
}
}
bool Signal()
{
if (m_waiting && m_cv) {
m_signaled = true;
m_cv->notify_one();
return true;
}
return false;
}
[[nodiscard]] bool Active() const
{
return m_active;
}
[[nodiscard]] bool Waiting() const
{
return m_waiting;
}
const uint32_t id;
private:
void Monitor(bool now)
{
m_active = true;
if (now) {
m_func(m_param, false);
}
while (!m_quit) {
job_time time = job_clock::now() + m_interval;
{
if (m_lock && m_cv) {
m_waiting = true;
std::unique_lock<std::mutex> lk(*m_lock);
m_cv->wait_until(lk, time);
m_waiting = false;
}
}
if (!m_quit && m_lock) {
std::lock_guard<std::mutex> lk(*m_lock);
m_func(m_param, m_signaled);
m_signaled = false;
}
}
m_active = false;
} | {
"domain": "codereview.stackexchange",
"id": 43534,
"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++
m_active = false;
}
std::shared_ptr<std::mutex> m_lock{nullptr};
std::shared_ptr<std::condition_variable> m_cv{nullptr};
std::shared_ptr<std::thread> m_thread{nullptr};
bool m_active{false};
bool m_signaled{false};
bool m_waiting{false};
bool m_quit{false};
job_func m_func;
job_interval m_interval;
std::any m_param;
};
} // namespace engine
// The JobManager class
#include <engine/Job.hpp>
namespace engine {
class JobManager final {
public:
JobManager(std::initializer_list<Job> jobs) : m_jobs(jobs) {}
JobManager() = default;
JobManager &operator=(const JobManager &rhs) = delete;
JobManager(const JobManager &rhs) = delete;
JobManager &operator=(JobManager &&rhs) = delete;
JobManager(JobManager &&rhs) = delete;
~JobManager()
{
Stop();
}
void Add(std::initializer_list<Job> jobs)
{
std::lock_guard<std::mutex> lk(m_lock);
for (auto &job : jobs) {
if (AddJobIfNonExistent(job)) {
m_jobs.back().Start(false);
}
}
}
void Add(const Job &job, bool run_now = false)
{
std::lock_guard<std::mutex> lk(m_lock);
if (AddJobIfNonExistent(job)) {
m_jobs.back().Start(run_now);
}
}
void Remove(uint32_t id)
{
std::lock_guard<std::mutex> lk(m_lock);
auto job = FindJobByID(id);
if (job != m_jobs.end()) {
job->Stop();
m_jobs.erase(job);
}
}
void SetJobParam(uint32_t id, const std::any ¶m)
{
std::lock_guard<std::mutex> lk(m_lock);
auto job = FindJobByID(id);
if (job != m_jobs.end()) {
job->SetParam(param);
}
} | {
"domain": "codereview.stackexchange",
"id": 43534,
"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++
void SetJobInterval(uint32_t id, job_interval interval)
{
std::lock_guard<std::mutex> lk(m_lock);
auto job = FindJobByID(id);
if (job != m_jobs.end()) {
job->SetInterval(interval);
}
}
void SetJobFunc(uint32_t id, job_func &&func)
{
std::lock_guard<std::mutex> lk(m_lock);
auto job = FindJobByID(id);
if (job != m_jobs.end()) {
job->SetFunc(std::move(func));
}
}
void Signal(uint32_t id)
{
std::lock_guard<std::mutex> lk(m_lock);
auto job = FindJobByID(id);
if (job != m_jobs.end()) {
job->Signal();
}
}
void Start()
{
std::lock_guard<std::mutex> lk(m_lock);
auto StartMonitoringJob = [](Job &job) { job.Start(false); };
ForEachJob(StartMonitoringJob);
}
void Stop()
{
std::lock_guard<std::mutex> lk(m_lock);
auto JoinAndBlock = [](Job &job) { job.Stop(); };
ForEachJob(JoinAndBlock);
}
private:
std::list<Job> m_jobs;
std::mutex m_lock;
std::list<Job>::iterator FindJobByID(uint32_t id)
{
auto IDMatch = [id](const Job &j) { return j.id == id; };
return std::find_if(m_jobs.begin(), m_jobs.end(), IDMatch);
}
bool AddJobIfNonExistent(const Job &job)
{
if (FindJobByID(job.id) == m_jobs.end()) {
m_jobs.push_back(job);
return true;
}
return false;
}
void ForEachJob(std::function<void(Job &)> predicate)
{
std::for_each(m_jobs.begin(), m_jobs.end(), predicate);
}
};
} // namespace engine
#include <spdlog/spdlog.h>
#include <engine/job_manager.hpp>
#define _dbg(f, ...) spdlog::info(f, ##__VA_ARGS__)
uint32_t JOB1_ID = 1;
uint32_t JOB2_ID = 2;
struct Job1Info {
int integer;
std::string str;
};
struct Job2Info {
int some_value;
bool other_value;
}; | {
"domain": "codereview.stackexchange",
"id": 43534,
"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++
struct Job2Info {
int some_value;
bool other_value;
};
void Job1(std::any param, bool signaled)
{
static int called = 1;
auto info = std::any_cast<Job1Info>(param);
_dbg("Job1: signaled={}, called={}, Job1Info({}, {})", signaled, called++,
info.integer, info.str);
}
void Job2(std::any param, bool signaled)
{
static int called = 1;
auto info = std::any_cast<Job2Info>(param);
_dbg("Job2: signaled={}, called={}, Job2Info({}, {})", signaled, called++,
info.some_value, info.other_value);
}
int main(int argc, char **argv)
{
using namespace std::literals::chrono_literals;
using namespace engine;
Job1Info info1{10, std::string("hello")};
Job2Info info2{50, false};
Job job1(JOB1_ID, job_func{Job1}, 5000ms, std::make_any<Job1Info>(info1));
Job job2(JOB2_ID, job_func{Job2}, 10000ms, std::make_any<Job2Info>(info2));
JobManager manager({job1, job2});
_dbg("Start");
manager.Start();
std::this_thread::sleep_for(20000ms);
manager.SetJobParam(JOB2_ID, std::make_any<Job2Info>(30, true));
manager.Remove(JOB1_ID);
std::this_thread::sleep_for(10000ms);
manager.Add(job1, true);
std::this_thread::sleep_for(20000ms);
manager.SetJobParam(JOB1_ID, std::make_any<Job1Info>(10, "something"));
std::this_thread::sleep_for(20000ms);
manager.Stop();
_dbg("end");
} | {
"domain": "codereview.stackexchange",
"id": 43534,
"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++
[2022-06-28 16:43:14.263] [info] Start
[2022-06-28 16:43:19.289] [info] Job1: signaled=false, called=1, Job1Info(10, hello)
[2022-06-28 16:43:24.291] [info] Job2: signaled=false, called=1, Job2Info(50, false)
[2022-06-28 16:43:24.291] [info] Job1: signaled=false, called=2, Job1Info(10, hello)
[2022-06-28 16:43:29.305] [info] Job1: signaled=false, called=3, Job1Info(10, hello)
[2022-06-28 16:43:34.307] [info] Job2: signaled=false, called=2, Job2Info(30, true)
[2022-06-28 16:43:44.305] [info] Job1: signaled=false, called=4, Job1Info(10, hello)
[2022-06-28 16:43:44.318] [info] Job2: signaled=false, called=3, Job2Info(30, true)
[2022-06-28 16:43:49.314] [info] Job1: signaled=false, called=5, Job1Info(10, hello)
[2022-06-28 16:43:54.325] [info] Job2: signaled=false, called=4, Job2Info(30, true)
[2022-06-28 16:43:54.325] [info] Job1: signaled=false, called=6, Job1Info(10, hello)
[2022-06-28 16:43:59.342] [info] Job1: signaled=false, called=7, Job1Info(10, hello)
[2022-06-28 16:44:04.327] [info] Job2: signaled=false, called=5, Job2Info(30, true)
[2022-06-28 16:44:04.358] [info] Job1: signaled=false, called=8, Job1Info(10, something)
[2022-06-28 16:44:09.374] [info] Job1: signaled=false, called=9, Job1Info(10, something)
[2022-06-28 16:44:14.342] [info] Job2: signaled=false, called=6, Job2Info(30, true)
[2022-06-28 16:44:14.388] [info] Job1: signaled=false, called=10, Job1Info(10, something)
[2022-06-28 16:44:19.397] [info] Job1: signaled=false, called=11, Job1Info(10, something)
[2022-06-28 16:44:24.322] [info] end | {
"domain": "codereview.stackexchange",
"id": 43534,
"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++
Answer: Use of std::shared_ptr
In Job, you store the lock, condition variable and thread in std::shared_ptrs, however that seems unnecessary. Just store those by value. The same goes for m_thread in JobManager.
Of course, this opens a can of worms, because you expect Jobs to be copyable, and by having plain std::thread and related variables in that class, it is no longer copyable. However, that is actually a good thing. Consider what happens if you copy a Job: there is only one m_thread running, but now you have two copies of m_active, m_signaled and so on. Consider doing the following:
Job job1(1, ...);
job1.Start();
JobManager manager({job1});
manager.Remove(1);
Because job1 was started before it was added to the manager, its Monitor() will use a different m_quit than when Stop() is called via manager.Remove(1), causing a deadlock.
The solution is to not have std::shared_ptrs inside Job, but instead having std::shared_ptr<Job>s passed to and stored inside JobManager, so that the code using it looks like:
auto job1 = std::make_shared<Job>(JOB1_ID, ...);
auto job2 = std::make_shared<Job>(JOB1_ID, ...);
JobManager manager({job1, job2}); | {
"domain": "codereview.stackexchange",
"id": 43534,
"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++
Now it is clear up front that jobs are passed as shared pointers, and there are no more surprises. But it is also possible to avoid std::shared_ptr altogether, which brings me to:
Let JobManager create Jobs
I think the intent is that the JobManager has full control over the Jobs it is managing. However, by letting the application create Jobs itself and pass them to JobManager, you open up the chance of misuse. It would be better if JobManager itself was creating new Jobs internally, and never exposing them to the application.
To do this, there have to be some changes in how you add jobs to a JobManager. In particular, you want to have an Add() function which takes all the parameters the constructor of Job would take:
class JobManager {
public:
...
void Add(uint32_t job_id, job_func &&func, const job_interval &interval, const std::any ¶m, bool run_now = false) {
auto &job = m_jobs.emplace_back(job_id, func, interval, param);
job.Start(run_now);
}
...
private:
std::list<Job> m_jobs;
...
};
Note that Job does not have to be copyable in order for it to be stored in a std::list.
Consider removing param
The job_func takes a std::any param as an argument, which allows you to pass arbitrary data to it. However, std::any has its issues: it's rather expensive since it allocates memory, and while it has some degree of type safety, it still allows you to pass an incorrect type, and this will only be caught at runtime instead of at compile time.
Instead, if you want to pass extra parameters to the function, consider using a lambda that captures those parameters, so that you can write:
void Job1(Job1Info &info, bool signaled) {
static int called = 1;
_dbg("Job1: signaled={}, called={}, Job1Info({}, {})",
signaled, called++, info.integer, info.str);
}
...
Job1Info info1{10, "Hello,"};
JobManager.Add(JOB1_ID, [&](bool signaled){Job1(info1, signaled);}, 5000ms); | {
"domain": "codereview.stackexchange",
"id": 43534,
"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++
Of course, if you also want to be able to change the job parameters while a job is running, you still need to do locking, for example by adding a std::mutex to the job info struct.
Improper locking
When you want to pass information between threads using some variables, make sure you always take a lock when reading from or writing to those variables, otherwise you might introduce race conditions to your code. For example, by not taking a locking when accessing m_quit, the notify in Stop() might not have any effect, because in Monitor(), you first read m_quit, which might still be false, then Stop() could set m_quit to true and notify m_cv, but only then Monitor() takes a lock and calls m_cv.wait_until(...), however that latter call will not see notifications that came before it, so it will wait for the full job interval, and if that is a large duration, it will seem like your program is hanging. | {
"domain": "codereview.stackexchange",
"id": 43534,
"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
} |
html, typescript, dom, to-do-list
Title: Refactored Todolist created using TS
Question: After getting the code review I refactored the code and the updated version is below.
I tried implementing the suggestions but because I am still learning I might refactor again after learning how to implement classes.
previous post: Created a todo list in TS
index.ts
import { v4 as uuidv4 } from 'uuid';
const addTaskBtn = document.querySelector('#add-btn') as HTMLButtonElement
const input = document.querySelector("#input") as HTMLInputElement
const ul = document.querySelector("#todoList") as HTMLUListElement
// array which stores the object
let todos:Array<Todo> = []
let updatingObject: Todo;
interface Todo {
id: string;
todo: string;
completed: boolean;
createdDate: Date;
updatedDate?: Date;
}
// creating objects that are stored in the array
const storeObject = (todo: string)=>{
todos.push({
id: uuidv4(),
todo: todo,
completed: false ,
createdDate: new Date(),
})
}
const renderTodos = ()=> {
// iterating over every object in array
todos.forEach((obj)=>{
const div = document.createElement("div");
div.classList.add("item")
const li = document.createElement("li");
li.classList.add("todo")
const checkbox = document.createElement("input")
checkbox.type = "checkbox"
if(obj.completed === true) checkbox.checked = true
const label = document.createElement("label")
label.textContent = obj.todo
label.htmlFor = `${obj.id}`
checkbox.addEventListener("click",()=>{
todos = todos.map(item=>{
if(item.id == obj.id ){
return {...obj,completed:!obj.completed}
}
return item
})
ul.innerText =""
renderTodos()
}) | {
"domain": "codereview.stackexchange",
"id": 43535,
"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": "html, typescript, dom, to-do-list",
"url": null
} |
html, typescript, dom, to-do-list
const btns = document.createElement("div");
const editBtn = document.createElement("button") as HTMLButtonElement
editBtn.textContent = "Edit "
editBtn.classList.add("editBtn")
editBtn.addEventListener("click",()=> updateTodo(obj))
const deleteBtn = document.createElement("button") as HTMLButtonElement
deleteBtn.textContent = "Delete"
deleteBtn.classList.add("deleteBtn")
deleteBtn.addEventListener("click",(e)=>{
// removing todo form array
deleteTodo(obj)
})
btns.appendChild(editBtn)
btns.appendChild(deleteBtn)
li.appendChild(checkbox)
li.appendChild(label)
div.appendChild(li);
div.appendChild(btns);
ul.appendChild(div);
})
}
const deleteTodo = (obj: Todo)=>{
// removed from array
todos = todos.filter((item)=>{
if(item.id !== obj.id){
return item
}
})
ul.innerText =""
renderTodos()
}
const updateArray = (updatingObject:Todo)=>{
let newTodo:string = input.value
todos = todos.map(item=>{
if(item.id === updatingObject.id){
return {...updatingObject,todo: newTodo}
}
return item
})
}
const updateTodo = (obj:Todo)=>{
input.value = obj.todo;
addTaskBtn.textContent = "Update"
updatingObject = obj
}
addTaskBtn.addEventListener("click",(e)=>{
if(input.value === "" || !(e.target instanceof HTMLElement) ) return
if(((e.target)as HTMLButtonElement).innerText == "Add Task"){
// push the todo in the array
storeObject(input.value)
input.value = ""
ul.innerText = ""
renderTodos()
}else{
updateArray(updatingObject)
ul.innerText = ""
input.value = ""
addTaskBtn.innerText = "Add Task"
renderTodos()
}
}); | {
"domain": "codereview.stackexchange",
"id": 43535,
"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": "html, typescript, dom, to-do-list",
"url": null
} |
html, typescript, dom, to-do-list
index.html
<main>
<div class="top">
<input type="text" name="todo-input" id="input" value="" placeholder="TODO" >
<button id="add-btn" class="add-btn">Add Task</button>
</div>
<ul id="todoList">
</ul>
</main>
I want to know if I have made any improvements from the previous version
How can I improve it?
Live version: https://codesandbox.io/s/recursing-black-wtbhob?file=/index.html
Answer: This implements the basics of a class to wrap the code, and shows how event listeners can be targetted at the class instance.
Because the class constructs the necessary HTML framework into a container element, it can keep internal references to those elements so its much easier to make changes and there is no need to deal with failed querySelector calls or type assertions for specific HTML element types.
My recommendations on the original post still stand, there is still much that could be done to better align the code with the DOM/CSS.
index.ts
import "./styles.css";
import { v4 as uuidv4 } from "uuid";
interface Todo {
id: string;
todo: string;
completed: boolean;
createdDate: Date;
updatedDate?: Date;
}
class TodoApp {
private todos: Todo[] = [];
private updatingTodo: Todo | undefined;
private readonly main: HTMLElement;
private readonly top: HTMLElement;
private readonly input: HTMLInputElement;
private readonly button: HTMLButtonElement;
private readonly ul: HTMLUListElement; | {
"domain": "codereview.stackexchange",
"id": 43535,
"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": "html, typescript, dom, to-do-list",
"url": null
} |
html, typescript, dom, to-do-list
constructor(container: HTMLElement) {
this.main = document.createElement("main");
this.top = document.createElement("div");
this.top.classList.add("top");
this.input = document.createElement("input");
this.input.name = "todo-input";
this.input.id = "input";
this.input.type = "text";
this.input.value = "";
this.input.placeholder = "TODO";
this.button = document.createElement("button");
this.button.id = "add-btn";
this.button.classList.add("add-btn");
this.button.innerText = "Add Task";
this.button.addEventListener("click", this.onButtonClick.bind(this));
this.top.appendChild(this.input);
this.top.appendChild(this.button);
this.ul = document.createElement("ul");
this.ul.classList.add("todoList");
this.main.appendChild(this.top);
this.main.appendChild(this.ul);
container.appendChild(this.main);
this.render();
}
render() {
while (this.ul.firstChild) {
this.ul.removeChild(this.ul.firstChild);
}
this.todos.forEach((todo) => {
const div = document.createElement("div");
div.classList.add("item");
const li = document.createElement("li");
li.classList.add("todo");
const label = document.createElement("label");
label.textContent = todo.todo;
label.htmlFor = todo.id;
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.checked = todo.completed;
checkbox.id = todo.id;
checkbox.addEventListener("click", this.onTodoChecked.bind(this, todo));
const btns = document.createElement("div"); | {
"domain": "codereview.stackexchange",
"id": 43535,
"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": "html, typescript, dom, to-do-list",
"url": null
} |
html, typescript, dom, to-do-list
const btns = document.createElement("div");
const editBtn = document.createElement("button");
editBtn.textContent = "Edit";
editBtn.classList.add("editBtn");
editBtn.addEventListener("click", this.onEditButtonClick.bind(this, todo));
const deleteBtn = document.createElement("button");
deleteBtn.textContent = "Delete";
deleteBtn.classList.add("deleteBtn");
deleteBtn.addEventListener("click", this.onDeleteButtonClick.bind(this, todo));
btns.appendChild(editBtn);
btns.appendChild(deleteBtn);
li.appendChild(checkbox);
li.appendChild(label);
div.appendChild(li);
div.appendChild(btns);
this.ul.appendChild(div);
});
if (this.updatingTodo === undefined) {
this.button.textContent = "Add Task";
} else {
this.button.textContent = "Update Task";
}
}
onButtonClick(ev: Event) {
if (this.input.value === "") {
return;
}
if (this.updatingTodo) {
this.updatingTodo.todo = this.input.value;
this.updatingTodo = undefined;
} else {
this.appendTodo(this.input.value);
}
this.input.value = "";
this.render();
}
onEditButtonClick(todo: Todo) {
this.input.value = todo.todo;
this.updatingTodo = todo;
this.render();
}
onDeleteButtonClick(todo: Todo) {
this.todos = this.todos.filter((existing) => existing.id !== todo.id);
this.render();
}
onTodoChecked(todo: Todo) {
todo.completed = !todo.completed;
this.render();
}
appendTodo(todo: string) {
this.todos.push({
id: uuidv4(),
todo: todo,
completed: false,
createdDate: new Date()
});
}
}
const container = document.querySelector("#app");
if (container && container instanceof HTMLElement) {
new TodoApp(container);
}
index.html
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head> | {
"domain": "codereview.stackexchange",
"id": 43535,
"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": "html, typescript, dom, to-do-list",
"url": null
} |
html, typescript, dom, to-do-list
index.html
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app" />
<script src="src/index.ts"></script>
</body>
</html>
style.css
Remains as original post. | {
"domain": "codereview.stackexchange",
"id": 43535,
"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": "html, typescript, dom, to-do-list",
"url": null
} |
javascript, linked-list
Title: Doubly Linked List Javascript
Question: A doubly linked list contains elements that include pointers to the previous and next element along with a value. This data structure is implemented with methods similar to what you would find in an array: insert or remove elements, read the value at an index or find an index that contains a value.
Just looking to see if my implementation is good. Did I make any mistakes? Did I do anything unusual?
function Node(v, p, n) {
this.v = v;
this.p = p;
this.n = n;
}
function DoublyLinkedList() {
this.size = 0;
this.head = null;
this.tail = null;
this.append = (v) => {
if (this.size === 0) {
this.head = this.tail = new Node(v, null, null);
} else {
this.tail.n = new Node(v, this.tail, null);
this.tail = this.tail.n;
}
this.size++;
};
this.prepend = (v) => {
if (this.size === 0) {
this.head = this.tail = new Node(v, null, null);
} else {
this.head.p = new Node(v, null, this.head);
this.head = this.head.p;
}
this.size++;
};
this.find = (v) => {
let current = this.head;
let index = -1;
while (current) {
index++;
if (current.v === v) {
return index;
} else {
current = current.n;
}
}
return -1;
};
this.read = (v) => {
if (v >= this.size) return null;
let current = this.head;
let step = 0;
while (step < v) {
step++;
current = current.n;
}
return current.v;
};
this.insert = (v, i) => {
let current = this.head;
let step = 0;
if (i === 0) {
this.prepend(v);
} else if (i === this.size) {
this.append(v);
} else {
while (step < i) {
step++;
current = current.n;
}
current.p.n = current.p = new Node(v, current.p, current);
this.size++;
}
};
this.remove = (i) => {
let current = this.head;
let step = 0; | {
"domain": "codereview.stackexchange",
"id": 43536,
"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, linked-list",
"url": null
} |
javascript, linked-list
this.remove = (i) => {
let current = this.head;
let step = 0;
if (i === 0 && this.size === 1) {
this.head = this.tail = null;
} else if (i === 0) {
this.head = this.head.n;
this.head.p = null;
} else if (i === this.size - 1) {
this.tail = this.tail.p;
this.tail.n = null;
} else {
while (step < i) {
step++;
current = current.n;
}
current.p.n = current.n;
current.n.p = current.p;
current.v = current.p = current.n = null;
}
this.size--;
};
}
```
Answer: First, a bug: read() doesn't properly check negative indices; list.read(-42) currently returns the first value (or throws an exception on an empty list).
As slepic pointed out, unless you want to support dinosaur browsers, you should be using class syntax instead of constructor functions; The way you have it right now, every DoublyLinkedList you create has a copy of every method stored on each individual object. The performance implications are not good. The class syntax automatically puts methods on the prototype instead, which also allows inheritance. (You don't need to understand prototypes unless you're doing something fancy, just stick to class syntax.)
I'm not sure I like using single letters for your member and parameter names. You definitely shouldn't be using "i" as a parameter name, since i is typically used as the index variable in a loop, making it very confusing.
insert(value, index) is confusing, the idiom would be insert(index, value).
The name "Node" already exists in JavaScript. This isn't a problem if your code is in a module, but otherwise might accidentally shadow the original.
Your code should probably return undefined for missing elements instead of null, here're some reasons:
Users might want to store null in the list.
It's consistent with Array and Map.
It plays nice with the optional chaining operator ?. (which returns undefined).
typeof null === "object" (all sorts of horrifying). | {
"domain": "codereview.stackexchange",
"id": 43536,
"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, linked-list",
"url": null
} |
javascript, linked-list
I also prefer using undefined internally so that I can pretend null doesn't exist.
size should be externally readonly; This means that the list can change its own size, but the user can't accidentally set size to some incorrect number. You can do this by using a private field and a public getter.
There are a couple bits of code that can be factored out: Getting a Node from an index and inserting before/after a given Node. This simplifies code and prevents mistakes/unmaintainability due to repetition.
class DoublyLinkedList {
// The hashtag at the start of member names makes them private
// (you might also come across code that uses underscores _ instead).
// Predeclaring field names like this is optional for public fields.
#head;
#tail;
// size is private to avoid user messing with it;
// We'll give them access with a getter instead:
#size;
// This is a getter; It acts like a normal field, but the user
// can only read it (i.e. they cannot set the size themselves).
get size() { return this.#size; }
// This is assuming you don't want to expose these functions publicly.
#getNode(index) {
if (index < 0 || index >= this.#size) return undefined;
let current = this.#head;
for (let step = 0; step < index; ++step) {
current = current.n;
}
return current;
}
#insertBefore(node, value) {
const newNode = new Node(value, node.p, node);
if (node.p) node.p.n = newNode;
else this.#head = newNode;
node.p = newNode;
++this.#size;
}
// Doesn't really refactor anything, but it'd be weird not to have:
#insertAfter(node, value) {
const newNode = new Node(value, node, node.n);
if (node.n) node.n.p = newNode;
else this.#tail = newNode;
node.n = newNode;
++this.#size;
}
// With this, you can refactor your class as: | {
"domain": "codereview.stackexchange",
"id": 43536,
"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, linked-list",
"url": null
} |
javascript, linked-list
++this.#size;
}
// With this, you can refactor your class as:
constructor() {
this.#size = 0;
this.#head = undefined;
this.#tail = undefined;
}
append(value) {
if (this.#size === 0) {
this.#head = this.#tail = new Node(value, undefined, undefined);
this.#size = 1;
return;
}
this.#insertAfter(this.#tail, value);
}
prepend(value) {
if (this.#size === 0) return this.append(value); // Reusing append
this.#insertBefore(this.#head, value);
}
find(value) {
let current = this.#head;
// Using a for-loop is cleaner:
for (let i = 0; current; ++i) {
if (current.v === value) return i;
current = current.n;
}
return -1;
}
read(index) { // Original's parameter had a typo: read(v) -> read(index)
const node = this.#getNode(index);
if (node) return node.v;
return undefined;
// Shorter using optional chaining: return this.#getNode(index)?.v;
}
// This function should return true/false to indicate success.
// I'd personally throw an Error on failure instead,
// since something's gone wrong if you have the wrong index.
// Your code does unintentionally throw an Error as-is,
// but the error message isn't appropriate.
// Also note the swapped parameter order.
insert(index, value) {
if (index < 0 || index > this.#size) return false;
if (index === this.#size) {
this.append(value);
return true;
}
this.#insertBefore( this.#getNode(index), value );
return true;
}
// Following Array's conventions, this should return the removed value
// or undefined if it didn't exist (could also throw Error).
remove(index) {
const node = this.#getNode(index);
if (!node) return undefined; | {
"domain": "codereview.stackexchange",
"id": 43536,
"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, linked-list",
"url": null
} |
javascript, linked-list
// Instead of having many special cases based on the index and list's size,
// just check if node the has neighbours and act accordingly.
// This is cleaner than having cases for every possible combination
// of the p and n nodes existing.
if (node.p) node.p.n = node.n;
else this.#head = node.n;
if (node.n) node.n.p = node.p;
else this.#tail = node.p;
--this.#size;
return node.v;
}
}
A few suggestions:
Currently, none of your code really needs the list to be doubly linked; You could switch to a singly linked list instead and save memory/performance/complexity, or you could add things like a reverse iterator which lets the user take advantage of it.
You could modify your functions to check if the index is more than halfway through the list and iterate backward if so. This would half the average number of nodes you need to traverse (though it might perform worse on small lists).
Don't let my rant discourage you though, good work! | {
"domain": "codereview.stackexchange",
"id": 43536,
"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, linked-list",
"url": null
} |
c++, ai, sfml, connect-four
Title: C++ Connect 4 in SFML
Question: After a substantial amount of programming experience in high level languages like Javascript and Python, I decided to try learning a low level language for once, so I did C++. As my first project I made a graphical connect 4 game, which also has a computer ai implemented in it, using the Monte Carlo Tree Search algorithm. I represent the connect 4 board using 64 bit numbers (1 means there is a piece there, 0 means there isn't). I do this just to make the game logic simpler to make (it is easier to calculate moves, check wins, etc).
Here are the files:
common.h (this is just global variables)
#pragma once
#include <cstdint>
extern uint64_t bits[42];
extern uint64_t columns[7];
extern uint64_t combinations[69];
extern int aiPlayer; | {
"domain": "codereview.stackexchange",
"id": 43537,
"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++, ai, sfml, connect-four",
"url": null
} |
c++, ai, sfml, connect-four
computerPlayer.cpp (my implimentation of the Monte Carlo Tree Search algorithm)
#include "common.h"
#include "node.h"
#include "game.h"
#include "computerPlayer.h"
#include <cstdint>
#include <vector>
#include <cstdlib>
#include <math.h>
int ComputerPlayer::bestMove(uint64_t redBoard, uint64_t yellowBoard, uint64_t bothBoards, int searcherSide) {
nodes.clear();
selectedNodeIndex = 0;
node rootNode;
rootNode.redBoard = redBoard;
rootNode.yellowBoard = yellowBoard;
rootNode.bothBoards = bothBoards;
rootNode.wins = 0.0;
rootNode.simulations = 0.0;
rootNode.sideToPlay = searcherSide;
// Assume that the position we are searching to begin with is not given to be terminal.
rootNode.terminalStatus = 0;
rootNode.parentNodeIndex = -1;
nodes.push_back(rootNode);
for (int i = 0; i < 100000; i++) {
expand();
simulate();
propogate();
select();
}
std::vector<int> rootNodeChildNodesIndices = nodes[0].childNodesIndices;
uint64_t bestBothBoards;
double bestSimulations = 0.0;
for (auto rootNodeChildNodeIndex : rootNodeChildNodesIndices) {
node childNode = nodes[rootNodeChildNodeIndex];
uint64_t childNodeBothBoards = childNode.bothBoards;
double childNodeSimulations = childNode.simulations;
if (childNodeSimulations > bestSimulations) {
bestBothBoards = childNodeBothBoards;
bestSimulations = childNodeSimulations;
}
}
std::vector<int> rootMoves = moves(bothBoards);
int bestMove;
for (auto rootMove : rootMoves) {
uint64_t rootMoveBit = bits[moveTargetSquare(rootMove, bothBoards)];
if ((bothBoards | rootMoveBit) == bestBothBoards) {
bestMove = rootMove;
break;
}
}
return bestMove;
}
void ComputerPlayer::expand() {
node selectedNode = nodes[selectedNodeIndex];
if (selectedNode.terminalStatus != 0) {
return;
}
uint64_t selectedNodeRedBoard = selectedNode.redBoard;
uint64_t selectedNodeYellowBoard = selectedNode.yellowBoard; | {
"domain": "codereview.stackexchange",
"id": 43537,
"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++, ai, sfml, connect-four",
"url": null
} |
c++, ai, sfml, connect-four
uint64_t selectedNodeYellowBoard = selectedNode.yellowBoard;
uint64_t selectedNodeBothBoards = selectedNode.bothBoards;
int selectedNodeSideToPlay = selectedNode.sideToPlay;
std::vector<int> selectedNodeMoves = moves(selectedNodeBothBoards);
for (auto selectedNodeMove : selectedNodeMoves) {
node childNode;
uint64_t childNodeRedBoard = selectedNodeRedBoard;
uint64_t childNodeYellowBoard = selectedNodeYellowBoard;
uint64_t childNodeBothBoards = selectedNodeBothBoards;
uint64_t childNodeMoveBit = bits[moveTargetSquare(selectedNodeMove, childNodeBothBoards)];
if (selectedNodeSideToPlay == 0) {
childNodeRedBoard |= childNodeMoveBit;
} else {
childNodeYellowBoard |= childNodeMoveBit;
}
childNodeBothBoards |= childNodeMoveBit;
int childNodeTerminalStatus = 0;
if (childNodeBothBoards == 4398046511103ULL) {
childNodeTerminalStatus = 1;
} else if (selectedNodeSideToPlay == 0) {
if (isWinning(childNodeRedBoard)) {
childNodeTerminalStatus = 2;
}
} else {
if (isWinning(childNodeYellowBoard)) {
childNodeTerminalStatus = 3;
}
}
childNode.redBoard = childNodeRedBoard;
childNode.yellowBoard = childNodeYellowBoard;
childNode.bothBoards = childNodeBothBoards;
childNode.wins = 0.0;
childNode.simulations = 0.0;
childNode.sideToPlay = selectedNodeSideToPlay ^ 1;
childNode.terminalStatus = childNodeTerminalStatus;
childNode.parentNodeIndex = selectedNodeIndex;
nodes[selectedNodeIndex].childNodesIndices.push_back(nodes.size());
nodes.push_back(childNode);
}
}
void ComputerPlayer::simulate() {
node selectedNode = nodes[selectedNodeIndex];
int selectedNodeTerminalStatus = selectedNode.terminalStatus;
if (selectedNodeTerminalStatus == 1) {
nodes[selectedNodeIndex].wins += 0.5;
nodes[selectedNodeIndex].simulations += 1.0;
return;
} else if (selectedNodeTerminalStatus == 2) { | {
"domain": "codereview.stackexchange",
"id": 43537,
"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++, ai, sfml, connect-four",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.