text stringlengths 1 2.12k | source dict |
|---|---|
python, beginner, object-oriented, hangman
def generate_word(self):
return self.word
def fill_blanks(self, hm):
self.filled = ""
for i in range(0, len(hm.get_word())):
if hm.get_word()[i] in hm.get_successful_letters():
self.filled += hm.get_word()[i]
else:
self.filled += "_"
return self.filled
def display(self, hm):
print(hm.get_man())
print(self.fill_blanks(hm))
print(f"Incorrect Letters Guessed {hm.get_missed_letters()}")
def play(self):
hm = HangManData(self.generate_word())
while True:
self.display(hm)
if hm.get_word() == "":
break
elif "_" not in self.fill_blanks(hm):
print("Congrats!")
break
elif hm.remaining_chances == 0:
print(f"The Word Was {hm.get_word()}")
break
else:
guessed_letter = input("Guess A Letter: ").upper()
if guessed_letter == "QUIT":
print(f"The Word Was {hm.get_word()}")
break
elif guessed_letter in hm.get_missed_letters() or guessed_letter in hm.get_successful_letters():
print("You Already Guessed This Letter")
elif guessed_letter in hm.get_word():
number_of_appearances = hm.get_word().count(guessed_letter)
if number_of_appearances == 1:
print(f"{guessed_letter} Appears Once In The Word")
else:
print(f"{guessed_letter} Appears {number_of_appearances} Times In The Word")
hm.set_successful_letters(guessed_letter)
else:
hm.set_missed_letters(guessed_letter)
hm.remaining_chances -= 1 | {
"domain": "codereview.stackexchange",
"id": 42629,
"lm_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, object-oriented, hangman",
"url": null
} |
python, beginner, object-oriented, hangman
def main():
play = True
while play:
u = UI()
u.play()
while True:
print("Play Again?")
play_again = input("Y/n > ").upper()
if play_again == "Y":
print("Setting Up...")
break
elif play_again == "N":
print("Goodbye")
play = False
break
else:
print("Invalid Input")
if __name__ == "__main__":
main()
Answer: This is the final code I'm content with. I'll definitely be doing more mini projects like this to improve my OOP skills.
I've added a is_invalid and appearances(returning a private variable) method in the HangManData class as well as making add_guess return false if the letter has already been guessed, and true if it hasnt allowing me to simplify the UI a little more. add_guess also defines _appearances because it was initially checking for the value anyways.
import random
from phases import hang_phases
class HangManData:
def __init__(self, word):
self.word = word
self.guesses = []
self._hits = []
self._misses = []
self._appearances = 0
def add_guess(self, letter):
if letter in self.guesses:
return False
else:
self.guesses.append(letter)
self._appearances = self.word.count(letter)
xs = self._hits if self.appearances > 0 else self._misses
xs.append(letter)
xs.sort()
return True
@property
def is_invalid(self):
return self.word == ""
@property
def appearances(self):
return self._appearances
@property
def hits(self):
return self._hits
@property
def misses(self):
return self._misses
@property
def remaining_chances(self):
return 9 - len(self._misses)
@property
def is_dead(self):
return self.remaining_chances <= 0 | {
"domain": "codereview.stackexchange",
"id": 42629,
"lm_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, object-oriented, hangman",
"url": null
} |
python, beginner, object-oriented, hangman
@property
def is_dead(self):
return self.remaining_chances <= 0
@property
def is_solved(self):
return all(letter in self._hits for letter in self.word)
@property
def diagram(self):
return hang_phases[self.remaining_chances]
@property
def display_word(self):
return ' '.join(
letter if letter in self._hits else '_'
for letter in self.word
)
class UI:
def __init__(self):
self.word_list = open('Words').read().split("\n")
self.word = random.choice(self.word_list).upper()
@staticmethod
def display(hm):
print(hm.word) # Left this here for testing purposes, prints word being looked for
print(hm.diagram)
print(hm.display_word)
print(f"Incorrect Letters Guessed {hm.misses}")
def generate_word(self):
return self.word | {
"domain": "codereview.stackexchange",
"id": 42629,
"lm_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, object-oriented, hangman",
"url": null
} |
python, beginner, object-oriented, hangman
def generate_word(self):
return self.word
def play(self):
hm = HangManData(self.generate_word())
while True:
self.display(hm)
if hm.is_invalid:
print("Invalid Word Was Generated")
break
elif hm.is_solved:
print("Congrats!")
break
elif hm.is_dead:
print(f"The Word Was {hm.word}")
break
else:
guessed_letter = input("Guess A Letter: ").upper()
if guessed_letter == hm.word:
print("Congrats!")
break
else:
check_added = hm.add_guess(guessed_letter)
if guessed_letter == "QUIT":
print(f"The Word Was {hm.word}")
break
elif not check_added:
print("You Already Guessed This Letter")
else:
if hm.appearances == 1:
print(f"{guessed_letter} Appears Once In The Word")
else:
print(f"{guessed_letter} Appears {hm.appearances} Times In The Word")
def main():
play = True
while play:
u = UI()
u.play()
while True:
print("Play Again?")
play_again = input("Y/n > ").upper()
if play_again == "Y":
print("Setting Up...")
break
elif play_again == "N":
print("Goodbye")
play = False
break
else:
print("Invalid Input")
if __name__ == "__main__":
main()
``` | {
"domain": "codereview.stackexchange",
"id": 42629,
"lm_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, object-oriented, hangman",
"url": null
} |
c++, constructor
Title: GameObject - Component hierarchy, component can access game object in constructor
Question: While creating a game engine using c++, when defining a component, I was tired of writing down essential but repeated elements such as 'GameObject* parent' every time I define a new component constructor.
So I thought of a shortcut. It's debatable, and I feel it can be improved.
When I need to create many different components, the following code is sufficient to disable the 'C6011', 'C26495' warnings?
Any potential problems with this code?
Is there a better way?
concept
Create a component class using malloc.
Enter the value of component begin.
Call the component`s constructor.
ComponentType* mptr = (ComponentType*)malloc(sizeof(ComponentType));
mptr->_begin = new Initialize(owner_game_object_ptr);
new(mptr) ComponentType(std::forward<Args>(args)...);
return mptr:
code
#pragma once
#include <memory>
#include <list>
#include <string>
#include <algorithm>
#include <iostream>
struct Initialize;
class GameObject;
class ComponentConstructor;
struct Initialize
{
GameObject* owner;
Initialize() = delete;
Initialize(const Initialize&) = delete;
Initialize(Initialize&&) = delete;
Initialize(GameObject* owner_game_object) :
owner(owner_game_object)
{}
};
class Component
{
private:
Initialize* _begin;
public:
__declspec(property(get = get_initialize)) Initialize* begin;
inline const Initialize* get_initialize() { return _begin; }
public:
Component() = default;
virtual ~Component() = default;
friend GameObject;
friend ComponentConstructor;
};
class ComponentConstructor
{
std::unique_ptr<Initialize> begin;
Component* component;
public:
ComponentConstructor()
: component(nullptr)
{}
~ComponentConstructor()
{
if (component != nullptr)
{
component->~Component();
free(component);
}
} | {
"domain": "codereview.stackexchange",
"id": 42630,
"lm_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++, constructor",
"url": null
} |
c++, constructor
void make_begin(GameObject* owner)
{
begin = std::make_unique<Initialize>(owner);
}
template <typename Type, typename... Args
, typename = typename std::enable_if<std::is_convertible<Type, Component>::value>::type
>
void make_component(Args&&... args)
{
Type* mptr = (Type*)malloc(sizeof(Type));
mptr->_begin = begin.get();
new(mptr) Type(std::forward<Args>(args)...);
component = mptr;
}
friend GameObject;
};
/*
for use initialize in derived component
*/
class GameObject
{
public:
std::string name;
GameObject(const std::string& object_name) : name(object_name)
{}
private:
std::list<std::unique_ptr<ComponentConstructor>> child_components;
public:
template <typename Type, typename... Args
, typename = typename std::enable_if<std::is_convertible<Type, Component>::value>::type
>
Type* add_component(Args&&... args)
{
child_components.emplace_back();
auto& elum = child_components.back();
elum = std::make_unique<ComponentConstructor>();
elum->make_begin(this);
elum->make_component<Type>(std::forward<Args>(args)...);
return static_cast<Type*>(elum->component);
}
void remove_component(Component* component)
{
auto it = std::find_if(child_components.begin(), child_components.end(),
[component](const std::unique_ptr<ComponentConstructor>& child_component)
{
return child_component->component == component;
});
if (it != child_components.end())
child_components.erase(it);
}
}; | {
"domain": "codereview.stackexchange",
"id": 42630,
"lm_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++, constructor",
"url": null
} |
c++, constructor
if (it != child_components.end())
child_components.erase(it);
}
};
use
class GameObjectComponent : public Component
{
GameObjectComponent()
{
std::cout << "GameObjectComponent is created" << std::endl;
}
~GameObjectComponent()
{
std::cout << "GameObjectComponent is deleted" << std::endl;
}
friend ComponentConstructor;
};
class CheckNameComponent : public Component
{
CheckNameComponent()
{
std::cout << "CheckNameComponent is created" << std::endl;
if (begin->owner->name == "Game object")
begin->owner->add_component<GameObjectComponent>();
}
~CheckNameComponent()
{
std::cout << "CheckNameComponent is deleted" << std::endl;
}
friend ComponentConstructor;
};
int main()
{
GameObject object("Game object");
object.add_component<CheckNameComponent>();
}
Answer: It looks like you have two motivations here:
Remove repetition of passing the owning GameObject* around.
Ensure that Components can add other components to their owning GameObject inside the Component constructor.
1 - Passing GameObject*s:
I wouldn't worry about having to pass the owning GameObject* around. Assuming our base Component class looks something like this:
class Component
{
private:
GameObject* owner;
public:
virtual ~Component() { }
GameObject* get_owner() const { return owner; }
protected:
explicit Component(GameObject* owner):
owner(owner) { }
};
All our component classes will take the owner pointer in a constructor and pass it to their base Component:
explicit CheckNameComponent(GameObject* owner):
Component(owner) { ... }
Where the GameObject pointer is passed as the first argument in GameObject::add_component:
std::make_unique<ComponentT>(this, std::forward<Args>(args)...); | {
"domain": "codereview.stackexchange",
"id": 42630,
"lm_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++, constructor",
"url": null
} |
c++, constructor
The only repeated "boilerplate" code here is the two lines in every component:
explicit CheckNameComponent(GameObject* owner):
Component(owner) { ... }
This is completely fine. It's not something that needs to be replaced with a very complicated system of construction using placement new and inheritance.
2 - Adding Components from Component constructors:
I think the problem here is with add_component being called recursively, e.g.:
CheckNameComponent()
{
std::cout << "CheckNameComponent is created" << std::endl;
if (begin->owner->name == "Game object")
begin->owner->add_component<GameObjectComponent>();
}
We need to be careful with ordering things so that:
We return the correct pointer from add_component.
Reallocation from recursive calls doesn't move our objects in memory (which I guess is why std::list is used instead of std::vector).
Certain rules are enforced with the order of construction of "child" components. (i.e. can a component added by an add_component call in a component constructor check that it's "parent" component exists on the owning game object? so could GameObjectComponent do begin->owner->get_component<CheckNameComponent>?) | {
"domain": "codereview.stackexchange",
"id": 42630,
"lm_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++, constructor",
"url": null
} |
c++, constructor
That last one is kinda hard to solve. It's up to you what exactly you want to do in this situation. Since the CheckNameComponent constructor hasn't returned, we can't guarantee that the object is "safe" to use in GameObjectComponent. But we could perhaps try to guarantee that GameObjectComponent can get a pointer to CheckNameComponent.
Personally I wouldn't try to make this guarantee! I think it's fine to document that components are not there in the GameObject (and can't be accessed) until add_component returns successfully.
Then we can use a std::vector<std::unique_ptr<Component>> for the components, and create the component before we add space for it in the component list:
template<class ComponentT, class... Args>
ComponentT* add_component(Args&&... args)
{
auto component = std::make_unique<ComponentT>(this, std::forward<Args>(args)...);
auto result = component.get();
components.push_back(std::move(component));
return result;
}
If a "child" component needs to be added, and needs access to its parent, it's up to the writer of the Component class to explicitly pass the relevant dependencies, e.g.:
explicit CheckNameComponent(GameObject* owner):
Component(owner)
{
if (get_owner()->name == "Game object")
get_owner()->add_component<OtherComponent>(this); // pass the needed pointer
}
explicit OtherComponent(GameObject* owner, CheckNameComponent* check_name):
Component(owner)
{
// use `check_name` here... it's up to the programmer to ensure we only access valid state
}
So overall I'm not sure the added complexity is worth it. I think the same thing can be achieved like so:
#include <iostream>
#include <memory>
#include <vector>
class Component;
class GameObject
{
public:
explicit GameObject(std::string const& name):
name(name) { } | {
"domain": "codereview.stackexchange",
"id": 42630,
"lm_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++, constructor",
"url": null
} |
c++, constructor
class GameObject
{
public:
explicit GameObject(std::string const& name):
name(name) { }
template<class ComponentT, class... Args>
ComponentT* add_component(Args&&... args)
{
auto component = std::make_unique<ComponentT>(this, std::forward<Args>(args)...);
auto result = component.get();
components.push_back(std::move(component));
return result;
}
std::string name;
private:
std::vector<std::unique_ptr<Component>> components;
};
class Component
{
private:
GameObject* owner;
public:
virtual ~Component() { }
GameObject* get_owner() const { return owner; }
protected:
explicit Component(GameObject* owner):
owner(owner) { }
};
class OtherComponent;
class CheckNameComponent : public Component
{
public:
explicit CheckNameComponent(GameObject* owner):
Component(owner)
{
if (get_owner()->name == "Game object")
{
get_owner()->add_component<OtherComponent>();
}
}
};
class OtherComponent : public Component
{
public:
explicit OtherComponent(GameObject* owner):
Component(owner)
{
std::cout << "OtherComponent constructor\n";
}
~OtherComponent()
{
std::cout << "OtherComponent destructor\n";
}
};
int main()
{
{
auto object = GameObject("Game object");
object.add_component<CheckNameComponent>();
}
std::cout << std::flush;
} | {
"domain": "codereview.stackexchange",
"id": 42630,
"lm_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++, constructor",
"url": null
} |
c++, constructor
std::cout << std::flush;
}
Some other things:
(Although I've suggested removing / changing most of your code above, here are some comments about your code as it exists at the moment).
Naming:
Initialize is not a good name for a class. Classes should usually use nouns for names, not verbs. Something like ComponentOwner or just ComponentBase might be better.
The name begin is nearly always used in C++ for something specific (the first iterator in a sequence), so it shouldn't be used for something else. This variable should probably be named after the Initialize class (so owner or base if you use my suggestions above).
malloc:
In C++ we should use the global operator new to allocate memory, instead of malloc. (And of course use delete instead of free). | {
"domain": "codereview.stackexchange",
"id": 42630,
"lm_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++, constructor",
"url": null
} |
python, python-3.x, pygame, sliding-tile-puzzle
Title: 15 Puzzle in Pygame
Question: This is a 15 puzzle implemented in pygame. The tiles can be moved with the arrow keys or by clicking and dragging the mouse. Parts of the code that require extra like icons and sound effects files have been commented out.
puzzle.py
import pygame
from random import choice
from math import sqrt
class Direction:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __repr__(self):
return f'Direction({self.x}, {self.y})'
def __str__(self):
return f'{self.x:3}, {self.y:3}'
def normalized(self):
magnitude = sqrt(self.x**2 + self.y**2) + 0.0001 # no division by zero
return Direction(self.x / magnitude, self.y / magnitude)
def dot_product(self, other):
return self.x * other.x + self.y * other.y
def reverse(self):
return Direction(-self.x, -self.y)
def closest_direction(displacement, directions):
norm = displacement.normalized()
return max(directions, key=lambda x: x.dot_product(norm))
class Puzzle:
TILE_SIZE = 50
SPACE_COLOR = 'black'
TEXT_COLOR = 'black'
TEXT_SIZE = 40
SOLVED_COLOR = (100, 255, 100)
BORDER_COLOR = 'black'
BORDER_WIDTH = 5
MOVES = {'left': Direction(-1, 0),
'right': Direction(1, 0),
'down': Direction(0, 1),
'up': Direction(0, -1)}
SHUFFLE_COUNT = 50
LEFT_CLICK = 1 | {
"domain": "codereview.stackexchange",
"id": 42631,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, pygame, sliding-tile-puzzle",
"url": null
} |
python, python-3.x, pygame, sliding-tile-puzzle
def __init__(self, width=4, height=4):
self.width = abs(int(width))
self.height = abs(int(height))
# create board
self.board = []
number = 1
for x in range(self.width):
self.board.append([])
for y in range(self.height):
if number < self.width * self.height:
self.board[x].append(str(number))
else:
self.board[x].append(' ')
number += 1
# keep track of space so it doesn't need to be found
self.space = (self.width - 1, self.height - 1)
# save solution
self.solution = str(self)
# save history
self.history = []
def __eq__(self, other):
for x in range(self.width):
for y in range(self.height):
if self.board[x][y] != other.board[x][y]:
return False
return True
def __repr__(self):
return f'Puzzle({self.width}, {self.height})'
def __str__(self):
result = ''
for x in range(self.width):
for y in range(self.height):
result += f'\t{self.board[x][y]}'
result += '\n'
return result | {
"domain": "codereview.stackexchange",
"id": 42631,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, pygame, sliding-tile-puzzle",
"url": null
} |
python, python-3.x, pygame, sliding-tile-puzzle
def move(self, direction):
""" Try making a move in the given direction.
Return whether the move changed the board"""
x, y = self.space
# left
if direction == self.MOVES['left']:
# move space up in row
if y < self.height - 1:
self.board[x][y] = self.board[x][y + 1]
self.board[x][y + 1] = ' '
# update space
self.space = (x, y + 1)
# update history
self.history.append(self.MOVES['left'])
return True
# right
if direction == self.MOVES['right']:
# move space down in row
if y > 0:
self.board[x][y] = self.board[x][y - 1]
self.board[x][y - 1] = ' '
# update space
self.space = (x, y - 1)
# update history
self.history.append(self.MOVES['right'])
return True
# down
if direction == self.MOVES['down']:
# move space up in column
if x > 0:
self.board[x][y] = self.board[x - 1][y]
self.board[x - 1][y] = ' '
# update space
self.space = (x - 1, y)
# update history
self.history.append(self.MOVES['down'])
return True
# up
if direction == self.MOVES['up']:
# move space down in column
if x < self.width - 1:
self.board[x][y] = self.board[x + 1][y]
self.board[x + 1][y] = ' '
# update space
self.space = (x + 1, y)
# update history
self.history.append(self.MOVES['up'])
return True
return False | {
"domain": "codereview.stackexchange",
"id": 42631,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, pygame, sliding-tile-puzzle",
"url": null
} |
python, python-3.x, pygame, sliding-tile-puzzle
def shuffle(self, move_count):
""" Make move_count moves, making sure each move changes the board """
moves_made = 0
while moves_made < move_count:
moves_made += int(self.move(choice(list(self.MOVES.values()))))
def is_solved(self):
return str(self) == self.solution
def prune_history(self):
to_remove = []
index = 0
while index < len(self.history) - 1:
# remove consecutive moves that are reverses
if self.history[index] == self.history[index + 1].reverse():
to_remove.extend([index, index + 1])
index += 2
else:
index += 1
for index in reversed(to_remove):
self.history.pop(index)
def solve(self):
# shorten history where possible
self.prune_history()
# start from the most recent move
for move in reversed(self.history):
reversal = move.reverse()
# make reverse move
self.move(reversal)
def show_history(self):
for move in self.history:
print(move)
def draw_square(self, screen, x, y, color):
# space
if (x, y) == self.space:
color = self.SPACE_COLOR
if self.is_solved():
color = self.SOLVED_COLOR
# border
pygame.draw.rect(screen, self.BORDER_COLOR, (y * self.TILE_SIZE, x * self.TILE_SIZE, self.TILE_SIZE, self.TILE_SIZE), self.BORDER_WIDTH)
# background
pygame.draw.rect(screen, color, (y * self.TILE_SIZE, x * self.TILE_SIZE, self.TILE_SIZE, self.TILE_SIZE), 0)
# text
myfont = pygame.font.SysFont('Times New Roman', self.TEXT_SIZE)
textsurface = myfont.render(self.board[x][y], False, self.TEXT_COLOR)
margin = (self.TILE_SIZE - self.TEXT_SIZE) // 2
screen.blit(textsurface, (margin + self.TILE_SIZE * y, margin + self.TILE_SIZE * x)) | {
"domain": "codereview.stackexchange",
"id": 42631,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, pygame, sliding-tile-puzzle",
"url": null
} |
python, python-3.x, pygame, sliding-tile-puzzle
def draw(self, screen):
for y in range(self.height):
for x in range(self.width):
number = self.board[x][y]
# ignore space
color = 'black'
if number != ' ':
color = tuple([min(255, 255 * (int(number) + 5) // (self.width * self.height + 5))] * 3) # shade of grey
self.draw_square(screen, x, y, color)
def show(self):
""" Displays a puzzle graphically. """
pygame.init()
pygame.display.set_caption('Show 15 puzzle position')
#img = pygame.image.load('icon.png')
#pygame.display.set_icon(img)
pygame.font.init()
screen = pygame.display.set_mode((self.TILE_SIZE * self.width, self.TILE_SIZE * self.height))
self.draw(screen)
pygame.display.update()
running = True
while running:
keys = pygame.key.get_pressed()
redraw_needed = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
# quit
running = False | {
"domain": "codereview.stackexchange",
"id": 42631,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, pygame, sliding-tile-puzzle",
"url": null
} |
python, python-3.x, pygame, sliding-tile-puzzle
def play(self):
pygame.init()
pygame.display.set_caption('15 puzzle')
pygame.font.init()
pygame.mixer.init()
#move_sound = pygame.mixer.Sound('move.wav')
screen = pygame.display.set_mode((self.TILE_SIZE * self.height, self.TILE_SIZE * self.width))
#img = pygame.image.load('icon.png')
#pygame.display.set_icon(img)
running = True
initial_position = True
while running:
keys = pygame.key.get_pressed()
redraw_needed = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# mouse handling
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == self.LEFT_CLICK:
# start of displacement
pygame.mouse.get_rel()
if event.type == pygame.MOUSEBUTTONUP:
if event.button == self.LEFT_CLICK:
# end of displacement
movement = pygame.mouse.get_rel()
displacement = Direction(*movement)
self.move(closest_direction(displacement, list(self.MOVES.values())))
redraw_needed = True
# key handling
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
# quit
running = False
elif event.key == pygame.K_SPACE:
# screenshot
pygame.image.save(screen, "capture.png")
elif event.key == pygame.K_h:
# history
self.show_history()
elif event.key == pygame.K_r:
# shuffle
self.shuffle(self.SHUFFLE_COUNT)
redraw_needed = True | {
"domain": "codereview.stackexchange",
"id": 42631,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, pygame, sliding-tile-puzzle",
"url": null
} |
python, python-3.x, pygame, sliding-tile-puzzle
redraw_needed = True
elif event.key == pygame.K_s:
# solve
self.solve()
redraw_needed = True
# movement
elif event.key == pygame.K_UP:
redraw_needed = self.move(self.MOVES['up'])
elif event.key == pygame.K_DOWN:
redraw_needed = self.move(self.MOVES['down'])
elif event.key == pygame.K_LEFT:
redraw_needed = self.move(self.MOVES['left'])
elif event.key == pygame.K_RIGHT:
redraw_needed = self.move(self.MOVES['right'])
if initial_position or redraw_needed:
# draw puzzle
self.draw(screen)
pygame.display.update()
# play sound
#move_sound.play()
initial_position = False
pygame.quit() | {
"domain": "codereview.stackexchange",
"id": 42631,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, pygame, sliding-tile-puzzle",
"url": null
} |
python, python-3.x, pygame, sliding-tile-puzzle
if __name__ == '__main__':
p = Puzzle(6, 8)
p.play()
```
Answer: Your code is really good and well-structured, well done.
The only improvement I could do is removing code repetition in the move function, because you had very similar code for the 4 directions, also I simplified the handling of the edge of the grid with a try except block:
def move(self, direction):
""" Try making a move in the given direction.
Return whether the move changed the board"""
x, y = self.space
# left
direction_string_to_new_index = {
"left" : (x, y + 1),
"right": (x, y - 1),
"down" : (x - 1, y),
"up" : (x + 1, y)
}
for dir_str in direction_string_to_new_index.keys():
new_x, new_y = direction_string_to_new_index[dir_str]
if direction == self.MOVES[dir_str]:
try:
self.board[x][y] = self.board[new_x][new_y]
self.board[new_x][new_y] = ' '
# update space
self.space = (new_x, new_y)
# update history
self.history.append(self.MOVES[dir_str])
return True
except IndexError:
return False
So now we have a dictionary containing the difference between the cases, and the common code is below, the try except allows to simplify the edge case handling and make it uniform for all 4 cases.
Another small improvement is:
self.board = []
number = 1
for x in range(self.width):
self.board.append([])
for y in range(self.height):
if number < self.width * self.height:
self.board[x].append(str(number))
else:
self.board[x].append(' ')
number += 1 | {
"domain": "codereview.stackexchange",
"id": 42631,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, pygame, sliding-tile-puzzle",
"url": null
} |
python, python-3.x, pygame, sliding-tile-puzzle
So you mean that the last one should be different, so you could do:
self.board = []
for x in range(self.width):
self.board.append([])
for y in range(self.height):
if (x, y) == (self.width, self.height):
self.board[x].append(' ')
else:
self.board[x].append(str(number))
to make it more explicit.
Finally the __eq__ function can be rewritten with the all built-in and a generator comprehension to make it a bit easier to understand at a glance. | {
"domain": "codereview.stackexchange",
"id": 42631,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, pygame, sliding-tile-puzzle",
"url": null
} |
python, performance, algorithm, recursion, binary-search
Title: Binary Search using recursive approach
Question: Is the following implementation of recursive function correct? How about the time complexity of the code; is it good in terms of performance?
def binary_search(arr, num):
# find the middle index
# compare the middle index to the number
# if the number is greater than the middle index,
# search the right half of the list
# if the number is less than the middle index,
# search the left half of the list
# if the number is equal to the middle index,
# return the index
# if the number is not in the list,
# return -1
start = 0
end = len(arr) - 1
lookup = int(len(arr) / 2)
def search(arr, num):
nonlocal start, end, lookup
# base case
if len(arr) == 0:
return -1
if end == lookup and arr[lookup] != num:
lookup = -1
return
if num != arr[lookup] and num > arr[lookup]:
start = lookup + 1
lookup = int((start + end) / 2)
search(arr, num)
elif num != arr[lookup] and num < arr[lookup]:
end = lookup
lookup = int((start + end) / 2)
search(arr, num)
search(arr, num)
return lookup
print(binary_search([x for x in range(1, 10000)], 8))
# prints the index of the num if found, 7 | {
"domain": "codereview.stackexchange",
"id": 42632,
"lm_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, performance, algorithm, recursion, binary-search",
"url": null
} |
python, performance, algorithm, recursion, binary-search
Answer: A function's calls must be consistent with its implementation. The search()
helper function is organized to return -1 under some conditions. However,
nowhere do you capture the return value. That does not make sense. Functions
are either called for their side effects (e.g., modifying the value of the
non-local lookup) or they are called for their return value (in which case,
you'd better capture it).
Base cases should not check unchanging information. When should we bail out
of search()? Not when the list is empty: the list never changes size, so
emptiness should be checked before search() is ever called. Bailing out of a
recursion should be driven by something that is changed as the function is
being called -- namely, when start and end cross each other, or when we
actually find the target number.
Global variables are never the answer. You're using functions, which is
good. However, you are undermining their power by resorting to nonlocal. In
this case, you are using this mechanism to create the effect of a global
variable within the scope of the binary_search() function. In well over a
decade of Python programming, I can remember only one use of global or
nonlocal, and that was for unusual circumstances where I was operating under
the constraints of a legacy code base. They just aren't needed under regular
circumstances, and they have a wide range of negative effects on software.
What's the solution? Pass start and end as arguments to search(), and
compute lookup only inside in function, never outside. The benefit of the
latter is that you need to compute its value in only one spot, not multiple. If
you're ever working on a recursive implementation and find yourself computing the
same values both outside and inside the recursive function, that's often a sign
that you have not organized the recursive logic well.
Use convenience variables to aid readability. The search() function uses
arr[lookup] several times. A simple convenience variable can simplify | {
"domain": "codereview.stackexchange",
"id": 42632,
"lm_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, performance, algorithm, recursion, binary-search",
"url": null
} |
python, performance, algorithm, recursion, binary-search
arr[lookup] several times. A simple convenience variable can simplify
and lighten up the code, enhancing readability.
Select descriptive and thematic variable names. Although num is good in
telling us that we're dealing with a number, it's still pretty vague. Much
better is a term that conveys the concept of something that is being searched
for: target is one option. Similarly, lookup is not a terrible variable
name, but it's also vague in the sense that it doesn't clarify whether lookup
is an index or value from the list. A more helpful name would build on the
theme you've already established with start and end: options are
midpoint, middle, or even just mid. Finally, since this is a general
purpose function, it's not easy to pick a good name for the list of values. In
that context, arr is fine. But a better name can be had by drawing on a
convention often seen in functional programming, where an arbitrary value can
be represented by a variable like x and a collection of such values can be
represented by pluralizing the variable name to become xs. Such names are
effective because convey (a) our lack of knowledge about the details of the
thing behind the variable, and (b) the connection between the collection (xs)
and a value from it (x).
Algorithmic code needs testing. Donald Knuth was a genius on the topic of
algorithms, and yet even he appreciated the difficulty of implementing
simple algorithms when he wrote the following: "although the basic idea of
binary search is comparatively straightforward, the details can be surprisingly
tricky". The way to avoid pitfalls is to organize your code from the beginning
to support testing. The best way to do that is to learn how to use one of the
Python testing frameworks, but if you're just learning or want a practical,
quick-and-dirty approach when working on programming exercises like this, you
can mimic the approach taken in main() below: define a collection of test | {
"domain": "codereview.stackexchange",
"id": 42632,
"lm_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, performance, algorithm, recursion, binary-search",
"url": null
} |
python, performance, algorithm, recursion, binary-search
can mimic the approach taken in main() below: define a collection of test
cases (inputs and expected output); iterate over the collection; confirm that
the return value matches expectations.
def main():
tests = (
([], 99, -1),
([1, 2], 1, 0),
([1, 2, 4], 4, 2),
([1, 2, 3, 4], 4, 3),
([2, 4, 5, 99, 100], 5, 2),
(tuple(range(1, 1000)), 50, 49),
)
for xs, target, exp in tests:
got = binary_search(xs, target)
if got == exp:
print('ok', target)
else:
print('FAIL', target, exp) | {
"domain": "codereview.stackexchange",
"id": 42632,
"lm_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, performance, algorithm, recursion, binary-search",
"url": null
} |
python, performance, algorithm, recursion, binary-search
def binary_search(xs, target):
def search(start, end):
mid = (end + start) // 2
x = xs[mid]
if x == target:
return mid
elif end <= start:
return -1
elif target > x:
return search(mid + 1, end)
else:
return search(start, mid - 1)
return search(0, len(xs) - 1) if xs else -1
if __name__ == '__main__':
main()
Why bother with recursion?. I would not use recursion for
a simple case like this: check for emptiness; initialize start and
end; and enter a while-true loop, modifying start and end inside
the loop rather than recursing. At a minimum, it's worth implementing
a non-recursive version to compare the two and see what you think. | {
"domain": "codereview.stackexchange",
"id": 42632,
"lm_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, performance, algorithm, recursion, binary-search",
"url": null
} |
javascript, ecmascript-6
Title: Show selected person in another panel
Question: I was playing with JavaScript in order to practice and wanted to make a list of people, which when clicked showed the person's details in another part of the screen.
Here's the code I used to achieve it, but I'd like to have your feedback; how would you do it? Here's a working snippet:
const divRoot = document.querySelector('#root');
const tv = document.querySelector('.tv');
const tvProfesion = document.querySelector('.tvProfesion');
const tvNombre = document.querySelector('.tvNombre');
const personas = [
{
nombre: 'Julio',
profesion: 'Web Developer',
},
{
nombre: 'Yisus',
profesion: 'Mesias troll',
},
{
nombre: 'Goku',
profesion: 'Sayayin',
},
];
personas.forEach((person) => {
const ul = document.createElement('ul');
ul.classList.add('ul');
ul.addEventListener('click', (event) => {
for (const prop in person) {
if(prop == 'nombre') {
tvNombre.innerText = person[prop];
}else{
tvProfesion.innerText = person[prop];
}
}
});
for (const prop in person) {
const li = document.createElement('li');
li.innerText = person[prop];
ul.appendChild(li);
}
divRoot.appendChild(ul);
});
function setName(prop) {
if(prop == 'nombre') {
tvNombre.innerText = person[prop];
}else{
tvProfesion.innerText = person[prop];
}
}
div,li {
border-radius: 15px;background-color: cadetblue; padding:5px
} | {
"domain": "codereview.stackexchange",
"id": 42633,
"lm_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, ecmascript-6",
"url": null
} |
javascript, ecmascript-6
.ul, p {
border: 1px solid grey !important;
padding: 10px;
background-color:slateblue;
border-radius: 15px;
margin:5px
}
li {
list-style: none;
}
.wrapper {
padding: 50px;
background-color: rgb(170, 165, 236);
display: flex;
justify-content: space-around;
align-items: center;
}
.tv {
border: 1px solid brown;
height: 200px;
width: 200px;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="wrapper">
<div id="root"></div>
<div class="tv">
<p class="tvNombre"></p>
<p class="tvProfesion"></p>
</div>
</div>
<script src="./app.js"></script>
</body>
</html>
I'd love to see other developers' ways of solving this problem in order to expand the small repertoire I have in my mind to solve this kind of problem. :) | {
"domain": "codereview.stackexchange",
"id": 42633,
"lm_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, ecmascript-6",
"url": null
} |
javascript, ecmascript-6
Answer: Just a few quick first thoughts:
You never use your const tv.
You never use your function setName(). also setName would be a wrong name for the function as it sets name and profession. Should be setPerson() instead.
You never use then event parameter of the event listener.
You should not create one event listener for each person in the person creation loop. Just add one event listener after creating all persons and check the event parameter target to get the right person to set
For me it makes no sense to set the properties in a loop when you have to add one if condition for each property you will set. To make it simple remove the loop and just use two lines of code setting number and profession directly.
If you want to make the code more flexible on adding more properties, I would suggest to use data tags in detail view naming the properties key.
For exmple:
<p class="tvNombre" data="nombre"></p>
then you can set your detail data in a loop by accessing the correct element just h\by the persons property key.
I only give you hints how to make your code better because I personal love it this way for myself if someone gives me a way not the complete answer. If you can’t figure something out for yourself or need any deeper information just ask. | {
"domain": "codereview.stackexchange",
"id": 42633,
"lm_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, ecmascript-6",
"url": null
} |
c++, strings
Title: Word transformation
Question: I have started to practice programming by doing exercises and I want to get feed back to improve my self in nice clean coding and I found this website.
The program I wrote now is a word transformation map.
It has a text file contains a pair of words in each line (transferor.txt), and an input text file(input.txt).
transferor.txt contains:
'em them
cuz because
gratz grateful
i I
nah no
pos supposed
sez said
tanx thanks
wuz was
and input.txt file contains:
nah i sez tanx cuz i wuz pos to
not cuz i wuz gratz
The result is an output file (output.txt) containing:
no I said thanks because I was supposed to
not because I was grateful
Here is the code:
#include <iostream>
#include <map>
#include <fstream>
#include <string>
#include <sstream> | {
"domain": "codereview.stackexchange",
"id": 42634,
"lm_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++, strings",
"url": null
} |
c++, strings
int main()
{
std::fstream fi;
std::fstream fo;
const char* transferor_dir = "/mnt/c/Users/meysa/source/repos/CPP_VIM_PRACTICE/ourplan/transferor.txt";
fi.open(transferor_dir,std::fstream::in);
if(!fi.is_open())
std::cerr << "Problem in opening the transferor file" << std::endl;
std::string key,mapped;
std::map<std::string,std::string> maptransferor;
while(fi >> key >> mapped )
{
maptransferor.insert(std::make_pair(key,mapped));
}
fi.close();
const char* input = "/mnt/c/Users/meysa/source/repos/CPP_VIM_PRACTICE/ourplan/input.txt";
const char* output = "/mnt/c/Users/meysa/source/repos/CPP_VIM_PRACTICE/ourplan/output.txt";
fi.open(input,std::fstream::in);
fo.open(output,std::fstream::out);
if(!fi.is_open())
std::cerr << "There is a problem in opening the input file! " << std::endl;
std::string line;
std::string word;
while(std::getline(fi,line))
{
std::stringstream ss(line,std::ios_base::in);
while( ss >> word)
{
if(maptransferor.count(word))
fo << (maptransferor.find(word))->second << " ";
else
fo << word << " ";
}
fo << std::endl;
}
fi.close();
fo.close();
return 0;
}
Answer: Your code is currently tied to very specific pathnames, and would need to be recompiled to work with a different mapping dictionary, or different input and output files.
I recommend using int main(int argc, char **argv) so that you can use a command argument to specify the mapping file, and once that's successfully read, then the program can operate as a filter (take input from std::cin and write output to std::cout).
You would then invoke the program as
translate transferor.txt <input.txt >output.txt | {
"domain": "codereview.stackexchange",
"id": 42634,
"lm_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++, strings",
"url": null
} |
c++, strings
It's also a good idea to divide the program into separately testable functions. I'd start with
std::map<std::string,std::string> make_mapping(std::istream& input);
and
void map_text(const std::map<std::string,std::string>& mapping,
std::istream& input, std::ostream& output);
I'm pleased that you check that the files can be opened:
if(!fi.is_open())
std::cerr << "There is a problem in opening the input file! " << std::endl;
However, if the opening failed, then there's really no point reading from it (or even opening an output file):
fi.open(input);
if (!fi.is_open()) {
std::cerr << "There is a problem in opening the input file!\n";
return EXIT_FAILURE;
}
fo.open(output, std::ofstream::trunc);
We do two lookups in the map here:
if(maptransferor.count(word))
fo << (maptransferor.find(word))->second << " ";
else
We can remember the result of find() and use it like this:
auto tr = maptransferor.find(word);
if (tr != maptransferor.end()) {
fo << it->second << " ";
} else {
We should be checking the return value from the close() operation on each stream - several kinds of failure make themselves apparent that way.
(If we wanted to ignore close() failures, we could just omit those calls because the streams' destructors will do exactly that.) | {
"domain": "codereview.stackexchange",
"id": 42634,
"lm_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++, strings",
"url": null
} |
javascript, datetime
Title: Check if calendar week number falls within two other week numbers | {
"domain": "codereview.stackexchange",
"id": 42635,
"lm_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, datetime",
"url": null
} |
javascript, datetime
Question: I want to check with Javascript if a week number (with year) is within two other week numbers.
Example data: Year-Week startDate: 2020-32 endDate: 2021-52 checkDate: 2021-30.
In this case checkDate is within the two years.
How do I make Javascript know this too? I figured I should check if the date is bigger than startDate and smaller than endDate. But doing these checks on both years and weeks seems to get quite big. Here is what I have implemented:
/**
* Returns whether the week is within the two given weeks or not.
*
* @param {Number} startYear Example data: 2020
* @param {Number} startWeek 32
* @param {Number} endYear 2021
* @param {Number} endWeek 52
* @param {Number} checkYear 2021
* @param {Number} checkWeek 30
* @returns true or false
*/
function isWeekWithinTwoWeeks(startYear, startWeek, endYear, endWeek, checkYear, checkWeek) {
// If checkYear is same as startyear and checkWeek bigger or equal to startWeek and checkWeek smaller or equal than endWeek, its not allowed.
// Else if checkYear is bigger than startYear, and checkYear is smaller than endYear it means it is in between.
// Also if checkYear is bigger than startYear but checkYear is not smaller but equal to endYear, and checkWeek is smaller or equal to endWeek, it is in between.
if (checkYear === startYear) {
if (checkWeek >= startWeek) {
if (checkWeek <= endWeek) {
addUserFormError.innerHTML = "Not allowed to have a week within two other weeks!";
return false;
}
}
} else if (checkYear > startYear) {
if (checkYear < endYear) {
addUserFormError.innerHTML = "Not allowed to have a week within two other weeks!";
return false;
} else if (checkYear === endYear) {
if (checkWeek <= endWeek) {
addUserFormError.innerHTML = "Not allowed to have a week within two other weeks!";
return false;
}
} | {
"domain": "codereview.stackexchange",
"id": 42635,
"lm_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, datetime",
"url": null
} |
javascript, datetime
return false;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 42635,
"lm_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, datetime",
"url": null
} |
javascript, datetime
return true;
}
I think it could be done in a much simpler way and would like to know if there is much to improve here and how. I do know I could use && signs in the if statements to make them more of a one-liner, but thought this might be more readable.
Answer: Logic
Your logic is not entirely correct, consider the following arguments:
startYear: 2001
startWeek: 10
endYear: 2002
endWeek: 5
checkYear: 2001
checkWeek: 15
checkYear === startYear is true, but checkWeek <= endWeek is not, leading to true output, which is not intended here. The check for checkWeek <= endWeek is only relevant if startYear === endYear.
Nested ifs vs. &&
This point does not consider the aformentioned logic issues, simply focuses on code style
I'd argue using the &&-operator here actually increases readability. You should consider that each level of indentation is another layer of context the reader needs to keep track of in their head. We're already two levels of indentation deep once we get to this check, which then (unnecessarily) adds another two levels of indentation.
if (checkWeek >= startWeek) {
if (checkWeek <= endWeek) {
// Do something
}
}
Using the &&-operator here is also closer to the natural thought process: If the week number is greater than or equal to startWeek AND less than or equal to the endWeek it is between the two. I'd say this is closer to a single logical unit instead of two subsequent logical units (as your implementation suggests).
if (checkWeek >= startWeek && checkWeek <= endWeek) {
// Do something
}
Please note that there is no absolute truth here, personal preference, use case and code style guidelines are always relevant factors. | {
"domain": "codereview.stackexchange",
"id": 42635,
"lm_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, datetime",
"url": null
} |
javascript, datetime
Function naming and return values
You have your function naming / return values the wrong way round. If I call isWeekWithinTwoWeeks(...) I expect to get true if my week number lies between start and end. Your function returns false for this case. Either your function name or your return values should be the exact opposite. This is extremely relevant for readability. As it is now, I would need to inspect and understand the implementation of every single function to be sure what they do. Intuitive naming enables readers to understand your code more easily and reliably.
Side effects
I don't know the structure of your project, but you might (/ should) consider removing this side effect
addUserFormError.innerHTML = "Not allowed to have a week within two other weeks!"
from this particular function. I would not expect a function called isWeekWithinTwoWeeks to directly modify the DOM. Instead I would move it to wherever the function is called from, dependent on the return value of isWeekWithinTwoWeeks. This reduces code duplication (the aforementioned line is repeated three times) and further increases readability as functionality is more closely related to naming. | {
"domain": "codereview.stackexchange",
"id": 42635,
"lm_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, datetime",
"url": null
} |
c++, algorithm, image, error-handling, c++20
Title: Dictionary based non-local mean implementation in C++
Question: This is a follow-up question for Manhattan distance calculation between two images in C++ and Dictionary based non-local mean implementation in Matlab. For learning C++20 and researching purposes, I am attempting to implement function create_dictionary and dictionaryBasedNonlocalMean which purpose are similar to the linked follow-up question, i.e. calculate dictionary based non-local mean. In mathematical form, output of function dictionaryBasedNonlocalMean is calculated with the following way.
$$output = K\sum_{{i = 1}}^{{N}_{D}} \left[ G_{\mu = 0, \sigma} (\left\|input - X(i)\right\|_{1}) \cdot Y(i) \right]
$$
where ND is the count of X-Y pairs (the cardinality of set X and set Y) in the dictionary and the Gaussian function
$$G_{\mu = 0, \sigma} (\left\|input - X(i)\right\|_{1}) = \left.e^{\frac{-(\left\|input - X(i)\right\|_{1} - \mu)^2}{2 {\sigma}^{2}}}\right|_{\mu=0}
$$
Moreover, K is a normalization factor
$$K = \frac{1}{\sum_{{i = 1}}^{{N}_{D}} G_{\mu = 0, \sigma} (\left\|input - X(i)\right\|_{1})}
$$
The experimental implementation | {
"domain": "codereview.stackexchange",
"id": 42636,
"lm_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++, algorithm, image, error-handling, c++20",
"url": null
} |
c++, algorithm, image, error-handling, c++20
The experimental implementation
create_dictionary template function implementation: The purpose of this function is similar to Matlab version CreateDictionary in the linked follow-up question. The N_D_ paired codewords are created in std::tuple<std::vector<...>, std::vector<...>> structure.
template<class ElementT = double>
constexpr static auto create_dictionary(const std::size_t ND, const std::size_t xsize, const std::size_t ysize, const std::size_t zsize)
{
auto code_words_x = TinyDIP::n_dim_vector_generator<1>(std::vector<TinyDIP::Image<ElementT>>(), ND);
auto code_words_y = TinyDIP::n_dim_vector_generator<1>(std::vector<TinyDIP::Image<ElementT>>(), ND);
for (std::size_t i = 0; i < ND; ++i)
{
code_words_x[i] = TinyDIP::n_dim_vector_generator<1>(
TinyDIP::Image<ElementT>(xsize, ysize, static_cast<ElementT>(i) / static_cast<ElementT>(ND)), zsize);
code_words_y[i] = TinyDIP::n_dim_vector_generator<1>(
TinyDIP::Image<ElementT>(xsize, ysize, 1.0 + static_cast<ElementT>(i) / static_cast<ElementT>(ND)), zsize);
}
return std::make_tuple(code_words_x, code_words_y);
} | {
"domain": "codereview.stackexchange",
"id": 42636,
"lm_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++, algorithm, image, error-handling, c++20",
"url": null
} |
c++, algorithm, image, error-handling, c++20
dictionaryBasedNonlocalMean template function implementation:
template<class ExPo, class ElementT = double>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr static auto dictionaryBasedNonlocalMean( ExPo execution_policy,
const std::tuple<
std::vector<std::vector<TinyDIP::Image<ElementT>>>,
std::vector<std::vector<TinyDIP::Image<ElementT>>>
>& dictionary,
const std::vector<TinyDIP::Image<ElementT>>& input,
const double gaussian_sigma = 3.0,
const double gaussian_mean = 0,
const double threshold = 1e-160) noexcept
{
std::vector<TinyDIP::Image<ElementT>> output =
TinyDIP::n_dim_vector_generator<1>(
TinyDIP::Image(input[0].getWidth(), input[0].getHeight(), 0.0), input.size());
auto code_words_x = std::get<0>(dictionary);
auto code_words_y = std::get<1>(dictionary);
if (code_words_x.size() != code_words_y.size())
{
throw std::runtime_error("Size of data in dictionary incorrect.");
}
auto weights = TinyDIP::recursive_transform<1>(
execution_policy,
[&](auto&& element)
{
return TinyDIP::normalDistribution1D(
TinyDIP::recursive_reduce(
TinyDIP::recursive_transform<1>(
[&](auto&& each_plane_x, auto&& each_plane_input) { return TinyDIP::manhattan_distance(each_plane_x, each_plane_input); },
element, input),
ElementT{}) + gaussian_mean,
gaussian_sigma);
}, code_words_x); | {
"domain": "codereview.stackexchange",
"id": 42636,
"lm_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++, algorithm, image, error-handling, c++20",
"url": null
} |
c++, algorithm, image, error-handling, c++20
gaussian_sigma);
}, code_words_x);
auto sum_of_weights = TinyDIP::recursive_reduce(weights, ElementT{});
std::cout << "sum_of_weights: " << std::to_string(sum_of_weights) << '\n';
if (sum_of_weights < threshold)
{
return output;
}
auto outputs = TinyDIP::recursive_transform<1>(
[&](auto&& input1, auto&& input2)
{
return TinyDIP::multiplies(input1, TinyDIP::n_dim_vector_generator<1>(TinyDIP::Image(input1[0].getWidth(), input1[0].getHeight(), input2), input1.size()));
}, code_words_y, weights); | {
"domain": "codereview.stackexchange",
"id": 42636,
"lm_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++, algorithm, image, error-handling, c++20",
"url": null
} |
c++, algorithm, image, error-handling, c++20
for (std::size_t i = 0; i < outputs.size(); ++i)
{
output = TinyDIP::plus(output, outputs[i]);
}
output = TinyDIP::divides(output, TinyDIP::n_dim_vector_generator<1>(TinyDIP::Image(output[0].getWidth(), output[0].getHeight(), sum_of_weights), output.size()));
return output;
}
manhattan_distance template function implementation:
template<arithmetic ElementT = double>
constexpr static ElementT manhattan_distance(const Image<ElementT>& input1, const Image<ElementT>& input2)
{
is_size_same(input1, input2);
return recursive_reduce(difference(input1, input2).getImageData(), ElementT{});
}
difference template function implementation:
template<arithmetic ElementT = double>
constexpr static auto difference(const Image<ElementT>& input1, const Image<ElementT>& input2)
{
return pixelwiseOperation([](auto&& element1, auto&& element2) { return std::abs(element1 - element2); }, input1, input2);
}
pixelwiseOperation template function implementation:
template<std::size_t unwrap_level = 1, class... Args>
constexpr static auto pixelwiseOperation(auto op, const Args&... inputs)
{
auto output = Image(
recursive_transform<unwrap_level>(
[&](auto&& element1, auto&&... elements)
{
return op(element1, elements...);
},
inputs.getImageData()...),
first_of(inputs...).getWidth(),
first_of(inputs...).getHeight());
return output;
} | {
"domain": "codereview.stackexchange",
"id": 42636,
"lm_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++, algorithm, image, error-handling, c++20",
"url": null
} |
c++, algorithm, image, error-handling, c++20
template<std::size_t unwrap_level = 1, class ExPo, class InputT>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr static auto pixelwiseOperation(ExPo execution_policy, auto op, const Image<InputT>& input1)
{
auto output = Image(
recursive_transform<unwrap_level>(
execution_policy,
[&](auto&& element1)
{
return op(element1);
},
(input1.getImageData())),
input1.getWidth(),
input1.getHeight());
return output;
}
Full Testing Code
Tests for dictionaryBasedNonlocalMean template function:
#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <cmath>
#include <concepts>
#include <exception>
#include <execution>
#include <fstream>
#include <functional>
#include <iostream>
#include <iterator>
#include <mutex>
#include <numeric>
#include <ranges>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
using BYTE = unsigned char;
struct RGB
{
BYTE channels[3];
};
using GrayScale = BYTE;
namespace TinyDIP
{
#define is_size_same(x, y) {assert(x.getWidth() == y.getWidth()); assert(x.getHeight() == y.getHeight());}
// Reference: https://stackoverflow.com/a/58067611/6667035
template <typename T>
concept arithmetic = std::is_arithmetic_v<T>;
// recursive_depth function implementation
template<typename T>
constexpr std::size_t recursive_depth()
{
return 0;
}
template<std::ranges::input_range Range>
constexpr std::size_t recursive_depth()
{
return recursive_depth<std::ranges::range_value_t<Range>>() + 1;
} | {
"domain": "codereview.stackexchange",
"id": 42636,
"lm_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++, algorithm, image, error-handling, c++20",
"url": null
} |
c++, algorithm, image, error-handling, c++20
template<std::size_t index = 1, typename Arg, typename... Args>
constexpr static auto& get_from_variadic_template(const Arg& first, const Args&... inputs)
{
if constexpr (index > 1)
return get_from_variadic_template<index - 1>(inputs...);
else
return first;
}
template<typename... Args>
constexpr static auto& first_of(Args&... inputs) {
return get_from_variadic_template<1>(inputs...);
}
// recursive_reduce implementation
// Reference: https://codereview.stackexchange.com/a/251310/231235
template<class T, class ValueType, class Function = std::plus<ValueType>>
constexpr auto recursive_reduce(const T& input, ValueType init, const Function& f)
{
return f(init, input);
}
template<std::ranges::range Container, class ValueType, class Function = std::plus<ValueType>>
constexpr auto recursive_reduce(const Container& input, ValueType init, const Function& f = std::plus<ValueType>())
{
for (const auto& element : input) {
auto result = recursive_reduce(element, ValueType{}, f);
init = f(init, result);
}
return init;
}
// recursive_invoke_result_t implementation
template<std::size_t, typename, typename>
struct recursive_invoke_result { };
template<typename T, typename F>
struct recursive_invoke_result<0, F, T> { using type = std::invoke_result_t<F, T>; };
template<std::size_t unwrap_level, typename F, template<typename...> typename Container, typename... Ts>
requires (std::ranges::input_range<Container<Ts...>> &&
requires { typename recursive_invoke_result<unwrap_level - 1, F, std::ranges::range_value_t<Container<Ts...>>>::type; })
struct recursive_invoke_result<unwrap_level, F, Container<Ts...>>
{
using type = Container<typename recursive_invoke_result<unwrap_level - 1, F, std::ranges::range_value_t<Container<Ts...>>>::type>;
}; | {
"domain": "codereview.stackexchange",
"id": 42636,
"lm_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++, algorithm, image, error-handling, c++20",
"url": null
} |
c++, algorithm, image, error-handling, c++20
template<std::size_t unwrap_level, typename F, typename T>
using recursive_invoke_result_t = typename recursive_invoke_result<unwrap_level, F, T>::type;
// recursive_variadic_invoke_result_t implementation
template<std::size_t, typename, typename, typename...>
struct recursive_variadic_invoke_result { };
template<typename F, class...Ts1, template<class...>class Container1, typename... Ts>
struct recursive_variadic_invoke_result<1, F, Container1<Ts1...>, Ts...>
{
using type = Container1<std::invoke_result_t<F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...>>;
};
template<std::size_t unwrap_level, typename F, class...Ts1, template<class...>class Container1, typename... Ts>
requires ( std::ranges::input_range<Container1<Ts1...>> &&
requires { typename recursive_variadic_invoke_result<
unwrap_level - 1,
F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...>::type; }) // The rest arguments are ranges
struct recursive_variadic_invoke_result<unwrap_level, F, Container1<Ts1...>, Ts...>
{
using type = Container1<
typename recursive_variadic_invoke_result<
unwrap_level - 1,
F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...
>::type>;
};
template<std::size_t unwrap_level, typename F, typename T1, typename... Ts>
using recursive_variadic_invoke_result_t = typename recursive_variadic_invoke_result<unwrap_level, F, T1, Ts...>::type; | {
"domain": "codereview.stackexchange",
"id": 42636,
"lm_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++, algorithm, image, error-handling, c++20",
"url": null
} |
c++, algorithm, image, error-handling, c++20
template<typename OutputIt, typename NAryOperation, typename InputIt, typename... InputIts>
OutputIt transform(OutputIt d_first, NAryOperation op, InputIt first, InputIt last, InputIts... rest) {
while (first != last) {
*d_first++ = op(*first++, (*rest++)...);
}
return d_first;
}
// recursive_transform for the multiple parameters cases (the version with unwrap_level)
template<std::size_t unwrap_level = 1, class F, class Arg1, class... Args>
constexpr auto recursive_transform(const F& f, const Arg1& arg1, const Args&... args)
{
if constexpr (unwrap_level > 0)
{
static_assert(unwrap_level <= recursive_depth<Arg1>(),
"unwrap level higher than recursion depth of input");
recursive_variadic_invoke_result_t<unwrap_level, F, Arg1, Args...> output{};
transform(
std::inserter(output, std::ranges::end(output)),
[&f](auto&& element1, auto&&... elements) { return recursive_transform<unwrap_level - 1>(f, element1, elements...); },
std::ranges::cbegin(arg1),
std::ranges::cend(arg1),
std::ranges::cbegin(args)...
);
return output;
}
else
{
return f(arg1, args...);
}
} | {
"domain": "codereview.stackexchange",
"id": 42636,
"lm_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++, algorithm, image, error-handling, c++20",
"url": null
} |
c++, algorithm, image, error-handling, c++20
// recursive_transform implementation (the version with unwrap_level, with execution policy)
template<std::size_t unwrap_level = 1, class ExPo, class T, class F>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr auto recursive_transform(ExPo execution_policy, const F& f, const T& input)
{
if constexpr (unwrap_level > 0)
{
static_assert(unwrap_level <= recursive_depth<T>(),
"unwrap level higher than recursion depth of input");
recursive_invoke_result_t<unwrap_level, F, T> output{};
output.resize(input.size());
std::mutex mutex;
std::transform(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), std::ranges::begin(output),
[&](auto&& element)
{
std::lock_guard lock(mutex);
return recursive_transform<unwrap_level - 1>(execution_policy, f, element);
});
return output;
}
else
{
return f(input);
}
}
template<std::size_t dim, class T>
constexpr auto n_dim_vector_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_vector_generator<dim - 1>(input, times);
std::vector<decltype(element)> output(times, element);
return output;
}
}
template <typename ElementT>
class Image
{
public:
Image() = default;
Image(const std::size_t width, const std::size_t height):
width(width),
height(height),
image_data(width * height) { }
Image(const std::size_t width, const std::size_t height, const ElementT initVal):
width(width),
height(height),
image_data(width * height, initVal) {} | {
"domain": "codereview.stackexchange",
"id": 42636,
"lm_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++, algorithm, image, error-handling, c++20",
"url": null
} |
c++, algorithm, image, error-handling, c++20
Image(const std::vector<ElementT> input, std::size_t newWidth, std::size_t newHeight):
width(newWidth),
height(newHeight)
{
if (input.size() != newWidth * newHeight)
{
throw std::runtime_error("Image data input and the given size are mismatched!");
}
image_data = std::move(input);
}
constexpr ElementT& at(const unsigned int x, const unsigned int y)
{
checkBoundary(x, y);
return image_data[y * width + x];
}
constexpr ElementT const& at(const unsigned int x, const unsigned int y) const
{
checkBoundary(x, y);
return image_data[y * width + x];
}
constexpr std::size_t getWidth() const
{
return width;
}
constexpr std::size_t getHeight() const
{
return height;
}
constexpr auto getSize()
{
return std::make_tuple(width, height);
}
std::vector<ElementT> const& getImageData() const { return image_data; } // expose the internal data
void print(std::string separator = "\t", std::ostream& os = std::cout) const
{
for (std::size_t y = 0; y < height; ++y)
{
for (std::size_t x = 0; x < width; ++x)
{
// Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number
os << +at(x, y) << separator;
}
os << "\n";
}
os << "\n";
return;
} | {
"domain": "codereview.stackexchange",
"id": 42636,
"lm_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++, algorithm, image, error-handling, c++20",
"url": null
} |
c++, algorithm, image, error-handling, c++20
// Enable this function if ElementT = RGB
void print(std::string separator = "\t", std::ostream& os = std::cout) const
requires(std::same_as<ElementT, RGB>)
{
for (std::size_t y = 0; y < height; ++y)
{
for (std::size_t x = 0; x < width; ++x)
{
os << "( ";
for (std::size_t channel_index = 0; channel_index < 3; ++channel_index)
{
// Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number
os << +at(x, y).channels[channel_index] << separator;
}
os << ")" << separator;
}
os << "\n";
}
os << "\n";
return;
}
friend std::ostream& operator<<(std::ostream& os, const Image<ElementT>& rhs)
{
const std::string separator = "\t";
for (std::size_t y = 0; y < rhs.height; ++y)
{
for (std::size_t x = 0; x < rhs.width; ++x)
{
// Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number
os << +rhs.at(x, y) << separator;
}
os << "\n";
}
os << "\n";
return os;
}
Image<ElementT>& operator+=(const Image<ElementT>& rhs)
{
assert(rhs.width == this->width);
assert(rhs.height == this->height);
std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data),
std::ranges::begin(image_data), std::plus<>{});
return *this;
} | {
"domain": "codereview.stackexchange",
"id": 42636,
"lm_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++, algorithm, image, error-handling, c++20",
"url": null
} |
c++, algorithm, image, error-handling, c++20
Image<ElementT>& operator-=(const Image<ElementT>& rhs)
{
assert(rhs.width == this->width);
assert(rhs.height == this->height);
std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data),
std::ranges::begin(image_data), std::minus<>{});
return *this;
}
Image<ElementT>& operator*=(const Image<ElementT>& rhs)
{
assert(rhs.width == this->width);
assert(rhs.height == this->height);
std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data),
std::ranges::begin(image_data), std::multiplies<>{});
return *this;
}
Image<ElementT>& operator/=(const Image<ElementT>& rhs)
{
assert(rhs.width == this->width);
assert(rhs.height == this->height);
std::transform(std::ranges::cbegin(image_data), std::ranges::cend(image_data), std::ranges::cbegin(rhs.image_data),
std::ranges::begin(image_data), std::divides<>{});
return *this;
}
friend bool operator==(Image<ElementT> const&, Image<ElementT> const&) = default;
friend bool operator!=(Image<ElementT> const&, Image<ElementT> const&) = default;
friend Image<ElementT> operator+(const Image<ElementT>& input1, const Image<ElementT>& input2);
friend Image<ElementT> operator-(const Image<ElementT>& input1, const Image<ElementT>& input2);
Image<ElementT>& operator=(Image<ElementT> const& input) = default; // Copy Assign
Image<ElementT>& operator=(Image<ElementT>&& other) = default; // Move Assign
Image(const Image<ElementT> &input) = default; // Copy Constructor | {
"domain": "codereview.stackexchange",
"id": 42636,
"lm_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++, algorithm, image, error-handling, c++20",
"url": null
} |
c++, algorithm, image, error-handling, c++20
Image(const Image<ElementT> &input) = default; // Copy Constructor
Image(Image<ElementT> &&input) = default; // Move Constructor
private:
std::size_t width;
std::size_t height;
std::vector<ElementT> image_data;
void checkBoundary(const size_t x, const size_t y) const
{
assert(x < width);
assert(y < height);
}
};
template<class ElementT>
Image<ElementT> operator+(const Image<ElementT>& input1, const Image<ElementT>& input2)
{
return plus(input1, input2);
}
template<class ElementT>
Image<ElementT> operator-(const Image<ElementT>& input1, const Image<ElementT>& input2)
{
return subtract(input1, input2);
}
template<typename T>
T normalDistribution1D(const T x, const T standard_deviation)
{
return std::exp(-x * x / (2 * standard_deviation * standard_deviation));
}
template<std::size_t unwrap_level = 1, class... Args>
constexpr static auto pixelwiseOperation(auto op, const Args&... inputs)
{
auto output = Image(
recursive_transform<unwrap_level>(
[&](auto&& element1, auto&&... elements)
{
return op(element1, elements...);
},
inputs.getImageData()...),
first_of(inputs...).getWidth(),
first_of(inputs...).getHeight());
return output;
} | {
"domain": "codereview.stackexchange",
"id": 42636,
"lm_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++, algorithm, image, error-handling, c++20",
"url": null
} |
c++, algorithm, image, error-handling, c++20
template<std::size_t unwrap_level = 1, class ExPo, class InputT>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr static auto pixelwiseOperation(ExPo execution_policy, auto op, const Image<InputT>& input1)
{
auto output = Image(
recursive_transform<unwrap_level>(
execution_policy,
[&](auto&& element1)
{
return op(element1);
},
(input1.getImageData())),
input1.getWidth(),
input1.getHeight());
return output;
}
template<class InputT>
constexpr static Image<InputT> plus(const Image<InputT>& input1)
{
return input1;
}
template<class InputT, class... Args>
constexpr static Image<InputT> plus(const Image<InputT>& input1, const Args&... inputs)
{
return pixelwiseOperation(std::plus<>{}, input1, plus(inputs...));
}
template<class InputT, class... Args>
constexpr static auto plus(const std::vector<Image<InputT>>& input1, const Args&... inputs)
{
return recursive_transform<1>(
[](auto&& input1_element, auto&&... inputs_element)
{
return plus(input1_element, inputs_element...);
}, input1, inputs...);
}
template<class InputT>
constexpr static Image<InputT> subtract(const Image<InputT>& input1, const Image<InputT>& input2)
{
is_size_same(input1, input2);
return pixelwiseOperation(std::minus<>{}, input1, input2);
}
template<class InputT>
constexpr static Image<InputT> subtract(const std::vector<Image<InputT>>& input1, const std::vector<Image<InputT>>& input2)
{
return recursive_transform<1>(
[](auto&& input1_element, auto&& input2_element)
{
return subtract(input1_element, input2_element);
}, input1, input2);
} | {
"domain": "codereview.stackexchange",
"id": 42636,
"lm_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++, algorithm, image, error-handling, c++20",
"url": null
} |
c++, algorithm, image, error-handling, c++20
template<class InputT = RGB>
requires (std::same_as<InputT, RGB>)
constexpr static Image<InputT> subtract(const Image<InputT>& input1, const Image<InputT>& input2)
{
is_size_same(input1, input2);
Image<InputT> output(input1.getWidth(), input1.getHeight());
for (std::size_t y = 0; y < input1.getHeight(); ++y)
{
for (std::size_t x = 0; x < input1.getWidth(); ++x)
{
for(std::size_t channel_index = 0; channel_index < 3; ++channel_index)
{
output.at(x, y).channels[channel_index] =
std::clamp(
input1.at(x, y).channels[channel_index] -
input2.at(x, y).channels[channel_index],
0,
255);
}
}
}
return output;
}
template<class InputT>
constexpr static Image<InputT> multiplies(const Image<InputT>& input1, const Image<InputT>& input2)
{
return pixelwiseOperation(std::multiplies<>{}, input1, input2);
}
template<class ExPo, class InputT>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr static Image<InputT> multiplies(ExPo execution_policy, const Image<InputT>& input1, const Image<InputT>& input2)
{
return pixelwiseOperation(execution_policy, std::multiplies<>{}, input1, input2);
}
template<class InputT, class... Args>
constexpr static Image<InputT> multiplies(const Image<InputT>& input1, const Args&... inputs)
{
return pixelwiseOperation(std::multiplies<>{}, input1, multiplies(inputs...));
} | {
"domain": "codereview.stackexchange",
"id": 42636,
"lm_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++, algorithm, image, error-handling, c++20",
"url": null
} |
c++, algorithm, image, error-handling, c++20
template<class InputT, class... Args>
constexpr static auto multiplies(const std::vector<Image<InputT>>& input1, const Args&... inputs)
{
return recursive_transform<1>(
[](auto&& input1_element, auto&&... inputs_element)
{
return multiplies(input1_element, inputs_element...);
}, input1, inputs...);
}
template<class InputT>
constexpr static Image<InputT> divides(const Image<InputT>& input1, const Image<InputT>& input2)
{
return pixelwiseOperation(std::divides<>{}, input1, input2);
}
template<class InputT>
constexpr static auto divides(const std::vector<Image<InputT>>& input1, const std::vector<Image<InputT>>& input2)
{
return recursive_transform<1>(
[](auto&& input1_element, auto&& input2_element)
{
return divides(input1_element, input2_element);
}, input1, input2);
}
template<class ExPo, class InputT>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr static Image<InputT> divides(ExPo execution_policy, const Image<InputT>& input1, const Image<InputT>& input2)
{
return pixelwiseOperation(execution_policy, std::divides<>{}, input1, input2);
}
template<arithmetic ElementT = double>
constexpr static auto abs(const Image<ElementT>& input)
{
return pixelwiseOperation([](auto&& element) { return std::abs(element); }, input);
}
template<class ExPo, arithmetic ElementT = double>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr static auto abs(ExPo execution_policy, const Image<ElementT>& input)
{
return pixelwiseOperation(execution_policy, [](auto&& element) { return std::abs(element); }, input);
} | {
"domain": "codereview.stackexchange",
"id": 42636,
"lm_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++, algorithm, image, error-handling, c++20",
"url": null
} |
c++, algorithm, image, error-handling, c++20
template<arithmetic ElementT = double>
constexpr static auto difference(const Image<ElementT>& input1, const Image<ElementT>& input2)
{
return pixelwiseOperation([](auto&& element1, auto&& element2) { return std::abs(element1 - element2); }, input1, input2);
}
template<arithmetic ElementT = double>
constexpr static ElementT manhattan_distance(const Image<ElementT>& input1, const Image<ElementT>& input2)
{
is_size_same(input1, input2);
return recursive_reduce(difference(input1, input2).getImageData(), ElementT{});
}
}
/* Matlab version:
function Dictionary = CreateDictionary(ND, xsize, ysize, zsize)
Dictionary.X = zeros(xsize, ysize, zsize, ND);
Dictionary.Y = zeros(xsize, ysize, zsize, ND);
for i = 1:ND
Dictionary.X(:, :, :, i) = ones(xsize, ysize, zsize) .* (i / ND);
Dictionary.Y(:, :, :, i) = ones(xsize, ysize, zsize) .* (1 + i / ND);
end
end
*/
template<class ElementT = double>
constexpr static auto create_dictionary(const std::size_t ND, const std::size_t xsize, const std::size_t ysize, const std::size_t zsize)
{
auto code_words_x = TinyDIP::n_dim_vector_generator<1>(std::vector<TinyDIP::Image<ElementT>>(), ND);
auto code_words_y = TinyDIP::n_dim_vector_generator<1>(std::vector<TinyDIP::Image<ElementT>>(), ND);
for (std::size_t i = 0; i < ND; ++i)
{
code_words_x[i] = TinyDIP::n_dim_vector_generator<1>(
TinyDIP::Image<ElementT>(xsize, ysize, static_cast<ElementT>(i) / static_cast<ElementT>(ND)), zsize);
code_words_y[i] = TinyDIP::n_dim_vector_generator<1>(
TinyDIP::Image<ElementT>(xsize, ysize, 1.0 + static_cast<ElementT>(i) / static_cast<ElementT>(ND)), zsize);
}
return std::make_tuple(code_words_x, code_words_y);
} | {
"domain": "codereview.stackexchange",
"id": 42636,
"lm_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++, algorithm, image, error-handling, c++20",
"url": null
} |
c++, algorithm, image, error-handling, c++20
/* Matlab version:
function [output] = dictionaryBasedNonlocalMean(Dictionary, input)
gaussian_sigma = 0.1;
gaussian_mean = 0;
if size(Dictionary.X) ~= size(Dictionary.Y)
disp("Size of data in dictionary incorrect.");
output = [];
return
end
[X, Y, Z, DataCount] = size(Dictionary.X);
weightOfEach = zeros(1, DataCount);
for i = 1:DataCount
% Gaussian of distance between X and input
weightOfEach(i) = gaussmf(ManhattanDistance(input, Dictionary.X(:, :, :, i)), [gaussian_sigma gaussian_mean]);
end
sumOfDist = sum(weightOfEach, 'all');
output = zeros(X, Y, Z);
%%% if sumOfDist too small
if (sumOfDist < 1e-160)
fprintf("sumOfDist = %d\n", sumOfDist);
return;
end
for i = 1:DataCount
output = output + Dictionary.Y(:, :, :, i) .* weightOfEach(i);
end
output = output ./ sumOfDist;
end
*/ | {
"domain": "codereview.stackexchange",
"id": 42636,
"lm_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++, algorithm, image, error-handling, c++20",
"url": null
} |
c++, algorithm, image, error-handling, c++20
template<class ExPo, class ElementT = double>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr static auto dictionaryBasedNonlocalMean( ExPo execution_policy,
const std::tuple<
std::vector<std::vector<TinyDIP::Image<ElementT>>>,
std::vector<std::vector<TinyDIP::Image<ElementT>>>
>& dictionary,
const std::vector<TinyDIP::Image<ElementT>>& input,
const double gaussian_sigma = 3.0,
const double gaussian_mean = 0,
const double threshold = 1e-160)
{
std::vector<TinyDIP::Image<ElementT>> output =
TinyDIP::n_dim_vector_generator<1>(
TinyDIP::Image(input[0].getWidth(), input[0].getHeight(), 0.0), input.size());
auto code_words_x = std::get<0>(dictionary);
auto code_words_y = std::get<1>(dictionary);
if (code_words_x.size() != code_words_y.size())
{
throw std::runtime_error("Size of data in dictionary incorrect.");
}
auto weights = TinyDIP::recursive_transform<1>(
execution_policy,
[&](auto&& element)
{
return TinyDIP::normalDistribution1D(
TinyDIP::recursive_reduce(
TinyDIP::recursive_transform<1>(
[&](auto&& each_plane_x, auto&& each_plane_input) { return TinyDIP::manhattan_distance(each_plane_x, each_plane_input); },
element, input),
ElementT{}) + gaussian_mean,
gaussian_sigma);
}, code_words_x);
auto sum_of_weights = TinyDIP::recursive_reduce(weights, ElementT{}); | {
"domain": "codereview.stackexchange",
"id": 42636,
"lm_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++, algorithm, image, error-handling, c++20",
"url": null
} |
c++, algorithm, image, error-handling, c++20
}, code_words_x);
auto sum_of_weights = TinyDIP::recursive_reduce(weights, ElementT{});
std::cout << "sum_of_weights: " << std::to_string(sum_of_weights) << '\n';
if (sum_of_weights < threshold)
{
return output;
}
auto outputs = TinyDIP::recursive_transform<1>(
[&](auto&& input1, auto&& input2)
{
return TinyDIP::multiplies(input1, TinyDIP::n_dim_vector_generator<1>(TinyDIP::Image(input1[0].getWidth(), input1[0].getHeight(), input2), input1.size()));
}, code_words_y, weights);
for (std::size_t i = 0; i < outputs.size(); ++i)
{
output = TinyDIP::plus(output, outputs[i]);
}
output = TinyDIP::divides(output, TinyDIP::n_dim_vector_generator<1>(TinyDIP::Image(output[0].getWidth(), output[0].getHeight(), sum_of_weights), output.size()));
return output;
} | {
"domain": "codereview.stackexchange",
"id": 42636,
"lm_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++, algorithm, image, error-handling, c++20",
"url": null
} |
c++, algorithm, image, error-handling, c++20
void dictionaryBasedNonLocalMeanTest()
{
std::size_t ND = 10;
std::size_t xsize = 8;
std::size_t ysize = 8;
std::size_t zsize = 1;
std::vector<TinyDIP::Image<double>> input;
for (std::size_t z = 0; z < zsize; ++z)
{
input.push_back(TinyDIP::Image(xsize, ysize, 0.66));
}
dictionaryBasedNonlocalMean(
std::execution::par,
create_dictionary(ND, xsize, ysize, zsize),
input
).at(0).print();
}
int main()
{
auto start = std::chrono::system_clock::now();
dictionaryBasedNonLocalMeanTest();
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::cout << "Computation finished at " << std::ctime(&end_time) << "elapsed time: " << elapsed_seconds.count() << '\n';
return 0;
}
The output of the testing code above:
sum_of_weights: 1.150129
1.66217 1.66217 1.66217 1.66217 1.66217 1.66217 1.66217 1.66217
1.66217 1.66217 1.66217 1.66217 1.66217 1.66217 1.66217 1.66217
1.66217 1.66217 1.66217 1.66217 1.66217 1.66217 1.66217 1.66217
1.66217 1.66217 1.66217 1.66217 1.66217 1.66217 1.66217 1.66217
1.66217 1.66217 1.66217 1.66217 1.66217 1.66217 1.66217 1.66217
1.66217 1.66217 1.66217 1.66217 1.66217 1.66217 1.66217 1.66217
1.66217 1.66217 1.66217 1.66217 1.66217 1.66217 1.66217 1.66217
1.66217 1.66217 1.66217 1.66217 1.66217 1.66217 1.66217 1.66217
Computation finished at Sat Dec 18 02:22:04 2021
elapsed time: 0.000108249
A Godbolt link is here.
TinyDIP on GitHub
All suggestions are welcome.
The summary information:
Which question it is a follow-up to?
Manhattan distance calculation between two images in C++ and
Dictionary based non-local mean implementation in Matlab
What changes have been made in the code since last question?
As the suggestions from G. Sliepen's answer and JDługosz's answer, these changes have been made: | {
"domain": "codereview.stackexchange",
"id": 42636,
"lm_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++, algorithm, image, error-handling, c++20",
"url": null
} |
c++, algorithm, image, error-handling, c++20
Unnecessary usages of this-> and TinyDIP:: are removed
The updated version of Image class has been proposed.
Why a new review is being asked for?
If there is any possible improvement, please let me know.
Answer: I don't have the time at the moment for a full review, but here are some things I noticed that may help you improve your code.
Free your functions
The operator+ and operator- don't need to be friend functions because they don't rely on any internal knowledge of the Image class. See also Klaus Iglberger's 2017 CppCon talk. In fact, they can be made even simpler per the next suggestion.
Use the canonical definition for operators
The typical way to define a function such as operator+ is to define it in terms of operator+= which makes things simple for copyable types:
template<class ElementT>
Image<ElementT> operator+(Image<ElementT> input1, const Image<ElementT>& input2)
{
return input1 += input2;
}
Note that input1 is passed by value so a copy is made. Then we use operator+= with input2. | {
"domain": "codereview.stackexchange",
"id": 42636,
"lm_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++, algorithm, image, error-handling, c++20",
"url": null
} |
c#
Title: Custom blocking priority queue
Question: I created priority queue which stores messages sent from asp net core controller and
then processes them in BackgroundService
The thread which loops through items is blocked when collection is empty.
It might look like reinventing the wheel as there is already BlockingCollectionOfT but I am clueless how to extend that thing to my scenario.
Are there any code smells, concurrency hazards?
Perhaps there might be even better way to do it.
I would like to hear your opinion
Thanks
Implementation
internal class BPQueue : IBPQueue, IDisposable
{
private readonly BaseMessage[] _items;
private readonly object _syncRoot = new();
private readonly ManualResetEventSlim _manualResetEventSlim;
private int _head;
public BPQueue ()
{
_items = new BaseMessage[100];
_head = -1;
_manualResetEventSlim = new ();
}
public bool TryEnqueue(BaseMessage message)
{
lock (_syncRoot)
{
if(_head + 1 == _items.Length)
{
return false;
}
_head++;
_items[_head] = message;
}
if (!_manualResetEventSlim.IsSet)
{
_manualResetEventSlim.Set();
}
return true;
}
public IEnumerable<BaseMessage> GetEnumerable(CancellationToken token = default)
{
while(true)
{
token.ThrowIfCancellationRequested();
if(_head == -1)
{
_manualResetEventSlim.Reset();
_manualResetEventSlim.Wait(token);
}
BaseMessage item;
lock (_syncRoot)
{
item = _items[_head];
_items[_head] = null;
_head--;
} | {
"domain": "codereview.stackexchange",
"id": 42637,
"lm_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#
yield return item;
}
}
public void Dispose()
{
_manualResetEventSlim.Dispose();
}
}
Message base class
public abstract class BaseMessage : IComparable<BaseMessage>
{
public Priority Priority { get; }
public BaseMessage(Priority priority)
{
Priority = priority;
}
public int CompareTo(BaseMessage? other)
{
if (other == null)
{
return -1;
}
if (Priority < other.Priority)
{
return 1;
}
if (Priority > other.Priority)
{
return -1;
}
return 0;
}
How is it used
Example controller
public class QueueController : ControllerBase
{
private readonly IBPQueue _queue;
public QueueController(IBPQueue queue)
{
_queue = queue;
}
[HttpPost]
public IActionResult AddMessage([FromBody] SampleMessage sampleMessage)
{
var enqueued = _queue.TryEnqueue(sampleMessage);
if (!enqueued)
{
return BadRequest();
}
return Ok();
}
}
Background service
internal class MessageProcessorHostedService : BackgroundService
{
private readonly ILogger _logger;
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly IBPQueue _queue;
public TaskQueueHostedService(
ILogger<MessageProcessorHostedService> logger,
IServiceScopeFactory serviceScopeFactory,
IBPQueue queue)
{
_logger = logger;
_serviceScopeFactory = serviceScopeFactory;
_queue = queue;
} | {
"domain": "codereview.stackexchange",
"id": 42637,
"lm_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#
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await Task.Run(async () =>
{
foreach (var message in _blockingPriorityQueue.GetEnumerable(stoppingToken))
{
try
{
stoppingToken.ThrowIfCancellationRequested();
using var serviceScope = _serviceScopeFactory.CreateScope();
var serviceProvider = serviceScope.ServiceProvider;
var messageHandler = serviceProvider.GetMessageHandler(message);
await messageHandler.HandleAsync(message);
stoppingToken.ThrowIfCancellationRequested();
}
catch (OperationCanceledException)
{
_logger.LogInformation("Queue has been stopped");
break;
}
catch (Exception ex)
{
_logger.LogError("An error occurred while processing queue", ex);
}
}
}, stoppingToken);
}
}
Priority
public enum Priority : byte
{
High = 0,
Medium = 1,
Low = 2
}
Answer: First let me share with you my observations related to your current implementation.
Then let me show you how to rewrite it to take advantage of IAsyncEnumerable.
BPQueue
Init
readonly field initialization: You don't need the constructor to initialize them, you can do that in-line
private readonly BaseMessage[] _items = new BaseMessage[100];
private readonly object _syncRoot = new();
private readonly ManualResetEventSlim _manualResetEventSlim = new();
private int _head = -1;
TryEnqueue
is there any free space: I think you can better express your intent if write the condition like this
if (_head == _items.Length - 1) | {
"domain": "codereview.stackexchange",
"id": 42637,
"lm_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#
if (_head == _items.Length - 1)
Reasoning: _head is an array index and you want to avoid over indexing
GetEnumerable
infinite loop: At the first glance it is not obvious whether it is an infinite loop or will it terminate in case of cancellation
If you write your main loop like this then yet again your intent becomes more clear IMHO
while (!token.IsCancellationRequested)
{
...
}
token.ThrowIfCancellationRequested();
Reasoning: Until it is not cancelled do that ... otherwise bubble up the cancellation
BaseMessage
CompareTo
If you use switch expression with case guards the whole method become more concise
public int CompareTo(BaseMessage? other) => other switch
{
null => -1,
var msg when msg.Priority > Priority => 1,
var msg when msg.Priority < Priority => -1,
_ => 0
};
Your GetEnumerator is blocked whenever there is no message to fetch. Since the introduction of Async Enumerables you can rewrite it to make it non-blocking.
Unfortunately there is no built-in async version of the ManualResetEvent
But Microsoft.VisualStudio.Threading does define an AsyncManualResetEvent
As well as the AutoResetEvent can be replaced with SemaphoreSlim.
Here is my version where I have used SemaphoreSlim:
internal class BPQueue<T>: IDisposable, IAsyncEnumerable<T> where T: class
{
private readonly T[] _items = new T[100];
private readonly object _syncRoot = new();
private readonly SemaphoreSlim isThereAnyData = new(0,1);
private int _head = -1;
public bool TryEnqueue(T message)
{
lock (_syncRoot)
{
if (_head == _items.Length - 1)
return false;
_head++;
_items[_head] = message;
if(_head == 0)
isThereAnyData.Release();
}
return true;
} | {
"domain": "codereview.stackexchange",
"id": 42637,
"lm_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#
return true;
}
public async IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken token = default)
{
while (!token.IsCancellationRequested)
{
if (_head == -1)
await isThereAnyData.WaitAsync(token);
T item;
lock (_syncRoot)
{
item = _items[_head];
_items[_head] = null;
_head--;
}
yield return item;
}
token.ThrowIfCancellationRequested();
}
public void Dispose() => isThereAnyData.Dispose();
}
I've initialized the SemaphoreSlim with 0 as initial value and 1 as the max
Inside the TryEnqueue I call the Release only if the _head was -1 prior this method call
Inside the GetAsyncEnumerator I call the WaitAsync if the _head is -1 to wait until there is some data to retrieve
The class itself implements IAsyncEnumerable so the GetAsyncEnumerator method returns an IAsyncEnumerator
Please note there is no need here to define the return type as Task<IAsyncEnumerator> to be able to use async-await inside the method
I've made your class generic because it was tightly coupled to the BaseMessage
Here is the code which I've used for testing:
static async Task Main()
{
var _queue = new BPQueue<SampleMessage>();
CancellationTokenSource cts = new();
_ = Task.Run(async () => {
await Task.Delay(2000);
_queue.TryEnqueue(new(Priority.Medium));
await Task.Delay(2000);
_queue.TryEnqueue(new(Priority.Medium));
_queue.TryEnqueue(new(Priority.High));
await Task.Delay(500);
_queue.TryEnqueue(new(Priority.High));
}); | {
"domain": "codereview.stackexchange",
"id": 42637,
"lm_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#
_ = Task.Run(async () => {
await Task.Delay(1750);
_queue.TryEnqueue(new(Priority.High));
await Task.Delay(2300);
_queue.TryEnqueue(new(Priority.Low));
_queue.TryEnqueue(new(Priority.High));
await Task.Delay(300);
cts.Cancel();
});
try
{
await foreach (var item in _queue.WithCancellation(cts.Token))
{
Console.WriteLine(item.Priority);
}
}
catch (OperationCanceledException)
{
Console.WriteLine("Operation has been cancelled");
}
}
There is a known limitation. The async foreach should start prior the first item is pushed into the queue, since the SemaphoreSlim has been initialized with 0. | {
"domain": "codereview.stackexchange",
"id": 42637,
"lm_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
} |
python
Title: Get words from a list in Python and assign it to a variable
Question: I made this code to search for words and put it in a variable:
nfo_labels = 'some phrase Horror'
if "Apocalyptic" in nfo_labels:
nfo_genre_1 = 'Apocalyptic,'
else:
nfo_genre_1 = ''
if "Horror" in nfo_labels:
nfo_genre_2 = 'Horror,'
else:
nfo_genre_2 = ''
if "Mystery" in nfo_labels:
nfo_genre_3 = 'Mystery,'
else:
nfo_genre_3 = ''
if "Gothic" in nfo_labels:
nfo_genre_4 = 'Gothic,'
else:
nfo_genre_4 = ''
nfo_genre = nfo_genre_1 + nfo_genre_2 + nfo_genre_3 + nfo_genre_4
print(nfo_genre)
I know it's bad, but I used to get the data I want from a list(code below), which works, but the data was each word to a line, and I wanted like 'word,word'. I am learning python, what can I improve?
The code I have is this:
nfo_labels = 'some phrase Horror'
nfo_genre = ''
total_genres_list = ['Apocalyptic', 'Horror', 'Sci-Fi']
for r in total_genres_list:
if r in nfo_labels:
nfo_genre = r
print(nfo_genre)
else:
pass
Answer: Rather than spawning many similar variable names with numeric suffixes, use
collections: (1) define a collection of all genres; (2) define a collection of
genres found in a specific phrase:
all_genres = ['Apocalyptic', 'Horror', 'Sci-Fi', 'Gothic', 'Mystery']
phrase = 'The Mystery of the Apocalyptic Loop'
genres = [g for g in all_genres if g in phrase]
Printing is an entirely separate matter. If the data is well organized,
printing is almost always easy. For example:
print(*genres, sep = ', ')
Structuring data well is the key to effective programming: smart data, simple code. | {
"domain": "codereview.stackexchange",
"id": 42638,
"lm_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",
"url": null
} |
c++, palindrome, c++20
Title: Checking whether a string is a permutation of a palindrome in C++20
Question: (See the next iteration/follow-up here.)
I have this short function is_permutation_palindrome, which returns true only if the input string may be rearranged to form a palindrome:
#include <iostream>
#include <string>
#include <unordered_map>
bool is_permutation_palindrome(const std::string& text)
{
std::unordered_map<char, size_t> counter_map;
for (const auto ch : text)
++counter_map[ch];
size_t number_of_odd_chars = 0;
for (const auto &pair: counter_map)
if (counter_map[pair.first] % 2 == 1)
{
++number_of_odd_chars;
if (number_of_odd_chars > 1)
return false;
}
return true;
}
int main() {
std::cout << std::boolalpha;
std::cout << is_permutation_palindrome("yash") << "\n";
std::cout << is_permutation_palindrome("vcciv") << "\n";
std::cout << is_permutation_palindrome("abnnab") << "\n";
}
Critique request
I believe that there must be a more idiomatic way of implementing that function, and would like to hear about it.
Answer: While your algorithm is \$O(n)\$, the constant factors are considerable. Specifically, you are suffering due to all the nodes the map needs.
Better options are:
Just std::sort() and then do a single pass. While the order is \$O(n * log(n))\$, it will probably still be far more efficient.
Use an array for a histogram. 256 elements (wrap-around of an unsigned type would be safe, so unsigned char suffices, or even flipping a bool) should fit comfortably.
Even if you are on a rare platform with bigger bytes, it ought to fit or you have bigger problems with your current implementation.
While the order is the same, the constants are far smaller.
Regarding your implementation:
Unless you need a null-terminated read-only string, passing by std::string const& is very sub-optimal. Considering your chosen algorithm, std::string_view would be best. | {
"domain": "codereview.stackexchange",
"id": 42639,
"lm_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++, palindrome, c++20",
"url": null
} |
c++, palindrome, c++20
You could mark your algorithm constexpr.
noexcept unfortunately eludes you due to all the allocations.
constexpr bool is_permutation_palindrome(std::string_view s) noexcept {
unsigned char counts[1u + (unsigned char)-1] {};
for (unsigned char c : s)
++counts[c];
return std::ranges::count_if(counts, [](auto a){ return a % 2; }) < 2;
} | {
"domain": "codereview.stackexchange",
"id": 42639,
"lm_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++, palindrome, c++20",
"url": null
} |
python, performance, python-3.x, pyqt, minesweeper
Title: Display routine for Minesweeper on PyQT5
Question: I'm trying to recreate minesweeper in python with PyQT5.
I have this function that updates the GUI by using nested for loops (one for column, and one for row) to check each cell in a 19x19 area to determine what type of tile said cell is.
The function works as intended, but runs very slow and takes around 4 seconds to complete. I have tried using threading, but this further harms performance. | {
"domain": "codereview.stackexchange",
"id": 42640,
"lm_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, performance, python-3.x, pyqt, minesweeper",
"url": null
} |
python, performance, python-3.x, pyqt, minesweeper
Here is the code:
(I know it's not the best, it's still a prototype)
def update_display(self):
if(Debug == 1):
print("[Updating Cells...]")
for column in range(self.cells):
#print(column)
for row in range(self.cells):
#print(row)
#if(Debug == 1):
# print("[Changing tile ({},{})]".format(row,column))
if self.initialArray[row][column] <= 9:
self.button[row, column].setIcon(QtGui.QIcon(dataFolder + 'tile_plain.gif'))
elif self.initialArray[row][column] == 10:
self.button[row, column].setIcon(QtGui.QIcon(dataFolder + 'tile_clicked.gif'))
elif self.initialArray[row][column] == 11:
self.button[row, column].setIcon(QtGui.QIcon(dataFolder + 'tile_1.gif'))
elif self.initialArray[row][column] == 12:
self.button[row, column].setIcon(QtGui.QIcon(dataFolder + 'tile_2.gif'))
elif self.initialArray[row][column] == 13:
self.button[row, column].setIcon(QtGui.QIcon(dataFolder + 'tile_3.gif'))
elif self.initialArray[row][column] == 14:
self.button[row, column].setIcon(QtGui.QIcon(dataFolder + 'tile_4.gif'))
elif self.initialArray[row][column] == 15:
self.button[row, column].setIcon(QtGui.QIcon(dataFolder + 'tile_5.gif'))
elif self.initialArray[row][column] == 16:
self.button[row, column].setIcon(QtGui.QIcon(dataFolder + 'tile_6.gif'))
elif self.initialArray[row][column] == 19: | {
"domain": "codereview.stackexchange",
"id": 42640,
"lm_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, performance, python-3.x, pyqt, minesweeper",
"url": null
} |
python, performance, python-3.x, pyqt, minesweeper
elif self.initialArray[row][column] == 19:
self.button[row, column].setIcon(QtGui.QIcon(dataFolder + 'tile_flag.gif'))
elif self.initialArray[row][column] == 29:
self.button[row, column].setIcon(QtGui.QIcon(dataFolder + 'tile_mine.gif')) | {
"domain": "codereview.stackexchange",
"id": 42640,
"lm_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, performance, python-3.x, pyqt, minesweeper",
"url": null
} |
python, performance, python-3.x, pyqt, minesweeper
Is there a faster way to do this?
(Preferably < 1 second as it needs to draw each cell)
If it helps any, I am using Python 3.10
Answer: I have a hard time believing that your loop is taking 4 seconds. If you're playing a reasonable minesweeper game, even at 100x100, that's just far too long.
Obviously, then, you must either be playing an unreasonably-sized game, or there's a performance problem in the Qt parts of your code. ;-)
Assuming the problem lies in the individual cases, the answer is two-fold:
First, stop checking all those cases!
Second, don't repeat work inside the cases.
Stop checking all the cases
Instead, use some kind of case to result mapping that you can look up at O(1). In this case, even with some holes in the indices, I'd recommend a list.
The simplest list (not recommended) would be a mapping of index values to file names:
Tile_files = [ 'tile_plain.gif' ] * 10 \
+ ...
With that you could look up the integer value and get either None or a string result. This would eliminate all the if / then / else redundancy from your code.
Don't repeat work
However, even with using a map to convert from sequential if statements, you're still repeating computations for each cell. At some level, you should be able to stop doing that without causing a problem. I think that level is the the icon image. Your buttons all have to be separate buttons, because you are using the buttons to encode the identity of the cells. But the images associated with the buttons can be shared.
So share them! Do the computation of dataFolder + file one time. Convert the path to an icon one time. Cache the result!
Instead of a mapping of tile # -> file path, let the mapping be from tile # -> icon image. | {
"domain": "codereview.stackexchange",
"id": 42640,
"lm_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, performance, python-3.x, pyqt, minesweeper",
"url": null
} |
c++, beginner, graph
Title: Finding cycles in graph
Question: I found this code for Java to find if graph has cycles and I edited it to print out path of cycle. I use adjacency list. As it is directed weighted graph I will need to implement compensations of cycles (if we have (1)--(2500)--> (2)--(2000)--> (3)--(1000)-->(1) then (1)--(1500)--> (2)--(1000)--> (3)--(0)-->(1)). Nevermind that, I tested this code with two graphs and it worked, I wanna know if there's something that could be done better and is there a way that this code crashes?
class Graph {
protected:
int num_ver;
vector <vector <pair <int, int> > > graph;
...
}
bool Graph::find_cycles() {
vector<int> white_set;
vector<int> grey_set;
vector<int> black_set;
vector<bool> visited(num_ver, false);
for (int vertex = 0; vertex < num_ver; vertex++) {
white_set.push_back(vertex);
}
for (int i = 0; 0 < graph[i].size(); i++) {
std::stack<int> stack;
if (visited[i] == false) {
stack.push(i);
if (dfs_cyc(i, white_set, grey_set, black_set, stack, visited)) {
if (stack.top() != i)
stack.push(i);
print_cycle(stack);
}
}
}
return false;
} | {
"domain": "codereview.stackexchange",
"id": 42641,
"lm_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, graph",
"url": null
} |
c++, beginner, graph
bool Graph::dfs_cyc(int i, vector<int>& white_set, vector<int>& gray_set, vector<int>& black_set, std::stack<int>& stack, vector<bool>& visited) {
//move current to gray set from white set and then explore it.
visited[i] = true;
move_vertex(i, white_set, gray_set);
for (int j = 0; j < graph[i].size(); j++) {
int neighbor = graph[i][j].first;
//if in black set means already explored so continue.
if (std::find(black_set.begin(), black_set.end(), neighbor) != black_set.end()) {
continue;
}
//if in gray set then cycle found.
if (std::find(gray_set.begin(), gray_set.end(), neighbor) != gray_set.end()) {
stack.push(neighbor);
return true;
}
if (dfs_cyc(neighbor, white_set, gray_set, black_set, stack, visited)) {
stack.push(neighbor);
return true;
}
}
//move vertex from gray set to black set when done exploring.
move_vertex(i, gray_set, black_set);
return false;
}
void Graph::move_vertex(int vertex, vector<int>& source_set, vector<int>& destination_set) {
source_set.erase(std::remove(source_set.begin(), source_set.end(), vertex), source_set.end());
destination_set.push_back(vertex);
}
void Graph::print_cycle(std::stack<int>& stack){
int ver = stack.top();
cout << "Cicles: ";
for(int i = 0; ; i++){
if (i != 0 && ver == stack.top()) {
cout << stack.top() + 1 << endl;
break;
}
cout << stack.top() + 1 << "->";
stack.pop();
}
}
Answer: Give names to things
There are several problems with this variable declaration:
vector <vector <pair <int, int> > > graph; | {
"domain": "codereview.stackexchange",
"id": 42641,
"lm_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, graph",
"url": null
} |
c++, beginner, graph
First, the variable should probably not named graph, as that is already the name of the class it is in. Since the outer std::vector contains information about each vertex in the graph, I would name this variable vertices.
Second, it is very hard to see what the type of this variable represents. If you would translate it to English, it says "a graph is a vector of a vector of a pair of integers". That is not very helpful at all. It would be much nicer if the declaration would say something similar to: "a graph is a set of vertices, and each vertex has a list of neihbors". Translated back into C++, that could look like:
struct Edge {
int vertex;
int weight;
};
struct Vertex {
std::vector<Edge> neighbors;
};
std::vector<Vertex> vertices;
Third, the pair<int, int> is now an Edge, but it still contains two ints. You can make aliases for these ints to make the meaning of it even more clear, while also making it easier to change those types later:
using VertexID = int;
using Weight = int;
struct Edge {
VertexID vertex;
Weight weight;
} | {
"domain": "codereview.stackexchange",
"id": 42641,
"lm_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, graph",
"url": null
} |
c++, beginner, graph
struct Edge {
VertexID vertex;
Weight weight;
}
Choose the right type for indices and weights
An int might not be large enough to store all possible indices into a std::vector. The proper type to use that is guaranteed to be large enough to be able to index every item in memory is std::size_t. It also has the advantage that it matches the return type of std::vector::size(), so you won't get any warnings from the compiler about comparing signed and unsigned integers.
For weights, maybe an int is the right type. But do consider the maximum value you need, and if negative weights are allowed. If not, an unsigned integer type might be more appropriate.
Don't store redundant information
There is no need to store num_ver if you have a vector of vertices. You can just use vertices.size() instead. Apart from using memory unnecessarily, if two values that should be the same go out of sync (maybe because of programming errors), you will run into problems. So it is best to avoid it.
Use std::vector<bool> for the white/grey/black sets
A std::vector<int> is not the most optimal way to store which color a vertex has during your cycle-finding algorithm. Finding and erasing random items in a std::vector are \$O(N)\$ operations, where \$N\$ is the size of the vector. Instead, use std::vector<bool>, like you did for visited. For example, dfs_cyc then becomes:
visited[i] = true;
white_set[i] = false;
grey_set[i] = true;
for (VertexID j = 0; j < vertices[i].neighbors.size(); j++) {
VertexID neighbor = vertices[i].neighbors[j].vertex;
if (black_set[neighbor]) {
continue;
}
if (gray_set[neighbor]) {
stack.push(neighbor);
return true;
}
...
}
gray_set[i] = false;
black_set[i] = true;
return false; | {
"domain": "codereview.stackexchange",
"id": 42641,
"lm_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, graph",
"url": null
} |
c++, beginner, graph
...
}
gray_set[i] = false;
black_set[i] = true;
return false;
Make find_cycles() return the cycles
The problem with find_cycles() calling print_cycles() is that this is now the only things the function can do: print cycles. If instead you don't print them out immediately, but just return the set of cycles found, the caller can decide what to do with the cycles: either print them, or do something else. It could look like:
struct Cycle {
std::vector<VertexID> vertices;
};
std::vector<Cycle> Graph::find_cycles() {
std::vector<Cycle> cycles;
...
...
if (dfs_cyc(...)) {
if (stack.top() != i)
stack.push(i);
cycles.push_back(pop_cycle(stack));
}
...
...
return cycles;
}
Cycle Graph::pop_cycle(std::stack<VertexID> &stack) {
Cycle cycle;
VertexID start = stack.top();
while (true) {
cycle.vertices.push_back(stack.top());
if (stack.top() == start)
break;
stack.pop();
};
return cycle;
}
Avoid putting everything into a class
Java requires all functions to be part of a class, but that is not a requirement in C++. Consider that a graph algorithm is not part of a graph, but rather something that acts upon a graph. So, you could make class Graph a simple struct instead;
struct Graph {
...
struct Vertex {
...
};
std::vector<Vertex> vertices;
};
And have find_cycles() be a free-standing function that takes a Graph as an input:
std::vector<Cycle> find_cycles(const Graph &graph) {
...
};
Then your main() could look like:
Graph graph;
graph.vertices.push_back(...);
...
Cycles cycles = find_cycles(graph);
for (auto &cycle: cycles)
print_cycles(cycle); | {
"domain": "codereview.stackexchange",
"id": 42641,
"lm_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, graph",
"url": null
} |
c++, beginner, graph
Use '\n' instead of std::endl
Prefer using '\n' instead of std::endl; the latter is equivalent to the former, but also forces the output to be flushed, which is usually not necessary and will lower performance.
Can it crash?
Your code doesn't contain any obvious bugs, you are using STL containers so there are no memory allocation issues to worry about. There are two things I would worry about:
Input validation: are the vertex indices stored in the graph valid indices? If you are reading adjacency lists from a file for example, and there is a number in such a list that is equal or larger than the number of vertices in your graph, then you risk accessing an element past the end of the vector of vertices. This will cause a segmentation fault if you are lucky, or worse the algorithm will continue but the results are undefined.
Infinite loops. If there is an error in the algorithm, it might be that it never terminates. This would then cause it to go into an infinite loop, if you are lucky it would use more and more memory and eventually crash because you run out of memory. However, your code is fine; the only place where such a thing could happen is when dfs_cyc() calls itself recursively, but this only happens for vertices in the white set, and every time it calls itself, it moves that vertex from the white to the grey set, so this guarantees termination.
Note that computers do not have infinite memory, so technically it might still crash if your input is large enough; either because it cannot do heap allocations for the std::vectors you create, or because dfs_cyc() calls itself with such a high recursion depth that you run out of stack space. | {
"domain": "codereview.stackexchange",
"id": 42641,
"lm_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, graph",
"url": null
} |
c, random, windows, ip-address
Title: Generating a random ipaddress in C
Question: I was looking to receive some feedback on the function I wrote to generate a random ip address. The code is pretty messy and just wanted some feedback regarding optimizations, memory leaks and best practices. I am aware that there are ip ranges that this could generate that don't actually exist but for my project it's fine if it generates non-existent local addresses.
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
int random_int(int limit) {
HCRYPTPROV crypt;
byte *buf = (byte *)malloc(1);
if (CryptAcquireContext(&crypt, NULL, NULL, PROV_RSA_AES, CRYPT_SILENT)) {
if (CryptGenRandom(crypt, sizeof(buf), buf)) {
CryptReleaseContext(crypt, 0);
return (int)buf % limit;
}
}
return 0;
}
int num_places(int n) {
if (n < 0) return num_places((n == INT_MIN) ? INT_MAX : -n);
if (n < 10) return 1;
return 1 + num_places(n / 10);
}
char* random_ip() {
char* ip = (char*)malloc(1);
int total_size = 1;
for (int i = 0; i < 4; i++) {
int realloc_size = 0;
int rand_num = random_int(255);
realloc_size = num_places(rand_num);
if (i != 3) {
realloc_size++;
}
total_size += realloc_size;
ip = realloc(ip, (total_size) * sizeof(char));
char* str_ip = (char*)malloc(1);
if (i == 3) {
str_ip = (char*)realloc(str_ip, (realloc_size + 1) * sizeof(char));
snprintf(str_ip, realloc_size + 1, "%d", rand_num);
}
else {
str_ip = (char*)realloc(str_ip, (realloc_size + 1) * sizeof(char));
snprintf(str_ip, realloc_size + 1, "%d.", rand_num);
}
ip[total_size - realloc_size - 1] = '\0';
strncat_s(ip, total_size, str_ip, realloc_size+1);
free(str_ip);
}
return ip;
}
int main(){
printf("GeneratedIpAddress: %s\n",random_ip());
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 42642,
"lm_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, random, windows, ip-address",
"url": null
} |
c, random, windows, ip-address
int main(){
printf("GeneratedIpAddress: %s\n",random_ip());
return 0;
}
Answer: Bugs
return (int)buf % limit; makes little sense to me. Why take a pointer and form a "random" number from the pointer.
Perhaps you meant: return buf[0] % limit; to take the value of what the pointer points to. Note that this % limit imparts a bias when limit is not a power-of-2. It is 255 in OP's code. OP, was it your intent to form values [0.. 254] (like this code does) or [0...255]?
CryptGenRandom(crypt, sizeof(buf), buf) is questionable too. Why does CryptGenRandom() care to know the size of a pointer as with sizeof(buf)? I'd expect 1 instead, the size of the allocation.
CryptGenRandom() looks deprecated.
Alternate digit counter
Just a small idea alternative: no recursion and no need for special handling of INT_MIN.
int num_places(int n) {
int count = 0;
do {
count++;
n /= 10;
} while (n);
return count;
}
Allocate to the refenced object, not type
Easier to code right, review and maintain.
Cast not needed either.
// str_ip = (char*)realloc(str_ip, (realloc_size + 1) * sizeof(char));
str_ip = realloc(str_ip, sizeof *str_ip * (realloc_size + 1u));
Better code checks for failed allocation
void *p = realloc(str_ip, sizeof *str_ip * (realloc_size + 1u));
if (p == NULL) Handle_Error();
str_ip = p;
Simplify allocation
Code does a lot of work allocating and re-allocating.
Instead, form a local worst case size buffer, populate that and then allocate/duplicate it once at the end.
Rather than strcat(), keep track of the length. Avoid Schlemiel the Painter code.
Simplify code with a variable separator.
No need for num_places().
#define BYTE_AS_DECIMAL_TEXT_SIZE 3
#define IP_BUF_SIZE (4*(BYTE_AS_DECIMAL_TEXT_SIZE + 1)) | {
"domain": "codereview.stackexchange",
"id": 42642,
"lm_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, random, windows, ip-address",
"url": null
} |
c, random, windows, ip-address
char* random_ip() {
char str_ip[IP_BUF_SIZE];
int offset = 0;
const char *separator = "";
for (int i = 0; i < 4; i++) {
offset += sprintf(str_ip + offset, "%s%d",
separator, random_int(255) & 255);
separator = ".";
}
return strdup(str_ip);
}
Simplify random calls
Rather than 4 calls to get 8 bits each time, consider 1 call to get 32 bits.
uint32_t r = random_32();
sprintf(str_ip, "%d.%d.%d.%d", (r >> 24) & 255, (r >> 16) & 255,
(r >> 8) & 255, (r >> 0) & 255);
Return allocated data
Better code explicitly frees allocated data.
int main(){
const char *ip_addr = random_ip();
if (ip_addr) { // add
printf("GeneratedIpAddress: %s\n", ip_addr);
free(ip_addr); // add
}
return 0;
}
Alternate allocation
Let caller provide the buffer.
//.h file
#define RANDOM_IP_SZ 16
char *random_ip(size_t sz, char buf[sz]);
// .c file
char *random_ip(size_t sz, char buf[sz]) {
char local_buf[RANDOM_IP_SZ];
// Form random IP in local_buf[]
// ...
if (strlen(local_buf) < sz) {
return strcpy(buf, local_buf);
}
return NULL; // Buffer too small
} | {
"domain": "codereview.stackexchange",
"id": 42642,
"lm_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, random, windows, ip-address",
"url": null
} |
php, laravel
Title: Optimization of a Laravel controller that passes data and views
Question: I am trying to build a website that shows events. And I use the following controller.
Please note that the urls ($view and $course) etc. are renamed and are not the ones used on the real website!
Controller:
<?php
namespace App\Http\Controllers;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Eventary;
class EventaryEventsController extends Controller
{
// function for the /kursangebote/{$course} pages
public function showEvents($course)
{
// filter the courses and set the views and id
if ($course == 'workshops') {
$view = 'pages.course.view-1';
$id = '1';
}
if ($course == 'events') {
$view = 'pages.course.view-2';
$id = '2';
}
if ($course == 'salsa') {
$view = 'pages.course.view-3';
$id = '3';
}
if ($course == 'dance4') {
$view = 'pages.course.view-4';
$id = '4';
}
if ($course == 'dance5') {
$view = 'pages.course.view-5';
$id = '5';
}
if ($course == 'dance6') {
$view = 'pages.course.view-6';
$id = '6';
}
if ($course == 'dance7') {
$view = 'pages.course.view-7';
$id = '7';
}
if ($course == 'dance8') {
$view = 'pages.course.view-8';
$id = '8';
}
// get the course data from the database
$events = Eventary::query()
->orderBy('title')
->orderBy('start')
->where('category', $id)
->where('start', '>', Carbon::now())
->get();
// pass through the data to the correct views
return view($view, [
"events" => $events
]);
} | {
"domain": "codereview.stackexchange",
"id": 42643,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, laravel",
"url": null
} |
php, laravel
}
// function for the /events page
public function workshopsList()
{
// get the course data from the database
$events = Eventary::query()
// show all events with the category 1 (events & workshops)
->where('category', '1')
->where('start', '>', Carbon::now())
->get();
// pass through the data to the correct views
return view('pages.course.event-list', [
"events" => $events
]);
}
// function for the /kalender page
public function calendarList()
{
// get the course data from the database
$events = Eventary::query()
// show all events with the category 1 (events & workshops)
->where('start', '>', Carbon::now())
->get();
// pass through the data to the correct views
return view('pages.calendar', [
"events" => $events
]);
}
// function for fullcalendar json generation
public function feed()
{
// get database
$events = DB::table('eventaries')->get();
return json_encode($events, JSON_PRETTY_PRINT);
}
}
there is a lot of code that gets reused. So I think that this is something that I should improve. But are there any other suggestions?
Answer: Put your repeated or complicated queries into scopes on the model class. Here I also use the helper now to avoid importing Carbon:
public function scopeFuture($query)
{
$query->where('start', '>', now());
}
You can even use this scope in other scopes. If you find yourself using the same scope on most to all queries, you could use a global scope, but I'm not a fan since they're usually unexpected and confusing. | {
"domain": "codereview.stackexchange",
"id": 42643,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, laravel",
"url": null
} |
php, laravel
What does your route look like for /kursangebote{$course}? If you're not constraining what $course can be, then this code will error out when someone inevitably tries to visit /kursangebotedance (no number). If you do have constraints on the route, I'd suggest not and instead making your controller responsible for returning a sensible response, e.g. if you can't match it to a category, abort(404).
Also it looks like you're expecting some partially uppercase URLs which is a confusing user experience. Everything should be lowercase, with words separated by hyphens (unless they're separated with a slash), as that's better for SEO.
What does the first "show all events with the category 1 (events & workshops)" mean? Aren't "Events" category 2? What does the second instance of this comment mean? You're not filtering on category there.
Try to avoid the magic of arbitrary numbers like '1' if you can. If you can't, consider using enums (PHP 8.1) to use a clear name instead.
The name "pages.course.view-N" is suboptimal. You don't need the word "view" because you know it's a view: it's a .blade.php file, and it's located in your "views" directory. What you don't know from looking at the file name is what type of dance it's for.
Style guides recommend using snake_case for view files, not hyphens.
If your "views" directory only contains a "pages" directory, then I would remove the "pages" directory. Even if it doesn't, it sounds like it's a catchall and not very descriptive. | {
"domain": "codereview.stackexchange",
"id": 42643,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, laravel",
"url": null
} |
php, laravel
The chain of if statements seems to me like it's indicating a deeper problem, but it's hard to give a suggestion without seeing more code. While you can use some other language construct here (such as match), I think you need a bigger rewrite.
What's the purpose of having so many different views ("course.view-N")? Is there a way that you can rewrite your view code to not need so many different views?
And why not store categories in the database? Right now, if you wanted to add more categories, you have to write more code. A database would allow you to expand and have an admin interface to add more categories as needed — or remove some. | {
"domain": "codereview.stackexchange",
"id": 42643,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, laravel",
"url": null
} |
python, git
Title: Best practices python repository. Import it as pip install
Question: I have this public repository.
Since it's the first repository I have created, I'm looking for tips on what should I improve (mainly in the GH project structure), although tips in the code would be greatly appreciated as well.
ideally, I would like to be able to import this package via the pip install command.
pip install git+https://github.com/jtorre94/dummydf
(venv) C:\Users\u339990\my_python_project>pip install git+https://github.com/jtorre94/dummydf
Collecting git+https://github.com/jtorre94/dummydf
Cloning https://github.com/jtorre94/dummydf to c:\users\myuser\appdata\local\temp\pip-req-build-0cywtbl6
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\myusers\AppData\Local\Continuum\anaconda3\lib\tokenize.py", line 447, in open
buffer = _builtin_open(filename, 'rb')
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\u339990\\AppData\\Local\\Temp\\pip-req-build-0cywtbl6\\setup.py'
Answer: Installing as a python package
To do this, you need to configure either a setup.py or setup.cfg file (or both). This defines all the requirements and settings that python should take into account when installing the package.
Documentation
You already have some documentation throughout the codebase which is great. However there are still some improvements possible.
Correct formatting of code samples
When documenting code samples, consider using >>> before every example. Apart from looking clearer (to someone who is used to the python standards), it also allows other tools to identify and parse that code.
Consider for example
doctest which can automatically test your code samples to make sure that your docs aren't lying.
Automated documentation, more on this in the next section. | {
"domain": "codereview.stackexchange",
"id": 42644,
"lm_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, git",
"url": null
} |
python, git
Render documentation
You already have the documentation present, but for a new user it can be hard to delve through the code to find documentation. Therefore there are tools that can render your documentation in a cleaner website.
The most common one for python is sphinx. You can go very far with this, but it might be nice to test the quickstart in the linked tutorial.
You can provide this with github pages to provide free hosting of the docs.
One package that uses this method of documentation is requests. Consider for example the raw code for their main api versus the rendered documentation. Of course there is still a fair amount of text, but the extra highlighting, formatting and clickable links to other parts of the code are really helpfull for people new to your codebase. | {
"domain": "codereview.stackexchange",
"id": 42644,
"lm_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, git",
"url": null
} |
c#, asp.net-core
Title: Feedback for lambda expression to count object by DateTime.Value.Month
Question: I want to count user registrations by month, currently the code I have works, but I want some feedback or some ideas on how to do it in a better way because I think mine looks a bit messy.
Using a Unit of Work Implementation with the Repository pattern:
var repository = _unitOfWork.GetBaseRepository<Customer>();
Use Lambda expression to get the CreatedOn property from the Customers object
var customerList = await repository.GetListAsync(cancellationToken: cancellationToken);
var customers = customerList.Where(q => q.DateCreated.HasValue && q.DateCreated.Value.Date <= DateTimeOffset.UtcNow);
Initialize a new Dictionary so I can use Key-Values to store the count of users on each month.
var months = new Dictionary<string, int>
{
{"January", 0}, {"February", 0},
{"March", 0}, {"April", 0},
{"May", 0}, {"June", 0},
{"July", 0}, {"August", 0},
{"September", 0}, {"October", 0},
{"November", 0}, {"December", 0}
}; | {
"domain": "codereview.stackexchange",
"id": 42645,
"lm_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#, asp.net-core",
"url": null
} |
c#, asp.net-core
iterate over the customers collection and use a switch statement to match the DateTime.Month (1-12), increment the value of key by 1.
foreach (var customer in customers)
if (customer.CreatedOn != null)
switch (customer.CreatedOn.Value.Month)
{
case 1:
months["January"] = +1;
break;
case 2:
months["February"] = +1;
break;
case 3:
months["March"] = +1;
break;
case 4:
months["April"] = +1;
break;
case 5:
months["May"] = +1;
break;
case 6:
months["June"] = +1;
break;
case 7:
months["July"] = +1;
break;
case 8:
months["August"] = +1;
break;
case 9:
months["September"] = +1;
break;
case 10:
months["October"] = +1;
break;
case 11:
months["November"] = +1;
break;
case 12:
months["December"] = +1;
break;
}
iterate with foreach over the months collection using destructuring and LINQ to transform the dictionary into a JSON response
var prettifiedList = new List<string>();
foreach (var (key, value) in months) prettifiedList.Add(@$"{key}: {value}");
return await Result<List<string>>.SuccessAsync(prettifiedList);
post was originally on stackoverflow but closed due to 'opinion-based': https://stackoverflow.com/posts/70365375 | {
"domain": "codereview.stackexchange",
"id": 42645,
"lm_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#, asp.net-core",
"url": null
} |
c#, asp.net-core
Answer: You do not say whether CreatedOn is always stored in UTC or always Local or a mix. There are a few gotcha's to be aware of when working with and comparing dates.
ONE, when comparing dates, you should make sure they are on the same Kind. This clause leaves me wondering:
q.DateCreated.Value.Date <= DateTimeOffset.UtcNow
Granted the left-hand side returns a DateTime with Kind of Unspecified. That's okay, but what really matters is the Kind of the Value itself. If Value was a local time stored in the database, then the comparison to UtcNow can produce the wrong results because they are different Kinds.
TWO, when working with dates and times, most of the time you should not worry about localization of times or month names until you are displaying. Maybe you are not thinking of running your application for 2 different cultures, but it takes little effort to do so and its a good practice.
By adhering to TWO, your code would be greatly reduced by having the dictionary be keyed by month's integer value rather than the name.
var months = Enumerable.Range(1, 12).ToDictionary(key => key, value => 0);
foreach (var customer in customers)
{
if (customer.CreatedOn.HasValue)
{
months[customer.CreatedOn.Value.Month]++;
}
}
You can display that a couple of different ways. One straightforward way, I do not recommend but here it is:
You will need an enum:
public enum MonthName
{
January = 1,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December
}
And the code to prettify:
// The limitation here is that Month enumeration has one
// very specific, very localized spelling of a month's name.
foreach (var entry in months)
{
Console.WriteLine($"{(MonthName)entry.Key} = {entry.Value}");
} | {
"domain": "codereview.stackexchange",
"id": 42645,
"lm_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#, asp.net-core",
"url": null
} |
c#, asp.net-core
Note the comment. The enum provides one very specific spelling of the month's name. This might be okay with you, but if you ever want it to run for different cultures, I would recommend skipping the enumeration and let ToString do its thing:
// In this version, the MMMM will use ToString to print the
// month name it the spelling of the current culture.
foreach (var entry in months)
{
Console.WriteLine($"{new DateTime(1, entry.Key, 1):MMMM} = {entry.Value}");
}
If an English language speaker runs the code, they get English month names. But if a French language speaker runs the code, they would get French month names. | {
"domain": "codereview.stackexchange",
"id": 42645,
"lm_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#, asp.net-core",
"url": null
} |
json, go, socket, fizzbuzz, ipc
Title: FizzBuzz JSON via Unix socket (Go)
Question: At heart, this program is just the basic "FizzBuzz" program. However, the program was pushed further, by making it a client-server via Unix Socket:
Server run, and listening on a socket.
Client run with an argument, a file containing a JSON one query or more. The client opens the file and takes the queries.
A typical JSON query would look like this: {"id":"first attempt","from":0,"to":15,"fizz":"Mango","buzz":"Avocado"}\n
and is sent through the unix socket file to the server.
The server receives the JSON message perform the FizzBuzz, and send an answer back to client (also JSON form). {"first attempt":["MangoAvocado",1,2,"Mango",4,"Avocado","Mango",7,8,"Mango","Avocado",11,"Mango",13,14,"MangoAvocado"]}
Client receives the JSON message and printout the JSON elements:
Here is the server.go:
package main
import (
"log"
"net"
"os"
"os/signal"
"syscall"
"encoding/json"
)
//thanks to https://mholt.github.io/json-to-go/
type input struct {
ID string `json:"id"`
From int `json:"from"`
To int `json:"to"`
Fizz string `json:"fizz"`
Buzz string `json:"buzz"`
}
type output struct {
Output []interface{} `json:"output"`
}
func nice(inputBytes []byte)[]byte{
var in input
json.Unmarshal(inputBytes, &in)
out := output{
Output: []interface{}{},
}
for i := in.From; i <= in.To; i++ {
if i % 3 == 0 {
if i % 5 == 0{
out.Output = append(out.Output, in.Fizz + in.Buzz)
}else{
out.Output = append(out.Output, in.Fizz)
}
}else if i % 5 == 0{
out.Output = append(out.Output, in.Buzz)
}else{
out.Output = append(out.Output, i)
}
}
d, _ := json.Marshal(out.Output)
d = append([]byte("\":"), d...)
d = append([]byte(in.ID), d...)
d = append([]byte("{\""), d...)
d = append(d, "}"...)
return d
} | {
"domain": "codereview.stackexchange",
"id": 42646,
"lm_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, socket, fizzbuzz, ipc",
"url": null
} |
json, go, socket, fizzbuzz, ipc
func echoServer(c net.Conn) {
for {
buf := make([]byte, 512)
nr, err := c.Read(buf)
if err != nil {
return
}
data := buf[0:nr]
println("Server got:", string(data))
data = nice(data)
_, err = c.Write(data)
if err != nil {
log.Fatal("Writing client error: ", err)
}
}
}
func main() {
log.Println("Starting echo server")
ln, err := net.Listen("unix", "/tmp/go.sock")
if err != nil {
log.Fatal("Listen error: ", err)
}
sigc := make(chan os.Signal, 1)
signal.Notify(sigc, os.Interrupt, syscall.SIGTERM)
go func(ln net.Listener, c chan os.Signal) {
sig := <-c
log.Printf("Caught signal %s: shutting down.", sig)
ln.Close()
os.Exit(0)
}(ln, sigc)
for {
fd, err := ln.Accept()
if err != nil {
log.Fatal("Accept error: ", err)
}
go echoServer(fd)
}
}
and the client.go:
package main
import (
"fmt"
"os"
"bufio"
"io"
"log"
"net"
"time"
)
func reader(r io.Reader) {
buf := make([]byte, 1024)
for {
n, err := r.Read(buf[:])
if err != nil {
return
}
println("Client got:", string(buf[0:n]))
}
}
func main() {
if len(os.Args) <= 1 {
fmt.Println("No args given. (expecting a filename)")
return
}
if len(os.Args) > 2 {
fmt.Println("Too many args (only expecting one)")
return
}
var file, err = os.OpenFile(os.Args[1], os.O_RDONLY, 0644)
if (err != nil){
log.Fatal(err) //problem opening filename
return
}
defer file.Close()
scanner := bufio.NewScanner(file)
msg := ""
c, err := net.Dial("unix", "/tmp/go.sock")
if err != nil {
log.Fatal("Dial error", err)
}
defer c.Close()
go reader(c) | {
"domain": "codereview.stackexchange",
"id": 42646,
"lm_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, socket, fizzbuzz, ipc",
"url": null
} |
json, go, socket, fizzbuzz, ipc
go reader(c)
for scanner.Scan(){
msg = scanner.Text()
_, err = c.Write([]byte(msg))
if err != nil {
log.Fatal("Write error:", err)
//break
return
}
println("Client sent:", msg)
time.Sleep(1e9) // this gives time for
}
if err:=scanner.Err(); err != nil{
log.Fatal(err)
}
}
Say, we have this file named input:
{"id":"first entry","from":0,"to":15,"fizz":"Orca","buzz":"Seal"}
{"id":"second entry","from":-3,"to":8,"fizz":"Mango","buzz":"Avocado"}
{"id":"third one","from":1001,"to":1025,"fizz":"Coke","buzz":"Pepsi"}
Running go run server.go and go run client.go input will give these:
Client sent: {"id":"first entry","from":0,"to":15,"fizz":"Orca","buzz":"Seal"}
Client got: {"first entry":["OrcaSeal",1,2,"Orca",4,"Seal","Orca",7,8,"Orca","Seal",11,"Orca",13,14,"OrcaSeal"]}
Client sent: {"id":"second entry","from":-3,"to":8,"fizz":"Mango","buzz":"Avocado"}
Client got: {"second entry":["Mango",-2,-1,"MangoAvocado",1,2,"Mango",4,"Avocado","Mango",7,8]}
Client sent: {"id":"third one","from":1001,"to":1025,"fizz":"Coke","buzz":"Pepsi"}
Client got: {"third one":[1001,"Coke",1003,1004,"CokePepsi",1006,1007,"Coke",1009,"Pepsi","Coke",1012,1013,"Coke","Pepsi",1016,"Coke",1018,1019,"CokePepsi",1021,1022,"Coke",1024,"Pepsi"]}
This program works as expected but I am somehow not satisfied since I am new to both JSON and Go. How can I improve the code?
Answer: The encoding/json package has Encoder and Decoder which you can take advantage of for operating on streams of JSON.
Redefining Output
In server.go you json.Marshal(out.Output), then manually build the JSON to add in.ID. You can add ID to Output to avoid this. Also instead of using []interface{} I would just define a Series []string
type Output struct {
ID string
Series []string
} | {
"domain": "codereview.stackexchange",
"id": 42646,
"lm_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, socket, fizzbuzz, ipc",
"url": null
} |
json, go, socket, fizzbuzz, ipc
Accepting net.Conn
You launch a goroutine after accepting from the listener. However, writing to the terminal isn't safe for concurrent use. Since this isn't a high throughput server, you don't need to handle each conn in parallel.
Also be sure to Close() the accepted connection.
Using Encoder and Decoder in server.go
d := json.NewDecoder(conn)
e := json.NewEncoder(conn)
Using these tools, you don't have to specify an arbitrary 512-byte buffer. Simply d.Decode(...) and e.Encode(...) to read and write JSON from the connection.
Using Encoder and Decider in client.go
Much the same as server.go, these simplify JSON stream handling (both for reading the input file and reading/writing from the connection).
inputd := json.NewDecoder(input)
connd := json.NewDecoder(conn)
conne := json.NewEncoder(conn)
First inputd.Decode(...) to read from the input file, then conne.Encode(...) to send it along the connection, finally connd.Decode(...) to get the server's response.
Minor notes
in client.go lines 20 & 62, should use fmt.Println instead of println
in client.go, time.Sleep() isn't needed since the server will respond immediately
in server.go, listening to os.Interrupt will catch Ctrl+C, so syscall.SIGTERM isn't needed
in server.go, when exiting you can os.Remove the socket, otherwise restarting the server will give an error because the socket already exists
Putting it all together
Updated code (gist)
common.go
package main
import "encoding/json"
type Input struct {
ID string
From int
To int
Fizz string
Buzz string
}
// just used for pretty-printing to terminal
func (in Input) String() string {
b, err := json.Marshal(in)
if err != nil {
panic(err)
}
return string(b)
}
type Output struct {
ID string
Series []string
}
// just used for pretty-printing to terminal
func (out Output) String() string {
b, err := json.Marshal(out)
if err != nil {
panic(err)
}
return string(b)
} | {
"domain": "codereview.stackexchange",
"id": 42646,
"lm_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, socket, fizzbuzz, ipc",
"url": null
} |
json, go, socket, fizzbuzz, ipc
server.go
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net"
"os"
"os/signal"
"strconv"
)
func main() {
if len(os.Args) != 2 {
fmt.Println("usage: ./server socket")
os.Exit(1)
}
ln, err := net.Listen("unix", os.Args[1])
if err != nil {
log.Fatal(err)
}
defer ln.Close()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
<-c
os.Remove(os.Args[1]) // clean up socket
os.Exit(1)
}()
for {
if err = accept(ln); err != nil {
log.Println(err)
}
}
}
func accept(ln net.Listener) error {
conn, err := ln.Accept()
if err != nil {
return err
}
defer conn.Close()
return respond(conn)
}
func respond(conn net.Conn) error {
d := json.NewDecoder(conn)
e := json.NewEncoder(conn)
for {
// Read from client
var in Input
if err := d.Decode(&in); err == io.EOF {
return nil
} else if err != nil {
return err
}
fmt.Println("recieved", in)
// Write to client
out := buildOutput(&in)
if err := e.Encode(&out); err != nil {
return err
}
fmt.Println("sent", out)
}
}
func buildOutput(in *Input) Output {
out := Output{
ID: in.ID,
}
for i := in.From; i <= in.To; i++ {
if i%3 == 0 && i%5 == 0 {
out.Series = append(out.Series, in.Fizz+in.Buzz)
} else if i%3 == 0 {
out.Series = append(out.Series, in.Fizz)
} else if i%5 == 0 {
out.Series = append(out.Series, in.Buzz)
} else {
out.Series = append(out.Series, strconv.Itoa(i))
}
}
return out
}
client.go
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net"
"os"
) | {
"domain": "codereview.stackexchange",
"id": 42646,
"lm_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, socket, fizzbuzz, ipc",
"url": null
} |
json, go, socket, fizzbuzz, ipc
import (
"encoding/json"
"fmt"
"io"
"log"
"net"
"os"
)
func main() {
if len(os.Args) != 3 {
fmt.Println("usage: ./client socket filename")
os.Exit(1)
}
input, err := os.Open(os.Args[2])
if err != nil {
log.Fatal(err)
}
defer input.Close()
inputd := json.NewDecoder(input)
conn, err := net.Dial("unix", os.Args[1])
if err != nil {
log.Fatal(err)
}
defer conn.Close()
connd := json.NewDecoder(conn)
conne := json.NewEncoder(conn)
for {
// Read from input
var in Input
if err = inputd.Decode(&in); err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
// Write to server
if err = conne.Encode(&in); err != nil {
log.Println(err)
continue
}
fmt.Println("sent", in)
// Read from server
var out Output
if err = connd.Decode(&out); err != nil {
log.Println(err)
}
fmt.Println("recieved", out)
}
}
Hope this helps! | {
"domain": "codereview.stackexchange",
"id": 42646,
"lm_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, socket, fizzbuzz, ipc",
"url": null
} |
c#, console
Title: I made a little mastermind game in C# to exercise - do I take the right approach?
Question: I'm very new in C#, and the best way to learn, is to do exercises. As I tried to find a challenging exercise, I created this little game called MasterMind. The rules are very simple, and are explained on numerous places (i.e. here). You can find below my version in C# of this game, but written only for the console application, so there's no fancy nice layout using Forms or WPF. I wanted to concentrate on the code. If anyone's interested, can you tell me if I made the right approach? For example, I created a new class called Ball, with just a color field and a method to choose a random color. I probably over-complicated this, but I wanted to work with Classes. Do you have any remarks on naming conventions, other things, ...
If anyone has suggestions to code better, I'm all ears :-)
You can find the code on my Github (https://github.com/TjerkBeke/MasterMind.git), or here beneath...
Program.cs
internal class Program
{
public static void Main(string[] args)
{
// The number of balls you can pick. The higher the number, the more difficult the game.
int NumberOfBalls = 4;
// The number of chances you get. The lower, the more difficult the game.
int NumberOfChances = 12;
// This string holds the overview of attempts already made
string Outcome = "";
// Take a random order of balls to guess
var BallsToGuess = new List<Ball>();
for (int i = 0; i < NumberOfBalls; i++)
{
BallsToGuess.Add(new());
}
// Show the computer's choice. Uncomment this section to cheat ;-)
//Console.WriteLine("The computer chose the following balls");
//Console.WriteLine(ConvertBallColorToString(BallsToGuess));
// Show the intro and game rules
ShowIntro(); | {
"domain": "codereview.stackexchange",
"id": 42647,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, console",
"url": null
} |
c#, console
// Show the intro and game rules
ShowIntro();
// Loop until you have no more chances left
for (int i = 0; i < NumberOfChances; i++)
{
Console.WriteLine($"Chances left: {NumberOfChances - i}");
// Choose your balls
Console.WriteLine("Provide your choice:");
List<Ball> BallsPicked = GetYourBalls(BallsToGuess.Count);
// Calculate the exact and non-exact matches. An exact match gicves you a black pin, a non-exact match gives you a white pin
int[] ReturnedPins = CalculatePins(BallsToGuess, BallsPicked);
// Show the results to the screen, and show the previous results as well.
Outcome = GetOutcome(ReturnedPins, BallsPicked, Outcome);
Console.Clear();
Console.WriteLine(Outcome);
// Check if you won
if (ReturnedPins[0] == 4)
{
Console.WriteLine("Congratulations!! You have guessed the correct answer!");
Console.WriteLine($"You had { NumberOfChances - i } chances left");
return;
}
}
// If you come to here, it means you didn't win :-(
Console.WriteLine("Sorry, but you didn't find the correct solution within the needed number of chances.");
Console.WriteLine("The computer chose the following balls");
Console.WriteLine(ConvertBallColorToString(BallsToGuess));
} | {
"domain": "codereview.stackexchange",
"id": 42647,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, console",
"url": null
} |
c#, console
}
#region Methods
/// <summary>
/// Shows the different pins, and the chosen ball collection.
/// </summary>
/// <param name="returnedPins"></param>
/// <param name="ballsPicked"></param>
private static string GetOutcome(int[] returnedPins, List<Ball> ballsPicked, string formerAttempt)
{
string ballColors = ConvertBallColorToString(ballsPicked);
string pinColors = ConvertPinColorToString(returnedPins);
return formerAttempt + (pinColors + ballColors) + "\n";
}
/// <summary>
/// Takes an array of 2 integers, and transforms them into a string with the number of characters defined in the integers.
/// # is the number of black pins.
/// | is the number of white pins.
/// </summary>
/// <param name="ReturnedPins"></param>
/// <returns></returns>
private static string ConvertPinColorToString(int[] ReturnedPins)
{
string PinList = "";
string Black = new string('#', ReturnedPins[0]);
string White = new string('|', ReturnedPins[1]);
PinList = (Black + White).PadRight(4);
return ($"'{PinList}'");
} | {
"domain": "codereview.stackexchange",
"id": 42647,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, console",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.