body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I found this interesting challenge in Exercism.
This is my approach to comparing poker hands in Rust. I've strived for code clarity.
I wish I had figured out how to only implement Ord or PartialOrd, in the end I had to implement both for all structs.</p>
<p>It would be nice also if I had a way to avoid using the rank associated function on the enum HandType. My original approach was to establish constant values for each enum variant (StraightFlush = 9) but then I had to spread tons of explicit casts through the code and that looked dirty (hand.hadn_type as u8).</p>
<pre><code>use std::cmp;
/// Given a list of poker hands, return a list of those hands which win.
///
/// Note the type signature: this function should return _the same_ reference to
/// the winning hand(s) as were passed in, not reconstructed strings which happen to be equal.
use std::cmp::Ordering;
use std::collections::HashMap;
#[derive(Debug)]
struct Card {
suit: char,
numeric_value: u8,
}
impl Card {
const ACE: u8 = 14;
const KING: u8 = 13;
const QUEEN: u8 = 12;
const JACK: u8 = 11;
fn new(str_card: &str) -> Result<Self, String> {
let size = str_card.len();
if !(2..=3).contains(&size) {
return Err("Invalid card length".into());
}
let value = match size {
2 => str_card.chars().next().unwrap(),
3 => {
let first_2: &str = &str_card[0..2];
if first_2 == "10" {
'T'
} else {
return Err(format!("Invalid card: {}", str_card));
}
}
_ => panic!("Invalid card length"),
};
let suit = str_card.chars().nth(size - 1).unwrap();
if suit != 'D' && suit != 'C' && suit != 'S' && suit != 'H' {
return Err(format!("Invalid suit: {}", suit));
}
let numeric_value = match value {
'2'..='9' => value.to_digit(10).unwrap() as u8,
'T' => 10,
'J' => Card::JACK,
'Q' => Card::QUEEN,
'K' => Card::KING,
'A' => Card::ACE,
_ => return Err("Invalid value".into()),
};
Ok(Self {
suit,
numeric_value,
})
}
}
#[derive(Eq, PartialEq, Debug)]
struct HighCardData {
cards: Vec<u8>,
}
impl HighCardData {
fn new(cards: Vec<u8>) -> Self {
Self { cards }
}
}
impl PartialOrd for HighCardData {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(&other))
}
}
impl Ord for HighCardData {
fn cmp(&self, other: &Self) -> Ordering {
for i in (0..self.cards.len()).rev() {
let self_value = self.cards[i];
let other_value = other.cards[i];
if self_value != other_value {
return self_value.cmp(&other_value);
}
}
Ordering::Equal
}
}
#[derive(Eq, PartialEq, Debug)]
struct OnePairData {
pair_value: u8,
remaining_cards: Vec<u8>,
}
impl OnePairData {
fn new(pair_value: u8, remaining_cards: Vec<u8>) -> Self {
Self {
pair_value,
remaining_cards,
}
}
}
impl PartialOrd for OnePairData {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(&other))
}
}
impl Ord for OnePairData {
fn cmp(&self, other: &Self) -> Ordering {
let cmp_pair_value = self.pair_value.cmp(&other.pair_value);
if cmp_pair_value != Ordering::Equal {
return cmp_pair_value;
}
HighCardData::new(self.remaining_cards.clone())
.cmp(&HighCardData::new(other.remaining_cards.clone()))
}
}
#[derive(Eq, PartialEq, Debug)]
struct TwoPairsData {
high_pair_value: u8,
low_pair_value: u8,
remaining_card: u8,
}
impl TwoPairsData {
fn new(high_pair_value: u8, low_pair_value: u8, remaining_card: u8) -> Self {
Self {
high_pair_value,
low_pair_value,
remaining_card,
}
}
}
impl PartialOrd for TwoPairsData {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(&other))
}
}
impl Ord for TwoPairsData {
fn cmp(&self, other: &Self) -> Ordering {
let cmp_high_pair_value = self.high_pair_value.cmp(&other.high_pair_value);
if cmp_high_pair_value != Ordering::Equal {
return cmp_high_pair_value;
}
let cmp_low_pair_value = self.low_pair_value.cmp(&other.low_pair_value);
if cmp_low_pair_value != Ordering::Equal {
return cmp_low_pair_value;
}
self.remaining_card.cmp(&other.remaining_card)
}
}
#[derive(Eq, PartialEq, Debug)]
struct ThreeOfAKindData {
three_of_a_kind_value: u8,
remaining_cards: Vec<u8>,
}
impl ThreeOfAKindData {
fn new(three_of_a_kind_value: u8, remaining_cards: Vec<u8>) -> Self {
Self {
three_of_a_kind_value,
remaining_cards,
}
}
}
impl PartialOrd for ThreeOfAKindData {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(&other))
}
}
impl Ord for ThreeOfAKindData {
fn cmp(&self, other: &Self) -> Ordering {
let cmp_value = self.three_of_a_kind_value.cmp(&other.three_of_a_kind_value);
if cmp_value != Ordering::Equal {
return cmp_value;
}
HighCardData::new(self.remaining_cards.clone())
.cmp(&HighCardData::new(other.remaining_cards.clone()))
}
}
#[derive(Eq, PartialEq, Debug)]
struct StraightData {
cards: Vec<u8>,
}
impl StraightData {
fn new(cards: Vec<u8>) -> Self {
Self { cards }
}
}
impl PartialOrd for StraightData {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(&other))
}
}
impl Ord for StraightData {
fn cmp(&self, other: &Self) -> Ordering {
let sv = &self.cards;
let ov = &other.cards;
let self_vec: Vec<u8>;
if sv[0] == 2 && sv[sv.len() - 1] == Card::ACE {
self_vec = vec![1, sv[0], sv[1], sv[2], sv[3]];
} else {
self_vec = sv.clone();
}
let other_vec: Vec<u8>;
if ov[0] == 2 && ov[ov.len() - 1] == Card::ACE {
other_vec = vec![1, ov[0], ov[1], ov[2], ov[3]];
} else {
other_vec = ov.clone();
}
HighCardData::new(self_vec).cmp(&HighCardData::new(other_vec))
}
}
#[derive(Eq, PartialEq, Debug)]
struct FullHouseData {
three_of_a_kind_value: u8,
pair_value: u8,
}
impl FullHouseData {
fn new(three_of_a_kind_value: u8, pair_value: u8) -> Self {
Self {
three_of_a_kind_value,
pair_value,
}
}
}
impl PartialOrd for FullHouseData {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(&other))
}
}
impl Ord for FullHouseData {
fn cmp(&self, other: &Self) -> Ordering {
let cmp_three = self.three_of_a_kind_value.cmp(&other.three_of_a_kind_value);
if cmp_three != Ordering::Equal {
return cmp_three;
}
self.pair_value.cmp(&other.pair_value)
}
}
#[derive(Eq, PartialEq, Debug)]
struct FourOfAKindData {
four_of_a_kind_value: u8,
remaining_card: u8,
}
impl FourOfAKindData {
fn new(four_of_a_kind_value: u8, remaining_card: u8) -> Self {
Self {
four_of_a_kind_value,
remaining_card,
}
}
}
impl PartialOrd for FourOfAKindData {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(&other))
}
}
impl Ord for FourOfAKindData {
fn cmp(&self, other: &Self) -> Ordering {
let cmp = self.four_of_a_kind_value.cmp(&other.four_of_a_kind_value);
if cmp != Ordering::Equal {
return cmp;
}
self.remaining_card.cmp(&other.remaining_card)
}
}
#[derive(Eq, PartialEq, Ord, PartialOrd, Debug)]
enum HandType {
StraightFlush(HighCardData),
FourOfAKind(FourOfAKindData),
FullHouse(FullHouseData),
Flush(HighCardData),
Straight(StraightData),
ThreeOfAKind(ThreeOfAKindData),
TwoPairs(TwoPairsData),
OnePair(OnePairData),
HighCard(HighCardData),
}
impl HandType {
fn rank(&self) -> u8 {
match self {
HandType::StraightFlush(_) => 9,
HandType::FourOfAKind(_) => 8,
HandType::FullHouse(_) => 7,
HandType::Flush(_) => 6,
HandType::Straight(_) => 5,
HandType::ThreeOfAKind(_) => 4,
HandType::TwoPairs(_) => 3,
HandType::OnePair(_) => 2,
HandType::HighCard(_) => 1,
}
}
}
#[derive(Eq, Debug)]
struct PokerHand<'a> {
str_hand: &'a str,
hand_type: HandType,
}
impl<'a> PokerHand<'a> {
fn new_from_values(str_hand: &'a str, hand_type: HandType) -> Self {
Self {
str_hand,
hand_type,
}
}
fn new(str_hand: &'a str) -> Result<Self, String> {
let mut cards: Vec<Card> = Vec::new();
let split = str_hand.split(' ');
for s in split {
let possible_new_card = Card::new(s);
let new_card = match possible_new_card {
Ok(card) => card,
Err(_) => return Err("Cannot create card".into()),
};
cards.push(new_card);
}
cards.sort_by(|a, b| a.numeric_value.cmp(&b.numeric_value));
let first_card = &cards[0];
let mut previous_suit = first_card.suit;
let mut previous_value = 0;
let mut suit_counter = 0;
let mut straight_counter = 1;
let mut kind_count_map: HashMap<u8, usize> = HashMap::new();
let mut starts_at_two = false;
for card in &cards {
if card.suit == previous_suit {
suit_counter += 1;
} else {
suit_counter = 0;
previous_suit = card.suit;
}
if previous_value == 0 {
if card.numeric_value == 2 {
starts_at_two = true;
} else {
previous_value = card.numeric_value;
}
} else if card.numeric_value == (previous_value + 1) {
straight_counter += 1;
}
if card.numeric_value != previous_value {
previous_value = card.numeric_value;
}
*kind_count_map.entry(card.numeric_value).or_insert(0) += 1;
}
let is_flush = suit_counter == 5;
let is_straight = PokerHand::is_straight(
straight_counter,
starts_at_two,
cards[cards.len() - 1].numeric_value,
);
let sorted_numeric_values: Vec<u8> = cards.iter().map(|c| c.numeric_value).collect();
if is_flush {
if is_straight {
return Ok(PokerHand::new_from_values(
str_hand,
HandType::StraightFlush(HighCardData::new(sorted_numeric_values)),
));
} else {
return Ok(PokerHand::new_from_values(
str_hand,
HandType::Flush(HighCardData::new(sorted_numeric_values)),
));
}
}
if is_straight {
return Ok(PokerHand::new_from_values(
str_hand,
HandType::Straight(StraightData::new(sorted_numeric_values)),
));
}
let mut has_three = false;
let mut pair_count = 0;
let mut three_of_a_kind_value: u8 = 0;
let mut pairs: Vec<u8> = Vec::new();
for (key, value) in kind_count_map {
if value == 4 {
let the_other_card: Vec<&u8> = sorted_numeric_values
.iter()
.filter(|v| *v != &key)
.collect();
return Ok(PokerHand::new_from_values(
str_hand,
HandType::FourOfAKind(FourOfAKindData::new(key, *the_other_card[0])),
));
} else if value == 3 {
has_three = true;
three_of_a_kind_value = key;
} else if value == 2 {
pairs.push(key);
pair_count += 1;
}
}
if has_three {
if pair_count == 1 {
return Ok(PokerHand::new_from_values(
str_hand,
HandType::FullHouse(FullHouseData::new(three_of_a_kind_value, pairs[0])),
));
} else {
let remaining_cards: Vec<u8> = sorted_numeric_values
.into_iter()
.filter(|v| *v != three_of_a_kind_value)
.collect();
return Ok(PokerHand::new_from_values(
str_hand,
HandType::ThreeOfAKind(ThreeOfAKindData::new(
three_of_a_kind_value,
remaining_cards,
)),
));
}
}
if pair_count == 2 {
let highest_pair = cmp::max(pairs[0], pairs[1]);
let lowest_pair = cmp::min(pairs[0], pairs[1]);
let the_other_card: Vec<&u8> = sorted_numeric_values
.iter()
.filter(|v| *v != &highest_pair && *v != &lowest_pair)
.collect();
return Ok(PokerHand::new_from_values(
str_hand,
HandType::TwoPairs(TwoPairsData::new(
highest_pair,
lowest_pair,
*the_other_card[0],
)),
));
}
if pair_count == 1 {
let pair_value = pairs[0];
let remaining_cards: Vec<u8> = sorted_numeric_values
.into_iter()
.filter(|v| *v != pair_value)
.collect();
return Ok(PokerHand::new_from_values(
str_hand,
HandType::OnePair(OnePairData::new(pair_value, remaining_cards)),
));
}
Ok(PokerHand::new_from_values(
str_hand,
HandType::HighCard(HighCardData::new(sorted_numeric_values)),
))
}
fn is_straight(
straight_counter: usize,
starts_at_two: bool,
last_card_numeric_value: u8,
) -> bool {
straight_counter == 5
|| PokerHand::is_straight_starting_with_ace(
straight_counter,
starts_at_two,
last_card_numeric_value,
)
}
fn is_straight_starting_with_ace(
straight_counter: usize,
starts_at_two: bool,
last_card_numeric_value: u8,
) -> bool {
straight_counter == 4 && starts_at_two && last_card_numeric_value == Card::ACE
}
}
impl<'a> Ord for PokerHand<'a> {
fn cmp(&self, other: &Self) -> Ordering {
let rank_cmp = self.hand_type.rank().cmp(&other.hand_type.rank());
if rank_cmp != Ordering::Equal {
return rank_cmp;
}
self.hand_type.cmp(&other.hand_type)
}
}
impl<'a> PartialOrd for PokerHand<'a> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<'a> PartialEq for PokerHand<'a> {
fn eq(&self, other: &Self) -> bool {
self.hand_type == other.hand_type
}
}
pub fn winning_hands<'a>(hands: &[&'a str]) -> Option<Vec<&'a str>> {
let size = hands.len();
if size == 0 {
return None;
}
if size == 1 {
return Some(vec![hands[0]]);
}
let mut processed_hands: Vec<PokerHand> = Vec::new();
for hand in hands {
let processed_hand = match PokerHand::new(hand) {
Ok(processed_hand) => processed_hand,
Err(_) => return None,
};
processed_hands.push(processed_hand);
}
processed_hands.sort();
processed_hands.reverse();
let mut result = Vec::new();
let highest_hand = &processed_hands[0];
result.push(highest_hand.str_hand);
for processed_hand in processed_hands.iter().skip(1) {
if processed_hand.cmp(highest_hand) == Ordering::Equal {
result.push(processed_hand.str_hand);
} else {
break;
}
}
Some(result)
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T12:28:46.327",
"Id": "510336",
"Score": "3",
"body": "If you're using `char` for suits, you should definitely use `'♠'`, `'♥'`, `'♣'`, and `'♦'` instead of `'S'`, `'H'`, `'C'`, `'D'` ;-)"
}
] |
[
{
"body": "<h1>General observations</h1>\n<ul>\n<li><code>rustfmt</code>-compliant formatting </li>\n<li>no warnings </li>\n<li><code>#[derive(Debug)]</code> on everything that might be useful to debug-print </li>\n<li>no tests or <code>main</code> (I guess this is built in to Exercism?) Some of the remainder of this review might be a little off base because I wasn't able to test the code.</li>\n</ul>\n<h1>Specific observations</h1>\n<h2>Use newtypes and/or enums for restricted values</h2>\n<pre><code>struct Card {\n suit: char,\n numeric_value: u8,\n}\n</code></pre>\n<p><code>char</code> and <code>u8</code> don't really tell you much about those values. What about some enums? <code>enum Suit { Heart, Spade, Diamond, Club }</code> would work great for <code>suit</code>, and for <code>value</code> you could use a C-style <code>enum Rank { Two = 2, Three, ... King, Ace }</code> (C-style enums can be cast to integers with <code>as</code> for the straight check). It might feel a little weird writing out names for the numbers from 2 to 10, but it's not as if they're going to change any time soon, and you only have to do it twice (once in the definition and once for parsing, on which more later).</p>\n<pre><code>impl Card {\n const ACE: u8 = 14;\n const KING: u8 = 13;\n const QUEEN: u8 = 12;\n const JACK: u8 = 11;\n</code></pre>\n<p>Making <code>Rank</code> an enum would eliminate these <code>const</code>s as well.</p>\n<h2>Parsing and initialization</h2>\n<pre><code> fn new(str_card: &str) -> Result<Self, String> {\n</code></pre>\n<p>Consider implementing <code>FromStr</code> instead of having a <code>new</code> function that parses a string. I would usually reserve the name <code>new</code> for a trivial constructor, or one that only does validation, not parsing.</p>\n<h2>Parsing</h2>\n<pre><code> let size = str_card.len();\n if !(2..=3).contains(&size) {\n return Err("Invalid card length".into());\n }\n</code></pre>\n<p>This part is a little weird because <code>len()</code> returns <em>byte</em> counts but you go on to parse <em>characters</em>, which is the same thing here but only because all the characters are in the ASCII subset. It's not exactly wrong, but it's fragile; if you wanted to support input like <code>"A♠"</code>, it would need a full rewrite. Consider using string methods to match against substrings instead of picking it apart character by character.</p>\n<h3>Note on error types</h3>\n<p><code>String</code> is fine as an error type for a self-contained program. For a library you'd want to have a custom error type and return values like <code>MyError::InvalidLength(n)</code>.</p>\n<pre><code> let value = match size {\n 2 => str_card.chars().next().unwrap(), // this is the second time you check the size of the string\n 3 => {\n let first_2: &str = &str_card[0..2]; // multi-byte inputs will panic here\n if first_2 == "10" {\n 'T'\n } else {\n return Err(format!("Invalid card: {}", str_card));\n }\n }\n _ => panic!("Invalid card length"), // this is the third time you check the size of the string\n };\n\n let suit = str_card.chars().nth(size - 1).unwrap(); // this is the FOURTH time you check the size of the string\n</code></pre>\n<p>Here's one example of doing something that kind of solves a problem, but doesn't really solve the <em>whole</em> problem. Because you check the length of the string, but don't validate the contents at this point, you will have to validate the contents in a second pass, during which you will have to essentially validate the length again. Forget validating the size in advance: chunk it up as best you can and parse the chunks individually.</p>\n<h3>Enums again</h3>\n<pre><code> if suit != 'D' && suit != 'C' && suit != 'S' && suit != 'H' {\n return Err(format!("Invalid suit: {}", suit));\n }\n</code></pre>\n<p>Okay, it's validated, but <code>suit</code> is still just a <code>char</code>, so there's no type-level record of this validation being performed. A suit is one of four things; a character could be anything. I think you get the point, let me hit it one more time:</p>\n<pre><code> let numeric_value = match value {\n '2'..='9' => value.to_digit(10).unwrap() as u8,\n 'T' => 10,\n 'J' => Card::JACK,\n 'Q' => Card::QUEEN,\n 'K' => Card::KING,\n 'A' => Card::ACE,\n _ => return Err("Invalid value".into()),\n };\n</code></pre>\n<p>Same here: you could use a <code>struct Rank(u8);</code> or an <code>enum Rank {...}</code>. If the parsing here is complex you could also implement <code>FromStr</code> for <code>Rank</code> and <code>Suit</code>, and defer to that, instead of implementing it in-line.</p>\n<p>Let's skip ahead a bit...</p>\n<h2><code>HandType</code> and ordering</h2>\n<pre><code>#[derive(Eq, PartialEq, Ord, PartialOrd, Debug)]\nenum HandType {\n StraightFlush(HighCardData),\n FourOfAKind(FourOfAKindData),\n FullHouse(FullHouseData),\n Flush(HighCardData),\n Straight(StraightData),\n ThreeOfAKind(ThreeOfAKindData),\n TwoPairs(TwoPairsData),\n OnePair(OnePairData),\n HighCard(HighCardData),\n}\n</code></pre>\n<p>This enum is unnecessarily complicated. In the first case, it's smart to take advantage of the built-in behavior of <code>#[derive(PartialOrd)]</code>, but you've made things unnecessarily hard on yourself by putting these in descending order of rank, so you can't rely on <code>PartialOrd</code> to give the ordering you want: you have to call <code>rank</code>, compare that first, <em>then</em> compare the rest of the contents. If you just list them in increasing order, you can make <code>derive(PartialOrd)</code> do the right thing without any additional work.</p>\n<p>Secondly, <code>StraightFlush</code> should hold <code>StraightData</code> instead of <code>HighCardData</code>; as written, you're treating an 5-high straight flush as higher than a king-high straight flush. You wrote the logic for this but you only used it for "normal" straights (I'm probably butchering the vocabulary here, sorry, I don't play poker).</p>\n<p>Furthermore, <code>HighCardData</code>'s <code>Ord</code> implementation is used, directly or indirectly, in six of the nine variants, which is a strong hint that there's unexploited symmetry in this data structure. Let's look at that...</p>\n<h3><code>HighCardData</code></h3>\n<pre><code>impl Ord for HighCardData {\n fn cmp(&self, other: &Self) -> Ordering {\n for i in (0..self.cards.len()).rev() {\n let self_value = self.cards[i];\n let other_value = other.cards[i];\n\n if self_value != other_value {\n return self_value.cmp(&other_value);\n }\n }\n Ordering::Equal\n }\n}\n</code></pre>\n<p>Hmm... so the only difference between this and the default <code>Ord</code> behavior for <code>Vec</code> is that it's in reverse order? Why not reverse the cards in the <code>new</code> function, and simply <code>#[derive]</code> it?</p>\n<h3><code>OnePairData</code>, etc.</h3>\n<pre><code>impl Ord for OnePairData {\n fn cmp(&self, other: &Self) -> Ordering {\n \n let cmp_pair_value = self.pair_value.cmp(&other.pair_value);\n // (note `Ordering` has `then` and `then_with` methods that you might use here)\n if cmp_pair_value != Ordering::Equal {\n return cmp_pair_value;\n }\n HighCardData::new(self.remaining_cards.clone())\n .cmp(&HighCardData::new(other.remaining_cards.clone()))\n }\n}\n</code></pre>\n<p>This would also work as <code>#[derive]</code>d if the <code>remaining_cards</code> were kept sorted in descending order of value. In fact, this is a common theme among most of the <code>Ord</code> implementations so I won't go through the rest of them one by one. <code>StraightData</code> is a bit special, though:</p>\n<h3><code>StraightData</code></h3>\n<pre><code>impl Ord for StraightData {\n fn cmp(&self, other: &Self) -> Ordering {\n let sv = &self.cards;\n let ov = &other.cards;\n let self_vec: Vec<u8>;\n if sv[0] == 2 && sv[sv.len() - 1] == Card::ACE {\n self_vec = vec![1, sv[0], sv[1], sv[2], sv[3]];\n } else {\n self_vec = sv.clone();\n }\n let other_vec: Vec<u8>;\n if ov[0] == 2 && ov[ov.len() - 1] == Card::ACE {\n other_vec = vec![1, ov[0], ov[1], ov[2], ov[3]];\n } else {\n other_vec = ov.clone();\n }\n\n HighCardData::new(self_vec).cmp(&HighCardData::new(other_vec))\n }\n}\n</code></pre>\n<p>This one might need a little more thought: if you sort the cards in descending order by rank, treating the ace as a 1, then the <code>#[derive]</code>d (<code>Partial</code>)<code>Ord</code> behavior (when the ace is treated as a 14) will be correct.</p>\n<pre><code>[K Q J 10 A] <- Ace-high straight sorted in descending order (with ace as 1)\n[K Q J 10 9] <- King-high straight sorted in descending order\n</code></pre>\n<h3>Using card ordering to your advantage</h3>\n<p>There's a common theme here: if you sort the cards in the "correct" order when creating <code>HandType</code>, you don't actually need any custom comparison code; it can all be <code>#[derive]</code>d. This suggests to me an alternate implementation:</p>\n<blockquote>\n<pre><code>#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]\nstruct Hand {\n kind: HandType,\n cards: Vec<u8>, // or Vec<Rank>, or just Vec<Card>\n}\n// If, when creating `Hand`, we detect `kind` and use it to determine how to order \n// `cards`, then we don't need to write any custom (Partial)Ord code.\n// Note none of these variants have data -- the cards are in `cards`.\n#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]\nenum HandType {\n HighCard,\n OnePair,\n TwoPairs,\n ThreeOfAKind,\n Straight,\n Flush,\n FullHouse,\n FourOfAKind,\n StraightFlush,\n}\n</code></pre>\n</blockquote>\n<h2><code>PokerHand</code></h2>\n<pre><code>struct PokerHand<'a> {\n str_hand: &'a str,\n hand_type: HandType,\n}\n</code></pre>\n<p>Minor quibble: assuming I'm willingly using a library that has to do with card games, I'm probably going to know that <code>Hand</code> is a hand of cards and not a primate appendage. Prefixing it with <code>Poker</code> doesn't, in my opinion, improve readability. Rust, unlike C, has a namespace system with fine-grained visibility controls, so we don't need to worry about it ever conflicting with some other library type also named <code>Hand</code>.</p>\n<p>One thing I would not do here is keep the <code>str_hand</code> as part of this struct. The string is useless once the <code>hand_type</code> has been parsed out of it: you are keeping it around for the sake of <code>winning_hands</code>, but that really shouldn't be any concern of <code>PokerHand</code>. It doesn't come into play during analysis. Just keep track of the parsed data, and let <code>winning_hands</code> remember where it came from (more on this later).</p>\n<h2>Parsing and validating a <code>PokerHand</code></h2>\n<pre><code>impl<'a> PokerHand<'a> {\n fn new(str_hand: &'a str) -> Result<Self, String> {\n</code></pre>\n<p>This is another dense <code>new</code> function that blends the responsibilities of parsing and initialization. I'd make <code>new</code> take a <code>Vec<Card></code> and do just the hand analysis, and again write a <code>FromStr</code> implementation that parses into a <code>Vec<Card></code> and then calls <code>new</code>.</p>\n<pre><code> let split = str_hand.split(' ');\n</code></pre>\n<p>Consider using <code>split_whitespace</code> instead.</p>\n<pre><code> cards.sort_by(|a, b| a.numeric_value.cmp(&b.numeric_value));\n</code></pre>\n<p>You have a lot of lines that look something like this. You should usually use <code>sort_unstable_by</code> when the original ordering of equal values is unimportant. It won't likely give a big speed boost (although it might for some datasets), but it is a form of documentation about your assumptions. Also note that you can use <code>u8::cmp(&a.numeric_value, &b.numeric_value)</code> (or <code>Ord::cmp</code>), which I like better because it looks more symmetric, but there's nothing wrong with the way you've written it either.</p>\n<h3>State machines</h3>\n<pre><code> let mut previous_suit = first_card.suit;\n let mut previous_value = 0;\n let mut suit_counter = 0;\n let mut straight_counter = 1;\n\n let mut kind_count_map: HashMap<u8, usize> = HashMap::new();\n\n let mut starts_at_two = false;\n</code></pre>\n<p>This is a state machine with six state registers. I personally find that, while it's possible to keep track of five "things" at a time mentally for short periods, the realistic limit should usually be four. Six things is just too many, unless they have some structure to them that allows you to treat them as groups of things (<code>(x, y, z)</code> triplets, or something like that). I apply this general principle not just to state machines, but to function arguments, type parameters, and shopping lists. I would do one of two things here:</p>\n<ol>\n<li>(recommended) Break a complex state machine into smaller ones. Basically, do several passes over the cards instead of trying to do it all in a single loop. Since you're looping over a slice that is already in memory, resetting the loop is essentially free. Since there are commonalities between the checks you need to do, you might exploit some of those symmetries to skip parts of later loops. But you don't need to do it all in one shot.</li>\n<li>Combine several state registers into a struct, simplifying the outer loop by pushing the complexity down into the struct's methods. Call it something like <code>CardSummary</code> and give it methods like <code>straight(&self) -> Option<Vec<Card>></code> and <code>full_house(&self) -> Option<[Card; 3], [Card; 2]></code> to call when you're done. This has the advantage of not requiring iterating over the cards more than once; however, it's probably not necessary in this case.</li>\n</ol>\n<pre><code> if card.numeric_value != previous_value {\n previous_value = card.numeric_value;\n }\n</code></pre>\n<p>This branch is extraneous. Just <code>previous_value = card.numeric_value;</code> should be fine. Making this change reveals that the <code>else</code> a few lines up is also redundant and can be eliminated as well.</p>\n<pre><code> let mut has_three = false;\n let mut pair_count = 0;\n\n let mut three_of_a_kind_value: u8 = 0;\n\n let mut pairs: Vec<u8> = Vec::new();\n</code></pre>\n<p>One non-trivial state machine per function, please.</p>\n<p>This one can be easily reduced to two state registers, because <code>has_three</code> is just the discriminant of the <code>Option</code> that should contain <code>three_of_a_kind_value</code>, and <code>pair_count</code> is just <code>pairs.len()</code>.</p>\n<p>All the logic embedded in <code>if has_three</code>, <code>if pair_count == 2</code>, etc. should be wrapped in smaller functions with descriptive names.</p>\n<h2><code>winning_hands</code></h2>\n<pre><code>pub fn winning_hands<'a>(hands: &[&'a str]) -> Option<Vec<&'a str>> {\n</code></pre>\n<p>I assume Exercism gives you this signature to fill in, so you don't have the ability to control it. However, it's not very good for several reasons. <code>Option<Vec></code> is weird because <code>Vec</code> can be empty, and in this case an empty output is the perfectly logical response to an empty input, so it should really just be <code>Vec</code>. Except that you're also using <code>None</code> to indicate an error condition, for which you should be using <code>Result</code> instead of <code>Option</code>. Moreover, the interesting part of this is taking a bunch of hands and deciding which one(s) win: not the parsing of hands from strings. So I would first write a function with the signature I <em>want</em> to write, and then write <code>winning_hands</code> to use it internally.</p>\n<p>Here's the function signature I'd implement: <code>fn(&[PokerHand]) -> Vec<usize></code> (the <code>usize</code>s are the indices of the winning hands in the input slice). Because it returns <code>usize</code>s, you can easily implement <code>winning_hands</code> without having to store the input strings in the <code>PokerHand</code>s. Bonus challenge: figure out how to accept any iterable of <code>&PokerHand</code>s.</p>\n<pre><code> processed_hands.sort();\n processed_hands.reverse();\n</code></pre>\n<p><code>processed_hands.sort_by(|a, b| Ord::cmp(b, a))</code> (note the reversal of <code>b</code> and <code>a</code>) or <code>processed_hands.sort_by(|a, b| a.cmp(b).reverse())</code>.</p>\n<pre><code> let highest_hand = &processed_hands[0];\n // ...\n for processed_hand in processed_hands.iter().skip(1) {\n</code></pre>\n<p>Consider using <code>processed_hands.split_first()</code> in situations like this. Not sure if it buys you much in this particular case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T16:42:34.947",
"Id": "510420",
"Score": "0",
"body": "Thank you times a thousand. This was very generous and professional. I have this up on my github and I'll carefully consider your great recommendations and apply them over there."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T14:30:23.280",
"Id": "258875",
"ParentId": "258836",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T12:18:04.340",
"Id": "258836",
"Score": "4",
"Tags": [
"programming-challenge",
"rust"
],
"Title": "Comparing Poker hands in Rust"
}
|
258836
|
<p>So I'm very new if JavaScript and my question is this a right way to implement this functionality? How could I improve this code.</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<title>TEST</title>
<script>
document.addEventListener('DOMContentLoaded', function() {
let correct = document.querySelector('.correct');
correct.addEventListener('click', function() {
correct.style.backgroundColor = 'green';
document.querySelector('#A1').innerHTML = 'Правильно';
});
let incorrects = document.querySelectorAll('.incorrect');
for (let i = 0; i < incorrects.length; i++) {
incorrects[i].addEventListener('click', function() {
incorrects[i].style.backgroundColor = 'red';
document.querySelector('#A1').innerHTML = 'Неправильно';
});
}
document.querySelector('.check').addEventListener('click', function() {
let input = document.querySelector('input');
if (input.value === '17') {
input.style.backgroundColor = 'green';
document.querySelector('#A2').innerHTML = 'Правильно';
} else {
input.style.backgroundColor = 'red';
document.querySelector('#A2').innerHTML = 'Неправильно';
}
});
});
</script>
</head>
<body>
<h1>TEST</h1>
<section>
<article>
<hr>
<h3>How many times can you subtract 6 from 30?</h3>
<button class="incorrect">ДВА РАЗA</button>
<button class="incorrect">ЧЕТЫРЕ РАЗA</button>
<button class="incorrect">ТРИ РАЗA</button>
<button class="incorrect">ШЕСТЬ РАЗ</button>
<button class="correct">ПЯТЬ РАЗ</button>
<p id="A1">Сколько раз вы можете вычесть 6 из 30?</p>
</article>
<article>
<hr>
<h3>What number should be subtracted from each of 50, 61, 92, 117 so that the numbers, so obtained in this order, are in proportion ?</h3>
<input type="text"></input>
<button class="check">Check</button>
<p id="A2">Какое число нужно вычесть из 50, 61, 92, 117, чтобы числа, полученные в таком порядке, были пропорциональны?</p>
</article>
</section>
</body>
</html>
</code></pre>
|
[] |
[
{
"body": "<p>Congrats on getting something like this working! I obviously don't know anything about the background of the project, so keep in mind that while my feedback may be valuable, if it's just a small side project you might not want to overengineer it.</p>\n<p>Regardless, here are some points for you to regard:</p>\n<ul>\n<li><p><strong>External scripts</strong>: While embedding scripts into the document directly is a slight performance gain, using an external script gives you the luxury of</p>\n</li>\n<li><p><strong>Mixed languages</strong>: While mostly an oddity while reading, it's generally a bad user experience to have two languages mixed together. For concistency in terms of UX, I'd advise that you stick to either one.</p>\n</li>\n<li><p><strong>Reducing duplicated code</strong>: When writing code, it's always nice that <em>if</em> you have to change something, you only have to change it in one place, instead of multiple. This makes your code less error prone to spontaneous changes made by you. Considering this, we could refactor the following:</p>\n</li>\n</ul>\n<pre><code>let input = document.querySelector('input');\nif (input.value === '17') {\n input.style.backgroundColor = 'green';\n document.querySelector('#A2').innerHTML = 'Правильно';\n} else {\n input.style.backgroundColor = 'red';\n document.querySelector('#A2').innerHTML = 'Неправильно';\n}\n</code></pre>\n<p>... into ...</p>\n<pre><code>const input = document.querySelector('input');\nconst answer = document.querySelector('#A2');\n\nif (input.value === '17') {\n input.style.backgroundColor = 'green';\n answer.innerHTML = 'Правильно';\n} else {\n input.style.backgroundColor = 'red';\n answer.innerHTML = 'Неправильно';\n}\n</code></pre>\n<ul>\n<li><strong>HTML cleanup</strong>: If you need to query the document to fetch elements, it's always good to be as explicit as possible. On one line you are querying for <code>input</code>, but what if the page contains multiple input elements later? You should try to get a consistent and explicit HTML structure going for the questions/answers (which also ties in with the point made later on below). An example could be this:</li>\n</ul>\n<pre><code><article id="q1" class="question">\n <hr>\n <h3>...</h3>\n <input type="text"></input>\n <button class="check">Check</button>\n <p class="answer">...</p>\n</article>\n</code></pre>\n<p>Each of the elements in this node can be uniquely identified simply by the fact that they are a child of the unique(!) question element with the ID "q1". Queries that looked for <code>input</code> before would now look for <code>#q1 > input</code> instead.</p>\n<p>You could also try to remove redundant classes, unless they are used for styling. In the first question, there is one button with the "correct" class, with all others being "incorrect". But the fact that every button that is not explicitely "correct" should be incorrect should be natural, hence you could consider removing these excessive classes.</p>\n<hr />\n<p>The points mentioned above will probably increase the overall readability and maintainability of the project, but the biggest concern currently is the <em>extendibility</em>.</p>\n<p>Look at it this way: Currently, every time you want to add a new question to the quiz, you need to modify your source code, mostly adding duplicated statements to check correct/incorrect answers. If you give your questions a more concrete structure, you could write <em>reusable</em> code, that is valid for any question that you add!</p>\n<p>The exact implementation for this is up to you, but it could help to generate an object from an HTML node, grabbing the question title, description, answering possibilities (and the correct one obviously!) and setting up the question/answer handling.</p>\n<p>Always remember: It's almost always better to have something that is extendible and/or scalable without having to modify the source code, just by modifying the markup or configuration.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T10:03:13.347",
"Id": "258865",
"ParentId": "258844",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T15:43:05.630",
"Id": "258844",
"Score": "2",
"Tags": [
"javascript",
"html"
],
"Title": "Asking and checking if the answer is correct"
}
|
258844
|
<p>I need help to format all the input values to the format ‘##-##/##'.
My input might include whole number, fraction or mixed fraction...Sample input 3, 1/1, 1 1/2. I have tried the below code it is giving expected result. Can someone please help for a standard and concise way of doing this</p>
<pre><code>using System.IO;
using System;
using System.Linq;
class Program
{
static void Main()
{
var input1 = "3"; /*Expected result 03-00/00 */
var input2 = "1/1"; /*Expected result 00-01/01*/
var input3 = "1 3/4"; /*Expected result 01-03/04*/
string[] splittedValue1= input1.Split( '/', ' ' );
string[] splittedValue2= input2.Split( '/', ' ' );
string[] splittedValue3= input3.Split( '/', ' ' );
/*Expected result 03-00/00 */
if(splittedValue1.Count()==1)
{
String test =splittedValue1[0].PadLeft(2, '0') +"-00/00" ;
Console.WriteLine(test);
}
/*Expected result 00-01/01*/
if(splittedValue2.Count()==2)
{
String format="00-00";
String test =Convert.ToInt32(splittedValue2[0]).ToString(format) + "/" + splittedValue2[1].PadLeft(2, '0');
Console.WriteLine(test);
}
/*Expected result 01-03/04*/
if(splittedValue3.Count()==3)
{
String test =splittedValue3[0].PadLeft(2, '0') +"-" +splittedValue3[1].PadLeft(2, '0') + "/" + splittedValue3[2].PadLeft(2, '0');
Console.WriteLine(test);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Does this help?</p>\n<p><a href=\"https://github.com/qqtf/StringFormat\" rel=\"nofollow noreferrer\">StringFormat on GitHub</a></p>\n<p>The actual string-logic worked, so I didn't touch it.\nEvery time you want to subject a new string to your logic, you had to adjust your code. This is against open-closed-principle. When using a List and a simple foreach loop that is no longer the case. It's a simple improvement without adding any complexity, hence the suggestion.</p>\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace StringFormat\n{\n class Program\n {\n static void Main(string[] args)\n {\n List<string> inputs = new List<string> { "3", "1/1", "1 3/4" };\n\n inputs.Add("2/2");\n inputs.Add("5");\n inputs.Add("2 4/5");\n\n foreach (string input in inputs)\n {\n string[] splittedValue = input.Split('/', ' ');\n\n /*Expected result 03-00/00 */\n if (splittedValue.Count() == 1)\n {\n String test = splittedValue[0].PadLeft(2, '0') + "-00/00";\n Console.WriteLine(test);\n }\n\n /*Expected result 00-01/01*/\n if (splittedValue.Count() == 2)\n {\n String format = "00-00";\n String test = Convert.ToInt32(splittedValue[0]).ToString(format) + "/" + splittedValue[1].PadLeft(2, '0');\n Console.WriteLine(test);\n }\n\n\n /*Expected result 01-03/04*/\n if (splittedValue.Count() == 3)\n {\n String test = splittedValue[0].PadLeft(2, '0') + "-" + splittedValue[1].PadLeft(2, '0') + "/" + splittedValue[2].PadLeft(2, '0');\n Console.WriteLine(test);\n }\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T20:00:18.703",
"Id": "510373",
"Score": "0",
"body": "Why are you doing `.Count()` fro array instead of `.Length`? Repeative code is a bad practice. This is not a review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T21:24:03.367",
"Id": "510380",
"Score": "0",
"body": "His splittedValue-logic worked and I did not need to change it to produce an answer to his question, to get it into a more standard / concise. His issue was to generate a loop, so he did not need to write another string[] splittedValueX= inputX.Split( '/', ' ' ); every time he wanted to format another string. The issue for DRY is especially relevant for large chunks of code, and modular programming. Not for someone who is starting to program and delivers 20-30 lines. Don't impose your coding practices. I try to make a suggestion that helps the issue, remains close to his own code without"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T21:31:55.140",
"Id": "510383",
"Score": "3",
"body": "This is a Code Review of the `string` formatting code. Look at the **String format C#** title. The answer contains neither changes to `string` fromatting code nor suggestions or warnings. You simply added a loop outside of the code for review. This is not a review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T21:32:54.943",
"Id": "510384",
"Score": "4",
"body": "Welcome to Code Review! this answer is a code only answer, and doesn't explain why the code you presented is better than that of the OP. Please feel free to edit your answer with the explanation of how your code is better than the code that the OP presented"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T21:40:27.300",
"Id": "510387",
"Score": "0",
"body": "adding unnecessary complexity like JimmyHu. His approach is totally different, which is fine. I'm not going to downvote him because he's using static methods, which is a bad practice, but understandable for the console application Devi is making. (Hence totally not relevant for the issue.) If the .Count() was something I added, your remark would be valid. But it wasn't. I flagged your comment."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T18:33:41.023",
"Id": "258848",
"ParentId": "258846",
"Score": "0"
}
},
{
"body": "<p>The main statements are:</p>\n<ul>\n<li>DRY = Don't Repeat Yourself. Avoid repetitive code if possible.</li>\n<li>The code would work only exactly for this set of test cases. As each test case is handled by separate branch. What if values will be different or entered by user from Console?</li>\n<li>Use method to encapsulate the code to be able to call it multiple times.</li>\n<li>As the fraction has a regular format, the <a href=\"https://en.wikipedia.org/wiki/Regular_expression\" rel=\"nofollow noreferrer\">Regular Expression</a> can be useful here. To test ReGex'es I use <a href=\"https://regex101.com/\" rel=\"nofollow noreferrer\">https://regex101.com/</a> site, it explains how each part of the expression works. Also there's a <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/base-types/regular-expressions\" rel=\"nofollow noreferrer\">documentation</a> for .NET.</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>static void Main(string[] args)\n{\n string[] inputs = new[] { "3", "1/1", "1 3/4" };\n foreach (string input in inputs)\n Console.WriteLine(FormatFraction(input));\n Console.ReadKey(true);\n}\n \nprivate static string FormatFraction(string input)\n{\n string[] tokens = Regex.Match(input, @"^((-?\\d+) ?)?((\\d+)\\/(\\d+))?$")\n .Groups\n .Cast<Group>()\n .Select(s => s.Value.PadLeft(2, '0'))\n .ToArray();\n return string.Format("{2}-{4}/{5}", tokens);\n}\n</code></pre>\n<p>The ReGex match groups are declared with braces <code>()</code>. For this pattern groups indexes are <code>0(1(2))(3(4)(5))</code> = 6 match groups, each Group contains a match inside it. The requred groups that contain the desired numbers <code>\\d+</code> (means the sequense of one and more digits) are 2, 4 and 5.</p>\n<p>Output</p>\n<pre class=\"lang-none prettyprint-override\"><code>03-00/00\n00-01/01\n01-03/04\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T21:42:14.853",
"Id": "510388",
"Score": "1",
"body": "Your answer is headed in the right direction but would you please explain what you are doing a little bit more, I have a feeling that the OP is newer to C# and might not know some of the operations that you are using to make your code cleaner and more precise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T11:47:18.853",
"Id": "510408",
"Score": "0",
"body": "Hi, Thanks for the review. I am trying to analyze the regex which you have used but i am facing issue during compilation. I have included the namepsace also \"System.Text.RegularExpressions\"...My .net framework is 4.5.The error i am getting is \"`System.Text.RegularExpressions.GroupCollection' does not contain a definition for `Values' and no extension method `Values' of type `System.Text.RegularExpressions.GroupCollection' could be found. Are you missing an assembly reference?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T12:00:40.150",
"Id": "510410",
"Score": "1",
"body": "@Devi fixed for old frameworks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T12:09:32.487",
"Id": "510411",
"Score": "1",
"body": "Thank you very much!. Got it"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T20:38:25.260",
"Id": "258855",
"ParentId": "258846",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "258855",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T17:45:55.343",
"Id": "258846",
"Score": "2",
"Tags": [
"c#"
],
"Title": "String format C#"
}
|
258846
|
<p>I need to create a component for displaying a list of avatar users....If the users present in the array is more then 3 I have to display a number to indicate the remaining amount of users.</p>
<p>Example:</p>
<pre><code>[{id:1, name: 'Paul', surname: 'Rudd'}, {id:2, name: 'Rose', surname: 'Pink'}, {id:3, name: 'Richard', surname: 'Gere'}, {id:4, name: 'Anna', surname: 'Ross'}, {id:5, name: 'Raphael', surname: 'Bublè'},{id:6, name: 'Gene', surname: 'Hoffman'},{id:7, name: 'Anthony', surname: 'Florence'}]
</code></pre>
<p>I have to see 3 avatar images with the first letter of name and surname:</p>
<p>PR, RP, RG 4+</p>
<p>This is my component:</p>
<pre><code> @Component({
selector: 'mgg-users-detail',
templateUrl: './users-detail.component.html',
styleUrls: ['./users-detail.component.scss'],
})
export interface users {
id: number;
name: string;
surname: string;
}
export class UsersDetailComponent implements OnInit {
@Input()
collaborators: users[]
constructor() {}
ngOnInit(): void {}
}
</code></pre>
<p>and this is the html:</p>
<pre><code> <div *ngIf="users && users.length > 1">
<div *ngFor="let user of users; index as i">
<img
*ngIf="i <= 2"
[src]="'https://dummyimage.com/50x50/6ECFDB/fff&text=' + collaborator.name[0] + collaborator.surname[0]"
></img>
</div>
<img
*ngIf="users.length > 3"
[src]="'https://dummyimage.com/50x50/6ECFDB/fff&text=' + (users.length - 3)"
>
</img>
</div>
</code></pre>
<p>Can I improve the code in other way?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T05:40:30.950",
"Id": "510398",
"Score": "0",
"body": "I see little code, nothing but modelling."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T06:07:19.943",
"Id": "510399",
"Score": "0",
"body": "Welcome to CodeReview! Could you please elaborate on *better way* and *in other way*? From what aspect are you looking for improvement?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T10:37:18.543",
"Id": "510406",
"Score": "0",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T19:23:37.490",
"Id": "258854",
"Score": "0",
"Tags": [
"javascript",
"typescript",
"angular-2+"
],
"Title": "Is there a better way for this ui component?"
}
|
258854
|
<p>I'm a Haskell beginner and trying to hone my skill by solving algorithmic problems. Here's what I got for <code>maxheapify</code> from <code>Introduction to Algorithms</code></p>
<pre><code>ixParent :: Int -> Int
ixParent = floor . flip (/) 2 . fromIntegral
ixLeft :: Int -> Int
ixLeft = (*) 2
ixRight :: Int -> Int
ixRight = (+) 1 . (*) 2
maxHeapify :: (Show a, Num a, Ord a) => Int -> [a] -> [a]
maxHeapify i h = if m == i then h else maxHeapify m h' where
s = length h
l = ixLeft i
r = ixRight i
m = snd $ maximumBy (\e1 e2-> compare (fst e1) (fst e2)) [(h!!(n-1), n)|n <- [i,l,r], n <= s]
h' = h & ix (i-1) .~ (h!!(m-1)) & ix (m-1) .~ (h!!(i-1))
</code></pre>
<p>Any suggestions on the improvements or correction are highly appreciated. I'm looking for more idiomatic way of doing Haskell</p>
<p><strong>Version 0.1:</strong></p>
<pre><code>import Control.Lens
import Data.List
ixP :: Int -> Int
ixP = floor . flip (/) 2 . fromIntegral
idxL :: Int -> Int
idxL = (*) 2
idxR :: Int -> Int
idxR = (+) 1 . (*) 2
maxHeapify ::(Ord a, Show a) => Int -> [a] -> [a]
maxHeapify _ [] = []
maxHeapify i h = if l == i then h else maxHeapify l h'
where
l = snd . maximumBy (\(i1,_) (i2,_) -> compare i1 i2)
$ [(h!!(n-1), n) | n<- [i, idxL i, idxR i], n <= length h]
h' = h
& ix (i-1) .~ h!!(l-1)
& ix (l-1) .~ h!!(i-1)
buildMaxHeap :: (Ord a, Show a) => [a] -> [a]
buildMaxHeap xs = go (ixP (length xs)) xs
where
go 0 xs = xs
go i xs = go (i - 1) (maxHeapify i xs)
heapSort :: (Ord a, Show a) => [a] -> [a]
heapSort [] = []
heapSort h = heapSort (maxHeapify 1 xs) ++ [x]
where
mx = buildMaxHeap h
x = head mx
xs = tail mx
</code></pre>
<p><strong>Update 1:</strong></p>
<p>Added <code>heapIncreaseKey</code></p>
<pre><code>heapIncreaseKey :: (Ord a, Show a) => Int -> a -> [a] -> [a]
heapIncreaseKey i k h =
if k < h!!(i-1)
then fail "New Key is smaller than current one"
else go i k h
where
go i k h = if i > 1 && h!!(p - 1) < k
then go p k (h & ix (i-1) .~ h!!(p -1))
else h & ix (i-1) .~ k
where
p = ixP i
</code></pre>
<p>Here my question is related to variable naming. I am using the same names for variables in the <code>go</code> function and the outer function. Is there a better way?</p>
|
[] |
[
{
"body": "<p>It's unusual to partially apply infix functions by first prefixing them, <code>(*) 2</code> is equivalent to <code>(2 *)</code> and the latter is so much more common I can't recall ever even seeing the former. Note that you can also partially apply the second argument, as in <code>(/ 2)</code>.</p>\n<p>When you're using <code>-By</code> functions, a handy tool to have in your toolbox is the higher order function <code>Data.Function.on :: (b -> b -> c) -> (a -> b) -> a -> a -> c</code>. It allows you to project a digest function to work on any type you can derive its inputs from. E.g., <code>maximumBy (compare `on` fst)</code>.</p>\n<p>Your version <span class=\"math-container\">\\$0.1\\$</span> I think does much better on readability, but you should be aware that you can pattern match on the left side of any assignment or bind. I.e. in <code>heapSort</code>, your entire where clause can be replaced by <code>(x:xs) = buildMaxHeap h</code>.</p>\n<p>As to the rest, this just doesn't have the complexity of a typical heapsort. Haskell lists are linked lists, not arrays. Indexing, computing length, assigning elements and appending to the back (<code>(++)</code>) are all <span class=\"math-container\">\\$O(n)\\$</span> operations. I <em>think</em> you might be able to write a version of heap sort with the right algorithmic complexity that is still pure using <code>"array".Data.Array</code> but it might involve tying the knot and I haven't put enough brain power to the task to say if it would really be possible. You could definitely do it with the vector package, having the escape hatch of working in <code>ST</code>.</p>\n<hr>\n<p>Based on your “Update 1,” I'd definitely use names longer than a single letter. It all blends together visually, changing <code>h</code> to <code>heap</code> would probably help a lot, maybe changing <code>k</code>. I'm not sure “key” is really the term d'art either, aren't the things in a heap just called “values?” You could also use guards in the definition to condense it vertically a bit.</p>\n<pre><code>heapIncreaseKey i k h\n | k < h !! (i - 1) = error "..."\n | otherwise = go i k h\n where\n ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T18:02:34.247",
"Id": "510433",
"Score": "0",
"body": "Thank you very much for your review! I've updated a new function. I have some doubts on the naming of variables and also on the use of `fail`. Could you comment?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T18:15:37.930",
"Id": "510438",
"Score": "0",
"body": "I am aware of the performance issues with `Data.List`. But the APIs for `List` is cleaner compared to the other packages. And this is definitely not production code. But really appreciate your thoughtful hints!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T18:20:33.883",
"Id": "510439",
"Score": "0",
"body": "BTW, do you mean `Data.Vector.Mutable`? I am seeing quite a number of `vector` sub-modules"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T22:50:54.620",
"Id": "510454",
"Score": "1",
"body": "I can provide a more thorough review on your update later, but I think you're looking for `error`, not `fail`. `fail` in the list monad will just return `[]` as far as I recall. `error` crashes the program. Maybe you'd like to use `Either String [a]` in the return type of the function?\n\nThere are a bunch of different flavors of vector, yeah. Since you're working on collections of unknown elements (`(Ord a, Show a) => a` being all you know) then yeah, `Data.Vector.Mutable`. If you knew more about the type you could take advantage of `Unboxed` or `Storable` for a more space-efficient vector."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T17:28:48.607",
"Id": "258884",
"ParentId": "258862",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "258884",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T06:57:13.680",
"Id": "258862",
"Score": "2",
"Tags": [
"haskell"
],
"Title": "Haskell maxheapify"
}
|
258862
|
<p>I'm making a user interface for an online coffee shop. I need to call methods that have already been created. The user is also able to make customisations to their drink order such as a different choice of milk, brown or white sugar etc. Once the user choice has been made it will add the drink to their basket. The user also has the option of editing their drinks basket and removing a drink if they so wish.</p>
<p>It will receive information from a file. This code works but is very messy. Are there ways to clean it up and make it neater/less repetitive?</p>
<pre><code>from display.output import ConsoleOutput
from user import User
from user.drinks import Drink
from user.drinks.customisations import CustomisationManager, Customisation
from user.drinks.drinks_manager import DrinksManager
from user.drinks.types import SoftDrink, Coffee
class Strings:
add_customisation_to_drink_yn = "Would you like to add a customisation to your drink? y/n"
remove_customisation_from_drink = "Would you like to remove a customisation from your drink? y/n"
change_customisation = "Would you like to change the customisations of your drink? y/n"
change_size = "Would you like to change the size of your drink? y/n"
current_drinks = "We currently have these drinks available:"
add_customisations = "Would you like to add any customisations? y/n"
current_customisations = "\nWe currently have these customisations available:"
commands = "\na: add new drink, u: update drink, b: show basket, q: quit, r: remove drink from basket"
@staticmethod
def items_in_basket_cost(basket):
return f"You currently have these items in your basket costing {basket.calculate_cost()}"
@staticmethod
def add_drink_to_basket(drinks_manager):
return f"Which drink would you like to add to your basket? 0-{len(drinks_manager.all_drinks()) - 1}"
@staticmethod
def add_size_to_drink(drink, sizes):
return f"Which size of {drink.name} would you like to add to your drink? 0-{len(sizes) - 1}"
@staticmethod
def add_customisation_to_drink(customisations_manager, drink):
return f"Which customisation would you like to add to your {drink.name}?" \
+ f"0-{len(customisations_manager.all_customisations()) - 1}"
@staticmethod
def remove_drink_from_basket(user):
return f"Which drink would you like to remove from your basket? 0-{len(user.basket.items) - 1}"
@staticmethod
def update_drink_in_basket(user):
return f"Which drink would you like to update in your basket? 0-{len(user.basket.items) - 1}"
@staticmethod
def customisation_to_remove(drink):
return f"Which customisation would you like to remove from your drink? 0-{len(drink.customisations) - 1}"
class Main:
def __init__(self):
self.display = Display(input_handler=ConsoleInput(), output_handler=ConsoleOutput())
self.drink_manager = DrinksManager()
self.customisation_manager = CustomisationManager()
self.drink_manager.register_drink(Coffee(1.0, 1, 'Coffee'))
self.drink_manager.register_drink(SoftDrink(1.0, 2, 'Juice'))
self.drink_manager.register_drink(Coffee(1.0, 3, 'Milk'))
self.drink_manager.register_drink(Coffee(1.0, 4, 'Mocha'))
self.drink_manager.register_drink(Coffee(1.0, 5, 'Cappuccino'))
self.drink_manager.register_drink(Coffee(1.0, 6, 'Water'))
self.customisation_manager.register_customisation(Customisation(1, 'White Sugar', 0.3))
self.customisation_manager.register_customisation(Customisation(2, 'Brown Sugar', 0.6))
self.customisation_manager.register_customisation(Customisation(3, 'Milk', 0.3))
self.customisation_manager.register_customisation(Customisation(4, 'Almond Milk', 0.2))
self.customisation_manager.register_customisation(Customisation(5, 'Cream', 0.8))
self.user = User()
self.main_menu()
def main_menu(self):
while True:
print(Strings.commands)
command = self.display.input.get('Enter a command:')
print('\n')
if command == 'a':
self.list_drinks()
self.add_drink_to_basket()
elif command == 'u':
self.display_basket()
self.update_drink_in_basket()
elif command == 'q':
break
elif command == 'b':
self.display_basket()
elif command == 'r':
self.remove_drink_from_basket()
def list_drinks(self):
self.display.output.print(Strings.current_drinks)
all_drinks = self.drink_manager.all_drinks()
for index, drink in enumerate(all_drinks):
self.display.output.print(f"{index}. {drink.name} -- £{drink.cost}")
def add_drink_to_basket(self):
drink_index = int(self.display.input.get(Strings.add_drink_to_basket(self.drink_manager)))
drink = self.add_customisation_to_drink(self.drink_manager.all_drinks()[drink_index])
drink = self.add_size_to_drink(drink)
self.user.basket.add_drink(drink)
def add_size_to_drink(self, drink: Drink) -> Drink:
self.list_sizes(drink)
sizes = drink.available_sizes
size_index = int(self.display.input.get(Strings.add_size_to_drink(drink, sizes)))
drink.size = sizes[size_index]
return drink
def list_sizes(self, drink: Drink):
for index, size in enumerate(drink.available_sizes):
print(f"{index}. {size.value.name} -- {size.value.volume}L, £{size.value.cost_multiplier * drink.cost}")
def list_customisations(self):
self.display.output.print(Strings.current_customisations)
all_customisations = self.customisation_manager.all_customisations()
for index, customisation in enumerate(all_customisations):
self.display.output.print(f"{index}. {customisation.name} -- £{customisation.cost}")
def add_customisation_to_drink(self, drink: Drink) -> Drink:
while True:
add_customisation = self.display.input.get(Strings.add_customisations)
if add_customisation == 'n':
return drink
self.list_customisations()
customisation_index = int(self.display.input.get(
Strings.add_customisation_to_drink(self.customisation_manager, drink)
))
drink.add_customisation(self.customisation_manager.all_customisations()[customisation_index])
def display_basket(self):
basket = self.user.basket
self.display.output.print(Strings.items_in_basket_cost(basket))
for drink_index, item in enumerate(basket.items):
self.display.output.print(f"{drink_index}. {item.name} ({item.size.value.name}): £{item.calculate_cost()}")
for customisation_index, customisation in enumerate(item.customisations):
self.display.output.print(f"{' ' * 4} {customisation.name}: {customisation.cost}")
def remove_drink_from_basket(self):
self.display_basket()
drink_index = int(self.display.input.get(
Strings.remove_drink_from_basket(self.user)
))
self.user.basket.remove_drink(self.user.basket.items[drink_index].id)
def update_drink_in_basket(self):
drink_index = int(self.display.input.get(
Strings.update_drink_in_basket(self.user)
))
drink = self.user.basket.items[drink_index]
change_size = self.display.input.get(Strings.change_size)
if change_size == 'y':
drink = self.add_size_to_drink(drink)
change_customisation = self.display.input.get(Strings.change_customisation)
if change_customisation == 'y':
remove_customisation = self.display.input.get(Strings.remove_customisation_from_drink)
if remove_customisation == 'y':
for index, customisation in enumerate(drink.customisations):
self.display.output.print(f"{index}. {customisation.name}: {customisation.cost}")
customisation_index = int(self.display.input.get(
Strings.customisation_to_remove(drink)
))
drink.remove_customisation(drink.customisations[customisation_index])
add_customisation = self.display.input.get(Strings.add_customisation_to_drink_yn)
if add_customisation == 'y':
drink = self.add_customisation_to_drink(drink)
self.user.basket.items[drink_index] = drink
if __name__ == "__main__":
Main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T18:04:36.867",
"Id": "510435",
"Score": "0",
"body": "I think there's probably (?) enough code here to be on topic, but you would benefit from showing your other submodules - `user`, `display`, etc."
}
] |
[
{
"body": "<h2>Strings</h2>\n<p>Given your current code, it doesn't make sense to have <code>Strings</code>. This kind of string centralization is typically seen if you're doing internationalization, but there's no evidence of that.</p>\n<p>Among other problems, <code>Strings</code> isn't used whatsoever as a class - everything in it is static, so if you were to keep your centralised strings (which you shouldn't) the works could be turned into a module.</p>\n<p>Detonate your <code>Strings</code> class and put the individual strings where they're used.</p>\n<p>There's another code smell in that class - all of the <code>y/n</code> strings suggest that you should factor out a yes/no input method that prints that suffix, rather than baking it into each individual prompt. Also, <code>commands</code> should be generated from a command sequence, rather than hard-coded.</p>\n<h2>Everything-on-construction</h2>\n<p><code>Main()</code> does all of the work of <code>main_menu()</code> right in the constructor. That should be avoided; move the <code>main_menu()</code> call up to your entry point.</p>\n<h2>Baked-in currency formatting</h2>\n<pre><code>£{size.value.cost_multiplier * drink.cost}\n</code></pre>\n<p>should be replaced with a call to <code>locale.currency()</code>. Ensure that your locale is set correctly and the pound symbol will be added for you.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T18:18:51.570",
"Id": "258889",
"ParentId": "258873",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T13:50:28.293",
"Id": "258873",
"Score": "4",
"Tags": [
"python",
"git",
"e-commerce"
],
"Title": "Making a coffee shop UI"
}
|
258873
|
<p>The integration field needs to get recalculated every time the starting or goal coordinates change. I wanted to use the flow field algorithm for a problem that includes bigger mazes with changing starting or ending points every 0.5 seconds. Right now the algorithm is far too slow to be useful because the integration field needs to get recalculated every time the starting or ending point changes.</p>
<p>Has someone an idea how to reduce the running time of the method <code>create_integration_field</code> in class <code>FlowField</code>? I'm glad about every hint! (If you are good with numpy, I'd appreciate a possible solution using it, too.) Thank you in advance:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
show_animation = True
def draw_horizontal_line(start_x, start_y, length, o_x, o_y, o_dict, path):
for i in range(start_x, start_x + length):
for j in range(start_y, start_y + 2):
o_x.append(i)
o_y.append(j)
o_dict[(i, j)] = path
def draw_vertical_line(start_x, start_y, length, o_x, o_y, o_dict, path):
for i in range(start_x, start_x + 2):
for j in range(start_y, start_y + length):
o_x.append(i)
o_y.append(j)
o_dict[(i, j)] = path
class FlowField:
def __init__(self, obs_grid, goal_x, goal_y, start_x, start_y,
limit_x, limit_y):
self.start_pt = [start_x, start_y]
self.goal_pt = [goal_x, goal_y]
self.obs_grid = obs_grid
self.limit_x, self.limit_y = limit_x, limit_y
self.cost_field = {}
self.integration_field = {}
self.vector_field = {}
def find_path(self):
self.create_cost_field()
self.create_integration_field()
self.assign_vectors()
self.follow_vectors()
def create_cost_field(self):
"""Assign cost to each grid which defines the energy
it would take to get there."""
for i in range(self.limit_x):
for j in range(self.limit_y):
if self.obs_grid[(i, j)] == 'free':
self.cost_field[(i, j)] = 1
elif self.obs_grid[(i, j)] == 'medium':
self.cost_field[(i, j)] = 7
elif self.obs_grid[(i, j)] == 'hard':
self.cost_field[(i, j)] = 20
elif self.obs_grid[(i, j)] == 'obs':
continue
if [i, j] == self.goal_pt:
self.cost_field[(i, j)] = 0
def create_integration_field(self):
"""Start from the goal node and calculate the value
of the integration field at each node. Start by
assigning a value of infinity to every node except
the goal node which is assigned a value of 0. Put the
goal node in the open list and then get its neighbors
(must not be obstacles). For each neighbor, the new
cost is equal to the cost of the current node in the
integration field (in the beginning, this will simply
be the goal node) + the cost of the neighbor in the
cost field + the extra cost (optional). The new cost
is only assigned if it is less than the previously
assigned cost of the node in the integration field and,
when that happens, the neighbor is put on the open list.
This process continues until the open list is empty."""
for i in range(self.limit_x):
for j in range(self.limit_y):
if self.obs_grid[(i, j)] == 'obs':
continue
self.integration_field[(i, j)] = np.inf
if [i, j] == self.goal_pt:
self.integration_field[(i, j)] = 0
open_list = [(self.goal_pt, 0)]
while open_list:
curr_pos, curr_cost = open_list[0]
curr_x, curr_y = curr_pos
for i in range(-1, 2):
for j in range(-1, 2):
x, y = curr_x + i, curr_y + j
if self.obs_grid[(x, y)] == 'obs':
continue
if (i, j) in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
e_cost = 10
else:
e_cost = 14
neighbor_energy = self.cost_field[(x, y)]
neighbor_old_cost = self.integration_field[(x, y)]
neighbor_new_cost = curr_cost + neighbor_energy + e_cost
if neighbor_new_cost < neighbor_old_cost:
self.integration_field[(x, y)] = neighbor_new_cost
open_list.append(([x, y], neighbor_new_cost))
del open_list[0]
def assign_vectors(self):
"""For each node, assign a vector from itself to the node with
the lowest cost in the integration field. An agent will simply
follow this vector field to the goal"""
for i in range(self.limit_x):
for j in range(self.limit_y):
if self.obs_grid[(i, j)] == 'obs':
continue
if [i, j] == self.goal_pt:
self.vector_field[(i, j)] = (None, None)
continue
offset_list = [(i + a, j + b)
for a in range(-1, 2)
for b in range(-1, 2)]
neighbor_list = [{'loc': pt,
'cost': self.integration_field[pt]}
for pt in offset_list
if self.obs_grid[pt] != 'obs']
neighbor_list = sorted(neighbor_list, key=lambda x: x['cost'])
best_neighbor = neighbor_list[0]['loc']
self.vector_field[(i, j)] = best_neighbor
def follow_vectors(self):
curr_x, curr_y = self.start_pt
while curr_x is not None and curr_y is not None:
curr_x, curr_y = self.vector_field[(curr_x, curr_y)]
if curr_x is None or curr_y is None:
break
if show_animation:
plt.plot(curr_x, curr_y, "b*")
plt.pause(0.001)
if show_animation:
plt.show()
def main():
# set obstacle positions
obs_dict = {}
for i in range(51):
for j in range(51):
obs_dict[(i, j)] = 'free'
o_x, o_y, m_x, m_y, h_x, h_y = [], [], [], [], [], []
s_x = 5.0
s_y = 5.0
g_x = 35.0
g_y = 45.0
# draw outer border of maze
draw_vertical_line(0, 0, 50, o_x, o_y, obs_dict, 'obs')
draw_vertical_line(48, 0, 50, o_x, o_y, obs_dict, 'obs')
draw_horizontal_line(0, 0, 50, o_x, o_y, obs_dict, 'obs')
draw_horizontal_line(0, 48, 50, o_x, o_y, obs_dict, 'obs')
# draw inner walls
all_x = [10, 10, 10, 15, 20, 20, 30, 30, 35, 30, 40, 45]
all_y = [10, 30, 45, 20, 5, 40, 10, 40, 5, 40, 10, 25]
all_len = [10, 10, 5, 10, 10, 5, 20, 10, 25, 10, 35, 15]
for x, y, l in zip(all_x, all_y, all_len):
draw_vertical_line(x, y, l, o_x, o_y, obs_dict, 'obs')
all_x[:], all_y[:], all_len[:] = [], [], []
all_x = [35, 40, 15, 10, 45, 20, 10, 15, 25, 45, 10, 30, 10, 40]
all_y = [5, 10, 15, 20, 20, 25, 30, 35, 35, 35, 40, 40, 45, 45]
all_len = [10, 5, 10, 10, 5, 5, 10, 5, 10, 5, 10, 5, 5, 5]
for x, y, l in zip(all_x, all_y, all_len):
draw_horizontal_line(x, y, l, o_x, o_y, obs_dict, 'obs')
# Some points are assigned a slightly higher energy value in the cost
# field. For example, if an agent wishes to go to a point, it might
# encounter different kind of terrain like grass and dirt. Grass is
# assigned medium difficulty of passage (color coded as green on the
# map here). Dirt is assigned hard difficulty of passage (color coded
# as brown here). Hence, this algorithm will take into account how
# difficult it is to go through certain areas of a map when deciding
# the shortest path.
# draw paths that have medium difficulty (in terms of going through them)
all_x[:], all_y[:], all_len[:] = [], [], []
all_x = [10, 45]
all_y = [22, 20]
all_len = [8, 5]
for x, y, l in zip(all_x, all_y, all_len):
draw_vertical_line(x, y, l, m_x, m_y, obs_dict, 'medium')
all_x[:], all_y[:], all_len[:] = [], [], []
all_x = [20, 30, 42] + [47] * 5
all_y = [35, 30, 38] + [37 + i for i in range(2)]
all_len = [5, 7, 3] + [1] * 3
for x, y, l in zip(all_x, all_y, all_len):
draw_horizontal_line(x, y, l, m_x, m_y, obs_dict, 'medium')
# draw paths that have hard difficulty (in terms of going through them)
all_x[:], all_y[:], all_len[:] = [], [], []
all_x = [15, 20, 35]
all_y = [45, 20, 35]
all_len = [3, 5, 7]
for x, y, l in zip(all_x, all_y, all_len):
draw_vertical_line(x, y, l, h_x, h_y, obs_dict, 'hard')
all_x[:], all_y[:], all_len[:] = [], [], []
all_x = [30] + [47] * 5
all_y = [10] + [37 + i for i in range(2)]
all_len = [5] + [1] * 3
for x, y, l in zip(all_x, all_y, all_len):
draw_horizontal_line(x, y, l, h_x, h_y, obs_dict, 'hard')
if show_animation:
plt.plot(o_x, o_y, "sr")
plt.plot(m_x, m_y, "sg")
plt.plot(h_x, h_y, "sy")
plt.plot(s_x, s_y, "og")
plt.plot(g_x, g_y, "o")
plt.grid(True)
flow_obj = FlowField(obs_dict, g_x, g_y, s_x, s_y, 50, 50)
flow_obj.find_path()
if __name__ == '__main__':
main()
</code></pre>
|
[] |
[
{
"body": "<p>The code, at least in terms of style, is already pretty decent. Consider:</p>\n<ul>\n<li><p>Add PEP484 type hints</p>\n</li>\n<li><p>Your <code>draw_*_line</code> methods have a confusing name - they don't actually draw anything; they're data construction/setup routines. Also, rather than mutating <code>o_x</code>, <code>o_y</code> and <code>o_dict</code>, entirely eliminating side-effects from this function is easy - just return two lists and a dict, and at the calling side call two <code>extend</code>s and an <code>update</code>, respectively.</p>\n</li>\n<li><p><code>start_pt</code> and <code>goal_pt</code> should use tuples, not lists</p>\n</li>\n<li><p>For this code:</p>\n<pre><code> for i in range(self.limit_x):\n for j in range(self.limit_y):\n</code></pre>\n</li>\n</ul>\n<p>Since it's repeated several times, consider factoring it out into a generator function that yields coordinate tuples.</p>\n<ul>\n<li>Consider replacing your <code>'obs'</code>, etc. strings with <code>Enum</code> values</li>\n<li>Use a set instead of a list for membership checks in <code>if (i, j) in [(1, 0), (0, 1), (-1, 0), (0, -1)]:</code></li>\n<li>For your <code>neighbor_list</code>, rather than a weakly-typed dictionary, make a class - a <code>@dataclass</code> would suit</li>\n</ul>\n<p>An implementation that does some of the above:</p>\n<pre><code>from typing import Tuple, Dict, List\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nshow_animation = True\n\n\nCoord = Tuple[int, int]\n\n\ndef draw_horizontal_line(\n start_x: int, start_y: int, length: int,\n o_x: List[int], o_y: List[int],\n o_dict: Dict[Coord, str],\n path: str,\n) -> None:\n for i in range(start_x, start_x + length):\n for j in range(start_y, start_y + 2):\n o_x.append(i)\n o_y.append(j)\n o_dict[(i, j)] = path\n\n\ndef draw_vertical_line(\n start_x: int, start_y: int, length: int,\n o_x: List[int], o_y: List[int],\n o_dict: Dict[Coord, str],\n path: str,\n) -> None:\n for i in range(start_x, start_x + 2):\n for j in range(start_y, start_y + length):\n o_x.append(i)\n o_y.append(j)\n o_dict[(i, j)] = path\n\n\nclass FlowField:\n def __init__(\n self,\n obs_grid: Dict[Coord, str],\n goal_x: float, goal_y: float,\n start_x: float, start_y: float,\n limit_x: int, limit_y: int,\n ):\n self.start_pt = (start_x, start_y)\n self.goal_pt = (goal_x, goal_y)\n self.obs_grid = obs_grid\n self.limit_x, self.limit_y = limit_x, limit_y\n self.cost_field: Dict[Coord, int] = {}\n self.integration_field: Dict[Coord, int] = {}\n self.vector_field: Dict[Coord, Coord] = {}\n\n def find_path(self) -> None:\n self.create_cost_field()\n self.create_integration_field()\n self.assign_vectors()\n self.follow_vectors()\n\n def create_cost_field(self) -> None:\n """Assign cost to each grid which defines the energy\n it would take to get there."""\n for i in range(self.limit_x):\n for j in range(self.limit_y):\n coord = (i, j)\n if self.obs_grid[coord] == 'free':\n self.cost_field[coord] = 1\n elif self.obs_grid[coord] == 'medium':\n self.cost_field[coord] = 7\n elif self.obs_grid[coord] == 'hard':\n self.cost_field[coord] = 20\n elif self.obs_grid[coord] == 'obs':\n continue\n\n if coord == self.goal_pt:\n self.cost_field[coord] = 0\n\n def create_integration_field(self) -> None:\n """Start from the goal node and calculate the value\n of the integration field at each node. Start by\n assigning a value of infinity to every node except\n the goal node which is assigned a value of 0. Put the\n goal node in the open list and then get its neighbors\n (must not be obstacles). For each neighbor, the new\n cost is equal to the cost of the current node in the\n integration field (in the beginning, this will simply\n be the goal node) + the cost of the neighbor in the\n cost field + the extra cost (optional). The new cost\n is only assigned if it is less than the previously\n assigned cost of the node in the integration field and,\n when that happens, the neighbor is put on the open list.\n This process continues until the open list is empty."""\n for i in range(self.limit_x):\n for j in range(self.limit_y):\n if self.obs_grid[(i, j)] == 'obs':\n continue\n self.integration_field[(i, j)] = np.inf\n if (i, j) == self.goal_pt:\n self.integration_field[(i, j)] = 0\n\n open_list = [(self.goal_pt, 0)]\n while open_list:\n curr_pos, curr_cost = open_list[0]\n curr_x, curr_y = curr_pos\n for i in range(-1, 2):\n for j in range(-1, 2):\n x, y = curr_x + i, curr_y + j\n if self.obs_grid[(x, y)] == 'obs':\n continue\n if (i, j) in [(1, 0), (0, 1), (-1, 0), (0, -1)]:\n e_cost = 10\n else:\n e_cost = 14\n neighbor_energy = self.cost_field[(x, y)]\n neighbor_old_cost = self.integration_field[(x, y)]\n neighbor_new_cost = curr_cost + neighbor_energy + e_cost\n if neighbor_new_cost < neighbor_old_cost:\n self.integration_field[(x, y)] = neighbor_new_cost\n open_list.append(([x, y], neighbor_new_cost))\n del open_list[0]\n\n def assign_vectors(self) -> None:\n """For each node, assign a vector from itself to the node with\n the lowest cost in the integration field. An agent will simply\n follow this vector field to the goal"""\n for i in range(self.limit_x):\n for j in range(self.limit_y):\n if self.obs_grid[(i, j)] == 'obs':\n continue\n if (i, j) == self.goal_pt:\n self.vector_field[(i, j)] = (None, None)\n continue\n offset_list = [(i + a, j + b)\n for a in range(-1, 2)\n for b in range(-1, 2)]\n neighbor_list = [{'loc': pt,\n 'cost': self.integration_field[pt]}\n for pt in offset_list\n if self.obs_grid[pt] != 'obs']\n neighbor_list = sorted(neighbor_list, key=lambda x: x['cost'])\n best_neighbor = neighbor_list[0]['loc']\n self.vector_field[(i, j)] = best_neighbor\n\n def follow_vectors(self) -> None:\n curr_x, curr_y = self.start_pt\n while curr_x is not None and curr_y is not None:\n curr_x, curr_y = self.vector_field[(curr_x, curr_y)]\n if curr_x is None or curr_y is None:\n break\n\n if show_animation:\n plt.plot(curr_x, curr_y, "b*")\n plt.pause(0.001)\n\n if show_animation:\n plt.show()\n\n\ndef main():\n # set obstacle positions\n obs_dict = {}\n for i in range(51):\n for j in range(51):\n obs_dict[(i, j)] = 'free'\n o_x, o_y, m_x, m_y, h_x, h_y = [], [], [], [], [], []\n\n s_x = 5.0\n s_y = 5.0\n g_x = 35.0\n g_y = 45.0\n\n # draw outer border of maze\n draw_vertical_line(0, 0, 50, o_x, o_y, obs_dict, 'obs')\n draw_vertical_line(48, 0, 50, o_x, o_y, obs_dict, 'obs')\n draw_horizontal_line(0, 0, 50, o_x, o_y, obs_dict, 'obs')\n draw_horizontal_line(0, 48, 50, o_x, o_y, obs_dict, 'obs')\n\n # draw inner walls\n all_x = [10, 10, 10, 15, 20, 20, 30, 30, 35, 30, 40, 45]\n all_y = [10, 30, 45, 20, 5, 40, 10, 40, 5, 40, 10, 25]\n all_len = [10, 10, 5, 10, 10, 5, 20, 10, 25, 10, 35, 15]\n for x, y, l in zip(all_x, all_y, all_len):\n draw_vertical_line(x, y, l, o_x, o_y, obs_dict, 'obs')\n\n all_x[:], all_y[:], all_len[:] = [], [], []\n all_x = [35, 40, 15, 10, 45, 20, 10, 15, 25, 45, 10, 30, 10, 40]\n all_y = [5, 10, 15, 20, 20, 25, 30, 35, 35, 35, 40, 40, 45, 45]\n all_len = [10, 5, 10, 10, 5, 5, 10, 5, 10, 5, 10, 5, 5, 5]\n for x, y, l in zip(all_x, all_y, all_len):\n draw_horizontal_line(x, y, l, o_x, o_y, obs_dict, 'obs')\n\n # Some points are assigned a slightly higher energy value in the cost\n # field. For example, if an agent wishes to go to a point, it might\n # encounter different kind of terrain like grass and dirt. Grass is\n # assigned medium difficulty of passage (color coded as green on the\n # map here). Dirt is assigned hard difficulty of passage (color coded\n # as brown here). Hence, this algorithm will take into account how\n # difficult it is to go through certain areas of a map when deciding\n # the shortest path.\n\n # draw paths that have medium difficulty (in terms of going through them)\n all_x[:], all_y[:], all_len[:] = [], [], []\n all_x = [10, 45]\n all_y = [22, 20]\n all_len = [8, 5]\n for x, y, l in zip(all_x, all_y, all_len):\n draw_vertical_line(x, y, l, m_x, m_y, obs_dict, 'medium')\n\n all_x[:], all_y[:], all_len[:] = [], [], []\n all_x = [20, 30, 42] + [47] * 5\n all_y = [35, 30, 38] + [37 + i for i in range(2)]\n all_len = [5, 7, 3] + [1] * 3\n for x, y, l in zip(all_x, all_y, all_len):\n draw_horizontal_line(x, y, l, m_x, m_y, obs_dict, 'medium')\n\n # draw paths that have hard difficulty (in terms of going through them)\n all_x[:], all_y[:], all_len[:] = [], [], []\n all_x = [15, 20, 35]\n all_y = [45, 20, 35]\n all_len = [3, 5, 7]\n for x, y, l in zip(all_x, all_y, all_len):\n draw_vertical_line(x, y, l, h_x, h_y, obs_dict, 'hard')\n\n all_x[:], all_y[:], all_len[:] = [], [], []\n all_x = [30] + [47] * 5\n all_y = [10] + [37 + i for i in range(2)]\n all_len = [5] + [1] * 3\n for x, y, l in zip(all_x, all_y, all_len):\n draw_horizontal_line(x, y, l, h_x, h_y, obs_dict, 'hard')\n\n if show_animation:\n plt.plot(o_x, o_y, "sr")\n plt.plot(m_x, m_y, "sg")\n plt.plot(h_x, h_y, "sy")\n plt.plot(s_x, s_y, "og")\n plt.plot(g_x, g_y, "o")\n plt.grid(True)\n\n flow_obj = FlowField(obs_dict, g_x, g_y, s_x, s_y, 50, 50)\n flow_obj.find_path()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T16:45:56.027",
"Id": "258880",
"ParentId": "258874",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T14:20:14.817",
"Id": "258874",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"numpy"
],
"Title": "Reducing running time of creating integration field in flow field algorithm (python)"
}
|
258874
|
<p>This is my third day of learning Javascript through an online class. I learned about arrays and while/for loops today, and to practice all of that stuff the challenge I'm working on is to make a function that produces <span class="math-container">\$(n)\$</span> terms of the Fibonacci sequence in an array.</p>
<p>So I'm hoping for some feedback on this code! I think it works but I would like to know how I could make it more efficient or better in any way.</p>
<pre><code>function fibonacciGenerator (n) {
var output=[];
if (n===1) {
output=[0];
} else if (n===2) {
output=[0,1];
} else if (n>2) {
output=[0,1];
for (var i=3;i<=n;i++) {
output.push(output[i-3]+output[i-2]);
}
}
return output;
}
</code></pre>
|
[] |
[
{
"body": "<p>For a beginner this code looks okay. Good job using strict equality comparisons - i.e. <code>===</code>. The indentation is mostly consistent, although the first indentation level is 4 spaces while all subsequent levels appear to be 2 spaces.</p>\n<p>The biggest thing I would change is spacing. For the sake of readability, it helps to add spacing around operators - especially binary operators like <code>===</code>, <code>></code>, <code>=</code>, etc. You could utilize a linter like <a href=\"https://eslint.org/\" rel=\"nofollow noreferrer\">ESLint</a>, JSHint, etc. ESLint has rules like <a href=\"https://eslint.org/docs/rules/space-infix-ops\" rel=\"nofollow noreferrer\">space-infix-ops</a>.</p>\n<blockquote>\n<p>While formatting preferences are very personal, a number of style\nguides require spaces around operators, such as:</p>\n<pre><code>var sum = 1 + 2; \n</code></pre>\n<p>The proponents of these extra spaces believe it make\nthe code easier to read and can more easily highlight potential\nerrors, such as:</p>\n<pre><code>var sum = i+++2; \n</code></pre>\n<p>While this is valid JavaScript syntax, it is hard to\ndetermine what the author intended.</p>\n</blockquote>\n<p><sup><a href=\"https://eslint.org/docs/rules/space-infix-ops\" rel=\"nofollow noreferrer\">1</a></sup></p>\n<p>I tried passing <code>0</code> to the function and it returned <code>[0, 1]</code>, which is the same output if I pass <code>2</code>. Theoretically it should return an empty array when <code>0</code> is passed.</p>\n<p>The first and second else cases could be simplified to just an <code>else</code>, since the loop won't run unless <code>i</code> is less than <code>n</code> and for the case of 2 it would never be the case that 3 is less than 2. So it can be simplified like this:</p>\n<pre><code>function fibonacciGenerator (n) {\n var output = [];\n if (n === 1) {\n output = [0];\n } else {\n output = [0, 1];\n for (var i=3; i <= n; i++) {\n output.push(output[i-3] + output[i-2]);\n }\n }\n return output;\n}\n</code></pre>\n<p>In more advanced JavaScript the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\"><code>const</code></a> keyword could be used to declare <code>output</code> so it can't be over-written, which would require exclusively using the <code>.push()</code> method to add elements to the output array. Using <code>const</code> when re-assignment isn't needed is a good habit because it can help avoid <a href=\"https://softwareengineering.stackexchange.com/a/278653/244085\">accidental re-assignment and other bugs</a>.</p>\n<p>Alternatively, the function could return early in the base cases - e.g. when <code>n</code> is <code>1</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T05:23:31.323",
"Id": "510477",
"Score": "0",
"body": "Awesome, I appreciate this a lot. I hadn't realized that I only needed one else condition. I'll have to revisit this once I get to learning about const, too!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T16:14:07.623",
"Id": "258878",
"ParentId": "258876",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T14:40:59.260",
"Id": "258876",
"Score": "1",
"Tags": [
"javascript",
"beginner",
"fibonacci-sequence"
],
"Title": "Fibonacci sequence array in Javascript"
}
|
258876
|
<p>I have to do a program in PHP that reads <a href="https://xp-soaring.github.io/igc_file_format/index.html" rel="nofollow noreferrer">IGC files</a> like <a href="https://xcportal.pl/sites/default/files/tracks/2020-06-09/069daro396091568.igc" rel="nofollow noreferrer">this IGC file</a> and gets records about the glider.</p>
<p>For now I came up with something like this:</p>
<pre><code><?php
class Pilot {
public $name;
public $gliderType;
public $competitionId;
public $gpsDatuml;
public $competitionClass;
public $startPoint;
public $endPoint;
}
$pilot = new Pilot();
$myFile = new SplFileObject("https://xcportal.pl/sites/default/files/tracks/2020-06-09/069daro396091568.igc", 'r', 10);
for($i=0; $i < 10; $i++) {
$information = $myFile->fgets();
if(($pos = strpos($information, "PILOT")) !== FALSE){
$pilot->name = substr($information, $pos+7);
}
if(($pos = strpos($information, "GLIDERTYPE")) !== FALSE){
$pilot->gliderType = substr($information, $pos+12);
}
if(($pos = strpos($information, "COMPETITIONID")) !== FALSE){
$pilot->competitionId = substr($information, $pos+15);
}
if(($pos = strpos($information, "GPSDATUM")) !== FALSE){
$pilot->gpsDatuml = substr($information, $pos+10);
}
if(($pos = strpos($information, "CLASS")) !== FALSE){
$pilot->competitionClass = substr($information, $pos+7);
}
// echo strpbrk($information, "PILOT");
// echo substr($information, 10);
}
echo $pilot->name;
echo $pilot->gliderType;
echo $pilot->competitionId;
echo $pilot->gpsDatuml;
echo $pilot->competitionClass;
$myFile = null;
?>
</code></pre>
<p>but I wonder if there is anyway to do it better that I haven't figured out already.</p>
<p>Also is it good practice to keep properties of the class as a private field or can I leave them as public if any other class doesn't use that property?</p>
|
[] |
[
{
"body": "<p>I don't think I understand the point of declaring a class if you aren't going to write any methods in it. I mean why go the expense of declaring a class just to store some variables outside of the global scope. Assuming this class can never populate its properties without parsing a document, so it make sense to have its constructor initiate the file reading and generate values for the properties.</p>\n<ul>\n<li><p>I haven't personally used <code>SPLFileObject</code> before, but <a href=\"https://www.php.net/manual/en/class.splfileobject.php\" rel=\"nofollow noreferrer\">the manual</a> says that:</p>\n<ul>\n<li>the 2nd parameter <code>$open_mode</code> defaults to <code>r</code> and</li>\n<li>the 3rd parameter <code>$use_include_path</code> expects a boolean value. I expect that that <code>10</code> is not doing what you intend.</li>\n</ul>\n</li>\n<li><p>Reading a limited number of lines from the file with <code>fgets()</code> is a professional decision that shows real care and deliberate scripting. Removing all debate regarding micro-optimization or if reading the whole file is an "affordable" cost, I love that you are endeavoring to ONLY "read what you need".</p>\n</li>\n<li><p>By my count, there are 3 factors which should halt the loop of reading of lines:</p>\n<ol>\n<li>there are no more lines in the file</li>\n<li>a line is encountered that does not contain a colon</li>\n<li>you have extracted all relevant details from the file up to your self-imposed "magic counter" <code>10</code></li>\n</ol>\n<p>The first two logical break points should be baked into the loop's breaking syntax. The third is probably something that you don't want to get into the habit of. Another developer may look at the code (without seeing a sample input file) and think: "Why is this operation limited to 10? Why not 20? Why not 5?" It is best to avoid magic numbers, or if you <em>need</em> to have them, write a comment explaining why it is implemented.</p>\n</li>\n<li><p>That battery of <code>if</code> conditions is considerably less wise. Think about it. If the first <code>if</code> is satisfied -- why would you want to bother executing the other four checks? They <em>should</em> never be satisfied if the first one is. While I am going to suggest a different technique in my snippet to follow, your snippet at the very least would be improved by using subsequent <code>elseif</code> conditions.</p>\n</li>\n</ul>\n<p>Because I'm rather familiar with regex, I find using regex with a lookup array to be a very convenient technique to extract your targeted values from the remote file. Not only does regex afford a more compact script, it maintains the flexibility of your original script by allowing the targeted lines to exist in any order.</p>\n<p>A code suggestion:</p>\n<pre><code>class Pilot\n{\n public $name;\n public $gliderType;\n public $competitionId;\n public $gpsDatuml;\n public $competitionClass;\n public $startPoint; // I don't know where/how this gets populated\n public $endPoint; // I don't know where/how this gets populated\n\n private $keywords = [\n 'PILOT' => 'name',\n 'GLIDERTYPE' => 'gliderType',\n 'COMPETITIONID' => 'competitionId',\n 'GPSDATUM' => 'gpsDatuml',\n 'CLASS' => 'competitionClass',\n ];\n \n public function __construct(string $url)\n {\n $this->populatePropertiesFromUrl($url); \n }\n \n public function populatePropertiesFromUrl(string $url): void\n {\n $pattern = '~(' . implode('|', array_keys($this->keywords)) . '): (.*)~';\n\n $file = new SplFileObject($url);\n while (!$file->eof()\n && ($line = $file->fgets())\n && strpos($line, ':') !== false\n ) {\n if (preg_match($pattern, $line, $match)) {\n $this->{$this->keywords[$match[1]]} = $match[2];\n }\n }\n }\n}\n$pilot = new Pilot('https://xcportal.pl/sites/default/files/tracks/2020-06-09/069daro396091568.igc');\nvar_export(get_object_vars($pilot));\n</code></pre>\n<p>Output (should be):</p>\n<pre><code>array (\n 'name' => 'DARIUSZ KISZKO',\n 'gliderType' => 'ADVANCE IOTA 2',\n 'competitionId' => '0000',\n 'gpsDatuml' => 'WGS-84',\n 'competitionClass' => 'Paraglider (Standard)',\n 'startPoint' => NULL,\n 'endPoint' => NULL,\n)\n</code></pre>\n<p>*Disclaimer: I am making some assumptions about the text in the remote file. I don't actually know how the text may vary. I don't know if my suggested code will hold up against other files. You may wish to adjust my loop breaking algorithm.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T17:32:02.250",
"Id": "513269",
"Score": "0",
"body": "Nice - I like it ... I believe the `while` conditions would need to be updated like `while (!$file->eof() && ($line = $file->fgets()) && strpos($line, ':') !== false) {` since 1. the assignment of `$line` seems to need to be outside the call to `strpos` (unless there is some config option I am missing?) and 2. the loop would stop as soon as a line contains a colon if `===` is used between `strpos()` and `false`; And I agree about it seeming pointless to have a class with no methods - I guess my thought was incomplete."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T20:53:22.957",
"Id": "513278",
"Score": "1",
"body": "Yes, thanks, I had the boolean check reversed. I clearly did not test my code and I still haven't because I don't have the time to setting a test. I am only eyeballing the code. I am assuming that `fgets()` is going to return a scalar value -- when it is `false`, it will not find a colon. Admittedly, I don't actually like declarations inside of conditions, but I was endeavoring to avoid any separate break conditions inside the `while()`'s body."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-18T05:11:38.963",
"Id": "259683",
"ParentId": "258877",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T15:21:09.753",
"Id": "258877",
"Score": "2",
"Tags": [
"php",
"strings",
"array",
"parsing"
],
"Title": "Parsing glider data from IGC files"
}
|
258877
|
<p>I have a code that does applies Dijkstra's algorithm for an adjacency list.</p>
<p>The data are taken from a file. In the file, the first line contains the number of vertices and edges, and the remaining lines contain three elements each (the first 2 are the numbers of the vertices and 3rd are the weight of the edges).</p>
<p>The output is written to another file. The main problem is long reading (adding to the list) of elements - 8 seconds versus 2 according to the rules of the correct test. In a file for reading, there are 400,000 such lines. How can I speed up the reading?</p>
<pre><code>#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
#include <list>
#include <vector>
#include <queue>
using namespace std;
# define INF 0x3f3f3f3f
typedef pair<int, int> iPair;
class Graph
{
int V;
list< pair<int, int> >* adj;
public:
Graph(int V);
void addEdge(int u, int v, int w);
void shortestPath(int s);
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<iPair>[V];
}
void Graph::addEdge(int u, int v, int w)
{
adj[u].push_back(make_pair(v, w));
adj[v].push_back(make_pair(u, w));
}
void Graph::shortestPath(int src)
{
priority_queue< iPair, vector <iPair>, greater<iPair> > pq;
vector<int> dist(V, INF);
pq.push(make_pair(0, src));
dist[src] = 0;
while (!pq.empty())
{
int u = pq.top().second;
pq.pop();
list< pair<int, int> >::iterator i;
for (i = adj[u].begin(); i != adj[u].end(); ++i)
{
int v = (*i).first;
int weight = (*i).second;
if (dist[v] > dist[u] + weight)
{
dist[v] = dist[u] + weight;
pq.push(make_pair(dist[v], v));
}
}
}
ofstream file1("C:\\Tests\\123.txt");
for (int i = 0; i < V; ++i)
cout << dist[i] << " ";
file1.close();
}
int main()
{
ifstream file("C:\\Tests\\21");
int number_of_veretexes, edges;
file >> number_of_veretexes >> edges;
Graph g(number_of_veretexes);
int _first_, _second_, _third_;
for (int i = 0; i < edges; i++) {
file >> _first_ >> _second_ >> _third_;
g.addEdge( _first_ - 1, _second_ - 1, _third_);
}
g.shortestPath(0);
file.close();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T17:04:45.930",
"Id": "510421",
"Score": "0",
"body": "Without looking at the details, your vector is probably resized and thereby reallocated many many times while it grows. If you know the total count upfront, resize the vector once right away."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T17:36:06.720",
"Id": "510424",
"Score": "0",
"body": "_according to the rules of the correct test_ - What test? Is this for a coding challenge? If so, can you link us?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T17:41:48.747",
"Id": "510427",
"Score": "0",
"body": "@Reinderien This is batch file.We run this bath file with exe file of this programm as first argument.This batch file check data and time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T00:26:59.707",
"Id": "510468",
"Score": "0",
"body": "This is not quite `Dijkstra's Algorithm` though close. There is small difference in setting the minimum distance and thus probably do more work than required. This line `dist[v] = dist[u] + weight;` in Dijkstra's is done at the point where you pop the value (as now you have the shortest route to the node. If the value has already been set you then don't need to iterate over its adjacency list (potentially saving you work). Not sure if that will reduce the time by 400% that seems like a large gap."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T14:41:09.727",
"Id": "510512",
"Score": "0",
"body": "As it turned out, the problem was in the wrongly selected IDE, after installing the Code Blocks everything just started to fly.The code used to compile on Visual Studio"
}
] |
[
{
"body": "<h1>Avoid <code>using namespace std</code></h1>\n<p>Avoid <code>using namespace std</code>, it is <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">considered bad practice</a>. It saves only a little bit of typing, but you can run into issues if names of local classes and variables clash with those defined in the standard library.</p>\n<h1>Use <code>INT_MAX</code> instead of <code>INF</code></h1>\n<p>Don't <code>#define INF</code> to some arbitrary value, just set it to exactly the largest possible value an <code>int</code> can have. This is already defined as <code>INT_MAX</code> in <a href=\"https://en.cppreference.com/w/cpp/types/climits\" rel=\"nofollow noreferrer\"><code><climits></code></a>.</p>\n<h1>Create a <code>struct Edge</code></h1>\n<p>Using a <code>std::pair<int, int></code> is convenient, especially since you can sort them, but it has some drawbacks. It is unclear from just looking at the definition of this type whether the first element is the node number and the second the weight, or the other way around. You actually use both conventions in your code: the adjacency list has the vertex number first, whereas the priority queue has the vertex number second. Create a proper <code>struct</code> to remove the ambiguity and increase type safety. Also, since an edge is a property of a graph, define <code>struct Edge</code> inside <code>class Graph</code>, like so:</p>\n<pre><code>class Graph {\n struct Edge {\n int vertex;\n int weight;\n };\n\n std::list<Edge>* adj;\n ...\n};\n</code></pre>\n<p>Instead of calling <code>adj[u].push_back(std::make_pair(v, w))</code>, you should now write:</p>\n<pre><code>adj[u].push_back({v, w});\n</code></pre>\n<p>For the priority queue, you also want to create a separate <code>struct</code> for the elements. Since only <code>Graph::shortestPath()</code> uses this, you can define this inside that function. To make it sortable, define an <code>operator<()</code> in this struct, like so:</p>\n<pre><code>void Graph::shortestPath(int src) {\n struct VertexDistance {\n int vertex;\n int distance;\n bool operator<(const VertexDistance &other) {\n if (distance != other.distance)\n return distance > other.distance;\n else\n return vertex > other.vertex;\n }\n };\n\n std::priority_queue<VertexDistance> pq;\n ...\n}\n</code></pre>\n<h1>Avoid manual memory allocation</h1>\n<p>It is a bit strange to see you use STL containers like <code>std::list</code> and <code>std::vector</code> and <code>std::priority_queue</code>, but then use <code>new</code> to allocate the array <code>adj</code>. Why not use a <code>std::vector</code> for that too? For example, like so:</p>\n<pre><code>std::vector<std::list<Edge>> adj;\n</code></pre>\n<p>This avoids the need for <code>new</code>, and fixes the memory leak you have because you never call <code>delete</code>. It also allows you to remove the member variable <code>V</code>, since the vector already keeps track of its size.</p>\n<p>You can make it a bit easier to read by creating an alias for the list of edges:</p>\n<pre><code>using AdjacencyList = std::list<Edge>;\nstd::vector<AdjacencyList> adj;\n</code></pre>\n<h1>Use <code>std::vector</code> instead of <code>std::list</code></h1>\n<p><code>std::vector</code> and <code>std::list</code> can both store a list of elements, but they have different tradeoffs in performance, memory requirements, and other aspects. In your code, you only ever add elements to the back of an adjacency list, you never insert or remove elements from the middle. In that case, a <code>std::vector</code> is a much more efficient data structure, so I would just write:</p>\n<pre><code>using AdjacencyList = std::vector<Edge>;\nstd::vector<AdjacencyList> adj;\n</code></pre>\n<h1>Use range-based <code>for</code> loops</h1>\n<p>Unless you cannot use any features from C++11 or later, I strongly recommend you start using <a href=\"https://en.cppreference.com/w/cpp/language/range-for\" rel=\"nofollow noreferrer\">range-based <code>for</code>-loops</a>. They save typing, make the code more readable and reduce the possibility of errors. For example, when iterating over an adjacency list in <code>Graph::shortestPath()</code>, you can write:</p>\n<pre><code>for (auto &edge: adj[u]) {\n int v = edge.vertex;\n int weight = edge.weight;\n ...\n}\n</code></pre>\n<p>The same goes for printing the contents of <code>dist</code>:</p>\n<pre><code>for (auto &distance: dist)\n file << distance << " ";\n</code></pre>\n<h1>Check for errors when reading and writing files</h1>\n<p>A lot of things can go wrong when reading from and writing to files: the files might not exist, be corrupted, you might not have permissions to read and/or write, the disk might get full halfway writing a file, and so on. You should therefore ensure that you have completely read and written files without errors.</p>\n<p>You don't have to check every I/O operation; the file objects will remember if an error condition has occured in the past. So the simplest way to get proper error checking is to do this after reading or writing the whole file. This can be done by checking the <a href=\"https://en.cppreference.com/w/cpp/io/ios_base/iostate\" rel=\"nofollow noreferrer\">I/O state bits</a>. In your case, just checking that <code>good()</code> returns <code>true</code> should be sufficient, like so for the input file:</p>\n<pre><code>int main() {\n ifstream file("...");\n ...\n if (!file.good()) {\n std::cerr << "An error occured while reading the input!\\n";\n return 1;\n }\n\n g.shortestPath(0);\n}\n</code></pre>\n<p>And like so for the output file:</p>\n<pre><code>void Graph::shortestPath(int src) {\n ...\n ofstream file("...");\n ...\n file.close();\n if (!file.good()) {\n std::cerr << "An error occured while writing the output!\\n";\n // TODO: ensure the error propagates to main, or call exit(1)\n }\n}\n</code></pre>\n<p>It is imporant to call <code>close()</code> first here, since the act of closing the stream will ensure its output buffer is completely flushed.</p>\n<p>When you detect an error, it is important that you don't continue using any bad data you might have gotten, that you print a helpful error message to <code>std::cerr</code>, and that if your program returns a non-zero exit code. The latter is important in case your program is called from a script for example, so the script won't continue with bogus data.</p>\n<h1>Move file output out of <code>Graph::shortestPath()</code></h1>\n<p>Following the principle of <a href=\"https://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">separation of concerns</a>, you should remove the file output functionality from <code>shortestPath()</code>. Instead, make that function <code>return</code> the shortest path, and let the caller write it to disk. This can simply be done like so:</p>\n<pre><code>std::vector<int> Graph::shortestPath(int src)\n{\n ...\n while (...) {\n ...\n }\n\n return dist;\n}\n\nint main()\n{\n ...\n auto path = g.shortestPath(0);\n std::ofstream file1(...);\n\n for (auto &distance: path)\n file1 << distance < " ";\n\n file1.close();\n\n if (!file1.good()) {\n std::cerr << "An error occured while writing the output!\\n";\n return 1;\n }\n}\n</code></pre>\n<p>You might also consider moving the file input and output into separate functions, so that <code>main()</code> is simplified to something that looks like this:</p>\n<pre><code>int main() {\n auto graph = readGraph("C:\\\\Tests\\\\21");\n auto path = graph.shortestPath(0);\n writePath(path, "C:\\\\Tests\\123.txt");\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T21:54:36.553",
"Id": "258897",
"ParentId": "258879",
"Score": "3"
}
},
{
"body": "<p>Everything @G. Sliepen said.</p>\n<h2>Small change in the algorithm.</h2>\n<p>Your original algorithm was <code>Dijkstra</code> like. But the difference meant that you potentially expanded a lot more nodes than you needed to. This would mean you added more items to the priority queue which takes time and space and may be enefecient.</p>\n<p>Below is more traditional implementation of Dijkstra's.</p>\n<pre><code>vector<int> Graph::shortestPath(int src)\n{\n priority_queue< iPair, vector <iPair>, greater<iPair> > pq;\n vector<int> dist(V, INT_MAX);\n\n pq.push(make_pair(0, src));\n\n while (!pq.empty())\n {\n int u = pq.top().second;\n int d2u = pq.top().first;\n pq.pop();\n\n // You were missing this first test.\n // And the following update to `dist[u]`\n if (dist[u] != INT_MAX) {\n // Already done this node we can ignore.\n continue;\n }\n\n // First time we made it to this node.\n // Record the distance (it must be the shortest as pq is priority based).\n dist[u] = d2u;\n \n // Loop over all edges from this node.\n for (auto const& item: adj[u])\n {\n int v = item.first;\n int weight = item.second;\n\n // Optimization. Don't need this as pq is priority based.\n // May or may not help.\n if (dist[v] != INT_MAX)\n {\n pq.push({d2u + weight, v});\n }\n }\n }\n return dist;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T00:38:48.167",
"Id": "258902",
"ParentId": "258879",
"Score": "2"
}
},
{
"body": "<p>I suspect that <code>push_back</code> is much more costly than <code>push</code>. (Or maybe vice versa?) (I assume it involves an array (vector) and it is cheaper to tack onto the end than to shift all the contents to make room at the start.)</p>\n<p>So, instead of doing <code>push_back</code>, do <code>push</code>. Then, when finished, reverse the contents of the vector.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T19:04:38.433",
"Id": "258936",
"ParentId": "258879",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "258897",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T16:42:38.507",
"Id": "258879",
"Score": "3",
"Tags": [
"c++",
"performance",
"file"
],
"Title": "Shortest path algorithm"
}
|
258879
|
<p>In the early days of Basic (1970's when i started coding) the midStr() function used left and right positions directly rather than left and length we now use with mid(). I always found it more efficient in my mind to code using the old midStr() method, so I finally just created some code to do it. It's certainly not as efficient as mid(), and if I am dealing with lots of data I'd use mid() directly instead, but for simplicity, I do like the old way better, it's more direct to simply code rightPos rather then rightpos - leftPos + 1, and to test for null.</p>
<p>I also made the rightPos optional, and when not used, the length of the textin is used instead, so it will simply return the remainder of the text starting at the leftPos.</p>
<p>Any kind critique is welcome, thank you.</p>
<pre><code>Function midStr(ByVal textin As String, _
ByVal leftPos As Long, _
Optional ByVal rightPos As Variant) As Variant
'midStr returns textin string using leftPos and rightPos (rather than num_chars).
'rightPos is optional, len(textin) is used for the rightPos when it's not otherwise defined.
On Error GoTo midStrErr
If IsMissing(rightPos) Then rightPos = Len(textin)
If rightPos < leftPos Then
midStr = vbNullString
Else
midStr = Mid(textin, leftPos, rightPos - leftPos + 1)
End If
Exit Function
midStrErr:
On Error Resume Next
midStr = CVErr(xlErrValue) '#VALUE!
End Function
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T23:44:37.440",
"Id": "510463",
"Score": "0",
"body": "It is interesting that `midStr(\"Hello World\", 2, 4)` returns `ell`. I would have thought that it would return 2 characters. Not character 2, 3 and 4."
}
] |
[
{
"body": "<p>While the <code>Optional ByVal rightPos As Variant</code> is a cool idea because you can use the <code>IsMissing</code> function, it introduces unnecessary errors. For example, <code>Debug.Print midStr("Hello World", 1, Nothing)</code> will print "Error 2015" in the Immediate window. That line should not be allowed to compile.</p>\n<p>I would declare the <code>rightPos</code> parameter as <code>Long</code>. The compiler will take care of some of the issues - for example you won't be able to pass an Object. The <code>Long</code> will default to 0 so you can replace <code>If IsMissing(rightPos) Then rightPos = Len(textin)</code> with <code>If rightPos = 0 Then rightPos = Len(textin)</code>.</p>\n<p>The generally accepted convention in VBA is that method names are written with <code>PascalCase</code> and variable names are written with <code>camelCase</code>. Moreover, an Excel User Defined Function (UDF) is usually written with UPPERCASE.</p>\n<p>This function seems to be designed as an Excel UDF. What if you need to use it in VBA? The Excel errors mean nothing to another VBA method. I would write this as a separate VBA only function that will work in any VBA-capable application host (no need to return a Variant):</p>\n<pre><code>Public Function MidStr(ByVal textin As String, _\n ByVal leftPos As Long, _\n Optional ByVal rightPos As Long _\n) As String\n Const methodName As String = "MidStr"\n \n If leftPos < 0 Then Err.Raise 5, methodName, "Invalid left position"\n If rightPos < 0 Then Err.Raise 5, methodName, "Invalid right position"\n \n If rightPos = 0 Then rightPos = Len(textin)\n If rightPos < leftPos Then\n MidStr = vbNullString\n Else\n MidStr = VBA.Mid$(textin, leftPos, rightPos - leftPos + 1)\n End If\nEnd Function\n</code></pre>\n<p>I would then have an Excel UDF:</p>\n<pre><code>Public Function MID_STR(ByVal textin As String, _\n ByVal leftPos As Long, _\n Optional ByVal rightPos As Long _\n) As Variant\n On Error GoTo ErrorHandler\n MID_STR = MidStr(textin, leftPos, rightPos)\nExit Function\nErrorHandler:\n MID_STR = CVErr(xlErrValue)\nEnd Function\n</code></pre>\n<p>This allows the use of <code>MidStr</code> function in other VBA methods and the <code>MID_STR</code> is only going to be called via the Excel interface.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T15:03:39.993",
"Id": "510513",
"Score": "0",
"body": "Raising a runtime error from a public function invoked from a worksheet cell would have Excel swallow the error and the cell would contain a `#VALUE!` error, without needing to explicitly return `CVErr(xlErrValue)`. Not sure duplicating the function is a good idea, basically - upvoted for everything else!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T15:08:48.073",
"Id": "510514",
"Score": "1",
"body": "@MathieuGuindon Yes, but dangeerous if you call the UDF using the ```Evaluate``` method from VBA (for whatever reason). Always best to make sure no error is raised within a UDF. An error raised during an ``Evaluate`` call will stop any VBA code in it's track."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T15:11:35.183",
"Id": "510515",
"Score": "0",
"body": "...and that would be the *expected* behavior, yes :) the most likely outcome otherwise is a *type mismatch* resulting from capturing the return value into a `String` and getting a `Variant/Error` into it - throwing from the guard clauses would point to the real cause of the problem without any indirection."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T15:17:30.923",
"Id": "510516",
"Score": "1",
"body": "@MathieuGuindon It is, I won't argue with that, but there are cases where one would want to make sure that the ```Evaluate``` call does not kill VBA without gracefully cleaning up. It's a matter of coding style I guess"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T22:22:40.083",
"Id": "510703",
"Score": "0",
"body": "Thank you for the suggestions. I will take the advice given by many to use StartIndex and EndIndex instead of LeftPos and RightPos. My current design allows any number to pass, and as long as StartPos <= EndPos then some character(s) will be returned, if not then NULL. But, I agree, defaulting to zero eliminates some error potential, and it does not limit the code at all, so I'll make that change. I also really appreciate the comments regarding PascalCase vs camelCase vs UPPER_CASE. I've never seen a dialog on the subject and so I plan to change to what is more standard."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T12:00:55.697",
"Id": "258919",
"ParentId": "258881",
"Score": "5"
}
},
{
"body": "<h2>Pascal Case</h2>\n<p>When I first started code, Hungarian Notations was a widely accepted standard for VBA. Over the years, Camel Case took over. In my opinion, it is time for Pascal Case to become the standard.</p>\n<p>This has been my rant for some time. I welcome a debate from all user from noob to MVP. The following snippet exemplifies my argument:</p>\n<pre><code>Dim value As Range\nvalue = Range("A1").value\n\nDim text As String\ntext = Range("A1").text\n</code></pre>\n<p>Using Camel Casing to name a variable changes the casing for all properties and methods that share the name for the whole project. I've answer over 2000 question in forum over the years. I can't tell you how many times the improper casing threw me off. It is ridiculous that Microsoft never fixed it.</p>\n<h2>Function Signature</h2>\n<blockquote>\n<pre><code>Function midStr(ByVal textin As String, _\n ByVal leftPos As Long, _\n Optional ByVal rightPos As Variant) As Variant\n</code></pre>\n</blockquote>\n<p>As Cristian Buse mentioned rightPos should be typed Long and the function itself should return a string. I would add that <code>rightPos</code> is rather confusing.</p>\n<blockquote>\n<p>*used left and right positions directly rather than left and length</p>\n</blockquote>\n<p>When I first read this, I thought: "midStr returns a string using the Left() and Right() functions. How peculiar. I wonder how this is easier than mid" <strong>WRONG!!</strong> As it turns out it it use the starting and ending position to return a substring. That's great, I love it!</p>\n<p>I would recommend calling the function <code>SubString</code> but it's named after a vintage VB function. Fo me, it would be better if it returned 1 less character like most similar substring functions.</p>\n<p><code>leftPos</code> and <code>rightPos</code> on the other hand they have got to go. It's too confusing, especially because the function already behaves a little different than expect by returning the extra character. I would use <code>start</code> and <code>end</code> if they were not reserved words. <code>StartIndex</code> and <code>EndIndex</code> or <code>pStart</code> and <code>pEnd</code> are much more intuitive to me.</p>\n<p>Function MidStr(ByVal Text As String, ByVal StartIndex As Long, Optional ByVal EndIndex As Variant) As String\n'midStr returns text string using startIndex and endIndex (rather than num_chars).\n'endIndex is optional, len(text) is used for the endIndex when it's not otherwise defined.</p>\n<pre><code> On Error GoTo midStrErr\n If EndIndex = 0 Then EndIndex = Len(Text)\n If EndIndex < StartIndex Then\n MidStr = vbNullString\n Else\n MidStr = Mid(Text, StartIndex, EndIndex - StartIndex + 1)\n End If\n Exit Function\n \nmidStrErr:\n On Error Resume Next\n MidStr = CVErr(xlErrValue) '#VALUE!\nEnd Function\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T23:06:24.697",
"Id": "510571",
"Score": "0",
"body": "I've semi-recently adopted `PascalCaseEverywhere` and haven't looked back since (had adopted `camelCaseForLocals` from years of C# influencing my VB style!). As for MS fixing it, I could be wrong but my understanding is that it's not something that's possible without rewriting how VBA caches in-scope names ...to make them case-sensitive."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T23:40:59.733",
"Id": "510573",
"Score": "0",
"body": "@MathieuGuindon you would know better that I do. I suspect that they originally did this to improve performance. In truth, I would hate to be the one responsible for fixing this nuisance and taking the heat for any new bug that comes along. Thanks for the ↑vote↑."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T23:47:20.977",
"Id": "510574",
"Score": "1",
"body": "To be fair, having a clean source control diff wasn't much of a concern back then :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T10:08:32.793",
"Id": "510622",
"Score": "1",
"body": "Indeed, absolutely annoying to have VBA lowercasing method names because a variable with same name is defined somewhere or vice versa. I found myself adding a _ at the end of the common variable names (value_, key_) but is ugly and I don't like it. I will consider PascalCase for everything"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T22:23:43.970",
"Id": "510704",
"Score": "1",
"body": "Thank you for the suggestions. I will take the advice given by many to use StartIndex and EndIndex instead of LeftPos and RightPos. My current design allows any number to pass, and as long as StartPos <= EndPos then some character(s) will be returned, if not then NULL. But, I agree, defaulting to zero eliminates some error potential, and it does not limit the code at all, so I'll make that change. I also really appreciate the comments regarding PascalCase vs camelCase vs UPPER_CASE. I've never seen a dialog on the subject and so I plan to change to what is more standard."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T23:03:58.340",
"Id": "510706",
"Score": "0",
"body": "@MarkMain I have one caveat to using Pascal Case. I do not use it for simple counters. For counters I use r and c for rows and columns lowercase letters for everything else."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T23:22:46.570",
"Id": "510707",
"Score": "0",
"body": "thanks, I do the same thing, i typically use r and c for the row and columns; i tend to use i, and i2 for simple indexing, and i'll generally just use 'a' for any quick string manipulation. single letters are nice when it's obvious they are used in a short block of code. I notice that the parameters for Excel use all lower_case with the underscore, and the name of the function seems to be all upper case."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T22:18:09.477",
"Id": "258943",
"ParentId": "258881",
"Score": "2"
}
},
{
"body": "<p>I believe this conforms to a more standard style, i am using start_num, all in lower_case, because that is what i find in the MID() function.\nI want the code clean and short. As always, I appreciate any helpful feedback. Thank you in advance.</p>\n<pre><code>Function MIDSTR(ByVal textin As String, _\n ByVal start_num As Long, _\n Optional ByVal end_num As Long = -1) As String\n 'MIDSTR() is similar to MID() except it returns textin string using start_num and end_num instead of using num_chars.\n 'end_num is optional, Len(textin) is used for the end_num when it's not otherwise defined or when end_enum is a negative number.\n 'Null is returned when start_num is greater than end_num.\n \n If end_num < 0 Then end_num = Len(textin)\n If start_num > end_num Then\n MIDSTR = vbNullString\n Else\n MIDSTR = Mid(textin, start_num, end_num - start_num + 1)\n End If\nEnd Function\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T02:08:51.257",
"Id": "510710",
"Score": "0",
"body": "(moderator hat on) Since the site has to adhere to its Q&A format (and also because actual \"answer\" posts can go much more in-depth than any comment), it would be better to re-frame this \"answer\" (it's technically flaggable as \"not an answer\") as a [follow-up question](https://codereview.meta.stackexchange.com/q/1065/23788). Cheers!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T02:15:52.410",
"Id": "510711",
"Score": "0",
"body": "(moderator hat off) I'd make the function explicitly `Public` and either 1) use language-standard `PascalCase` and return a `String` to leverage VBA error handling (cells get `#VALUE!`), or 2) use the Excel-inspired `SCREAMCASE` and return a `Variant` to emphasize intended use as a UDF. Do you know about Rubberduck?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T02:21:13.787",
"Id": "510714",
"Score": "0",
"body": "[Rubberduck](https://rubberduckvba.com) inspections would flag the implicit/default access modifier, and would suggest using the stringly-typed `Mid$` function over the variant-returning `Mid`, for example. And you could reword that comment into a `@Description` annotation just above the procedure, and then that documentation string could appear in the *Object Browser*."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T23:12:42.477",
"Id": "258990",
"ParentId": "258881",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T16:47:21.223",
"Id": "258881",
"Score": "4",
"Tags": [
"strings",
"vba",
"excel"
],
"Title": "Excel VBA code midStr() function using left and right position instead of length used with mid()"
}
|
258881
|
<pre><code>//MEM = initial memory, INDATA, the actual floating point value
#define atomicAddFloatX(MEM, INDATA)\
{\
float data = INDATA;\
float prev_mem = uintBitsToFloat(MEM);\
float exchange_mem = prev_mem;\
float input_mem = (data + prev_mem);\ //initially this is what we assume we want to put in here.
while (true){\
uint exchange_memuint = atomicExchange(MEM, floatBitsToUint(input_mem));\ //exchange with memory location, assume other threads are doing the same exact thing. atomic exchange returns the value that was already there.
exchange_mem = uintBitsToFloat(exchange_memuint);\ //get the floating point value from returned value.
if (prev_mem != exchange_mem){\ //if it was equal to what we initially suspected, we can exit, our data is guaranteed to be in this memory location for all other threads trying to perform this function.
input_mem = exchange_mem + data;\ //otherwise we need to update our input. Another thread completed their atomic exchange before us.
prev_mem = exchange_mem;\ // update our expectation of return now.
} else {\
break;\
}\
}\
}
//example
atomicAddFloatX(output[thread_id].x, 3.0);
</code></pre>
<p>Vulkan supports atomic float, but only for <a href="https://vulkan.gpuinfo.org/listdevicescoverage.php?extension=VK_EXT_shader_atomic_float&platform=windows" rel="nofollow noreferrer">Nvidia at the moment</a>. It's possible however that other vendors will never support atomic float. In order to provide atomic float functionality, which is absolutely required for some algorithms, I tried my best to try to create something that would have the same effect, if less performant.</p>
<p>I have access to <a href="https://github.com/KhronosGroup/GLSL/blob/master/extensions/khr/GL_KHR_memory_scope_semantics.txt" rel="nofollow noreferrer">#extension GL_KHR_memory_scope_semantics</a>, but it is unclear if that can help me or not. I think I have bugs in how I'm dealing with loading the initial memory logically, though through internal tests in projects where this is used this seems to not have errors, but that may be a fluke of the Nvidia memory model. I'm currently using this for the immersed boundary method for fluid solid coupling, its used to accumulate forces in a part of the algorithm.</p>
<p>I'm also not sure if there's other things I can do to speed this up, though I think this has serialized performance characteristics, which should be equivalent to atomic float normally.</p>
|
[] |
[
{
"body": "<p>I did not realize what atomicCompSwap did nor that it was common for this kind of usecase: <a href=\"https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/atomicCompSwap.xhtml\" rel=\"nofollow noreferrer\">https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/atomicCompSwap.xhtml</a> . This function handles the case of the loaded value for MEM being read incorrectly, this check is automatically handled via the function itself, and simplifies the code. Using the original value of memory we can verify if our assumptions about what we should be adding to are correct:</p>\n<pre><code>#define atomicAddFloatX(MEM, INDATA) \\\n{ \\\n uint expected_mem = MEM; \\\n float input_mem = (uintBitsToFloat(MEM) + INDATA); \\ //initially this is what we assume we want to put in here. \n uint returned_mem = atomicCompSwap(MEM, expected_mem, floatBitsToUint(input_mem)); \\ //if data returned is what we expected it to be, we're good, we added to it successfully\n while(returned_mem != expected_mem){ \\ // if the data returned is something different, we know another thread completed its transaction, so we'll have to add to that instead. \n expected_mem = returned_mem; \\\n input_mem = (uintBitsToFloat(expected_mem) + INDATA) \\\n returned_mem = atomicCompSwap(MEM, expected_mem, floatBitsToUint(input_mem)); \\\n } \\\n}\n</code></pre>\n<p>Basically the code I wrote before was attempting to do something like this, but more confusing and a much less safe way.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T19:05:14.633",
"Id": "258976",
"ParentId": "258883",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T16:54:50.990",
"Id": "258883",
"Score": "0",
"Tags": [
"floating-point",
"atomic",
"glsl"
],
"Title": "GLSL atomic float add for architectures with out atomic float add"
}
|
258883
|
<p>I have been trying to improve my Python coding and was just wondering if there was a more pythonic way to perform what I have done so far, namely around the date in the <code>main()</code> function.</p>
<pre><code>import datetime
import sybase
account_list = []
def get_date(): # Date -1 day unless Monday then -3 days
d = datetime.date.today()
if d.weekday() == 0:
date = d - datetime.timedelta(days=3)
return date
else:
date = d - datetime.timedelta(days=1)
return date
def get_unique_accounts(date):
conn = sybase.Connection('')
c = conn.cursor()
c.execute("SELECT DISTINCT acct from accounts WHERE date = @date", {"@date": date})
result = c.fetchall()
for row in result:
account_list.append(row[0])
c.close()
conn.close()
def check_balance(date):
conn = sybase.Connection('')
c = conn.cursor()
c.execute("SELECT TOP 1 name,balance from balance WHERE date = @date", {"@date": date})
result = c.fetchone()
c.close()
conn.close()
return result
def main():
date = get_date()
get_unique_accounts(date) # This will be used for future functions
check_balance(date)
if __name__ == "__main__":
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T17:41:05.860",
"Id": "510426",
"Score": "0",
"body": "Sybase, though? Why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T17:43:06.937",
"Id": "510428",
"Score": "0",
"body": "I have no control over the current in place DB solution :("
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T17:58:57.293",
"Id": "510430",
"Score": "0",
"body": "That's deeply unfortunate. For your own learning purposes, if you have the opportunity I suggest trying out PostgreSQL instead of a museum piece."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T17:59:35.153",
"Id": "510431",
"Score": "0",
"body": "You've tagged this as both Python 2 and 3. What are the constraints? Does the `sybase` package work with 3?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T18:00:35.887",
"Id": "510432",
"Score": "0",
"body": "I will do for sure, as I've used MySQL and variants when I did PHP coding. But as for what I've posted above is there a more 'pythonic' method? Or have I done all I can so far correctly. We have a modified sybase module that we can import for both 2 and 3."
}
] |
[
{
"body": "<p>I will focus on the <code>get_date()</code> method. First of all, what sort of date is it? Currently the name makes me think it will get the current date, but it's sort of a banking date? Something along the lines of <code>get_last_banking_day()</code> would be more descriptive?</p>\n<p>You can move the return to the end of the function as that is the same in both blocks of the if/else:</p>\n<pre><code>def get_last_banking_day(): # Date -1 day unless Monday then -3 days\n d = datetime.date.today()\n\n if d.weekday() == 0:\n date = d - datetime.timedelta(days=3)\n else:\n date = d - datetime.timedelta(days=1)\n \n return date\n</code></pre>\n<p>You could clean up the import and only import the 2 things needed from <code>datetime</code>, <code>date</code> and <code>timedelta</code>.:</p>\n<pre><code>from datetime import date, timedelta\n</code></pre>\n<p>The function would become:</p>\n<pre><code>def get_last_banking_day(): # Date -1 day unless Monday then -3 days\n d = date.today()\n\n if d.weekday() == 0:\n date = d - timedelta(days=3)\n else:\n date = d - timedelta(days=1)\n \n return date\n</code></pre>\n<p>Now we can look at variable names and do some cleanup, especially the <code>d</code> variable. Always try to avoid non-descriptive names:</p>\n<pre><code>def get_last_banking_day(): # Date -1 day unless Monday then -3 days\n today = date.today()\n\n if today.weekday() == 0:\n last_banking_day = today - timedelta(days=3)\n else:\n last_banking_day = today - timedelta(days=1)\n \n return last_banking_day\n</code></pre>\n<p>As the <code>today - timedelta(days=1)</code> is the default we use it as such and set the value to this and only use an if-statement to set the exception:</p>\n<pre><code>def get_last_banking_day(): # Date -1 day unless Monday then -3 days\n today = date.today()\n last_banking_day = today - timedelta(days=1)\n\n if today.weekday() == 0:\n last_banking_day = today - timedelta(days=3)\n\n return last_banking_day\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T06:32:15.620",
"Id": "510604",
"Score": "0",
"body": "AH thanks Korfoo, the if loop where there is already a default is mistake I need to remove from my mindset when coding. Although just for reference you still have 'return date' rather than 'return 'last_banking_day'"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T07:03:24.747",
"Id": "510608",
"Score": "0",
"body": "Oops, I edited it to correct the return. Do note that I only looked at the `get_date` method as I do not have experience with `sybase` so I can not give tips about that :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T08:12:35.860",
"Id": "510616",
"Score": "0",
"body": "Appreciate it, I do not think there are improvements that could be made elsewhere in what has been posted."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T09:14:18.397",
"Id": "258914",
"ParentId": "258885",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "258914",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T17:31:04.640",
"Id": "258885",
"Score": "2",
"Tags": [
"python"
],
"Title": "Bank database program"
}
|
258885
|
<h1>Enumerating all fixed-length paths from a vertex in a graph</h1>
<h2>1. Graph-related classes</h2>
<p>Base implementations of the relevant classes in my graph library. I'm using C#9 in a .NET 5 project. I opted to use <code>struct</code>s for my <code>Vertex</code> and <code>Edge</code> types to disallow <code>null</code>, which simplifies the equality and comparison implementations. I've also chosen to keep all collections as generic as possible using <code>IEnumerable<T></code> and I've also tried to use LINQ where I could because it's convenient.</p>
<h3>1.1. <code>Graph.cs</code></h3>
<p>A simple directed graph with some basic functionalities.</p>
<pre class="lang-csharp prettyprint-override"><code>public class DirectedGraph<T, U>
where T : IComparable<T>, IEquatable<T>
where U : IComparable<U>, IEquatable<U>
{
public LinkedList<Vertex<T>> Vertices { get; set; } = new();
public LinkedList<Edge<T, U>> Edges { get; set; } = new();
public virtual void Add(T state)
=> Vertices.AddLast(new Vertex<T>(state));
public virtual void SetEdge(Vertex<T> from, Vertex<T> to, U weight)
{
if (Vertices.Contains(from) && Vertices.Contains(to))
{
Edges.AddLast(new Edge<T, U>(from, to, weight));
}
}
public virtual IEnumerable<Edge<T, U>> GetEdgesFrom(Vertex<T> from)
=> Edges.Where(x => x.From.Equals(from));
public virtual IEnumerable<Edge<T, U>> GetEdgesTo(Vertex<T> to)
=> Edges.Where(x => x.To.Equals(to));
// Method to be reviewed
public IEnumerable<IEnumerable<Edge<T, U>>> GetPathsWithLengthFrom(int length, Vertex<T> vertex)
{
// Using breadth-first search
if (length == 1)
{
// This seems like a reasonable base case
return GetEdgesFrom(vertex).Select(x => Enumerable.Empty<Edge<T, U>>().Append(x));
}
else if (length > 1)
{
var pathsSoFar = GetPathsWithLengthFrom(length - 1, vertex);
var newPaths = Enumerable.Empty<IEnumerable<Edge<T, U>>>();
foreach (var path in pathsSoFar)
{
// Better way to duplicate paths or other approach altogether?
var pathEnd = path.Last().To;
var nextPieces = GetEdgesFrom(pathEnd);
foreach (var nextPiece in nextPieces)
{
newPaths = newPaths.Append(path.Append(nextPiece));
}
}
return newPaths;
}
throw new ArgumentOutOfRangeException(nameof(length), "Path length must be greater than or equal to 1.");
}
}
</code></pre>
<h3>1.2. <code>Vertex.cs</code></h3>
<p>Vertex class with basic interface implementations.</p>
<pre class="lang-csharp prettyprint-override"><code>public struct Vertex<T> :
IComparable<Vertex<T>>,
IEquatable<Vertex<T>>,
IComparable<T>,
IEquatable<T>
where T :
IComparable<T>,
IEquatable<T>
{
public Vertex(T state)
=> State = state;
public T State { get; set; }
#region Interface implementations
public int CompareTo(Vertex<T> other)
=> State.CompareTo(other.State);
public int CompareTo(T other)
=> State.CompareTo(other);
public bool Equals(Vertex<T> other)
=> CompareTo(other) == 0;
public bool Equals(T other)
=> CompareTo(other) == 0;
public override int GetHashCode()
=> State.GetHashCode();
#endregion
}
</code></pre>
<h3>1.3. <code>Edge.cs</code></h3>
<pre class="lang-csharp prettyprint-override"><code>public struct Edge<T, U>
where T : IComparable<T>, IEquatable<T>
where U : IComparable<U>, IEquatable<U>
{
public Edge(Vertex<T> from, Vertex<T> to, U weight)
=> (From, To, Weight) = (from, to, weight);
public Vertex<T> From { get; set; }
public Vertex<T> To { get; set; }
public U Weight { get; set; }
}
</code></pre>
<h2>2. Main program and benchmarks</h2>
<h3>2.1. Main program</h3>
<pre class="lang-csharp prettyprint-override"><code>static void Main()
{
// Set the initial graph
var vertices = 20;
var graph = new DirectedGraph<int, int>();
var defaultWeight = 1;
graph.AddMany(Enumerable.Range(1, vertices));
foreach (var v1 in graph.Vertices)
{
foreach (var v2 in graph.Vertices)
{
if (v1 != v2)
{
graph.SetEdge(v1, v2, defaultWeight);
}
}
}
// Timing the method
var sw = new Stopwatch();
for (int i = 1; i < 6; i++)
{
var firstVertex = graph.Vertices.First();
var pathLength = i;
sw.Start();
var pathsFromVertex = graph.GetPathsWithLengthFrom(pathLength, firstVertex);
sw.Stop();
var pathsList = pathsFromVertex
.Select(x => string.Join(", ", x))
.ToList();
var pathsListCount = pathsList.Count;
Console.WriteLine($"It took {sw.ElapsedMilliseconds} ms to find all {pathsListCount} paths of length {pathLength} in a connected graph with {vertices} vertices.");
}
}
</code></pre>
<h3>2.2. Results</h3>
<p>The method as is will look for all the paths, and for a connected graph where each vertex is connected to every other vertex but not to itself, it will return <code>(|V| - 1)^L</code> paths where <code>|V|</code> is the number of vertices and <code>L</code> is the desired length of the path.</p>
<p>This makes sense because every vertex is connected to every other vertex in the graph, which means there are <code>|V| - 1</code> edges from each vertex. By the <a href="https://en.wikipedia.org/wiki/Rule_of_product" rel="nofollow noreferrer">multiplication principle</a> you then arrive at the total number of paths <code>(|V| - 1)^L</code>.</p>
With 20 vertices, path lengths from 1 to 4 included
<blockquote>
<p>It took 3 ms to find all 19 paths of length 1 in a connected graph with 20 vertices.</p>
<p>It took 6 ms to find all 361 paths of length 2 in a connected graph with 20 vertices.</p>
<p>It took 15 ms to find all 6859 paths of length 3 in a connected graph with 20 vertices.</p>
<p>It took 223 ms to find all 130321 paths of length 4 in a connected graph with 20 vertices.</p>
</blockquote>
With 30 vertices, path lengths from 1 to 4 included
<blockquote>
<p>It took 4 ms to find all 29 paths of length 1 in a connected graph with 30 vertices.</p>
<p>It took 8 ms to find all 841 paths of length 2 in a connected graph with 30 vertices.</p>
<p>It took 55 ms to find all 24389 paths of length 3 in a connected graph with 30 vertices.</p>
<p>It took 1403 ms to find all 707281 paths of length 4 in a connected graph with 30 vertices.</p>
</blockquote>
With 40 vertices, path lengths from 1 to 4 included
<blockquote>
<p>It took 4 ms to find all 39 paths of length 1 in a connected graph with 40 vertices.</p>
<p>It took 11 ms to find all 1521 paths of length 2 in a connected graph with 40 vertices.</p>
<p>It took 135 ms to find all 59319 paths of length 3 in a connected graph with 40 vertices.</p>
<p>It took 4839 ms to find all 2313441 paths of length 4 in a connected graph with 40 vertices.</p>
</blockquote>
<h2>3. Goal of the graph library</h2>
<p>Initially, I wanted to use graphs to enumerate all possible ways to choose <code>k</code> elements from a set of <code>n</code> total elements, but I discovered <a href="https://cs.stackexchange.com/questions/138207/find-all-the-ways-to-choose-k-objects-from-a-list-of-n-objects-using-a-grap">better ways</a> to achieve that goal.</p>
<p>That being said, I created a graph with customizable states and weights for a poker calculator. The customizable weight could for example keep track of which cards were drawn or which hands are likely to arise given the current game state and the remaining cards in the deck.</p>
<p>Finally, writing a small graph theory library from scratch helps me learn more about algorithms and data structures.</p>
<h2>4. Why C# and not a faster language like C/C++?</h2>
<p>I'm just more familiar with C# and I like LINQ, C# also has a ton of abstractions that I would likely have to import or write myself in C/C++ (the more I have to write myself, the more likely I'm going to make mistakes). Not to mention memory management with pointers and references.</p>
<p>But if C# turns out to be too slow, even after optimisations, I might switch over to C/C++ anyway.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T19:27:20.700",
"Id": "510443",
"Score": "1",
"body": "C# isn't slow, it's a myth, the code you can write may be slow. I say more, it's possible to write code that faster in some cases than C++ because CLR have shiny GC, C++ require memory management instead (to keep performance that GC allows out-of-the-box, in ++ developer must implement a lot of well-optimized memory-management code). Btw, as the code is \"abridged\", it's not ready for review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T20:45:41.077",
"Id": "510447",
"Score": "1",
"body": "@aepot I understand that C# isn't remotely slow or necessarily always slower than C++, but admittedly for these data manipulations C++ more often than not takes the cake, does it not? Also, my abridged code simply does not include the implementations of `<`, `>`, `<=`, `=>`,`==` and `!=` but those operators aren't used anywhere in the method in question, so I don't see why that would pose a problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T20:51:36.430",
"Id": "510448",
"Score": "1",
"body": "If \"abridged\" doesn't affect the code, you may remove that word from the post. Now it has misleading meaning. Also some test case to run the code would be useful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T22:08:37.203",
"Id": "510453",
"Score": "1",
"body": "@aepot I've added some benchmarking details, I hope those can serve as test cases as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T00:26:26.863",
"Id": "510467",
"Score": "0",
"body": "You could improve the performance by at least an order of magnitude by representing the graph using an adjacency matrix rather than as vertex objects."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T18:06:02.520",
"Id": "258888",
"Score": "0",
"Tags": [
"c#",
"algorithm",
"object-oriented",
"recursion",
"graph"
],
"Title": "Enumerating all fixed-length paths from a vertex in a graph"
}
|
258888
|
<p>I'm writing a code where a class member, if != -1, set its own position at array. If the value is == -1, the next free index (whose range is 0 too array's length) is used. In this review, I'm more interested in the algorithm, making it faster, accurate and readable than anything else. despite I'm using C#, I'd like to keep it simple, C-like and avoid C#'s stuff like Linq, etc. If there's a readable and faster way to do that without the <code>valueSet</code> flag, would be nice. I just added it because after the <code>swap()</code> call, the swapped elements would be visited twice, with value != -1, making it to be set again, wrongly. Let me know if there's anything that's not clear. Below the code with some functions that acts like unittests. Complete different ways to do that are also very welcome.</p>
<p><strong>UPDATE</strong>:</p>
<ol>
<li>the index range is <code>0</code> to <code>arr.Length</code>. Anything outside this bounds is wrong.</li>
<li>The indexes are linear and sequential, so for each <code>i</code> in <code>arr</code>, this must be true <code>arr[x] + 1 == arr[x + 1]</code></li>
<li><code>null</code> storage isn't allowed</li>
</ol>
<p>;</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace sort
{
class Program
{
static void Main(string[] args)
{
t1();
t2();
t3();
t4();
}
//test case 1
static void t1()
{
var arr = new List<A>();
arr.Add(new A(-1, "a"));
arr.Add(new A(-1, "b"));
arr.Add(new A(0, "c"));
arr.Add(new A(-1, "d"));
var sortedArr = doSort(arr.ToArray());
Debug.Assert(isSorted(sortedArr));
}
// test case 2
static void t2()
{
var arr = new List<A>();
arr.Add(new A(-1, "a"));
arr.Add(new A(-1, "b"));
arr.Add(new A(-1, "c"));
arr.Add(new A(-1, "d"));
var sortedArr = doSort(arr.ToArray());
Debug.Assert(isSorted(sortedArr));
}
// test case 3
static void t3()
{
var arr = new List<A>();
arr.Add(new A(0, "a"));
arr.Add(new A(1, "b"));
arr.Add(new A(2, "c"));
arr.Add(new A(3, "d"));
var sortedArr = doSort(arr.ToArray());
Debug.Assert(isSorted(arr.ToArray()));
}
static void t4()
{
var arr = new List<A>();
arr.Add(new A(-1, "a"));
arr.Add(new A(1, "b"));
arr.Add(new A(0, "c"));
arr.Add(new A(-1, "d"));
var sortedArr = doSort(arr.ToArray());
Debug.Assert(isSorted(sortedArr));
}
// not meant to be very fast just to be used in the "unittest"
static bool isSorted(A[] arr)
{
if(arr.Length == 0)
{
return false;
}
// this make sure the values is sequential, starting with 0
// and the last value must be same value as array's length
if(arr[0].index != 0 || arr[arr.Length - 1].index != arr.Length - 1)
{
return false;
}
// we have checked already if the first and last values
// are sequential, no need to recheck here so
// we loop from 1 to arr.length - 1
for (int i = 1; i < arr.Length - 1; i++)
{
if(i + 1 > arr.Length &&
arr[i].index + 1 != arr[i + 1].index)
{
return false;
}
}
return true;
}
static A[] doSort(A[] arr)
{
for(int i = 0; i < arr.Length; i++)
{
initValue(arr, i);
}
return arr;
}
static void initValue(A[] arr, int i)
{
var e = arr[i];
if(e.valueSet)
{
return; /* nothing to do, value initialized already */
}
// initialize to current index
if(e.index == -1)
{
e.index = i;
}
// an explicit index was set, the value at i index
// must be set to the value at e.index index
else if(e.index != i)
{
swap(arr, i, e.index);
// after the swap, that element may be left
// unitialized. Do initialize now.
initValue(arr, i);
}
e.valueSet = true;
}
static void swap(A[] arr, int i, int j)
{
// swap items
var t = arr[i];
arr[i] = arr[j];
arr[j] = t;
// update indexes
arr[i].index = i;
arr[j].index = j;
}
}
class A
{
public A(int i, string s)
{
index = i;
value = s;
}
public override string ToString()
{
return string.Format("index = {0}, value = {1}", index, value);
}
public int index { get; set; }
public string value { get; set; }
public bool valueSet { get; set; }
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T20:08:17.077",
"Id": "510445",
"Score": "0",
"body": "Is `arr.Add(new A(0, \"aaa\")); arr.Add(new A(0, \"bbb\"));` a wrong input? How sorting method must behave with such input? `arr.Add(null)`? `arr.Add(new A(-456, \"ccc\"))`? `arr.Add(new A(int.MaxValue, \"ddd\"))`? I'm not suggesting to fix it now but asking, what's the idea for these test cases?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T21:26:04.247",
"Id": "510450",
"Score": "0",
"body": "Doesn't work for `{ new A(2, \"a\"), new A(-1, \"b\"), new A(3, \"c\"), new A(-1, \"d\") }`. Output `cbad` expected `bdac` or `dbac`. It sorts properly only indexes, not data. Or is it expected output? Also a tip: `string.Format(\"index = %d, value = %s\", index, value);` won't work, do `string.Format(\"index = {0}, value = {1}\", index, value);` instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T06:52:45.673",
"Id": "510483",
"Score": "1",
"body": "@Jack If you would like to improve on legibility then the bear minimum would be to use better naming than `A`, `e`, `arr`, `t`, etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T10:05:54.450",
"Id": "510490",
"Score": "1",
"body": "Welcome to Code Review@SE. Please heed [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask), starting with providing more context: where do the indices specified stem from, how is the result going to be used?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T14:53:03.867",
"Id": "510641",
"Score": "1",
"body": "@aepot Duplicate cases can be ignored. At time `index` is set the value it can have is from `0` to `arr.Length`. `arr.Add(null)` isn't allowed, we can throw an exception. `-456` and `int.MaxValue` are out of the 0 .. arr.Length length I mentioned so outOfRangeException would be throw"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T15:21:24.270",
"Id": "510646",
"Score": "0",
"body": "@aepot you're right, the data isn't sorted properly. I haven't see this case. This is a bug in the implementation, when the index is `-1` it gets a new index must its data mustn't change. I'll fix the formatting error, thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T15:23:12.853",
"Id": "510647",
"Score": "0",
"body": "@PeterCsala those are just example, like we use variables named `foo`, `baa`, etc but my focus here is improving the algorithm"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T15:28:53.570",
"Id": "510648",
"Score": "0",
"body": "Ok, looking forward for working as intended solution. Tag me when you'll done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T17:13:10.793",
"Id": "510660",
"Score": "2",
"body": "Welcome to Code Review! After getting an answer you are [not allowed to change your code anymore](https://codereview.stackexchange.com/help/someone-answers). This is to ensure that answers do not get invalidated and have to hit a moving target. Refer to [this post](https://codereview.meta.stackexchange.com/a/1765/120114) for more information"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T23:14:16.523",
"Id": "513684",
"Score": "0",
"body": "This is an impressively over-complex bubble sort. [Read this](https://www.programiz.com/dsa/bubble-sort). Optimizing is also shown which, like your code, stops as soon as no swap is done."
}
] |
[
{
"body": "<h3>Review</h3>\n<ul>\n<li><p>In your test cases, why not use array directly (<code>new A[] { new A(-1, "a"), new A(-1, "b"), new A(0, "c"),... };</code>) instead of <code>List<A>.ToArray()</code>?</p>\n</li>\n<li><p>In the part of <code>isSorted</code> method, do you expect that the return value is <code>false</code> if <code>(arr.Length == 0)</code>? Or <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.argumentexception?view=net-5.0\" rel=\"nofollow noreferrer\">ArgumentException Class</a> can be used here.</p>\n</li>\n<li><p>In <code>class A</code>, maybe <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=net-5.0\" rel=\"nofollow noreferrer\">Dictionary<TKey,TValue> Class</a> can be used here. Make TKey is index and <code>TValue</code> is string .</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T23:35:34.917",
"Id": "510462",
"Score": "0",
"body": "Keys are immutable in `Dictionary`. The code is modifying indexes."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T22:56:09.357",
"Id": "258900",
"ParentId": "258890",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T19:18:52.910",
"Id": "258890",
"Score": "0",
"Tags": [
"c#",
"array",
"sorting"
],
"Title": "Array member set its own index in the array"
}
|
258890
|
<p>So in my free time, I made a discord bot to play around with and learn a bit of python. I'm mainly a java developer. The bot has a few commands that allow it to find and output recipe for cocktails and a few other things revolving around cocktails.</p>
<p>In the background, there are 2 JSON files. My bot mainly reads and filters these JSON files and returns what it finds. In java, I am used to streams which I don't have in python so I just had to make do with what I know but I get a feeling that some things can definitely be done cleaner/shorter/better/ and I'm not sure everything follows python standards so I would be grateful for any feedback.</p>
<hr />
<pre class="lang-css prettyprint-override"><code> [ !! cocktails can be exchanged with -c, ingredients with -i !! ]
[ <KW> find cocktails <search criteria1> <search criteria2> ... Find cocktail. ]
[ <KW> find ingredients <search criteria1> <search criteria2> ... Find ingredient. ]
[ <KW> cocktails List all cocktails. ]
[ <KW> ingredients List all ingredients. ]
[ <KW> categories List all cocktail categories. ]
[ <KW> list <category> List all cocktails by category ]
[ <KW> count cocktails How many cocktails? ]
[ <KW> count ingredients How many ingredients? ]
[ <KW> with <ingredient> <ingredient2> ... Cocktails with ingredient. ]
[ <KW> recipe <cocktail> How to make a cocktail. ]
</code></pre>
<p>The possible commands are as above <KW> is the trigger word for the bot that a different component handles. bartender.py receives the content with this cut off.</p>
<hr />
<p><strong>bartender.py</strong></p>
<pre class="lang-py prettyprint-override"><code>import json
class Bartender:
with open("recipes.json") as recipes_file:
recipes = json.load(recipes_file)
with open("ingredients.json") as ingredients_file:
ingredients = json.load(ingredients_file)
default = "This command does not exist or you mistyped something"
error = "There was a problem with processing the command"
def handle(self, message):
command_prefix = message.content.strip().lower()
answer = self.default
if self.starts_with_ingredients_prefix(command_prefix):
answer = self.get_all_ingredients()
elif self.starts_with_cocktails_prefix(command_prefix):
answer = self.get_all_cocktails()
elif command_prefix == "categories":
answer = self.get_all_categories()
elif command_prefix.startswith("count"):
answer = self.get_count(command_prefix.removeprefix("count").strip())
elif command_prefix.startswith("recipe"):
answer = self.get_recipe(command_prefix.removeprefix("recipe").strip())
elif command_prefix.startswith("list"):
answer = self.get_cocktails_by_category(command_prefix.removeprefix("list").strip())
elif command_prefix.startswith("find"):
answer = self.find(command_prefix.removeprefix("find").strip())
elif command_prefix.startswith("with"):
answer = self.get_cocktails_with(command_prefix.removeprefix("with").strip())
return answer
def get_all_ingredients(self):
"""Returns a string containing all of the ingredients the bot knows."""
answer = ""
for key, value in self.ingredients.items():
answer += f"{key} ({value.get('abv')}%)\n"
return answer
def get_all_cocktails(self):
"""Returns a string containing the names of all of the cocktails the bot knows."""
answer = ""
for cocktail in self.recipes:
answer += f"{cocktail.get('name')}\n"
return answer
def get_all_categories(self):
"""Returns a string containing all the cocktail categories the bot knows."""
answer = ""
categories_list = []
for cocktail in self.recipes:
categories_list.append(cocktail.get("category"))
# Remove duplicates
categories_list = list(set(categories_list))
categories_list.sort(key=str)
for category in categories_list:
answer += f"{category}\n"
return answer
def get_count(self, param):
"""Returns the amount of ingredients or cocktails the bot knows."""
answer = self.error
if self.starts_with_ingredients_prefix(param):
answer = len(self.ingredients)
elif self.starts_with_cocktails_prefix(param):
answer = len(self.recipes)
return answer
def get_recipe(self, param):
"""Returns the full recipe for the passed cocktail name."""
answer = f"There is no recipe for a cocktail called {param}. To see all cocktails with a recipe " \
f"type '$bt cocktails'"
for cocktail in self.recipes:
if param == cocktail.get("name").lower():
formatted_ingredients = self.get_formatted_ingredients(cocktail.get("ingredients"))
garnish = self.get_garnisch(cocktail)
return f"__**{cocktail.get('name')}**__\n" \
f"**Ingriedients:**\n" \
f"{formatted_ingredients}" \
f"{garnish}" \
f"**Preparation:**\n" \
f"{cocktail.get('preparation')} \n"
return answer
def get_formatted_ingredients(self, ingredients):
"""Returns a string of ingredients formatted as list for the cocktails including the special ones if it has
any."""
formatted_ingredients = ""
special_ingredients = ""
for ingredient in ingredients:
if ingredient.get("special") is not None:
special_ingredients += f" - {ingredient.get('special')}\n"
else:
formatted_ingredients += f" - {ingredient.get('amount')} {ingredient.get('unit')} {ingredient.get('ingredient')} "
if ingredient.get("label") is not None:
f"({ingredient.get('label')})"
formatted_ingredients += "\n"
return formatted_ingredients + special_ingredients
def get_garnisch(self, cocktail):
"""Returns the garnish for the cocktail if it has one."""
if cocktail.get("garnish") is not None:
return f"**Garnish:**\n" \
f" - {cocktail.get('garnish')} \n"
else:
return ""
def get_cocktails_by_category(self, category):
"""Returns all cocktails in the given category."""
answer = ""
for cocktail in self.recipes:
if category == str(cocktail.get("category")).lower():
answer += f"{cocktail.get('name')}\n"
return answer if len(answer) > 0 else f"There is no category called {category} or it contains no cocktails"
def starts_with_cocktails_prefix(self, param):
"""Returns true if passed string starts with the cocktails prefix (-c or cocktails)."""
return param.startswith("-c") or param.startswith("cocktails")
def remove_cocktails_prefix(self, param):
"""Returns a string with the cocktails prefix (-c or cocktails) removed. If the string does not start with
the cocktails prefix it will return the original string."""
if param.startswith("-c"):
param = param.removeprefix("-c")
elif param.startswith("cocktails"):
param = param.removeprefix("cocktails")
return param
def starts_with_ingredients_prefix(self, param):
"""Returns true if passed string starts with the ingredient prefix (-i or ingredients)."""
return param.startswith("-i") or param.startswith("ingredients")
def remove_ingredients_prefix(self, param):
"""Returns a string with the ingredient prefix (-i or ingredients) removed. If the string does not start with
the ingredients prefix it will return the original string."""
if param.startswith("-i"):
param = param.removeprefix("-i")
elif param.startswith("ingredients"):
param = param.removeprefix("ingredients")
return param
def find(self, param):
"""Returns all ingredients or cocktails containing the criteria in the parameter separated by commas."""
answer = ""
if self.starts_with_cocktails_prefix(param):
param = self.remove_cocktails_prefix(param)
for criteria in param.strip().split():
answer += f"**Criteria: {criteria}**\n"
answer += self.get_cocktails_containing(criteria)
elif self.starts_with_ingredients_prefix(param):
param = self.remove_ingredients_prefix(param)
for criteria in param.strip().split():
answer += f"**Criteria: {criteria}**\n"
answer += self.get_ingredients_containing(criteria)
return answer if len(answer) > 0 else "Nothing was found matching your criteria"
def get_cocktails_containing(self, criteria):
"""Returns all cocktails containing the criteria in its name."""
answer = ""
for cocktail in self.recipes:
if criteria in str(cocktail.get("name")).lower():
answer += f"{cocktail.get('name')}\n"
return answer if len(answer) > 0 else "Nothing was found matching your criteria"
def get_ingredients_containing(self, criteria):
"""Returns all ingredients containing the criteria in its name."""
answer = ""
for ingredient in self.ingredients.keys():
if criteria in ingredient.lower():
answer += f"{ingredient}\n"
return answer if len(answer) > 0 else "Nothing was found matching your criteria"
def get_cocktails_with(self, param):
"""Returns all cocktails containing the searched for ingredients in the parameter separated by commas."""
answer = ""
for ingredient in param.strip().split(","):
for cocktail in self.recipes:
cocktail_ingredients = cocktail.get("ingredients")
answer += self.does_cocktail_contain(cocktail, cocktail_ingredients, ingredient.strip())
return answer if len(answer) > 0 else "Nothing was found matching your criteria"
def does_cocktail_contain(self, cocktail, cocktail_ingredients, ingredient):
"""Returns the name of the cocktail if the cocktail contains the searched for ingredient."""
for cocktail_ingredient in cocktail_ingredients:
if cocktail_ingredient.get("ingredient") is not None and ingredient in cocktail_ingredient.get(
"ingredient").lower():
return f"{cocktail.get('name')}\n"
return ""
</code></pre>
<hr />
<p><strong>recipes.json</strong></p>
<pre class="lang-json prettyprint-override"><code>[
{ "name": "Vesper",
"glass": "martini",
"category": "Before Dinner Cocktail",
"ingredients": [
{ "unit": "cl",
"amount": 6,
"ingredient": "Gin" },
{ "unit": "cl",
"amount": 1.5,
"ingredient": "Vodka" },
{ "unit": "cl",
"amount": 0.75,
"ingredient": "Lillet Blonde" },
{ "special": "3 dashes Strawberry syrup" }
],
"garnish": "Lemon twist",
"preparation": "Shake and strain into a chilled cocktail glass."
},
...
]
</code></pre>
<p>Not all cocktails have the glass attribute and a cocktail can have 0 to n "special" ingredients.</p>
<hr />
<p><strong>ingredients.json</strong></p>
<pre class="lang-json prettyprint-override"><code>{
"Absinthe": {
"abv": 40,
"taste": null
},
"Aperol": {
"abv": 11,
"taste": "bitter"
},
...
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T13:36:32.310",
"Id": "510508",
"Score": "1",
"body": "_\"I am used to streams which I don't have in python\"_ -- when you learn a bit more of python, you'll be delighted to see that Javas Streams are just a kludge to achieve a subset of the things you can achieve with pythons list/set/dict comprehensions and generators. In Python, you just don't have a buzzword for it, because all of that is already baked into the basic language instead of being an \"add-on\" via the standard library. These functional concepts can be taken even further, but you'll need a pure functional language like Haskell for that."
}
] |
[
{
"body": "<p>You could replace some for loops with list comprehensions.\nI think list comprehensions are generally preferred and often faster.\nI've also:</p>\n<ul>\n<li>added a default value to the get command in case your JSON is malformed or missing the ABV for some reason, and</li>\n<li>replaced the <code>\\n</code> on the end of each line with the join method.</li>\n</ul>\n\n<pre><code>def get_all_ingredients(self):\n """Returns a string containing all of the ingredients the bot knows."""\n answer = ""\n for key, value in self.ingredients.items():\n answer += f"{key} ({value.get('abv')}%)\\n"\n return answer\n\ndef get_all_ingredients(self):\n answers = [f'{key} ({value.get("drink_info", "-")}%)' for key, value in self.ingredients.items()]\n return '\\n'.join(answers)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T23:16:00.330",
"Id": "510461",
"Score": "1",
"body": "`'\\n'.join(answers)` is different than OP's implementation, since it does not include a trailing newline. Might or might not be an issue depending on the use case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T10:24:02.033",
"Id": "510493",
"Score": "0",
"body": "Welcome to CodeReview@SE. It's entirely OK for an answer to raise but one valid point. (In fact, I think the tendency towards comprehensive reviews unfavorably increases the threshold to answer.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T10:36:13.617",
"Id": "510494",
"Score": "0",
"body": "(Then again, this adds little to Reinderien's take on `get_all_ingredients()`, while ***dropping*** the docstring. And it seems to repeat code from the question, which is unusual.)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T20:36:23.277",
"Id": "258894",
"ParentId": "258892",
"Score": "1"
}
},
{
"body": "<p><strong>get_all_ingredients</strong></p>\n<p><a href=\"https://www.programiz.com/python-programming/list-comprehension\" rel=\"nofollow noreferrer\">List comprehensions</a> are <em>very pythonic</em> and often times faster (especially for operations, that aren't computationally expensive), so instead of</p>\n<pre><code>answer = ""\nfor key, value in self.ingredients.items():\n answer += f"{key} ({value.get('abv')}%)\\n"\n</code></pre>\n<p>you should use</p>\n<pre><code>answer = "".join(f"{key} ({value.get('abv')}%)\\n" for key, value in self.ingredients.items())\nreturn answer\n</code></pre>\n<p>or as a one-liner</p>\n<pre><code>return "".join(f"{key} ({value.get('abv')}%)\\n" for key, value in self.ingredients.items())\n</code></pre>\n<p><code>str.join(...)</code> joins each element of an iterable by a string separator (the string on which it is called) and returns the concatenated string.</p>\n<p>What we're using here is actually not a list comprehension, but a generator expression. If you're interested you can read more about <a href=\"https://dbader.org/blog/python-generator-expressions\" rel=\"nofollow noreferrer\">Generator Expressions vs List Comprehensions</a>.</p>\n<p>The same is also applicable to <code>get_all_cocktails</code>.</p>\n<hr />\n<p><strong>get_all_categories</strong></p>\n<p>As seen before we can replace</p>\n<pre><code>categories_list = []\nfor cocktail in self.recipes:\n categories_list.append(cocktail.get("category"))\n</code></pre>\n<p>by a list comprehension. But since we actually want a sorted list of distinct values we can use a set comprehension or use <code>set()</code> and a generator expression.</p>\n<pre><code>{cocktail.get("category") for cocktail in self.recipes}\n# or\nset(cocktail.get("category") for cocktail in self.recipes)\n</code></pre>\n<p>Now we wrap this with <code>sorted()</code> which returns a sorted list and we get <code>categories_list</code> concisely. Providing <code>str</code> as the key function should not be necessary since the values are already strings.</p>\n<pre><code>categories_list = sorted(set(cocktail.get("category") for cocktail in self.recipes))\n</code></pre>\n<p>Using <code>str.join()</code> again brings the entire method down to 2 lines:</p>\n<pre><code>categories_list = sorted(set(cocktail.get("category") for cocktail in self.recipes))\nreturn "".join(f"{category}\\n" for category in categories_list)\n</code></pre>\n<p>Note that we don't need to assign an empty string as a default value since <code>"".join(...)</code> will return an empty string if there are no elements in the iterable.</p>\n<hr />\n<p><strong>get_formatted_ingredients</strong></p>\n<p>You will sometimes be able to replace</p>\n<pre><code>if ingredient.get("special") is not None:\n</code></pre>\n<p>by</p>\n<pre><code>if ingredient.get("special"):\n</code></pre>\n<p>This however depends on the use case, since the expressions are not equivalent. The second one will fail for all falsey values, not just <code>None</code> (e.g. an empty string in this case, which you also might want to skip). If you're interested, you can read more about <a href=\"https://www.freecodecamp.org/news/truthy-and-falsy-values-in-python/\" rel=\"nofollow noreferrer\">Truthy and Falsy Values in Python</a>.</p>\n<p>Using the <a href=\"https://realpython.com/lessons/assignment-expressions/\" rel=\"nofollow noreferrer\">walrus operator</a> we can make this more concise, and remove the redundant <code>get</code>:</p>\n<pre><code>if special_ingredient := ingredient.get("special") is not None:\n special_ingredients += f" - {special_ingredient}\\n"\n</code></pre>\n<p>I don't think the following code does anything at all, since it doesn't do anything with the string:</p>\n<pre><code>if ingredient.get("label") is not None:\n f"({ingredient.get('label')})"\n</code></pre>\n<hr />\n<p>These are just some things I noticed. You will find these patterns in different places throughout your code. This is of course not a complete list of possible improvements, just the ones I found on my first read through your code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T22:51:12.033",
"Id": "510455",
"Score": "2",
"body": "_list comprehensions are [...] generally more efficient_ - That depends on a lot of factors, and won't always be the case; but here efficiency is not really an issue"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T22:52:35.580",
"Id": "510456",
"Score": "0",
"body": "You may also want to consider using a set literal `{}` and not a named `set()` constructor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T22:54:27.083",
"Id": "510457",
"Score": "0",
"body": "You claim that `if get() is not None` is equivalent to `if get()`, but this is not so. For any falsey-evaluated expressions, it's entirely possible for `if get()` to be false and `if get() is not None` to be true; the trivial case is an empty string."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T22:55:26.440",
"Id": "510458",
"Score": "0",
"body": "The above also applies to your equivalence claim for `return answer if len(answer) > 0`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T22:56:24.010",
"Id": "510459",
"Score": "1",
"body": "Your recommendation to try `.removeprefix(\"-c\").removeprefix(\"cocktails\")` is buggy. What if a user passes `-ccocktails`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T23:11:09.287",
"Id": "510460",
"Score": "1",
"body": "Thanks for your comments, I removed or corrected the incorrect claims. The set literal was already included in my answer, but I often find the named constructor more readable, especially in conjunction with `sorted()` etc.. I haven't yet come across a use case where loops clearly outperform list comprehensions, I'd be interested in learning more about the performance differences between the two if you know of any resources."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T06:24:23.170",
"Id": "510481",
"Score": "1",
"body": "Thank you very much for the great feedback looks like I have a lot to do :D. Do you have any ideas on making the handle method better. I'm not a fan of the else if however, I started with a switcher but after a certain point, it wasn't possible anymore."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T11:48:39.883",
"Id": "510497",
"Score": "0",
"body": "@LuciferUchiha The next Python version 3.10 will introduce the `match` statement, which will definitely improve these kinds of situations. Here's a [good video](https://www.youtube.com/watch?v=-79HGfWmH_w) explaining the feature, if you're interested."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T12:29:45.020",
"Id": "510501",
"Score": "0",
"body": "Less lines of code != better code. Now I have to horizontally scroll when I read your the code in your answer. Much better to just put the comprehension on multiple lines."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T20:52:33.930",
"Id": "258895",
"ParentId": "258892",
"Score": "4"
}
},
{
"body": "<h2>Instance-ness</h2>\n<p>Your file reading is done in class static scope. It should be moved to class instance scope.</p>\n<h2>Type hints</h2>\n<p>Add some PEP484 type hints to your function signatures.</p>\n<h2>Type soundness and dictionary soup</h2>\n<p>Once you've read in your data from JSON, you should not leave it as dictionaries - make actual classes so that your data have stronger correctness guarantees and static analysis tools can actually say something about your code.</p>\n<p>Another benefit of this approach is that your new classes for recipes and ingredients can have methods dealing with data specific to that class.</p>\n<h2>Indexing</h2>\n<p>You haven't built up any index dictionaries for faster, simpler lookup based on search terms; you should.</p>\n<h2>Line continuation</h2>\n<p>For long string, prefer to put them in parenthesized expressions rather than adding backslashes.</p>\n<h2>Bug: label</h2>\n<p>This statement:</p>\n<pre><code>f"({ingredient.get('label')})"\n</code></pre>\n<p>does nothing, so you'll never see your label.</p>\n<h2>Spelling</h2>\n<p>garnisch -> garnish</p>\n<p>Ingriedients -> Ingredients</p>\n<h2>Documentation lies</h2>\n<pre><code> """Returns all ingredients or cocktails containing the criteria in the parameter separated by commas."""\n</code></pre>\n<p>is not, in fact, what's happening. Your <code>split()</code> splits on whitespace.</p>\n<h2>Statics</h2>\n<p>Any method that doesn't actually touch the <code>self</code> reference doesn't need to be an instance method and can benefit from being a static, or sometimes a classmethod if (in simple terms) it references other statics or the constructor. In reality <code>@classmethod</code>s can reference any attribute on the class object which is a touch more detail than I suspect you need right now.</p>\n<p>Benefits to proper use of static methods include easier testability due to fewer internal dependencies, and more accurate representation of "what's actually happening" to other developers reading your code.</p>\n<p>It's also worth mentioning (due to your comment) that public/private and instance/static are very different mechanisms. public/private, in other languages, controls visibility from the outside of the class, whereas instance/static controls whether the method is visible on an instance or on the class type itself. Python does not have a strong concept of public/private at all, aside from the leading-underscore-implying-private and double-underscore-implying-name-mangling conventions; neither is called for here I think.</p>\n<h2>Suggested</h2>\n<p>There are many ways to implement some of the above, particularly conversion to classes. Presented below is one way.</p>\n<pre><code>import json\nfrom collections import defaultdict\nfrom dataclasses import dataclass\nfrom itertools import chain\nfrom typing import Optional, Iterable, Tuple, Dict, Any, List\n\n\n@dataclass\nclass FakeMessage:\n content: str\n\n\n@dataclass\nclass Ingredient:\n name: str\n abv: float\n taste: Optional[str]\n\n @classmethod\n def from_json(cls, fname: str = 'ingredients.json') -> Iterable['Ingredient']:\n with open(fname) as ingredients_file:\n data = json.load(ingredients_file)\n\n for name, attributes in data.items():\n yield cls(name=name, **attributes)\n\n def __str__(self):\n return f'{self.name} ({self.abv}%)'\n\n\n@dataclass\nclass RecipeIngredient:\n unit: str\n amount: float\n ingredient: Ingredient\n label: Optional[str] = None\n\n @classmethod\n def from_dicts(\n cls,\n dicts: Iterable[Dict[str, Any]],\n all_ingredients: Dict[str, Ingredient],\n ) -> Iterable['RecipeIngredient']:\n for data in dicts:\n if 'special' not in data:\n name = data.pop('ingredient')\n yield cls(**data, ingredient=all_ingredients[name.lower()])\n\n def __str__(self):\n desc = f'{self.amount} {self.unit} {self.ingredient}'\n if self.label is not None:\n desc += f' {self.label}'\n return desc\n\n\n@dataclass\nclass Recipe:\n name: str\n glass: str\n category: str\n preparation: str\n ingredients: Tuple[RecipeIngredient, ...]\n special_ingredients: Tuple[str, ...]\n garnish: Optional[str] = None\n\n @classmethod\n def from_json(\n cls,\n all_ingredients: Dict[str, Ingredient],\n fname: str = 'recipes.json',\n ) -> Iterable['Recipe']:\n with open(fname) as recipes_file:\n data = json.load(recipes_file)\n\n for recipe in data:\n ingredient_data = recipe.pop('ingredients')\n specials = tuple(\n ingredient['special']\n for ingredient in ingredient_data\n if 'special' in ingredient\n )\n yield cls(\n **recipe,\n ingredients=tuple(\n RecipeIngredient.from_dicts(ingredient_data, all_ingredients)\n ),\n special_ingredients=specials,\n )\n\n @property\n def formatted_ingredients(self) -> str:\n """Returns a string of ingredients formatted as list for the cocktails including the special ones if it has\n any."""\n ingredients = chain(self.ingredients, self.special_ingredients)\n return '\\n'.join(\n f' - {ingredient}'\n for ingredient in ingredients\n )\n\n @property\n def as_markdown(self) -> str:\n desc = (\n f"__**{self.name}**__\\n"\n f"**Ingredients:**\\n"\n f"{self.formatted_ingredients}\\n"\n )\n\n if self.garnish is not None:\n desc += f' - {self.garnish}\\n'\n\n desc += (\n f"**Preparation:**\\n"\n f"{self.preparation}\\n"\n )\n return desc\n\n\nclass Bartender:\n ERROR = "There was a problem with processing the command"\n\n def __init__(self):\n self.ingredients: Dict[str, Ingredient] = {\n i.name.lower(): i for i in Ingredient.from_json()\n }\n self.recipes: Dict[str, Recipe] = {\n r.name.lower(): r for r in Recipe.from_json(self.ingredients)\n }\n\n self.categories: Dict[str, List[Recipe]] = defaultdict(list)\n for recipe in self.recipes.values():\n self.categories[recipe.category.lower()].append(recipe)\n\n self.by_ingredient: Dict[str, List[Recipe]] = defaultdict(list)\n for recipe in self.recipes.values():\n for ingredient in recipe.ingredients:\n self.by_ingredient[ingredient.ingredient.name.lower()].append(recipe)\n\n def handle(self, message: FakeMessage) -> str:\n command_prefix = message.content.strip().lower()\n\n if self.starts_with_ingredients_prefix(command_prefix):\n return self.get_all_ingredients()\n if self.starts_with_cocktails_prefix(command_prefix):\n return self.get_all_cocktails()\n if command_prefix == "categories":\n return self.get_all_categories()\n if command_prefix.startswith("count"):\n return self.get_count(command_prefix.removeprefix("count").strip())\n if command_prefix.startswith("recipe"):\n return self.get_recipe(command_prefix.removeprefix("recipe").strip())\n if command_prefix.startswith("list"):\n return self.get_cocktails_by_category(command_prefix.removeprefix("list").strip())\n if command_prefix.startswith("find"):\n return self.find(command_prefix.removeprefix("find").strip())\n if command_prefix.startswith("with"):\n return self.get_cocktails_with(command_prefix.removeprefix("with").strip())\n\n return "This command does not exist or you mistyped something"\n\n def get_all_ingredients(self) -> str:\n """Returns a string containing all of the ingredients the bot knows."""\n return '\\n'.join(str(i) for i in self.ingredients.values())\n\n def get_all_cocktails(self) -> str:\n """Returns a string containing the names of all of the cocktails the bot knows."""\n return '\\n'.join(r.name for r in self.recipes.values())\n\n def get_all_categories(self) -> str:\n """Returns a string containing all the cocktail categories the bot knows."""\n categories = sorted({\n recipe.category\n for recipe in self.recipes.values()\n })\n return '\\n'.join(categories)\n\n def get_count(self, param: str) -> str:\n """Returns the amount of ingredients or cocktails the bot knows."""\n if self.starts_with_ingredients_prefix(param):\n sequence = self.ingredients\n elif self.starts_with_cocktails_prefix(param):\n sequence = self.recipes\n else:\n return self.ERROR\n\n return str(len(sequence))\n\n def get_recipe(self, param: str) -> str:\n """Returns the full recipe for the passed cocktail name."""\n recipe = self.recipes.get(param)\n if recipe is None:\n return (\n f"There is no recipe for a cocktail called {param}. To see all "\n f"cocktails with a recipe type '$bt cocktails'"\n )\n return recipe.as_markdown\n\n def get_cocktails_by_category(self, category: str) -> str:\n """Returns all cocktails in the given category."""\n recipes = self.categories.get(category)\n if not recipes:\n return f"There is no category called {category} or it contains no cocktails"\n\n return '\\n'.join(r.name for r in recipes)\n\n @staticmethod\n def starts_with_cocktails_prefix(param: str) -> bool:\n """Returns true if passed string starts with the cocktails prefix (-c or cocktails)."""\n return param.startswith("-c") or param.startswith("cocktails")\n\n @staticmethod\n def remove_cocktails_prefix(param: str) -> str:\n """Returns a string with the cocktails prefix (-c or cocktails) removed. If the string does not start with\n the cocktails prefix it will return the original string."""\n if param.startswith("-c"):\n return param.removeprefix("-c")\n if param.startswith("cocktails"):\n return param.removeprefix("cocktails")\n return param\n\n @staticmethod\n def starts_with_ingredients_prefix(param: str) -> bool:\n """Returns true if passed string starts with the ingredient prefix (-i or ingredients)."""\n return param.startswith("-i") or param.startswith("ingredients")\n\n @staticmethod\n def remove_ingredients_prefix(param: str) -> str:\n """Returns a string with the ingredient prefix (-i or ingredients) removed. If the string does not start with\n the ingredients prefix it will return the original string."""\n if param.startswith("-i"):\n return param.removeprefix("-i")\n if param.startswith("ingredients"):\n return param.removeprefix("ingredients")\n return param\n\n def find(self, param: str) -> str:\n """Returns all ingredients or cocktails containing the criteria in the parameter separated by commas."""\n answer = ""\n if self.starts_with_cocktails_prefix(param):\n param = self.remove_cocktails_prefix(param)\n for criteria in param.strip().split():\n answer += f"**Criteria: {criteria}**\\n"\n answer += self.get_cocktails_containing(criteria)\n return answer\n\n if self.starts_with_ingredients_prefix(param):\n param = self.remove_ingredients_prefix(param)\n for criteria in param.strip().split():\n answer += f"**Criteria: {criteria}**\\n"\n answer += self.get_ingredients_containing(criteria)\n return answer\n\n return self.ERROR\n\n def get_cocktails_containing(self, criteria: str) -> str:\n """Returns all cocktails containing the criteria in its name."""\n answer = ""\n for name, recipe in self.recipes.items():\n if criteria in name:\n answer += f"{recipe.name}\\n"\n\n if answer:\n return answer\n return "Nothing was found matching your criteria"\n\n def get_ingredients_containing(self, criteria: str) -> str:\n """Returns all ingredients containing the criteria in its name."""\n answer = ""\n for name, ingredient in self.ingredients.items():\n if criteria in name:\n answer += f"{ingredient.name}\\n"\n\n if answer:\n return answer\n return "Nothing was found matching your criteria"\n\n def get_cocktails_with(self, param: str) -> str:\n """Returns all cocktails containing the searched for ingredients in the parameter separated by commas."""\n answer = '\\n'.join(\n recipe.name\n for ingredient in param.strip().split(",")\n for recipe in self.by_ingredient.get(ingredient, ())\n )\n\n if answer:\n return answer\n return "Nothing was found matching your criteria"\n\n\ndef test():\n bar = Bartender()\n while True:\n try:\n cmd = input('> ')\n except KeyboardInterrupt:\n break\n\n print(bar.handle(FakeMessage(cmd)))\n print()\n\ntest()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T06:26:47.370",
"Id": "510482",
"Score": "0",
"body": "Thank you very much for the great feedback :D Do you have any ideas on making the handle method better? I'm not a fan of the big elif. hHowever, I started with a switcher but after a certain point, it wasn't possible anymore."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T07:20:14.293",
"Id": "510484",
"Score": "0",
"body": "I have 2 questions after further looking at your suggestion. What is the FakeMessage for? I can't really wrap my head around it since it only gets used in the handle. And the other question is why some methods are static? In java, I would normally make all of the methods private apart from the handle but that's not possible as far as I"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T07:32:43.013",
"Id": "510486",
"Score": "2",
"body": "This is a very opiniated answer and does not reflect broad consesus. It's not bad per se, just be wary following this anwser."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T13:02:13.397",
"Id": "510502",
"Score": "0",
"body": "@Hakaishin It's \"opiniated\" for a reason - I'm happy to share more justification for any points that you think need them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T13:03:04.940",
"Id": "510503",
"Score": "0",
"body": "@LuciferUchiha `FakeMessage` is just what I used to mock out actual Discord, so that the test doesn't need it. In the actual code, there will be a type from the Discord library that you'll want to reference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T13:11:41.733",
"Id": "510505",
"Score": "0",
"body": "I've edited my answer to address your question re. statics"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T15:25:43.230",
"Id": "510517",
"Score": "0",
"body": "Thank you makes more sense now :D"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T22:40:16.367",
"Id": "258899",
"ParentId": "258892",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T19:33:48.130",
"Id": "258892",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"json"
],
"Title": "Python discord bot"
}
|
258892
|
<p>I need to store sensitive strings in DB, so decided to encrypt it in a DB and decrypt it at the application layer. And noticed that it is not so easy to find ready to use an example. Please check my code below. It is based on <a href="https://damienbod.com/2020/08/19/symmetric-and-asymmetric-encryption-in-net-core/" rel="nofollow noreferrer">this damienbod's</a> topic, but I included IV to the string itself and also want to know if it is production-ready. And a somewhat unrelated question: probably I should use an old Rijndael solution like <a href="https://github.com/2Toad/Rijndael256/issues/13#issuecomment-637724412" rel="nofollow noreferrer">this</a>?</p>
<pre><code>public class SymmetricEncryptDecrypt
{
private const int ivBytes = 128;
public (string Key, string IVBase64) InitSymmetricEncryptionKeyIV()
{
var key = GetEncodedRandomString(32); // 256
using (Aes cipher = CreateCipher(key))
{
cipher.GenerateIV();
var IVBase64 = Convert.ToBase64String(cipher.IV);
return (key, IVBase64);
}
}
private byte[] GetNewIv()
{
using (Aes cipher = CreateCipher(GetEncodedRandomString(32)))
{
cipher.GenerateIV();
return cipher.IV;
}
}
/// <summary>
/// Encrypt using AES
/// </summary>
/// <param name="text">any text</param>
/// <param name="IV">Base64 IV string/param>
/// <param name="key">Base64 key</param>
/// <returns>Returns an encrypted string</returns>
public string Encrypt(string text, string key)
{
var iv = this.GetNewIv();
using (Aes cipher = CreateCipher(key))
{
cipher.IV = iv;
ICryptoTransform cryptTransform = cipher.CreateEncryptor();
byte[] plaintext = Encoding.UTF8.GetBytes(text);
byte[] cipherText = cryptTransform.TransformFinalBlock(plaintext, 0, plaintext.Length);
return Convert.ToBase64String(iv.Concat(cipherText).ToArray());
}
}
/// <summary>
/// Decrypt using AES
/// </summary>
/// <param name="text">Base64 string for an AES encryption</param>
/// <param name="key">Base64 key</param>
/// <returns>Returns a string</returns>
public string Decrypt(string encryptedText, string key)
{
var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(encryptedText);
var ivStringBytes = cipherTextBytesWithSaltAndIv.Take(ivBytes / 8).ToArray();
// Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip(ivBytes / 8).Take(cipherTextBytesWithSaltAndIv.Length - (ivBytes / 8)).ToArray();
using (Aes cipher = CreateCipher(key))
{
cipher.IV = ivStringBytes;
ICryptoTransform cryptTransform = cipher.CreateDecryptor();
byte[] plainBytes = cryptTransform.TransformFinalBlock(cipherTextBytes, 0, cipherTextBytes.Length);
return Encoding.UTF8.GetString(plainBytes);
}
}
private string GetEncodedRandomString(int length)
{
var base64 = Convert.ToBase64String(GenerateRandomBytes(length));
return base64;
}
/// <summary>
/// Create an AES Cipher using a base64 key
/// </summary>
/// <param name="key"></param>
/// <returns>AES</returns>
private Aes CreateCipher(string keyBase64)
{
// Default values: Keysize 256, Padding PKC27
Aes cipher = Aes.Create();
cipher.Mode = CipherMode.CBC; // Ensure the integrity of the ciphertext if using CBC
cipher.Padding = PaddingMode.ISO10126;
cipher.Key = Convert.FromBase64String(keyBase64);
return cipher;
}
private byte[] GenerateRandomBytes(int length)
{
var byteArray = new byte[length];
RandomNumberGenerator.Fill(byteArray);
return byteArray;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T21:42:19.200",
"Id": "510451",
"Score": "0",
"body": "What .NET version? 3.1?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T21:51:49.250",
"Id": "510452",
"Score": "1",
"body": "@aepot, yes .NET 3+"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T13:53:05.180",
"Id": "511455",
"Score": "0",
"body": "You're documenting PKCS#7 compatible padding, and then use a slightly different ISO 10126 padding mode, which is by-and-large deprecated."
}
] |
[
{
"body": "<p>This code looks complicated for me. Not because I don't know how to use AES encrypter but it contains a lot of redundancy. From setting <code>CipherMode.CBC</code> which is default to <code>GetNewIv()</code> which is random by default.</p>\n<p>Is a lot of code is targeting the a security improvement? If it is, you have a breach storing key in a <code>string</code>. I can easily get the key from App's memory even if it currently not in use because <code>string</code> is immutable and can be stored in memory for undefined period of time. Storing key in <code>byte[]</code> array allows to <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.array.clear?view=netcore-3.1\" rel=\"nofollow noreferrer\">cleanup the array</a> at any moment.</p>\n<p>If security on DB side is enough then you may simplify the code as following two methods.</p>\n<p>I use streams because it more friendly for me. As a bonus the code can be easily ported to streams use.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private static string Encrypt(string text, byte[] key)\n{\n using AesManaged aes = new AesManaged() { Key = key };\n using MemoryStream ms = new MemoryStream();\n ms.Write(aes.IV);\n using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write, true))\n {\n cs.Write(Encoding.UTF8.GetBytes(text));\n }\n return Convert.ToBase64String(ms.ToArray());\n}\n\nprivate static string Decrypt(string base64, byte[] key)\n{\n using MemoryStream ms = new MemoryStream(Convert.FromBase64String(base64));\n byte[] iv = new byte[16];\n ms.Read(iv);\n using AesManaged aes = new AesManaged() { Key = key, IV = iv };\n using CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read, true);\n using MemoryStream output = new MemoryStream();\n cs.CopyTo(output);\n return Encoding.UTF8.GetString(output.ToArray());\n}\n</code></pre>\n<p>Demo</p>\n<pre class=\"lang-cs prettyprint-override\"><code>string text = "Hello world";\nbyte[] key = Enumerable.Range(0, 32).Select(x => (byte)x).ToArray(); // just for example :)\nstring base64 = Encrypt(text, key);\nConsole.WriteLine(base64);\nConsole.WriteLine(Decrypt(base64, key));\n</code></pre>\n<p>Output</p>\n<pre class=\"lang-none prettyprint-override\"><code>Qh+XfnIuIdgllOiKFgzCpTURW+bUuj91S91zA1przRQ=\nHello world\n</code></pre>\n<p>I think that's enough to keep it secure on DB side. Btw, you may keep the Key generator methods if you need it.</p>\n<p>P.S. <code>old Rijndael solution</code> - <code>Rijndael</code> was superseded by <code>Aes</code> in .NET, i don't remember the exact reason but something like <code>Rijndael</code> has a padding issue and <code>Aes</code> fixed it.</p>\n<hr />\n<p>One more tip. If you're on Windows and the encrypted data is allowed to be lost (in case of emergency), you can use DPAPI to protect the <strong>key</strong> (MS NuGet package exists, Current User/Local Machine protecting modes available) and store protected key in DB in the same sequence as IV. Then you can use totally random key for each <code>Encrypt()</code> call and store it with data. The data may be lost on Windows reinstall or moving the ASP.NET server to other machine, because DPAPI uses key associated with Current User credentials or Local Machine ID. But protected data can't be restored if DB was stolen or in any other way on other PC. Anyway learn how DPAPI works, it may be useful if the server runs under Windows.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T13:58:23.233",
"Id": "511456",
"Score": "1",
"body": "Personally I don't like default values at all. They are largely hidden in the API documentation; I'd much rather use explicit values. The key generator doesn't seem to be secure, so I would not keep it (or do you mean the key generator in the original code?). You may want to look at the padding remark I made below the question, it's not PKCS#7."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T14:59:18.917",
"Id": "511462",
"Score": "0",
"body": "@MaartenBodewes yes, I mean key generator in the original code. Shoul I remove `Padding = PaddingMode.ISO10126`? I'm not sure about it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T15:10:07.493",
"Id": "511465",
"Score": "1",
"body": "Well, you copied it from the question and a remark has been made now, so I guess it is clear as it is. However, I would consider PKCS#7 better supported so I would use it just to avoid interesting errors during decryption on another platform."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T22:15:12.923",
"Id": "258898",
"ParentId": "258896",
"Score": "3"
}
},
{
"body": "<p>There is already a security review and a hint on how to better code the class, but I would like to point out the issues with the coding quality and documentation.</p>\n<h2>Initialization</h2>\n<pre><code>private const int ivBytes = 128;\n</code></pre>\n<p>Constants should be in all caps, and an IV for AES-CBC is 16 bytes / 128 bits, not 128 bytes.</p>\n<pre><code>public (string Key, string IVBase64) InitSymmetricEncryptionKeyIV()\n</code></pre>\n<p>The parameters should not be capitalized. As it is already in a class called <code>SymmetricEncryptDecrypt</code> you can loose the <code>SymmetricEncryption</code> part.</p>\n<pre><code>var key = GetEncodedRandomString(32); // 256\n</code></pre>\n<p>Encoded as <em>what</em>? What does 256 even mean here? And a key is not a string, it's a byte array.</p>\n<pre><code>cipher.GenerateIV();\n</code></pre>\n<p>This call is repeated twice, which is generally considered code smell if it is only needed once (but kudos for using a method for it).</p>\n<h2>Encryption</h2>\n<pre><code>/// Encrypt using AES\n</code></pre>\n<p>AES in which mode? Shouldn't you specify the padding mode either? And the fact that you prefix the IV? And the fact that you use UTF-8?</p>\n<pre><code>/// <returns>Returns an encrypted string</returns>\n</code></pre>\n<p>But here the encoding is not specified (again).</p>\n<pre><code>return Convert.ToBase64String(iv.Concat(cipherText).ToArray());\n</code></pre>\n<h2>Decryption</h2>\n<p>One-liners like this just make reading and debugging harder. Split into 3 lines.</p>\n<pre><code>var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(encryptedText);\n</code></pre>\n<p>Oh, right, where is the salt in the encryption phase?</p>\n<pre><code> var ivStringBytes = cipherTextBytesWithSaltAndIv.Take(ivBytes / 8).ToArray();\n</code></pre>\n<p>Where is the string? Do you mean octet string?</p>\n<h2>The rest</h2>\n<pre><code>var base64 = Convert.ToBase64String(GenerateRandomBytes(length));\nreturn base64;\n</code></pre>\n<p>I'd think that <code>var randomBytes = GenerateRandomBytes(length)</code> followed by <code>return Convert.ToBase64String(randomBytes)</code> is acceptable: don't perform two functions in one line unless it helps readability.</p>\n<pre><code>// Default values: Keysize 256, Padding PKC27\n</code></pre>\n<p>The padding mode is called PKCS#7 compatible padding, and you're not using it.</p>\n<pre><code> cipher.Mode = CipherMode.CBC; // Ensure the integrity of the ciphertext if using CBC\n</code></pre>\n<p>That's a good hint, but #1: you're not doing it and #2 the comment should be in the documentation of the class if you're not doing it yourself, not in an end-of-line comment.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-14T08:10:27.250",
"Id": "511882",
"Score": "0",
"body": "thanks for the answer. Could you please elaborate on this: \"where is the salt in the encryption phase?\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-14T08:17:51.810",
"Id": "511883",
"Score": "0",
"body": "Are you speaking about variable names only? Yes, it is a \"copy-paste\" issue. Or do you mean that we need salt?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-14T09:05:45.203",
"Id": "511888",
"Score": "1",
"body": "`cipherTextBytesWithSaltAndIv` is in your decryption method, but no mention is there in the encryption method of a salt. So I don't know - you tell me. Maybe that part of the code is missing, but in that case your program isn't very symmetric w.r.t. method & input / output parameter definitions. You'd only really need a salt if you use password based encryption (rather than using a fully randomized key). That kind of copy / paste error should not be acceptable *anywhere*, don't wrong foot your colleagues (including a future you)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T14:17:48.220",
"Id": "259309",
"ParentId": "258896",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "258898",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T20:54:40.460",
"Id": "258896",
"Score": "4",
"Tags": [
"c#",
".net",
"asp.net-core",
"encryption"
],
"Title": ".Net core string symmetric encryption"
}
|
258896
|
<p>I'm building a very simple Lisp interpreter. Similar to the the one <a href="https://norvig.com/lispy.html" rel="nofollow noreferrer">from here</a>. Here is what I have so far for the parsing part, that is, everything from "text is passed to the the program" to "ast is built". How does the below look? What can be improved? The hardest part for me was the recursive <code>read_from_tokens</code> function.</p>
<pre><code>import re
Symbol = str
def pops(L, d=None):
"Pop from the left of the list, or return the default."
return L.pop(0) if L else d
def parse(program):
"Read a Scheme expression from a string and return tokens in AST."
program = preprocess(program)
assert program.count(')') == program.count('('), "Mismatched parens"
return read_from_tokens(tokenize(program))
def preprocess(s):
"Replace comments with a single space."
return re.sub(r';.+', ' ', s)
def tokenize(s):
"Convert a string into a list of tokens."
return s.replace('(', ' ( ').replace(')', ' ) ').split()
def atom(token):
"Return a number (only accepted literal) or a symbol."
try:
return int(token) if token.isdigit() else float(token)
except ValueError:
return Symbol(token)
def read_from_tokens(tokens):
"Read one or more expression from a sequence of tokens. Returns a list of lists."
L = []
while (token := pops(tokens, ')')) != ')':
L.append(atom(token) if token!='(' else read_from_tokens(tokens))
return L
if __name__ == '__main__':
print (parse("(define (+ 2 2) 10) (* pi (* r r))"))
print (parse("(define r 10)"))
print (parse("(* pi (* (+ 1 1) r))"))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T05:24:59.353",
"Id": "510478",
"Score": "0",
"body": "No string literals?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T07:34:30.350",
"Id": "510487",
"Score": "0",
"body": "@vnp nope, not yet."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T17:26:31.360",
"Id": "510531",
"Score": "3",
"body": "A lot can be learned from Peter Norvig's Python examples, which usually combine elegance and practicality. If you want to pursue this topic, I recommend Ruslan Spivak's [Let's build a simple interpreter](https://github.com/rspivak/lsbasi). I have referred to them several times while working on an unusual parsing project over the past few months."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T01:40:08.170",
"Id": "258908",
"Score": "3",
"Tags": [
"python",
"parsing",
"recursion"
],
"Title": "Lisp expression parser"
}
|
258908
|
<p><strong>Goal</strong></p>
<p>In the vector <code>x</code>, I would like to insert the elements of the vector <code>values</code> at indices stored in vector <code>positions</code>. Note that the vector <code>positions</code> is not sorted.</p>
<p>For example, from the following input</p>
<pre><code>std::vector<char> x = {'H','e','l','l','W','o','l','d'};
std::vector<char> values = {'r','o'};
std::vector<size_t> positions = {6,4};
</code></pre>
<p>I expect the following output</p>
<pre><code>std::vector<char> x = {'H','e','l','l','o','W','o','r','l','d'};
</code></pre>
<p><strong>My implementation</strong></p>
<p>The idea is first to sort <code>positions</code> and reorder <code>values</code> accordingly. Then, I resize the vector <code>x</code> so that it can welcome the new elements. Finally, I iterate through the vector <code>x</code> from its last index to the lowest position of insertion by asking at each step what element should go there and move this element (whether it comes from a lower index in <code>x</code> of from <code>values</code>).</p>
<pre><code>#include <iostream>
#include <vector>
#include <numeric>
//// Print a vector
template <typename T>
void print(std::vector<T>& x)
{
for (auto& e : x) std::cout << e << " ";
std::cout << "\n";
}
//// Return the indices to inform on how to sort the inputted vector
template <typename T>
std::vector<uint32_t> sort_indices(const std::vector<T> &v)
{
// initialize original index locations
std::vector<uint32_t> idx(v.size());
std::iota(idx.begin(), idx.end(), 0);
// sort indexes based on comparing values in v
std::sort(idx.begin(), idx.end(),
[&v](uint32_t i1, uint32_t i2) {return v[i1] < v[i2];});
return idx;
}
//// reorder vector based on indices
template <typename T>
void reorder(std::vector<T>& v, std::vector<uint32_t>& order)
{
auto v2 = v;
for (uint32_t i = 0 ; i < v.size() ; i++)
{
v[i] = v2[order[i]];
}
}
//// Insert multiple elements at specified positions into vector
template<typename T>
void insertAtPositions(std::vector<T>& x, std::vector<T>& values, std::vector<size_t>& positions)
{
// assert values and positions are the same size
assert(values.size() == positions.size());
// Special case - values is empty
if (values.size() == 0) return;
// sort the values and the positions where those values should be inserted
auto indices = sort_indices(positions);
reorder(positions, indices);
reorder(values, indices);
// Special case - x is empty
if (x.size() == 0)
{
x.swap(values);
return;
}
// Allocate memory to x
x.resize(x.size() + values.size());
// Move things to make room for insertions and insert
int pos_index = positions.size()-1;
for (size_t i = x.size()-1 ; pos_index >= 0 ; --i)
{
if (i == positions[pos_index] + pos_index)
{
// A new value should go at index i
x[i] = std::move(values[pos_index]);
--pos_index;
} else
{
// The value from index 'i-pos_index-1' must go to index 'i'
x[i] = std::move(x[i-pos_index-1]);
}
}
}
int main()
{
std::vector<char> x = {'H','e','l','l','W','o','l','d'};
std::vector<char> values = {'r','o'};
std::vector<size_t> positions = {6,4};
print(x);
insertAtPositions(x,values,positions);
print(x);
}
</code></pre>
<p>It prints, as expected</p>
<pre><code>H e l l W o l d
H e l l o W o r l d
</code></pre>
<p><strong>Are there faster (or better in some other respect) implementations?</strong></p>
<p>Note that</p>
<ol>
<li>in practice, <code>x</code>'s size typically ranges from 0 to 10^7 and <code>positions</code> (and <code>values</code>)'s size typically ranges from 0 to 50.</li>
<li>I have good reasons for using a vector and not a deque despite this insertion.</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T18:30:13.483",
"Id": "510535",
"Score": "0",
"body": "A single tiny hint: for `.size() == 0`, I'd write `.empty()` due to better readability of the intentions IMO."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T18:59:59.573",
"Id": "510536",
"Score": "0",
"body": "Definitional problem: You can get a different result by first sorting the indexes!"
}
] |
[
{
"body": "<ul>\n<li><p>We need to include <code><algorithm></code> for <code>std::sort</code> and <code><cassert></code> for <code>assert</code>.</p>\n</li>\n<li><p><code>void print(std::vector<T> &x)</code>: Since we don't modify the vector, this should take a <code>const&</code> (and use a <code>const&</code> internally in the range-based for loop).</p>\n</li>\n<li><p><code>void reorder(std::vector<T> &v, std::vector<uint32_t> &order)</code>: Again, <code>order</code> can be a <code>const&</code>.</p>\n</li>\n<li><p>We should use <code>std::size_t</code> for indices into a vector, not <code>uint32_t</code> or <code>size_t</code>.</p>\n</li>\n<li><p>If we need a signed type for dealing with index differences, we should use <code>std::ptrdiff_t</code>, not <code>int</code>. It might be easier to count forwards, and then calculate the indices we need inside the loop though.</p>\n</li>\n<li><p>There's no point in <code>std::move</code>ing a <code>char</code>.</p>\n</li>\n</ul>\n<hr />\n<p>Rather than inserting elements in-place, we can create a new vector and copy the elements over, selecting from the appropriate source at each index. This doesn't require any more memory than calling <code>x.resize()</code>.</p>\n<p>e.g.:</p>\n<pre><code>{\n std::vector<char> x = {'H', 'e', 'l', 'l', 'W', 'o', 'l', 'd'};\n std::vector<char> values = {'r', 'o'};\n std::vector<size_t> positions = {6, 4};\n\n auto indices = sort_indices(positions);\n reorder(positions, indices);\n reorder(values, indices);\n\n auto size = x.size() + values.size();\n\n auto y = std::vector<char>();\n y.reserve(size);\n\n auto v = std::size_t{ 0 }; // index into x\n auto p = std::size_t{ 0 }; // index into positions / values\n\n for (auto i = std::size_t{ 0 }; i != size; ) // index into y\n {\n if (v == positions[p])\n {\n y.push_back(values[p]);\n ++p;\n ++i;\n }\n else\n {\n y.push_back(x[v]);\n ++v;\n ++i;\n }\n }\n\n print(y);\n}\n</code></pre>\n<p>Since we expect the <code>x</code> vector to be much larger than the <code>values</code> to be inserted, we could copy larger ranges from <code>x</code> in the <code>else</code> branch above, something like:</p>\n<pre><code> auto beg = v;\n auto end = (p == positions.size() ? x.size() : positions[p]);\n\n y.insert(y.end(), x.begin() + beg, x.begin() + end);\n v = end;\n i += (beg - end);\n</code></pre>\n<p>(Warning: code not properly tested).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T21:45:34.097",
"Id": "510561",
"Score": "1",
"body": "\"This doesn't require any more memory than calling `x.resize()`.\" That's not generally true. Especially with the given typical sizes those few additional entries may very often not lead to a reallocation. (Of course given that no `shrink_to_fit` was called before or the last reallocation was due to a call to `resize`.) And about `std::move`ing a `char`: The function is implemented as a template."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T08:51:10.007",
"Id": "258912",
"ParentId": "258910",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T07:09:05.130",
"Id": "258910",
"Score": "2",
"Tags": [
"c++",
"performance",
"vectors",
"insertion-sort"
],
"Title": "Inserting multiple elements at known locations in a vector"
}
|
258910
|
<p>I have created Azure Blob Trigger function. If file is inserted in Azure Blob Container at that time this function is trigger and based on that file data we need to insert into our database table.</p>
<p>My Trigger Function Class be like below</p>
<pre><code>public static class StockCountTrigger
{
[FunctionName("StockCountTrigger")]
public static void Run([BlobTrigger("importstockcount/{name}", Connection = "AzureWebJobsStorage")] CloudBlockBlob cloudBlockBlob, TraceWriter log)
{
try
{
log.Info($"FileName:{cloudBlockBlob.Name}");
var environment = Constants.Environment;
IStockCountService stockCountService;
if (environment.IsIn(Helper.Environment.Client1))
{
stockCountService = new StockCountServiceClient1(cloudBlockBlob, log);
}
else
{
throw new NotImplementedException();
}
stockCountService.Import();
}
catch (Exception ex)
{
log.Error($"Error.", ex);
throw ex;
}
}
}
</code></pre>
<p>same function is use for multiple client with different file format and that data is inserting into <code>StockCount</code> table.</p>
<p>my service be like below</p>
<pre><code>public class StockCountServiceClient1: IStockCountService
{
private readonly CloudBlockBlob cloudBlockBlob;
private readonly TraceWriter log;
private readonly IStockCountRepository _stockCountRepository;
public StockCountServiceClient1(CloudBlockBlob cloudBlockBlob, TraceWriter log)
{
this.cloudBlockBlob = cloudBlockBlob;
this.log = log;
_stockCountRepository = new StockCountRepository();
}
public void Import()
{
var stockCounts = GetFromCSV();
if (!stockCounts.Any())
return;
log.Info($"Total Records:{stockCounts.Count}");
_stockCountRepository.Insert(stockCounts);
}
private List<StockCountModel> GetFromCSV()
{
using (var stream = cloudBlockBlob.OpenRead())
{
TextReader reader = new StreamReader(stream);
using (var csvReader = new CsvReader(reader))
{
var records = csvReader.GetRecords<dynamic>().ToList();
return records.Select(x => new StockCountModel
{
StoreNo = x.StoreNo,
ArticleNo = x.ArticleNo,
Quantity = x.Quantity,
StockDateTime = x.StockDateTime,
Reference = cloudBlockBlob.Name
}).ToList();
}
}
}
}
</code></pre>
<p>Here in repository i have created object and insert into database.</p>
<p>here my question is that Function class is static and its method <code>Run</code> is also Static. Is it right way written code to create repository and object and based on environment assign instance to it.
which approach is best is need to create static method in repository also ?</p>
<p>Frequency of file coming is every 10 minutes in container.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T10:49:41.583",
"Id": "510495",
"Score": "0",
"body": "You can easily make you function nonstatic or even go forward and use DI. Why is your environment constant? Probably it should be in the environment variables. I don't think it is a good idea to have client-specific services like \"StockCountServiceClient1\" better to separate them by functionality and not by the client. Also, take a look at the factory pattern."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T13:08:56.513",
"Id": "510504",
"Score": "0",
"body": "@Ssss separate based on functionality means like here we are importing csv but for 1 client multiple format need to support like csv, xml, json so can you please help me how to separate this functionality with different client"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T07:44:15.640",
"Id": "258911",
"Score": "0",
"Tags": [
"c#",
"beginner",
"object-oriented",
"design-patterns"
],
"Title": "Implementation in Azure Blob Function Trigger for Insert into Database"
}
|
258911
|
<p>To find neighbors of a vector and return array of Vectors which are neighbors of a Vector:</p>
<pre class="lang-cpp prettyprint-override"><code>vector<XY> neighboursOf(XY coord){
short x = coord.x;
short y = coord.y;
vector<XY> neighbours;
neighbours.reserve(9);
neighbours.push_back(XY(x-1, y));
neighbours.push_back(XY(x-1, y-1));
neighbours.push_back(XY(x-1, y+1));
neighbours.push_back(XY(x+1, y));
neighbours.push_back(XY(x+1, y-1));
neighbours.push_back(XY(x+1, y+1));
neighbours.push_back(XY(x+1, y-1));
neighbours.push_back(XY(x, y-1));
neighbours.push_back(XY(x, y+1));
return neighbours;
}
}
</code></pre>
<p><code>XY</code> is a class which has members <code>x</code> and <code>y</code>:</p>
<pre class="lang-cpp prettyprint-override"><code>class XY{
public:
XY(short x=0, short y=0);
short x;
short y;
};
XY::XY(short x, short y) {
this->x = x;
this->y = y;
}
</code></pre>
<p>The param is Vector of the yellow square, the neighbor array is supposed to be the black squares</p>
<p><a href="https://i.stack.imgur.com/p5iLx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/p5iLx.png" alt="Example" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T11:45:47.517",
"Id": "510496",
"Score": "5",
"body": "A bit more context would be helpful to reviewers. First, it would be helpful to see the `XY` class or struct. Second, I don't believe that `XY[]` is a valid return type. It would look to the compiler like a structured binding."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T12:07:49.777",
"Id": "510500",
"Score": "2",
"body": "There may be a recursive way, but here we review *the code you have written*, not the code you may write in the future. If you have code that *works* (to the best of your knowledge), then post it for review (as Edward says, we'll want more context), and perhaps someone will point out if it's inefficient (personally, I'd leave it as is, or perhaps write a short loop)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T12:51:44.803",
"Id": "510630",
"Score": "1",
"body": "Incorporating advice from an answer into the question violates the question-and-answer nature of this site. You could post improved code as a new question, as an answer, or as a link to an external site - as described in [I improved my code based on the reviews. What next?](/help/someone-answers#help-post-body). I have rolled back the edit, so the answers make sense again."
}
] |
[
{
"body": "<p>The <code>XY</code> class looks like it would be better as a plain <code>struct</code>:</p>\n<pre><code>struct XY\n{\n short x;\n short y;\n};\n</code></pre>\n<p>Then we don't need to declare a constructor, because it can be <em>aggregate-initialised</em>.</p>\n<p>I'll assume that your <code>vector</code> is an alias for <code>std::vector</code> here, since there's no definition visible.</p>\n<p>Eight of the statements to populate the vector look reasonable. The duplicate of <code>x+1, y-1</code> is probably unintended, though.</p>\n<p>You might profitably use <code>emplace_back</code> rather than writing those constructors. We could create the vector directly, with all the element values as its initializer-list:</p>\n<pre><code>std::vector<XY> neighboursOf(XY coord)\n{\n auto const x = coord.x;\n auto const y = coord.y;\n\n return { {x-1, y-1}, {x, y-1}, {x+1, y-1},\n {x-1, y }, {x+1, y },\n {x-1, y+1}, {x, y+1}, {x+1, y+1} };\n}\n</code></pre>\n<p>See how the formatting here helps us see that each neighbour is included exactly once?</p>\n<p>It is possible to write a clever loop, but that's going to be harder to read and no more efficient than the straightforward code.</p>\n<p>Note that if we have a finite grid, then we might want special behaviour at the edges. And if we have an infinite grid, we'll suffer arithmetic overflow (Undefined Behaviour) when we reach the limits of <code>short</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T17:20:16.110",
"Id": "258928",
"ParentId": "258915",
"Score": "6"
}
},
{
"body": "<p>I suggest initializing the vector on creation since you know all the needed elements at compile time. Also, if you are not changing the size of that vector, it is probably better to use a <code>std::array</code> instead of <code>std::vector</code>. Keep in mind, that most x64 C++ compilers by default use QWORD-aligned (8-byte) pointers, so it is better to align your variables with the pointer size. There is a <code>ptrdiff_t</code> type in <code><cstddef></code> library created for this purpose.\nCheck the following code snippet:</p>\n<pre><code>#include <array>\n#include <cstddef>\n\nclass XY\n{\npublic:\n ptrdiff_t x;\n ptrdiff_t y;\npublic:\n XY(const ptrdiff_t& x=0, const ptrdiff_t& y=0): x(x), y(y) {}\n};\n\nstd::array<XY, 8> neighboursOf(const XY& coord)\n{\n const auto x = coord.x;\n const auto y = coord.y;\n\n return {\n XY{x-1, y}, XY{x-1, y-1},\n XY{x-1, y+1}, XY{x+1, y},\n XY{x+1, y+1}, XY{x+1, y-1},\n XY{x, y-1}, XY{x, y+1}\n };\n}\n</code></pre>\n<p>You can check the compiler output on <a href=\"https://godbolt.org/z/qG9rb1495\" rel=\"nofollow noreferrer\">godbolt</a> and compare it with your code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T17:23:35.023",
"Id": "510529",
"Score": "1",
"body": "We managed to write very similar answers within seconds of each other!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T17:26:20.103",
"Id": "510530",
"Score": "0",
"body": "Yeah, I just have been checking the assembler output before posting the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T04:03:46.567",
"Id": "510588",
"Score": "0",
"body": "The duplicate `XY(x+1, y-1)` was unintended btw, so you can edit that out"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T17:20:47.393",
"Id": "258929",
"ParentId": "258915",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T11:22:51.640",
"Id": "258915",
"Score": "2",
"Tags": [
"c++",
"c++17",
"vectors"
],
"Title": "Find neighbours of a vector"
}
|
258915
|
<p>For a project I have a large dataset with a multitude of variables from different questionnaires. Not all variables are required for all analyses.</p>
<p>So I created a preprocessing script, in which subsets of variables (with and without abbreviations) are created. However it gets confusing pretty fast.
For convenience I decided to create a <code>index_list</code> which holds all data.frames as well as a data.frame called <code>index_df</code> which holds the name of the respective data.frame as well as a brief description of each subversion of the dataset.</p>
<pre><code>######################## Preparation / Loading #####################
# Clean Out Global Environment
rm(list=ls())
# Detach all unnecessary pacakges
pacman::p_unload()
# Load Required Libraries
pacman::p_load(dplyr, tidyr, gridExtra, conflicted)
# Load Data
#source("00_Preprocess.R")
#create simulation data instead
sub_data <- data.frame(x=c(2,3,5,1,6),y=c(20,30,10,302,5))
uv_newScale <- data.frame(item1=c(2,3,5,1,6),item2=c(3,5,1,3,2))
# Resolving conflicted Namepsaces
conflict_prefer("filter", "dplyr")
# Creating an Index
index_list <- list("sub_data"=sub_data,
"uv_newScale"=uv_newScale
)
index_df <- data.frame("Data.Frame"=c("sub_data",
"uv_newScale"),
"Description"=c("Contains all sumscales + sociodemographics, names abbreviated",
"Only sum scores for the UV Scale"))
</code></pre>
<p>I am wondering if there is a more efficient way to do so. Like saving the data.frames together with the description in one container?</p>
|
[] |
[
{
"body": "<h2>One approach</h2>\n<p>If the description is to serve only as a metadata, <code>R</code> allows you to add any number of metadata to objects with attributes feature. you can add it as an attribute for the <code>data.frame</code> object.</p>\n<pre><code>attr(sub_data, "Description") <- "Contains all sumscales + sociodemographics, names abbreviated"\n\n# Description now shows in the data frame structure \nstr(sub_data)\n# 'data.frame': 5 obs. of 2 variables:\n# $ x: num 2 3 5 1 6\n# $ y: num 20 30 10 302 5\n# - attr(*, "Description")= chr "Contains all sumscales + sociodemographics, names # abbreviated"\n\n#You can access the Description only\nattributes(sub_data)$Description\n# [1] "Contains all sumscales + sociodemographics, names abbreviated"\n</code></pre>\n<p>However, custom attributes come with limitations.They are not persistent when you perform certain operations on objects such as subsetting. Here is an example using same object with the new Description attribute we just added. If we subset the data, the custom attribute will be lost.</p>\n<pre><code>sub2_data <- sub_data[,"x", drop = FALSE]\n\nattributes(sub2_data)$Description\n# NULL\n\n</code></pre>\n<h2>Alternative approach</h2>\n<p>You can use the same idea of creating a container within container. However, instead of creating a list that contains data frames, you can create a <code>data.frame</code> within a <code>data.frame</code>. This makes it easier to access and manipulate. You can access the inner data frame by adding second <code>$</code></p>\n<pre><code># Assigning new column `data` to hold data frames \nindex_df$data <- index_list\n\n# We can access Description \nindex_df$Description\n# [1] "Contains all sumscales + sociodemographics, names abbreviated"\n# [2] "Only sum scores for the UV Scale" \n\n# Accessing Data \nindex_df$data$sub_data\n# x y\n#1 2 20\n#2 3 30\n#3 5 10\n#4 1 302\n#5 6 5\n\nstr(index_df)\n# 'data.frame': 2 obs. of 3 variables:\n# $ Data.Frame : chr "sub_data" "uv_newScale"\n# $ Description: chr "Contains all sumscales + sociodemographics, names abbreviated" "Only sum scores for the UV Scale"\n# $ data :List of 2\n# ..$ sub_data :'data.frame': 5 obs. of 2 variables:\n# .. ..$ x: num 2 3 5 1 6\n# .. ..$ y: num 20 30 10 302 5\n# ..$ uv_newScale:'data.frame': 5 obs. of 2 variables:\n# .. ..$ item1: num 2 3 5 1 6\n# .. ..$ item2: num 3 5 1 3 2\n</code></pre>\n<h2>Efficiency</h2>\n<p>The first approach is more efficient than the second in terms of memory footprint. Here is a comparison between objects sizes in bytes.</p>\n<pre><code># Creating one data frame within one data frame for comparison\nlist_df <- list(sub_data=sub_data)\ndfs <- data.frame("Data.Frame"="sub_data",\n "Description"="Contains all sumscales + sociodemographics, names abbreviated")\n\ndfs$data <- list_df \n\n# Adding attributes\nattr(sub_data, "Description") <- "Contains all sumscales + sociodemographics, names abbreviated"\n \n\n# Memory Size in bytes\nobject.size(dfs)\n# 2376 bytes\nobject.size(sub_data)\n# 1224 bytes\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T07:43:54.743",
"Id": "512411",
"Score": "0",
"body": "Perfect. Thanks this was exactly what I was looking for"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-16T10:29:04.873",
"Id": "259611",
"ParentId": "258916",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259611",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T11:41:19.953",
"Id": "258916",
"Score": "1",
"Tags": [
"r",
"collections"
],
"Title": "R Container for Multiple data.frame with a Brief Description of the Content of the data.frame"
}
|
258916
|
<p>I'm just starting to learn website coding with html, css, and JavaScript. To get a bit of a hang for it, I'm trying to build a complete web page.</p>
<p>So far, I've only done the navbar. I started with a basic Bootstrap 5 navbar and modified it to get it to look and behave like I want. It took me three days, but it looks good now.</p>
<p>Or at least, on the outside it does. I can't, however, shake the feeling that this could've been done way easier, with a lot less code.</p>
<p>Could anyone point out some examples of where I may have gone about it way too roundabout and what I could've done better?</p>
<p>I've pasted my code in a CodePen:</p>
<p><a href="https://codepen.io/AlexanderSplat/pen/ZELLEeB" rel="nofollow noreferrer">https://codepen.io/AlexanderSplat/pen/ZELLEeB</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(window).scroll(function() {
var scroll = $(window).scrollTop();
var width = $(window).width();
if (scroll >= 50 && width <= 1000) {
document.querySelector(".navbar").style.paddingTop = "0";
document.querySelector(".navbar").style.paddingBottom = "0";
document.querySelector(".navbar-brand").style.fontSize = "28px";
document.querySelector(".navbar-brand").style.paddingTop = "0.4%";
document.querySelector(".navbar-brand").style.paddingBottom = "0.3%";
document.querySelector(".navbar-brand").style.height = "40px";
document.querySelector(".navbar-brand").style.lineHeight = "40px";
document.querySelector("#navhome").style.paddingTop = "15px";
document.querySelector("#navabout").style.paddingTop = "15px";
document.querySelector("#navport").style.paddingTop = "15px";
document.querySelector("#navteam").style.paddingTop = "15px";
document.querySelector("#navcont").style.paddingTop = "15px";
document.querySelector("#navhome").style.paddingBottom = "14px";
document.querySelector("#navabout").style.paddingBottom = "14px";
document.querySelector("#navport").style.paddingBottom = "14px";
document.querySelector("#navteam").style.paddingBottom = "14px";
document.querySelector("#navcont").style.paddingBottom = "14px";
} else if (scroll >= 50 && width >= 1001) {
document.querySelector(".navbar").style.paddingTop = "0";
document.querySelector(".navbar").style.paddingBottom = "0";
document.querySelector(".navbar-brand").style.fontSize = "28px";
document.querySelector(".navbar-brand").style.paddingTop = "0.4%";
document.querySelector(".navbar-brand").style.paddingBottom = "0.3%";
document.querySelector(".navbar-brand").style.height = 'initial';
document.querySelector(".navbar-brand").style.lineHeight = 'initial';
document.querySelector("#navhome").style.paddingTop = "15px";
document.querySelector("#navabout").style.paddingTop = "15px";
document.querySelector("#navport").style.paddingTop = "15px";
document.querySelector("#navteam").style.paddingTop = "15px";
document.querySelector("#navcont").style.paddingTop = "15px";
document.querySelector("#navhome").style.paddingBottom = "14px";
document.querySelector("#navabout").style.paddingBottom = "14px";
document.querySelector("#navport").style.paddingBottom = "14px";
document.querySelector("#navteam").style.paddingBottom = "14px";
document.querySelector("#navcont").style.paddingBottom = "14px";
} else {
document.querySelector(".navbar").style.paddingTop = "8px";
document.querySelector(".navbar-brand").style.fontSize = "40px";
document.querySelector(".navbar-brand").style.paddingTop = "0.6%";
document.querySelector(".navbar-brand").style.paddingBottom = "0.6%";
document.querySelector(".navbar-brand").style.height = 'initial';
document.querySelector(".navbar-brand").style.lineHeight = 'initial';
document.querySelector("#navhome").style.paddingTop = "28px";
document.querySelector("#navabout").style.paddingTop = "28px";
document.querySelector("#navport").style.paddingTop = "28px";
document.querySelector("#navteam").style.paddingTop = "28px";
document.querySelector("#navcont").style.paddingTop = "28px";
document.querySelector("#navhome").style.paddingBottom = "28px";
document.querySelector("#navabout").style.paddingBottom = "28px";
document.querySelector("#navport").style.paddingBottom = "28px";
document.querySelector("#navteam").style.paddingBottom = "28px";
document.querySelector("#navcont").style.paddingBottom = "28px";
}
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
height: 200vh;
}
@media (min-width: 1001px) {
.navbar-brand {
color: white;
font-family: 'Julius Sans One';
font-style: normal;
font-weight: 400;
font-size: 40px;
padding-left: 67px;
margin-left: 1.9%;
transition: 0.4s;
}
.navbar {
background-color: #105565;
position: fixed;
width: 100%;
transition: 0.4s;
}
}
@media (max-width: 1000px) {
.navbar-brand {
color: white;
font-family: 'Julius Sans One';
font-style: normal;
font-weight: 400;
font-size: 40px;
height: 52px;
line-height: 52px;
padding-top: 0;
padding-bottom: 0;
margin-left: 2.5%;
transition: 0.4s;
}
.navbar {
background-color: #105565;
position: fixed;
width: 100%;
padding-top: 0px;
padding-bottom: 0px;
transition: 0.4s;
}
.fas {
color: rgba(255, 255, 255, 1.00);
}
}
.navbar-nav {
margin-right: 4.4%;
}
.nav-item {
font-family: 'roboto';
font-size: 14px;
font-weight: 300;
}
#navhome {
color: white;
background: #105565;
padding-top: 28px;
padding-bottom: 28px;
padding-left: 12px;
padding-right: 12px;
}
#navabout {
color: white;
background: #105565;
padding-top: 28px;
padding-bottom: 28px;
padding-left: 12px;
padding-right: 12px;
}
#navport {
color: white;
background: #105565;
padding-top: 28px;
padding-bottom: 28px;
padding-left: 12px;
padding-right: 12px;
}
#navteam {
color: white;
background: #105565;
padding-top: 28px;
padding-bottom: 28px;
padding-left: 12px;
padding-right: 12px;
}
#navcont {
color: white;
background: #105565;
padding-top: 28px;
padding-bottom: 28px;
padding-left: 12px;
padding-right: 12px;
}
#navhome:hover {
color: #105565 !important;
background: white;
padding-top: 28px;
padding-bottom: 28px;
padding-left: 12px;
padding-right: 12px;
}
#navabout:hover {
color: #105565 !important;
background: white;
padding-top: 28px;
padding-bottom: 28px;
padding-left: 12px;
padding-right: 12px;
}
#navport:hover {
color: #105565 !important;
background: white;
padding-top: 28px;
padding-bottom: 28px;
padding-left: 12px;
padding-right: 12px;
}
#navteam:hover {
color: #105565 !important;
background: white;
padding-top: 28px;
padding-bottom: 28px;
padding-left: 12px;
padding-right: 12px;
}
#navcont:hover {
color: #105565 !important;
background: white;
padding-top: 28px;
padding-bottom: 28px;
padding-left: 12px;
padding-right: 12px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="navbar navbar-expand-lg navbar-dark m-0 p-0">
<div class="container-fluid"> <a class="navbar-brand" href="#">Navbar Inc.</a> <button class="navbar-toggler" style="color: rgba(0,0,0,0.00);" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false"
aria-label="Toggle navigation"> <span class="fas fa-bars"></span> </button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav ms-auto mb-2 mb-lg-0">
<li class="nav-item"> <a class="nav-link active" id="navhome" style="color:white;" aria-current="page" href="#">HOME</a> </li>
<li class="nav-item"> <a class="nav-link active" id="navabout" style="color:white;" aria-current="page" href="#">ABOUT</a> </li>
<li class="nav-item"> <a class="nav-link active" id="navport" style="color:white;" aria-current="page" href="#">PORTFOLIO</a> </li>
<li class="nav-item"> <a class="nav-link active" id="navteam" style="color:white;" aria-current="page" href="#">TEAM</a> </li>
<li class="nav-item"> <a class="nav-link active" id="navcont" style="color:white;" aria-current="page" href="#">CONTACT</a> </li>
</ul>
</div>
</div>
</nav></code></pre>
</div>
</div>
</p>
<p>I had the most trouble with getting the white selection boxes (that appear when you hover over each of the nav-links) to cover the entire height of the navbar and the entire width of the nav-item in each responsive size, and with the position of the text in each size. (There are basically four size states: scrolled up or down in a narrow (<1000px) or a wide window.)</p>
<p>By <a href="https://stackoverflow.com/questions/66887886/is-this-navbar-properly-coded-or-way-too-verbose">posting this question in the wrong section</a> (I'm new here), I already got some great suggestions, but more tips to improve this code are very welcome.</p>
<p>It's true that I couldn't find a way to solve the padding conflicts without <code>!important</code>, so if someone can point me in the right direction there, I'd be much obliged.</p>
|
[] |
[
{
"body": "<p>First off, congrats on getting your navbar working and sticking with this over several days! </p>\n<p>There are a lot of things which could be improved, but at a glance the most glaring issue is that your styles are spread all across the HTML, CSS, and JS files. This makes it very difficult to reason about them. Here's how you could simplify the situation and make it easier to work with.</p>\n<ol>\n<li>Remove all <code>style</code> attribute assignments from your HTML and JS - put these style instructions in your CSS classes, instead.</li>\n<li>Replace the style attribute assignments in your JS code with class assignments to simplify things and reduce the number of (expensive!) DOM queries you are running whenever the user scrolls.</li>\n<li>Use media queries to handle all styles dependent on the horizontal size of the viewport. You are already doing this in your CSS (e.g. <code>@media (max-width: 1000px)</code>), but then you're also doing it separately in the JS code which confuses things. Just do it in CSS.</li>\n<li>(Optional) Don't use jQuery. The native web APIs are more than capable of doing what you're achieving with jQuery here, you can simplify a lot by removing it.</li>\n</ol>\n<p>With the above-described changes, here's what your JS might look like:</p>\n<pre><code>// Query just once, and reuse the reference.\nvar navbar = document.querySelector(".navbar");\nvar isScrolledDownClass = "is-scrolled-down";\nvar scrollDownClassThreshold = 50;\n\nwindow.addEventListener("scroll", function() {\n if (!navbar) return; // or treat the failure to query the navbar as an error\n if (window.scrollY >= scrollDownClassThreshold) {\n navbar.classList.add(isScrolledDownClass);\n } else {\n navbar.classList.remove(isScrolledDownClass);\n }\n});\n</code></pre>\n<p>In CSS, you can use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Descendant_combinator\" rel=\"nofollow noreferrer\">descendent combinator</a> to apply styles to children based on the state of their ancestors. This will help you apply certain styles only when the navbar element has the <code>is-scrolled-down</code> class:</p>\n<pre><code>#navabout {\n color: white;\n background: #105565;\n padding-top: 28px;\n padding-bottom: 28px;\n padding-left: 12px;\n padding-right: 12px;\n}\n\n.navbar.is-scrolled-down #navabout {\n padding-bottom: 14px;\n padding-top: 15px;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T12:47:17.177",
"Id": "510629",
"Score": "0",
"body": "Thanks so much! This helps me a lot. I think I understand most of your suggestions. Although I do wonder why you need to add the \"is-scrolled-down\" class through a variable instead of directly. Why not ```navbar.classList.add(\"is-scrolled-down\");```?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T13:14:29.340",
"Id": "510633",
"Score": "1",
"body": "Glad it helps! Feel free to ask if anything is unclear. You don't need use a variable, but I do out of habit for a number of reasons, the most pertinent in this case being that the string is used in two places, so using a variable protects you from a typo in one place and not the other. I habitually try to avoid using special strings directly in code for a number of reasons, [this question](https://softwareengineering.stackexchange.com/questions/365339/what-is-wrong-with-magic-strings) sums it up reasonably well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T13:29:42.817",
"Id": "510634",
"Score": "0",
"body": "Makes sense! Sounds like good practice. There's actually one more line I don't understand: ```if (!navbar) return;``` (nor the comment after it, actually: ```or treat the failure to query the navbar as an error```). What does the exclamation mark mean there, and what is being returned?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T13:43:56.913",
"Id": "510635",
"Score": "2",
"body": "@AlexanderSplat it is the [logical NOT](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT) operator- basically equivalent to a check for `false`, `undefined` or `null` ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T16:02:02.757",
"Id": "510650",
"Score": "1",
"body": "Yes, and to add on to @SᴀᴍOnᴇᴌᴀ's answer this is because of the concept of [truthy/falsy](https://medium.com/jspoint/truthy-vs-falsy-values-in-javascript-b9d9ada08bae) values in JS. WRT the `return` statement, [it returns `undefined`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return#syntax). JS functions often return `undefined` in the absence of a meaningful return value. You can give yourself a good, solid foundation in all this by going through [chapters 1-4](https://eloquentjavascript.net/) of Eloquent JavaScript :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T16:13:22.340",
"Id": "510653",
"Score": "0",
"body": "Thanks for the book recommendation! :D I've cleaned up my code with your suggestions. I still have a few questions, though. It's too much to ask here, I think, so I've posted a [new question](https://codereview.stackexchange.com/questions/258967/web-site-navigation-bar-part-ii) with the changed code."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T06:33:57.610",
"Id": "258953",
"ParentId": "258921",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "258953",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T13:29:33.917",
"Id": "258921",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"html",
"css"
],
"Title": "Web-site navigation bar"
}
|
258921
|
<p>This is a follow up of <a href="https://codereview.stackexchange.com/questions/257451/skyscraper-solver-for-nxn-size-version-3-using-bitmasks/257468?noredirect=1#comment508823_257468">Skyscraper Solver for NxN Size Version 3</a></p>
<p>I know its getting old...</p>
<p>So I still have the same Issue the code is to slow to solve bigger skyscraper puzzles.</p>
<p>Since the last Version I made the following improvements:</p>
<p>-Implement Class ClueHint direktly with Fields</p>
<ul>
<li>I removed unecessary std::optional in <code>ClueHint</code></li>
</ul>
<p>-Class <code>Row</code> now uses Class <code>Board</code> reference to access each field on the board</p>
<ul>
<li>Fields implementation uses still bitmasks. But as suggested in the answers to the old code i inverted the logic. I also tried out to use
<code>std::bitset</code> for <code>Field</code> but that was alot slower so i stayed with a bitmask here.</li>
</ul>
<p>I still wonder is backtracking the fastest solution? Anything else we can try to speed it up?</p>
<p>Here is the code:</p>
<pre><code>#include <algorithm>
#include <cassert>
#include <cstdint>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
namespace codewarsbacktracking {
using BitmaskType = std::uint32_t;
/*
Example size = 4
b0000 0 Impossible
b0001 1 Skyscraper = 1
b0010 2 Skyscraper = 2
b0011 3 Nopes = 3, 4
b0100 4 Skyscraper = 3
b0101 5 Nopes = 2, 4
b0110 6 Nopes = 1, 4
b0111 7 Nopes = 4
b1000 8 Skyscraper = 1
b1001 9 Nopes = 2, 3
b1010 10 Nopes = 1, 3
b1011 11 Nopes = 3
b1100 12 Nopes = 1,2
b1101 13 Nopes = 2
b1110 14 Nopes = 1
b1111 15 Nopes = {}
*/
class Field {
public:
Field() = default;
void insertSkyscraper(int skyscraper);
void insertNope(int nope);
void insertNopes(const std::vector<int> &nopes);
void insertNopes(const Field &field);
int skyscraper(std::size_t size) const;
std::vector<int> nopes(std::size_t size) const;
bool hasSkyscraper() const;
bool containsNope(int value) const;
bool containsNopes(const std::vector<int> &values) const;
private:
bool bitIsToggled(BitmaskType bitmask, int bit) const;
// same as c++20 std::has_single_bit()
bool hasSingleBit(BitmaskType bitmask) const;
BitmaskType mBitmask{static_cast<BitmaskType>(-1)};
friend inline bool operator==(const Field &lhs, const Field &rhs);
friend inline bool operator!=(const Field &lhs, const Field &rhs);
};
inline bool operator==(const Field &lhs, const Field &rhs)
{
return lhs.mBitmask == rhs.mBitmask;
}
inline bool operator!=(const Field &lhs, const Field &rhs)
{
return !(lhs == rhs);
}
void Field::insertSkyscraper(int skyscraper)
{
mBitmask = 1 << (skyscraper - 1);
}
void Field::insertNope(int nope)
{
mBitmask &= ~(1 << (nope - 1));
}
void Field::insertNopes(const std::vector<int> &nopes)
{
for (const auto nope : nopes) {
insertNope(nope);
}
}
void Field::insertNopes(const Field &field)
{
mBitmask &= field.mBitmask;
}
int Field::skyscraper(std::size_t size) const
{
if (!hasSkyscraper()) {
return 0;
}
for (std::size_t i = 0; i < size; ++i) {
if (bitIsToggled(mBitmask, i)) {
return i + 1;
}
}
assert(false);
return 0;
}
std::vector<int> Field::nopes(std::size_t size) const
{
std::vector<int> nopes;
nopes.reserve(size - 1);
for (std::size_t i = 0; i < size; ++i) {
if (!bitIsToggled(mBitmask, i)) {
nopes.emplace_back(i + 1);
}
}
return nopes;
}
bool Field::hasSkyscraper() const
{
return hasSingleBit(mBitmask);
}
bool Field::containsNope(int value) const
{
return !bitIsToggled(mBitmask, value - 1);
}
bool Field::containsNopes(const std::vector<int> &values) const
{
for (const auto &value : values) {
if (!containsNope(value)) {
return false;
}
}
return true;
}
bool Field::bitIsToggled(BitmaskType bitmask, int bit) const
{
return bitmask & (1 << bit);
}
bool Field::hasSingleBit(BitmaskType bitmask) const
{
return bitmask != 0 && (bitmask & (bitmask - 1)) == 0;
}
struct RowClues {
RowClues(std::size_t boardSize);
RowClues() = default;
void reverse();
bool isEmpty() const;
std::vector<Field> fields;
};
RowClues::RowClues(std::size_t boardSize)
: fields{std::vector<Field>(boardSize, Field{})}
{
}
void RowClues::reverse()
{
std::reverse(fields.begin(), fields.end());
}
bool RowClues::isEmpty() const
{
return fields.empty();
}
RowClues getRowClue(int clue, std::size_t boardSize)
{
if (clue == 0) {
return RowClues{};
}
RowClues rowClues{boardSize};
if (clue == static_cast<int>(boardSize)) {
for (std::size_t i = 0; i < boardSize; ++i) {
rowClues.fields[i].insertSkyscraper(i + 1);
}
}
else if (clue == 1) {
rowClues.fields[0].insertSkyscraper(boardSize);
}
else if (clue == 2) {
rowClues.fields[0].insertNope(boardSize);
rowClues.fields[1].insertNope(boardSize - 1);
}
else {
for (std::size_t fieldIdx = 0;
fieldIdx < static_cast<std::size_t>(clue - 1); ++fieldIdx) {
for (std::size_t nopeValue = boardSize;
nopeValue >= (boardSize - (clue - 2) + fieldIdx);
--nopeValue) {
rowClues.fields[fieldIdx].insertNope(nopeValue);
}
}
}
return rowClues;
}
RowClues merge(RowClues frontRowClues, RowClues backRowClues)
{
if (frontRowClues.isEmpty() && backRowClues.isEmpty()) {
return frontRowClues;
}
if (frontRowClues.isEmpty()) {
backRowClues.reverse();
return backRowClues;
}
if (backRowClues.isEmpty()) {
return backRowClues;
}
assert(frontRowClues.fields.size() == backRowClues.fields.size());
backRowClues.reverse();
for (std::size_t i = 0; i < frontRowClues.fields.size(); ++i) {
if (frontRowClues.fields[i].hasSkyscraper()) {
continue;
}
else if (backRowClues.fields[i].hasSkyscraper()) {
frontRowClues.fields[i] = backRowClues.fields[i];
}
else { // only nopes merge nopes
frontRowClues.fields[i].insertNopes(backRowClues.fields[i]);
}
}
return frontRowClues;
}
void mergeClueHintsPerRow(std::vector<RowClues> &rowClues)
{
std::size_t startOffset = rowClues.size() / 4 * 3 - 1;
std::size_t offset = startOffset;
for (std::size_t frontIdx = 0; frontIdx < rowClues.size() / 2;
++frontIdx, offset -= 2) {
if (frontIdx == rowClues.size() / 4) {
offset = startOffset;
}
int backIdx = frontIdx + offset;
rowClues[frontIdx] = merge(rowClues[frontIdx], rowClues[backIdx]);
}
rowClues.erase(rowClues.begin() + rowClues.size() / 2, rowClues.end());
}
std::vector<RowClues> getRowClues(const std::vector<int> &clues,
std::size_t boardSize)
{
std::vector<RowClues> rowClues;
rowClues.reserve(clues.size());
for (const auto &clue : clues) {
rowClues.emplace_back(getRowClue(clue, boardSize));
}
mergeClueHintsPerRow(rowClues);
return rowClues;
}
struct Point {
int x;
int y;
};
inline bool operator==(const Point &lhs, const Point &rhs)
{
return lhs.x == rhs.x && lhs.y == rhs.y;
}
inline bool operator!=(const Point &lhs, const Point &rhs)
{
return !(lhs == rhs);
}
enum class ReadDirection { topToBottom, rightToLeft };
void nextDirection(ReadDirection &readDirection)
{
assert(readDirection != ReadDirection::rightToLeft);
int dir = static_cast<int>(readDirection);
++dir;
readDirection = static_cast<ReadDirection>(dir);
}
void advanceToNextPosition(Point &point, ReadDirection readDirection,
int clueIdx)
{
if (clueIdx == 0) {
return;
}
switch (readDirection) {
case ReadDirection::topToBottom:
++point.x;
break;
case ReadDirection::rightToLeft:
++point.y;
break;
}
}
class BorderIterator {
public:
BorderIterator(std::size_t boardSize);
Point point() const;
ReadDirection readDirection() const;
BorderIterator &operator++();
private:
int mIdx = 0;
std::size_t mBoardSize;
Point mPoint{0, 0};
ReadDirection mReadDirection{ReadDirection::topToBottom};
};
BorderIterator::BorderIterator(std::size_t boardSize) : mBoardSize{boardSize}
{
}
Point BorderIterator::point() const
{
return mPoint;
}
ReadDirection BorderIterator::readDirection() const
{
return mReadDirection;
}
BorderIterator &BorderIterator::operator++()
{
++mIdx;
if (mIdx == static_cast<int>(2 * mBoardSize)) {
return *this;
}
if (mIdx != 0 && mIdx % mBoardSize == 0) {
nextDirection(mReadDirection);
}
advanceToNextPosition(mPoint, mReadDirection, mIdx % mBoardSize);
return *this;
}
class Board;
class Row {
public:
Row(Board &board, const Point &startPoint,
const ReadDirection &readDirection);
void addCrossingRows(Row *crossingRow);
bool hasOnlyOneNopeField() const;
void addLastMissingSkyscraper();
void addNopesToAllNopeFields(int nope);
bool allFieldsContainSkyscraper() const;
int skyscraperCount() const;
int nopeCount(int nope) const;
enum class Direction { front, back };
bool hasSkyscrapers(const std::vector<int> &skyscrapers,
Direction direction) const;
bool hasNopes(const std::vector<std::vector<int>> &nopes,
Direction direction) const;
void addFieldData(const std::vector<Field> &fieldData, Direction direction);
const Field &getFieldRef(std::size_t idx) const;
Field &getFieldRef(std::size_t idx);
private:
template <typename SkyIterator>
bool hasSkyscrapers(SkyIterator skyItBegin, SkyIterator skyItEnd) const;
template <typename NopesIterator>
bool hasNopes(NopesIterator nopesItBegin, NopesIterator nopesItEnd) const;
template <typename FieldDataIterator>
void addFieldData(FieldDataIterator fieldDataItBegin,
FieldDataIterator fieldDataItEnd);
void insertFieldData(std::size_t idx, const Field &fieldData);
void insertSkyscraperNeighbourHandling(std::size_t idx, int skyscraper);
void insertNopesNeighbourHandling(std::size_t idx, int nopes,
bool hadSkyscraperBefore);
bool onlyOneFieldWithoutNope(int nope) const;
bool nopeExistsAsSkyscraperInFields(int nope) const;
std::optional<int> nopeValueInAllButOneField() const;
void insertSkyscraperToFirstFieldWithoutNope(int nope);
bool hasSkyscraper(int skyscraper) const;
// Field &getFieldRef(std::size_t idx);
Board &mBoard;
Point mStartPoint;
ReadDirection mReadDirection;
std::vector<Row *> mCrossingRows;
};
class Board {
public:
Board(std::size_t size);
void insert(const std::vector<RowClues> &rowClues);
void insert(const std::vector<std::vector<int>> &startingSkyscrapers);
bool isSolved() const;
std::vector<Field> fields;
std::vector<Row> mRows;
std::vector<std::vector<int>> skyscrapers2d() const;
std::size_t size() const;
private:
void makeRows();
void connnectRowsWithCrossingRows();
std::size_t mSize;
};
template <typename It> int missingNumberInSequence(It begin, It end)
{
int n = std::distance(begin, end) + 1;
double projectedSum = (n + 1) * (n / 2.0);
int actualSum = std::accumulate(begin, end, 0);
return projectedSum - actualSum;
}
Row::Row(Board &board, const Point &startPoint,
const ReadDirection &readDirection)
: mBoard{board}, mStartPoint{startPoint}, mReadDirection{readDirection}
{
}
void Row::addCrossingRows(Row *crossingRow)
{
assert(crossingRow != nullptr);
assert(mCrossingRows.size() < mBoard.size());
mCrossingRows.push_back(crossingRow);
}
bool Row::hasOnlyOneNopeField() const
{
return skyscraperCount() == static_cast<int>(mBoard.size() - 1);
}
void Row::addLastMissingSkyscraper()
{
assert(hasOnlyOneNopeField());
std::vector<int> sequence;
sequence.reserve(mBoard.size() - 1);
std::size_t nopeFieldIdx = -1;
for (std::size_t idx = 0; idx < mBoard.size(); ++idx) {
if (getFieldRef(idx).hasSkyscraper()) {
sequence.emplace_back((getFieldRef(idx)).skyscraper(mBoard.size()));
}
else {
nopeFieldIdx = idx;
}
}
assert(nopeFieldIdx != -1);
assert(skyscraperCount() == static_cast<int>(sequence.size()));
auto missingValue =
missingNumberInSequence(sequence.begin(), sequence.end());
assert(missingValue >= 0 &&
missingValue <= static_cast<int>(mBoard.size()));
(getFieldRef(nopeFieldIdx)).insertSkyscraper(missingValue);
insertSkyscraperNeighbourHandling(nopeFieldIdx, missingValue);
}
void Row::addNopesToAllNopeFields(int nope)
{
for (std::size_t idx = 0; idx < mBoard.size(); ++idx) {
if (getFieldRef(idx).hasSkyscraper()) {
continue;
}
bool hasSkyscraperBefore = false;
getFieldRef(idx).insertNope(nope);
insertNopesNeighbourHandling(idx, nope, hasSkyscraperBefore);
}
}
bool Row::allFieldsContainSkyscraper() const
{
return skyscraperCount() == static_cast<int>(mBoard.size());
}
int Row::skyscraperCount() const
{
int count = 0;
for (std::size_t i = 0; i < mBoard.size(); ++i) {
if (getFieldRef(i).hasSkyscraper()) {
++count;
}
}
return count;
}
int Row::nopeCount(int nope) const
{
int count = 0;
for (std::size_t i = 0; i < mBoard.size(); ++i) {
if (getFieldRef(i).hasSkyscraper()) {
continue;
}
if (getFieldRef(i).containsNope(nope)) {
++count;
}
}
return count;
}
bool Row::hasSkyscrapers(const std::vector<int> &skyscrapers,
Row::Direction direction) const
{
if (direction == Direction::front) {
return hasSkyscrapers(skyscrapers.cbegin(), skyscrapers.cend());
}
return hasSkyscrapers(skyscrapers.crbegin(), skyscrapers.crend());
}
bool Row::hasNopes(const std::vector<std::vector<int>> &nopes,
Direction direction) const
{
if (direction == Direction::front) {
return hasNopes(nopes.cbegin(), nopes.cend());
}
return hasNopes(nopes.crbegin(), nopes.crend());
}
void Row::addFieldData(const std::vector<Field> &fieldData, Direction direction)
{
if (direction == Direction::front) {
addFieldData(fieldData.begin(), fieldData.end());
}
else {
addFieldData(fieldData.rbegin(), fieldData.rend());
}
}
template <typename SkyIterator>
bool Row::hasSkyscrapers(SkyIterator skyItBegin, SkyIterator skyItEnd) const
{
for (auto skyIt = skyItBegin; skyIt != skyItEnd; ++skyIt) {
auto idx = std::distance(skyItBegin, skyIt);
if (*skyIt == 0 && getFieldRef(idx).hasSkyscraper()) {
continue;
}
if (getFieldRef(idx).skyscraper(mBoard.size()) != *skyIt) {
return false;
}
}
return true;
}
template <typename NopesIterator>
bool Row::hasNopes(NopesIterator nopesItBegin, NopesIterator nopesItEnd) const
{
for (auto nopesIt = nopesItBegin; nopesIt != nopesItEnd; ++nopesIt) {
if (nopesIt->empty()) {
continue;
}
auto idx = std::distance(nopesItBegin, nopesIt);
if (getFieldRef(idx).hasSkyscraper()) {
return false;
}
if (!getFieldRef(idx).containsNopes(*nopesIt)) {
return false;
}
}
return true;
}
template <typename FieldDataIterator>
void Row::addFieldData(FieldDataIterator fieldDataItBegin,
FieldDataIterator fieldDataItEnd)
{
for (auto fieldDataIt = fieldDataItBegin; fieldDataIt != fieldDataItEnd;
++fieldDataIt) {
auto idx = std::distance(fieldDataItBegin, fieldDataIt);
insertFieldData(idx, *fieldDataIt);
}
}
const Field &Row::getFieldRef(std::size_t idx) const
{
assert(idx >= 0 && idx < mBoard.size());
if (mReadDirection == ReadDirection::topToBottom) {
return mBoard
.fields[mStartPoint.x + (mStartPoint.y + idx) * mBoard.size()];
}
return mBoard.fields[mStartPoint.x - idx + (mStartPoint.y) * mBoard.size()];
}
void Row::insertFieldData(std::size_t idx, const Field &fieldData)
{
if (fieldData.hasSkyscraper()) {
if (getFieldRef(idx).hasSkyscraper()) {
return;
}
getFieldRef(idx) = fieldData;
insertSkyscraperNeighbourHandling(
idx, getFieldRef(idx).skyscraper(mBoard.size()));
}
else {
bool hasSkyscraperBefore = getFieldRef(idx).hasSkyscraper();
getFieldRef(idx).insertNopes(fieldData);
auto nopes = fieldData.nopes(mBoard.size());
for (const auto &nope : nopes) {
insertNopesNeighbourHandling(idx, nope, hasSkyscraperBefore);
}
}
}
void Row::insertSkyscraperNeighbourHandling(std::size_t idx, int skyscraper)
{
if (hasOnlyOneNopeField()) {
addLastMissingSkyscraper();
}
addNopesToAllNopeFields(skyscraper);
if (mCrossingRows[idx]->hasOnlyOneNopeField()) {
mCrossingRows[idx]->addLastMissingSkyscraper();
}
mCrossingRows[idx]->addNopesToAllNopeFields(skyscraper);
}
void Row::insertNopesNeighbourHandling(std::size_t idx, int nope,
bool hadSkyscraperBefore)
{
// skyscraper was added so we have to add nopes to the neighbours
if (!hadSkyscraperBefore && getFieldRef(idx).hasSkyscraper()) {
insertSkyscraperNeighbourHandling(
idx, getFieldRef(idx).skyscraper(mBoard.size()));
}
if (onlyOneFieldWithoutNope(nope)) {
insertSkyscraperToFirstFieldWithoutNope(nope);
}
if (mCrossingRows[idx]->onlyOneFieldWithoutNope(nope)) {
mCrossingRows[idx]->insertSkyscraperToFirstFieldWithoutNope(nope);
}
}
bool Row::onlyOneFieldWithoutNope(int nope) const
{
if (nopeExistsAsSkyscraperInFields(nope)) {
return false;
}
if (nopeCount(nope) <
static_cast<int>(mBoard.size()) - skyscraperCount() - 1) {
return false;
}
return true;
}
bool Row::nopeExistsAsSkyscraperInFields(int nope) const
{
for (std::size_t idx = 0; idx < mBoard.size(); ++idx) {
if (getFieldRef(idx).skyscraper(mBoard.size()) == nope) {
return true;
}
}
return false;
}
std::optional<int> Row::nopeValueInAllButOneField() const
{
std::unordered_map<int, int> nopeAndCount;
for (std::size_t i = 0; i < mBoard.size(); ++i) {
if (!getFieldRef(i).hasSkyscraper()) {
auto nopes = getFieldRef(i).nopes(mBoard.size());
for (const auto &nope : nopes) {
if (hasSkyscraper(nope)) {
continue;
}
++nopeAndCount[nope];
}
}
}
for (auto cit = nopeAndCount.cbegin(); cit != nopeAndCount.end(); ++cit) {
if (cit->second ==
static_cast<int>(mBoard.size()) - skyscraperCount() - 1) {
return {cit->first};
}
}
return {};
}
void Row::insertSkyscraperToFirstFieldWithoutNope(int nope)
{
for (std::size_t idx = 0; idx < mBoard.size(); ++idx) {
if ((getFieldRef(idx)).hasSkyscraper()) {
continue;
}
if (!(getFieldRef(idx)).containsNope(nope)) {
(getFieldRef(idx).insertSkyscraper(nope));
insertSkyscraperNeighbourHandling(idx, nope);
return; // there can be max one skyscraper per row;
}
}
}
bool Row::hasSkyscraper(int skyscraper) const
{
for (std::size_t i = 0; i < mBoard.size(); ++i) {
if (getFieldRef(i).skyscraper(mBoard.size()) == skyscraper) {
return true;
}
}
return false;
}
Field &Row::getFieldRef(std::size_t idx)
{
assert(idx >= 0 && idx < mBoard.size());
if (mReadDirection == ReadDirection::topToBottom) {
return mBoard
.fields[mStartPoint.x + (mStartPoint.y + idx) * mBoard.size()];
}
return mBoard.fields[mStartPoint.x - idx + (mStartPoint.y) * mBoard.size()];
}
Board::Board(std::size_t size)
: fields{std::vector<Field>(size * size, Field{})}, mSize{size}
{
makeRows();
}
void Board::insert(const std::vector<RowClues> &rowClues)
{
assert(rowClues.size() == mRows.size());
for (std::size_t i = 0; i < rowClues.size(); ++i) {
if (rowClues[i].isEmpty()) {
continue;
}
mRows[i].addFieldData(rowClues[i].fields, Row::Direction::front);
}
}
void Board::insert(const std::vector<std::vector<int>> &startingSkyscrapers)
{
if (startingSkyscrapers.empty()) {
return;
}
std::size_t boardSize = mRows.size() / 2;
assert(startingSkyscrapers.size() == boardSize);
for (std::size_t i = 0; i < startingSkyscrapers.size(); ++i) {
// ugly glue code probaly better to set skyscrapers directly in the
// fields
std::vector<Field> fields(startingSkyscrapers[i].size());
for (std::size_t fieldIdx = 0; fieldIdx < fields.size(); ++fieldIdx) {
if (startingSkyscrapers[i][fieldIdx] == 0) {
continue;
}
fields[fieldIdx].insertSkyscraper(startingSkyscrapers[i][fieldIdx]);
}
mRows[i + boardSize].addFieldData(fields, Row::Direction::back);
}
}
bool Board::isSolved() const
{
std::size_t endVerticalRows = mRows.size() / 2;
for (std::size_t i = 0; i < endVerticalRows; ++i) {
if (!mRows[i].allFieldsContainSkyscraper()) {
return false;
}
}
return true;
}
std::vector<std::vector<int>> Board::skyscrapers2d() const
{
std::vector<std::vector<int>> skyscrapers2d(mSize, std::vector<int>());
std::size_t j = 0;
skyscrapers2d[j].reserve(mSize);
for (std::size_t i = 0; i < fields.size(); ++i) {
if (i != 0 && i % mSize == 0) {
++j;
skyscrapers2d[j].reserve(mSize);
}
skyscrapers2d[j].emplace_back(fields[i].skyscraper(mSize));
}
return skyscrapers2d;
}
std::size_t Board::size() const
{
return mSize;
}
void Board::makeRows()
{
BorderIterator borderIterator{mSize};
std::size_t rowSize = mSize * 2;
mRows.reserve(rowSize);
for (std::size_t i = 0; i < rowSize; ++i, ++borderIterator) {
mRows.emplace_back(
Row{*this, borderIterator.point(), borderIterator.readDirection()});
}
connnectRowsWithCrossingRows();
}
void Board::connnectRowsWithCrossingRows()
{
std::size_t boardSize = mRows.size() / 2;
std::vector<int> targetRowsIdx(boardSize);
std::iota(targetRowsIdx.begin(), targetRowsIdx.end(), boardSize);
for (std::size_t i = 0; i < mRows.size(); ++i) {
if (i == mRows.size() / 2) {
std::iota(targetRowsIdx.begin(), targetRowsIdx.end(), 0);
std::reverse(targetRowsIdx.begin(), targetRowsIdx.end());
}
for (const auto &targetRowIdx : targetRowsIdx) {
mRows[i].addCrossingRows(&mRows[targetRowIdx]);
}
}
}
void debug_print(Board &board, const std::string &title)
{
std::cout << title << '\n';
for (std::size_t i = 0; i < board.fields.size(); ++i) {
if (i % board.size() == 0 && i != 0) {
std::cout << '\n';
}
auto elementSize = board.size() * 2;
std::string element;
element.reserve(elementSize);
if (board.fields[i].skyscraper(board.size()) != 0) {
element =
"V" + std::to_string(board.fields[i].skyscraper(board.size()));
}
else if (board.fields[i].skyscraper(board.size()) == 0 &&
!board.fields[i].nopes(board.size()).empty()) {
auto nopes_set = board.fields[i].nopes(board.size());
std::vector<int> nopes(nopes_set.begin(), nopes_set.end());
std::sort(nopes.begin(), nopes.end());
for (std::size_t i = 0; i < nopes.size(); ++i) {
element.append(std::to_string(nopes[i]));
if (i != nopes.size() - 1) {
element.push_back(',');
}
}
}
element.resize(elementSize, ' ');
std::cout << element;
}
std::cout << '\n';
}
bool rowsAreValid(const std::vector<Field> &fields, std::size_t index,
std::size_t rowSize)
{
std::size_t row = index / rowSize;
for (std::size_t currIndex = row * rowSize; currIndex < (row + 1) * rowSize;
++currIndex) {
if (currIndex == index) {
continue;
}
if (fields[currIndex].skyscraper(rowSize) ==
fields[index].skyscraper(rowSize)) {
return false;
}
}
return true;
}
bool columnsAreValid(const std::vector<Field> &fields, std::size_t index,
std::size_t rowSize)
{
std::size_t column = index % rowSize;
for (std::size_t i = 0; i < rowSize; ++i) {
std::size_t currIndex = column + i * rowSize;
if (currIndex == index) {
continue;
}
if (fields[currIndex].skyscraper(rowSize) ==
fields[index].skyscraper(rowSize)) {
return false;
}
}
return true;
}
template <typename FieldIterator>
int visibleBuildings(FieldIterator begin, FieldIterator end,
std::size_t rowSize)
{
int visibleBuildingsCount = 0;
int highestSeen = 0;
for (auto it = begin; it != end; ++it) {
if (it->skyscraper(rowSize) != 0 &&
it->skyscraper(rowSize) > highestSeen) {
++visibleBuildingsCount;
highestSeen = it->skyscraper(rowSize);
}
}
return visibleBuildingsCount;
}
std::tuple<int, int> getCluesInRow(const std::vector<int> &clues,
std::size_t row, std::size_t rowSize)
{
int frontClue = clues[clues.size() - 1 - row];
int backClue = clues[rowSize + row];
return {frontClue, backClue};
}
bool cluesInRowAreValid(const std::vector<Field> &fields,
const std::vector<int> &clues, std::size_t index,
std::size_t rowSize)
{
std::size_t row = index / rowSize;
auto [frontClue, backClue] = getCluesInRow(clues, row, rowSize);
if (frontClue == 0 && backClue == 0) {
return true;
}
std::size_t rowIndexBegin = row * rowSize;
std::size_t rowIndexEnd = (row + 1) * rowSize;
auto citBegin = fields.cbegin() + rowIndexBegin;
auto citEnd = fields.cbegin() + rowIndexEnd;
bool rowIsFull = std::find_if(citBegin, citEnd, [](const Field &field) {
return !field.hasSkyscraper();
}) == citEnd;
if (!rowIsFull) {
return true;
}
if (frontClue != 0) {
auto frontVisible = visibleBuildings(citBegin, citEnd, rowSize);
if (frontClue != frontVisible) {
return false;
}
}
auto critBegin = std::make_reverse_iterator(citEnd);
auto critEnd = std::make_reverse_iterator(citBegin);
if (backClue != 0) {
auto backVisible = visibleBuildings(critBegin, critEnd, rowSize);
if (backClue != backVisible) {
return false;
}
}
return true;
}
std::tuple<int, int> getCluesInColumn(const std::vector<int> &clues,
std::size_t column, std::size_t rowSize)
{
int frontClue = clues[column];
int backClue = clues[rowSize * 3 - 1 - column];
return {frontClue, backClue};
}
bool cluesInColumnAreValid(const std::vector<Field> &fields,
const std::vector<int> &clues, std::size_t index,
std::size_t rowSize)
{
std::size_t column = index % rowSize;
auto [frontClue, backClue] = getCluesInColumn(clues, column, rowSize);
if (frontClue == 0 && backClue == 0) {
return true;
}
std::vector<Field> verticalFields;
verticalFields.reserve(rowSize);
for (std::size_t i = 0; i < rowSize; ++i) {
verticalFields.emplace_back(fields[column + i * rowSize]);
}
bool columnIsFull =
std::find_if(verticalFields.cbegin(), verticalFields.cend(),
[](const Field &field) {
return !field.hasSkyscraper();
}) == verticalFields.cend();
if (!columnIsFull) {
return true;
}
if (frontClue != 0) {
auto frontVisible = visibleBuildings(verticalFields.cbegin(),
verticalFields.cend(), rowSize);
if (frontClue != frontVisible) {
return false;
}
}
if (backClue != 0) {
auto backVisible = visibleBuildings(verticalFields.crbegin(),
verticalFields.crend(), rowSize);
if (backClue != backVisible) {
return false;
}
}
return true;
}
bool skyscrapersAreValidPositioned(const std::vector<Field> &fields,
const std::vector<int> &clues,
std::size_t index, std::size_t rowSize)
{
if (!rowsAreValid(fields, index, rowSize)) {
return false;
}
if (!columnsAreValid(fields, index, rowSize)) {
return false;
}
if (!cluesInRowAreValid(fields, clues, index, rowSize)) {
return false;
}
if (!cluesInColumnAreValid(fields, clues, index, rowSize)) {
return false;
}
return true;
}
bool guessSkyscrapers(Board &board, const std::vector<int> &clues,
std::size_t index, std::size_t countOfElements,
std::size_t rowSize)
{
if (index == countOfElements) {
return true;
}
if (board.fields[index].hasSkyscraper()) {
if (!skyscrapersAreValidPositioned(board.fields, clues, index,
rowSize)) {
return false;
}
if (guessSkyscrapers(board, clues, index + 1, countOfElements,
rowSize)) {
return true;
}
return false;
}
auto oldField = board.fields[index];
for (int trySkyscraper = 1; trySkyscraper <= static_cast<int>(rowSize);
++trySkyscraper) {
if (board.fields[index].containsNope(trySkyscraper)) {
continue;
}
board.fields[index].insertSkyscraper(trySkyscraper);
if (!skyscrapersAreValidPositioned(board.fields, clues, index,
rowSize)) {
board.fields[index] = oldField;
continue;
}
if (guessSkyscrapers(board, clues, index + 1, countOfElements,
rowSize)) {
return true;
}
board.fields[index] = oldField;
}
board.fields[index] = oldField;
return false;
}
void solveBoard(Board &board, const std::vector<int> &clues)
{
guessSkyscrapers(board, clues, 0, board.fields.size(), board.size());
}
std::vector<std::vector<int>>
SolvePuzzle(const std::vector<int> &clues,
std::vector<std::vector<int>> startingGrid, int)
{
assert(clues.size() % 4 == 0);
std::size_t boardSize = clues.size() / 4;
auto rowClues = getRowClues(clues, boardSize);
Board board{boardSize};
board.insert(rowClues);
board.insert(startingGrid);
if (board.isSolved()) {
return board.skyscrapers2d();
}
solveBoard(board, clues);
return board.skyscrapers2d();
}
std::vector<std::vector<int>> SolvePuzzle(const std::vector<int> &clues)
{
return SolvePuzzle(clues, std::vector<std::vector<int>>{}, 0);
}
} // namespace codewarsbacktracking
</code></pre>
<p>I also like to include some unit tests. Here I list all the unit tests which are currently to slow. With the start clues these boards are not very filled out. Because of that the backtracking needs to insert many many times to come an solution. Is it even possible to get this faster?</p>
<pre><code>#include <gmock/gmock-matchers.h>
#include <gtest/gtest.h>
#include "../Skyscrapers/codewarsbacktracking.h"
#include <vector>
using namespace testing;
struct TestSkyscraperProvider {
std::vector<int> clues;
std::vector<std::vector<int>> result;
};
TestSkyscraperProvider sky6_medium{
{0, 0, 0, 2, 2, 0, 0, 0, 0, 6, 3, 0, 0, 4, 0, 0, 0, 0, 4, 4, 0, 3, 0, 0},
{{{5, 6, 1, 4, 3, 2},
{4, 1, 3, 2, 6, 5},
{2, 3, 6, 1, 5, 4},
{6, 5, 4, 3, 2, 1},
{1, 2, 5, 6, 4, 3},
{3, 4, 2, 5, 1, 6}}}};
TestSkyscraperProvider sky6_hard{
{0, 3, 0, 5, 3, 4, 0, 0, 0, 0, 0, 1, 0, 3, 0, 3, 2, 3, 3, 2, 0, 3, 1, 0},
{{{5, 2, 6, 1, 4, 3},
{6, 4, 3, 2, 5, 1},
{3, 1, 5, 4, 6, 2},
{2, 6, 1, 5, 3, 4},
{4, 3, 2, 6, 1, 5},
{1, 5, 4, 3, 2, 6}}}};
TestSkyscraperProvider sky6_random_2{
{4, 1, 0, 0, 3, 0, 0, 2, 1, 0, 6, 0, 2, 0, 2, 4, 0, 0, 0, 0, 0, 0, 0, 0},
{{{2, 6, 1, 5, 3, 4},
{3, 4, 6, 2, 1, 5},
{4, 2, 3, 1, 5, 6},
{1, 3, 5, 6, 4, 2},
{6, 5, 4, 3, 2, 1},
{5, 1, 2, 4, 6, 3}}}};
TestSkyscraperProvider sky7_medium{{7, 0, 0, 0, 2, 2, 3, 0, 0, 3, 0, 0, 0, 0,
3, 0, 3, 0, 0, 5, 0, 0, 0, 0, 0, 5, 0, 4},
{{{1, 5, 6, 7, 4, 3, 2},
{2, 7, 4, 5, 3, 1, 6},
{3, 4, 5, 6, 7, 2, 1},
{4, 6, 3, 1, 2, 7, 5},
{5, 3, 1, 2, 6, 4, 7},
{6, 2, 7, 3, 1, 5, 4},
{7, 1, 2, 4, 5, 6, 3}}}};
TestSkyscraperProvider sky7_very_hard{{0, 0, 5, 0, 0, 0, 6, 4, 0, 0,
2, 0, 2, 0, 0, 5, 2, 0, 0, 0,
5, 0, 3, 0, 5, 0, 0, 3},
{{{3, 4, 1, 7, 6, 5, 2},
{7, 1, 2, 5, 4, 6, 3},
{6, 3, 5, 2, 1, 7, 4},
{1, 2, 3, 6, 7, 4, 5},
{5, 7, 6, 4, 2, 3, 1},
{4, 5, 7, 1, 3, 2, 6},
{2, 6, 4, 3, 5, 1, 7}}}};
TestSkyscraperProvider sky7_random{{0, 5, 0, 5, 0, 2, 0, 0, 0, 0, 4, 0, 0, 3,
6, 4, 0, 2, 0, 0, 3, 0, 3, 3, 3, 0, 0, 4},
{{{2, 3, 6, 1, 4, 5, 7},
{7, 1, 5, 2, 3, 4, 6},
{6, 4, 2, 3, 1, 7, 5},
{4, 5, 7, 6, 2, 3, 1},
{3, 2, 1, 5, 7, 6, 4},
{1, 6, 4, 7, 5, 2, 3},
{5, 7, 3, 4, 6, 1, 2}}}};
struct TestDataPartialProvider {
std::vector<int> clues;
std::vector<std::vector<int>> result;
std::vector<std::vector<int>> board{};
};
TestDataPartialProvider sky8_hard_partial{{3, 0, 4, 3, 3, 0, 3, 2, 0, 0, 2,
4, 0, 4, 1, 5, 0, 4, 0, 3, 0, 0,
4, 3, 0, 0, 0, 3, 3, 4, 0, 3},
{{1, 6, 2, 4, 3, 8, 5, 7},
{6, 8, 5, 2, 4, 1, 7, 3},
{2, 3, 7, 5, 8, 4, 1, 6},
{3, 1, 6, 8, 7, 5, 2, 4},
{4, 7, 1, 6, 5, 3, 8, 2},
{8, 2, 4, 3, 1, 7, 6, 5},
{7, 5, 3, 1, 2, 6, 4, 8},
{5, 4, 8, 7, 6, 2, 3, 1}},
{{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 5, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 0, 0, 0, 0, 0, 4},
{0, 0, 1, 6, 5, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 3, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 1}}};
TestDataPartialProvider sky11_medium_partial{
{3, 2, 2, 3, 1, 4, 4, 3, 5, 2, 6, 5, 2, 3, 3, 2, 2, 1, 4, 3, 3, 5,
4, 4, 3, 2, 1, 5, 3, 4, 3, 3, 2, 2, 4, 3, 3, 5, 3, 3, 2, 1, 3, 4},
{{6, 8, 10, 5, 11, 3, 7, 9, 4, 2, 1},
{9, 5, 6, 10, 7, 2, 1, 4, 8, 11, 3},
{11, 2, 7, 8, 1, 4, 6, 3, 9, 10, 5},
{3, 11, 2, 4, 5, 6, 9, 7, 10, 1, 8},
{8, 10, 3, 7, 9, 11, 4, 1, 2, 5, 6},
{5, 4, 9, 2, 8, 1, 3, 6, 11, 7, 10},
{2, 7, 1, 9, 4, 10, 8, 5, 3, 6, 11},
{4, 1, 5, 11, 3, 9, 10, 2, 6, 8, 7},
{1, 3, 11, 6, 2, 8, 5, 10, 7, 4, 9},
{7, 6, 8, 3, 10, 5, 2, 11, 1, 9, 4},
{10, 9, 4, 1, 6, 7, 11, 8, 5, 3, 2}},
{{0, 8, 0, 0, 0, 3, 0, 0, 0, 2, 0},
{0, 0, 0, 0, 7, 2, 0, 0, 0, 0, 3},
{0, 0, 7, 0, 0, 0, 6, 0, 0, 10, 0},
{0, 11, 0, 4, 0, 0, 0, 0, 10, 1, 8},
{8, 0, 0, 7, 0, 0, 0, 1, 2, 0, 6},
{0, 4, 0, 0, 8, 1, 0, 0, 0, 7, 0},
{2, 0, 0, 0, 4, 0, 8, 5, 3, 0, 0},
{0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{1, 3, 11, 0, 2, 0, 0, 10, 0, 4, 0},
{0, 0, 0, 3, 10, 5, 0, 11, 0, 0, 0},
{0, 0, 4, 0, 0, 0, 0, 0, 0, 3, 0}}};
TestDataPartialProvider sky11_medium_partial_2{
{1, 2, 2, 5, 3, 2, 5, 3, 5, 4, 3, 4, 2, 3, 1, 2, 3, 2, 4, 3, 4, 4,
3, 4, 3, 2, 3, 5, 3, 1, 2, 3, 3, 3, 3, 2, 3, 5, 2, 5, 3, 4, 2, 1},
{{11, 9, 10, 5, 8, 6, 2, 4, 1, 3, 7},
{9, 1, 3, 8, 7, 11, 6, 5, 2, 4, 10},
{6, 2, 1, 7, 3, 9, 8, 11, 5, 10, 4},
{7, 6, 4, 2, 10, 8, 1, 3, 9, 5, 11},
{2, 7, 6, 9, 4, 10, 3, 8, 11, 1, 5},
{4, 11, 2, 6, 9, 5, 10, 1, 3, 7, 8},
{1, 4, 7, 10, 2, 3, 5, 6, 8, 11, 9},
{3, 8, 5, 4, 11, 7, 9, 2, 10, 6, 1},
{10, 5, 8, 1, 6, 2, 11, 7, 4, 9, 3},
{5, 10, 11, 3, 1, 4, 7, 9, 6, 8, 2},
{8, 3, 9, 11, 5, 1, 4, 10, 7, 2, 6}},
{{0, 0, 10, 0, 8, 0, 2, 0, 1, 0, 0},
{0, 0, 0, 0, 7, 11, 0, 5, 0, 0, 0},
{0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 4},
{0, 0, 0, 0, 0, 0, 1, 3, 9, 0, 0},
{0, 0, 6, 0, 4, 0, 3, 0, 11, 1, 0},
{0, 0, 0, 6, 9, 0, 0, 1, 3, 0, 8},
{0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 9},
{0, 0, 0, 4, 11, 0, 0, 0, 0, 0, 1},
{10, 0, 8, 1, 0, 2, 11, 7, 4, 0, 0},
{5, 10, 0, 0, 0, 0, 0, 0, 0, 8, 0},
{0, 0, 9, 0, 5, 0, 0, 0, 7, 0, 6}}};
TEST(CodewarsBacktracking, sky6_medium)
{
EXPECT_EQ(codewarsbacktracking::SolvePuzzle(sky6_medium.clues),
sky6_medium.result);
}
TEST(CodewarsBacktracking, sky6_hard)
{
EXPECT_EQ(codewarsbacktracking::SolvePuzzle(sky6_hard.clues),
sky6_hard.result);
}
TEST(CodewarsBacktracking, sky6_random_2)
{
EXPECT_EQ(codewarsbacktracking::SolvePuzzle(sky6_random_2.clues),
sky6_random_2.result);
}
TEST(CodewarsBacktracking, sky7_medium)
{
EXPECT_EQ(codewarsbacktracking::SolvePuzzle(sky7_medium.clues),
sky7_medium.result);
}
TEST(CodewarsBacktracking, sky7_very_hard)
{
EXPECT_EQ(codewarsbacktracking::SolvePuzzle(sky7_very_hard.clues),
sky7_very_hard.result);
}
TEST(CodewarsBacktracking, sky7_random)
{
EXPECT_EQ(codewarsbacktracking::SolvePuzzle(sky7_random.clues),
sky7_random.result);
}
TEST(CodewarsBacktracking, sky8_hard_partial)
{
EXPECT_EQ(codewarsbacktracking::SolvePuzzle(sky8_hard_partial.clues,
sky8_hard_partial.board,
sky8_hard_partial.board.size()),
sky8_hard_partial.result);
}
TEST(CodewarsBacktracking, sky11_medium_partial)
{
EXPECT_EQ(codewarsbacktracking::SolvePuzzle(
sky11_medium_partial.clues, sky11_medium_partial.board,
sky11_medium_partial.board.size()),
sky11_medium_partial.result);
}
TEST(CodewarsBacktracking, sky11_medium_partial_2)
{
EXPECT_EQ(codewarsbacktracking::SolvePuzzle(
sky11_medium_partial_2.clues, sky11_medium_partial_2.board,
sky11_medium_partial_2.board.size()),
sky11_medium_partial_2.result);
}
int main(int argc, char *argv[])
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
</code></pre>
<p>Edit:</p>
<p>Please let me know if there is a faster way to solve the issue than with backtracking. There was already another method mentioned in the comments but no real explanation how it could work.</p>
<p>So the question is do I need another algorithm to solve the puzzle faster or just optimize more on the backtracking implementation?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T13:56:05.343",
"Id": "510833",
"Score": "0",
"body": "I didn't read very carefully what the problem is, but it appears to be some kind of a puzzle (like Sudoku or something similar). You could borrow ideas for solving constraint satisfaction (CSP) problems or SAT (= Boolean satisfiability) to find faster methods than (naive) backtracking. For instance, when modeling Sudoku as a CSP, there are very effective heuristics such as *minimum remaining values* and *least-constraining value* etc. along with consistency enforcing methods (like AC-3)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T16:32:07.787",
"Id": "510903",
"Score": "0",
"body": "Sounds all interesting but I would lile some explanation what I can do regarding the skyscraper problem. Currently with backtracking I run through all the possible combinations left from the initial clues I get"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T14:58:31.563",
"Id": "511170",
"Score": "0",
"body": "I read on the sudoku CSP in this article: https://medium.com/my-udacity-ai-nanodegree-notes/solving-sudoku-think-constraint-satisfaction-problem-75763f0742c9 So if I understand correctly backtracking is the right way but I should select were to start trying out the numbers? At the moment I just insert all the numbers beginning on Point 0,0 and traverse linear all the field. So maybe there has to be a better way?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T15:11:42.840",
"Id": "511171",
"Score": "0",
"body": "Well, I'm not saying \"backtracking is the right way\", but I am saying that you can presumably speed up backtracking considerably by considering the order in which you try values. This part is exactly as you observed. These heuristics usually follow the principle of \"fail fast\", or \"in order to succeed, you must fail quickly\". It's also easy to imagine what would happen if you had a perfect oracle for telling you in which order to try values: you would solve the instance in an instant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T18:05:41.813",
"Id": "511192",
"Score": "0",
"body": "So I could sort the fields by the fields with the less remaining possible options and traverse them first in the backtracking. very interesting idea. I think the algorithm for that should be almost the same as in sudoku."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T18:25:50.027",
"Id": "511194",
"Score": "0",
"body": "Yes, I definitely suggest you give it a try."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T16:46:10.427",
"Id": "258925",
"Score": "1",
"Tags": [
"c++",
"performance",
"c++17"
],
"Title": "Skyscraper Solver for NxN Size Version 4"
}
|
258925
|
<p>Here is the problem.</p>
<p><em>Repeatedly ask the user to enter game scores in a format like team1 score1 - team2 score2. Store this information in a dictionary where the keys are the team names and the values are tuples of the form (wins, losses).</em></p>
<p>Here is my Solution, what can I change for the better in it?</p>
<pre><code>number_of_games = int(input("Enter the total number of Games: "))
team_wins_and_loses = {}
for _ in range(number_of_games):
team1, score1, __, team2, score2 = input("Enter the game results(Note that the name of the team must be a single word, without spaces):").split()
team1_result, team2_result = ((1, 0), (0, 1)) if int(score1) > int(score2) else ((0, 1), (1, 0))
if team1 not in team_wins_and_loses:
team_wins_and_loses[team1] = team1_result
else:
updated_result = (team_wins_and_loses[team1][0] + team1_result[0], team_wins_and_loses[team1][1] + team1_result[1])
team_wins_and_loses[team1] = updated_result
if team2 not in team_wins_and_loses:
team_wins_and_loses[team2] = team2_result
else:
updated_result = (team_wins_and_loses[team2][0] + team2_result[0], team_wins_and_loses[team2][1] + team2_result[1])
team_wins_and_loses[team2] = updated_result
print(team_wins_and_loses)
</code></pre>
|
[] |
[
{
"body": "<p><strong>add_tuples</strong></p>\n<p>Since you need <code>tuple[int, int] + tuple[int, int]</code> multiple times, I'd put it into a simple function. This will make the rest of your code more concise and readable.</p>\n<pre><code>def add_tuples(tuple1: tuple[int, int], tuple2: tuple[int, int]):\n return tuple1[0] + tuple2[0], tuple1[1] + tuple2[1]\n</code></pre>\n<hr />\n<p><strong>collections.defaultdict</strong></p>\n<p>This is a perfect use case for a <code>defaultdict</code>. Instead of manually checking if a team already exists as a key in <code>team_wins_and_losses</code>, we can let <code>defaultdict</code> handle that for us.</p>\n<pre><code>from collections import defaultdict\nteam_wins_and_losses = defaultdict(lambda: (0, 0))\n</code></pre>\n<p>This will give us a <code>defaultdict</code> that inserts the tuple <code>(0, 0)</code> anytime we try to call a non-existent key for the first time.</p>\n<p><em>Why the lambda?</em> <code>defaultdict</code> expects a callable as an argument, which returns the desired default value without taking any arguments. I don't currently know of a better way to achieve this for tuples.</p>\n<hr />\n<p><strong>Tied games</strong></p>\n<p>Your code currently handles everything that isn't a win for team1 as a win for team2. The problem statement does not explicitly specify ho to handle ties, so I would just skip tie games completely:</p>\n<pre><code>if score1 == score2:\n continue\n</code></pre>\n<hr />\n<p><strong>Complete code</strong></p>\n<p>I made some other small changes (including corrected spelling) that should be pretty straightforward and added clarifying comments where necessary. Feel free to ask for further information if needed.</p>\n<pre><code>from collections import defaultdict\n\n\ndef add_tuples(tuple1: tuple[int, int], tuple2: tuple[int, int]):\n return tuple1[0] + tuple2[0], tuple1[1] + tuple2[1]\n\n\nnumber_of_games = int(input("Enter the total number of games: "))\n\n# Moved this message to only print once instead of on every line\nprint("Note that the team names must be a single word, without spaces")\n\nteam_wins_and_losses = defaultdict(lambda: (0, 0))\n\nfor _ in range(number_of_games):\n team1, score1, _, team2, score2 = input("Enter game results: ").split()\n\n # Tied game\n if score1 == score2:\n continue\n\n # I find this to be more readable than the one-liner\n if int(score1) > int(score2):\n team1_result, team2_result = (1, 0), (0, 1)\n else:\n team1_result, team2_result = (0, 1), (1, 0)\n\n # We can now concisely update the team scores\n team_wins_and_losses[team1] = add_tuples(team_wins_and_losses[team1], team1_result)\n team_wins_and_losses[team2] = add_tuples(team_wins_and_losses[team2], team2_result)\n\n\n# If you want to print this as a regular dict you can simply cast it to a dict\n# dict(team_wins_and_losses)\n# Generally not necessary though, as defaultdict provides the same functionalities\nprint(team_wins_and_losses)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T20:08:32.993",
"Id": "258938",
"ParentId": "258926",
"Score": "3"
}
},
{
"body": "<ol>\n<li><p>Please always use 4 spaces to indent when using Python.</p>\n</li>\n<li><p>Rather than the verbose name <code>team_wins_and_loses</code> we could use <code>team_results</code>.</p>\n</li>\n<li><p>Rather than adding both values of the tuple we should focus on adding 1 win to the winning team, and 1 lose to the losing team.</p>\n<pre class=\"lang-py prettyprint-override\"><code>winner[0] += 1\nloser[1] += 1\n</code></pre>\n</li>\n<li><p>We can change your turnery to pick the wining or losing team, and then extract the value with the correct default.</p>\n<pre class=\"lang-py prettyprint-override\"><code>winning_team, losing_team = (\n (team1, team2)\n if int(score1) > int(score2) else\n (team2, team1)\n)\nif winning_team not in team_results:\n winner = team_results[winning_team] = [0, 0]\nelse:\n winner = team_results[winning_team]\n# same for losing team\n</code></pre>\n</li>\n<li><p>We can use <code>dict.setdefault</code> to remove the need for the if.</p>\n<pre class=\"lang-py prettyprint-override\"><code>winner = team_results.setdefault(winning_team, [0, 0])\n</code></pre>\n</li>\n<li><p>We can use <code>collections.defaultdict</code> to make interacting with <code>team_results</code> much cleaner, rather than using <code>dict.setdefault</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def default_scores():\n return [0, 0]\n\nteam_results = collections.defaultdict(default_scores)\n# ...\nteam_results[winning_team][0] += 1\n</code></pre>\n</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>import collections\n\n\ndef default_scores():\n return [0, 0]\n\n\nteam_results = collections.defaultdict(default_scores)\nnumber_of_games = int(input("Enter the total number of Games: "))\nfor _ in range(number_of_games):\n team1, score1, __, team2, score2 = input("Enter the game results(Note that the name of the team must be a single word, without spaces):").split()\n winner, loser = (\n (team1, team2)\n if int(score1) > int(score2) else\n (team2, team1)\n )\n team_results[winner][0] += 1\n team_results[loser][1] += 1\n print(team_results)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T20:35:26.313",
"Id": "258939",
"ParentId": "258926",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "258939",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T17:02:04.417",
"Id": "258926",
"Score": "5",
"Tags": [
"python"
],
"Title": "Count wins and losses for each team in a league"
}
|
258926
|
<p>My code currently doesn't insert data into MySQL fast enough. However I don't know how to measure the current speed.</p>
<pre><code>def insert():
mycursor = mydb.cursor()
plik = input(":::")
agefile = open("C:/Users/juczi/Desktop/New Folder/" + plik, "r")
sql = "INSERT INTO wyciek (nick, ip) VALUES (%s, %s)"
for row in agefile:
mydb.commit()
data = row.split(':')
val = (data[0].replace("\n",""), data[1].replace("\n", ""))
mycursor.execute(sql, val)
agefile.close()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T17:14:45.623",
"Id": "510526",
"Score": "0",
"body": "\"I was wondering if there is any faster way ...\" why? Is your code currently not fast enough, or do you just want speed for speed's sake?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T17:17:39.347",
"Id": "510527",
"Score": "0",
"body": "The code is not fast enough, i need it to be faster."
}
] |
[
{
"body": "<p>If you are trying to insert data in bulk to Mysql the best would be to use <a href=\"https://dev.mysql.com/doc/refman/8.0/en/load-data.html\" rel=\"nofollow noreferrer\">LOAD DATA</a> instead of doing it in a loop on top of an interpreted language, which is inevitably slower. However there is less flexibility if you need to transform data but that shouldn't be a problem in your case. All you're doing is get rid of carriage return. This is a plain delimited file without heavy transformation.</p>\n<p>The <code>mydb.commit()</code> is misplaced. It should be called <em>after</em> running an insert/update. On the first iteration there is nothing to be committed.\nBut this is not efficient. I suggest that you take full advantage of <strong>transactions</strong>. Start a transaction at the beginning, do your loop and commit at the end. In case of error, you roll back. The added benefit is <strong>data integrity</strong>. If an error occurs, the data already inserted is "undone" so you don't end up with garbage due to a partial import of data.</p>\n<p>Schema:</p>\n<pre><code>try:\n conn.autocommit = False\n\n # insert loop..\n\n # Commit your changes\n conn.commit()\n\nexcept mysql.connector.Error as error:\n print("Failed to update record to database rollback: {}".format(error))\n # reverting changes because of exception\n conn.rollback()\n</code></pre>\n<p>See for example: <a href=\"https://pynative.com/python-mysql-transaction-management-using-commit-rollback/\" rel=\"nofollow noreferrer\">Use Commit and Rollback to Manage MySQL Transactions in Python</a></p>\n<p>This alone should improve performance but you have to test it to measure the gain.</p>\n<p>Not performance-related, but you can also use a <strong>context manager</strong> whenever possible, for instance when opening/writing to a file. So:</p>\n<pre><code>agefile = open("C:/Users/juczi/Desktop/New Folder/" + plik, "r")\n</code></pre>\n<p>becomes:</p>\n<pre><code>with open("C:/Users/juczi/Desktop/New Folder/" + plik, "r") as agefile:\n # do something\n</code></pre>\n<p>and you don't have to bother closing the file, this is done automatically.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T19:08:45.700",
"Id": "258937",
"ParentId": "258927",
"Score": "1"
}
},
{
"body": "<p>Plan A:</p>\n<p>Build a 'batch' <code>INSERT</code>:</p>\n<pre><code>INSERT INTO wyciek (nick, ip) VALUES (12, 34), (234, 456), ...\n</code></pre>\n<p>Then execute it. If your columns are <code>VARCHAR</code> instead of <code>INT</code>, be sure to put quotes around each value.</p>\n<p>For 100 rows, this will run about 10 times as fast as 100 single-row <code>INSERTs</code>.</p>\n<p>(And that is aside from having the <code>COMMIT</code> inside the loop!)</p>\n<p>Plan B:</p>\n<p>If your data comes from a file, consider using <code>LOAD DATA INFILE ...</code>. It may be even faster than plan A.</p>\n<p>If you data is not <em>already</em> in a file, building the file to do <code>LOAD</code> <em>may</em> be slower than Plan A.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T01:00:47.117",
"Id": "260002",
"ParentId": "258927",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "258937",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T17:05:43.370",
"Id": "258927",
"Score": "1",
"Tags": [
"python",
"mysql",
"time-limit-exceeded"
],
"Title": "Inserting data into MySQL"
}
|
258927
|
<p>I implemented the <a href="https://en.wikipedia.org/wiki/Maze_generation_algorithm#Iterative_implementation" rel="nofollow noreferrer">iterative randomized depth-first search</a>, with my goal for it to be <em>performant</em>, and have code that made complete sense.</p>
<p>It utilizes <code>AtomicReference<T></code> inside of <code>Cell</code> to keep track of it's walls (as multiple cells can share walls). The randomization does not utilize Java 8 streams at all.</p>
<p><strong>AdjacentDirection.java</strong>:</p>
<pre class="lang-java prettyprint-override"><code>public enum AdjacentDirection
{
TOP,
BOTTOM,
LEFT,
RIGHT;
static final AdjacentDirection[] VALUES = values();
}
</code></pre>
<p><strong>Cell.java</strong>:</p>
<pre class="lang-java prettyprint-override"><code>import java.util.HashMap;
import java.util.Map;
import java.util.StringJoiner;
import java.util.concurrent.atomic.AtomicReference;
public class Cell
{
private final int x;
private final int y;
private boolean visited;
// Cells can share walls, so make this a reference.
private final Map<AdjacentDirection, AtomicReference<Boolean>> walls = new HashMap<>();
Cell(int x, int y)
{
this.x = x;
this.y = y;
}
public boolean isVisited()
{
return visited;
}
void setVisited(boolean visited)
{
this.visited = visited;
}
void setWall(AdjacentDirection dir, AtomicReference<Boolean> wall)
{
walls.put(dir, wall);
}
AtomicReference<Boolean> getWall(AdjacentDirection dir)
{
return walls.get(dir);
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
@Override
public String toString()
{
return new StringJoiner(", ", Cell.class.getSimpleName() + "[", "]")
.add("x=" + x)
.add("y=" + y)
.add("visited=" + visited)
.add("walls=" + walls)
.toString();
}
}
</code></pre>
<p><strong>CellMap.java</strong>:</p>
<pre class="lang-java prettyprint-override"><code>import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicReference;
// This map assumes that the bottom-left most cell is point (0, 0)
public class CellMap
{
private final Cell[][] cells;
public CellMap(int width, int height)
{
if (width <= 0 || height <= 0)
throw new IllegalArgumentException("Width and height must be > 0");
cells = new Cell[height][];
for (var y = 0; y < cells.length; y++)
{
cells[y] = new Cell[width];
for (var x = 0; x < cells[y].length; x++)
{
var cell = cells[y][x] = new Cell(x, y);
// Let's resolve references to the cell walls.
// Because we go left to right, bottom to top, there will never:
// Be a cell above us generated yet.
// Be a cell to our right generated yet.
// The other ones will always be there, unless x = 0 or y = 0
var leftNeighborIndex = x - 1;
var bottomNeighborIndex = y - 1;
// The wall to our left is the right wall of the cell to our left.
if (leftNeighborIndex >= 0)
cell.setWall(AdjacentDirection.LEFT, cells[y][leftNeighborIndex].getWall(AdjacentDirection.RIGHT));
else
cell.setWall(AdjacentDirection.LEFT, new AtomicReference<>(true));
// The wall beneath us is the top wall of the cell beneath us.
if (bottomNeighborIndex >= 0)
cell.setWall(AdjacentDirection.BOTTOM, cells[bottomNeighborIndex][x].getWall(AdjacentDirection.TOP));
else
cell.setWall(AdjacentDirection.BOTTOM, new AtomicReference<>(true));
cell.setWall(AdjacentDirection.TOP, new AtomicReference<>(true));
cell.setWall(AdjacentDirection.RIGHT, new AtomicReference<>(true));
}
}
}
public void randomDepthFirstSearch(Random rnd)
{
randomDepthFirstSearch(rnd, 0, 0);
}
// https://en.wikipedia.org/wiki/Maze_generation_algorithm#Iterative_implementation
public void randomDepthFirstSearch(Random rnd, int initialX, int initialY)
{
var stack = new ArrayDeque<Cell>();
// Choose the initial cell, mark it as visited and push it to the stack
var initial = cells[initialY][initialX];
initial.setVisited(true);
stack.push(initial);
// While the stack is not empty
while (!stack.isEmpty())
{
// Pop a cell from the stack and make it a current cell
var current = stack.pop();
var unvisitedNeighbors = getNeighbors(current.getX(), current.getY()).entrySet();
unvisitedNeighbors.removeIf(kv -> kv.getValue().isVisited());
// If the current cell has any neighbours which have not been visited
if (!unvisitedNeighbors.isEmpty())
{
// Push the current cell to the stack
stack.push(current);
// Choose one of the unvisited neighbours
Map.Entry<AdjacentDirection, Cell> chosen;
var toSkip = rnd.nextInt(unvisitedNeighbors.size());
var unvisitedIter = unvisitedNeighbors.iterator();
for (var i = 0; i < toSkip; i++)
unvisitedIter.next();
chosen = unvisitedIter.next();
// Remove the wall between the current cell and the chosen cell
current.getWall(chosen.getKey()).set(false);
// Mark the chosen cell as visited and push it to the stack
chosen.getValue().setVisited(true);
stack.push(chosen.getValue());
}
}
}
public Cell getAt(int x, int y)
{
return cells[y][x];
}
public int getHeight()
{
return cells.length;
}
public int getWidth()
{
return cells[0].length;
}
public Map<AdjacentDirection, Cell> getNeighbors(int x, int y)
{
var map = new HashMap<AdjacentDirection, Cell>();
for (var dir : AdjacentDirection.VALUES)
{
var cell = getNeighbor(dir, x, y);
if (cell != null)
map.put(dir, cell);
}
return map;
}
public Cell getNeighbor(AdjacentDirection dir, int x, int y)
{
switch (dir)
{
case TOP:
{
var ind = y + 1;
if (ind >= cells.length)
return null;
return cells[ind][x];
}
case BOTTOM:
{
var ind = y - 1;
if (ind < 0)
return null;
return cells[ind][x];
}
case RIGHT:
{
var ind = x + 1;
if (ind >= cells[y].length)
return null;
return cells[y][ind];
}
case LEFT:
{
var ind = x - 1;
if (ind < 0)
return null;
return cells[y][ind];
}
default:
throw new IllegalArgumentException("Invalid direction?");
}
}
}
</code></pre>
<p>The following class is a swing <code>JPanel</code>, that helps with visualization of <code>CellMap</code>. I am <strong>not</strong> explicitly asking for anyone to review this.</p>
<p><strong>CellMapPanel.java</strong>:</p>
<pre class="lang-java prettyprint-override"><code>import javax.swing.*;
import java.awt.*;
public class CellMapPanel extends JPanel
{
private final CellMap map;
private final int cellSize;
public CellMapPanel(CellMap map, int cellSize)
{
this.map = map;
this.cellSize = cellSize;
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.WHITE);
for (var x = 0; x < map.getWidth(); x++)
{
for (var y = 0; y < map.getHeight(); y++)
{
var visualX = x;
// Graphics in Java have (0, 0) in the top-left -- we need it in the bottom-left.
var visualY = map.getHeight() - y - 1;
var cell = map.getAt(x, y);
if (cell.getWall(AdjacentDirection.LEFT).get())
g.drawLine(visualX * cellSize, visualY * cellSize, visualX * cellSize, visualY * cellSize + cellSize);
if (cell.getWall(AdjacentDirection.TOP).get())
g.drawLine(visualX * cellSize, visualY * cellSize, visualX * cellSize + cellSize, visualY * cellSize);
if (cell.getWall(AdjacentDirection.RIGHT).get())
g.drawLine(visualX * cellSize + cellSize, visualY * cellSize, visualX * cellSize + cellSize, visualY * cellSize + cellSize);
if (cell.getWall(AdjacentDirection.BOTTOM).get())
g.drawLine(visualX * cellSize, visualY * cellSize + cellSize, visualX * cellSize + cellSize, visualY * cellSize + cellSize);
}
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T05:09:57.867",
"Id": "510595",
"Score": "0",
"body": "Welcome to CodeReview@SE. Every question here is required to be about (coding) an implementation, and I can tell *Java* from the \"required\" language tag: leave both from the title and [tell *what*](https://codereview.stackexchange.com/help/how-to-ask) to find, and possibly *where to search*."
}
] |
[
{
"body": "<h3>Review</h3>\n<ul>\n<li><p><code>private final int x;</code> and <code>private final int y;</code> part in <code>Cell.java</code>, do you consider to use <a href=\"https://docs.oracle.com/javase/7/docs/api/java/awt/geom/Point2D.html\" rel=\"nofollow noreferrer\">Point2D</a> class?</p>\n</li>\n<li><p>In <code>CellMap</code> class, do you expect the value <code>null</code> is returned if the location passing into <code>public Cell getNeighbor(AdjacentDirection dir, int x, int y)</code> method is out of boundary? Or <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/IllegalStateException.html\" rel=\"nofollow noreferrer\"><code>IllegalStateException</code></a> can be used here?</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T17:45:10.830",
"Id": "510771",
"Score": "2",
"body": "I don't believe the dependency on the `java.desktop` module is worth for the single `Point2D` class.\nThough you are correct that an out of bounds index into the cell map is an exceptional state."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T23:59:38.333",
"Id": "258991",
"ParentId": "258942",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T21:25:16.747",
"Id": "258942",
"Score": "1",
"Tags": [
"java",
"algorithm"
],
"Title": "Iterative Random Depth First Search implementation in Java"
}
|
258942
|
<p>I've recently started learning Python again after a long time away from it and doing MATLAB at university. Today, I spent some time working on a first little project of mine. Right now it works as it should minus ending the game when all the fields are full. I would love to get advice on how I could improve the code and would like to fix any bad habits early on in learning.</p>
<pre><code> mapA = [[" ", "|", " ", "|", " "],
[" ", "|", " ", "|", " "],
[" ", "|", " ", "|", " "]]
def printMap():
# prints out the map
map = ["".join(mapA[0]),
"".join(mapA[1]),
"".join(mapA[2])]
print(map[0])
print(map[1])
print(map[2])
# makes a list of just the fields with x and o
mapB = [map[0].split("|"),
map[1].split("|"),
map[2].split("|")]
for x in range(3): # converts the board to numbers
for y in range(3):
if mapB[x][y] == "X":
mapB[x][y] = 1
elif mapB[x][y] == "O":
mapB[x][y] = -1
elif mapB[x][y] == " ":
mapB[x][y] = 0
for x in range(3):
if abs(sum(mapB[x])) == 3: # checks for full rows
return "END"
elif abs(int(mapB[0][x]) + int(mapB[1][x]) + int(mapB[2][x])) == 3: # checks for full columns
return "END"
if abs(int(mapB[0][0]) + int(mapB[1][1]) + int(mapB[2][2])) == 3: # checks for full right diagonal
return "END"
elif abs(int(mapB[0][2]) + int(mapB[1][1]) + int(mapB[2][0])) == 3: # checks for full left diagonal
return "END"
counter = 0
def choice(): # allows the user to choose O or X
print("O or X?")
symbol = input().lower() # case insensitive
if symbol == "o":
return ["O", "X"]
elif symbol == "x":
return ["X", "O"]
else:
print("Invalid symbol")
return choice() # restarts the function if the user input neither O nor X
def placement(symbol):
print("Place " + symbol + " in form: rowNumber columnNumber")
x = input()
coordinates = x.split(" ")
while len(coordinates) != 2 or coordinates[0].isnumeric() != True or coordinates[1].isnumeric() != True:
print("Invalid input.")
print("Place " + symbol + " in form: rowNumber columnNumber")
x = input()
coordinates = x.split(" ")
while mapA[int(coordinates[0]) - 1][int(coordinates[1]) * 2 - 2] != " ":
if mapA[int(coordinates[0]) - 1][int(coordinates[1]) * 2 - 2] != " ":
print("That space is taken.")
else:
print("Invalid input.")
print("Place " + symbol + " in form: rowNumber columnNumber")
x = input()
coordinates = x.split(" ")
if coordinates[0] == "1" and coordinates[1] == "1":
mapA[0][0] = symbol
elif coordinates[0] == "1" and coordinates[1] == "2":
mapA[0][2] = symbol
elif coordinates[0] == "1" and coordinates[1] == "3":
mapA[0][4] = symbol
elif coordinates[0] == "2" and coordinates[1] == "1":
mapA[1][0] = symbol
elif coordinates[0] == "2" and coordinates[1] == "2":
mapA[1][2] = symbol
elif coordinates[0] == "2" and coordinates[1] == "3":
mapA[1][4] = symbol
elif coordinates[0] == "3" and coordinates[1] == "1":
mapA[2][0] = symbol
elif coordinates[0] == "3" and coordinates[1] == "2":
mapA[2][2] = symbol
elif coordinates[0] == "3" and coordinates[1] == "3":
mapA[2][4] = symbol
return printMap()
symbol = choice()
printMap()
end = ""
while end != "END":
end = placement(symbol[0])
if end == "END":
print("Game Finished")
break
end = placement(symbol[1])
if end == "END":
print("Game Finished")
break
tictac()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T06:37:24.080",
"Id": "510605",
"Score": "0",
"body": "Welcome to CodeReview. Here we can review complete and working code. If your application is not finished and you are struggling with some problem then please consider to ask question on StackOverflow."
}
] |
[
{
"body": "<p>The first thing I notice is the two separate maps. Since the only actual information you're storing is X / O positions in a 3x3 grid, I think it is good practice to only store those values. Then add any additional formatting when you print. I've also used <code>snake_case</code> for function and variable names, which is the preferred style. The first section could be rewritten:</p>\n<pre><code>x_o_grid = [\n [' ', ' ', ' ', ],\n [' ', ' ', ' ', ],\n [' ', ' ', ' ', ]\n]\n\ndef print_map():\n for row in x_o_grid:\n print('|'.join(row))\n</code></pre>\n<p>You can continue with this pattern by again only storing -1, 0, or 1 in this grid. Then doing your comparison in a slightly different way.</p>\n<p>I would suggest refactoring the portion of <code>printMap</code> where you check for matches into a new <code>check_for_solution</code> function:</p>\n<pre><code>def check_for_solution():\n # Check rows\n for row in x_o_grid:\n if all(x == row[0] for x in row):\n if row[0] != ' ':\n return row[0]\n\n # Check columns\n for i in range(len(x_o_grid)):\n column = [row[i] for row in x_o_grid]\n if all(x == column[0] for x in column):\n if column[0] != ' ':\n return column[0]\n\n # Check diagonals\n diagonal1 = [x_o_grid[i][i] for i in range(len(x_o_grid))]\n diagonal2 = [x_o_grid[len(x_o_grid) - i][len(x_o_grid) - i] for i in range(len(x_o_grid))]\n for diagonal in [diagonal1, diagonal2]:\n if all(x == diagonal[0] for x in diagonal):\n if diagonal[0] != ' ':\n return diagonal[0]\n\n return None\n</code></pre>\n<p>In the above rewrite, I have tried to avoid hardcoding the indices of the grid we are checking. And instead of using <code>sum()</code> to check for equivalence, I'm using the <code>all()</code> function where we check to see if the first element of the list is equal to every other element. This will return true if it is or false if any element is off.</p>\n<p>This helps to make our code reusable and neater and allows for more flexible data storage. By not using <code>range(3)</code> and instead just looping through the available rows, we can accommodate any square matrix when checking for solutions.</p>\n<p>The placement you can change <code>!= True</code> to <code>not</code>. I believe the below will also error out if you pass a <code>None</code> or a <code>float</code>, so these should be captured in <code>try: except:</code> statements.</p>\n<pre><code>while not len(coordinates) == 2 or not coordinates[0].isnumeric() or not coordinates[1].isnumeric():\n</code></pre>\n<p>You might also consider f-strings, available in Python 3.6+. I believe this is preferred, but may come down to preference.</p>\n<pre><code>print(f"Place {symbol} in form: rowNumber columnNumber")\n</code></pre>\n<p>The placement logic can also be simplified to:</p>\n<pre><code>x_o_grid[int(coordinates[0]) - 1][int(coordinates[1]) - 1] = symbol\n</code></pre>\n<p>I would also recommend you change the <code>end</code> variable to a <code>bool</code> since you're only really checking for two states:</p>\n<pre><code>end = False\n\nwhile not end:\n ...\n</code></pre>\n<p>I believe the <code>check_solutions</code> function will require a rewrite of your main loop, as it now returns either a none or the winning value.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T17:31:54.573",
"Id": "258972",
"ParentId": "258945",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "258972",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T23:56:44.530",
"Id": "258945",
"Score": "1",
"Tags": [
"python",
"beginner",
"tic-tac-toe"
],
"Title": "Text-based Tic Tac Toe in Python (First Project)"
}
|
258945
|
<p>In my data I have few hierarchy values - example address</p>
<blockquote>
<p>Name -> Street -> City -> County -> State -> Country</p>
</blockquote>
<p>The validation I need is: if a value in the above hierarchy is present, then all the previous/higher order values should be present.</p>
<p>Below is a valid case</p>
<blockquote>
<p>Name -> Street -> City -> State<br />
This is valid even though there is no country - as it is last in the order</p>
</blockquote>
<p>and below is an invalid case</p>
<blockquote>
<p>Name -> Street -> State -> Country<br />
This is invalid as there is no City Which is of higher order than state and country.</p>
</blockquote>
<p>The below code helped me in doing the checks. Can this be simplified further? I want to get rid of the last dummy return statement. (To the best of my knowledge, it is difficult to get rid of it. But there are more people far more knowledgeable than me.)</p>
<pre><code> package com.example.demo;
public class SimplyfyHierarchyCheck {
public static void main(String[] args) {
String a="a", b="b", c="c", d="d";
SimplyfyHierarchyCheck shc = new SimplyfyHierarchyCheck();
System.out.println(shc.isGapLessHierarchy("a", b, "", "") );
}
//can this method be made even more concise.
private boolean isGapLessHierarchy(String... args) { //Hierarchy
boolean isGapLess=true;
for(int i=args.length-1; i>=0; i--) {
if(args[i].isBlank() ) //nothing to check
{
continue;
}
for(int j=i-1; j>=0; j--) {
if(args[j].isBlank() ) //gap found i.e false
{
return false;
}
}
}
return isGapLess; //dummy return // am required to return true or false // can i get rid of this
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T02:29:55.583",
"Id": "510586",
"Score": "1",
"body": "Why was this tagged C/C++? It's java."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T04:31:12.030",
"Id": "510589",
"Score": "0",
"body": "IMO, you should always return `isGapLess`. In your loop, you can set `isGapLess = false; break;` and then let the control to reach the last return statement"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T20:15:26.737",
"Id": "510693",
"Score": "0",
"body": "Is `County` excluded as _optional_ node in your hierarchical validation (first valid example without 'country')?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T20:20:22.720",
"Id": "510694",
"Score": "0",
"body": "What is abstraction and what is true domain-context? What purpose has the gap-identification (i.e. to avoid \"gaps in hierarchy\"): an address should be _resolvable_ or be _specific enough_ to be locatable❔"
}
] |
[
{
"body": "<p><strong>What I'd recommend:</strong><br />\nIf Gapless, only a single complete iteration of the sequence is required. Otherwise, checks till the first gap found.</p>\n<pre class=\"lang-java prettyprint-override\"><code> private boolean isGapLessHierarchy(String... args) { //Hierarchy \n int i=args.length-1;\n while(args[i].isBlank() && i>=0) //till data is found\n i--;\n for(--i; i>=0; i--)\n if(args[i].isBlank()) //gap found i.e false \n return false;\n return true; //is necessary\n }\n</code></pre>\n<p><strong>What you did:</strong><br />\nNested the j-controlled loop in the i-controlled loop.\nFor every Gapless sequence you pass on, parts of the sequence are checked multiple times.<br />\nThe last return statement is necessary to get <code>true</code> as return from the function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T05:34:17.490",
"Id": "510598",
"Score": "0",
"body": "Why `i>=0;` above the while loop?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T05:42:02.590",
"Id": "510601",
"Score": "0",
"body": "A mistake while pasting. Sorry. I don't have Java 11 where String.isBlank() was introduced https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#isBlank() and hence could not run the program before presenting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T06:43:45.253",
"Id": "510606",
"Score": "0",
"body": "i got the core logic. Thanks for it. That's wonderful. Tiny things matter for programmer. +1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T06:50:15.230",
"Id": "510607",
"Score": "0",
"body": "Happy to help. You can accept my answer if it solved your problem. Marc's code is more concise, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T12:22:06.540",
"Id": "510628",
"Score": "2",
"body": "Small thing: `return isGapLess` can be reduced to `return true`. `isGapLess` is never modified, which makes it always equal to `true` and is thus not needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T13:56:12.387",
"Id": "510637",
"Score": "0",
"body": "@JensV Done. Thanks for pointing out."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T05:23:33.393",
"Id": "258949",
"ParentId": "258947",
"Score": "2"
}
},
{
"body": "<p>Since you are looking for a more concise way, you can use a <code>for-loop</code> with an empty body:</p>\n<pre><code>boolean isGapLessHierarchy(String... args) {\n int i = args.length - 1;\n for (; i >= 0 && args[i].isBlank(); i--);\n for (; i >= 0 && !args[i].isBlank(); i--);\n return i == -1;\n}\n</code></pre>\n<p>This also removes the need for the variable <code>isGapless</code>.</p>\n<p>With Streams you can use <a href=\"https://docs.oracle.com/javase/9/docs/api/java/util/stream/Stream.html#dropWhile-java.util.function.Predicate-\" rel=\"nofollow noreferrer\">dropWhile</a> and <a href=\"https://docs.oracle.com/javase/9/docs/api/java/util/stream/Stream.html#noneMatch-java.util.function.Predicate-\" rel=\"nofollow noreferrer\">noneMatch</a>:</p>\n<pre><code>boolean isGapLessHierarchy(String... args) {\n List<String> argsList = Arrays.asList(args);\n Collections.reverse(argsList);\n return argsList.stream()\n .dropWhile(String::isBlank)\n .noneMatch(String::isBlank);\n}\n</code></pre>\n<p>Note that this approach creates an additional list.</p>\n<p><strong>General recommendation</strong>: I believe you have your reasons to try to make the code shorter. As also others pointed out, making the code shorter often affects readability and that is hardly worth it. I have to admit that the solutions I provided are not the most readable, so think twice before using them in a shared project. On the other hand, if you are the only maintainer and doing some experiments it's totally fine. Good luck with your project.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T08:46:53.820",
"Id": "510617",
"Score": "0",
"body": "tested and works. +1. from java doc's i could not figure out how dropWhile is doing it for unordered list - `returns, if this stream is unordered, a stream consisting of the remaining elements of this stream after dropping a subset of elements that match the given predicate.` So if I have after reversing {a, b, \" \", d, \" \", f }, for this unordered list i am hoping the output will be {a, b, d, f}. But seems i am wrong. Any hints."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T08:58:54.397",
"Id": "510619",
"Score": "0",
"body": "plz don't ask for a SOF post - that will loose the context and can get lengthy for me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T09:08:31.090",
"Id": "510621",
"Score": "0",
"body": "got it - `Certain stream sources (such as List or arrays) are intrinsically ordered, whereas others (such as HashSet) are not.`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T15:47:22.060",
"Id": "510649",
"Score": "2",
"body": "I've had to look at some of my code after 5 or even 10 years... Even if you're the sole maintainer clarity matters! ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T20:12:31.380",
"Id": "510692",
"Score": "0",
"body": "When reviewing this answer could try to improve names: (a) `isGapLessHierarchy(String... args)` to `hasConsequentHierarchy(Address address)` to communicate domain-knowledge and specific purpose (instead of over-generic vagueness)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T06:32:29.437",
"Id": "258952",
"ParentId": "258947",
"Score": "5"
}
},
{
"body": "<p>As a long-term Java programmer, I know that most of my time will be spent in maintenance.</p>\n<p>On that basis I prefer simple code that expresses its purpose clearly to clever, concise, unclear code.</p>\n<p>With that context in place here's some basic comments.</p>\n<pre><code> String a="a", b="b", c="c", d="d"; \n</code></pre>\n<ul>\n<li><p>It's not the Java way to do multiple declarations together - I'd\nsplit these.</p>\n</li>\n<li><p>They are constants not variables, so they should be "static final" (and UPPERCASE).</p>\n</li>\n<li><p>Three of them are not used, so delete them.</p>\n<p>System.out.println(shc.isGapLessHierarchy("a", b, "", "") );</p>\n</li>\n<li><p>Why do you mix use of a constant and a literal? As a maintenance\nprogrammer looking at your code I'm now wondering whether this has\nsome significance.</p>\n</li>\n</ul>\n<p>Now to your "isGapLessHierarchy()" method:</p>\n<ul>\n<li>The method has no dependency on an object, so it should be "static"</li>\n<li>Never call anything "args" (other than perhaps the arguments to a main method). Give your method parameters meaningful names. How about "hierarchyElements" in this case?</li>\n<li>(Almost) Never use 'i' and 'j' as indexes. Use something meaningful.</li>\n<li>Going forwards through a list is (IMHO) clearer than going backwards. Your condition can be expressed as "a gap should never be followed by a non-gap", which allows us to go forwards.</li>\n</ul>\n<p>Here's my code using your pattern, with some cleanup and adding a more extensive set of tests (I couldn't be bothered with Junit in this case, but you probably should).</p>\n<pre><code> public class HierarchyCheck {\n\n public static void main(String[] args) {\n String[][] testCases = new String[][]{\n new String[]{"Name", "Street", "City", "County", "State", "Country"},\n new String[]{"Name", "Street", "City", "County", "State", ""},\n new String[]{"Name", "Street", "City", "County", "", "Country"},\n new String[]{"Name", "Street", "", "County", "State", "Country"},\n new String[]{"Name", "", "City", "", "State", "Country"},\n new String[]{"Name", "", "", "", "", ""}\n };\n\n for (String[] testCase : testCases) {\n System.out.format("%s %s gapLess%n", \n Arrays.toString(testCase),\n isGapLessHierarchy(testCase) ? "is" : "is not");\n }\n }\n\n private static boolean isGapLessHierarchy(String... hierarchyElements) {\n\n // Find the first gap\n int firstGap = 0;\n for (firstGap = 0; firstGap < hierarchyElements.length; firstGap++) {\n if (isBlank(hierarchyElements[firstGap])) {\n break;\n }\n }\n\n // Is there a non-gap after the first gap?\n for (int nonGap = firstGap + 1; nonGap < hierarchyElements.length; nonGap++) {\n if (!isBlank(hierarchyElements[nonGap])) {\n // There is, so it's not gapless\n return false;\n }\n }\n\n // Definitely gapless\n return true;\n }\n\n // We don't have Java 11 for the String.isBlank() method, so fake it!\n private static boolean isBlank(String string) {\n return (string == null) || (string.trim().length() == 0);\n }\n}\n</code></pre>\n<p>However, I'd probably have gone for a simpler, arguably cruder approach.</p>\n<pre><code> private static boolean isGapLessHierarchy(String... hierarchyElements) {\n\n boolean seenGap = false;\n\n for (String hierarchyElement : hierarchyElements) {\n if (isBlank(hierarchyElement)) {\n seenGap = true;\n }\n else {\n if (seenGap) { // gap followed by non-gap\n return false;\n }\n }\n }\n\n // Definitely gapless\n return true;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T09:04:35.330",
"Id": "510620",
"Score": "0",
"body": "good advice. +1. Thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T20:05:20.060",
"Id": "510691",
"Score": "2",
"body": "I would even try to avoid _negation_ whenever possible: `it's not gapless` means \"has gaps\" and `gap-less` is probably _continuous_. Athough I am neither domain-expert nor native-speaker "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T20:38:38.937",
"Id": "510698",
"Score": "1",
"body": "Fair points @hc_dev but there were limits to how much I could fit in, given that I basically did my review and rewrites in a coffee break."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T08:14:37.183",
"Id": "258958",
"ParentId": "258947",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "258952",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T00:26:43.600",
"Id": "258947",
"Score": "5",
"Tags": [
"java"
],
"Title": "Program for checking gaps in hierarchy?"
}
|
258947
|
<p>See code below and my comment with questions:</p>
<pre class="lang-rs prettyprint-override"><code>pub fn factors(n: u64) -> Vec<u64> {
let mut m = n; // is it possible to convert n to a mutable type without using another variable?
let mut a:Vec<u64> = Vec::new();
while m % 2 == 0 {
m /= 2;
a.push(2);
}
// in C we can just write for (int i = 3; i <= sqrt(m); i+= 2) ... just saying... and C is not even as fast as python to code... am I really doing it right??
for i in (3..((m as f64).sqrt() as usize + 1usize)).step_by(2) {
while m % i as u64 == 0 { // is there a way to avoid all the casts to u64
a.push(i as u64);
m /= i as u64;
}
}
if m > 2 {
a.push(m);
}
return a;
}
</code></pre>
<ul>
<li>Is it possible to convert n to a mutable type without using another variable?</li>
<li>The C equivalent of the main loop use twice less ink. Is Rust so verbose by design?</li>
<li>Is there a way to avoid all the casts to u64</li>
<li>any other insight welcome</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T05:05:16.123",
"Id": "510591",
"Score": "0",
"body": "Your while loop is infinite, because m never changes. Does this code have a copy-paste error?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T05:07:45.957",
"Id": "510593",
"Score": "1",
"body": "The first while loop"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T05:08:36.443",
"Id": "510594",
"Score": "0",
"body": "copy/paste, I edit"
}
] |
[
{
"body": "<pre><code>pub fn factors(n: u64) -> Vec<u64> {\n let mut m = n; // is it possible to convert n to a mutable type without using another variable?\n</code></pre>\n<p>use <code>pub fn factors(mut n: u64)</code> to allow the parameter to be mutable</p>\n<pre><code> let mut a:Vec<u64> = Vec::new();\n</code></pre>\n<p>You don't need <code>: Vec<u64></code>, rust will infer it.</p>\n<pre><code> while m % 2 == 0 {\n m /= 2;\n a.push(2);\n }\n\n\n // in C we can just write for (int i = 3; i <= sqrt(m); i+= 2) ... just saying... and C is not even as fast as python to code... am I really doing it right??\n for i in (3..((m as f64).sqrt() as usize + 1usize)).step_by(2) { \n</code></pre>\n<p>Generally speaking, Rust is less verbose than C, but you've hit one of the major exceptions. Rust is pickier about types, it won't let you mix and match different numeric types. But we can make some improvements here.</p>\n<ul>\n<li>You don't need <code>1usize</code> just use 1.</li>\n<li>You can also use <code>3 ..= (m as f64).sqrt() as usize</code> (..= includes the end)</li>\n</ul>\n<p>Alternatively, you could reverse the check:</p>\n<pre><code>for index in (3..).step_by(2).take_while(|i| i * i <= m)\n</code></pre>\n<p>I'm not sure if that's better or not.</p>\n<pre><code> while m % i as u64 == 0 { // is there a way to avoid all the casts to u64\n a.push(i as u64);\n m /= i as u64;\n }\n</code></pre>\n<p>You need casts because you are being inconsistent about your types. If you change the <code>usize</code> in the for loop to <code>u64</code> there will be no need for casts.</p>\n<pre><code> }\n if m > 2 {\n a.push(m);\n }\n return a;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T05:38:21.330",
"Id": "510599",
"Score": "0",
"body": "Thanks so much Winston! Just a quick question, in C, even though most of the time the compiler would optimize the following with optimization flags, it is better to compute an expression outside of loop or when it changes, what about Rush for `(m as f64).sqrt()` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T05:41:04.540",
"Id": "510600",
"Score": "0",
"body": "Also how comes index are only implemented for usize and not for u8,u16,u32,u64 etc? Would it be a breaking change?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T05:45:04.287",
"Id": "510602",
"Score": "1",
"body": "In Rust, `3 .. .(m as f64).sqrt()` is evaluated once before the loop starts. It's not like C where the expressions are repeatedly evaluated. So there is no optimization reason to move the sqrt calculation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T05:54:44.377",
"Id": "510603",
"Score": "0",
"body": "As for indexes, I think it follows from Rust's general practice of not allowing implicit type conversions. `usize` has a size depending on your architecture and thus isn't compatible with any of the types. But I really haven't looked closely at the rationale for that decision."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T05:35:00.117",
"Id": "258951",
"ParentId": "258948",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "258951",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T04:29:59.153",
"Id": "258948",
"Score": "0",
"Tags": [
"performance",
"primes",
"rust"
],
"Title": "Function returning a vec with prime factors of number"
}
|
258948
|
<p>I'm new to C# and would appreciate any feedback you might have on the following doubly-linked list implementation, particularly WRT the following language features:</p>
<ul>
<li>Exception handling</li>
<li>Debug.Assert</li>
<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/attributes/nullable-analysis" rel="nofollow noreferrer">Null state attributes</a> (e.g. <code>MaybeNullWhen</code>)</li>
<li>The Try pattern with <code>out</code> params</li>
<li>Test style with <code>xunit</code></li>
<li>Anything else that looks "weird" or unconventional</li>
</ul>
<p>Thanks very much for your time! <3</p>
<p>Imlementation:</p>
<pre><code>using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace DataStructures
{
public class LinkedList<T>
{
public LinkedList(T val)
{
Add(val);
}
public LinkedList()
{
}
public LinkedListNode<T>? HeadNode { get; set; }
public LinkedListNode<T>? TailNode { get; set; }
public int Count { get; private set; }
public T GetHead()
{
return HeadNode is null ? throw new InvalidOperationException(nameof(HeadNode)) : HeadNode.Val;
}
public T GetTail()
{
return TailNode is null ? throw new InvalidOperationException(nameof(TailNode)) : TailNode.Val;
}
public T Add(T val, int? index = null)
{
return index switch
{
null => AddLast(val),
0 => AddFirst(val),
_ => index == Count ? AddLast(val) : AddToMiddle(val, index.Value)
};
}
public void Clear()
{
HeadNode = null;
TailNode = null;
Count = 0;
}
public T GetAt(int index)
{
return GetNodeAt(index).Val;
}
public T RemoveAt(int index)
{
ValidateIndex(index);
return Remove(GetNodeAt(index));
}
public bool TryRemoveFor(Predicate<T> predicate, [ MaybeNullWhen(false) ] out T removed)
{
if (TryFindNode(predicate, out LinkedListNode<T>? node))
{
removed = Remove(node);
return true;
}
removed = default;
return false;
}
public bool TryFind(Predicate<T> predicate, [ MaybeNullWhen(false) ] out T found)
{
if (TryFindNode(predicate, out LinkedListNode<T>? foundNode))
{
found = foundNode.Val;
return true;
}
found = default;
return false;
}
bool TryFindNode(Predicate<T> predicate, [ NotNullWhen(true) ] out LinkedListNode<T>? node)
{
node = HeadNode;
while (node != null)
{
if (predicate(node.Val)) return true;
node = node.Next;
}
return false;
}
LinkedListNode<T> GetNodeAt(int index)
{
ValidateIndex(index);
Debug.Assert(TailNode != null, "The linked list should be non-empty");
if (index == Count - 1)
{
return TailNode;
}
Debug.Assert(HeadNode != null, "The linked list should be non-empty");
LinkedListNode<T> node = HeadNode;
for (var i = 0; i != index; i++)
{
Debug.Assert(node != null, "All nodes within the linked list must be defined");
Debug.Assert(node.Next != null, "This loop shouldn't run for the last entry in the linked list");
node = node.Next;
}
return node;
}
T Remove(LinkedListNode<T> node)
{
if (node.Prev is null)
{
HeadNode = node.Next;
}
else
{
node.Prev.Next = node.Next;
}
if (node.Next is null)
{
TailNode = node.Prev;
}
else
{
node.Next.Prev = node.Prev;
}
Count--;
if (Count <= 1) HeadNode = TailNode = HeadNode ?? TailNode;
return node.Val;
}
T AddFirst(T val)
{
if (HeadNode is null) return AddLast(val);
var newNode = new LinkedListNode<T>(val);
HeadNode.Prev = newNode;
HeadNode = newNode;
Count++;
return newNode.Val;
}
T AddToMiddle(T val, int index)
{
ValidateIndex(index, 1);
var newNode = new LinkedListNode<T>(val);
LinkedListNode<T> toShift = GetNodeAt(index);
LinkedListNode<T>? precedingNode = toShift.Prev;
Debug.Assert(precedingNode != null, "index should not refer to the head");
precedingNode.Next = newNode;
newNode.Prev = precedingNode;
toShift.Prev = newNode;
newNode.Next = toShift;
Count++;
return val;
}
T AddLast(T val)
{
var newNode = new LinkedListNode<T>(val);
if (HeadNode is null)
{
HeadNode = TailNode = newNode;
}
else
{
Debug.Assert(TailNode != null, "Head and tail should both be either null or non-null");
TailNode.Next = newNode;
newNode.Prev = TailNode;
TailNode = newNode;
}
Count++;
return newNode.Val;
}
void ValidateIndex(int index, int lowerBoundInclusive = 0)
{
if (index >= lowerBoundInclusive ||
index < Count)
{
return;
}
throw new ArgumentOutOfRangeException(nameof(index));
}
}
public class LinkedListNode<T>
{
public LinkedListNode(T val, LinkedListNode<T>? prev = null, LinkedListNode<T>? next = null)
{
Val = val;
Prev = prev;
Next = next;
}
public LinkedListNode<T>? Next { get; set; }
public LinkedListNode<T>? Prev { get; set; }
public T Val { get; }
}
}
</code></pre>
<p>Tests:</p>
<pre><code>using System;
using DataStructures;
using Xunit;
namespace TestDataStructures
{
public class LinkedListTest
{
const int TestValue = -100;
[ Fact ]
public void InitializeEmptyTest()
{
var ll = new LinkedList<int>();
Assert.Equal(0, ll.Count);
Assert.Null(ll.HeadNode!);
Assert.Null(ll.TailNode!);
Assert.Throws<InvalidOperationException>(() => ll.GetHead());
Assert.Throws<InvalidOperationException>(() => ll.GetTail());
}
[ Fact ]
public void InitializeNonEmptyTest()
{
var ll = new LinkedList<int>(TestValue);
Assert.Equal(1, ll.Count);
Assert.NotNull(ll.HeadNode!);
Assert.NotNull(ll.TailNode!);
Assert.Equal(TestValue, ll.GetHead());
Assert.Equal(TestValue, ll.GetTail());
}
[ Fact ]
public void AddTest()
{
const int numToAdd = 5;
var ll = new LinkedList<int>();
for (var i = 0; i < numToAdd; i++)
{
int added = ll.Add(i);
Assert.Equal(i, added);
}
LinkedListNode<int>? node = ll.HeadNode;
for (var i = 0; i < numToAdd; i++)
{
Assert.Equal(i, node?.Val);
node = node?.Next;
}
Assert.Equal(numToAdd, ll.Count);
}
[ Theory ]
[ InlineData(0, 0) ]
[ InlineData(3, 0) ]
[ InlineData(3, 1) ]
[ InlineData(3, 2) ]
[ InlineData(5, 3) ]
[ InlineData(3, 3) ]
public void AddAtIndexTest(int collectionSize, int? insertIndex = null)
{
var ll = new LinkedList<int>();
for (var i = 0; i < collectionSize; i++)
{
ll.Add(i);
}
int added = ll.Add(TestValue, insertIndex);
Assert.Equal(TestValue, added);
LinkedListNode<int>? node = ll.HeadNode;
for (var i = 0; i != insertIndex; i++)
{
node = node?.Next;
}
Assert.Equal(TestValue, node?.Val);
Assert.Equal(collectionSize + 1, ll.Count);
}
[ Fact ]
public void ClearTest()
{
const int numToAdd = 3;
var ll = new LinkedList<int>();
for (var i = 0; i < numToAdd; i++)
{
int added = ll.Add(i);
Assert.Equal(i, added);
}
ll.Clear();
Assert.Equal(0, ll.Count);
Assert.Null(ll.HeadNode!);
Assert.Null(ll.TailNode!);
Assert.Throws<InvalidOperationException>(() => ll.GetHead());
Assert.Throws<InvalidOperationException>(() => ll.GetTail());
}
[ Theory ]
[ InlineData(0, 3) ]
[ InlineData(1, 3) ]
[ InlineData(2, 3) ]
public void GetAtTest(int getIndex, int collectionSize)
{
var ll = new LinkedList<int>();
for (var i = 0; i < collectionSize; i++)
{
ll.Add(i);
}
int got = ll.GetAt(getIndex);
Assert.Equal(getIndex, got);
}
[ Theory ]
[ InlineData(3, 0, 0) ]
[ InlineData(3, 1, 1) ]
[ InlineData(3, 2, 2) ]
[ InlineData(3, 3) ]
[ InlineData(3, -1) ]
public void TryFindTest(int collectionSize, int toCompare, int? expected = null)
{
bool Predicate(int i)
{
return i == toCompare;
}
var ll = new LinkedList<int>();
for (var i = 0; i < collectionSize; i++)
{
ll.Add(i);
}
bool wasFound = ll.TryFind(Predicate, out int got);
Assert.Equal(expected.HasValue, wasFound);
Assert.Equal(expected ?? default, got);
}
[ Theory ]
[ InlineData(0, 3) ]
[ InlineData(1, 3) ]
[ InlineData(2, 3) ]
[ InlineData(2, 5) ]
public void RemoveAtTest(int removeIndex, int collectionSize)
{
var ll = new LinkedList<int>();
for (var i = 0; i < collectionSize; i++)
{
ll.Add(i);
}
int got = ll.RemoveAt(removeIndex);
Assert.Equal(removeIndex, got);
Assert.Equal(collectionSize - 1, ll.Count);
}
[ Theory ]
[ InlineData(3, 0, 0) ]
[ InlineData(3, 1, 1) ]
[ InlineData(3, 2, 2) ]
[ InlineData(3, 3) ]
[ InlineData(3, -1) ]
public void RemoveForTest(int collectionSize, int toCompare, int? expected = null)
{
bool Predicate(int i)
{
return i == toCompare;
}
var ll = new LinkedList<int>();
for (var i = 0; i < collectionSize; i++)
{
ll.Add(i);
}
bool wasFound = ll.TryRemoveFor(Predicate, out int got);
Assert.Equal(expected.HasValue, wasFound);
Assert.Equal(expected ?? default, got);
Assert.Equal(wasFound ? collectionSize - 1 : collectionSize, ll.Count);
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T05:28:24.867",
"Id": "510597",
"Score": "0",
"body": "If someone with 300+ rep could create the `nullable-reference-types` tag I'll add it to this question. [StackOverflow](https://stackoverflow.com/questions/tagged/nullable-reference-types) has the feature tagged with that name, so best to keep it the same."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T12:55:02.773",
"Id": "510631",
"Score": "3",
"body": "Please don't edit the question after it has been answered, especially the code. Everyone must be able to view the code as the original reviewer did."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T13:08:16.460",
"Id": "510632",
"Score": "0",
"body": "@pacmaninbw Ah, I left the original question's code alone and just added a new section with the updated code according to the feedback I got, the header explained this. I've seen that done on stack overflow, but if it's frowned upon I'll not do it again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T16:19:05.433",
"Id": "510656",
"Score": "1",
"body": "For more information, please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T02:18:01.787",
"Id": "510713",
"Score": "0",
"body": "@Mast Great post, thanks for that! I'll be sure not to edit the question in this way again :)"
}
] |
[
{
"body": "<p>In this review I'll focus on the implementation.</p>\n<h3><code>LinkedList</code></h3>\n<p>I have two problem with this name:</p>\n<ul>\n<li>It is a <strong>doubly</strong> linked list</li>\n<li>There is a <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1\" rel=\"nofollow noreferrer\">built-in BCL class</a> with same name</li>\n</ul>\n<p>I would highly recommend you to scrutinize the built-in class before you start to re-invent the wheel.</p>\n<p>Just to name a few things:</p>\n<ul>\n<li>There is a ctor which can receive an <code>IEnumerable</code>\n<ul>\n<li>This is a really powerful feature to help integrate with other collections</li>\n</ul>\n</li>\n<li><code>CopyTo</code> is yet again an extremely useful method from integration perspective</li>\n<li>There are methods like <code>AddAfter</code>, <code>AddBefore</code> which can ease the usage\n<ul>\n<li>Because we do not need to know the index</li>\n</ul>\n</li>\n<li><code>GetEnumerator</code> provides the ability to use <code>foreach</code> loops\n<ul>\n<li>In your case <code>GetForwardXYZ</code> and <code>GetBackwardXYZ</code> would make sense also</li>\n</ul>\n</li>\n</ul>\n<p>In case of doubly linked list it might not make too much sense to expose things like: <code>Head</code> and <code>Tail</code>. Their meaning are true only in case of forward iteration. But if you provide backward iteration as well their semantics break.</p>\n<h3><code>LinkedListNode</code></h3>\n<p><code>LinkedListNode</code> yet again this is also a <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlistnode-1\" rel=\"nofollow noreferrer\">built-in type</a></p>\n<ul>\n<li>It has a really useful property called <code>List</code>\n<ul>\n<li>This give you a pointer to that LinkedList where this node belongs</li>\n</ul>\n</li>\n</ul>\n<p>Unnecessary abbreviations:</p>\n<ul>\n<li><code>T val</code> >> <code>T value</code></li>\n<li><code>Prev</code> >> <code>Previous</code></li>\n</ul>\n<p>IMO these are just making your API look weird.</p>\n<ul>\n<li>If you don’t need to abbreviate then don’t do that</li>\n</ul>\n<hr />\n<h3><code>GetHead</code> / <code>GetTail</code></h3>\n<ul>\n<li>Personally I prefer this kind of one-liners:\n<ul>\n<li><strong>if</strong> data is present <strong>then</strong> return that one <strong>otherwise</strong> fallback</li>\n</ul>\n</li>\n<li>In case of C# 9:</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>
public T GetHead() => HeadNode is not null ? HeadNode.Val : throw new InvalidOperationException(nameof(HeadNode));\n</code></pre>\n<ul>\n<li>In case of C# 8:</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>public T GetHead() => HeadNode?.Val ?? throw new InvalidOperationException(nameof(HeadNode));\n</code></pre>\n<ul>\n<li>Please bear in mind that this could work only if you restrict <code>T</code> either to <code>struct</code> or <code>class</code></li>\n</ul>\n<h3><code>Add</code></h3>\n<ul>\n<li>I think instead of <code>int? index = null</code> I would use <code>int? index = default</code>\n<ul>\n<li>It expresses the intent in a bit more clear way</li>\n</ul>\n</li>\n<li>I would split your default case in your switch expression like this:</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>public T Add(T val, int? index = null)\n => index switch\n {\n null => AddLast(val),\n 0 => AddFirst(val),\n _ when index == Count => AddLast(val),\n _ => AddToMiddle(val, index.Value)\n };\n</code></pre>\n<ul>\n<li>Maybe it might make sense to split this method into two: <code>Add</code> and <code>AddAt</code></li>\n</ul>\n<h3><code>TryRemoveFor</code>, <code>TryFind</code></h3>\n<ul>\n<li>They had a huge resemblance, it might make sense to have a common ground</li>\n<li>I’m not really a huge fan of naming like <code>Predicate<T> predicate</code>\n<ul>\n<li>I prefer names like <code>nodeSelector</code>, <code>nodeValueMatcher</code>, etc.</li>\n</ul>\n</li>\n</ul>\n<h3><code>GetNodeAt</code> / <code>Remove</code></h3>\n<ul>\n<li><code>node.Next</code> might have null, because it has a public setter that means you can easily have <code>NullReferenceException</code> here</li>\n<li>Same applies to <code>node.Prev.Next</code> and <code>node.Next.Prev</code></li>\n</ul>\n<h3><code>ValidateIndex</code></h3>\n<ul>\n<li>Even though <code>ArgumentOutOfRangeException</code> does not have a ctor where you can specify the allowed range, I do recommend to provide helpful error message, something like this:</li>\n</ul>\n<blockquote>\n<p>The allowed range is [0…n], the provided index is n+3. Please try to provide\nindex inside the range.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T10:41:47.170",
"Id": "510625",
"Score": "1",
"body": "Thanks very much, there's some great advice here! I'll make some changes.\n\nI'll edit the original post to make it clear that this was just a code exercise and I'm not intending to use this implementation in an application. I would definitely use `System.Collections.Generic.LinkedList` in that case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T11:45:42.500",
"Id": "510627",
"Score": "1",
"body": "WRT `TryRemoveFor` and `TryFind`, good point they are super similar. I merged them but then decided to pull them apart again - they're pretty simple functions and not much was saved by having a common base. I often wait until I have 3 repetitions before refactoring, anyways.\n\nWRT the potential `NullReferenceExceptions`, yes good point! I added some exceptions to the code, but I guess if I wanted to do this properly I would add safety guards to ensure consumers couldn't inject null nodes to the middle of the list."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T08:43:42.063",
"Id": "258960",
"ParentId": "258950",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "258960",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T05:24:33.660",
"Id": "258950",
"Score": "1",
"Tags": [
"c#",
"unit-testing",
"null",
"xunit",
"nullable-reference-types"
],
"Title": "Conventional C# for LinkedList with (non-)nullable references + xunit tests"
}
|
258950
|
For questions related to C# 8's nullable reference types.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T07:37:04.747",
"Id": "258957",
"Score": "0",
"Tags": null,
"Title": null
}
|
258957
|
<p>I would like to get some feed back on my code; the goal is to get all agencies address of banks. I wrote a pretty simple brute force algorithm.
I was wondering if you would have any advice to improve the code, design it differently (do I need an OOP approach here) etc .</p>
<pre><code>import requests
from lxml import html
groupe = "credit-agricole"
dep = '21'
groupes =["credit-agricole"]
deps = ['53', '44', '56', '35', '22', '49', '72', '29', '85']
def get_nb_pages(groupe,dep):
""" Return nb_pages ([int]): number of pages containing banks information .
Args:
groupe ([string]): bank groupe ("credit-agricole",...)
dep ([string]): departement ("01",...)
"""
url ="https://www.moneyvox.fr/pratique/agences/{groupe}/{dep}".format(groupe=groupe,dep=dep)
req = requests.get(url)
raw_html = req.text
xpath = "/html/body/div[2]/article/div/div/div[3]/div[2]/nav/a"
tree = html.fromstring(raw_html)
nb_pages = len(tree.xpath(xpath)) +1
return nb_pages
def get_agencies(groupe,dep,page_num):
""" Return agencies ([List]): description of agencies scrapped on website target page.
Args:
groupe ([string]): bank groupe ("credit-agricole",...)
dep ([string]): departement ("01",...)
page_num ([int]): target page
"""
url ="https://www.moneyvox.fr/pratique/agences/{groupe}/{dep}/{page_num}".format(groupe=groupe,dep=dep,page_num=page_num)
req = requests.get(url)
raw_html = req.text
xpath = '//div[@class="lh-bloc-agence like-text"]'
tree = html.fromstring(raw_html)
blocs_agencies = tree.xpath(xpath)
agencies = []
for bloc in blocs_agencies:
agence = bloc.xpath("div/div[1]/h4")[0].text
rue = bloc.xpath("div/div[1]/p[1]")[0].text
code_postale = bloc.xpath("div/div[1]/p[2]")[0].text
agencies.append((agence,rue,code_postale))
return agencies
def get_all(groupes,deps):
"""Return all_agencies ([List]): description of agencies scrapped.
Args:
groupes ([List]): target groups
deps ([List]): target departments
"""
all_agencies = []
for groupe in groupes:
for dep in deps:
nb_pages = get_nb_pages(groupe,dep)
for p in range(1,nb_pages+1):
agencies = get_agencies(groupe,dep,p)
all_agencies.extend(agencies)
df_agencies = pd.DataFrame(all_agencies,columns=['agence','rue','code_postale'])
return df_agencies
get_nb_pages(groupe,dep)
get_agencies(groupe,dep,1)
df_agencies = get_all(groupes,deps)
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>It's fine for your strings - and scraped web content - to be localised in French; but ensure that your variables are in English (groupe -> group) for consistency</li>\n<li>Prefer tuples over lists when you have immutable data</li>\n<li>Add PEP484 type hints when possible</li>\n<li>Do not leave those first four variables in global scope; move them to a function</li>\n<li>Consider using f-strings instead of <code>format</code> calls</li>\n<li>Always check to see if your <code>requests</code> calls fail; the easiest way is via <code>raise_for_status</code></li>\n<li>Tell <code>requests</code> when you're done with a response via context management</li>\n<li>Use actual integers for your department numbers instead of stringly-typed data</li>\n<li>Consider using an intermediate dataclass for your agency data instead of implicit tuples</li>\n<li>Consider using generator functions (<code>yield</code>) to simplify your iterative code</li>\n</ul>\n<h2>First Suggested</h2>\n<pre><code>from dataclasses import dataclass, astuple\nfrom typing import Iterable, Collection\n\nimport pandas as pd\nimport requests\nfrom lxml import html\nfrom lxml.html import HtmlElement\n\n\n@dataclass\nclass Agency:\n name: str\n street: str\n postal_code: str\n\n @classmethod\n def from_block(cls, block: HtmlElement) -> 'Agency':\n return cls(\n name=block.xpath("div/div[1]/h4")[0].text,\n street=block.xpath("div/div[1]/p[1]")[0].text,\n postal_code=block.xpath("div/div[1]/p[2]")[0].text,\n )\n\n\ndef get_nb_pages(group: str, department: int) -> int:\n """ Return nb_pages ([int]): number of pages containing banks information .\n Args:\n groupe ([string]): bank groupe ("credit-agricole",...)\n department ([string]): departement ("01",...)\n """\n url = f"https://www.moneyvox.fr/pratique/agences/{group}/{department}"\n with requests.get(url) as req:\n req.raise_for_status()\n raw_html = req.text\n\n xpath = "/html/body/div[2]/article/div/div/div[3]/div[2]/nav/a"\n tree = html.fromstring(raw_html)\n return len(tree.xpath(xpath)) + 1\n\n\ndef get_agencies(group: str, department: int, page_num: int) -> Iterable[Agency]:\n """ Return agencies ([List]): description of agencies scrapped on website target page.\n Args:\n groupe ([string]): bank groupe ("credit-agricole",...)\n department ([string]): departement ("01",...)\n page_num ([int]): target page\n """\n url = f"https://www.moneyvox.fr/pratique/agences/{group}/{department}/{page_num}"\n with requests.get(url) as req:\n req.raise_for_status()\n raw_html = req.text\n\n xpath = '//div[@class="lh-bloc-agence like-text"]'\n tree = html.fromstring(raw_html)\n for block in tree.xpath(xpath):\n yield Agency.from_block(block)\n\n\ndef get_all(groups: Iterable[str], departments: Collection[int]):\n """Return all_agencies ([List]): description of agencies scrapped.\n Args:\n groupes ([List]): target groups\n departments ([List]): target departments\n """\n for group in groups:\n for department in departments:\n nb_pages = get_nb_pages(group, department)\n for page in range(1, nb_pages + 1):\n yield from get_agencies(group, department, page)\n\n\ndef main():\n group = "credit-agricole"\n department = 21\n groups = ("credit-agricole",)\n departments = (53, 44,) # ... 56, 35, 22, 49, 72, 29, 85)\n\n n_pages = get_nb_pages(group, department)\n agencies = tuple(get_agencies(group, department, page_num=1))\n\n all_agencies = get_all(groups, departments)\n df_agencies = pd.DataFrame(\n (astuple(agency) for agency in all_agencies),\n columns=('agence', 'rue', 'code_postale'),\n )\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>All of that being the case, your approach using xpath selectors is very fragile. Here is an alternate approach that uses named elements with classes and IDs where available. It is incomplete because I think the site rate-limited my IP, which is of course a direct risk of scraping and totally within the rights of the website.</p>\n<h2>BeautifulSoup Alternate</h2>\n<pre><code>import re\nfrom dataclasses import dataclass, astuple\nfrom typing import Iterable, Dict, ClassVar, Pattern\nfrom bs4 import BeautifulSoup, Tag\n\nimport pandas as pd\nfrom requests import Session\n\nROOT = 'https://www.moneyvox.fr'\n\n\n@dataclass\nclass Branch:\n name: str\n street: str\n city: str\n postal_code: str\n path: str\n\n @classmethod\n def scrape_all(cls, session: Session, path: str) -> Iterable['Branch']:\n page = ''\n while True:\n with session.get(ROOT + path + page) as response:\n response.raise_for_status()\n doc = BeautifulSoup(response.text, 'xml')\n\n body = doc.select_one('div.main-body')\n city = None\n\n for head_or_cell in body.select('h2, div.lh-bloc-agence'):\n if head_or_cell.name == 'h2':\n city = head_or_cell.text\n elif head_or_cell.name == 'div':\n street, postal_code = head_or_cell.select('p')\n yield cls(\n name=head_or_cell.h4.text,\n street=street.text,\n city=city,\n postal_code=postal_code.text,\n path=head_or_cell.select_one('a.lh-btn-info')['href'],\n )\n\n # perform depagination here\n\n\n@dataclass\nclass Department:\n name: str\n code: str\n path: str\n n_branches: int\n\n re_count: ClassVar[Pattern] = re.compile(r'\\d+')\n\n @classmethod\n def from_li(cls, li: Tag) -> 'Department':\n return cls(\n name=li.strong.text,\n path=li.a['href'],\n code=cls.re_count.search(li.a.text)[0],\n n_branches=int(cls.re_count.search(li.em.text)[0]),\n )\n\n\n@dataclass\nclass Agency:\n name: str\n category: str\n path: str\n\n @classmethod\n def scrape_all(cls, session: Session) -> Iterable['Agency']:\n with session.get(ROOT + '/pratique/agences') as response:\n response.raise_for_status()\n doc = BeautifulSoup(response.text, 'xml')\n\n body = doc.select_one('div.main-body')\n category = None\n for head_or_cell in body.select('h2, a.lh-lien-bloc-liste'):\n if head_or_cell.name == 'h2':\n category = head_or_cell.text\n elif head_or_cell.name == 'a':\n yield cls(\n name=head_or_cell.text,\n category=category,\n path=head_or_cell['href'],\n )\n\n def get_departments(self, session: Session) -> Dict[str, int]:\n with session.get(ROOT + self.path) as response:\n response.raise_for_status()\n doc = BeautifulSoup(response.text, 'xml')\n\n for li in doc.select('#tabs-departement li'):\n yield Department.from_li(li)\n\n def __str__(self):\n return self.name\n\n\ndef main():\n pd.set_option('display.max_columns', None)\n pd.set_option('display.width', None)\n\n with Session() as session:\n agencies = {a.name: a for a in Agency.scrape_all(session)}\n agency_df = pd.DataFrame(\n (astuple(a) for a in agencies.values()),\n columns=('Nom', 'Catégorie', 'Lien'),\n )\n print(agency_df)\n\n agency = agencies['Crédit Agricole']\n departments = {d.name: d for d in agency.get_departments(session)}\n\n department = departments['Ardennes']\n branches = {b.name: b for b in Branch.scrape_all(session, department.path)}\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T04:18:37.210",
"Id": "258997",
"ParentId": "258961",
"Score": "1"
}
},
{
"body": "<p>To emphasize what Reinderien already said, always check the return of your calls to requests. <code>status_code</code> should return 200. If you get anything else you should stop and investigate. It is possible that the website is blocking you and there is no point running blind.</p>\n<p>Also, I recommend that you <strong>spoof the user agent</strong>, otherwise it is obvious to the web server that you are running a <strong>bot</strong> and they may block you, or apply more stringent rate limiting measures than a casual user would experience. By default the user agent would be something like this: python-requests/2.25.1.</p>\n<p>And since you are making repeated calls, you should use a <a href=\"https://docs.python-requests.org/en/master/user/advanced/\" rel=\"nofollow noreferrer\">session</a> instead. Reinderien already refactored your code with session but did not mention this point explicitly. The benefits are persistence (when using cookies for instance) and also more efficient connection pooling at TCP level. And you can use session to set default headers for all your requests.</p>\n<p>Example:</p>\n<pre><code>>>> session = requests.session()\n>>> session.headers\n{'User-Agent': 'python-requests/2.25.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}\n>>> \n</code></pre>\n<p>Change the user agent for the session, here we spoof Firefox:</p>\n<pre><code>session.headers.update({'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:87.0) Gecko/20100101 Firefox/87.0'})\n</code></pre>\n<p>And then you can use session.get to retrieve pages.</p>\n<p>May you could be interested in <strong>prepared queries</strong> too. I strongly recommend that Python developers get acquainted with that section of the documentation.</p>\n<p>To speed up the process you could also add parallel processing, for example using threads. But be gentle, if you have too many open connections at the same time, it is one thing that can get you blocked. Usage patterns have to remain reasonable and human-like.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T21:15:22.143",
"Id": "259028",
"ParentId": "258961",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T09:11:57.237",
"Id": "258961",
"Score": "2",
"Tags": [
"python",
"design-patterns",
"web-scraping"
],
"Title": "Web scraping and design pattern lifting"
}
|
258961
|
<p>This is my implementation of the divide-and-conquer Quicksort algorithm using the <a href="https://en.wikipedia.org/wiki/Quicksort#Lomuto_partition_scheme" rel="nofollow noreferrer">Lomuto partition scheme</a> in C. This is part of a personal project and I'm following Linus Torvalds's <a href="https://www.kernel.org/doc/html/v4.10/process/coding-style.html" rel="nofollow noreferrer">coding style</a>.</p>
<pre><code>void swap(int *i, int *j)
{
int tmp = *i;
*i = *j;
*j = tmp;
}
int partition(int *arr, int l, int r)
{
int pivot = arr[r];
int i = l;
for (int j = l; j < r; ++j) {
if (arr[j] < pivot) {
swap(&arr[i], &arr[j]);
++i;
}
}
swap(&arr[i], &arr[r]);
return i;
}
void quicksort(int *arr, int l, int r)
{
if (l >= r)
return;
int i = partition(arr, l, r);
quicksort(arr, l, i - 1);
quicksort(arr, i + 1, r);
}
</code></pre>
<p>The function <code>void quicksort(int *arr, int l, int r)</code> can be called like this:</p>
<pre><code>int arr[] = {4, 1, 0, 2, 5, 3, 8, 9, 7, 6};
size_t arrlen = sizeof(arr) / sizeof(int);
quicksort(arr, 0, arrlen - 1);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T10:42:11.697",
"Id": "510820",
"Score": "0",
"body": "HI @andySukowsiBang - partition function doesn't seem to be correct ... It always does a swap on the first element with itself ... should it perhaps be `for (j = l+1;`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T12:32:00.957",
"Id": "510828",
"Score": "0",
"body": "@MrR You are partially right. The first element is swapped with itself, but the reason why the for-loop needs to start with `j = l` is that `++i` has to be reached if the first element is smaller than `pivot`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T18:44:29.767",
"Id": "511292",
"Score": "0",
"body": "@MrR Is there something else that could be optimized?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T20:44:39.857",
"Id": "511308",
"Score": "0",
"body": "@AndySukowskiBang Anything unnecessary is always a problem. What happens for bad inputs - e.g. negative numbers, null value for `arr`, `&arr[offset]` might be slower than using pointers directly [depends on your platform & compiler]. Is it really the intention for partition to always do at least one swap (whenever l < r)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T13:01:49.157",
"Id": "258962",
"Score": "3",
"Tags": [
"algorithm",
"c",
"array",
"sorting",
"quick-sort"
],
"Title": "Quicksort using Lomuto partition scheme in C"
}
|
258962
|
<p>If used right, <code>strcmp</code> is not dangerous. However <a href="https://stackoverflow.com/q/1623769/10870835">the code calling it might be</a>. Limiting the opportunity for bugs I might in large teams "dictate" some kind of preemptive strike against bugs from bad calling code. It seems problem number one is comparing not zero-terminated strings. The core of my solution so far is this:</p>
<pre><code> // ----------------------------------------------
//
#include<assert.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define VERIFY(X) do { if (!(X)) { perror(#X); exit(0); } } while(0)
#define B(X_) (X_) ? "true" : "false"
#define P(F,X_) fprintf( stdout, "\n%4d : %16s : " F, __LINE__, #X_, (X_))
#undef COUNT_OF
#define COUNT_OF(x) ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % \
sizeof(0[x])))))
// safer strcmp
static int safer_strcmp_ (
const size_t N,
const size_t M,
const char (*L)[N],
const char (*R)[M])
{
VERIFY( L );
VERIFY( R );
VERIFY( 0 == ((*L)[N]) );
VERIFY( 0 == ((*R)[M]) );
const char * str1 = &(*L)[0] ;
const char * str2 = &(*R)[0] ;
VERIFY( str1 );
VERIFY( str2 );
// https://codereview.stackexchange.com/a/31954/179062
while (*str1 && *str1 == *str2) {
str1++;
str2++;
}
return *str1 - *str2;
} // eof safer_strcmp_
#undef COMPARE
// macro front is OK for string literals
// COUNT_OF includes the EOS char, hence the -1
#define COMPARE(A,B) \
safer_strcmp_( COUNT_OF(A) - 1 ,COUNT_OF(B) - 1, &A, &B )
int main(void) {
// does not compile: P("%d", COMPARE( NULL,"")) ;
P("%d", COMPARE("","")) ;
P("%d", COMPARE("A","AA")) ;
P("%d", COMPARE("A","A")) ;
P("%d", COMPARE("AA","A")) ;
P("%d", COMPARE("B","A")) ;
return 0 ;
}
</code></pre>
<p><a href="https://godbolt.org/z/6bbeWazYW" rel="nofollow noreferrer">https://godbolt.org/z/6bbeWazYW</a></p>
<p>Basically, the code just checks if both strings are properly terminated. That is a macro for calling it with literals:</p>
<p>The macro hides the complexity of making that call. If using variables, anything I can think of involves using <code>strlen</code> / <code>strnlen</code> and that defeats the purpose.</p>
<p>Is there a way of using the above with variables?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T15:00:26.960",
"Id": "510643",
"Score": "0",
"body": "This looks more like a question of how to do something than a request for a code review. Consider asking this on [StackOverflow](https://stackoverflow.com/) instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T18:32:58.693",
"Id": "510667",
"Score": "3",
"body": "Are you targetting C99 or C11? You can't target both at the same time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T19:21:22.280",
"Id": "510677",
"Score": "0",
"body": "@Mast you are right and I am not targeting them both in the same time. These are just tags on this post. Please see the Godbolt link provided for a working sample."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T19:57:07.417",
"Id": "510685",
"Score": "0",
"body": "Arthur, that is a [Chromium macro](https://stackoverflow.com/a/4415646/10870835)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T19:09:42.027",
"Id": "511295",
"Score": "1",
"body": "After you get answers you are not supposed to edit the question, especially the code. Please (re)read [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers). Every time you edit the code it shows up in chat and we need to review the edit. Changing the question after you have answers invalidates the answers. The code must remain the same as what the reviewers that posted answers saw or their answers don't make sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T19:13:22.283",
"Id": "511296",
"Score": "0",
"body": "Ok that is reasonable ...let me then add my own \"answer\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T19:15:43.060",
"Id": "511297",
"Score": "0",
"body": "If your answer explains why the new version is better than the old one, sure. That's kind-of a review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T23:31:01.190",
"Id": "511328",
"Score": "0",
"body": "Your code looks very inconsistent regarding spacing and indentation. Please run your code through a beautifier next time before posting it, to make it easier to review."
}
] |
[
{
"body": "<p>The macro is only safe when passed string literals, it is not safe when you pass it pointers to strings. In particular, given a <code>char *s</code>, the result of <code>COUNT_OF(s)</code> is 8 on 64-bit machines. This means that if you pass it pointers to strings shorter than 8 characters (including the NUL-byte), it will read past the end of the string.\nGiven that the whole point of the excercise is to provide more safety than regular <code>strcmp()</code>, this macro fails to deliver the promise.\nThe macro is also not very useful for string literals, as the compiler will already guarantee that the literals are NUL-terminated.</p>\n<p>It is not possible to make this code work with variables. The only way to check the length of a string pointed to by a <code>char *</code> variable is to call <code>strlen()</code> on it, and that assumes that the string is properly NUL-terminated. The only way to make this work is to have the caller pass the length of the string, but this just shifts the burden to the caller.</p>\n<p>The best strategy in my opinion is just to have the caller call <code>strcmp()</code> when it knows both arguments are proper NUL-terminated strings, and <a href=\"https://en.cppreference.com/w/c/string/byte/strncmp\" rel=\"nofollow noreferrer\"><code>strncmp()</code></a> if it has knowledge of the size of one or both of the strings.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T20:21:58.233",
"Id": "511303",
"Score": "0",
"body": "It might seem like it is safe, but consider what happens if we pass in very large values of `N` and `M`, say `SIZE_MAX - 1`. It would then check the byte right before the string. What if it happens to contain a zero? And even if you don't allow values that would cause the pointer to wrap, consider that not all memory in the process's memory space might be validly mapped. I could give it an `N` that points to a valid piece of memory with a NUL-byte, but there might be invalid memory between that and the start of the string."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T21:18:23.237",
"Id": "258984",
"ParentId": "258964",
"Score": "1"
}
},
{
"body": "<p><strong>Subtle functional bug</strong></p>\n<p><code>return *str1 - *str2;</code> may return the wrong sign value when the <code>char</code> values are negative.</p>\n<p>C string library functions specify:</p>\n<blockquote>\n<p>For all functions in this subclause, each character shall be interpreted as if it had the type <code>unsigned char</code> (and therefore every possible object representation is valid and has a different value). C17 § 7.24.1 3</p>\n</blockquote>\n<p>A repaired compare below.</p>\n<p>Pedantic: This code also properly handles rare non-2's complement and when <code>CHAR_MAX > INT_MAX</code> unlike OP's.</p>\n<pre><code>const unsigned char *u1 = (const unsigned char *) str1;\nconst unsigned char *u2 = (const unsigned char *) str2;\nwhile (*u1 && *u1 == *u2) {\n u1++;\n u2++;\n}\nreturn (*u1 > *u2) - (*u1 < *u2);\n</code></pre>\n<p><strong>What is a <em>string</em>?</strong></p>\n<p>OP reports "It seems problem number one is comparing not zero-terminated strings.". The C library defines <em>string</em> below. A <em>string</em> always contains a <em>null character</em> <code>'\\0'</code>.</p>\n<hr />\n<blockquote>\n<p>A <em>string</em> is a contiguous sequence of characters terminated by and including the first null character.</p>\n</blockquote>\n<p>Of course, an array of characters may lack a <em>null character</em> and so this function may have value with those non-strings.</p>\n<hr />\n<p>Calling <code>COMPARE()</code> with a pointer and not an array leads to troubles, unlike <code>strcmp()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T02:17:05.630",
"Id": "510712",
"Score": "0",
"body": "Thanks for the sober response."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T19:01:49.307",
"Id": "511294",
"Score": "0",
"body": "I reverted back to using `strcmp()` after all the checks are done."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T21:27:14.197",
"Id": "258985",
"ParentId": "258964",
"Score": "4"
}
},
{
"body": "<p>Apologies for changing the code that was answered. Since a few days ago I have evolved :)</p>\n<p>Yes, that function is ok and will work for any legal call and that macro will work only with two string literals, of course. The only change I want to add inside the function is to call <code>strncmp()</code> instead of reinventing it</p>\n<pre><code>// two char arrays comparison\n int safer_strcmp_ (\n const size_t N, const size_t M, \n /* pointer to char array of length N*/\n const char (*L)[N], \n /* pointer to char array of length M */\n const char (*R)[M])\n {\n VERIFY( L && R );\n VERIFY( N > 0 && M > 0 );\n // checking if both strings\n // are zero terminated\n VERIFY( 0 == ((*L)[N]) );\n VERIFY( 0 == ((*R)[M]) );\n\n return strncmp( *L, *R, MIN(N,M) );\n }\n</code></pre>\n<p>Inbuilt <code>str(n)cmp()</code> is certainly much faster vs. what any result of my re-invention might be.</p>\n<p>Thank you all for your involvement and time spent.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T19:24:33.243",
"Id": "259254",
"ParentId": "258964",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T14:03:12.117",
"Id": "258964",
"Score": "0",
"Tags": [
"c",
"strings"
],
"Title": "My safer strcmp"
}
|
258964
|
<p>I made simple interpreter in C and now, I want to make my code better.</p>
<p>Here is my code:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include "def.h"
int main(int argc, char *argv[])
{
int i;
char ch[100];
char input[100];
char sinput[100];
char output[100];
int while_int;
if (argv[1] != NULL)
{
char *file_extension = strrchr(argv[1], '.');
if (file_extension == NULL)
{
printf("Error\nNo File Extension\n");
}
else if (strcmp(file_extension, ".pri") == FALSE)
{
FILE *fp = fopen(argv[1], "r");
fgets(ch, 100, fp);
fclose(fp);
}
}
do
{
if (argv[1] == NULL)
{
printf(">>> ");
scanf("%[^\n]%*c", ch);
}
if (ch[0] != '@' & argv[1] == NULL)
{
while_int = TRUE;
}
else
{
while_int = FALSE;
}
if (ch[0] == '"' & ch[strlen(ch) - 1] == '"')
{
if (strlen(ch) == 1 | strlen(ch) == 2)
{
printf("Error\nError Code: PRINTLANG.1\n");
ch[0] = '@';
}
else
{
chh(ch, output, 0, strlen(ch) - 1);
printf("%s\n", output);
ch[0] = '@';
}
}
if (ch[0] == 'p' & ch[1] == 'r' & ch[2] == 'i' & ch[3] == 'n' & ch[4] == 't')
{
if (ch[5] == '(' & ch[strlen(ch) - 1] == ')')
{
if (ch[6] == '"' & ch[strlen(ch) - 2] == '"')
{
if (strlen(ch) == 8 | strlen(ch) == 9)
{
printf("Error\nError Code: PRINTLANG.2\n");
ch[0] = '@';
}
else
{
chh(ch, output, 6, strlen(ch) - 2);
printf("%s\n", output);
ch[0] = '@';
}
}
else if (ch[6] == 'i' & ch[7] == 'n' & ch[8] == 'p' & ch[9] == 'u' & ch[10] == 't')
{
if (ch[11] == '(' & ch[strlen(ch) - 2] == ')')
{
if (strlen(ch) == 14)
{
scanf("%[^\n]%*c", input);
printf("%s\n", input);
ch[0] = '@';
}
else
{
if (ch[12] == '"' & ch[strlen(ch) - 3] == '"')
{
if (strlen(ch) == 16)
{
printf("Error\nError Code: PRINTLANG.3\n");
ch[0] = '@';
}
else
{
chh(ch, output, 12, strlen(ch) - 3);
printf("%s", output);
scanf("%[^\n]%*c", input);
printf("%s\n", input);
ch[0] = '@';
}
}
else
{
printf("Error\nError Code: PRINTLANG.4\n");
}
}
}
else
{
printf("Error\nError Code: PRINTLANG.5\n");
ch[0] = '@';
}
}
else
{
printf("Error\nError Code: PRINTLANG.6\n");
ch[0] = '@';
}
}
else
{
printf("Error\nError Code: PRINTLANG.7\n");
ch[0] = '@';
}
}
else if (ch[0] == 'e' & ch[1] == 'c' & ch[2] == 'h' & ch[3] == 'o')
{
if (ch[4] == ' ')
{
if (ch[5] == '"' & ch[strlen(ch) - 1] == '"')
{
chh(ch, output, 5, strlen(ch) - 1);
printf("%s\n", output);
ch[0] = '@';
}
else
{
printf("Error\nError Code: PRINTLANG.8\n");
ch[0] = '@';
}
}
else
{
printf("Error\nError Code: PRINTLANG.9\n");
ch[0] = '@';
}
}
else
{
ch[0] = '@';
}
}
while (while_int);
}
</code></pre>
<p>def.h:</p>
<pre><code>#ifndef _DEF_H
# define _DEF_H
#endif
#define TRUE (1 == 1)
#define FALSE (1 == 0)
char *chh(char *ch, char *output, int x, int y)
{
int i;
for (i = x + 1; i < y; i++)
{
output[i - (x + 1)] = ch[i];
}
return output;
}
</code></pre>
<p><a href="https://github.com/ArianKG/PrintLang" rel="nofollow noreferrer">GitHub Link</a></p>
<p><a href="https://codereview.stackexchange.com/questions/256533/very-simple-interpreter-in-c">Recommended question (My question)</a></p>
|
[] |
[
{
"body": "<h1>Use a parser generator</h1>\n<p>Since it seems like you intend to extend the language you are currently supporting, I cannot recommend that you continue writing the parsing code yourself. It is already not pretty, and even though it could be improved, there are <a href=\"https://en.wikipedia.org/wiki/Compiler-compiler\" rel=\"nofollow noreferrer\">common tools</a> available that, given a description of the tokens and the grammar of your language, generate the C code necessary to parse that language. Most well known are <a href=\"https://en.wikipedia.org/wiki/Flex_(lexical_analyser_generator)\" rel=\"nofollow noreferrer\">GNU Flex</a> and <a href=\"https://en.wikipedia.org/wiki/GNU_Bison\" rel=\"nofollow noreferrer\">GNU Bison</a>.</p>\n<h1>Split up your program into multiple functions</h1>\n<p>Apart from the one function in <code>def.h</code>, which should actually be in its own <code>.c</code> file, you have all the functionality inside <code>main()</code>. You should try to split up your program into individual functions that each do a simple thing. This will make your code easier to read and easier to maintain.</p>\n<h1>Print useful error messages</h1>\n<p>When your interpreter encounters an error, it just prints:</p>\n<pre><code>Error\nError Code: PRINTLANG.n\n</code></pre>\n<p>Where <code>n</code> is some number. This is very unhelpful. Error messages are there to inform the user what has gone wrong. So write something that tells the user what was wrong, and if possible also a suggestion of how they can do to fix the problem. For example, instead of <code>PRINTLANG.1</code>, write:</p>\n<pre><code>Error: empty or unterminated quoted string\n</code></pre>\n<p>Also make it a habit to write error messages to <code>stderr</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T16:38:07.170",
"Id": "258970",
"ParentId": "258966",
"Score": "1"
}
},
{
"body": "<p>I assume that you are learning how to write code. So, to keep it simple, I think you should focus on dividing your code into layers of abstraction. If a function becomes too\nlong, break it into subfunctions. Try to keep code in a function at a uniform abstraction level, avoid mixing high level and low level work.</p>\n<p>This is an art that takes a lot of practice to get right. Instead of thinking of your code as something that the computer will execute, you should think of it as something another human will read. That will give you the right mindset.</p>\n<p>Introducing layers of abstraction to your code, might look like the code below. Notice how redundant variables have been eliminated. This code makes more sense if you start at the bottom. Try to improve it further by making it readable from the top as well. To do this you could introduce some comments that explains the context, or you could rethink the functions to be generic, instead of specific to a parent calling them at one exact spot - like they are now.</p>\n<p>You should spend as much time making your code readable, as you have spent time making it work correctly.</p>\n<p>Happy coding.</p>\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <stddef.h>\n#include <string.h>\n\n#include "def.h"\n\nvoid do_quotes(char* ch)\n{\n char output[100];\n\n if (strlen(ch) == 1 | strlen(ch) == 2)\n {\n printf("Error\\nError Code: PRINTLANG.1\\n");\n ch[0] = '@';\n }\n else\n {\n chh(ch, output, 0, strlen(ch) - 1);\n printf("%s\\n", output);\n ch[0] = '@';\n }\n}\n\nvoid do_print_quote(char* ch)\n{\n char output[100];\n\n if (strlen(ch) == 8 | strlen(ch) == 9)\n {\n printf("Error\\nError Code: PRINTLANG.2\\n");\n ch[0] = '@';\n }\n else\n {\n chh(ch, output, 6, strlen(ch) - 2);\n printf("%s\\n", output);\n ch[0] = '@';\n }\n}\n\nvoid do_print_input(char* ch)\n{\n char output[100];\n char input[100];\n\n if (ch[11] == '(' & ch[strlen(ch) - 2] == ')')\n {\n if (strlen(ch) == 14)\n {\n scanf("%[^\\n]%*c", input);\n printf("%s\\n", input);\n ch[0] = '@';\n }\n else\n {\n if (ch[12] == '"' & ch[strlen(ch) - 3] == '"')\n {\n if (strlen(ch) == 16)\n {\n printf("Error\\nError Code: PRINTLANG.3\\n");\n ch[0] = '@';\n }\n else\n {\n chh(ch, output, 12, strlen(ch) - 3);\n printf("%s", output);\n scanf("%[^\\n]%*c", input);\n printf("%s\\n", input);\n ch[0] = '@';\n }\n }\n else\n {\n printf("Error\\nError Code: PRINTLANG.4\\n");\n }\n }\n }\n else\n {\n printf("Error\\nError Code: PRINTLANG.5\\n");\n ch[0] = '@';\n }\n}\n\nvoid do_print(char* ch)\n{\n if (ch[5] == '(' & ch[strlen(ch) - 1] == ')')\n {\n if (ch[6] == '"' & ch[strlen(ch) - 2] == '"')\n {\n do_print_quote(ch);\n }\n else if (ch[6] == 'i' & ch[7] == 'n' & ch[8] == 'p' & ch[9] == 'u' & ch[10] == 't')\n {\n do_print_input(ch);\n }\n else\n {\n printf("Error\\nError Code: PRINTLANG.6\\n");\n ch[0] = '@';\n }\n }\n else\n {\n printf("Error\\nError Code: PRINTLANG.7\\n");\n ch[0] = '@';\n }\n}\n\nvoid do_echo(char* ch)\n{\n char output[100];\n\n if (ch[4] == ' ')\n {\n if (ch[5] == '"' & ch[strlen(ch) - 1] == '"')\n {\n chh(ch, output, 5, strlen(ch) - 1);\n printf("%s\\n", output);\n ch[0] = '@';\n }\n else\n {\n printf("Error\\nError Code: PRINTLANG.8\\n");\n ch[0] = '@';\n }\n }\n else\n {\n printf("Error\\nError Code: PRINTLANG.9\\n");\n ch[0] = '@';\n }\n}\n\nint main(int argc, char *argv[])\n{\n char ch[100];\n int while_int;\n if (argv[1] != NULL)\n {\n char *file_extension = strrchr(argv[1], '.');\n if (file_extension == NULL)\n {\n printf("Error\\nNo File Extension\\n");\n }\n else if (strcmp(file_extension, ".pri") == FALSE)\n {\n FILE *fp = fopen(argv[1], "r");\n fgets(ch, 100, fp);\n fclose(fp);\n }\n }\n do\n {\n if (argv[1] == NULL)\n {\n printf(">>> ");\n scanf("%[^\\n]%*c", ch);\n }\n while_int = (ch[0] != '@' & argv[1] == NULL);\n if (ch[0] == '"' & ch[strlen(ch) - 1] == '"')\n {\n do_quotes(ch);\n }\n if (ch[0] == 'p' & ch[1] == 'r' & ch[2] == 'i' & ch[3] == 'n' & ch[4] == 't')\n {\n do_print(ch);\n }\n else if (ch[0] == 'e' & ch[1] == 'c' & ch[2] == 'h' & ch[3] == 'o')\n {\n do_echo(ch);\n }\n else\n {\n ch[0] = '@';\n }\n }\n while (while_int);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T10:07:12.963",
"Id": "259002",
"ParentId": "258966",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "258970",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T16:04:35.157",
"Id": "258966",
"Score": "0",
"Tags": [
"c",
"interpreter"
],
"Title": "Simple interpreter in C"
}
|
258966
|
<p>I wrote my own dynamic array library for C as I was not happy with the others I found. It is very crude but the basic logic should be correct, it mainly revolves making <code>realloc</code> easier to use and avoiding repetitive code.</p>
<p>Please offer your suggestions and criticisms!</p>
<pre class="lang-c prettyprint-override"><code>#include <stdlib.h>
#include <string.h>
#define DYNARRAY_H_INCREMENT 50
typedef struct dynarr dynarr;
struct dynarr {
void *actual;
size_t size;
size_t e_size;
size_t occupied;
size_t increment;
void (*mem_callback)(dynarr *);
};
void *dynarr_nomen(dynarr *array) {
if (array->mem_callback) array->mem_callback(array);
array->actual = NULL;
array->occupied = 0;
return NULL;
}
dynarr dynarr_init_full(size_t e_size, size_t increment, void (*mem_callback)(dynarr *)) {
return (dynarr){
.actual = NULL,
.size = 0,
.e_size = e_size,
.occupied = 0,
.increment = increment,
.mem_callback = mem_callback,
};
}
dynarr dynarr_init(size_t element_size) {
return dynarr_init_full(element_size, DYNARRAY_H_INCREMENT, NULL);
}
void *dynarr_push(dynarr *array, void *data) {
if (array->occupied == array->size) {
// Array is full
// Increase size
size_t new_real_size = (array->size + array->increment) * array->e_size;
array->actual = realloc(array->actual, new_real_size);
if (!array->actual) return dynarr_nomen(array);
array->size += array->increment;
}
// Copy data
char *charr = (char *) array->actual;
memcpy(charr + array->occupied++ * array->e_size, data, array->e_size);
return array->actual;
}
void *dynarr_get(dynarr *array, size_t *size) {
if (size) *size = array->occupied;
return array->actual;
}
void *dynarr_compact(dynarr *array) {
if (array->occupied == array->size) goto end;
array->actual = realloc(array->actual, array->occupied * array->e_size);
if (!array->actual) return dynarr_nomen(array);
array->size = array->occupied;
end: return array->actual;
}
void dynarr_free(dynarr *array) {
free(array->actual);
array->actual = NULL;
array->occupied = 0;
}
</code></pre>
<p>I intend to split declarations into a separate header in the future, I have kept it as a simple single source file for now.</p>
<p>I also made a very crude example program which could definitely use some major improvements... or maybe it can even be replaced by something else.</p>
<pre class="lang-c prettyprint-override"><code>#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include "dynarr.c"
volatile sig_atomic_t signaled = false;
void trap_interrupt(int sig) {
signaled = true;
}
int main(void) {
signal(SIGINT, trap_interrupt);
int c;
char data;
dynarr input = dynarr_init(sizeof data);
for (;;) {
if (signaled) break;
c = getc(stdin);
if (c == EOF) break;
data = c;
if (!dynarr_push(&input, &data)) {
puts("Ran out of memory!!!");
break;
};
}
size_t count;
dynarr_get(&input, &count);
printf("Stored %zu bytes in dynamic array\n", count);
return EXIT_SUCCESS;
}
</code></pre>
|
[] |
[
{
"body": "<h1>Regarding incrementing by a fixed amount</h1>\n<p>The problem with resizing the storage by a fixed amount each time you reach capacity is that it effectively makes pushing a new element to the array an <span class=\"math-container\">\\$\\mathcal{O}(N)\\$</span> operation. If you instead double the amount of storage each time, pushing will be <em>amortized</em> <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span>.</p>\n<p>The drawback of doubling the capacity each time is that you might waste more memory than if you only increase it by fixed amounts. However, unless you are constrained by the amount of memory you have, I would recommend the doubling approach.</p>\n<h1>Memory leaks</h1>\n<p>Your code leaks memory when running out of memory. If you call <code>realloc()</code>, but it returns <code>NULL</code>, the original memory is not freed and still valid. So instead of unconditionally overwriting <code>array->actual</code>, you should write something like:</p>\n<pre><code>void *new_actual = realloc(array->actual, new_real_size);\n\nif (!new_actual) {\n free(array->actual);\n return dynarray_nomem(array->actual);\n}\n\narray->actual = new_actual;\narray->size = new_real_size;\n</code></pre>\n<p>Alternatively, and perhaps even better, is to just keep the original data and return <code>NULL</code>, and let the caller worry about whether they want to destroy the array or want to keep using it:</p>\n<pre><code>void *new_actual = realloc(array->actual, new_real_size);\n\nif (!new_actual) {\n return NULL;\n}\n...\n</code></pre>\n<h1>(Re)move the callback</h1>\n<p>I don't see the point of having a callback function that is called when memory allocation failed, if the caller already has to check the return value of <code>dynarray_push()</code> and <code>dynarray_compact()</code>. I would just remove this unnecessary complexity.</p>\n<blockquote>\n<p>This is an useful feature which can be used to avoid error checking for each push, instead of the caller can specify a callback function which would use something like longjmp to initiate a no memory exit sequence.</p>\n</blockquote>\n<p>If you want this, I recommend you move the <code>mem_callback</code> pointer out of <code>struct dynarr</code>, and make it a global variable named <code>dynarr_mem_callback</code>.</p>\n<h1>Consider returning a pointer to the pushed element</h1>\n<p>It would be much more useful if <code>dynarray_push()</code> would return a pointer to the element that was just pushed, instead of a pointer to the start of the array. There is already <code>dynarray_get()</code> to get a pointer to the start, but see below.</p>\n<h1>Add a function to get a pointer to a specific element</h1>\n<p>Since it is likely that a user might want to access a specific element in the dynamic array, it would be helpful to add a function that does that in one go. In fact, I would name that function <code>dynarray_get()</code>:</p>\n<pre><code>void *dynarray_get(dynarray *array, size_t offset) {\n // Bounds checking, has a performance impact though:\n if (offset >= array->occupied)\n return NULL;\n\n return (char *)array->actual + offset * array->e_size;\n}\n</code></pre>\n<p>And add separate functions <code>dynarray_data()</code> and <code>dynarray_size()</code> to get a pointer to the underlying storage and the number of elements respectively.</p>\n<h1>Avoid using <code>goto</code></h1>\n<p>It is quite easy to avoid the <code>goto</code> statement in <code>dynarray_compact()</code>, just replace it with <code>return array->actual</code>. Even better would be to just unconditionally call <code>realloc()</code>, since it is unlikely that <code>size</code> and <code>occupied</code> will be the same, and this is not a function that would be called very often anyway, so it is not performance critical:</p>\n<pre><code>void *dynarr_compact(dynarr *array) {\n void *new_actual = realloc(array->actual, array->occupied * array->e_size);\n\n if (new_actual) {\n array->actual = new_actual;\n array->size = array->occupied;\n }\n\n return array->actual;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T06:35:54.283",
"Id": "510719",
"Score": "0",
"body": "Thank you for the review, I would like to clarify some points:"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T06:36:55.890",
"Id": "510720",
"Score": "0",
"body": "Don't increment by a fixed amount: The problem with doubling the memory is that the growth is exponential and for a sufficiently large array, the system might not have enough memory, while the operation does not require such huge amounts. The option to customize the increments is therefore given so that the end-user can choose their ideal size increments."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T06:39:41.177",
"Id": "510721",
"Score": "0",
"body": "Remove the callback: This is an useful feature which can be used to avoid error checking for each push, instead of the caller can specify a callback function which would use something like `longjmp` to initiate a no memory exit sequence."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T06:40:59.587",
"Id": "510722",
"Score": "0",
"body": "I agree with the rest of your points. I apologize of being unaware, but what is the general etiquette followed here to revise code and put it up for review again? Is that skipped entirely by some?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T07:48:10.770",
"Id": "510731",
"Score": "1",
"body": "If you have improved the code and would like a review of the improved code, then please do ask a new question (include a link to this first review, to give more context). See [I improved my code based on the reviews. What next?](/help/someone-answers#help-post-body)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T07:54:40.263",
"Id": "510732",
"Score": "0",
"body": "Shouldn't that last `dynarr_compact()` return `new_actual` rather than `array_actual`, so the caller can instantly know if it succeeded? (It's probably not very important here, as it seems that it's only called when reducing the allocation, and I'm not convinced that `realloc()` is allowed to fail in that case)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T09:29:24.660",
"Id": "510736",
"Score": "0",
"body": "@TobySpeight If the realloc failed (if that is indeed possible), then the original allocation should still be intact. Technically it failed to compact the array, but otherwise there is nothing preventing you from continuing to use the array, so I don't think it makes sense to return `NULL`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T09:45:19.093",
"Id": "510737",
"Score": "1",
"body": "@TheDcoder As for the exponential growth, it can indeed be an issue. However, it is quite unlikely you run into it on modern systems. Also, with the major operating systems using virtual memory and overcommitting it, the unused part of a large dynarray will typically not even cost any memory. If you are working on a small embedded system, it is different of course."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T10:00:28.567",
"Id": "510738",
"Score": "0",
"body": "Ah, yes - makes sense. My brain was still focused on the enlarge case, where we need to ensure we don't write outside the bounds afterwards, but that's not a concern when shrinking."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T17:08:58.500",
"Id": "510765",
"Score": "0",
"body": "Thank you everyone, I have incorporated some of the changes from this answer and published the code on [GitHub](https://github.com/TheDcoder/dynarr)."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T19:12:08.337",
"Id": "258977",
"ParentId": "258968",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "258977",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T16:14:08.967",
"Id": "258968",
"Score": "1",
"Tags": [
"c",
"array",
"memory-management",
"library"
],
"Title": "dynarr - yet another simple C dynamic array library"
}
|
258968
|
<p>In my real case I have a set of time series related to different IDs stored in a single <code>DataFrame</code>
Some are composed by 400 samples, some by 1000 samples, some by 2000.
They are stored in the same df and:</p>
<p><em><strong>I would like to drop all the IDs made up of time series shorter than a custom length.</strong></em></p>
<p>I wrote the following code, but I think is very ugly and inefficient.</p>
<pre><code>import pandas as pd
import numpy as np
dict={"samples":[1,2,3,4,5,6,7,8,9],"id":["a","b","c","b","b","b","c","c","c"]}
df=pd.DataFrame(dict)
df_id=pd.DataFrame()
for i in set(df.id):
df_filtered=df[df.id==i]
len_id=len(df_filtered.samples)
if len_id>3: #3 is just a random choice for this example
df_id=df_id.append(df_filtered)
print(df_id)
</code></pre>
<p>Output:</p>
<pre><code> samples id
2 3 c
6 7 c
7 8 c
8 9 c
1 2 b
3 4 b
4 5 b
5 6 b
</code></pre>
<p>How to improve it in a more Pythonic way?
Thanks</p>
|
[] |
[
{
"body": "<p>There are many solutions. For example, you can use a groupby-transform and drop the "small" samples. An appropriate solution will depend on what your requirements are more closely, i.e., will you do the preprocessing once, and then drop different samples?</p>\n<p>Anyway, consider:</p>\n<pre><code>import pandas as pd\n\ndf = pd.DataFrame({"samples": [1,2,3,4,5,6,7,8,9], "id": ["a","b","c","b","b","b","c","c","c"]})\n\ndf["counts"] = df.groupby("id")["samples"].transform("count")\ndf[df["counts"] > 3]\n\n# Or if you want:\ndf[df["counts"] > 3].drop(columns="counts")\n</code></pre>\n<p>By the way, avoid using <code>dict</code> as a variable name.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T19:14:57.083",
"Id": "258978",
"ParentId": "258969",
"Score": "2"
}
},
{
"body": "<p>Good answer by Juho. Another option is a <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.filter.html\" rel=\"nofollow noreferrer\"><strong><code>groupby-filter</code></strong></a>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>df.groupby('id').filter(lambda group: len(group) > 3)\n\n# samples id\n# 1 2 b\n# 2 3 c\n# 3 4 b\n# 4 5 b\n# 5 6 b\n# 6 7 c\n# 7 8 c\n# 8 9 c\n</code></pre>\n<p>To match your output order exactly, add a descending <code>id</code> sort: <code>.sort_values('id', ascending=False)</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T06:19:32.027",
"Id": "510718",
"Score": "1",
"body": "This is neat as well."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T02:52:05.053",
"Id": "258995",
"ParentId": "258969",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "258995",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T16:25:45.057",
"Id": "258969",
"Score": "2",
"Tags": [
"python",
"pandas"
],
"Title": "Pandas Filtering based on the length of the same kind variables in a column"
}
|
258969
|
<p>I wasn't sure about how to name it, maybe "follow_ptr", "self_updating_ptr", or "stalking_ptr" or something on those lines. For now it's called Identifier.</p>
<p>What I'm trying to achieve is a pointer wrapper which will always refer to the same object even when that object is moved in memory (vector resizes is a quite frequent example, also algorithms like std::remove_if that can move elements around).</p>
<hr />
<p>EDIT:
One requirement is to allow storing objects in sequential containers (like vector and deque) without losing sequential storage as one would by using unique_ptr or shared_ptr. This whole system is not meant to take care about ownership.</p>
<p>It's my bad for using the term "smart pointer in the original title", it's smart in the sense that it follows the pointed object as opposed to an observer pointer which wouldn't do that.</p>
<hr />
<p>A requirement is that the object is stored within an "Identified" class. That class is necessary to keep all the Identifiers updated.</p>
<p>The trick is having a double indirection, where a raw pointer living in the heap will point to the object to be stalked:</p>
<pre><code>#include <memory>
#include <stdexcept>
template <typename T>
class Identifier;
template <typename T>
class Identified;
// A pointer to an identified object. This object lives in the heap and is used to share information with all identifiers about the object moving in memory.
template <typename T>
class Inner_identifier
{
public:
Inner_identifier() = default;
Inner_identifier(T* identified) noexcept : identified{identified} {}
Inner_identifier(const Inner_identifier& copy) = delete;
Inner_identifier& operator=(const Inner_identifier& copy) = delete;
Inner_identifier(Inner_identifier&& move) = delete;
Inner_identifier& operator=(Inner_identifier&& move) = delete;
T* identified{nullptr};
};
</code></pre>
<p>The Identifier, or stalker, acts as an in-between a smart pointer and an optional. The idea is that if Identifiers outlive an object, they're still valid (assuming the user checks with has_value before using them, like with an optional).</p>
<p>I'm unsure if I should just delete the default constructor, so that it's always certain that an Identifier's pointer to the Inner_identifier is always valid, and I can get rid of some checks. For now I've left it just to make writing the example simpler.</p>
<pre><code>template <typename T>
class Identifier
{
public:
Identifier() = default;
Identifier(Identified<T>& identified) : inner_identifier{identified.inner_identifier} {}
Identifier& operator=(Identified<T>& identified) { inner_identifier = identified.inner_identifier; return *this; }
Identifier(const Identifier& copy) = default;
Identifier& operator=(const Identifier& copy) = default;
Identifier(Identifier&& move) = default;
Identifier& operator=(Identifier&& move) = default;
const T& operator* () const { check_all(); return *inner_identifier->identified; }
T& operator* () { check_all(); return *inner_identifier->identified; }
const T* operator->() const { check_all(); return inner_identifier->identified; }
T* operator->() { check_all(); return inner_identifier->identified; }
const T* get() const { check_initialized(); return inner_identifier->identified; }
T* get() { check_initialized(); return inner_identifier->identified; }
bool has_value() const noexcept { return inner_identifier && inner_identifier->identified != nullptr; }
explicit operator bool() const noexcept { return has_value(); }
private:
std::shared_ptr<Inner_identifier<T>> inner_identifier{nullptr};
void check_initialized() const
{
#ifndef NDEBUG
if (!inner_identifier) { throw std::runtime_error{"Trying to use an uninitialized Identifier."}; }
#endif
}
void check_has_value() const
{
#ifndef NDEBUG
if (inner_identifier->identified == nullptr) { throw std::runtime_error{"Trying to retrive object from an identifier which identified object had already been destroyed."}; }
#endif
}
void check_all() const { check_initialized(); check_has_value(); }
};
</code></pre>
<p>Finally the Identified class, which holds the instance of the object to be pointed to by one or more Identifiers. It is responsible for updating the Inner_identifier whenever it is moved around in memory with either move constructor or move assignment. On the opposite the copy constructor makes sure that the new copy has its own new Inner_identifier and all the existing Identifiers still work with the instance being copied from. Upon destruction, the Inner_identifier is nullified but it will keep existing for reference as long as at least one Identifier to the now defunct object still exists (hence the internal shared_ptrs)</p>
<pre><code>template <typename T>
class Identified
{
friend class Identifier<T>;
public:
template <typename ...Args>
Identified(Args&&... args) : object{std::forward<Args>(args)...}, inner_identifier{std::make_shared<Inner_identifier<T>>(&object)} {}
Identified(Identified& copy) : Identified{static_cast<const Identified&>(copy)} {}
Identified(const Identified& copy) : object{copy.object}, inner_identifier{std::make_shared<Inner_identifier<T>>(&object)} {}
Identified& operator=(const Identified& copy) { object = copy.object; return *this; } //Note: no need to reassign the pointer, already points to current instance
Identified(Identified&& move) noexcept : object{std::move(move.object)}, inner_identifier{std::move(move.inner_identifier)} { inner_identifier->identified = &object; }
Identified& operator=(Identified&& move) noexcept { object = std::move(move.object); inner_identifier = std::move(move.inner_identifier); inner_identifier->identified = &object; return *this; }
~Identified() { if (inner_identifier) { inner_identifier->identified = nullptr; } }
const T& operator* () const { return *get(); }
T& operator* () { return *get(); }
const T* operator->() const { return get(); }
T* operator->() { return get(); }
const T* get() const
{
#ifndef NDEBUG
if (!inner_identifier || inner_identifier->identified == nullptr) { throw std::runtime_error{"Attempting to retrive object from an identifier which identified object had already been destroyed."}; }
#endif
return &object;
}
T* get()
{
#ifndef NDEBUG
if (!inner_identifier || inner_identifier->identified == nullptr) { throw std::runtime_error{"Attempting to retrive object from an identifier which identified object had already been destroyed."}; }
#endif
return &object;
}
T object;
private:
std::shared_ptr<Inner_identifier<T>> inner_identifier;
};
</code></pre>
<p>On top of criticisms, I'd like some advice on naming. If I were to call the Identifier "follow_ptr", "self_updating_ptr", or "stalking_ptr", I've no idea how to call the other two classes.</p>
<p>Aside for the first capital letter of the classes, does the interface feel "standard" enough?</p>
<p>Here is an usage example, compile in debug mode for the exceptions:</p>
<pre><code>#include <stdexcept>
#include <iostream>
#include <vector>
#include <algorithm>
struct Base
{
int tmp; bool enabled = true; bool alive = true;
Base(int tmp) : tmp(tmp) {}
virtual volatile void f() { std::cout << "Base::f" << tmp << std::endl; };
void g() { std::cout << "Base::g" << tmp << std::endl; };
};
struct TmpA : public Base
{
TmpA(int tmp) : Base(tmp) {}
virtual volatile void f() override { std::cout << "TmpA::f" << tmp << std::endl; };
void g() { std::cout << "TmpA::g" << tmp << std::endl;/**/ };
};
int main()
{
//Create empty identifiers
Identifier<TmpA> idn;
Identifier<TmpA> id1;
Identifier<TmpA> id5;
std::vector<Identified<TmpA>> vec;
if (true)
{
//Create some data and assign iit to identifiers
Identified<TmpA> identified_a1{1};
Identified<TmpA> identified_will_die{0};
idn = identified_will_die;
id1 = identified_a1;
id5 = vec.emplace_back(5);
//Move some identified objects around, this also causes the vector to grow, moving the object Identified by id5.
vec.emplace_back(std::move(identified_a1));
}
std::cout << " _______________________________________________ " << std::endl;
std::cout << "vec[0]: " << " "; try { vec[0]->f(); } catch (std::exception& e) { std::cout << e.what() << std::endl; }
std::cout << "vec[1]: " << " "; try { vec[1]->f(); } catch (std::exception& e) { std::cout << e.what() << std::endl; }
std::cout << "id1: " << " "; try { id1->f(); } catch (std::exception& e) { std::cout << e.what() << std::endl; }
std::cout << "id5: " << " "; try { id5->f(); } catch (std::exception& e) { std::cout << e.what() << std::endl; }
std::cout << "null: " << " "; try { idn->f(); } catch (std::exception& e) { std::cout << e.what() << std::endl; }
//Move some identified objects around
std::partition(vec.begin(), vec.end(), [](Identified<TmpA>& idobj) { return idobj->tmp > 2; });
std::cout << " _______________________________________________ " << std::endl;
std::cout << "vec[0]: " << " "; try { vec[0]->f(); } catch (std::exception& e) { std::cout << e.what() << std::endl; }
std::cout << "vec[1]: " << " "; try { vec[1]->f(); } catch (std::exception& e) { std::cout << e.what() << std::endl; }
std::cout << "id1: " << " "; try { id1->f(); } catch (std::exception& e) { std::cout << e.what() << std::endl; }
std::cout << "id5: " << " "; try { id5->f(); } catch (std::exception& e) { std::cout << e.what() << std::endl; }
std::cout << "null: " << " "; try { idn->f(); } catch (std::exception& e) { std::cout << e.what() << std::endl; }
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T18:31:05.950",
"Id": "510665",
"Score": "0",
"body": "Yay time to check if I just wasted 6 hours of my life..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T18:37:17.650",
"Id": "510669",
"Score": "1",
"body": "@G.Sliepen for my understanding it has nothing to do with weak_ptr. Weak_ptr doesn't follow the object when it's moved in memory, which is the only thing my code is meant to do. Objects here aren't stored dynamically, they're stored however the user decides to store them. No need to store them in shared pointers. They can be stored sequentially in a vector for instance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T18:58:28.453",
"Id": "510671",
"Score": "0",
"body": "@Barnack what's the purpose? Isn't easier and safer to simply store the object on the heap as a `shared_ptr`? What functionality does it add that `shared_ptr` cannot provide? I mean, beyond being extremely non thread-safe."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T19:00:22.830",
"Id": "510672",
"Score": "0",
"body": "@ALX23z the functionality shared_ptr cannot provide is sequential storage for multiple objects and having those objects moved around.\nThe whole point here is letting you store objects in some sequential storage like a vector or a deque, freely use algorithms that move things in memory, keeping the external identifiers always valid pointing at the same object.\nSequential storage's advantage is cache friendliness, which sometimes one isn't willing to leave out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T19:06:02.580",
"Id": "510673",
"Score": "0",
"body": "@ALX23z say you iterate and re-partition a vector's content thousands of times, and just a dozen times you need to access an element through some externally stored pointer to it. Do you really want to make the thousand iterations go find each object somewhere in the heap just for the sake of the dozen times you need to access an element from outside an iteration?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T19:26:35.763",
"Id": "510678",
"Score": "0",
"body": "@Barnack I posted a review. This code is very non thread-safe and it is impossible fix it without causing major performance issues. I cannot recommend to use a smart pointer tracker that is not thread-safe."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T19:33:02.583",
"Id": "510680",
"Score": "0",
"body": "@Barnack I don't understand how your solution is helpful. Here each move of the object requires RAM access to fix the pointer address of identifier. How is that much better than `shared_ptr` that is non friendly to cache when the object is accessed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T19:47:35.187",
"Id": "510681",
"Score": "0",
"body": "@ALX23z shared_ptr implies that objects won't be necessarily stored sequentially. This thing only observes, the ownership is left outside. I got it, it's not thread safe; and it's not meant nor designed to be, it doesn't want to replace shared_ptr. There won't be concurrent accesses to identifiers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T19:55:32.267",
"Id": "510683",
"Score": "1",
"body": "@Barnack Correct me if I am wrong, but you don't actually want to keep track of all the objects but only several of them, right? I'd rather use some other methods to keep track of a few objects you need. Say, keep a copy in a separate `shared_ptr` and update it each time the tracked object is modified."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T19:59:18.870",
"Id": "510686",
"Score": "0",
"body": "@ALX23z that's actually an alternative I didn't even think about... You mean a large vector for all the instances to be iterated, and a smaller one with dynamically allocated copies for the objects I need to reference from outside, defining a moment in which i update the copies with changes done in the vector, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T20:55:17.053",
"Id": "510699",
"Score": "1",
"body": "yeah, something like that. I originally thought about coupling the `shared_ptr` with variables but how you described is more or less the same - only that you suggest that an external class manages the instances update which is probably better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T16:12:40.220",
"Id": "510760",
"Score": "1",
"body": "Have you heard of the concept of a \"Handle\". Basically a pointer to a pointer. User holds the handle that points at a pointer in a table. When an object is moved the table pointer is updated with the new location. The user does not need to know as their pointer simply points to the location of the pointer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T16:36:31.917",
"Id": "510763",
"Score": "0",
"body": "@MartinYork isn't that basically what I've done except mine aren't in a table? Actually sounds really close to G.Sliepen's answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T18:44:14.520",
"Id": "510775",
"Score": "1",
"body": "@Barnack: It's simply the name of the concept you were missing \"Handle\". They don't need to be in tables (that is just a common implementation) (or even pointers). It's good to use the common name (pattern) to describe what you are trying to achieve. This is a common concept that is used by a lot of OS's to handle resource management. So if you use \"Handle_ptr\" rather than \"self_updating_ptr\" everybody that understands the concept of patterns will automatically have an idea of what you are building."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T18:48:23.313",
"Id": "510778",
"Score": "0",
"body": "@MartinYork makes sense, thanks! How would you go on naming what in the example is the \"Identified\" class? Handled sounds a bit off..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T18:49:46.947",
"Id": "510780",
"Score": "1",
"body": "@Barnack G. Sliepen has a good recommendation."
}
] |
[
{
"body": "<p>The fundamental problem is that the mechanism as it is very non-thread-safe. If you hold identifier in one thread and move it in another thread then it results in data racing as you don't use any memory synchronisation routines.</p>\n<p>Furthermore, you cannot move the object when another thread uses it. And currently there is no way to even test it if it is being used or anything of the sort. To fix it you've gotta lock a mutex each time you use it or move it. Meaning a move might take a lot of time due to long wait and if you have many of those then you'll have to lock that many mutexes - which is a good source of deadlocks if you don't apply special algorithms that ensure that mutexes will be locked in a deadlock safe way.</p>\n<p>Furthermore, whatever cache friendliness you hoped to achieve with this object is going to get ruined as soon as any memory fencing is triggered (only <em>relaxed</em> memory operation might not ruin it but you will need <em>acquire</em> and <em>release</em> which require re caching up to shared memory).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T19:20:46.353",
"Id": "258979",
"ParentId": "258973",
"Score": "3"
}
},
{
"body": "<h1>Keeping objects as sequential as possible</h1>\n<p>After reading the comments, it seems the most important use case is for tracking moves of objects in containers, but we want to keep those objects sequential, and be as cache-friendly as possible. It is also likely that you don't want to track all the objects in a container, but just a few. In that case, your implementation has some drawbacks. The main one is that you store a <code>std::unique_ptr</code> along with every object, so they are no longer sequential. Consider that you had a:</p>\n<pre><code>std::vector<T> vec;\n</code></pre>\n<p>Then in memory you have:</p>\n<pre><code>T0 T1 T2 T3 ...\n</code></pre>\n<p>But now you want to track some of the <code>T</code>s, then you'd write:</p>\n<pre><code>std::vector<Identified<T>> vec;\n</code></pre>\n<p>Then in memory you would have:</p>\n<pre><code>T0 std::shared_ptr<Inner_identifier<T>> T1 std::shared_ptr<...> T2 ...\n</code></pre>\n<p>Can we do better? Ideally we want to get the <code>T</code>'s packed back-to-back like in the original vector. We can get that if we move the tracking to a separate, global registry:</p>\n<pre><code>template<typename T>\nstd::unordered_map<T *, std::shared_ptr<T *>> registry;\n</code></pre>\n<p>Now when you create an instance of <code>Identified<T></code>, you want it to put the address of the object that it constructed into that map. When the object is moved, you have to update the map and the inner identifier accordingly.\nHowever, if no one is tracking a given object, it doesn't even have to be stored in the registry, so we can delay adding an object to the registry until someone wants to create an <code>Identifier<T></code> from it.</p>\n<p>Here is an example of what it could look like:</p>\n<pre><code>template<typename T>\nclass Identifier {\n std::shared_ptr<T *> object;\npublic:\n Identifier(Identified<T> &identified) {\n // Check if this object is already in the registry\n if (auto it = registry<T>.find(&identified.object); it != registry<T>.end()) {\n // Yes, we also want a reference to it\n object = *it;\n } else {\n // No, make a new entry in the registry\n object.reset(&identified.object);\n registry<T>[&object] = object;\n }\n }\n\n T &operator*() {\n if (!*object)\n throw ...;\n return **object;\n }\n\n ...\n};\n\ntemplate<typename T>\nclass Identified {\n T object;\n\npublic:\n // Constructor just constructs the object\n template <typename ...Args>\n Identified(Args&&... args): object{std::forward<Args>(args)...} {}\n\n // Move constructor has to update the registry\n Identified(Identified &&other) {\n // Check if this object is already in the registry\n if (auto it = registry<T>.find(&other.object); it != registry<T>.end()) {\n // Yes, update the value\n *it.reset(&object);\n\n // And also update the key\n auto nh = registry<T>.extract(it);\n nh.key() = &object;\n registry<T>.insert(std::move(nh));\n }\n\n // Now move the actual contents of the object\n object = std::move(other.object);\n }\n\n ... \n};\n</code></pre>\n<h1>Naming things</h1>\n<p>Consider renaming the classes to better convey their purpose:</p>\n<ul>\n<li><code>Identified</code> -> <code>Trackable</code></li>\n<li><code>Identifier</code> -> <code>Tracker</code></li>\n</ul>\n<p>I don't think there is a need for an <code>Inner_identifier</code> if you have the registry.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T21:11:41.933",
"Id": "510700",
"Score": "0",
"body": "uhm would you mind further elaborating how the move operation should interact with that registry? If T* is the key wouldn't you lose the key once the object is moved?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T21:48:25.277",
"Id": "510702",
"Score": "1",
"body": "I added an example. The trick is to update both the key and value in the map when an object is moved."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T20:25:13.520",
"Id": "258983",
"ParentId": "258973",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "258983",
"CommentCount": "16",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T18:19:11.577",
"Id": "258973",
"Score": "4",
"Tags": [
"c++",
"memory-management",
"c++17",
"pointers"
],
"Title": "\"observer pointer\" meant to stay updated when the pointed object is moved in memory"
}
|
258973
|
<p>This is a <a href="https://en.wikipedia.org/wiki/Steganography" rel="nofollow noreferrer">steganography</a> tool enabling you to conceal any file within a PNG file. In order to compile the program you need <a href="http://www.libpng.org/pub/png/libpng.html" rel="nofollow noreferrer">libpng</a> to be installed on the system. It is one of my personal projects and I would love to receive expert advice.</p>
<h2>Running</h2>
<p>Hide message in PNG file:</p>
<pre class="lang-sh prettyprint-override"><code>steg -h <file_in> <png_in> <png_out>
</code></pre>
<p>Read message from PNG file:</p>
<pre class="lang-sh prettyprint-override"><code>steg -r <png_in> <file_out>
</code></pre>
<p>The arguments <code><file_in></code> and <code><file_out></code> can be filenames of any (binary) files.</p>
<h2>Code</h2>
<p>I'm following Linus Torvalds's <a href="https://www.kernel.org/doc/html/v4.10/process/coding-style.html" rel="nofollow noreferrer">coding style</a>.</p>
<p>In <code>steg.c</code> I have:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "png_io.h"
/* hide one byte in png */
void hide_byte(unsigned char byte, long i)
{
short bit;
for (bit = 0; bit < CHAR_BIT; ++bit) {
long abs_bit = i * CHAR_BIT + bit;
int y = abs_bit / channels / width;
int x = abs_bit % (width * channels);
png_byte *value = &row_pointers[y][x];
if (byte & (1 << (CHAR_BIT - bit - 1)))
*value = (*value & ~1) + 1; /* 1 */
else
*value = *value & ~1; /* 0 */
}
}
/* hide file contents in png */
void hide_file(char *filename, char *src_png_name, char *out_png_name)
{
FILE *fp = fopen(filename, "rb");
if (!fp) {
fprintf(stderr, "Error: failed to open file \"%s\"\n", filename);
exit(EXIT_FAILURE);
}
fseek(fp, 0, SEEK_END);
long fsize = ftell(fp);
fseek(fp, 0, SEEK_SET);
unsigned char buffer[4 + fsize];
buffer[0] = fsize >> 24;
buffer[1] = fsize >> 16;
buffer[2] = fsize >> 8;
buffer[3] = fsize;
fread(&buffer[4], fsize, 1, fp);
printf("sizeof(buffer) = %zu\n", sizeof(buffer));
read_png(src_png_name);
printf("width: %d\nheight: %d\nchannels: %d\n", width, height, channels);
if ((CHAR_BIT * sizeof(buffer)) > (width * height * channels)) {
fprintf(stderr, "Error: binary file doesn't fit into png file\n");
exit(EXIT_FAILURE);
}
long i;
for (i = 0; i < sizeof(buffer); ++i) {
hide_byte(buffer[i], i);
}
write_png(out_png_name);
fclose(fp);
}
/* read one byte from png */
void read_byte(unsigned char *byte, long i)
{
short bit;
for (bit = 0; bit < CHAR_BIT; ++bit) {
long abs_bit = i * CHAR_BIT + bit;
int y = abs_bit / channels / width;
int x = abs_bit % (width * channels);
png_byte *value = &row_pointers[y][x];
if (*value & 1)
*byte += 1 << (7 - bit);
}
}
/* read file contents from png */
void read_file(char *filename, char *png_name)
{
FILE *fp = fopen(filename, "wb");
if (!fp) {
fprintf(stderr, "Error: failed to open file \"%s\"", filename);
exit(EXIT_FAILURE);
}
read_png(png_name);
printf("width: %d\nheight: %d\nchannels: %d\n", width, height, channels);
long fsize = 0;
short ib;
for (ib = 0; ib < 32; ++ib) {
int y = ib / (width * channels);
int x = ib % (width * channels);
png_byte *value = &row_pointers[y][x];
if (*value % 2 == 1)
fsize += 1 << (31 - ib);
}
unsigned char buffer[4 + fsize];
memset(buffer, 0, sizeof(buffer));
printf("sizeof(buffer) = %zu\n", sizeof(buffer));
long i;
for (i = 0; i < sizeof(buffer); ++i) {
read_byte(&buffer[i], i);
}
fwrite(&buffer[4], fsize, 1, fp);
fclose(fp);
}
/* handle command line arguments */
int main(int argc, char *argv[])
{
if (argc == 5 && !strcmp(argv[1], "-h")) {
hide_file(argv[2], argv[3], argv[4]);
} else if (argc == 4 && !strcmp(argv[1], "-r")) {
read_file(argv[3], argv[2]);
} else {
printf("Hide message: %s -h <file_in> <png_in> <png_out>\n"
"Read message: %s -r <png_in> <file_out>\n",
argv[0], argv[0]);
}
return EXIT_SUCCESS;
}
</code></pre>
<p>In <code>png_io.c</code> I have:</p>
<pre><code>#include <png.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include "png_io.h"
#define PNG_BYTES_TO_CHECK 4
/* global variables */
png_infop info_ptr;
png_bytepp row_pointers;
png_uint_32 width, height;
png_byte channels;
/* read png file */
void read_png(char *filename)
{
FILE *fp = fopen(filename, "rb");
if (!fp) {
fprintf(stderr, "Error: failed to open file '%s'\n", filename);
exit(EXIT_FAILURE);
}
/* read signature bytes */
unsigned char sig[PNG_BYTES_TO_CHECK];
if (fread(sig, 1, PNG_BYTES_TO_CHECK, fp) != PNG_BYTES_TO_CHECK) {
fprintf(stderr, "Error: failed to read signature bytes"
"from '%s'\n", filename);
exit(EXIT_FAILURE);
}
/* compare first bytes of signature */
if (png_sig_cmp(sig, 0, PNG_BYTES_TO_CHECK)) {
fprintf(stderr, "Error: '%s' is not a PNG file\n", filename);
exit(EXIT_FAILURE);
}
/* initialize png_struct `png_ptr` */
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,
NULL, NULL, NULL);
if (!png_ptr) {
fclose(fp);
fprintf(stderr, "Error: memory allocation failed\n");
exit(EXIT_FAILURE);
}
/* allocate memory for image information */
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
fclose(fp);
png_destroy_read_struct(&png_ptr, NULL, NULL);
exit(EXIT_FAILURE);
}
/* set error handling */
if (setjmp(png_jmpbuf(png_ptr))) {
fclose(fp);
png_destroy_read_struct(&png_ptr, NULL, NULL);
exit(EXIT_FAILURE);
}
/* set up input control */
png_init_io(png_ptr, fp);
/* because we read some of the signature */
png_set_sig_bytes(png_ptr, PNG_BYTES_TO_CHECK);
/* read entire image into info structure */
png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
/* optain information */
row_pointers = png_get_rows(png_ptr, info_ptr);
width = png_get_image_width(png_ptr, info_ptr);
height = png_get_image_height(png_ptr, info_ptr);
channels = png_get_channels(png_ptr, info_ptr);
/* free allocated memory */
png_destroy_read_struct(&png_ptr, NULL, NULL);
fclose(fp);
}
/* write png file */
void write_png(char *filename)
{
FILE *fp = fopen(filename, "wb");
if (!fp) {
fprintf(stderr, "Error: failed to open file '%s'\n", filename);
exit(EXIT_FAILURE);
}
/* initialize png_struct `png_ptr` */
png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
NULL, NULL, NULL);
if (!png_ptr) {
fclose(fp);
fprintf(stderr, "Error: memory allocation failed\n");
exit(EXIT_FAILURE);
}
/* set up output control */
png_init_io(png_ptr, fp);
/* save new pixel values */
png_set_rows(png_ptr, info_ptr, row_pointers);
/* all image data in info structure */
png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
/* free allocated memory */
png_destroy_write_struct(&png_ptr, &info_ptr);
fclose(fp);
}
</code></pre>
<p>In <code>png_io.h</code> I have:</p>
<pre><code>#ifndef PNG_IO_H
#define PNG_IO_H
#include <png.h>
/* global variables */
extern png_bytepp row_pointers;
extern png_byte channels;
extern png_uint_32 width, height;
/* read png file */
void read_png(char *filename);
/* write png file */
void write_png(char *filename);
#endif /* PNG_IO_H */
</code></pre>
|
[] |
[
{
"body": "<h2>Unconditional masks</h2>\n<p>This:</p>\n<pre><code> if (byte & (1 << (CHAR_BIT - bit - 1)))\n *value = (*value & ~1) + 1; /* 1 */\n else\n *value = *value & ~1; /* 0 */\n</code></pre>\n<p>is really just</p>\n<pre><code>*value &= ~1;\nif (byte & (1 << (CHAR_BIT - bit - 1)))\n *value |= 1;\n</code></pre>\n<h2>Const arguments</h2>\n<pre><code>void hide_file(char *filename, char *src_png_name, char *out_png_name)\n</code></pre>\n<p>should be</p>\n<pre><code>void hide_file(const char *filename, const char *src_png_name, const char *out_png_name)\n</code></pre>\n<h2>C99</h2>\n<p>It's nice. It will allow this:</p>\n<pre><code>long i;\nfor (i = 0; i < sizeof(buffer); ++i) {\n</code></pre>\n<p>to be</p>\n<pre><code>for (long i = 0; i < sizeof(buffer); ++i) {\n</code></pre>\n<h2>Or vs. add</h2>\n<p>I suspect that these:</p>\n<pre><code> *byte += 1 << (7 - bit);\n *value = (*value & ~1) + 1; /* 1 */\n</code></pre>\n<p>are more safely expressed as bitwise or <code>|</code> operations, and really that better communicates your intent anyway.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T03:25:06.263",
"Id": "258996",
"ParentId": "258986",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "258996",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T21:51:12.027",
"Id": "258986",
"Score": "2",
"Tags": [
"algorithm",
"c",
"file",
"image",
"steganography"
],
"Title": "PNG steganography tool in C"
}
|
258986
|
<p>this is an Angular application, this page will have a list and sublist with action for each one (add/edit/delete)
<a href="https://i.stack.imgur.com/jgdMN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jgdMN.png" alt="enter image description here" /></a>
the buttons (add/edit) will show a popup with the same form except the landmark will show one more filed.</p>
<pre class="lang-html prettyprint-override"><code><ng-template #modaleTemplate>
<div class="modal-header">
<h4 class="modal-title pull-left">Modal</h4>
<button type="button" class="close pull-right" aria-label="Close" (click)="modalRef.hide()">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body text-center">
<div class="d-flex justify-content-center">
<div class="w-50">
<input
class="form-control shadow-sm bg-white rounded"
[(ngModel)]="areaModel.name"
placeholder="{{ 'Name' | translate }}"
/>
</div>
<div class="w-50" *ngIf="showTypes">
<select-menu
[label]="'landmarkType'"
[itemKey]="'Id'"
[dropDownListInputs]="landmarkTypeList"
(SearchVAlue)="getLandmarkType($event)"
(selectedListChange)="onLandmarTypekDDLChanged($event)"
[options]="selectMenuOptions"
></select-menu>
</div>
</div>
<div class="pt-5">
<tabset>
<tab heading="Location" class="py-3" id="tab1">
<input
class="w-100 d-inline-block form-control shadow-sm bg-white rounded"
[(ngModel)]="areaModel.location"
placeholder="{{ 'Name' | translate }}"
/>
</tab>
<tab heading="MoreDetails" class="py-3">
<div class="row">
<div class="col-12">
<div class="form-group">
<label for="description">{{"Description" | translate}}</label>
<input type="text" class="form-control shadow-sm bg-white rounded" [(ngModel)]="areaModel.description" placeholder="{{ 'Description' | translate }}" id="description">
</div>
</div>
<div class="col-6">
<div class="form-group">
<label for="telephone1">{{"Telephone #1" | translate}}</label>
<input type="text" class="form-control shadow-sm bg-white rounded" [(ngModel)]="areaModel.telephone1" placeholder="{{ 'Telephone #1' | translate }}" id="telephone1">
</div>
</div>
<div class="col-6">
<div class="form-group">
<label for="telephone2">{{"Telephone #2" | translate}}</label>
<input type="text" class="form-control shadow-sm bg-white rounded" [(ngModel)]="areaModel.telephone2" placeholder="{{ 'Telephone #2' | translate }}" id="telephone2">
</div>
</div>
<div class="col-6">
<div class="form-group">
<label for="Mobile">{{"Mobile" | translate}}</label>
<input type="text" class="form-control shadow-sm bg-white rounded" [(ngModel)]="areaModel.mobile" placeholder="{{ 'Mobile' | translate }}" id="Mobile">
</div>
</div>
<div class="col-6">
<div class="form-group">
<label for="Fax">{{"Fax" | translate}}</label>
<input type="text" class="form-control shadow-sm bg-white rounded" [(ngModel)]="areaModel.fax" placeholder="{{ 'Fax' | translate }}" id="Fax">
</div>
</div>
<div class="col-6">
<div class="form-group">
<label for="Website">{{"Website" | translate}}</label>
<input type="text" class="form-control shadow-sm bg-white rounded" [(ngModel)]="areaModel.website" placeholder="{{ 'Website' | translate }}" id="Website">
</div>
</div>
<div class="col-6">
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" [(ngModel)]="areaModel.isLive" id="isLive">
<label class="custom-control-label" for="isLive">{{ "IsLive" | translate }}</label>
</div>
</div>
</div>
</tab>
</tabset>
</div>
</div>
<div class="d-flex p-3 justify-content-end">
<button type="button" class="btn btn-link" (click)="modalRef.hide()">cancel</button>
<button type="button" class="btn btn-primary" (click)="save()">save</button>
</div>
</ng-template>
<div class="branch-management container-fluid">
<div class="row">
<div class="col-12">
<span class="actions d-flex justify-content-end mb-3">
<a class="add-btn" (click)="showModal(modaleTemplate, {name: 'area', action: 'add'})">
<i class="fas fa-plus"></i>
addArea
</a>
</span>
<div class="level-areas" id="areas">
<div class="item d-flex justify-content-between align-items-center">
<div class="btn btn-link collapsed"
data-toggle="collapse"
data-target="#area-1">
<div class="btn btn-link icon">
<i class="fas fa-plus"></i>
<i class="fas fa-minus"></i>
</div>
Area title
</div>
<span class="actions">
<a class="add-btn" (click)="showModal(modaleTemplate, {name: 'city', action: 'add', id: 1})">
<i class="fas fa-plus"></i>
addCity
</a>
<a class="edit-btn" (click)="showModal(modaleTemplate, {name: 'area', action: 'edit', id: 1})">
<i class="fas fa-pen"></i>
edit
</a>
<a class="delete-btn" (click)="delete({name: 'area', id: 1})">
<i class="fas fa-trash-alt"></i>
delete
</a>
</span>
</div>
<div id="area-1" class="collapse" data-parent="#areas">
<div class="level-cities" id="cities">
<div class="item d-flex justify-content-between align-items-center">
<div class="btn btn-link collapsed"
data-toggle="collapse"
data-target="#city-2">
<div class="btn btn-link icon">
<i class="fas fa-plus"></i>
<i class="fas fa-minus"></i>
</div>
City title
</div>
<span class="actions">
<a class="add-btn" (click)="showModal(modaleTemplate, {name: 'landmark', action: 'add', id: 1})">
<i class="fas fa-plus"></i>
addLandmark
</a>
<a class="edit-btn" (click)="showModal(modaleTemplate, {name: 'city', action: 'edit', id: 1})">
<i class="fas fa-pen"></i>
edit
</a>
<a class="delete-btn" (click)="delete({name: 'city', id: 1})">
<i class="fas fa-trash-alt"></i>
delete
</a>
</span>
</div>
<div id="city-2" class="collapse" data-parent="#cities">
<div class="level-landmarks">
<ul>
<li class="item d-flex justify-content-between align-items-center">
landmark name
<span class="actions">
<a class="edit-btn" (click)="showModal(modaleTemplate, {name: 'landmark', action: 'edit', id: 1})">
<i class="fas fa-pen"></i>
edit
</a>
<a class="delete-btn" (click)="delete({name: 'landmark', id: 1})">
<i class="fas fa-trash-alt"></i>
delete
</a>
</span>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</code></pre>
<p>So, instead of creating a function for every action for each element and repeat the modal template I've created two functions and passed parameters to tell the function to show the modal as needed.
<a href="https://i.stack.imgur.com/xbwq0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xbwq0.png" alt="enter image description here" /></a>
Also, on the modal save button it fires a save() method, which is will execute a method depends on what has passed on show modal function.</p>
<p>Then, I've checked the income action by <code>swich</code> statment to call its service.</p>
<pre><code>modalRef: BsModalRef;
showTypes = false;
areaModel: AreaModel = new AreaModel();
action = {
action: string,
name: string,
id: string
};
showModal(template: TemplateRef<any>, props: any) {
console.log(props);
this.action = props;
if(props.action === "edit") {
switch (props.name) {
case 'area':
console.log(props.action, props.name);
this.cpService.getAreaById(props.id).subscribe(res => this.areaModel = res.Value);
break;
case 'city':
console.log(props.action, props.name);
this.cpService.getCityById(props.id).subscribe(res => this.areaModel = res.Value);
break;
case 'landmark':
console.log(props.action, props.name);
this.cpService.getLandmarkById(props.id).subscribe(res => this.areaModel = res.Value);
break;
}
}
if(props.name === "landmark") {
this.showTypes = true;
} else {
this.showTypes = false;
}
this.modalRef = this.modalService.show(
template,
Object.assign({}, { class: 'modal-lg' })
);
}
delete(name, id) {
switch (name) {
case 'area':
this.cpService.deleteArea(id).subscribe(res => console.log(res))
break;
case 'city':
this.cpService.deleteCity(id).subscribe(res => console.log(res))
break;
case 'landmark':
this.cpService.deleteLandmark(id).subscribe(res => console.log(res))
break;
}
}
save() {
const currentAction = this.action.action as any;
switch (this.action.name as any) {
case 'area':
if (currentAction === 'edit') {
this.cpService.editArea(this.areaModel).subscribe(res => console.log(res));
} else {
this.cpService.addArea(this.areaModel).subscribe(res => console.log(res));
}
break;
case 'city':
if (currentAction === 'edit') {
this.cpService.editCity(this.areaModel).subscribe(res => console.log(res));
} else {
this.cpService.addCity(this.areaModel).subscribe(res => console.log(res));
}
break;
case 'landmark':
if (currentAction === 'edit') {
this.cpService.editLandmark(this.areaModel).subscribe(res => console.log(res));
} else {
this.cpService.addLandmark(this.areaModel).subscribe(res => console.log(res));
}
break;
}
}
</code></pre>
<p>Is that a good practice, or there is another good options to do that?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T22:17:22.747",
"Id": "258988",
"Score": "0",
"Tags": [
"javascript",
"typescript",
"angular-2+"
],
"Title": "JS, a multi purpose function"
}
|
258988
|
<p>I'm practicing refactoring and Java 8 with very simple examples of Powerball.</p>
<p>I used LottoRank enum to write a function that returns the matched LottoRank based on the number of matches and bonus balls.</p>
<ul>
<li><p>The 1st place is when you hit all 6 numbers.</p>
</li>
<li><p>The 2nd place is when you hit 5 with bonus ball.</p>
</li>
<li><p>The 3rd place is when you hit 5 without bonus ball.</p>
</li>
<li><p>The 4th place is when you hit 4 numbers.</p>
</li>
<li><p>The 5th place is when you hit 3 numbers.</p>
</li>
</ul>
<p>The logic for obtaining this value is as follows.</p>
<ul>
<li>LottoRank</li>
</ul>
<pre><code>NONE(Integer.MIN_VALUE, 0),
FIFTH(3, 5000),
FOURTH(4, 50000),
THIRD(5, 1500000),
SECOND(5, 30000000),
FIRST(6, 2000000000);
private final int matchCount;
private final Money winnerMoney;
LottoRank(int matchCount, int winnerMoney) {
this.matchCount = matchCount;
this.winnerMoney = new Money(winnerMoney);
}
public boolean isCorrectMatchCount(int matchCount) {
return this.matchCount == matchCount;
}
public int calculateWinningMoney(Integer value) {
return winnerMoney.multiple(value);
}
public static LottoRank findRank(String winnerRank) {
return LottoRankPredicates.filterLottoRankWithString(winnerRank);
}
public static LottoRank valueOf(int matchCount, boolean bonusBall) {
return Arrays.stream(LottoRank.values())
.filter(rank -> isThirdOrSecond(matchCount) ?
filterIsSecond(bonusBall, rank.winnerMoney) : rank.matchCount == matchCount)
.findAny()
.orElse(LottoRank.NONE);
}
private static boolean isThirdOrSecond(int matchCount) {
return matchCount == LottoRank.THIRD.matchCount;
}
private static boolean filterIsSecond(boolean bonusBall, Money winnerMoney) {
return bonusBall ? winnerMoney.equals(LottoRank.SECOND.winnerMoney) : winnerMoney.equals(LottoRank.THIRD.winnerMoney);
}
public static LottoRank matches(List<Number> winningNumbers, List<Number> holdingLottoNumbers, Number bonusBall) {
int matchCount = Math.toIntExact(winningNumbers.stream()
.filter(holdingLottoNumbers::contains)
.count());
boolean isSecond = holdingLottoNumbers.contains(bonusBall);
return LottoRank.valueOf(matchCount, isSecond);
}
</code></pre>
<p>If you look at the filter part of <code>valueOf()</code>, you will determine whether it is 2nd or 3rd (i.e., you got 5 correct). Based on whether the bonus ball has been hit or not, the logic is updated to 2nd place and if not, the ranking is processed according to the correct number.</p>
<p>I want to erase the trinomial operator in this part.</p>
<p><strong>However, else statements and switch-case statements are not allowed.</strong></p>
<p>I thought of a prefix or multiple filters, but eventually the first condition must be correct to run on the next condition, and this code will be generated.</p>
<p>It's a code that didn't work properly, but it's like this.</p>
<pre><code> public static LottoRank valueOf(int matchCount, boolean bonusBall) {
return Arrays.stream(LottoRank.values())
.filter(rank -> matchCount == rank.matchCount)
.filter(rank -> isThirdOrSecond(matchCount))
.filter(rank -> filterIsSecond(bonusBall, rank.winnerMoney))
.findAny()
.orElse(LottoRank.NONE);
}
</code></pre>
<p>Is there a way to refactory this more?</p>
<h2>Edited</h2>
<p>I was thinking about the above and i processed it with the <code>LottoRankPredicates</code> class as below.</p>
<p>I wonder what you think about refactoring like this.</p>
<ul>
<li>LottoRankPredicates</li>
</ul>
<pre><code>public class LottoRankPredicates {
private static Predicate<LottoRank> isSecondOrThird(boolean bonusBall) {
return rank -> getSecondOrThird(bonusBall, rank);
}
private static Predicate<LottoRank> defaultCase(int matchCount) {
return rank -> rank.isCorrectMatchCount(matchCount);
}
private static Predicate<LottoRank> findRank(String winnerRank) {
return rank -> rank.name().equals(winnerRank);
}
private static boolean getSecondOrThird(boolean bonusBall, LottoRank rank) {
if(bonusBall) {
return rank == LottoRank.SECOND;
}
return rank == LottoRank.THIRD;
}
public static LottoRank filterLottoRankWithString(String winnerRank) {
return Arrays.stream(LottoRank.values())
.filter(findRank(winnerRank))
.findAny()
.orElseThrow(IllegalArgumentException::new);
}
public static LottoRank filterLottoRankIsSecondOrThird(boolean bonusBall) {
return Arrays.stream(LottoRank.values())
.filter(isSecondOrThird(bonusBall))
.findAny()
.orElse(LottoRank.NONE);
}
public static LottoRank filterLottRankIsDefault(int matchCount) {
return Arrays.stream(LottoRank.values())
.filter(defaultCase(matchCount))
.findAny()
.orElse(LottoRank.NONE);
}
}
</code></pre>
<ul>
<li>LottoRank</li>
</ul>
<pre><code>public static LottoRank findRank(String winnerRank) {
return LottoRankPredicates.filterLottoRankWithString(winnerRank);
}
public static LottoRank valueOf(int matchCount, boolean bonusBall) {
if(isThirdOrSecond(matchCount)) {
return LottoRankPredicates.filterLottoRankIsSecondOrThird(bonusBall);
}
return LottoRankPredicates.filterLottRankIsDefault(matchCount);
}
private static boolean isThirdOrSecond(int matchCount) {
return matchCount == LottoRank.THIRD.matchCount;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T05:17:00.367",
"Id": "510716",
"Score": "0",
"body": "@Marc I added that part, and there's a refactoring part, so I'll add this part as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T06:18:55.403",
"Id": "510717",
"Score": "2",
"body": "\"I want to erase the trinomial operator in this part.\" --> Simple: create a method returning boolean which holds that logic and give it a meaningful name. And please take this as a real world hint, as this will make your code much more readable and maintainable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T06:54:25.320",
"Id": "510725",
"Score": "2",
"body": "I'm confused - is all the code here for review, or only the last couple of blocks? It would make the review request clearer if you used \"blockquote\" markdown (```> ```)for code that's illustrative but not for review, such as original code pre-refactoring."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T17:29:53.307",
"Id": "510846",
"Score": "0",
"body": "@mtj thanks i got a hint from your comment"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T17:30:29.943",
"Id": "510847",
"Score": "0",
"body": "@TobySpeight sorry, just only the last couple of blocks"
}
] |
[
{
"body": "<p>The constants of an <code>enum</code> are <em>full featured classes</em>. This means, in any of that constants you can override any non private method of the <code>enum</code> class itself and change the behavior to something constant specific. Basically this is the OO best practice <em>exchange branching with inheritance</em>.</p>\n<p>So the approach would be to make <code>filterIsSecond()</code> non static and add an override in the constants <code>SECOND</code> and <code>THIRD</code> like this:<br />\n<sub>(ATTENTION! My refactoring might not be semantically correct since you did not provide a <a href=\"http://sscce.org\" rel=\"nofollow noreferrer\">sscce</a> nor unittests.)</sub></p>\n<pre><code> // ...\n THIRD(5, 1500000){\n @Override\n boolean filterIsSecond(boolean bonusBall, Money winnerMoney) {\n return bonusBall && this.winnerMoney==winnerMoney;\n }\n },\n SECOND(5, 30000000){\n @Override\n boolean filterIsSecond(boolean bonusBall, Money winnerMoney) {\n return this.winnerMoney==winnerMoney;\n }\n },\n FIRST( //..\n\n\n boolean filterIsSecond(boolean bonusBall, Money winnerMoney) { \n return this.matchCount == matchCount;\n }\n\n public static LottoRank valueOf(int matchCount, boolean bonusBall) {\n return Arrays.stream(LottoRank.values())\n .filter(rank -> rank.filterIsSecond(bonusBall, rank.winnerMoney))\n .findAny()\n .orElse(LottoRank.NONE);\n }\n</code></pre>\n<p>Beside of that you should follow the Java naming conventions which promote methods (which you call functions) should start with a <em>verb</em> or in case they return <code>boolean</code> (as in your case) shoudl start with <code>is</code>, <code>can</code>, <code>has</code> or alike. This way the code that uses them reads much better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T08:40:37.960",
"Id": "510815",
"Score": "0",
"body": "Hello, fyi there is the typo @Overrode."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T17:03:47.327",
"Id": "510843",
"Score": "0",
"body": "@dariosicily: fixed it, thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T17:33:38.213",
"Id": "510849",
"Score": "0",
"body": "@TimothyTruckle i appreciate your dedication.\n\nHowever, because winnerMoney is private, there is an issue in the Override method that cannot access the value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T18:05:02.460",
"Id": "510854",
"Score": "0",
"body": "@TimothyTruckle \nbut, I took a hint from your code and created an interface and handled it neatly.\nThank you for expanding the Insight."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T20:54:26.317",
"Id": "510860",
"Score": "0",
"body": "You are welcome."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T12:56:10.973",
"Id": "511148",
"Score": "0",
"body": "Note: MCVE, SSCCE and similar are NOT recommended on Code Review. We prefer to see the actual code, not minimized examples of it."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T12:17:38.247",
"Id": "259010",
"ParentId": "258993",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "259010",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T02:09:19.703",
"Id": "258993",
"Score": "1",
"Tags": [
"java"
],
"Title": "how to remove trinocular operator in Java8 Stream filter"
}
|
258993
|
<p>So this time I am going to use ActionableWrapper on
<a href="https://github.com/ScottLilly/SOSCSRPG" rel="nofollow noreferrer">https://github.com/ScottLilly/SOSCSRPG</a> which is a simple RPG game.</p>
<p>The main portion of which is GameSession.cs which is the controller and owner of all the game pieces like player, trader, monster, location, etc.</p>
<p>GameSession also inherits from BaseNotificationClass(PropertyChanged Event) so I can use that event to hook the conversation service up. Ok so here goes.</p>
<p>First I need my wrapper class to be able to handle checking a condition and calling back after that property is set correctly. For this purpose, I have rewritten some old code and expanded on it a bit.</p>
<pre><code>using System;
namespace Engine.Services
{
[Serializable]
public class ActionableWrapper<T>
{
public ActionableWrapper(
Action<ActionableWrapper<T>, string> failAction = default,
Action<ActionableWrapper<T>, string> successAfterCheck = default,
Action<ActionableWrapper<T>, string> successAfterSet = default,
Func<ActionableWrapper<T>, T, bool> checkBeforeSet = default,
Func<ActionableWrapper<T>, T, T> modifyBeforeSet = default
)
{
FailAction = failAction;
CheckBeforeSet = checkBeforeSet;
ModifyBeforeSet = modifyBeforeSet;
SuccessAfterCheck = successAfterCheck;
SuccessAfterSet = successAfterSet;
}
private readonly Action<ActionableWrapper<T>, string> FailAction;
private readonly Action<ActionableWrapper<T>, string> SuccessAfterCheck;
private readonly Action<ActionableWrapper<T>, string> SuccessAfterSet;
#region ControlFlow
private readonly Func<ActionableWrapper<T>, T, bool> CheckBeforeSet;
private readonly Func<ActionableWrapper<T>, T, T> ModifyBeforeSet;
#endregion
private T data = default;
internal T Data { get => data; set => data = Filter(value); }
internal T Comparer { get; }
internal T ModifyInput(T value) => ModifyBeforeSet.Invoke(this, value);
internal bool CheckInput(T value) => CheckBeforeSet.Invoke(this, value);
public bool TryToSet(T value)
{
if (value != null)
{
Data = value;
// actual check to see if success
if (value.Equals(Data))
{
SuccessAfterSet(this, string.Empty);
return true;
}
else
{
if (FailAction != default)
{
FailAction(this, "Value did not get set.");
}
}
}
return false;
}
private T Filter(T value)
{
void SuccessfulCheck()
{
if (SuccessAfterCheck != default)
{
SuccessAfterCheck(this, "Value passed check.");
}
}
if (ModifyBeforeSet != default)
{
if (value != null)
{
T Local = ModifyInput(value);
if (CheckBeforeSet != default)
{
if (CheckInput(Local))
{
SuccessfulCheck();
return Local;
}
return default;
}
}
return value;
}
else
{
if (CheckBeforeSet != default && value != null)
{
if (CheckInput(value))
{
SuccessfulCheck();
return value;
}
return default;
}
return value;
}
}
}
}
</code></pre>
<p>Then I can create my Conversation service</p>
<pre><code>using Engine.ViewModels;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
namespace Engine.Services
{
public static class ConversationService
{
private static readonly MessageBroker Broker = MessageBroker.GetInstance();
// I use Location X,Y to find the conversation for the object,
// Todo: Dictionary<string, List<(int, Func<string>)> where
// the string is trader.name
public static List<(int x, int y, List<(int order, Func<string> GetText)> speachOrder)> Dialog = new List<(int x, int y, List<(int order, Func<string> GetText)>)>();
// this gets called on GameSession init.
public static void InitConversationService(this GameSession game)
{
// use CurrentLocation.TraderHere instead of CurrentTrader as it is not set when called.
// add conversation pieces
Dialog.Add((-1, 0,
new List<(int order, Func<string> GetText)>
{
(0, () => $"{game.CurrentLocation.TraderHere.Name}: Hello {game.CurrentPlayer.Name}, how are you doing today?"),
(1, () => $"{game.CurrentLocation.TraderHere.Name}: Do you need any Items?")
}));
// hook up monitor.
game.PropertyChanged += (object sender, PropertyChangedEventArgs e) =>
{
if (e.PropertyName == "CurrentTrader")
{
LocationsWatch.TryToSet(game);
}
};
}
// build checking routine
public static bool CheckLocation(ActionableWrapper<GameSession> result, GameSession loc) => loc.CurrentLocation.TraderHere != null;
// build failure routine
public static void FailAction(ActionableWrapper<GameSession> conditional, string output) => Broker.RaiseMessage(output);
// build success routine that places the dialog in order on the screen.
public static void SuccessAction(ActionableWrapper<GameSession> conditional, string output)
{
var obj = Dialog.FirstOrDefault(x => x.x == conditional.Data.CurrentLocation.XCoordinate && x.y == conditional.Data.CurrentLocation.YCoordinate);
if(obj != default)
{
foreach(var (order, GetText) in obj.speachOrder.OrderBy(x => x.order))
{
Broker.RaiseMessage(GetText());
}
}
}
// create our watcher
public static ActionableWrapper<GameSession> LocationsWatch = new ActionableWrapper<GameSession>(null, FailAction, null, SuccessAction, CheckLocation, null);
}
}
</code></pre>
<p>That's it. I need to polish it a little more to make adding conversation pieces more dynamic, loadable from config, but I think this is a good start. Any comments are apprecieated!</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T02:52:01.350",
"Id": "258994",
"Score": "0",
"Tags": [
"c#",
"properties"
],
"Title": "ActionableWrapper<T> Creating a conversationservice"
}
|
258994
|
<p>I been trying to implement a text processor in JavaScript that can handle 4 different types of operations: append, backspace, undo, redo.</p>
<p>The input for this text processor is an array of arraries of a single element or tuples. For example:</p>
<pre class="lang-js prettyprint-override"><code> const input = [['APPEND', 'Hey'], ['APPEND', ' there'], ['APPEND', '!']]
textProcessor.process(input)
textProcessor.text // Hey there!
</code></pre>
<pre class="lang-js prettyprint-override"><code> const input = [['APPEND', 'Hey'], ['APPEND', ' there'], ['APPEND', '!'], ['UNDO'], ['UNDO']]
textProcessor.process(input)
textProcessor.text // Hey
</code></pre>
<pre class="lang-js prettyprint-override"><code> const input = [['APPEND', 'Hey'], ['APPEND', ' there'], ['APPEND', '!'], ['UNDO'], ['UNDO'], ['REDO'], ['REDO']]
textProcessor.process(input)
textProcessor.text // Hey there!
</code></pre>
<pre class="lang-js prettyprint-override"><code> const input = [['APPEND', 'Hey'], ['APPEND', ' there'], ['APPEND', '!'], ['BACKSPACE']]
textProcessor.process(input)
textProcessor.text // Hey there
</code></pre>
<p>Here is my implementation</p>
<pre class="lang-js prettyprint-override"><code>class TextProcessor {
constructor() {
this.undos = []
this.redos = []
this.text = ''
this.operations = {
APPEND: (text) => {
this.undos.push(this.text)
this.redos.length = 0
return this.text + text
},
BACKSPACE: () => {
this.undos.push(this.text)
this.redos.length = 0
return this.text.slice(0, -1)
},
UNDO: () => {
const undo = this.undos.pop() ?? ''
this.redos.push(this.text)
return undo
},
REDO: () => {
this.undos.push(this.text)
return this.redos.pop() ?? this.text
},
}
}
process(input) {
input.forEach(([operation, text]) => {
this.text = this.operations[operation](text) ?? this.text
})
}
}
</code></pre>
<p>I used an object to map the various operation names to their corresponding functions. Not sure if this is better than switch-case statements.</p>
|
[] |
[
{
"body": "<h2>Unusual undo redo</h2>\n<p>Your undo and redo operations have a strange behavior in that they are them selves undo-able. Generally undo and redo operations are themselves not undo-able.</p>\n<h2>Bug?</h2>\n<p>Unknown commands will throw the error <code>TypeError: this.operations[operation] is not a function</code></p>\n<h2>SEMICOLONS!</h2>\n<p>I think I mentioned semicolons last time I reviewed your code. If you do not wish to use them you should be familiar with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#automatic_semicolon_insertion\" rel=\"nofollow noreferrer\">ASI</a></p>\n<h2>Identifiers</h2>\n<p>Try to avoid string identifiers as they are memory hungry ad can be much slower depending on the number and similarity of identifiers.</p>\n<p>One method of creating unique identifiers is via an enumeration object.</p>\n<p>Example</p>\n<pre><code>const operators = {\n append: 0,\n undo: 1,\n redo: 2,\n backspace: 3,\n}\n</code></pre>\n<p>The rewrite uses a function <code>Enum</code> that returns an object containing named integer Identifiers.</p>\n<h2>Encapsulation</h2>\n<p>Protect the state of the object. All properties of an object exposed to other code can not be trusted. Without a trusted state you can not guarantee that your code will run as expected.</p>\n<p>A well designed encapsulated object (once tested) can NOT fail.</p>\n<p>JavaScript has an excellent OO encapsulation model.</p>\n<ul>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures\" rel=\"nofollow noreferrer\">Closure</a> is used to encapsulate state within the Object that do not require additional language tokens to access (eg <code>this</code>)</li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Object\">Object</a> functions\n<ul>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Object freeze\">Object.freeze</a> will set all properties to writable: false, and the object to immutable.</li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Object seal\">Object.seal</a> properties remain writable but the object is set to immutable.</li>\n</ul>\n</li>\n</ul>\n<p>Using closure to hold the objects state, you then create an interface to provide an interface to the state. The interface is just an object (frozen or sealed) that uses getters, setters, and functions to access state and control behavior</p>\n<h2>Be efficient</h2>\n<p>Always write code to be as efficient as possible.</p>\n<p>Yes this is a balance between productivity and code efficiency but with a constant eye on efficiency you become more adept at writing efficient code</p>\n<h3>Inefficient undo buffer</h3>\n<p>Your undo is expensive as it stores the complete text for every action that can be undone. You need only store each operation and associated data in the undo buffer.</p>\n<p>This will make your code more complex but for large documents it will run much quicker and use far less memory. Clients don't see or care how things are done, they only care about what it does, if that include slow response and power hungry it is never a plus.</p>\n<h2>Rewrite</h2>\n<p>The rewrite adds a little functionality to help demonstrate some of the points above regarding the interface getters and setters.</p>\n<p>Usage remains the same</p>\n<p>Behavior is a little different</p>\n<ul>\n<li><p>Undo and redo are not undo-able commands</p>\n</li>\n<li><p>It uses an named integer values to identify operations. Which is a static property of <code>TextProcessor.operators</code> and internally accessed via <code>operators</code></p>\n</li>\n<li><p>The function <code>TextProcessor.process</code> ensures input is an array, filters out non arrays to avoid errors, and checks for valid operation before attempting to call the operation, again to avoid throwing errors.</p>\n</li>\n<li><p>For every undo-able operation there is an equivalent redo operation. This means that only the operation and operation data need be stored in the undo buffer.</p>\n</li>\n<li><p>All objects accessible by unrelated code are frozen to ensure that state can be trusted and maintained.</p>\n</li>\n<li><p>Individual operations are not available via the interface but would be easy to add if needed.</p>\n</li>\n</ul>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const Enum = (baseId, ...names) => Object.freeze(\n names.reduce((obj, name, i) => (obj[name] = i + baseId | 0, obj), {})\n); \nconst TextProcessor = (() => {\n function TextProcessor() {\n const undos = [];\n const undoOperations = {\n [operators.APPEND](txt) { text = text.slice(0, -txt.length) },\n [operators.BACKSPACE](txt) { text += txt }, \n [operators.CLEAR](txt) { text = txt }, \n };\n const undoable = (operation, ...data) => {\n undos.length = undoPos++;\n undos.push({operation, data});\n }\n const redoUndoable = () => undoPos++;\n const operations = {\n [operators.APPEND](txt) {\n txt = \"\" + txt; // forces txt to be a string\n addUndoable(operators.APPEND, txt);\n text += txt;\n },\n [operators.BACKSPACE]() {\n addUndoable(operators.BACKSPACE, text[text.length - 1]);\n text = text.slice(0, -1); \n }, \n [operators.CLEAR]() {\n addUndoable(operators.CLEAR, text);\n text = \"\"; \n }, \n [operators.UNDO]() {\n if (undoPos) {\n const op = undos[--undoPos];\n undoOperations[op.operation](...op.data);\n } \n }, \n [operators.REDO]() {\n if (undoPos < undos.length) {\n const op = undos[undoPos];\n addUndoable = redoUndoable;\n operations[op.operation](...op.data);\n addUndoable = undoable;\n } \n }\n }; \n var undoPos = 0, text = \"\", addUndoable = undoable; \n return Object.freeze({\n get text() { return text },\n set text(txt) {\n operations[operators.CLEAR]();\n operations[operators.APPEND](txt);\n },\n process(input) {\n if (Array.isArray(input)) {\n input = input.filter(operation => Array.isArray(operation));\n for (const [opName, data] of input) { \n operations[operators[opName]]?.(data);\n }\n }\n } \n });\n }\n const operators = Enum(1, \"APPEND\", \"BACKSPACE\", \"UNDO\", \"REDO\", \"CLEAR\");\n return Object.freeze(Object.assign(\n TextProcessor,\n operators\n ));\n})();\n\nconst textProcessor = TextProcessor()\ntextProcessor.process([\n ['APPEND', 'Hey'], \n ['APPEND', ' there'], \n ['APPEND', '!'], \n ['BACKSPACE'], ['BACKSPACE'], ['BACKSPACE'], ['BACKSPACE'],\n ['APPEND', '$'],\n ['UNDO'], ['REDO'],\n ['UNDO'], ['UNDO'], ['UNDO'], ['UNDO'], ['UNDO'], ['UNDO']\n ['REDO'], ['REDO'], ['REDO'], ['REDO'], ['REDO'], ['REDO'],\n ['UNDO'],\n ['APPEND', 'e'],\n ['APPEND', 'r'],\n ['APPEND', 'e'],\n ['APPEND', '$'], ['UNDO'],\n ['APPEND', '!'],\n ['CLEAR'],\n ['UNDO'],\n]);\n\nconsole.log(\"'\" + textProcessor.text + \"'\" + \" === 'Hey there!' \" + (textProcessor.text === \"Hey there!\"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T08:27:11.077",
"Id": "510813",
"Score": "0",
"body": "Great answer. I noticed you used `var` instead of `let` , is it possible use `let` or in this case better to use `var` for some specific reason I'm missing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T12:02:12.337",
"Id": "510825",
"Score": "0",
"body": "@dariosicily There is no reason you can not use a block scoped variable in function scope. i am a strong believer that all code should show clear intent and understanding."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T12:08:40.220",
"Id": "510826",
"Score": "0",
"body": "Thank you for your time and your explanation."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T21:45:21.103",
"Id": "259030",
"ParentId": "258999",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T07:09:25.427",
"Id": "258999",
"Score": "1",
"Tags": [
"javascript",
"object-oriented"
],
"Title": "JavaScript: Text Processor"
}
|
258999
|
<p>As a Haskell beginner I'm currently playing around the IO monad and prepared simple program which gets from the user two information:</p>
<ul>
<li>URL (http)</li>
<li>Output file path</li>
</ul>
<p>Then it performs <code>GET</code> request to the provided URL and stores the result in the selected file. HTTP status code of the response is displayed on the standard output</p>
<p>Could you please suggest how such code could be improved? Maybe some places when point-free style can be used? I also feel that the part with confirmation of file overwriting is not very elegant.</p>
<pre><code>import System.IO
import Network.HTTP
import System.Directory
getUrl :: IO String
getUrl = putStr "URL: " >> hFlush stdout >> getLine
confirmOverideOrGetNewPath :: String -> IO String
confirmOverideOrGetNewPath filepath = do
putStr $ "File " ++ filepath ++ " exists. Override? [y/n] "
hFlush stdout
decision <- getLine
let shouldOverride = (if decision == "y" then True else False)
case shouldOverride of True -> return filepath
False -> putStrLn "\nProvide other path" >> getOutputFilepath
getOutputFilepath :: IO String
getOutputFilepath = do
putStr "Output file path: "
hFlush stdout
filepath <- getLine
file_exists <- doesFileExist filepath
case file_exists of True -> confirmOverideOrGetNewPath filepath
False -> return filepath
performGetRequest :: String -> IO (String, Int)
performGetRequest url = do
rsp <- Network.HTTP.simpleHTTP (getRequest url)
content <- getResponseBody rsp
responseCode <- getResponseCode rsp
return (content, responseCodeToInt responseCode)
where
responseCodeToInt :: ResponseCode -> Int
responseCodeToInt code = let (x,y,z) = code in read (mconcat $ show <$> [x,y,z]) :: Int
saveContentToFile :: FilePath -> String -> IO ()
saveContentToFile = writeFile
printHttpStatusCode :: Int -> IO ()
printHttpStatusCode statusCode = putStrLn ("\nStatus code: " ++ show statusCode)
>> putStrLn "Content saved into file"
main :: IO ()
main = do
url <- getUrl
filepath <- getOutputFilepath
(content, statusCode) <- performGetRequest url
saveContentToFile filepath content
printHttpStatusCode statusCode
</code></pre>
|
[] |
[
{
"body": "<p>Right from the top I notice you could benefit from some factoring.</p>\n<pre><code>prompt :: String -> IO String\nprompt str = do\n putStr str\n hFlush stdout\n getLine\n</code></pre>\n<p>Then <code>getURL</code> is <code>prompt "URL: "</code> (and maybe doesn't even need to exist separately!) and <code>confirmOverideOrGetNewPath</code> and <code>getOutputFilepath</code> both lose two lines at the top. You'll notice that I also wrote this function with do-notation, it's a stylistic preference but I just don't like to run monads into one line like that, not sure if I have a great reason why. I guess it just feels right to make imperative-y monadic code look like an imperative language would.</p>\n<p>The diversion through <code>shouldOverride</code> in <code>confirmOverideOrGetNewPath</code> is unnecessary, just put your expression in the case-statement.</p>\n<pre><code>case decision == "y" of\n True -> ...\n</code></pre>\n<p>But then I'd also skip the check for equality entirely and just pattern match on the returned string.</p>\n<pre><code>case decision of\n "y" -> return filepath\n "n" -> getOutputFilepath\n _ -> do\n putStrLn "Unrecognized input"\n confirmOverrideOrGetNewPath filepath\n</code></pre>\n<p>I changed the logic to make the behavior more elucidating. If a user actually enters <code>"n"</code>, it's not really necessary to tell them to provide a new path since <code>getOutputFilepath</code> will prompt them for a new one immediately. The user presumably expects that, given their input. If they type something other than <code>"y"</code> or <code>"n"</code>, instead of requiring them to input a new path, just check again if they're cool with the override.</p>\n<p>In <code>getOutputFilepath</code> all I'd note is that <code>file_exists</code> should be camel cased for consistency.</p>\n<p>Over the rest of your program, the only thing I'd switch up would be the whole logic around response codes. In <code>performGetRequest</code> I'd just change the return type to be <code>ResponseCode</code> instead of <code>Int</code>, and push your display logic into <code>printHttpStatusCode</code> (which should probably be <code>printResponseCode</code>). Since <code>ResponseCode</code> is just a type alias for tuples, you can also pattern match in the function call (i.e. in your original version <code>responseCodeToInt (x, y, z) = ...</code> instead of the <code>let</code>). And then it also probably makes more sense to have a pure <code>showResponseCode</code> and leave printing up to the caller.</p>\n<pre><code>showResponseCode :: ResponseCode -> String\nshowResponseCode (i, j, k) = concatMap show [i, j, k]\n</code></pre>\n<p>Then I'd just carry the changes through to <code>main</code> and reorder things for clarity and truth in logic.</p>\n<pre><code>main = do\n ...\n (content, statusCode) <- performGetRequest url\n putStrLn $ "Response status: " ++ showResponseCode statusCode\n writeFile filepath content\n putStrLn "Content saved"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T22:58:29.943",
"Id": "259032",
"ParentId": "259003",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259032",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T10:27:47.417",
"Id": "259003",
"Score": "3",
"Tags": [
"haskell",
"monads"
],
"Title": "Haskell - saving content of HTTP request in selected file"
}
|
259003
|
<p>I would like to generate Millions of Random String and Hashes in Java fast as possible. For the moment, @Turing85 gave me a pretty good code who was pretty fast only 5 sec for 50M of random String but the next problem to which I am confronted is the slowness when I hash my passwords in my String. The only problem is that the hash must match the generated password.</p>
<p>For the moment I got this code for sha256 and the random String into a file.</p>
<pre><code>import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Random;
import java.util.concurrent.TimeUnit;
class Scratch {
private final static String policy = "azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBN1234567890";
private final static Random random = new Random();
private static final int MIN = '!';
private static final int MAX = '~';
private static final Random RANDOM = new Random();
public static void main(final String... args) throws IOException, NoSuchAlgorithmException {
final Path passwordFile = Path.of("passwords.txt");
final Path hashFile = Path.of("hash.txt");
if (!Files.exists(passwordFile)) {
Files.createFile(passwordFile);
}
if (!Files.exists(hashFile)) {
Files.createFile(hashFile);
}
final DecimalFormat df = new DecimalFormat();
final DecimalFormatSymbols ds = df.getDecimalFormatSymbols();
ds.setGroupingSeparator('_');
df.setDecimalFormatSymbols(ds);
final int numberOfPasswordsToGenerate = 50_000_000;
final int chunkSize = 500_000;
int passwordLength;
final int min = 'A';
final int max = 'Z';
int generated = 0;
int chunk = 0;
final long start = System.nanoTime();
while (generated < numberOfPasswordsToGenerate) {
final StringBuilder passwords = new StringBuilder();
final StringBuilder hashes = new StringBuilder();
for (int index = chunk * chunkSize; index < (chunk + 1) * chunkSize && index < numberOfPasswordsToGenerate;
++index) {
final StringBuilder password = new StringBuilder();
final StringBuilder hash = new StringBuilder();
passwordLength = random.nextInt(9 - 6) + 6;
for (int character = 0; character < passwordLength; ++character) {
//password.append(policy.charAt(random.nextInt(policy.length())));
password.append(fetchRandomLetterFromAlphabet());
}
passwords.append(password.toString()).append(System.lineSeparator());
hash.append(toHexString(getSHA(password.toString())));
hashes.append(hash.toString()).append(System.lineSeparator());
++generated;
if (generated % 500_000 == 0) {
System.out.printf(
"%s / %s%n",
df.format(generated),
df.format(numberOfPasswordsToGenerate));
}
}
++chunk;
Files.writeString(passwordFile, passwords.toString(), StandardOpenOption.WRITE);
Files.writeString(hashFile, hashes.toString(), StandardOpenOption.WRITE);
}
final long consumed = System.nanoTime() - start;
System.out.printf("Done. Took %d seconds%n", TimeUnit.NANOSECONDS.toSeconds(consumed));
//System.out.printf("Done. Took %d seconds%n", TimeUnit.NANOSECONDS.toNanos(consumed)/*.toSeconds(consumed)*/);
}
private static char fetchRandomLetterFromAlphabet() {
return (char) (RANDOM.nextInt(MAX - MIN + 1) + MIN);
}
public static byte[] getSHA(String input) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
return md.digest(input.getBytes(StandardCharsets.UTF_8));
}
public static String toHexString(byte[] hash) {
BigInteger number = new BigInteger(1, hash);
StringBuilder hexString = new StringBuilder(number.toString(16));
while (hexString.length() < 32) {
hexString.insert(0, '0');
}
return hexString.toString();
}
}
</code></pre>
<p>btw if you didn't understand the problematic, I would like to increase speed of the sha256 algorithm to make it more efficient</p>
<p>Thanks :)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T11:20:12.357",
"Id": "510749",
"Score": "0",
"body": "To my mind it's a bad idea to be storing the passwords and hashes like this. It would make more sense to generate the password, display it to the user and store only hash with the users id. Also you say you want to improve the SHA-256 algorithm but you don't present the actual algorithm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T12:21:33.940",
"Id": "510752",
"Score": "1",
"body": "In my view this question does not belong to *codereview.se* since this site is about **code quality**, not performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T00:21:44.847",
"Id": "510800",
"Score": "1",
"body": "@timothytruckle this has been discussed several times in meta, and the consensus is that performance is also a topic of review. Too tired to search for the thread right now but I'm sure you'll find it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T17:02:08.913",
"Id": "510842",
"Score": "0",
"body": "@EmilyL. thanks for pointing that out for me."
}
] |
[
{
"body": "<p>"I would like to increase the speed of the SHA256 algorithm"</p>\n<p>You're using a library for the hash so there's really no way for you to make it faster. In theory, if you're an expert in cryptography and in computer science you could maybe build something faster yourself but most likely it'll be slower because it's actually hard...</p>\n<p>From the resources I quickly checked online the Java sha256 implementation should be able to do atleast 100 MB/s on a modern ish computer.</p>\n<p>You say it takes 5 seconds to do 50M hashes of an average of 7.5 characters per string. That works out to 75 MB/s, which is in the ballpark but a bit on the slow end. I don't know what CPU your using so this could be normal or it could be slow.</p>\n<p>So as I see it there are some ways for you to make your code faster: optimize the generation of the strings (not the computation of the hash), OR use a faster sha256 implantation which likely means using JNI and a suitable C/C++ library (this may involve some hairloss and sacrificing a goat), OR probably the most effective way is to just use several threads each processing one chunk in parallel. They can then write to the same file with synchronization or separate files if you want maximum speed but you'll need to merge them later if you need a single file. Or you could do any combination of the three options above.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T11:56:59.010",
"Id": "510751",
"Score": "0",
"body": "And how implementing the multiThreading algorithm in my code for every hash ?\nYeah I used a prebuild librairy so maybe I can't speed up the hash for password"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T00:23:07.057",
"Id": "510801",
"Score": "1",
"body": "By learning multi threading for Java. There are plenty of tutorials and guides online that you can search for."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T11:46:38.567",
"Id": "259008",
"ParentId": "259004",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T10:44:08.717",
"Id": "259004",
"Score": "4",
"Tags": [
"java",
"beginner"
],
"Title": "Generating millions of hashes sha256 and random String in Java"
}
|
259004
|
<p>I implemented a convenience class to time code execution and print it to the user. This is part of a bigger project that will be distributed to external users. The timer however is only called by other procedures, not by the user directly. I was interested in implementing this myself, so I'm not looking for an external module or similiar. Docstrings are omitted here, the functions are rather straightforward.</p>
<pre><code>from time import perf_counter
class Timer:
def __init__(self, default_round_digits: int = 5):
self.default_digits = default_round_digits
self.start_timer()
def start_timer(self) -> None:
self.start_time = perf_counter()
self.pause_start_time = None
self.pause_length = 0
def pause_timer(self) -> None:
self.pause_start_time = perf_counter()
def resume_timer(self) -> None:
if self.pause_start_time is not None:
self.pause_length += perf_counter() - self.pause_start_time
self.pause_start_time = None
@property
def elapsed_seconds(self) -> float:
# If timer is paused only consider time up to self.pause_start_time instead of now
if self.pause_start_time is not None:
return self.pause_start_time - self.start_time - self.pause_length
else:
return perf_counter() - self.start_time - self.pause_length
def get_timer(self, round_digits: int = None, print_text: str = None, restart: bool = False) -> float:
if round_digits is None:
round_digits = self.default_digits
elapsed_seconds = round(self.elapsed_seconds, ndigits=round_digits)
if print_text is not None:
print(f"{print_text}{elapsed_seconds} seconds")
if restart:
self.start_timer()
return elapsed_seconds
def __str__(self) -> str:
state = "Running" if self.pause_start_time is None else "Paused"
return f"{state} Timer at {self.get_timer()} seconds"
</code></pre>
<p>I'm still unsure about initializing attributes outside of <code>__init__</code>. I know it's not recommended, but copying <code>start_timer</code> into <code>__init__</code> seemed like the worse option to me.</p>
|
[] |
[
{
"body": "<p>Regarding your question about attribute initialization:</p>\n<p>It's not necessarily better to put all attributes into <code>__init__</code>. It's generally recommended, since we expect to find all class attributes inside of <code>__init__</code>, but I would argue in this case, it's just as readable. In fact I would say initializing these values with <code>None</code> inside <code>__init__</code> (just to suppress the warnings or follow the recommendation) hurts readability in your case:</p>\n<pre><code>def __init__(self, default_round_digits: int = 5):\n self.default_digits = default_round_digits\n\n self.start_time = None\n self.pause_start_time = None\n self.pause_length = None\n\n self.start_timer()\n</code></pre>\n<p>Here are some further discussions on StackOverflow regarding the topic:</p>\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/19284857/instance-attribute-attribute-name-defined-outside-init\">Instance attribute attribute_name defined outside <strong>init</strong></a></li>\n<li><a href=\"https://stackoverflow.com/questions/46434475/python-instance-attribute-defined-outside-init\">Python - instance attribute defined outside <strong>init</strong>()</a></li>\n<li><a href=\"https://stackoverflow.com/questions/25158898/why-is-defining-an-object-variable-outside-of-init-frowned-upon/25159060\">why is defining an object variable outside of <strong>init</strong> frowned upon?</a></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T13:18:23.533",
"Id": "259012",
"ParentId": "259011",
"Score": "3"
}
},
{
"body": "<ol>\n<li><p>Your <code>Timer</code> class contains two timers.</p>\n<ol>\n<li>The entire duration timer.</li>\n<li>The timer for tracking pauses.</li>\n</ol>\n<p>I'd move the core timer code out into a separate class.\nAnd we can see you're starting to repeat yourself.</p>\n</li>\n<li><p>Initializing a timer shouldn't start the timer.\nIf I open my timer app should the timer start running straight away?</p>\n<p>If I want to create some timers but I don't want the timer to be started your class gives me no options.\nHowever just not calling <code>start_timer</code> in <code>__init__</code> will allow everyone to use your class however is desired.</p>\n<p>If you really really want to start the timer when building the object, you can write a class method.</p>\n<pre><code>class Timer:\n @classmethod\n def run(cls, *args, **kwargs):\n self = cls(*args, **kwargs)\n self.start_timer()\n return self\n\n# option 1\ntimer = Timer()\ntimer.start_timer()\n\n# option 2\ntimer = Timer.run()\n</code></pre>\n</li>\n<li><p><code>start_timer</code> restarts the timers.\nYou should rename the method or make the method do what is expected.</p>\n</li>\n<li><p>If you call <code>pause_timer</code> twice without calling <code>resume_timer</code> your code acts as if the timer was never paused the first time.</p>\n</li>\n<li><p>I don't really see the point of making <code>elapsed_seconds</code> a property.</p>\n</li>\n<li><p><code>get_timer</code> is doing way too much and violates the SRP principle.</p>\n<ol>\n<li>Rounds elapsed timings to a specified amount of decimal places.</li>\n<li>Prints the elapsed timings.</li>\n<li>Restarts the timer.</li>\n<li>Returns the elapsed timings.</li>\n</ol>\n<p>You should make a function to round the elapsed timings.\nThen leave printing and restarting to the user.</p>\n</li>\n<li><p>I'd a couple more methods from functionality I'd expect from a timer.</p>\n</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>from time import perf_counter\n\n\nclass CoreTimer:\n def __init__(self):\n self.stop()\n\n def __bool__(self):\n return bool(self.start_time)\n\n def start(self):\n self.start_time = perf_counter()\n\n def stop(self):\n self.start_time = 0\n\n def time_taken(self, now):\n return now - self.start_time\n\n def elapsed(self):\n return self.time_taken(perf_counter())\n\n\nclass Timer:\n def __init__(self, decimal_places=5):\n self._decimal_places = decimal_places\n self._timer = CoreTimer()\n self._pause = CoreTimer()\n self._pause_length = 0\n\n def __str__(self):\n state = "Paused" if self._pause else "Running"\n return f"{state} Timer at {self.elapsed_rounded()} seconds"\n\n @classmethod\n def run(cls, *args, **kwargs):\n self = cls(*args, **kwargs)\n self.start()\n return self\n\n def start(self):\n if not self._timer:\n self._timer.start()\n\n def stop(self):\n self._timer.stop()\n self._pause.stop()\n self._pause_length = 0\n\n def restart(self):\n self.stop()\n self.start()\n\n def pause(self):\n if not self._pause:\n self._pause.start()\n\n def resume(self):\n if self._pause:\n self._pause_length += self._pause.elapsed()\n self._pause.stop()\n\n def elapsed(self):\n if self._pause:\n duration = self._timer.time_taken(self._pause.start_time)\n else:\n duration = self._timer.elapsed()\n return duration - self._pause_length\n\n def elapsed_rounded(self, decimal_places=None):\n if decimal_places is None:\n decimal_places = self.decimal_places\n return round(self.elapsed(), ndigits=decimal_places)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T14:46:05.413",
"Id": "510755",
"Score": "1",
"body": "Thank you for your perspective, this is really helpful (a lot of improvements I hadn't considered yet)! I should've specified, that the timer will not be used directly by the user, only the print-outs by `get_timer` are seen by the user. That's why I included as much convenience for myself as possible. Considering that, would you still advise against the existence of convenience methods for printing and restarting? Something like `print_elapsed_and_restart`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T15:00:32.987",
"Id": "510756",
"Score": "1",
"body": "@riskypenguin By \"the user\" I mean \"anyone who uses `Timer`\" not \"anyone who uses your library\". I can understand the desire for convenience. But many times what you think is convenient at the start of the project is an inconvenience by the end of the project."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T15:24:36.673",
"Id": "510758",
"Score": "1",
"body": "I see your point, thanks again for the comprehensive review!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T13:58:28.160",
"Id": "259014",
"ParentId": "259011",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "259014",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T12:51:34.243",
"Id": "259011",
"Score": "3",
"Tags": [
"python",
"python-3.x"
],
"Title": "Timer convenience class to time code execution for user output"
}
|
259011
|
<p>I'm beginner on doing programming and just started learning C language. Then, i decide to make Tic-Tac-Toe as my first program.</p>
<p>My Tic-Tac-Toe summary: User can choose whether want to play 2 player or against computer. For computer player, i use <strong>Minimax Algorithm</strong> so it's not easy for user to win, whether they choose to be X or O. </p>
<p>Can you guys review my code? Is it good and clean enough or maybe there is something i can do better? Thank you!</p>
<pre><code>#include <ctype.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
typedef struct
{
char name[30];
char symbol;
}
player;
// GRID TOTAL BOX
const int N = 3;
char board[3][3] = {
{'1', '2', '3'},
{'4', '5', '6'},
{'7', '8', '9'}
};
player players[2];
char COMPUTER_AI;
int numOfplayer, winner;
void delay(int seconds);
void information();
void draw_board();
void draw_line();
void two_player_gameplay();
int check_win();
int check_minimax_win();
void show_the_winner(int result);
void human_move();
void computer_move();
int minimax(int depth, bool isMaximizing);
int main(void)
{
printf("Welcome to Tic-Tac-Toe game!\n\n");
information();
if (numOfplayer == 2)
{
two_player_gameplay();
}
else
{
// IF user choose to be X, move first
if (players[0].symbol == 'X')
{
human_move();
}
else
{
computer_move();
}
}
return 0;
}
// FUNCTION TO HANDLE HUMAN MOVE
void human_move()
{
int choice, found, result;
char mark, char_choice;
draw_board();
// Keep prompt user get the valid board number
do
{
printf("\t\t\t\t");
printf("%s : ", players[0].name);
scanf("%i", &choice);
// Get player symbol
mark = players[0].symbol;
// Always reset found to 0
found = 0;
for (int row = 0; row < N; row++)
{
for (int col = 0; col < N; col++)
{
// Convert user choice from int to char to compare with board array
char_choice = choice + '0';
// Check if number user choose is still exist in board, then it's legal to change it with user symbol
if (board[row][col] == char_choice)
{
// After change it, increment found if the board valid
board[row][col] = mark;
found++;
// Break the loop
row = col = N;
break;
}
}
}
}
while ((choice < 1 || choice > 9) || found == 0);
// Check if there's a winner
// IF It's 2, game still running, computer turn to move
// Otherwise, call show the winner function
result = check_win();
if (result == 2)
{
computer_move();
}
else
{
show_the_winner(result);
}
}
// FUNCTION TO HANDEL COMPUTER MOVE
void computer_move()
{
char board_number;
int move_i, move_j;
// Set best score to minus INFINITY
float bestScore = -INFINITY;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
// CHECK IF BOARD IS EMPTY
if (board[i][j] != 'X' && board[i][j] != 'O')
{
// Get the real number on board
board_number = board[i][j];
// Change the board temporary
// So we can call minimax to calculate it
board[i][j] = COMPUTER_AI;
float score = minimax(0, false);
// Reset to default board number
board[i][j] = board_number;
// AS maximizing player, IF score GREATER Than best score,
// Change the best score, store current board position to be placed
if (score > bestScore)
{
bestScore = score;
move_i = i;
move_j = j;
}
}
}
}
// Placed the best position
board[move_i][move_j] = COMPUTER_AI;
// Check win, if it's still running, human turn to move
int result = check_win();
if (result == 2)
{
human_move();
}
else
{
show_the_winner(result);
}
}
// MINIMAX FUNCTION
int minimax(int depth, bool isMaximizing)
{
// Base case
// Return static evaluation after get the winner
int result = check_minimax_win();
if (result != 2)
{
return result;
}
// IF Maximizing player turn to analyze
if (isMaximizing)
{
// SET best score to minus infinity
float bestScore = -INFINITY;
// ITERATE THROUGH BOARD
for (int row = 0; row < N; row++)
{
for (int col = 0; col < N; col++)
{
// Check if the positon in board is empty
if (board[row][col] != 'X' && board[row][col] != 'O')
{
// Get the real number on board
char board_number = board[row][col];
// Change the current position in board as MAXIMIZING (COMPUTER) symbol
// Call minimax recursively, minimizing turn
board[row][col] = COMPUTER_AI;
float score = minimax(depth + 1, false);
// Reset to default board number
board[row][col] = board_number;
// AS maximizing player, find the MAX score, store into best score
if (score > bestScore)
{
bestScore = score;
}
}
}
}
return bestScore;
}
// OTHERWISE, MINIMIZING TURN to analyze
else
{
// SET best score to +INFINITY
float bestScore = INFINITY;
for (int row = 0; row < N; row++)
{
for (int col = 0; col < N; col++)
{
if (board[row][col] != 'X' && board[row][col] != 'O')
{
char board_number = board[row][col];
// Change the current position in board as MAXIMIZING (COMPUTER) symbol, temporary
// Call minimax recursively, maximizing turn
board[row][col] = players[0].symbol;
float score = minimax(depth + 1, true);
// Reset to default board number
board[row][col] = board_number;
// AS Minimizing, get the Minimum score, store it to best score
if (score < bestScore)
{
bestScore = score;
}
}
}
}
return bestScore;
}
}
// TWO PLAYER GAMEPLAY
void two_player_gameplay()
{
int player = 0;
int choice, found, result;
char mark, char_choice;
do
{
draw_board();
// PROMPT current player to move
printf("\t\t\t\t");
printf("%s : ", players[player % 2].name);
scanf("%i", &choice);
// Get player symbol
mark = players[player % 2].symbol;
// Iterate through board to check and replace the board with user symbol
for (int row = 0; row < N; row++)
{
for (int col = 0; col < N; col++)
{
// Convert user choice from int to char to compare with board array
char_choice = choice + '0';
// Check if number user choose is still exist in board, then it's legal to change it with user symbol
if (board[row][col] == char_choice)
{
// After change it, increment player to the next
board[row][col] = mark;
player++;
// Break the loop
row = col = 3;
break;
}
}
}
// Call function to check if there's already winner
result = check_win();
}
while ((choice < 1 || choice > 9) || result == 2);
draw_board();
show_the_winner(result);
}
// FUNCTION TO ASK USER BEFORE STARTING GAME
void information()
{
// KEEP prompt user until enter valid number of player
do
{
printf("How many player will play (MAX is 2): ");
scanf("%i", &numOfplayer);
}
while (numOfplayer > 2);
printf("\n");
// If there's only one player
if(numOfplayer < 2)
{
printf("Enter your name: ");
scanf("%s", players[0].name);
getchar();
// Keep prompt user until enter valid symbol
do
{
printf("X or O: ");
scanf("%c", &players[0].symbol);
getchar();
}
while (players[0].symbol != 'X' && players[0].symbol != 'O');
// Assign symbol to user and computer
players[0].symbol = toupper(players[0].symbol);
COMPUTER_AI = (players[0].symbol == 'X' ? 'O' : 'X');
}
// Otherwise, two player
else
{
for (int i = 0; i < 2; i++)
{
// Get user name
printf("Enter Player %i name: ", i + 1);
scanf("%s", players[i].name);
getchar();
printf("\n");
}
// First player get X symbol
// Second player get O symbol
players[0].symbol = toupper('X');
players[1].symbol = ((toupper(players[0].symbol) == 'X') ? 'O' : 'X');
}
printf("\n\n");
}
// FUNCTION TO CHECK IF THERE IS WINNER
/*
Return 1 means X is winning.
Return -1 means O is winning.
Return 0 means game is draw.
Return 2 means game still running.
*/
int check_win()
{
for (int i = 0; i < N; i++)
{
for (int j = 1; j <= 1; j++)
{
// CHECK THREE in a row on HORIZONTAL Board
if (board[i][j - 1] == board[i][j] && board[i][j] == board[i][j + 1])
{
if (board[i][j] == 'X')
{
return 1;
}
else
{
return -1;
}
}
// CHECK THREE in a row on VERTICAL Board
else if (board[j - 1][i] == board[j][i] && board[j][i] == board[j + 1][i])
{
if (board[j][i] == 'X')
{
return 1;
}
else
{
return -1;
}
}
// CHECK THREE in a row on SLASH Board || 1 - 5- 9 or 3 - 5 - 7
else if (board[j - 1][j - 1] == board[j][j] && board[j][j] == board[j + 1][j + 1])
{
if (board[j][j] == 'X')
{
return 1;
}
else
{
return -1;
}
}
else if (board[j - 1][j + 1] == board[j][j] && board[j][j] == board[j + 1][j - 1])
{
if (board[j][j] == 'X')
{
return 1;
}
else
{
return -1;
}
}
// CHECK IF BOARD ALREADY FULL, AND NO ONES WIN (DRAW)
else if (board[j - 1][j - 1] != '1' && board[j - 1][j] != '2' && board[j - 1][j + 1] != '3' &&
board[j][j - 1] != '4' && board[j][j] != '5' && board[j][j + 1] != '6' &&
board[j + 1][j - 1] != '7' && board[j + 1][j] != '8' && board[j + 1][j + 1] != '9')
{
return 0;
}
}
}
// IF there's no three symbol in a row yet, game still running
return 2;
}
// FUNCTION TO CHECK THE WINNER || ONLY SPECIFY FOR MINIMAX FUNCTION
// HANDLE DIFFERENT RETURN BETWEEN X and O
/*
When user decide to play as X: O is computer as maximizing player
So, it always return 1 for best score
When user decide to play as O: X is computer as maximizing player
So, it ALSO always return 1 for best score
-1 is ONLY score for minimizing player: Human.
*/
int check_minimax_win()
{
for (int i = 0; i < N; i++)
{
for (int j = 1; j <= 1; j++)
{
// CHECK THREE in a row on HORIZONTAL Board
if (board[i][j - 1] == board[i][j] && board[i][j] == board[i][j + 1])
{
// IF user decide to play as O
if (players[0].symbol == 'O')
{
// Computer as maximizing player, X return 1 as best score
// O return -1 as minimizing score
if (board[i][j] == 'X')
{
return 1;
}
else
{
return -1;
}
}
// IF user decide to play as X
if (players[0].symbol == 'X')
{
// REVERSE THE RETURN VALUE (NOT CONDITION)
// Computer as maximizing player, X return -1 as minimizing score
// O return 1 as maximizing score
if (board[i][j] == 'X')
{
// X as minimizing
return -1;
}
else
{
// O as maximizing
return 1;
}
}
}
// CHECK THREE in a row on VERTICAL Board
else if (board[j - 1][i] == board[j][i] && board[j][i] == board[j + 1][i])
{
if (players[0].symbol == 'O')
{
// Computer as maximizing player, X return 1 as best score
// O return -1 as minimizing score
if (board[j][i] == 'X')
{
return 1;
}
else
{
return -1;
}
}
if (players[0].symbol == 'X')
{
// REVERSE THE RETURN VALUE (NOT CONDITION)
// Computer as maximizing player, X return -1 as minimizing score
// O return 1 as maximizing score
if (board[j][i] == 'X')
{
return -1;
}
else
{
return 1;
}
}
}
// CHECK THREE in a row on SLASH Board || 1 - 5- 9 or 3 - 5 - 7
else if (board[j - 1][j - 1] == board[j][j] && board[j][j] == board[j + 1][j + 1])
{
if (players[0].symbol == 'O')
{
// Computer as maximizing player, X return 1 as best score
// O return -1 as minimizing score
if (board[j][j] == 'X')
{
return 1;
}
else
{
return -1;
}
}
if (players[0].symbol == 'X')
{
// REVERSE THE RETURN VALUE (NOT CONDITION)
// Computer as maximizing player, X return -1 as minimizing score
// O return 1 as maximizing score
if (board[j][j] == 'X')
{
return -1;
}
else
{
return 1;
}
}
}
else if (board[j - 1][j + 1] == board[j][j] && board[j][j] == board[j + 1][j - 1])
{
if (players[0].symbol == 'O')
{
// Computer as maximizing player, X return 1 as best score
// O return -1 as minimizing score
if (board[j][j] == 'X')
{
return 1;
}
else
{
return -1;
}
}
if (players[0].symbol == 'X')
{
// REVERSE THE RETURN VALUE (NOT CONDITION)
// Computer as maximizing player, X return -1 as minimizing score
// O return 1 as maximizing score
if (board[j][j] == 'X')
{
return -1;
}
else
{
return 1;
}
}
}
// CHECK IF BOARD ALREADY FULL, AND NO ONES WIN (DRAW)
else if (board[j - 1][j - 1] != '1' && board[j - 1][j] != '2' && board[j - 1][j + 1] != '3' &&
board[j][j - 1] != '4' && board[j][j] != '5' && board[j][j + 1] != '6' &&
board[j + 1][j - 1] != '7' && board[j + 1][j] != '8' && board[j + 1][j + 1] != '9')
{
return 0;
}
}
}
// IF there's no three symbol in a row yet, game still running
return 2;
}
// FUNCTION TO SHOW THE WINNER
void show_the_winner(int result)
{
// AS one player only
if (numOfplayer < 2)
{
// CHECK IF the user symbol match with the result
if ((players[0].symbol == 'X' && result == 1) || (players[0].symbol == 'O' && result == -1))
{
draw_board();
printf("\n\t\t\t\t\t ---THE WINNER IS %s---\n\n\n", players[0].name);
}
// MAKE SURE COMPUTER PLAY AS X(1) OR O (-1)
else if (result == -1 || result == 1)
{
draw_board();
printf("\n\t\t\t\t\t\t ---YOU LOSE---\n\n\n");
}
// TIES
else
{
draw_board();
printf("\n\t\t\t\t\t ---THE GAME IS DRAW---\n\n\n");
}
}
// TWO PLAYER GAMEPLAY
else
{
// The end of game conditions
for (int i = 0; i < 2; i++)
{
if (result == 1)
{
if (players[i].symbol == 'X')
{
printf("\n\t\t\t\t\t ---THE WINNER IS %s---\n\n\n", players[i].name);
break;
}
}
if (result == -1)
{
if (players[i].symbol == 'O')
{
printf("\n\t\t\t\t\t ---THE WINNER IS %s---\n\n\n", players[i].name);
break;
}
}
if (result == 0)
{
printf("\n\t\t\t\t\t ---THE GAME IS DRAW---\n\n\n");
break;
}
}
}
}
// FUNCTION TO DRAW TICTACTOE BOARD
void draw_board()
{
system("clear");
printf("\n\n");
printf("\t\t\t\tEnter the number on board to choose your place!\n\n\n");
if (numOfplayer < 2)
{
printf("\t\t\t\t");
printf("%s : %c", players[0].name, toupper(players[0].symbol));
}
else
{
printf("\t\t\t\t");
printf("(Player 1) %s : %c\n", players[0].name, toupper(players[0].symbol));
printf("\t\t\t\t");
printf("(Player 2) %s : %c\n", players[1].name, toupper(players[1].symbol));
}
printf("\n\n");
for (int row = 0; row < N; row++)
{
for (int col = 0; col < N; col++)
{
// Print extra vertical bar on top only when for first column
if (col == 0)
{
printf("\t\t\t\t\t\t");
printf(" | | ");
printf("\n");
printf("\t\t\t\t\t\t");
}
// Print the number on each board column--Horizontally
printf(" %c ", board[row][col]);
// Print vertical bar at the end of number || EXCEPT for the last number
if (col != 2)
{
printf("|");
}
}
printf("\n");
// Print horizontal bar only for 2 column
if (row != 2)
{
printf("\t\t\t\t\t\t");
printf("_____|_____|_____");
printf("\n");
}
// Print extra vertical bar on below
if (row == 2)
{
printf("\t\t\t\t\t\t");
printf(" | | ");
printf("\n");
}
}
printf("\n\n");
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T23:44:21.740",
"Id": "510798",
"Score": "0",
"body": "Always write your main() at the bottom of your C file and try not to use global variables."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T01:47:56.377",
"Id": "510804",
"Score": "0",
"body": "@paladin \"Always write your main() at the bottom of your C file\" Can you explain why? I've seen suggestions to write it at the top instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T01:59:59.117",
"Id": "510805",
"Score": "1",
"body": "When writing main() at the end of your C file, you not only save 11 lines of redundant code (`void delay(int seconds); void information(); void draw_board(); void draw_line(); void two_player_gameplay(); int check_win(); int check_minimax_win(); void show_the_winner(int result); void human_move(); void computer_move(); int minimax(int depth, bool isMaximizing);`), you also have less ways to create bugs in your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T20:38:36.320",
"Id": "513828",
"Score": "0",
"body": "@paladin Incorrect. As written, the functions `computer_move` and `human_move` are mutually recursive. There will have to be a forward declaration or prototype for at least one of them. What's more, removing the prototypes imposes the requirement that the functions by topologically sorted, rather than sorted for the convenience of the author or maintainer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T00:06:50.027",
"Id": "513847",
"Score": "0",
"body": "@aghast I wouldn't call that \"mutually recursive\" I would call that less optimal programming. (It's better to use a game loop instead of a function driven program.) A C-program should be sorted chronologically, while special elements should be commented. This is my opinion."
}
] |
[
{
"body": "<p>regarding the posted code:</p>\n<p>Running it through the compiler results in:</p>\n<pre><code>gcc -ggdb3 -Wall -Wextra -Wconversion -pedantic -std=gnu11 -c "untitled2.c" -o "untitled2.o"\n\nuntitled2.c: In function ‘human_move’:\n\nuntitled2.c:95:31: warning: conversion from ‘int’ to ‘char’ may change value [-Wconversion]\n 95 | char_choice = choice + '0';\n | ^~~~~~\n\nuntitled2.c: In function ‘computer_move’:\n\nuntitled2.c:150:31: warning: conversion from ‘int’ to ‘float’ may change value [-Wconversion]\n 150 | float score = minimax(0, false);\n | ^~~~~~~\n\nuntitled2.c: In function ‘minimax’:\n\nuntitled2.c:212:35: warning: conversion from ‘int’ to ‘float’ may change value [-Wconversion]\n 212 | float score = minimax(depth + 1, false);\n | ^~~~~~~\n\nuntitled2.c:225:16: warning: conversion from ‘float’ to ‘int’ may change value [-Wfloat-conversion]\n 225 | return bestScore;\n | ^~~~~~~~~\n\nuntitled2.c:244:35: warning: conversion from ‘int’ to ‘float’ may change value [-Wconversion]\n 244 | float score = minimax(depth + 1, true);\n | ^~~~~~~\n\nuntitled2.c:257:16: warning: conversion from ‘float’ to ‘int’ may change value [-Wfloat-conversion]\n 257 | return bestScore;\n | ^~~~~~~~~\n\nuntitled2.c: In function ‘two_player_gameplay’:\n\nuntitled2.c:286:31: warning: conversion from ‘int’ to ‘char’ may change value [-Wconversion]\n 286 | char_choice = choice + '0';\n | ^~~~~~\n\nuntitled2.c:265:17: warning: unused variable ‘found’ [-Wunused-variable]\n 265 | int choice, found, result;\n | ^~~~~\n\nuntitled2.c: In function ‘information’:\n\nuntitled2.c:341:29: warning: conversion from ‘int’ to ‘char’ may change value [-Wconversion]\n 341 | players[0].symbol = toupper(players[0].symbol);\n | ^~~~~~~\n\nuntitled2.c:360:29: warning: conversion from ‘int’ to ‘char’ may change value [-Wconversion]\n 360 | players[0].symbol = toupper('X');\n | ^~~~~~~\n\nCompilation finished successfully.\n</code></pre>\n<p>regarding: <em>Compilation finished successfully.</em></p>\n<p>since there are warnings, this only means the compiler made some guess as to what you wanted, not that the produced code will do what you want.</p>\n<p>when posting code for review, please post code that cleanly compiles.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T20:44:14.210",
"Id": "513830",
"Score": "0",
"body": "I had never heard of -Wconversion until today. So thanks for that. But seriously, is gcc going to add -Wdouble-plus-extra for the next bunch of \"warnings that should be in -Wall but aren't\"? Maybe someone could submit an ENH for \"-Wmany\" to do what -Wall does now, and then -Wall could mean \"all\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T22:55:32.870",
"Id": "513840",
"Score": "1",
"body": "Without `-O2`, some of the warning flags do not have any effect since they are side-effects of optimizing the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T23:52:55.863",
"Id": "513844",
"Score": "0",
"body": "I compiled the OPs code with no optimization. so the warnings I discussed are not side effects of optimization"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T23:58:51.600",
"Id": "513846",
"Score": "0",
"body": "suggest starting at [gcc options](https://gcc.gnu.org/onlinedocs/gcc/Invoking-GCC.html#Invoking-GCC) to learn about the `gcc` options"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T17:42:28.523",
"Id": "259050",
"ParentId": "259015",
"Score": "0"
}
},
{
"body": "<h1>General Observations</h1>\n<p>The computer plays a good game!</p>\n<p>The visual display is pretty good, but I would normally expect to see the box bound by vertical and horizontal lines.</p>\n<p>The program could be a little more user friendly by accepting lower case input for <code>x</code> and <code>o</code> as well.</p>\n<p>The error checking in some cases could be improved, the game treats 0 players as 1 player.</p>\n<p>The game isn't quite as portable as it could be, I'm using Visual Studio 2019 Professional on Windows 10 and the system function clear doesn't work in the code, it generates a run time warning the first time it is executed. On a Linux or Unix system it might be better to use the NCurses library, but that still doesn't port to windows well.</p>\n<h1>Code Review</h1>\n<h2>Avoid Global Variables</h2>\n<p>It is very difficult to read, write, debug and maintain programs that use global variables. Global variables can be modified by any function within the program and therefore require each function to be examined before making changes in the code. In C and C++ global variables impact the namespace and they can cause linking errors if they are defined in multiple files. The <a href=\"https://stackoverflow.com/questions/484635/are-global-variables-bad\">answers in this stackoverflow question</a> provide a fuller explanation.</p>\n<p>Here are the global variable declarations:</p>\n<pre><code>char board[3][3] = {\n {'1', '2', '3'},\n {'4', '5', '6'},\n {'7', '8', '9'}\n};\n\nplayer players[2];\n\nchar COMPUTER_AI;\n\nint numOfplayer, winner;\n</code></pre>\n<h2>Naming Best Practices</h2>\n<p>A best practice in C programming is to make all constants upper case and all variables lower case, it would be better if <code>COMPUTER_AI</code> was <code>computer_ai</code>. User defined types such as</p>\n<pre><code>typedef struct\n{\n char name[30];\n char symbol;\n}\nplayer;\n</code></pre>\n<p>should have the first letter capitalized.</p>\n<pre><code>typedef struct\n{\n char name[30];\n char symbol;\n}\nPlayer;\n</code></pre>\n<h2>Initialize the Variables When They are Declared</h2>\n<p>I may not have looked hard enough, but I only found one place where a local variable was initialized when it was declared. The following is from the function <code>two_player_gameplay()</code>.</p>\n<pre><code> int player = 0;\n int choice, found, result;\n char mark, char_choice;\n</code></pre>\n<p>The C programming language has no concept of default initialization, every variable declared on the stack (in a function) should be initialized when it is declared. If it isn't initialized when it is declared the memory location will contain whatever was in that memory location before the variable was declared. This can lead to all kinds of interesting side affects.</p>\n<p>Each variable should be declared and initialized on one line of code to make the code more dependable, more readable and easier to maintain. Adding or deleting a variable then means just adding or deleting one line of code.</p>\n<pre><code> int player = 0;\n int choice = 0;\n int found = 0;\n int result = 0;\n char mark = players[player % 2].symbol;\n char char_choice = 0;\n</code></pre>\n<h2>Complexity</h2>\n<p>The function <code>check_minimax_win()</code> is too complex (does too much), it is 149 lines long including comments. Functions should be able to fit into a single screen in an editor or IDE. This is to make reading, writing, debugging and maintenance of the function easier. It would be better if each <code>if</code> or <code>else if</code> was a function or contained a function. This might also reduce the number of comments necessary if the functions are well named.</p>\n<p>There is a programming principle called the Single Responsibility Principle that applies here. The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> states:</p>\n<blockquote>\n<p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n<h2>Recursion Versus Iteration</h2>\n<p>The human versus computer game is implemented using what was once known as Figure 8 Recursion, where 2 functions alternately call each other. While the stack depth this will reach in this particular program is limited, there are costs associated with recursion that are not incurred by iterative programming. If this was a large grid rather than a 3 by 3 grid there would be the possibility of a stack overflow. Recursion repeated puts the function information for the function call on the stack, since in this implementation the function never returns from the call to <code>human_move()</code> or <code>computer_move()</code> during the execution these functions are never popped off the stack.</p>\n<p>It would be better to have a <code>do while</code> or <code>while</code> loop in main implement the calls to <code>human_move()</code> and <code>computer_move()</code> as is implemented in <code>two_player_gameplay()</code>, quite possibly there should be a <code>one_payer_gameplay()</code> function as well.</p>\n<h2>Constants and Array Sizes</h2>\n<p>The code contains</p>\n<pre><code>// GRID TOTAL BOX\nconst int N = 3;\n\nchar board[3][3] = {\n {'1', '2', '3'},\n {'4', '5', '6'},\n {'7', '8', '9'}\n};\n</code></pre>\n<p>The constant N is used in many places for accessing the board, but the board should be defined using N as well. This would allow a one line edit to change the size of the board. If you get a compiler error when using <code>N</code> for array size, then change the code</p>\n<pre><code>const int N = 3;\n</code></pre>\n<p>to</p>\n<pre><code>#define N 3\n\nchar board[N][N] = {\n {'1', '2', '3'},\n {'4', '5', '6'},\n {'7', '8', '9'}\n};\n</code></pre>\n<p>A constant named <code>BOARD_SIZE</code> might be better than <code>N</code>.</p>\n<h2>Code Organization</h2>\n<p>As @paladin observed in their comment, the normal file organization would put the <code>main(void)</code> function definition at the end of the file, and in that case prototype function declarations would not be necessary, especially if the recursion mentioned above was removed.</p>\n<p>Function prototypes are very useful in large programs that contain multiple source files, and that case they will be in header files. In a single file program like this it is better to put the main() function at the bottom of the file and all the functions that get used in the proper order above main(). Keep in mind that every line of code written is another line of code where a bug can crawl into the code.</p>\n<h2>User Input</h2>\n<p>In the function <code>information()</code> some variant of this code is repeated multiple times:</p>\n<pre><code> scanf("%s", players[0].name);\n getchar();\n</code></pre>\n<p>I believe the code is working around the fact that the end of line character <code>'\\n'</code> was not read in by the <code>scanf()</code> function. There is a better function to use instead of <code>scanf()</code>, that function is <a href=\"https://en.cppreference.com/w/c/io/fgets\" rel=\"nofollow noreferrer\">fgets( char *buffer, int buffer_size, FILE *stream )</a>. <code>fgets()</code> is better because it reads an entire line of input into the character array <code>buffer</code>, therefore the <code>getchar()</code> call is not necessary. A second improvement is that there is no possibility of buffer overflow using this method. Using the <code>scanf()</code> implementation can cause additional characters to be read into the player.name string array beyond the current size of 30. If that happens the player.symbol variable will be overwritten (possibly other variables as well).</p>\n<p>Example:</p>\n<pre><code> char buffer[128] = "";\n fgets(buffer, 128, stdin);\n strncpy(players[0].name, buffer, 30);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T17:25:15.453",
"Id": "263559",
"ParentId": "259015",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "263559",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T15:00:35.467",
"Id": "259015",
"Score": "3",
"Tags": [
"algorithm",
"c",
"tic-tac-toe"
],
"Title": "Tic-Tac-Toe in C language"
}
|
259015
|
<p>I have a Scrabble game program which takes two players' words and calculates who has the winning score.</p>
<p>Whichever player has the highest score is the winner; there's a tie if the scores are the same.</p>
<p>It all seems to work how I have written it; however I am sure it can be done better. Just wondering if anyone could give me some ideas on a more efficient way to write this?</p>
<pre><code>#include <ctype.h>
#include <cs50.h>
#include <stdio.h>
#include <string.h>
// Points assigned to each letter of the alphabet
int points[] = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10};
int compute_score(string word);
int main(void)
{
// Get input words from both players
string word1 = get_string("Player 1: ");
string word2 = get_string("Player 2: ");
// Score both words
int score1 = compute_score(word1);
int score2 = compute_score(word2);
// TODO: Print the winner
if (score1 < score2)
{
printf("Player 2 wins!...");
}
else if (score1 == score2)
{
printf("Tie!");
}
else
{
printf("Player 1 wins!...");
}
}
int compute_score(string word)
{
// TODO: Compute and return score for string
char letters[26];
int asciiletter = 97;
int score = 0;
int i = 0;
int k = 0;
for (i = 0; i < 26; i++)
{
letters[i] = asciiletter + i;
}
//Get the chars in the string of word and compare to all letters in alphabet letters[26]
for(int j= 0, n = strlen(word); j < n; j++)
{
//if entered values uppercase, convert to lower as points are the same for either case
word[j] = tolower(word[j]);
for(k = 0; k < 26; k++ )
{
if (word[j] == letters[k])
{
score = score + points[k];
}
}
}
return score;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T08:26:41.557",
"Id": "510812",
"Score": "0",
"body": "I compiled and executed your code: 1) the code did not cleanly compile. Always enable the warnings, then fix those warnings. 2) I ran your code with inputs of `rich` and `chucj` the result is the statement: `Player 2 wins!...` That seems a bit odd. Suggest: first, display the scrabble board second, instruct the user on what they are expected to input"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T08:32:05.610",
"Id": "510814",
"Score": "0",
"body": "regarding: `for(int j= 0, n = strlen(word); j < n; j++)` the function: `strlen()` returns a `size_t` (unsigned long) but this is comparing that to a `int` (which is signed) ... Not a good idea"
}
] |
[
{
"body": "<p>and welcome to C programming! Also, to Code Review.</p>\n<h1>Style</h1>\n<p>There are a couple of "style" issues with your code. The most obvious one is that your indentation is not consistent. I don't know if that's due to pasting it into the browser, or if it appears that way in your code. But <code>computescore</code> needs to be cleaned up.</p>\n<p>Next is an issue of "comprehensibility". You have this array:</p>\n<pre><code>// Points assigned to each letter of the alphabet\nint points[] = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10};\n</code></pre>\n<p>Quick, how many points for 'S'?</p>\n<p>This array might possibly be correct, but it's not comprehensible and it's not modifiable. It would be much better to provide some other mechanism to initialize the array, or initialize some other structure, such that the next guy to maintain the code has a chance of seeing bugs and/or being able to make changes.</p>\n<p>For example:</p>\n<ol>\n<li><p>You might create an enum, with point values for each letter, then initialize the array using the enum labels:</p>\n<pre><code>enum {\n A_POINTS = 1,\n B_POINTS = 3,\n C_POINTS = 3,\n :\n};\n\nint points[] = {\n A_POINTS,\n B_POINTS,\n C_POINTS,\n :\n};\n</code></pre>\n</li>\n<li><p>You might create a clever <a href=\"https://en.cppreference.com/w/c/language/array_initialization#Initialization_from_brace-enclosed_lists\" rel=\"nofollow noreferrer\"><em>designated initializer</em></a> macro that makes things more clear:</p>\n<pre><code>#define TILE(CH) [CH - 'a']\n\nint points[] = {\n TILE('a') = 1,\n TILE('b') = 3,\n TILE('c') = 3,\n :\n};\n</code></pre>\n</li>\n<li><p>You might consider building a string and parsing it at runtime, like:</p>\n<pre><code>const char * points = \n "A = 1; B = 3; C = 3; ...;"\n "N = ..."\n ;\n</code></pre>\n</li>\n</ol>\n<p>Be aware: the point of this is <em>purely</em> to make it easy to understand the mapping between letters and points. Ideally, you want to make it easy enough to understand that someone could look at the code and catch a mistake before you compiled it and went to testing.</p>\n<h1>Magic</h1>\n<p>Your scoring function searches through a list of characters in order to obtain the index of a particular character. <strong>Never do that!</strong> You <em>know</em> the index, it's just hidden behind a thin layer of mathematics.</p>\n<p>In ASCII, the upper and lowercase letters (also, digits) are runs of encoding values assigned in consecutive, increasing order. Once you know where the start of the run is, you can get to any other character by simple addition. Likewise, you can reverse that trick using simple subtraction:</p>\n<pre><code> score_index = ch - 'a';\n score += points[score_index];\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T20:07:00.273",
"Id": "510791",
"Score": "0",
"body": "Thank you for your comments. A lot of great points for me to revisit. I felt like I was over complicating how I dealt with the ascii chars and your comments help that."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T19:46:17.113",
"Id": "259026",
"ParentId": "259016",
"Score": "3"
}
},
{
"body": "<h1>Bug - <code>tolower()</code></h1>\n<blockquote>\n<pre><code> word[j] = tolower(word[j]);\n</code></pre>\n</blockquote>\n<p>We need to be careful with the functions in <code><ctype.h></code>. They generally accept <code>int</code> parameters that hold <em>unsigned</em> representations of characters; the only negative value that may be passed is <code>EOF</code>. So a robust program always converts any <code>char</code> value to <code>unsigned char</code> before allowing it to be promoted to <code>int</code>:</p>\n<pre><code> word[j] = tolower((unsigned char)word[j]);\n</code></pre>\n<p>In practice, you're unlikely to hit this bug if users enter only valid English Scrabble words, on systems using ASCII character coding. Which nicely introduces my two main points:</p>\n<h1>Character coding</h1>\n<p>This code assumes the host character set is ASCII, or at least includes ASCII as a subset. That might be acceptable, but we can minimise the code that needs to change when we need to compile for a different platform. Firstly, we could add a big fat warning, to alert the developer that work is required:</p>\n<pre><code>#if 'a' != 97\n#error compute_score() requires ASCII platform\n#endif\n</code></pre>\n<p>Where we use literal <code>97</code>, we would be better using the character literal <code>'a'</code> - this also helps show the reader our intent here:</p>\n<pre><code>int asciiletter = 'a';\n</code></pre>\n<p>Though I'd get rid of that completely, and convert the loop that depends on letters being consecutive:</p>\n<blockquote>\n<pre><code>for (i = 0; i < 26; i++)\n{\n letters[i] = asciiletter + i;\n}\n</code></pre>\n</blockquote>\n<p>into a simple string that's independent of character coding:</p>\n<pre><code>static const char *letters = "abcdefghijklmnopqrstuvwxyz";\n</code></pre>\n<p>Having done that, there's no longer any need for the <code>#if</code>/<code>#warning</code> I proposed earlier.</p>\n<h1>Languages</h1>\n<p>Although we have provided some flexibility by storing the tile point-values in a table, our code is tied to English, notably in this line:</p>\n<blockquote>\n<pre><code>char letters[26];\n</code></pre>\n</blockquote>\n<p>Other languages have fewer (e.g. <a href=\"https://en.wikipedia.org/wiki/Scrabble_letter_distributions#Irish\" rel=\"nofollow noreferrer\">Irish</a>) or more (e.g. <a href=\"https://en.wikipedia.org/wiki/Scrabble_letter_distributions#Swedish\" rel=\"nofollow noreferrer\">Swedish</a>) than 26 different tiles.</p>\n<p>One possibility for dealing with the differences is to ask a function for the letter score, and to allow different functions to be swapped in, using a function pointer:</p>\n<pre><code>typedef int(*tile_score)(char);\n\nint tile_score_english(char c)\n{\n switch (tolower((unsigned char)c)) {\n case 'a': case 'e': case 'i': case 'o': case 'n':\n case 'r': case 't': case 'l': case 's': case 'u':\n return 1;\n case 'd': case 'g':\n return 2;\n case 'b': case 'c': case 'm': case 'p':\n return 3;\n case 'f': case 'h': case 'v': case 'w': case 'y':\n return 4;\n case 'k':\n return 5;\n case 'j': case 'x':\n return 8;\n case 'q': case 'z':\n return 10;\n }\n return 0;\n}\n\nint tile_score_french(char c)\n{\n switch (tolower((unsigned char)c)) {\n case 'a': case 'e': case 'i': case 'o': case 'n':\n case 'r': case 't': case 'l': case 's': case 'u':\n return 1;\n case 'd': case 'm': case 'g':\n return 2;\n case 'b': case 'c': case 'p':\n return 3;\n case 'f': case 'h': case 'v':\n return 4;\n case 'j': case 'q':\n return 8;\n case 'k': case 'w': case 'x': case 'y': case 'z':\n return 10;\n }\n return 0;\n}\n\n⋮\n</code></pre>\n<p>Then we simply pass the language's score function when we want the total score:</p>\n<pre><code>int compute_score(string word, tile_score distribution)\n{\n int score = 0;\n for (char *p = word; *p; ++p) {\n score += distribution(*p);\n }\n return score;\n}\n</code></pre>\n<p>As a side benefit, good compilers will turn the <code>switch</code>/<code>case</code> into a simple lookup, which will be more efficient than the linear search we currently have.</p>\n<p>We still have some work to do for languages such as <a href=\"https://en.wikipedia.org/wiki/Scrabble_letter_distributions#Welsh\" rel=\"nofollow noreferrer\">Welsh</a>, which have diphthong tiles (DD, FF, TH, CH, LL, NG, RH). I'll leave handling those as an exercise for the reader!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T09:26:42.437",
"Id": "259074",
"ParentId": "259016",
"Score": "0"
}
},
{
"body": "<p>The simple points array just needs two newlines:</p>\n<pre><code>int points[] = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, //10 \n 5, 1, 3, 1, 1, 3,10, 1, 1, 1, //20\n 1, 4, 4, 8, 4,10}; //26\n</code></pre>\n<p>This is not super user-friendly, but also not the opposite.</p>\n<p>How to quite directly map the ASCII to the index has already been answered ("Magic").</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T11:36:19.413",
"Id": "259078",
"ParentId": "259016",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T15:44:21.433",
"Id": "259016",
"Score": "1",
"Tags": [
"beginner",
"c"
],
"Title": "Scrabble word scoring"
}
|
259016
|
<p>I am fairly new to C++ and I was wondering if there is anything I can improve in this code(perf, readability)? Thanks. This is the full code: <a href="https://github.com/test1230-lab/graphing_calc_cpp/blob/master/MathParser/MathParser.cpp" rel="noreferrer">Github Link</a></p>
<p>I will post the parser that creates a rpn representation of an input string and a function that evaluates the rpn here(the rest is on the github):</p>
<pre><code>#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <string_view>
#include <string>
#include <vector>
#include <utility>
#include <stack>
#include <numbers>
#include <regex>
#include <variant>
#include <chrono>
#include <cmath>
constexpr int LEFT_ASSOC = 0;
constexpr int RIGHT_ASSOC = 1;
//pair is <prec, assoc_id>
static const std::unordered_map<std::string_view, std::pair<int, int>> assoc_prec{ {"^", std::make_pair(4, RIGHT_ASSOC)},
{"*", std::make_pair(3, LEFT_ASSOC)},
{"/", std::make_pair(3, LEFT_ASSOC)},
{"+", std::make_pair(2, LEFT_ASSOC)},
{"-", std::make_pair(2, LEFT_ASSOC)} };
static const std::unordered_map<std::string_view, double(*)(double)> unary_func_tbl{ {"sin", &sin},
{"cos", &cos},
{"sqrt", &sqrt},
{"abs", &abs},
{"tan", &tan},
{"acos", &acos},
{"asin", &asin},
{"atan", &atan},
{"log", &log},
{"log10", &log10},
{"cosh", &cosh},
{"sinh", &sinh},
{"tanh", &tanh},
{"exp", &exp},
{"cbrt", &cbrt},
{"tgamma", &tgamma},
{"lgamma", &lgamma},
{"ceil", &ceil},
{"floor", &floor},
{"acosh", &acosh},
{"asinh", &asinh},
{"trunc", &trunc},
{"atanh", &atanh} };
static const std::unordered_set<std::string_view> funcs{ "sin", "tan", "acos", "asin", "asin", "abs",
"atan", "cosh", "sinh", "cos", "tanh",
"acosh", "asinh", "atanh", "exp", "ldexp",
"log", "log10", "sqrt", "cbrt", "tgamma",
"lgamma", "ceil", "floor", "trunc" };
bool is_left_assoc(std::string_view str)
{
int id = assoc_prec.at(str).second;
if (id == 0) return true;
else return false;
}
bool is_binary_op(std::string_view str)
{
if (str == "/" || str == "*" || str == "+" || str == "-" || str == "^")
{
return true;
}
else return false;
}
bool is_func(std::string_view str)
{
if (funcs.count(str) > 0) return true;
else return false;
}
//handls decimal numbers
bool is_num(std::string_view str)
{
int num_found_periods = 0;
for (const auto c : str)
{
if (c == '.')
{
num_found_periods++;
if (num_found_periods > 1)
{
return false;
}
}
if (!isdigit(c) && c != '.')
{
return false;
}
}
return true;
}
int get_prec(std::string_view str)
{
if (is_func(str))
{
return 1; //TODO: check it this is the correct value
}
else if (is_binary_op(str))
{
return assoc_prec.at(str).first;
}
else
{
return 0;
}
}
//from https://stackoverflow.com/a/56204256
//modified regex expr
std::vector<std::string> tokenize(const std::string& str)
{
std::vector<std::string> res;
const std::regex words_regex("(sin|tan|acos|asin|abs|atan|cosh|sinh|cos|"
"tanh|acosh|asinh|atanh|exp|ldexp|log|log10|"
"sqrt|cbrt|tgamma|lgamma|ceil|floor|x|e)|^-|[0-9]?"
"([0-9]*[.])?[0-9]+|[\\-\\+\\\\\(\\)\\/\\*\\^\\]",
std::regex_constants::egrep);
auto words_begin = std::sregex_iterator(str.begin(), str.end(), words_regex);
auto words_end = std::sregex_iterator();
for (std::sregex_iterator i = words_begin; i != words_end; ++i)
{
res.push_back((*i).str());
}
return res;
}
//params:
//str - string to be converted
//var_name - any occurances of this as a seperate token will be treated as a varable
//convert string in infix notation to a string in Reverse Polish Notation
//using dijkstra's shunting yard algorithm
std::vector<std::variant<double, std::string>> s_yard(const std::string& str, std::string var_name)
{
std::vector<std::variant<double, std::string>> output_queue;
std::stack<std::string> op_stack;
for (const auto& tok : tokenize(str))
{
if (tok == "pi")
{
output_queue.push_back(std::numbers::pi_v<double>);
}
else if (tok == "e")
{
output_queue.push_back(std::numbers::e_v<double>);
}
else if (tok == var_name)
{
output_queue.push_back(tok);
}
else if (is_num(tok))
{
output_queue.push_back(strtod(tok.c_str(), NULL));
}
else if (is_func(tok))
{
op_stack.push(tok);
}
else if (is_binary_op(tok))
{
while (!op_stack.empty() && \
(is_binary_op(op_stack.top()) && get_prec(op_stack.top()) > (get_prec(tok)) || \
(get_prec(op_stack.top()) == get_prec(tok) && is_left_assoc(tok))) && \
(op_stack.top() != "("))
{
//pop operators from stack to queue
while (!op_stack.empty())
{
output_queue.push_back(op_stack.top());
op_stack.pop();
}
}
op_stack.push(tok);
}
else if (tok == "(")
{
op_stack.push(tok);
}
else if (tok == ")")
{
while (op_stack.top() != "(")
{
output_queue.push_back(op_stack.top());
op_stack.pop();
}
if (op_stack.top() == "(")
{
op_stack.pop();
}
if (is_func(op_stack.top()))
{
output_queue.push_back(op_stack.top());
op_stack.pop();
}
}
}
//all tokens read
while (!op_stack.empty())
{
//there are mismatched parentheses
if (op_stack.top() == "(" || op_stack.top() == ")")
{
std::cout << "mismatched parentheses\n";
}
output_queue.push_back(op_stack.top());
op_stack.pop();
}
return output_queue;
}
double compute_binary_ops(double d1, double d2, std::string_view op)
{
if (op == "*") return d1 * d2;
else if (op == "+") return d1 + d2;
else if (op == "-") return d1 - d2;
else if (op == "/") return d1 / d2;
else if (op == "^") return pow(d1, d2);
else
{
std::cout << R"(invalid operator: ")" << op << R"(" passed to func "compute_binary_ops")" << '\n';
exit(-1);
}
}
double eval_rpn(const std::vector<std::variant<double, std::string>>& tokens, std::string var_name, double var_value)
{
double d2 = 0.0;
double res = 0.0;
std::stack<std::variant<double, std::string>> stack;
for (const auto& tok : tokens)
{
if (const double *number = std::get_if<double>(&tok))
{
stack.push(*number);
}
else if (std::get<std::string>(tok) == var_name)
{
stack.push(var_value);
}
//handle binary operaters
else if(is_binary_op(std::get<std::string>(tok)))
{
d2 = std::get<double>(stack.top());
stack.pop();
if (!stack.empty())
{
const double d1 = std::get<double>(stack.top());
stack.pop();
res = compute_binary_ops(d1, d2, std::get<std::string>(tok));
stack.push(res);
}
else
{
if (std::get<std::string>(tok) == "-") res = -(d2);
else res = d2;
stack.push(res);
}
}
//handle funcs(unary ops)
else if (is_func(std::get<std::string>(tok)))
{
if (!stack.empty())
{
const double d1 = std::get<double>(stack.top());
stack.pop();
res = (*unary_func_tbl.at(std::get<std::string>(tok)))(d1);
stack.push(res);
}
else
{
if (std::get<std::string>(tok) == "-") res = -(d2);
else res = d2;
stack.push(res);
}
}
}
return std::get<double>(stack.top());
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T17:33:30.240",
"Id": "510769",
"Score": "0",
"body": "Elaborate in what way?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T19:08:07.967",
"Id": "510783",
"Score": "1",
"body": "Welcome to CodeReview! Because we like to have things stand alone (in case the target of a link changes or disappears at some point in the future), the question needs a bit more context to allow a review to be done on just this code. So for instance, a bit of description of what `tokenize` returns and some examples of the kinds of equations you're intending to parse would be helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T19:40:45.813",
"Id": "510786",
"Score": "0",
"body": "I will post most of the functions here, I was just concerned that it would be too long of a post. How much should I include in the post?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T19:45:09.457",
"Id": "510787",
"Score": "0",
"body": "Unlike some other sister sites, we tend to like more complete code. Reviews tend to benefit from a fuller context; it makes the code easier to meaningfully review and it gives the person asking for the review a more useful result. You don't need to post everything, but if it fits, it's probably not too long."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T19:51:33.983",
"Id": "510789",
"Score": "0",
"body": "Ok I edited it to include everything other than the rendering for the graphing calculator. Thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T21:45:33.357",
"Id": "510793",
"Score": "0",
"body": "Could you add some testing code as well? It would be nice to verify that the shown code actually works."
}
] |
[
{
"body": "<h1>Avoid overly large indentation</h1>\n<p>I can't read the contents of the maps and set being declared at the start of the code without scrolling far to the right. I suggest you reduce the indentation by putting the first element inside the initializer list on its own line, like so:</p>\n<pre><code>static const std::unordered_map<std::string_view, std::pair<int, int>> assoc_prec{\n {"^", std::make_pair(4, RIGHT_ASSOC)},\n {"*", std::make_pair(3, LEFT_ASSOC)},\n {"/", std::make_pair(3, LEFT_ASSOC)},\n {"+", std::make_pair(2, LEFT_ASSOC)},\n {"-", std::make_pair(2, LEFT_ASSOC)}\n};\n</code></pre>\n<h1>Use initializer lists instead of <code>std::make_pair()</code> where possible</h1>\n<p>In the case of the above map, the compiler knows up front what the type of the value of each element is, so you don't have to use <code>std::make_pair()</code>. You should be able to write:</p>\n<pre><code>static const std::unordered_map<std::string_view, std::pair<int, int>> assoc_prec{\n {"^", {4, RIGHT_ASSOC}},\n {"*", {3, LEFT_ASSOC}},\n ...\n</code></pre>\n<h1>Use an <code>enum class</code> for the associativity</h1>\n<p>To increase type safety and to allow the compiler to catch more errors, make the associativity an <code>enum class</code>, like so:</p>\n<pre><code>enum class associativity {\n LEFT,\n RIGHT\n};\n</code></pre>\n<p>And then use it like so:</p>\n<pre><code>static const std::unordered_map<std::string_view, std::pair<int, associativity>> assoc_prec{\n {"^", {4, associativity::RIGHT}},\n {"*", {3, associativity::LEFT}},\n ...\n};\n</code></pre>\n<h1>Use <code>fabs()</code> instead of <code>abs()</code></h1>\n<p>There is a compile error, since you wrote <code>&abs</code> in the initialization of <code>unary_func_tbl</code>, which should have been <code>&fabs</code>. Note that the ampersands here are redundant, you can omit them.</p>\n<p>You could also have written <code>std::abs</code>, and it would have been fine, since that one has an overload for <code>double</code>s.</p>\n<h1>No need for <code>funcs</code></h1>\n<p>The set <code>funcs</code> is not necessary, you already have <code>unary_func_tbl</code> which contains the same information.</p>\n<h1>Redundant <code>if</code>-statements</h1>\n<p>An <code>if</code>-statement that looks like:</p>\n<pre><code>if (condition) return true; else return false;\n</code></pre>\n<p>Is redundant. You can just write:</p>\n<pre><code>return condition;\n</code></pre>\n<p>For example, <code>is_left_assoc()</code> can be rewritten as:</p>\n<pre><code>bool is_left_assoc(std::string_view str)\n{\n return assoc_prec[str].second == associativity::LEFT;\n}\n</code></pre>\n<h1>Use <code>contains()</code> instead of <code>count()</code></h1>\n<p>Since you added the C++20 tag, you should know that they finally added the <a href=\"https://en.cppreference.com/w/cpp/container/unordered_map/contains\" rel=\"nofollow noreferrer\"><code>contains()</code></a> member function to the associative containers in the STL. So now you can write:</p>\n<pre><code>bool is_func(std::string_view str)\n{\n return funcs.contains(str);\n}\n</code></pre>\n<h1>About error handling</h1>\n<p>There are a few things where your error handling could be improved. First, write error messages to <code>std::cerr</code>. This ensures they don't get mixed with the normal output, in particular consider that someone might call your program and redirect the standard output to a file.</p>\n<p>Second, use a consistent way to handle errors. Most errors in the input are just ignored, some get error messages (mismatched parentheses), some error handling is in the wrong place (<code>compute_binary_ops()</code> checks for invalid operators, but this should never happen there since it had to pass <code>is_binary_op()</code> first), and only in one place do you actually stop parsing by calling <code>exit(-1)</code>.</p>\n<p>I suggest that you start using exceptions to report errors. Create one or more exception types that derive from one of the <a href=\"https://en.cppreference.com/w/cpp/header/stdexcept\" rel=\"nofollow noreferrer\">standard exception types</a>, I recommend either <code>std::exception</code> or <code>std::runtime_error</code>. For example:</p>\n<pre><code>class parse_error: public std::runtime_error {\npublic:\n explicit parse_error(const string &what): std::runtime_error(what) {}\n explicit parse_error(const char *what): std::runtime_error(what) {}\n};\n</code></pre>\n<p>And then <code>throw</code> whenever you encounter an error:</p>\n<pre><code>if (op_stack.top() == "(" || op_stack.top() == ")")\n{\n throw parse_error("Mismatched parentheses");\n}\n</code></pre>\n<p>If you don't catch exceptions, this will ensure your program aborts with a non-zero exit code, and it will print the error message. It also allows callers to catch exceptions in case they are able to handle them in some useful way.</p>\n<p>Don't forget to throw an exception in all unhandled cases, for example add the following to the end of the <code>if</code>-<code>else</code> chain in <code>s_yard()</code>:</p>\n<pre><code>else\n{\n throw parse_error("Unknown token: " + tok);\n}\n</code></pre>\n<h1>Consider using a parser generator</h1>\n<p>The main goal of your program is plotting equations. Parsing equations is just something to do to reach that goal. Consider using a <a href=\"https://en.wikipedia.org/wiki/Compiler-compiler\" rel=\"nofollow noreferrer\">parser generator</a> that will generate the C++ code for you to parse equations. Some well known tools for generating C++ parsers are <a href=\"https://en.wikipedia.org/wiki/Flex_(lexical_analyser_generator)\" rel=\"nofollow noreferrer\">GNU Flex</a> and <a href=\"https://en.wikipedia.org/wiki/GNU_Bison\" rel=\"nofollow noreferrer\">GNU Bison</a> (used together), although there are <a href=\"https://en.wikipedia.org/wiki/Comparison_of_parser_generators\" rel=\"nofollow noreferrer\">many others</a>.</p>\n<h1>Performance</h1>\n<p>It looks like when you will be plotting an equation, you will call <code>eval_rpn()</code> many times. Even though you only have to tokenize and call <code>s_yard()</code> once, your code still has to parse each individual token to find out if they are a value, function, or binary operator. Wouldn't it be nice if we could pre-process it even more, so that we don't have to do that each time we want to evaluate the equation?</p>\n<p>Ideally, we want to generate a function that we can call with the variable's value as an argument, and that returns the result of applying the equation. Thanks to lambdas and <a href=\"https://en.cppreference.com/w/cpp/utility/functional/function\" rel=\"nofollow noreferrer\"><code>std::function</code></a> objects, we can actually make a poor man's JIT compiler in C++. Here is an example of what it looks like:</p>\n<pre><code>std::function<double(double)> build_function(const std::vector<std::variant<double, std::string>>& tokens, std::string var_name)\n{ \n std::stack<std::function<double(double)>> stack;\n\n for (const auto& tok : tokens)\n {\n if (const double *num_ptr = std::get_if<double>(&tok))\n {\n stack.push([number=*num_ptr](double){return number;});\n }\n else if (std::get<std::string>(tok) == var_name)\n {\n stack.push([](double var_value){return var_value;});\n }\n else if(is_binary_op(std::get<std::string>(tok)))\n {\n auto right = stack.top();\n stack.pop();\n auto left = stack.top();\n stack.pop();\n auto op = std::get<std::string>(tok);\n stack.push([left, right, op](double var_value){return compute_binary_ops(left(var_value), right(var_value), op);});\n }\n else if (is_func(std::get<std::string>(tok)))\n {\n auto operand = stack.top();\n stack.pop();\n auto function = unary_func_tbl.at(std::get<std::string>(tok));\n stack.push([operand, function](double var_value){return function(operand(var_value));});\n }\n }\n\n return stack.top();\n}\n</code></pre>\n<p>And you use it like so:</p>\n<pre><code>auto rpn = s_yard("sin(x) + 1", "x");\nauto function = build_function(rpn, "x");\n\nfor(double x = 0; x <= 6.28; x += 0.1)\n std::cout << x << ' ' << func(x) << '\\n';\n</code></pre>\n<p>If you want to go even faster than this, you could consider converting the equation to C++ source code and compiling it into a shared library, and use <a href=\"https://man7.org/linux/man-pages/man3/dlopen.3.html\" rel=\"nofollow noreferrer\"><code>dlopen()</code></a> to load it.</p>\n<p>Since you are using SDL to plot the equation, you could also consider generating a <a href=\"https://www.khronos.org/opengl/wiki/Compute_Shader\" rel=\"nofollow noreferrer\">compute shader</a> from the equation, and letting the GPU process it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T22:56:21.093",
"Id": "510796",
"Score": "0",
"body": "Can you please elaborate on the performance section? I don't understand why the lambda would operate on the whole stack. Also how would the lambda be created with the plus operator or the sin function(any func)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T08:40:52.673",
"Id": "510816",
"Score": "0",
"body": "I changed it so it no longer needs the stack at the end, the \"poor man's JIT\" now produces a single `std::function` that you can use to evaluate the equation for any value of the variable. I added a fully working example. Let me know if things are still unclear."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T15:49:35.067",
"Id": "510837",
"Score": "0",
"body": "I was told that the map of function pointers is not compliant because it is taking the address of standard library functions. Should I replace this with a if else chain to compute the unary functions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T15:55:02.997",
"Id": "510838",
"Score": "1",
"body": "I don't see anything wrong with the map of function pointers. It's perfectly fine to take the address of a function, regardless of where it comes from."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T16:23:49.163",
"Id": "510841",
"Score": "0",
"body": "ok, and btw the perf suggestion you made worked very well. thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T17:09:41.023",
"Id": "510844",
"Score": "0",
"body": "this makes the \"-\" operator work: https://pastebin.com/MhpUvqs5 (too long for comment)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T17:43:07.633",
"Id": "510851",
"Score": "0",
"body": "Hm, I don't think it's correct to decide whether `-` is a binary or unary operator based on the number of elements on the stack."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T21:56:12.683",
"Id": "259031",
"ParentId": "259019",
"Score": "4"
}
},
{
"body": "<p>In all, it's not bad, especially for someone new to the language. Here are some things that may help you improve your code.</p>\n<h2>Know the difference betwee <code><cmath></code> and <code><math.h></code></h2>\n<p>The difference between the two forms is that the former defines things within the <code>std::</code> namespace versus into the global namespace. This means that in your <code>unary_func_tbl</code>, each of the functions should be prefixed with <code>std::</code>. Also, if we just write <code>std::sin</code> we don't need to further qualify it with <code>&</code> since we are referring to the function rather than actually calling it.</p>\n<h2>Simplify your regex string using a raw string</h2>\n<p>Regex expressions are complex enough without the added complexity of having to also escape backslash characters. We can use a <a href=\"https://en.cppreference.com/w/cpp/language/string_literal\" rel=\"noreferrer\">raw string</a> for this:</p>\n<pre><code>const std::regex words_regex(R"((sin|tan|acos|asin|abs|atan|cosh|sinh|cos|)"\n R"(tanh|acosh|asinh|atanh|exp|ldexp|log|log10|)"\n R"(sqrt|cbrt|tgamma|lgamma|ceil|floor|x|e)|^-|[0-9]?)"\n R"(([0-9]*[.])?[0-9]+|[\\\\-\\\\+\\\\\\\\\\(\\\\)\\\\/\\\\*\\\\^\\\\]")"};\n</code></pre>\n<h2>Fix your regex</h2>\n<p>When I made the change I suggested above, it was easier to spot that there was a spurious extra <code>'\\'</code> character before the penultimate <code>')'</code> character. There are still some issues that might be improved here. I'll come back to the keyword portion of the regex later, but wanted to take a closer look at the other clauses. First, we have <code>^-</code> which matches exactly a single <code>-</code> at the beginning of the string. I assume it's captured that way to take care of unary minus, but I believe the last clause captures that, so it could be removed. Moving on to the next clause, it is:</p>\n<pre><code>[0-9]?([0-9]*[.])?[0-9]+\n</code></pre>\n<p>This is not a very efficient or clear construction. What it seeks to capture is either integers with no decimal point or numbers with decimal point. It also requires at least one digit after the decimal point. The much more straightforward way to do that is like this:</p>\n<pre><code>([0-9]+[.])?[0-9]+\n</code></pre>\n<p>Finally, the last curious clause was originally this:</p>\n<pre><code>[\\\\-\\\\+\\\\\\\\\\(\\\\)\\\\/\\\\*\\\\^\\\\]\n</code></pre>\n<p>I don't think that does what you want. It's hard to tell by peering through that <a href=\"https://www.grymoire.com/Unix/Sed.html#uh-2\" rel=\"noreferrer\">"picket fence"</a> but I think what you intend looks more like this:</p>\n<pre><code>[-+\\()/*^]\n</code></pre>\n<p>Within <em>bracket expressions</em>, those other characters lose their special meaning, just in the way that <code>'[.]'</code> matches a period instead of <em>any-character</em>, which it would outside the <code>[]</code> context. Regular expressions are complex enough without adding extra characters!</p>\n<h2>Simplify your code</h2>\n<p>The code has a number of places in which somthing like this is done:</p>\n<pre><code>if (id == 0) return true;\nelse return false;\n</code></pre>\n<p>This is much more easily and simply written as <code>return id == 0;</code></p>\n<h2>Don't Repeat Yourself (DRY)</h2>\n<p>The code enumerates the function names at least three times. There is the <code>unary_func_tbl</code>, the <code>funcs</code> set and once in the regex. This leads to errors, such as the fact that "asin" appears twice within <code>funcs</code> and <code>trunc</code> is omitted from the regex. There are many ways to combine these, but since you're using C++20, I'll show you how to use a new feature from that version of the standard. The next few suggestions show how that might be done.</p>\n<h2>Use <code>contains</code></h2>\n<p>The current version of <code>is_func</code> is like this:</p>\n<pre><code>bool is_func(std::string_view str)\n{\n if (funcs.count(str) > 0) return true;\n else return false;\n}\n</code></pre>\n<p>As mentioned above, this can be simplified:</p>\n<pre><code>bool is_func(std::string_view str) {\n return funcs.count(str) > 0;\n}\n</code></pre>\n<p>But we don't actually need the separate <code>funcs</code> because we can simply use <code>unary_func_tbl</code>:</p>\n<pre><code>bool is_func(std::string_view str) {\n return unary_func_tbl.contains(str);\n}\n</code></pre>\n<p>Note that <code>contains</code> for a <code>std::unordered_set</code> was introduced in C++20, so your compiler may or not implement that. If it does, however, it means that you can simply omit <code>funcs</code> entirely. A similar thing can be done with <code>is_binary_op</code>.</p>\n<h2>Construct the regex</h2>\n<p>Since the function names are already in <code>func_names</code>, we can extract them into an appropriate regex using this:</p>\n<pre><code>static const std::string func_name_regex() {\n auto func_names{std::views::keys(unary_func_tbl)};\n std::ostringstream os;\n os << "(";\n for (const auto &name : std::views::keys(unary_func_tbl)) {\n os << name << "|";\n }\n os << R"(x|e)|)"\n << R"(([0-9]+[.])?[0-9]+|[-+\\()/*^])";\n return os.str();\n}\n</code></pre>\n<p>This uses the C++20 <a href=\"https://en.cppreference.com/w/cpp/ranges/keys_view\" rel=\"noreferrer\"><code>std::views::keys</code></a>. There may be an even more efficient way to construct the string as as <code>constexpr</code> function, but I didn't look into it very deeply. The nice part about this, however, is that we can use it like this:</p>\n<pre><code>static const std::regex words_regex(func_name_regex(),\n std::regex_constants::egrep);\n</code></pre>\n<h2>Use/omit parentheses to clarify</h2>\n<p>The code currently contains this rather complex construct:</p>\n<pre><code>while (!op_stack.empty() && \\\n (is_binary_op(op_stack.top()) && get_prec(op_stack.top()) > (get_prec(tok)) || \\\n (get_prec(op_stack.top()) == get_prec(tok) && is_left_assoc(tok))) && \\\n (op_stack.top() != "("))\n</code></pre>\n<p>First, the trailing backslashes are not required in C++ (except in the context of multiline macros, which you also should generally not be using in C++). Second, because <code>&&</code> has a higher precedence than <code>||</code> the way this expression is evaluated requires the reader of the code to remember this fact in order to correctly understand what it's doing. Adding parentheses around subexpressions won't affect the compiler but it will give the reader more confidence in both understanding the code and in realizing that the original programmer (you!) intended it to be that way. The extra parentheses around <code>get_prec(tok)</code> however, confuses things and elicits doubt and should be eliminated.</p>\n<h2>Provide complete code to reviewers</h2>\n<p>This is not so much a change to the code as a change in how you present it to other people. Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code. This affects not only code reviews, but also maintenance of the code in the future, by you or by others. One good way to address that is by the use of comments. Another good technique is to include test code showing how your code is intended to be used.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T01:31:15.570",
"Id": "259035",
"ParentId": "259019",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T17:11:45.900",
"Id": "259019",
"Score": "5",
"Tags": [
"c++",
"c++20"
],
"Title": "A C++ Program to Plot An Equation"
}
|
259019
|
<p>I have written a Common Lisp implementation of Scheme's s-expression comments (<a href="https://srfi.schemers.org/srfi-62/srfi-62.html" rel="nofollow noreferrer">SRFI 62</a>):</p>
<pre class="lang-lisp prettyprint-override"><code>(eval-when (:compile-toplevel
:load-toplevel
:execute)
(defun handle-s-expression-comment (stream char n)
(declare (ignore char))
(when n
(error "Infix parameter not allowed in s-expression comment."))
(read stream) ; Discard the next s-expression.
(values))
(set-dispatch-macro-character #\# #\; #'handle-s-expression-comment))
</code></pre>
<p>With s-expression comments:</p>
<ul>
<li><code>(+ 1 #;(* 2 3) 4)</code> returns <code>5</code></li>
<li><code>(list 'x #;'y 'z)</code> returns <code>(x z)</code></li>
<li><code>(* 3 4 #;(+ 5 6))</code> returns <code>12</code></li>
<li><code>(#;sqrt abs -123)</code> returns <code>123</code></li>
</ul>
<p>Is my implementation correct? What improvements can I make?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-17T03:55:44.837",
"Id": "530744",
"Score": "0",
"body": "`(read stream)` should be `(read stream t nil t)` instead. Refer to: [read's recursive-p argument when used inside a reader macro](https://stackoverflow.com/questions/69248229/reads-recursive-p-argument-when-used-inside-a-reader-macro)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T17:27:10.473",
"Id": "259020",
"Score": "2",
"Tags": [
"common-lisp"
],
"Title": "S-expression comments in Common Lisp"
}
|
259020
|
<p>How could i improve the following code. This part was easy to implement but there is a lot of redondancy and i use pandas to return as dict which seems quite odd.</p>
<pre><code>def pipeline_place_details(place_id, fields, lang):
"""Return a dataframe with useful information
Args:
place_id ([string]): Id retrieved from google api
fields ([type]): Field retrieved from json output
"""
fields = ['name', 'formatted_address', 'international_phone_number', 'website', 'rating', 'review']
lang = 'fr'
# details will give us a dict which is the result of serialized json returned from google api
details = get_place_details(place_id, fields, "fr")
try:
website = details['result']['website']
except KeyError:
website = ""
try:
address = details['result']['formatted_address']
except KeyError:
address = ""
try:
phone_number = details['result']['international_phone_number']
except KeyError:
phone_number = ""
try:
reviews = details['result']['reviews']
except KeyError:
reviews = []
rev_temp = []
for review in reviews:
author_name = review['author_name']
user_rating = review['rating']
text = review['text']
time = review['relative_time_description']
rev_temp.append((author_name, user_rating, text, time))
rev_temp_2 = pd.DataFrame(rev_temp, columns = ['author_name', 'rating', 'text', 'relative_time'])
rev_temp_2['place_id'] = i
rev_temp_2['address'] = address
rev_temp_2['phone_number'] = phone_number
rev_temp_2['website'] = website
review_desc = review_desc.append(rev_temp_2, ignore_index = True)
return review_desc.to_dict('records')
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p><strong>1. Getting data from dict</strong></p>\n<p>When <code>details</code> is a <code>dict</code>, then instead of writing:</p>\n<pre><code>try:\n address = details['result']['formatted_address']\nexcept KeyError:\n address = ""\n</code></pre>\n<p>you can do:</p>\n<pre><code>address = details.get('result', {}).get('formatted_address', '')\n</code></pre>\n<p>Second parameter of <code>.get</code> represents the default value which is returned when a dictionary doesn't contain a specific element</p>\n<p><strong>2. Modularization</strong></p>\n<p>Function <code>pipeline_place_details</code> is not short, so it might be a good idea to break it up into a smaller functions. Each time when you write a loop, it's worth to consider if moving body of the loop to a separate function will increase the code readability.</p>\n<p>For example that part:</p>\n<pre><code> author_name = review['author_name']\n user_rating = review['rating']\n text = review['text']\n time = review['relative_time_description']\n rev_temp.append((author_name, user_rating, text, time))\n</code></pre>\n<p>can be easiliy extracted to the new function:</p>\n<pre><code>def process_review(review):\n return (\n review['author_name'],\n review['rating'],\n review['text'],\n review['relative_time_description']\n )\n</code></pre>\n<p>and you can use it as below:</p>\n<pre><code>rev_temp = [process_review(review) for review in reviews]\n</code></pre>\n<p><strong>3. Variables naming</strong></p>\n<p>Good code should be not only working and efficient but it should be also easy to read and understand. So it's a good rule to use really meaningful variable names. I belive that you can find better names than for example <code>rev_temp</code> or <code>rev_temp2</code>. ;)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T18:48:48.137",
"Id": "259023",
"ParentId": "259021",
"Score": "1"
}
},
{
"body": "<p>I worked a bit on code and suggest that (i could encapsulate some parts as trivel suggest), what do you think ?</p>\n<p>I directly work with dictionaries and try to avoid redundance letting the try except jon in get_from_dict function. It looks better (but perhaps perform more slowly ...).</p>\n<pre><code>def get_from_dict(dic, keys):\n """Iterate nested dictionary"""\n return reduce(lambda d, k: d.get(k, ""), keys, dic)\n\ndef parse_place_details(place_id):\n fields = ['name', 'formatted_address', 'rating', 'review','geometry']\n details = get_place_details(place_id, fields, 'fr')\n core_keys = {'adress':('result','formatted_address'),\n 'name':('result','name'),\n 'longitude':('result','geometry','location','lng'),\n 'latitude':('result','geometry','location','lat')}\n review_keys = {'author_name':('author_name',),\n 'user_rating':('rating',),\n 'text':('text',),\n 'time':('relative_time_description',)}\n results =[]\n core = {'place_id':place_id}\n for k,path in core_keys.items():\n core[k] = get_from_dict(details,path)\n reviews = get_from_dict(details,('result','reviews')) \n for review in reviews:\n descr ={k:get_from_dict(review,rkey) for k,rkey in review_keys.items()}\n descr.update(core)\n results.append(descr) \n return results\n \n\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T17:42:59.293",
"Id": "259124",
"ParentId": "259021",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T18:19:23.890",
"Id": "259021",
"Score": "0",
"Tags": [
"python"
],
"Title": "Return target informations from nested api json output"
}
|
259021
|
<p>I'm trying to make a console application to sort and delete duplicate image files. I have a folder with about 20000 images which take up roughly 70GB of space.</p>
<p>I wrote the following script and it seems to work fine, but the issue is that my PC runs out of available RAM memory (it has 16GB) without reaching halfway through.</p>
<pre><code>static void Main(string[] args)
{
var uniqueData = new HashSet<string>();
int progress = 0;
int fileCount = Directory.GetFiles(imageFolderPath).Length;
foreach (var file in Directory.GetFiles(imageFolderPath))
{
string data, year, month;
using (var image = Image.FromFile(file))
{
using (var ms = new MemoryStream())
{
image.Save(ms, ImageFormat.Jpeg);
data = Convert.ToBase64String(ms.ToArray());
}
try //try to get image date
{
var date = Encoding.UTF8.GetString(image.GetPropertyItem(36867).Value).Split(':');
year = date[0];
month = date[1];
}
catch
{
year = "Unknown";
month = "Unknown";
}
}
if (!uniqueData.Contains(data))
{
uniqueData.Add(data);
string yearDirectory = Path.Combine(outputFolderPath, year);
if (!Directory.Exists(yearDirectory))
{
Directory.CreateDirectory(yearDirectory);
}
string monthDirectory = Path.Combine(yearDirectory, (int.TryParse(month, out int i) && i > 0 && i < 14) ? CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(i) : month);
if (!Directory.Exists(monthDirectory))
{
Directory.CreateDirectory(monthDirectory);
}
File.Move(file, Path.Combine(monthDirectory, Path.GetFileName(file)));
}
else
{
File.Delete(file);
}
progress++;
Console.WriteLine($"{progress} / {fileCount}");
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T18:45:04.180",
"Id": "510776",
"Score": "0",
"body": "What is this code doing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T18:46:56.597",
"Id": "510777",
"Score": "0",
"body": "Welcome to Code Review! I [changed the title](https://codereview.stackexchange.com/revisions/259022/2) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T18:49:29.823",
"Id": "510779",
"Score": "1",
"body": "@aepot it extracts the bytes of each image file in the designated folder, and converts them to a string. Then it checks if the string is already present in a hashset, and if it is, it deletes said file, otherwise, it tries to create a folder based on the file's date and moves it there."
}
] |
[
{
"body": "<p>You don't need to store the whole file contents, compute hash instead. Also converting each image to JPEG is not necessary, use <code>image.RawFormat</code>, it would be a bit faster.</p>\n<pre><code>using (SHA256 sha = SHA256.Create())\nusing (var ms = new MemoryStream((int)new FileInfo(file).Length))\n{\n image.Save(ms, image.RawFormat);\n ms.Position = 0;\n data = Convert.ToBase64String(sha.ComputeHash(ms));\n}\n</code></pre>\n<p>2nd option</p>\n<pre class=\"lang-cs prettyprint-override\"><code>if (!uniqueData.Contains(data))\n{\n uniqueData.Add(data);\n // ...\n}\n</code></pre>\n<p>Can be simplified to</p>\n<pre class=\"lang-cs prettyprint-override\"><code>if (uniqueData.Add(data))\n{\n // ...\n}\n</code></pre>\n<p>Also twice getting the directoriry files can be once</p>\n<pre class=\"lang-cs prettyprint-override\"><code>string[] files = Directory.GetFiles(imageFolderPath);\nint fileCount = files.Length;\n\nforeach (var file in files)\n{\n // ...\n}\n</code></pre>\n<p>And finally this one</p>\n<pre class=\"lang-cs prettyprint-override\"><code>if (!Directory.Exists(yearDirectory))\n{\n Directory.CreateDirectory(yearDirectory);\n}\n</code></pre>\n<p><code>Directory.CreateDirectory</code> creates directory if it not exists, otherwise it does nothing. You can remove <code>Exists</code> check.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>Directory.CreateDirectory(yearDirectory);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T19:26:54.173",
"Id": "510785",
"Score": "1",
"body": "Excellent, so far it has not exceeded 200MB of memory (it's still going but it looks very promising), I will try to benchmark the impact of each of your suggested changes and append it to my question as edit. Cheers!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T19:49:53.307",
"Id": "510788",
"Score": "0",
"body": "@oRoiDev you're welcome. Btw, don't edit the question. Some users here suggests to post the final code as additional answer if you want but it isn't necessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T20:17:55.653",
"Id": "510792",
"Score": "0",
"body": "@oRoiDev one more improvement and fixed a bug, updated the answer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T18:55:56.930",
"Id": "259024",
"ParentId": "259022",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "259024",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T18:35:51.173",
"Id": "259022",
"Score": "1",
"Tags": [
"c#",
"time-limit-exceeded",
"image"
],
"Title": "Sort and Delete duplicate image files"
}
|
259022
|
<p>I have a table <code>data</code> stored in a database <code>ships.db</code>,
the data are informations of tracked ships hourly.
The table data looks like this.</p>
<pre><code>time | shipId | longitude | latitude
---------------------------------------------------------------------
00:00:00 1 xx.xxxx yy.yyyy
00:00:00 2 xx.xxxx yy.yyyy
00:00:00 3 xx.xxxx yy.yyyy
00:00:00 4 xx.xxxx yy.yyyy
01:00:00 2 xx.xxxx yy.yyyy
01:00:00 4 xx.xxxx yy.yyyy
... ... ... ...
23:00:00 4 xx.xxxx yy.yyyy
</code></pre>
<p>Splitting the whole earth to a grid of <strong>5</strong>-degree width and length for each cell,
I would get the number of fetched records hourly per cell of that grid.</p>
<p><em>Note that the number of records are not the same each hour because some ships are not more live therefore not fetched.</em></p>
<p>I wrote this code in python, it works but it takes large time because the database has roughly <code>250000</code> records.
Is there another method or approach to make it better and faster in python?</p>
<p>My script:</p>
<pre><code>import sqlite3
def writeToFile(string, file):
with open(file,"a") as ouf:
ouf.write(string+"\n")
output = "report.txt"
with sqlite3.connect("ships.db") as con:
cur = con.cursor()
#iterate over times from 0 to 23 (hours)
for hour in range(0,24): # hours: from 0 to 23
#make each loop of time in this time format "hh:00:00"
time = str(hour).zfill(2)+":00:00"
#scan from longitude -180 (180 W) to +180 (180 E) each 5 degree of longitude
for longitude in range(-180,180,5):
#scan from latitude -90 (90 S) to +90 (90 N) each 5 degree of latitude
for latitude in range(-90,90,5):
sql = f'''SELECT time, count(*) AS occurence FROM 'data'
WHERE time ="{time}"
AND latitude BETWEEN {latitude} AND {latitude+5}
AND longitude BETWEEN {longitude} AND {longitude+5}
GROUP BY time'''
data = cur.execute(sql).fetchone() #fetchone because group by time
if data != None:
time, occurence = data
else: #some cell of grid may have no ship at a hour therefore this else
occurence = None
result = [time, occurence, longitude, latitude]
#writing the result to output
writeToFile("\t".join(result), output)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T22:30:20.293",
"Id": "510794",
"Score": "1",
"body": "What is your table structure ? Do you have indexes ? Your three nested loops produce a total of 62209 DB calls. I am thinking that *maybe* a more sophisticated SELECT could retrieve the information you want, or at least half-baked results that would make the job easier."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T22:37:03.747",
"Id": "510795",
"Score": "0",
"body": "No indexes and that is the structure: CREATE TABLE IF NOT EXISTS 'data' (time TEXT, shipId INTEGER, longitude REAL, latitude REAL);"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T00:00:16.647",
"Id": "510799",
"Score": "1",
"body": "Well then, without any indexes, that means your script does a *full table scan* to retrieve results, and it does that at every iteration. So yes it's going to be slow. Seems to me that you could add latitude + longitude in your GROUP BY, thus get rid of two loops and simplify things."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T10:43:25.453",
"Id": "510821",
"Score": "0",
"body": "@Anonymous , I think, I got it, I will take the floor of latitude and longitude then divide by 5, multiply by 5 to get the range start of the cell in which lies each ship then group by longitude and latitude and time. It worked perfectly and so much better than before. But I would test it for edges and exceptional cases before taking it as generalization."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T14:47:35.160",
"Id": "528442",
"Score": "0",
"body": "It's difficult to say how the database query could be improved without seeing the definition for that table."
}
] |
[
{
"body": "<p>There are multiple things that I would like to point out to you, just to help you improve coding style. Currently you are not noticing as performance issues as they are hidden due to you DB performance.</p>\n<ol>\n<li><p>Fixed values: You are computing fixed list every time through 'range'. Try to store them in list. As this is unnecessary compute overhead.</p>\n</li>\n<li><p>File writing: You are opening and closing file per record. This can cause huge disk performance issues once you start noticing. Try to collect record in list and maybe write to file once every 'hour'.</p>\n</li>\n<li><p>Always try to add 'Indexes' on DB. They are made for purpose of speeding up searching.</p>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-17T06:50:57.200",
"Id": "259654",
"ParentId": "259025",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T19:45:19.063",
"Id": "259025",
"Score": "1",
"Tags": [
"python",
"performance",
"sqlite"
],
"Title": "Speed performance of sqlite3 queries looped in python"
}
|
259025
|
<p>This is an experiment to see what's involved in adding new functional
capability to the Common Lisp baseline. In this case, it's adding a
sequence function to select elements from a sequence satisfying a
predicate. I don't regard such baseline functions as simple utilities,
because they seem more foundational, better optimized, and better at
handling all corner cases.</p>
<p>The function <code>select-if</code> below is patterned after the standard -if
sequence functions--namely, remove-if, delete-if, substitute-if, find-if,
position-if, count-if (and their -if-not counterparts). If there's a way
to combine these functions to easily select items from an arbitrary
sequence without inventing a new function, I don't see it (although
<code>loop</code> does cover some cases). But in any event <code>select-if</code> seems like
a good test case.</p>
<pre><code>(defun select-if (predicate sequence &key from-end (start 0) end
count (key #'identity))
"Return elements from a sequence satisfying a predicate."
(let* ((tally 0)
(max-tally (or count most-positive-fixnum))
(subsequence (if from-end
(nreverse (subseq sequence start end))
(subseq sequence start end)))
(marker (gensym))
(items (delete marker
(map 'list
(lambda (elem)
(cond ((and (< tally max-tally)
(funcall predicate (funcall key elem)))
(incf tally)
elem)
(t marker)))
subsequence))))
(declare (fixnum tally max-tally))
(etypecase sequence
(list items)
(bit-vector (coerce items 'bit-vector))
(string (format nil "~{~A~}" items))
(vector (coerce items 'vector)))))
</code></pre>
<p>I'm particularly interested in whether there are better ways to do sequence selection, better optimization, and corner cases. Thanks for your time.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T07:11:25.283",
"Id": "511731",
"Score": "0",
"body": "“If there's a way to combine these functions to easily select items from an arbitrary sequence...” it seems to me that your function has the same semantics as [`remove-if-not`](http://www.lispworks.com/documentation/HyperSpec/Body/f_rm_rm.htm). So a good starting point could be looking at the definition of such a function in your Common Lisp environment of choice (in emacs-slime, after the name of the function press Meta-.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-14T20:42:26.703",
"Id": "511962",
"Score": "0",
"body": "To me the semantics seem subtly different. For example, `(select-if #'evenp '(0 1 2 3 4 5) :count 2) => (0 2)`. How would you write the equivalent `remove-if-not`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-15T07:46:29.367",
"Id": "511999",
"Score": "0",
"body": "Ops, you are right, when there is a `:count` parameter the results are different."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-15T10:16:54.010",
"Id": "512002",
"Score": "1",
"body": "Note that at the end if `from-end` is true then the result must be reversed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-15T15:21:53.510",
"Id": "512034",
"Score": "0",
"body": "@Renzo Yes, you're right. Thanks. My (select-if #'evenp '(0 1 2 3 4 5) :count 2 :from-end t) => (4 2), when the result should be (2 4), to follow the hyperspec for `remove-if-not`."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T20:56:23.297",
"Id": "259027",
"Score": "0",
"Tags": [
"performance",
"common-lisp"
],
"Title": "Constructing Functions Patterned After Common Lisp Built-in Functions"
}
|
259027
|
<p>I am processing an unknown "length" of generator object.
I have to keep things "lazy" because of memory management.
The processing is compute heavy, so writing it multiproc style is the solution (or at least it seems for me).</p>
<p>I have solved this problem of multiproc on generator object with a combination of monkey patch and a bounded Queue.</p>
<p>What really itches me is the monkey patch...
Do you think this is fine to apply <code>imap()</code> on a generator object? How would you do this?</p>
<p>I would like to underline that the focus is to <strong>compute the outputs of a generator in parallel.</strong>
From the perspective of this "minimal example" :</p>
<pre><code>process_line, process_line_init, process_first_n_line
</code></pre>
<p>are the functions I am most interested about your opinion.</p>
<pre><code>import multiprocessing as mp
import psutil
import queue
from typing import Any, Dict, Iterable, Set
def yield_n_line(n: int)-> Iterable[Dict[str, str]]:
for i in range(n):
yield {'body': "Never try to 'put' without a timeout sec declared"}
def get_unique_words(x: Dict[str, str])-> Set[str]:
return set(x['body'].split())
def process_line(x:Dict[str, str])-> Set[str]:
try:
process_line.q.put(x, block=True, timeout=2)
except queue.Full:
pass
return get_unique_words(x)
def process_line_init(q: mp.Queue)-> None:
process_line.q = q
def process_first_n_line(number_of_lines: int)-> Any:
n_line = yield_n_line(number_of_lines)
if psutil.cpu_count(logical=False) > 4:
cpu_count = psutil.cpu_count(logical=False)-2
else:
cpu_count = psutil.cpu_count(logical=False)
q = mp.Queue(maxsize=8000)
p = mp.Pool(cpu_count, process_line_init, [q])
results = p.imap(process_line, n_line)
for _ in range(number_of_lines):
try:
q.get(timeout=2)
except queue.Empty:
q.close()
q.join_thread()
yield results.next()
p.close()
p.terminate()
p.join()
pass
def yield_uniqueword_chunks(
n_line: int = 10_000_000,
chunksize: int = 1_787_000)-> Iterable[Set[str]]:
chunk = set()
for result in process_first_n_line(n_line):
chunk.update(result)
if len(chunk) > chunksize:
yield chunk
chunk = set()
yield chunk
def main()-> None:
for chunk in yield_uniqueword_chunks(
n_line=1000, #Number of total comments to process
chunksize=200 #number of unique words in a chunk (around 32MB)
):
print(chunk)
#export(chunk)
if __name__ == "__main__":
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T01:41:31.093",
"Id": "510803",
"Score": "0",
"body": "The idea behind `multiprocessing.Pool` is that it handles queuing work for the processes. If you want more control, then use Process and Queue."
}
] |
[
{
"body": "<p>Here's a condensed illustration of how to achieve your stated purpose, namely\nto <strong>compute the outputs of a generator in parallel</strong>. I offer it because\nI could not understand the purpose of most of the complexity in your current\ncode. I suspect there are issues that you have not explained to us or that I\nfailed to infer (if so, this answer might be off the mark). In any case,\nsometimes it helps to look at a problem in a simplified form to see\nwhether your actual use case might work just fine within those parameters.</p>\n<pre><code>import multiprocessing as mp\n\ndef main():\n for chunk in process_data(1000, 50):\n print()\n print(len(chunk), chunk)\n \ndef process_data(n, chunksize):\n # Set up the Pool using a context manager.\n # This relieves you of the hassle of join/close.\n with mp.Pool() as p:\n s = set()\n # Just iterate over the results as they come in.\n # No need to check for empty queues, etc.\n for res in p.imap(worker, source_gen(n)):\n s.update(res)\n if len(s) >= chunksize:\n yield s\n s = set()\n\ndef source_gen(n):\n # A data source that will yield N values.\n # To get the data in this example:\n # curl 'https://www.gutenberg.org/files/2600/2600-0.txt' -o war-peace.txt\n with open('war-peace.txt') as fh:\n for i, line in enumerate(fh):\n yield line\n if i >= n:\n break\n\ndef worker(line):\n # A single-argument worker function.\n # If you need multiple args, bundle them in tuple/dict/etc.\n return [word.lower() for word in line.split()]\n\nif __name__ == "__main__":\n main()\n</code></pre>\n<p>This example illustrates a garden-variety type of parallelization:</p>\n<ul>\n<li><p>The data source is running in a single process (the parent).</p>\n</li>\n<li><p>Downstream computation is\nrunning in multiple child processes.</p>\n</li>\n<li><p>And final aggregation/reporting\nis running in a single process (also the parent).</p>\n</li>\n</ul>\n<p>Behind the scenes, <code>Pool.imap()</code> is\nusing pickling and queues to shuttle data between processes. If your real\nuse case requires parallelizing data generation and/or reporting,\na different approach is needed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T01:00:13.987",
"Id": "510802",
"Score": "1",
"body": "Thank you, for the fast response, I have checked out your example, and on its own it is working and deserves an up. In a day, I will be able to check / implement it on my specific use case and see, where have I overcomplicated this problem. 'for res in p.imap(worker, source_gen(n))' pattern somehow always errored out for me that is why I went with my solution. Thank you, and will come back bit later!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T11:09:22.500",
"Id": "510823",
"Score": "0",
"body": "Works like a charm, \nEarlier I have used the 'With' pattern for pool, hut just for list.\nI have over-complicated this task."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T00:01:22.887",
"Id": "259034",
"ParentId": "259029",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "259034",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T21:18:35.857",
"Id": "259029",
"Score": "6",
"Tags": [
"python",
"queue",
"generator",
"multiprocessing"
],
"Title": "Compute the outputs of a generator in parallel"
}
|
259029
|
<p>I'm trying to get a list of unique colors (rgba values) in an image. Here are my attempts:</p>
<pre><code># 1 - too ugly and clunky
all_colors = []
for i in range(width):
for j in range(height):
color = pix[i, j]
if color not in all_colors:
all_colors.append(color)
</code></pre>
<p>OR</p>
<pre><code># 2 - not memory-efficient, as it adds the whole list into memory
all_colors = list(set([pix[i, j] for i in range(width) for j in range(height)]))
</code></pre>
<p>Edit: here is the setup:</p>
<pre><code>from PIL import Image
img = Image.open("../Camouflage.png")
pix = img.load()
</code></pre>
<p>Thank you very much.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T02:51:45.983",
"Id": "510806",
"Score": "1",
"body": "`as it adds the whole list into memory` both options do that. Or you mean something else?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T09:18:38.183",
"Id": "510817",
"Score": "0",
"body": "@Marc Looks like they mean \"the whole list of all pixels\", not just the list of *different* colors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T09:23:48.137",
"Id": "510819",
"Score": "0",
"body": "Quite possibly there's a way without looping yourself, but we can't tell because you're keeping it secret what `pix` is and not giving us a chance to test."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T17:19:38.123",
"Id": "510845",
"Score": "0",
"body": "@Manuel, just updated to show what `pix` is. Thank you for your help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T20:07:48.647",
"Id": "510856",
"Score": "0",
"body": "Are any of the downvoters going to bother explaining what's wrong with my question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T20:27:45.533",
"Id": "510857",
"Score": "2",
"body": "The downvotes from before your latest edits were probably because the code was incomplete, lacking context. On Code Review, we require more than just snippets. Feel free to refer to [Simon's guide on asking questions](https://codereview.meta.stackexchange.com/a/6429/52915)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T21:17:08.440",
"Id": "510862",
"Score": "0",
"body": "Why do you want the code to be more memory efficient?"
}
] |
[
{
"body": "<p>It isn't necessary to pass a <code>list</code> to <code>set()</code>. Use a generator expression:</p>\n<pre><code>all_colors = set(pix[i,j] for i in range(width) for j in range(height))\n</code></pre>\n<p>or, use a set comprehension:</p>\n<pre><code>all_colors = {pix[i,j] for i in range(width) for j in range(height)}\n</code></pre>\n<p>I timed them by building sets of 1_000_000 items. On average, the set comprehension was a < 10ms faster and they were within 1 std dev of each other.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T09:21:04.593",
"Id": "510818",
"Score": "0",
"body": "They already do. The thing you're doing which they're not is the *generator*. Btw less efficient than using a set comprehension."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T17:32:21.197",
"Id": "510848",
"Score": "1",
"body": "@Manuel, how so? Generators are far more memory efficient that comprehensions since they are lazy iterators. There's no real difference in terms of computational complexity, it is exactly the same."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T20:33:23.557",
"Id": "510858",
"Score": "0",
"body": "@pavel No, feeding the generator to `set` completely eliminates that memory efficiency. The complexity class is the same, yes, but all the back-and-forth between generator and `set` does make it slower."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T21:27:32.643",
"Id": "510864",
"Score": "0",
"body": "thank you so much, this is exactly what I was looking for."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T07:58:09.170",
"Id": "510872",
"Score": "0",
"body": "@pavel [small benchmark](https://tio.run/##TY7BCsIwEETv@Yq5lCRSpLUXEXrsF/QoIhW2GjBpSFeoiN9eEwPiHBb2zbA7/sm3yTV7H9Z1DJMFG0uGYayfAiOQp4GF6NFCDnHczcwqDO5Kqq6qSmtsUFdSdNE7CkTJmVgtGKeABcZh0LLMxuufviM9CZHAOYF8s9GHbzZhSrjLexLHF9Y4lTspKtGXcA97odDmLr@oD8axksV2N0oU4BKUzWzodf0A)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T01:45:36.120",
"Id": "259037",
"ParentId": "259036",
"Score": "2"
}
},
{
"body": "<p>How about simply this?</p>\n<pre><code>all_colors = set(img.getdata())\n</code></pre>\n<p>Or let Pillow do the hard work:</p>\n<pre><code>all_colors = [color for _, color in img.getcolors()]\n</code></pre>\n<p>Benchmark results along with the set comprehension solution on a test image of mine (since you didn't provide any):</p>\n<pre><code>113 ms set_comp\n 68 ms set_getdata\n 1 ms getcolors\n\n115 ms set_comp\n 65 ms set_getdata\n 1 ms getcolors\n\n106 ms set_comp\n 62 ms set_getdata\n 1 ms getcolors\n</code></pre>\n<p>With <a href=\"https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.getdata\" rel=\"nofollow noreferrer\"><code>img.getdata()</code></a> you get a "sequence-like object" that seems light-weight:</p>\n<pre><code>>>> img.getdata()\n<ImagingCore object at 0x7f0ebd0f1e50>\n\n>>> import sys\n>>> sys.getsizeof(img.getdata())\n32\n</code></pre>\n<p>Benchmark code:</p>\n<pre><code>from timeit import repeat\nfrom PIL import Image\n\ndef set_comp(img):\n pix = img.load()\n width, height = img.size\n return {pix[i,j] for i in range(width) for j in range(height)}\n\ndef set_getdata(img):\n return set(img.getdata())\n\ndef getcolors(img):\n return [color for _, color in img.getcolors()]\n\nfuncs = set_comp, set_getdata, getcolors\n\ndef main():\n img = Image.open("test.png")\n for _ in range(3):\n for func in funcs:\n t = min(repeat(lambda: func(img), number=1))\n print('%3d ms ' % (t * 1e3), func.__name__)\n print()\n\nmain()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T19:32:57.193",
"Id": "510914",
"Score": "0",
"body": "hmmm I think part of its speed comes from the fact that you don't need to `img.load()` the whole image. but, I'll need to do that eventually to iterate over the pixels and change them if they're not black."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T19:55:32.733",
"Id": "510916",
"Score": "0",
"body": "@tommy2111111111 Have a look at `getdata`'s source code (it's linked to in the documentation), the first thing it does is `self.load()`. Also, see my update, new solution using `getcolors`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T21:30:32.000",
"Id": "510918",
"Score": "0",
"body": "thank you, `getcolors` works great. would it still be the best/fastest solution if I still needed to iterate over all the pixels anyways like this? https://pastebin.com/UnAR6kzv"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T21:40:49.203",
"Id": "510919",
"Score": "0",
"body": "@tommy2111111111 I don't see what getting the colors has to do with that. Anyway, for efficient manipulation there might be other Pillow methods or you could use NumPy on the image data."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T08:29:19.970",
"Id": "259071",
"ParentId": "259036",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "259071",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T01:33:43.487",
"Id": "259036",
"Score": "-3",
"Tags": [
"python"
],
"Title": "memory-efficient & clean set() in python"
}
|
259036
|
<p>Intended as a small project to test out various C++20 features, as well as learn a little bit more about matrices and their uses, I decided to implement a relatively simple matrix class.</p>
<p>After implementing it, I figured out that every single part of it should be able to be done in a compile time context, and re-implemented it (and cleaned it up a little). I'll provide the whole code here, and then highlight some parts where I'm unsure of whether there's a better way. There's a very barebones vector class alongside it for use with the matrix multiplication operator.</p>
<pre><code>#include <array>
#include <stdexcept>
#include <functional>
namespace ctm
{
typedef std::size_t index_t;
typedef long double real;
template <index_t N>
requires (N > 0)
struct vector
{
std::array<real, N> values;
constexpr vector(const std::array<real, N>& vals)
{
for (index_t i = 0; i < N; ++i)
{
values[i] = vals[i];
}
};
constexpr real dot(const vector<N>& other) const
{
real sum = 0.L;
for (index_t i = 0; i < N; ++i)
{
sum += values[i] * other.values[i];
}
return sum;
};
};
template <index_t M, index_t N>
requires (M > 0 && N > 0)
struct matrix
{
std::array<std::array<real, N>, M> elements = {};
constexpr matrix() = default;
constexpr matrix(const std::array<real, M* N>& elems)
{
for (index_t i = 0; i < M; ++i)
{
for (index_t j = 0; j < N; ++j)
{
elements[i][j] = elems[i * N + j];
}
}
};
constexpr matrix(const std::function<real(index_t, index_t)>& func)
{
for (index_t i = 1; i <= M; ++i)
{
for (index_t j = 1; j <= N; ++j)
{
elements[i - 1][j - 1] = func(i, j);
}
}
};
// accessor functions
// 0-based indexing
constexpr std::array<real, N>& operator [](index_t index)
{
return elements[index];
};
// 0-based indexing
constexpr const std::array<real, N>& operator [](index_t index) const
{
return elements[index];
};
// 1-based indexing
constexpr real& operator ()(index_t index_m, index_t index_n)
{
if (index_m == 0 || index_n == 0)
{
throw std::out_of_range("compound access is 1-indexed");
}
else if (index_m > M || index_n > N)
{
throw std::out_of_range("compound access out of range");
}
return elements[index_m - 1][index_n - 1];
};
// 1-based indexing
constexpr const real& operator ()(index_t index_m, index_t index_n) const
{
if (index_m == 0 || index_n == 0)
{
throw std::out_of_range("compound access is 1-indexed");
}
else if (index_m > M || index_n > N)
{
throw std::out_of_range("compound access out of range");
}
return elements[index_m - 1][index_n - 1];
};
// 1-based indexing
constexpr vector<N> row(index_t index) const
{
if (index == 0)
{
throw std::out_of_range{ "row access is 1-indexed " };
}
else if (index > M)
{
throw std::out_of_range("row access out of range");
}
return vector<N>{ elements[index - 1] };
};
// 1-based indexing
constexpr vector<M> column(index_t index) const
{
if (index == 0)
{
throw std::out_of_range{ "column access is 1-indexed " };
}
else if (index > N)
{
throw std::out_of_range("column access out of range");
}
std::array<real, M> column = {};
for (index_t j = 0; j < M; ++j)
{
column[j] = elements[j][index - 1];
}
return vector<M>{ column };
};
constexpr matrix<N, M> transpose() const
{
matrix<N, M> result = {};
for (index_t j = 0; j < N; ++j)
{
for (index_t i = 0; i < M; ++i)
{
result.elements[j][i] = elements[i][j];
}
}
return result;
};
consteval std::pair<index_t, index_t> size() const
{
return { M, N };
};
// arithmetic operators
constexpr matrix& operator +=(const matrix& other)
{
for (index_t i = 0; i < M; ++i)
{
for (index_t j = 0; j < N; ++j)
{
elements[i][j] += other.elements[i][j];
}
}
return *this;
};
constexpr matrix& operator -=(const matrix& other)
{
for (index_t i = 0; i < M; ++i)
{
for (index_t j = 0; j < N; ++j)
{
elements[i][j] -= other.elements[i][j];
}
}
return *this;
};
constexpr matrix& operator *=(real scalar)
{
for (index_t i = 0; i < M; ++i)
{
for (index_t j = 0; j < N; ++j)
{
elements[i][j] *= scalar;
}
}
return *this;
};
constexpr matrix& operator /=(real scalar)
{
for (index_t i = 0; i < M; ++i)
{
for (index_t j = 0; j < N; ++j)
{
elements[i][j] /= scalar;
}
}
return *this;
};
constexpr friend matrix operator +(matrix left, const matrix& right)
{
return left += right;
};
constexpr friend matrix operator -(matrix left, const matrix& right)
{
return left -= right;
};
constexpr friend matrix operator *(matrix mat, real scalar)
{
return mat *= scalar;
};
constexpr friend matrix operator *(real scalar, matrix mat)
{
return mat *= scalar;
};
constexpr friend matrix operator /(matrix mat, real scalar)
{
return mat /= scalar;
};
template <index_t P>
constexpr friend matrix<M, P> operator *(const matrix<M, N>& left, const matrix<N, P>& right)
{
matrix<M, P> result;
for (index_t i = 1; i <= M; ++i)
{
for (index_t j = 1; j <= P; ++j)
{
vector<N> left_row = left.row(i);
vector<N> right_column = right.column(j);
result(i, j) = left_row.dot(right_column);
}
}
return result;
};
// comparison operator
constexpr friend bool operator ==(const matrix&, const matrix&) = default;
// the following functions are only valid for square matrices (M == N)
// 1-based indexing
template <index_t m = M, index_t n = N>
requires (m == n && m > 1)
constexpr matrix<m - 1, n - 1> first_minor(index_t i, index_t j) const
{
if (i == 0 || j == 0)
{
throw std::out_of_range("minor row and column indices are 1-indexed");
}
else if (i > M || j > N)
{
throw std::out_of_range("minor row and column indices out of range");
}
matrix<m - 1, n - 1> minor = {};
index_t k = 0;
index_t l = 0;
for (index_t p = 0; p < m; ++p)
{
// skip over the row specified by i
if (p == i - 1)
{
continue;
}
for (index_t q = 0; q < n; ++q)
{
// skip over the column specified by j
if (q == j - 1)
{
continue;
}
minor.elements[k][l] = elements[p][q];
++l;
}
++k;
l = 0;
}
return minor;
};
constexpr real trace() const requires(M == N)
{
real sum = 0.L;
for (index_t i = 0, j = 0; i < M; ++i, ++j)
{
sum += elements[i][j];
}
return sum;
};
constexpr real determinant() const requires(M == N && M == 2)
{
return elements[0][0] * elements[1][1] - elements[0][1] * elements[1][0];
};
constexpr real determinant() const requires(M == N && M > 2)
{
real sum = 0.L;
real parity = 1.L;
for (index_t j = 0; j < N; ++j)
{
auto submatrix = first_minor(1, j + 1);
sum += elements[0][j] * parity * submatrix.determinant();
parity = -parity;
}
return sum;
};
constexpr bool symmetric() const requires(M == N)
{
return *this == transpose();
};
constexpr bool skew_symmetric() const requires(M == N)
{
return *this == (transpose() *= -1.L);
};
// static square matrix creators
static constexpr matrix<M, N> identity() requires(M == N)
{
matrix<M, N> id = {};
for (index_t i = 0, j = 0; i < M; ++i, ++j)
{
id.elements[i][j] = 1.L;
}
return id;
};
static constexpr matrix<M, N> diagonal(const std::array<real, M>& elems) requires(M == N)
{
matrix<M, N> diag = {};
for (index_t i = 0, j = 0; i < M; ++i, ++j)
{
diag.elements[i][j] = elems[i];
}
return diag;
};
};
};
</code></pre>
<p>One area that has caused trouble in both of my implementations is the constructor that takes a std::function object. Matrices can have their elements defined by the result of a function that takes the indices of the element as an input, and I wanted to replicate that. Is this the most effective way? I had to make it explicit because a <code>matrix<M, N></code> is able to be converted into a <code>std::function<real(index_t, index_t)></code>, since it defines <code>real operator ()(index_t, index_t)</code> for doing 1-indexed matrix access.</p>
<p>Also, is there any way to potentially clean up the <code>first_minor</code>'s declaration? I dislike what I have to do to make that one work, but if I try to follow the same pattern as the other functions with a <code>requires</code> expression, it complains.</p>
<p>General advice would also be appreciated, thanks!</p>
|
[] |
[
{
"body": "<p>Stylistically, I'd prefer to see <code>requires</code>-clauses (like <code>noexcept</code>-clauses and trailing return types) indented. That is, where you have</p>\n<pre><code>template <class T>\nrequires foo<T>\nauto foo()\nnoexcept(bar)\n-> baz\n</code></pre>\n<p>I'd prefer to see</p>\n<pre><code>template<class T>\n requires foo<T>\nauto foo()\n noexcept(bar)\n -> baz\n</code></pre>\n<p>just to highlight the important parts better.</p>\n<hr />\n<p>You use <code>size_t</code> for your index type, which means you have to special-case <code>0</code> in a lot of places. Prefer signed types when dealing with "integers"; unsigned types are better reserved for bitmask manipulations. See <a href=\"https://quuxplusone.github.io/blog/2018/03/13/unsigned-for-value-range/\" rel=\"nofollow noreferrer\">"The '<code>unsigned</code> for value range' antipattern"</a> (2018-03-13). Where you have</p>\n<pre><code>typedef std::size_t index_t;\n[...]\n constexpr real& operator ()(index_t index_m, index_t index_n)\n {\n if (index_m == 0 || index_n == 0)\n {\n throw std::out_of_range("compound access is 1-indexed");\n }\n else if (index_m > M || index_n > N)\n {\n throw std::out_of_range("compound access out of range");\n }\n</code></pre>\n<p>I'd rather see</p>\n<pre><code>using index_t = int; // actually you don't even need this typedef for anything\n[...]\n constexpr real& operator()(int m, int n)\n {\n if (!(1 <= m && m <= M) || !(1 <= n && n <= N)) {\n throw std::out_of_range("compound access out of range");\n }\n</code></pre>\n<p>If the user writes <code>mymatrix(-1, -1)</code>, you don't want your code silently converting that into <code>mymatrix(ULONG_MAX, ULONG_MAX)</code> — that's just confusing!</p>\n<p>Also, notice my stylistic cleanups: cuddled braces to save vertical real estate; idiomatic range-comparisons (and btw if you thought we could maybe use C++20 <code>std::in_range</code> here, you'd be wrong, it doesn't do what you'd think it does). And writing the names of operators as a single word without whitespace: <code>operator()</code> is the name of this function, just as much as <code>column</code> is the name of the function below it.</p>\n<hr />\n<pre><code> constexpr friend matrix operator +(matrix left, const matrix& right)\n {\n return left += right;\n };\n</code></pre>\n<p>The trailing semicolon is unnecessary.\nIt doesn't <em>really</em> matter because your <code>matrix</code> is trivially copyable and can't benefit from move semantics anyway; but notice that what you're asking for here is</p>\n<ul>\n<li>Make an object named <code>left</code></li>\n<li>Add <code>right</code> into <code>left</code>, yielding a <code>matrix&</code> (that happens to refer to <code>left</code>)</li>\n<li>Copy the matrix referred to by that <code>matrix&</code> into the return slot</li>\n</ul>\n<p>In typical move-friendly code (like, if your <code>matrix</code> were a <code>std::string</code> or <code>std::vector</code>), you'd be much better off saying</p>\n<ul>\n<li>Make an object named <code>left</code></li>\n<li>Add <code>right</code> into <code>left</code></li>\n<li>Move (or move-elide) <code>left</code> itself into the return slot</li>\n</ul>\n<p>which would be spelled</p>\n<pre><code> friend constexpr matrix operator+(matrix a, const matrix& b)\n {\n a += b;\n return a; // implicit move happens here\n }\n</code></pre>\n<p>Notice also the "adjective order": just as in English we can have a "lovely little old French whittling knife," in C++ we can have a</p>\n<pre><code>friend static inline constexpr virtual explicit operator T()\n</code></pre>\n<p>(<code>friend</code> precedes an otherwise ordinary declaration and is thus the "easiest to strip off"; <code>static</code> and <code>inline</code> are storage specifiers; <code>constexpr</code> doesn't yet affect how the type system sees the entity; <code>virtual</code> affects it; and <code>explicit</code> is basically the keyword that says "look out, here comes a constructor or conversion operator," going syntactically in place of a normal function's return type.)</p>\n<p>EDIT: This is now a blog post. See <a href=\"https://quuxplusone.github.io/blog/2021/04/03/static-constexpr-whittling-knife/\" rel=\"nofollow noreferrer\">"<code>static constexpr unsigned long</code> is C++'s 'lovely little old French whittling knife'"</a> (2021-04-03).</p>\n<hr />\n<pre><code>constexpr matrix(const std::array<real, M* N>& elems)\n ^\n</code></pre>\n<p>That's a very unfortunate stray space!</p>\n<hr />\n<pre><code>constexpr matrix(const std::function<real(index_t, index_t)>& func)\n</code></pre>\n<p>Since you can't call a <code>std::function</code> at compile time, there's no point to putting <code>constexpr</code> on this constructor. But you knew that. Probably what you should have written instead — in C++20 — is either</p>\n<pre><code>template<std::invocable<int, int> F>\nconstexpr matrix(const F& func)\n{\n</code></pre>\n<p>or</p>\n<pre><code>template<class F>\n requires std::is_invocable_r<real, const F&, int, int>\nconstexpr matrix(const F& func)\n{\n</code></pre>\n<p>The former is prettier. The latter is more rigorous: it checks not only that <code>F</code> is invocable, but that <code>const F&</code> is invocable (since that's what you'll actually be invoking within the body of the function) and also that the result of that invocation is convertible to <code>real</code>. Another option is:</p>\n<pre><code>template<class F>\nconstexpr matrix(const F& func)\n requires requires { { func(1,1) } -> std::convertible_to<real>; }\n{\n</code></pre>\n<p>But that's much ickier-looking syntactically, and ends up checking basically the same thing as the <code>is_invocable_r</code> version.</p>\n<p>Anyway, the point of all of these is to <em>avoid type erasure.</em> You want this constructor to take any callable object?— so <em>make</em> it take any callable object! Cut out the middleman. This will also produce better codegen, since the optimizer can probably inline the whole thing and even unroll those loops.</p>\n<p><strong>However.</strong> This probably runs you smack into the usual problem with greedy constructor templates, because guess what type you've made invocable with the signature <code>real(int, int)</code>? That's right: <code>matrix</code> itself! The solution here is <em>don't do that</em>. Combine a normal explicit constructor template with a normal <code>.at()</code> member function (just like <code>vector</code> and <code>map</code> have), while you wait for multi-operand <code>operator[]</code> to land in C++2b.</p>\n<pre><code>template<std::invocable<int, int> F>\nconstexpr explicit matrix(const F& func) { ... }\n\nconstexpr real& at(int i, int j) { ... }\nconstexpr const real& at(int i, int j) const { ... }\n</code></pre>\n<p>Notice that I've marked this constructor <code>explicit</code>, in order to prevent implicit conversions from <code>std::function</code> to <code>ctm::matrix</code>. You want those conversions to be <em>possible</em>, but you never want them to happen <em>implicitly!</em> As a general rule, every constructor you write should be <code>explicit</code>, except for the copy and move constructors (because you <em>want</em> copies to happen implicitly), and except for extremely rare cases such as <code>std::string</code>'s constructor from <code>const char *</code>.</p>\n<hr />\n<p>You asked about <code>first_minor</code>:</p>\n<pre><code> template <index_t m = M, index_t n = N>\n requires (m == n && m > 1)\n constexpr matrix<m - 1, n - 1> first_minor(index_t i, index_t j) const\n</code></pre>\n<p>At first, I can't even really tell what you're trying to do here. Are those template parameters <code>m</code> and <code>n</code> actual parameters you expect the caller to pass in? or just copies of <code>M</code> and <code>N</code> that you're using for metaprogramming? If you're putting metaprogramming into your template parameter list <em>anyway</em>, then you should first try to do it in the way we've done it since C++11:</p>\n<pre><code> template<class = std::enable_if_t<(M == N) && (M > 1)>\n constexpr matrix<M-1, N-1> first_minor(int i, int j) const\n</code></pre>\n<p>However, this still fails when either <code>M</code> or <code>N</code> is 1, because at that point the return type <code>matrix<M-1, N-1></code> becomes ill-formed (thanks to the requires-clause on <code>matrix</code>). So we have to do something sneaky to keep it well-formed. For example:</p>\n<pre><code> using SmallerMatrix = matrix<(M > 1) ? M-1 : 1, (N > 1) ? N-1 : 1>;\n\n constexpr SmallerMatrix first_minor(int i, int j) const\n requires (M == N && M > 1)\n</code></pre>\n<p>A more "C++20-ish" clever way to write that would be</p>\n<pre><code> constexpr auto first_minor(int i, int j) const\n -> matrix<std::clamp(M-1, 1, M), std::clamp(N-1, 1, N)>\n requires (M == N && M > 1)\n</code></pre>\n<p>(As long as you have already taken my advice to use <code>int</code> for <code>index_t</code>, that is. Otherwise the compiler will complain that <code>std::clamp</code> has deduced conflicting types for its template type parameter. All this stuff kind of hangs together as one system. :))</p>\n<hr />\n<p>Finally, write some unit tests! You could have improved this question by linking to a complete compilable example on Godbolt. That would have made it easier to play around with the <code>first_minor</code> metaprogramming, for example.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T05:51:43.530",
"Id": "510808",
"Score": "1",
"body": "Thanks for the great writeup! You've helped me smooth out the code a good bit. Some of the decisions made regarding the interface of the class and the types used are due to matrices only really making sense when they have positive dimensions, but I have decided to change the index type to `std::int_64t` at your suggestion. I believe I'll keep the 1-indexed `operator()`, since part of my goal with this was to have an interface as close as I could get to usual usage of a matrix. Also, making the return type on `first_minor` trailing helped fix the code there. Again, thanks a ton!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T05:09:01.297",
"Id": "259040",
"ParentId": "259038",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "259040",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T02:58:13.083",
"Id": "259038",
"Score": "5",
"Tags": [
"c++",
"matrix",
"c++20",
"constant-expression"
],
"Title": "Compile-time Matrix Class"
}
|
259038
|
<p>This Python code</p>
<pre><code>im_data = np.ones((100,100))
im_data[20:50,20:50]=np.zeros((30,30))
</code></pre>
<p>can generate a 2d array that could be used to create an image</p>
<pre><code>plt.axis('off')
axi = plt.imshow(im_data, cmap='Greys')
</code></pre>
<p><a href="https://i.stack.imgur.com/t6fqO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/t6fqO.png" alt="enter image description here" /></a></p>
<p>I'm trying to do the same job with Java</p>
<pre><code>class Arr100{
public static void main(String[] args){
System.out.println("H");
int[][] arr = new int[100][100];
for(int i=0; i<arr.length; i++){
for (int j=0; j<arr[i].length; j++){
arr[i][j]=1;
}
}
for(int i=20; i<50; i++){
for (int j=20; j<50; j++){
arr[i][j]=0;
}
}
}
}
</code></pre>
<p>In terms of GPU and memory, is there a better way to do the same thing?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T07:21:13.753",
"Id": "510810",
"Score": "1",
"body": "Crossposting from [how-do-i-create-a-black-and-white-image-from-a-2d-array-in-java](https://stackoverflow.com/questions/66927922/how-do-i-create-a-black-and-white-image-from-a-2d-array-in-java)"
}
] |
[
{
"body": "<p>You don't need to manually manage nested <code>for</code> loops.</p>\n<pre><code>int[][] pixels = new int[100][100];\nfor (int[] row : pixels) {\n Arrays.fill(row, 1);\n}\n\nfor (int i = 20; i < 50; i++) {\n Arrays.fill(pixels[i], 20, 50, 0);\n}\n</code></pre>\n<p>This will make better use of optimizations available for managing array values.</p>\n<p>I personally don't like <code>arr</code> as a name for an array. If I need a generic name, I tend to use <code>data</code>. I used <code>pixels</code> here. Or <code>colors</code> would work.</p>\n<p>This may be more or less efficient than</p>\n<pre><code>int[][] pixels = new int[100][100];\nint i = 0;\nfor (; i < 20; i++) {\n Arrays.fill(pixels[i], 1);\n}\nfor (; i < 50; i++) {\n Arrays.fill(pixels[i], 0, 20, 1);\n Arrays.fill(pixels[i], 50, pixels[i].length, 1);\n}\nfor (; i < pixels.length; i++) {\n Arrays.fill(pixels[i], 1);\n}\n</code></pre>\n<p>That doesn't set any of the pixels twice and relies on the default values for the 0 pixels. That may be more efficient. Although it is also possible that it is easier to set the entire array to one value than to work with rows and parts of rows.</p>\n<p>Note that if you are willing to change the representation, then</p>\n<pre><code>int[][] pixels = new int[100][100];\nfor (int i = 20; i < 50; i++) {\n Arrays.fill(pixels[i], 20, 50, 1);\n}\n</code></pre>\n<p>would probably be better than either. In this, black is the default 0 while 1 is the white square.</p>\n<p>The third form is the least code and probably fastest. The only way that I could see it being as slow or slower than either of the others is if something is happening implicitly. For example, if there is a memory initialization that the first form skips because it immediately does its own initialization.</p>\n<p>The first form is less code than the second. The comparative speed would probably depend on the platform (and possibly compiler). Platforms that allow for managing memory as blocks would probably find the first quicker, while platforms that can only address one word at a time would probably find the second quicker.</p>\n<p>You would have to do timing tests on all platforms where you expect to run to get a real idea of the speed.</p>\n<p>There is probably a streams-based version that is faster as well.</p>\n<p>If you want to go further and try to pass the information for regions, you would either have to write your own solution or use a third party library. Note that such a thing would probably be slower. But it might be less code. I suspect that your Python example is also slower on some platforms (albeit less code). My guess is that Python implements it much as the first example code block in this answer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T18:45:50.697",
"Id": "259052",
"ParentId": "259039",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259052",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T04:19:36.290",
"Id": "259039",
"Score": "0",
"Tags": [
"java"
],
"Title": "generate a 2d array that could be used to create an image with Java"
}
|
259039
|
<p>I'm trying to build an email verification for user signup using <a href="https://docs.djangoproject.com/en/3.1/ref/class-based-views/generic-editing/#django.views.generic.edit.CreateView" rel="nofollow noreferrer"><code>CreateView</code></a>. This view check <strong>whether the user is a new or already existing inactive user?</strong> and resend verification if the user is inactive.</p>
<p>Here's how I did it(email sending part),</p>
<p><strong>views.py</strong></p>
<pre><code>class SignUpView(CreateView):
""" SignUp view """
form_class = SignUpForm
success_url = reverse_lazy('login')
template_name = 'registration/register.html'
def send_activation_email(self, request, user):
""" sends email confirmation email """
uidb64 = urlsafe_base64_encode(force_bytes(user.pk))
token = token_generator.make_token(user)
domain = get_current_site(request).domain
schema = request.is_secure() and "https" or "http"
link = reverse('user_activation', kwargs={'uidb64': uidb64, 'token': token})
url = '{}://{}{}'.format(schema, domain, link)
payload = {
'receiver': user.email,
'email_body': {
'username': user.username,
'email_body': 'Verify your email to finish signing up for RapidReady',
'link': url,
'link_text': 'Verify Your Email',
'email_reason': "You're receiving this email because you signed up in {}".format(domain),
'site_name': domain
},
'email_subject': 'Verify your Email',
}
Util.send_email(payload)
messages.success(request, 'Please Confirm your email to complete registration.')
def get(self, request, *args, **kwargs):
""" Prevents authenticated user accessing registration path """
if request.user.is_authenticated:
return redirect('home')
return super(SignUpView, self).get(request, *args, **kwargs)
def form_valid(self, form):
""" Handles valid form """
form = self.form_class(self.request.POST)
user = form.save(commit=False)
user.is_active = False
user.save()
self.send_activation_email(self.request, user)
return render(self.request, 'registration/confirm_email.html', {'email': user.email})
def post(self, request, *args, **kwargs):
""" Handles existing inactive user registration attempt """
form = self.form_class(self.request.POST)
if User.objects.filter(email=request.POST['email']).exists():
user = User.objects.get(email=request.POST['email'])
if not user.is_active:
self.send_activation_email(request, user)
return render(self.request, 'registration/confirm_email.html', {'email': user.email})
# if no record found pass to form_valid
return self.form_valid(form)
</code></pre>
<p><strong>util.py</strong></p>
<pre><code>class TokenGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self, user, timestamp):
return text_type(user.is_active) + text_type(user.pk) + text_type(timestamp)
token_generator = TokenGenerator()
class EmailThread(threading.Thread):
def __init__(self, email):
self.email = email
threading.Thread.__init__(self)
def run(self):
self.email.send()
class Util:
@staticmethod
def send_email(data):
msg_plain = render_to_string('email/email_normal_email.txt', data['email_body'])
msg_html = render_to_string('email/email_normal_email.html', data['email_body'])
msg = EmailMultiAlternatives(data['email_subject'], msg_plain, config('EMAIL_HOST_USER'), [data['receiver']])
msg.attach_alternative(msg_html, "text/html")
EmailThread(msg).start()
</code></pre>
<p>In the above code, I used <a href="https://docs.djangoproject.com/en/3.1/ref/class-based-views/mixins-editing/#django.views.generic.edit.ModelFormMixin.form_valid" rel="nofollow noreferrer"><code>form_valid()</code></a> method to handle a <strong>new user registration</strong> and the <code>post()</code> method to check whether the user is <strong>new or already registered inactive user</strong>.</p>
<p>If no record found the <code>post()</code> method will call <code>form_valid()</code> method passing the form as an argument(last line in views). And this logic works just fine.</p>
<p>So, my main question is, 'Are there any negative effects due to this implementation?' and any advice(best practices, improvements, etc.) will be greatly appreciated.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T09:32:06.603",
"Id": "259041",
"Score": "2",
"Tags": [
"python",
"django"
],
"Title": "Email verification resend implementation Django"
}
|
259041
|
<p>I'm teaching myself Object Oriented Programming in JavaScript and I'm looking over <a href="https://editor.p5js.org/codingtrain/sketches/D4ty3DgZB" rel="nofollow noreferrer">this small P5 code</a> of <a href="https://thecodingtrain.com/CodingChallenges/078-simple-particle-system.html" rel="nofollow noreferrer">CodingTrain's No.78</a>, which deals with flying particles in the canvas, as a material.</p>
<p>The full code is below:</p>
<pre><code>// Daniel Shiffman
// http://codingtra.in
// Simple Particle System
// https://youtu.be/UcdigVaIYAk
const particles = [];
function setup() {
createCanvas(600, 400);
}
function draw() {
background(0);
for (let i = 0; i < 5; i++) {
let p = new Particle();
particles.push(p);
}
for (let i = particles.length - 1; i >= 0; i--) {
particles[i].update();
particles[i].show();
if (particles[i].finished()) {
// remove this particle
particles.splice(i, 1);
}
}
}
class Particle {
constructor() {
this.x = 300;
this.y = 380;
this.vx = random(-1, 1);
this.vy = random(-5, -1);
this.alpha = 255;
}
finished() {
return this.alpha < 0;
}
update() {
this.x += this.vx;
this.y += this.vy;
this.alpha -= 5;
}
show() {
noStroke();
//stroke(255);
fill(255, this.alpha);
ellipse(this.x, this.y, 16);
}
}
</code></pre>
<p>Wanting to train my OOP skill, I'm trying to refactor this code into more sophisticated one in the OOP point of view. So I refactored it by adding <code>Particles_Manipulation</code> class and moving the process written in <code>draw</code> function into the <code>Particles_Manipulation</code> class as <code>action</code> method.
The code is below:</p>
<pre><code>// Daniel Shiffman
// http://codingtra.in
// Simple Particle System
// https://youtu.be/UcdigVaIYAk
class Particle {
constructor() {
this.x = 300;
this.y = 380;
this.vx = random(-1, 1);
this.vy = random(-5, -1);
this.alpha = 255;
}
finished() {
return this.alpha < 0;
}
update() {
this.x += this.vx;
this.y += this.vy;
this.alpha -= 5;
}
show() {
noStroke();
//stroke(255);
fill(255, this.alpha);
ellipse(this.x, this.y, 16);
}
}
class Particles_Manipulation{
constructor(){
this.particles = [];
}
push_particles(_n){
for (let i = 0; i < _n; i++) {
let p = new Particle();
this.particles.push(p);
}
}
action(){
for (let i = this.particles.length - 1; i >= 0; i--) {
this.particles[i].update();
this.particles[i].show();
if (this.particles[i].finished()) {
// remove this particle
this.particles.splice(i, 1);
}
}
}
}
const my_Particles_Manipulation = new Particles_Manipulation();
function setup() {
createCanvas(600, 400);
}
function draw() {
background(0);
my_Particles_Manipulation.push_particles(5);
my_Particles_Manipulation.action();
}
</code></pre>
<p>Could you evaluate my refactoring is nice or not?</p>
|
[] |
[
{
"body": "<p>From a short review;</p>\n<ul>\n<li>In OOP, your objects are supposed to be re-usable\n<ul>\n<li>I would take the <code>x</code>,<code>y</code> from a parameter</li>\n<li>I would take the <code>vx</code>, <code>vy</code> from a parameter</li>\n<li>I would even take the <code>alpha</code> from a parameter</li>\n</ul>\n</li>\n<li>Its nicer to call <code>finished</code> -> <code>isFinished</code>, this way the reader expects a boolean to return</li>\n<li>In <code>update</code>, it makes sense to update the location with velocity, but I would have expected the particle to take a 'updateFunction<code>which would reduce the</code>alpha` by 5</li>\n<li>In <code>show</code>, 16 should be either a nicely named constant, or something that can be set by the user of the particle. It breaks currently the rule of magic numbers, and it makes the class less re-usable</li>\n<li><code>Particles_Manipulation</code> -> <code>ParticlesManipulation</code></li>\n<li>No fan of underscores, <code>_n</code> -> <code>n</code> or even <code>particleCount</code></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T18:44:53.573",
"Id": "259051",
"ParentId": "259044",
"Score": "1"
}
},
{
"body": "<h2>Magic numbers</h2>\n<p>Avoid magic numbers. Magic numbers are just numbers in your code that represent some abstract data value. The problem is that they are spreed within the code. To make changes to these values requires searching the code and often the same values are repeated making the task even more difficult.</p>\n<p>Defining the magic numbers as named constants makes making changes very easy. See rewrite</p>\n<h2>Using native API's</h2>\n<p>P5 is great but using it to create such a simple rendering task is not worth the need to load a huge chunk of code to do what the native API will do quicker (No need for the P5's overhead)</p>\n<h2>Naming</h2>\n<p>There are a lot of problems with your naming style.</p>\n<h3>JS naming convention</h3>\n<p>The naming convention for JavaScript is to use lowerCamelCase for all names with the exception of objects created with the new token which uses UpperCamelCase (Static objects and object factories can also use UpperCamelCase). For constants you can use UPPER_SNAKE_CASE</p>\n<h3>_underscoredNames</h3>\n<p>Use underscore to avoid possible naming classes in systems where you have no control of names.</p>\n<p>Using underscore should only ever be a very last option and should never be used if there is no need. Eg the argument <code>_n</code> in <code>push_particles(_n) {</code> should be <code>pushParticles(n)</code></p>\n<h3>Avoid redundancy</h3>\n<p>It is easy to add too much to a name. Keep names short and use as few words as possible. Names are never created in isolation and like a natural language requires context to have meaning.</p>\n<p>Eg</p>\n<ul>\n<li><p><code>Particles_Manipulation</code> is overkill when <code>Particles</code> is all that is needed</p>\n</li>\n<li><p><code>my_Particles_Manipulation</code> Never use <code>my</code> (unless its instructional code) This name can just be <code>particles</code>, or <code>smoke</code></p>\n</li>\n<li><p><code>push_particles</code> (don't repeat names) What does this function do? "Adds particles". <code>push becomes </code>add<code>. What does it add particles to? "The Particles object", thus </code>particles<code>can be inferred. The name</code>add<code>is all that is needed. If you were adding monkeys then maybe</code>addMonkeys`</p>\n</li>\n</ul>\n<h3>Avoid repeated long references</h3>\n<p>Avoid doing the same long reference path and array indexing by store the object reference in a variable.</p>\n<pre><code> this.particles[i].update();\n this.particles[i].show();\n if (this.particles[i].finished()) {\n // remove this particle\n this.particles.splice(i, 1);\n }\n</code></pre>\n<p>Becomes</p>\n<pre><code> const p = this.particles[i];\n p.update();\n p.show();\n if (p.finished()) { \n this.particles.splice(i, 1);\n }\n</code></pre>\n<h2>Keep an eye on Logic</h2>\n<p>The render system reduces the particle alpha each step. You use the alpha value to check when to remove particles <code>alpha < 0</code>. However you reduce the alpha, then render, then remove. That means than once going every frame you are trying to render 5 invisible particles. Remove befor rendering.</p>\n<h2>JS and Memory</h2>\n<p>Javascript is a managed language. Meaning that it manages memory for you.</p>\n<p>This is great in most cases but it comes with a serious performance hit in applications like particle systems where many small independent objects are frequently being created and destroyed .</p>\n<h3>Object pool</h3>\n<p>To avoid the memory management overhead we use object pools.</p>\n<p>An object pool is just an array of objects that are not being used. When an object is no longer needed we remove it from the main array and put it in the pool. When a new object is needed we check the pool, if there are any object in the pool we use it rather than create a new one.</p>\n<p>This means that the particle object will need a function that resets it.</p>\n<p>See rewrite</p>\n<p>Note you can also pool the particles in the one array by using a bubble iterator to avoid the expensive @MDN.JS.OBJ.Array.slice@. Dead particle bubble to one end of the array. This is even faster but makes the inner update loop a lot more complex. You would only do this if you where using 10K+ particles.</p>\n<h2>JavaScript OO design</h2>\n<p>Many believe that using <code>class</code> is how to write good OO JavaScript. Sorry to say it is not and is in fact the worst way to write OO JavaScript. The class syntax does not provide a good encapsulation model, its only plus is easy inheritance, which is kind of redundant in lieu of JavaScript's lose polymorphism</p>\n<p>In this case factory functions (a function that creates Object AKA Object factory) is best suited. Because we use an object pool when need not even bother with assigning a <code>prototytpe</code> for particle functions.</p>\n<p>Some advantages of factory functions</p>\n<ul>\n<li><p>This eliminates the need to use <code>this</code> and <code>new</code>.</p>\n</li>\n<li><p>Lets you define private properties without the need to <code>#hack</code> names</p>\n</li>\n<li><p>Lets you create objects before the first execution pass has completed (move the init and setups to the top where it belongs)</p>\n</li>\n</ul>\n<p>Some disadvantages of factory functions</p>\n<ul>\n<li><p>Requires a good understanding of <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures\" rel=\"nofollow noreferrer\">closure</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Scope\" rel=\"nofollow noreferrer\">Scope</a> both of which are a difficult subjects to get a good understanding of.</p>\n</li>\n<li><p>Does not work well with object prototypes.</p>\n</li>\n</ul>\n<h2>Rewrite</h2>\n<p>The rewrite uses the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D\" rel=\"nofollow noreferrer\">CanvasRenderingContext2D API</a> to avoid the overhead of P5, Some replacement functions are at the bottom.</p>\n<p>Note that when defining constants it is always a good idea to include unit types, ranges, and or a description as a comment</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>animate();\n;(() => {\n const CANVAS_WIDTH = 600; // in CSS pixels\n const CANVAS_HEIGHT = 400;\n const PARTICLE_SPREAD = 1; // max x speed in canvas pixels\n const PARTICLE_POWER = 3; // max y speed in canvas pixels\n const PARTICLE_RADIUS = 12; // max y speed in canvas pixels\n const MAX_PARTICLES = 1000; // Approx max particle count\n const PARTICLES_RATE = 3; // new particle per frame\n const SMOKE_PARTICLES_PATH = new Path2D; // circle used to render particle\n const PARTICLE_COLOR = \"#FFF\"; // any valid CSS color value\n const START_ALPHA = 1; // particle start alpha max\n const START_ALPHA_MIN = 0.5; // particle start alpha\n\n // Rate particle alpha decays to match MAX_PARTICLES. The life time in seconds \n // can be calculates as Math.ceil(1 / ALPHA_DECAY_SPEED) * 60\n const ALPHA_DECAY_SPEED = 1 / (MAX_PARTICLES / PARTICLES_RATE); \n\n SMOKE_PARTICLES_PATH.arc(0, 0, PARTICLE_RADIUS, 0, Math.PI * 2);\n const canvas = createCanvas(CANVAS_WIDTH, CANVAS_HEIGHT);\n const smoke = new Particles(canvas);\n animate.draw = function() {\n canvas.ctx.setTransform(1, 0, 0, 1, 0, 0);\n canvas.ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);\n smoke.add(PARTICLES_RATE);\n smoke.update();\n }\n\n function Particle() { \n var x, y, vx, vy, alpha;\n const PARTICLE = {\n init() {\n x = CANVAS_WIDTH / 2;\n y = CANVAS_HEIGHT;\n vx = random(-PARTICLE_SPREAD, PARTICLE_SPREAD);\n vy = random(-PARTICLE_POWER, -PARTICLE_POWER);\n alpha = random(START_ALPHA_MIN, START_ALPHA);\n return PARTICLE;\n },\n update() {\n x += vx;\n y += vy;\n alpha -= ALPHA_DECAY_SPEED;\n return alpha < 0;\n },\n draw(ctx) {\n ctx.globalAlpha = alpha;\n ctx.setTransform(1, 0, 0, 1, x, y);\n ctx.fill(SMOKE_PARTICLES_PATH);\n },\n };\n return Object.freeze(PARTICLE.init());\n }\n function Particles(canvas) {\n const particles = [];\n const pool = [];\n const ctx = canvas.ctx;\n return Object.freeze({\n add(n) {\n while (n-- > 0) {\n pool.length ?\n particles.push(pool.pop().init()) :\n particles.push(Particle());\n }\n },\n update() {\n var i = 0;\n ctx.fillStyle = PARTICLE_COLOR;\n while (i < particles.length) {\n const p = particles[i];\n p.update() ? \n pool.push(particles.splice(i--, 1)[0]) : \n p.draw(ctx);\n i++;\n }\n }\n });\n }\n})();\n\n\n// functions to replace P5\nfunction createCanvas(width, height) {\n const canvas = Object.assign(document.createElement(\"canvas\"), {width, height, className: \"renderCanvas\"});\n document.body.appendChild(canvas);\n canvas.ctx = canvas.getContext(\"2d\");\n return canvas;\n}\nfunction random(min, max) { return Math.random() * (max - min) + min }\n\nfunction animate() {\n animate.draw?.();\n requestAnimationFrame(animate);\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.renderCanvas {\n background: black;\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T15:23:12.723",
"Id": "510956",
"Score": "0",
"body": "Modern high-performance garbage collectors and object allocators are *extremely* efficient. However, they typically rely on the *Generational Hypotheses* to gain their performance: 1) Objects die young, 2) Old objects never reference new objects. Also, mutation destroys performance. Object pools screw with all three: they unnaturally extend the lifetimes of objects, they typically lead to older objects referencing newer objects at least some of the time, and they rely on mutation (resetting an object to a starting state instead of discarding the object and creating a new one)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T15:23:29.270",
"Id": "510957",
"Score": "0",
"body": "This absolutely *destroys* performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T17:12:13.183",
"Id": "510966",
"Score": "0",
"body": "Do you have a good reference for mutation destroys performance?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T20:13:55.397",
"Id": "510977",
"Score": "0",
"body": "@JörgWMittag Every point in your comment is wrong. All my Objects are frozen and can't be mutated, No particle dies and incur NO GC and only one instantiation hit.. I don't know what you mean by \"Old objects never reference new objects\" Objs are not references,. references refer to objs, you can bind references to objs, however `this` is read only. Note no `this`tokens in my answer. There is no `Particle` or `Particles` obj (only as abstractions) I use closure to hold state and interface (frozen), `Particles` is only 2 arrays and a canvas. It does not hold the interface. AND last point..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T20:14:05.530",
"Id": "510978",
"Score": "0",
"body": "If pools destroy performance, what makes using pools use less memory, and run faster???"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T07:16:57.643",
"Id": "259070",
"ParentId": "259044",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T11:11:25.020",
"Id": "259044",
"Score": "2",
"Tags": [
"javascript",
"object-oriented",
"programming-challenge"
],
"Title": "OOP refactoring technique"
}
|
259044
|
<p>While answering <a href="https://codereview.stackexchange.com/questions/259019/a-c-program-to-plot-an-equation/259031?noredirect=1#comment510796_259031">this code review question</a>, I came up with a way to convert an equation given at runtime to a <code>std::function<double(double)></code> that would evaluate that equation at a given point. Assuming the equation was already split into tokens and converted to <a href="https://en.wikipedia.org/wiki/Reverse_Polish_notation" rel="noreferrer">postfix notation</a>, this is done by evaluating those tokens like you would do in a normal implementation of a RPN calculator by maintaining a stack of intermediate results, but instead of just storing the values, the stack stores lambda expressions that can calculate those values. At the end of the evaluation, the stack should thus contain a single lambda expression that implements the desired equation. Here is a simplified version of the parser than only supports a few operations:</p>
<pre><code>#include <cmath>
#include <functional>
#include <iostream>
#include <numbers>
#include <stack>
#include <string>
#include <string_view>
std::function<double(double)> build_function(const std::vector<std::string_view> &rpn_tokens) {
std::stack<std::function<double(double)>> subexpressions;
for (const auto &token: rpn_tokens) {
if (token.empty())
throw std::runtime_error("empty token");
if (token == "x") { // Variable
subexpressions.push([](double x){
return x;
});
} else if (isdigit(token[0])) { // Literal number
double value = std::stof(token.data());
subexpressions.push([=](double /* ignored */){
return value;
});
} else if (token == "sin") { // Example unary operator
if (subexpressions.size() < 1) {
throw std::runtime_error("invalid expression");
}
auto operand = subexpressions.top();
subexpressions.pop();
subexpressions.push([=](double x){
return std::sin(operand(x));
});
} else if (token == "+") { // Example binary operator
if (subexpressions.size() < 2) {
throw std::runtime_error("invalid expression");
}
auto right_operand = subexpressions.top();
subexpressions.pop();
auto left_operand = subexpressions.top();
subexpressions.pop();
subexpressions.push([=](double x){
return left_operand(x) + right_operand(x);
});
} else {
throw std::runtime_error("invalid token");
}
}
if (subexpressions.size() != 1) {
throw std::runtime_error("invalid expression");
}
return subexpressions.top();
}
int main() {
auto function = build_function({"1", "x", "2", "+", "sin", "+"}); // 1 + sin(2 + x)
for (double x = 0; x < 2 * std::numbers::pi; x += 0.1) {
std::cout << x << ' ' << function(x) << '\n';
}
}
</code></pre>
<p>I call this a poor man's JIT because while it looks like we get a function object that is seemingly created at runtime, it basically is a bunch of precompiled functions (one for each lambda body in the above code) strung together by the lambda captures. So there is quite a lot more overhead when calling the above <code>function()</code> than if one would write the following:</p>
<pre><code>auto function = [](double x){
return 1 + sin(2 + x);
}
</code></pre>
<p>But it should still be much faster than parsing the bunch of tokens that make up the equation each time you want to evaluate it.</p>
<p>Some questions:</p>
<ul>
<li>Is there a better way to do this?</li>
<li>Is this technique already implemented in some library?</li>
<li>The argument to resulting function has to be passed down to most of the lambdas (the exception being the one returning literal numbers). Is there a better way to do this?</li>
<li>How should one handle building a function that takes multiple arguments? Can we make <code>build_function</code> a template somehow that can return a <code>std::function</code> with a variable number of arguments?</li>
</ul>
<hr />
<p>Performance measurements on an AMD Ryzen 3900X, code compiled with GCC 10.2.1 with <code>-O2</code>, after a warm-up of 60 million invocations, averaged over another 60 million invocations of <code>function()</code>:</p>
<ul>
<li>A simple lambda: 10 ns per evaluation</li>
<li>The above code: 21 ns per evaluation</li>
<li>Deduplicator's original answer: 77 ns per evaluation
<ul>
<li>Adding <code>stack.reserve()</code>: 39 ns per evaluation</li>
<li>Making <code>stack</code> <code>static</code>: 26 ns per evaluation</li>
</ul>
</li>
<li>Deduplicator's version using <a href="https://coliru.stacked-crooked.com/a/a788b331c7c21993" rel="noreferrer">separate bytecode and data stacks</a>: 19 ns per evaluation
<ul>
<li>Hardcoding using a fixed small stack: 17 ns per evaluation</li>
</ul>
</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T15:40:12.453",
"Id": "510836",
"Score": "9",
"body": "You have reinvented Forth, I believe! :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T17:47:49.727",
"Id": "510852",
"Score": "2",
"body": "@Edward You mean [threaded code](https://en.wikipedia.org/wiki/Threaded_code)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T18:01:03.590",
"Id": "510853",
"Score": "1",
"body": "There are two basic aspects to Forth. One is to have a series of RPN-style instructions that operate on a stack. The second is to have threaded code. There are, of course, other things in Forth, but these are the most fundamental and unique."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T23:49:35.990",
"Id": "510868",
"Score": "3",
"body": "@G.Sliepen This is probably obvious, but if you're going to try to benchmark this, make sure your tokens are specified as command-line arguments, rather than as string literals in `main()`. Otherwise the compiler can just substitute the hell out of everything."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T07:53:52.433",
"Id": "510871",
"Score": "0",
"body": "@Will Good point, I didn't do that, but the assembly looked reasonable. I will make the change and benchmark again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T13:56:45.510",
"Id": "510884",
"Score": "0",
"body": "@Will Reading the tokens from the command line didn't change the benchmark results."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T03:58:21.677",
"Id": "510934",
"Score": "0",
"body": "How about -O3? Would this change the results a lot?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T07:10:19.817",
"Id": "510936",
"Score": "0",
"body": "If you want *Just in Time* compilation, generate *machine code* with libraries like [asmjit](http://asmjit.com/) or [libgccjit](https://gcc.gnu.org/onlinedocs/jit/)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T21:23:02.630",
"Id": "510987",
"Score": "2",
"body": "What you have discovered is called \"threaded code\" and it's basically a tail-call interpreter. Wasm3 for example is a WebAssembly interpreter that uses [exactly this technique](https://github.com/wasm3/wasm3/blob/main/docs/Interpreter.md) and it's one of the fastest interpreters out there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T11:01:27.800",
"Id": "511013",
"Score": "0",
"body": "Is the part that has a bounty on-topic on codereview?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T13:56:46.387",
"Id": "511046",
"Score": "1",
"body": "@CarstenS Sure, an answer that proposes an alternative way to get the same result in a better way (whether that is better looking code, better performance, less memory usage, and so on) is perfectly fine for this site."
}
] |
[
{
"body": "<blockquote>\n<p>Is there a better way to do this?</p>\n</blockquote>\n<p>Well, you have dynamic dispatch and yet another scattered island of memory for <em>every single token</em>. That is massively inefficient.</p>\n<p>A simple way to more efficiency is writing your own mini-VM for executing expressions. You will still only have to parse once, but now all the memory is in a single compact chunk which will be linearly used, and the compiler can see all the code.</p>\n<p>Switch-statements with a single compact range of valid values are simplicity itself, and you avoid the argument shuffling, register saving, and all the other overhead of dynamically calling arbitrary functions.</p>\n<p>The next step for efficiency would be compiling to native code instead.</p>\n<p>Also, putting all the arguments in an array and then using an instruction with operand or consecutive simple instructions to get them should be a simple modification.</p>\n<p>I also added extensive X-Macros to reduce repetition and avoid defining all applicable transformations all over the place.</p>\n<p>Adapted example <a href=\"//coliru.stacked-crooked.com/a/a788b331c7c21993\" rel=\"noreferrer\">live on coliru</a>:</p>\n<pre><code>#include <iostream>\n#include <numbers>\n\n#include <charconv>\n#include <cmath>\n#include <exception>\n#include <memory>\n#include <span>\n#include <string_view>\n#include <string>\n#include <vector>\n\n#define XX() \\\n /* token, tag, args, results, code */ \\\n X("x", x, 0, 1, *stack = x) \\\n X("sin", sin, 1, 1, *stack = std::sin(*stack)) \\\n X("+", plus, 2, 1, *stack += stack[-1])\n\nenum class instruction : char {\n end,\n push,\n#define X(a, b, c, d, e) b,\n XX()\n#undef X\n};\n \nauto build_function(std::span<const std::string_view> rpn_tokens) {\n std::vector<instruction> code;\n std::vector<double> data;\n double temp;\n unsigned count = 0, max_count = 0;\n auto process = [&](instruction id, unsigned args, unsigned results) {\n if (count < args)\n throw std::runtime_error("invalid expression: underflow");\n code.push_back(id);\n count += results - args;\n max_count = std::max(max_count, count);\n };\n for (auto token : rpn_tokens) {\n#define X(a, b, c, d, e) \\\n if (token == a) \\\n process(instruction::b, c, d); \\\n else\n XX()\n#undef X\n// if (auto [p, ec] = std::from_chars(token.begin(), token.end(), temp); !ec && p = token.end()) {\n// process(instruction::push, 0, 1);\n// data.push_back(temp);\n// } else\n// throw std::runtime_error("invalid token");\n try {\n temp = std::stod(std::string(token));\n data.push_back(temp);\n process(instruction::push, 0, 1);\n } catch(...) {\n std::throw_with_nested(std::runtime_error("invalid token"));\n }\n }\n process(instruction::end, 1, 0);\n if (count)\n throw std::runtime_error("invalid expression: overflow");\n code.shrink_to_fit();\n data.shrink_to_fit();\n return [code, data, max_count](double x) {\n constexpr auto small_stack = 128;\n\n auto core = [](auto code, auto data, auto stack, auto x){\n for (;;) {\n switch(*code++) {\n case instruction::end:\n return *stack;\n case instruction::push:\n *--stack = *data++;\n break;\n\n#define X(a, b, c, d, e) \\\n case instruction::b: \\\n stack += c - d; \\\n e; \\\n break;\n XX()\n#undef X\n default:\n throw std::runtime_error("unexpected");\n }\n }\n };\n auto small = [&]{\n double stack[small_stack];\n return core(code.cbegin(), data.cbegin(), std::end(stack), x);\n };\n auto big = [&]{\n auto stack = std::make_unique<double[]>(max_count);\n return core(code.cbegin(), data.cbegin(), &stack[0] + max_count, x);\n };\n return max_count <= small_stack ? small() : big();\n };\n}\n#undef XX\n\nint main() {\n std::string_view rpn[] = {"1", "x", "2", "+", "sin", "+"}; // 1 + sin(2 + x)\n auto function = build_function(rpn);\n\n for (double x = 0; x < 2 * std::numbers::pi; x += 0.1) {\n std::cout << x << ' ' << function(x) << '\\n';\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T22:21:55.590",
"Id": "510866",
"Score": "3",
"body": "I benchmarked your code against mine, and I was surprised my code was about 3.7 times faster! Of course, those numbers might be meaningless, as this code is just a very simplified expression parser, I should check it with more functions added and trying to evaluate more complex equations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T23:27:23.667",
"Id": "510867",
"Score": "1",
"body": "Did you benchmark parsing, invoking, or both? Anyway, seems there is no substitute for measuring. I think a big part of the problem is the dynamic allocation while executing. Must experiment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T07:52:51.520",
"Id": "510870",
"Score": "0",
"body": "I benchmarked just the invoking. Indeed, I will experiment as well, maybe just `reserve()`ing space on the stack will be enough to speed it up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T08:04:28.043",
"Id": "510873",
"Score": "1",
"body": "It seems the `stack` is indeed a big part of the problem. With a `static` `stack` it goes down to 26 ns, very close to my solution. I guess a stack should not be necessary; the order and number of the stack operations is always the same for each invokation of the returned function, my solution kind of \"hardcodes\" that, but I don't see how to do that with yours while keeping `bin` as compact as it is..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T09:39:36.040",
"Id": "510876",
"Score": "7",
"body": "Threaded code can be surprisingly fast and surprisingly dense at the same time. There are many tales of embedded systems programmers who discovered that a FORTH interpreter plus a FORTH program are both faster and more compact than a hand-optimized C program for the same problem. And once you have to solve more than just one single problem, the density advantage only increases because you only need one copy of the FORTH interpreter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T15:35:31.170",
"Id": "510894",
"Score": "0",
"body": "Call me crazy, but X macros are completely unreadable to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T15:35:43.390",
"Id": "510895",
"Score": "0",
"body": "@G.Sliepen Fixed the bug. But most commands manipulate the stack in the exact same way, so pulling it out of the individual calls to `X` saves code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T15:38:15.577",
"Id": "510896",
"Score": "2",
"body": "@PasserBy X macros are kind of neat. If you know them, and don't get too overboard. But yes, the preprocessor deserves to be treated as its own completely different language, which has to be understood. And it will only really start to pay off after adding a few more commands."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T22:19:43.243",
"Id": "510923",
"Score": "0",
"body": "@G.Sliepen Can you time this too? https://coliru.stacked-crooked.com/a/a788b331c7c21993"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T22:37:40.913",
"Id": "510924",
"Score": "0",
"body": "@Deduplicator Nice! That gets it down to 19 ns. If you hoist the choice between `big()` and `small()` out of the returned lambda, it gets down to 17 ns."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T17:47:28.687",
"Id": "510968",
"Score": "1",
"body": "@Deduplicator Having had to debug such macros in the past, the amount of work they save when writing the code is spent ten times if you ever have to debug the bloody code (at the very least you then have to look at the code after the preprocessor). But that might just be me. [Here's](https://openjdk.java.net/groups/hotspot/docs/RuntimeOverview.html#Interpreter|outline) an outline what HotSpot does these days. The template table is a pretty nifty trick to outperform your usual switch on bytecode interpreter, but if one thinks that X macros are hard to debug.. have fun with the generated code."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T21:24:48.043",
"Id": "259056",
"ParentId": "259045",
"Score": "19"
}
},
{
"body": "<p>Technically <code>isdigit(token[0])</code>:</p>\n<ul>\n<li>Needs <code>#include <cctype></code>.</li>\n<li>Should be <code>std::isdigit(static_cast<unsigned char>(token[0]))</code>.</li>\n</ul>\n<hr />\n<p>I guess passing a <code>std::map<std::string_view, double> const&</code> gives us flexibility with arguments.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T06:37:48.423",
"Id": "259069",
"ParentId": "259045",
"Score": "3"
}
},
{
"body": "<p>You can do better. But this is a deep rabbit hole.</p>\n<p>How about we start with a purely compile-time sublanguage.</p>\n<pre><code>template<auto v>\nstruct int_constant {\n constexpr double operator()(double)const{return v;}\n};\nstruct literal {\n double v = 0.;\n constexpr double operator()(double)const{return v;}\n};\nstruct variable {\n constexpr double operator()(double arg)const{return arg;}\n};\ntemplate<class Op, class T>\nstruct monoop {\n Op op;\n T t;\n constexpr double operator()(double arg)const{ return op(t(arg)); }\n};\ntemplate<class Op, class T>\nmonoop(Op, T)->monoop<Op,T>;\nconstexpr auto negate( auto t ) { return monoop{ std::negate<>{}, t }; }\n\ntemplate<class Op, class Lhs, class Rhs>\nstruct binop {\n Op op;\n Lhs lhs; \n Rhs rhs;\n constexpr double operator()(double arg)const{ return op(lhs(arg),rhs(arg)); }\n};\ntemplate<class Op, class Lhs, class Rhs>\nbinop(Op,Lhs,Rhs)->binop<Op,Lhs,Rhs>;\n\nauto sum( auto Lhs, auto Rhs ){\n return binop{ std::plus<>{}, Lhs, Rhs };\n}\nauto product( auto Lhs, auto Rhs ){\n return binop{ std::multiplies<>{}, Lhs, Rhs };\n}\n</code></pre>\n<p>I can then write</p>\n<pre><code>auto program = product( sum( literal{3.0}, variable{} ), int_constant<2>{} );\nauto squared = product( program, program );\nauto again = product( squared, squared );\nauto recurse = monoop{ program, program };\nauto recurse2 = monoop{ recurse, recurse };\n</code></pre>\n<p>which are done at compile time. Cute and all, but not quite practical, because you want to read in a script.</p>\n<p>But you can see that I can now build more complex expressions out of primitives. What more, I can do it at compile time, automatically, with some work.</p>\n<p>We have this:</p>\n<pre><code>using subprogram = std::function<double(double)>;\n</code></pre>\n<p>now, everything above is a <code>subprogram</code>. We can add compilers:</p>\n<pre><code>using binop_reducer = std::function<subprogram(subprogram, subprogram)>;\nusing monoop_reducer = std::function<subprogram(subprogram)>;\n</code></pre>\n<p>these take subprograms, and compiles them into other subprograms. You did it manually with a bunch of switch cases.</p>\n<p>With the idea of binary and unary compilers, you can build a map from the token "sin" to a sin compiler. Then your parser looks for an operation, be it "x" or "sin" or "+" or "-", determines what part of the grammar it matches, finds the appropriate compiler, and calls it, producing the result.</p>\n<p>This gets you back to roughly where you started, using a more complex system.</p>\n<p>To go a step further, you have to build a parse tree. Next, write a reducer -- it takes pieces of the parse tree, and reduces it to smaller ones.</p>\n<pre><code>struct binary_node {\n e_binary_operation op;\n parse_tree left;\n parse_tree right;\n};\n</code></pre>\n<p>The first pass version of the binary node compiler might compile the left, compile the right, look up the compiler for <code>op</code>, and connect them.</p>\n<p>The next step would be to write non-trivial reduction steps, like one for <code>a+b*c</code>, or <code>a+-b</code>. A compiler that sees <code>+</code> as the binary op might know how to look in the right; if it sees a <code>*</code> instead of compiling it seperate, it compiles <strong>all of <code>a</code> <code>b</code> and <code>c</code></strong>, then implements <code>a+b*c</code>.</p>\n<p>This is manual work and it sucks. But you can write non-type erased compilers (!), make a compile time map from an <code>enum class</code> describing the binary and unary operation to the non-type erased compiler, then write metaprogramming code that composes them together.</p>\n<p>It can then describe the parse tree that it was built out of, store that at run time how to recognize it in a reduction map, and the parse tree reducer can check each node in the parse tree for more complex reductions, and apply them.</p>\n<p>How far down this rabbit hole do you want to go?</p>\n<p>For a simple version of this, we'll look at RPN.</p>\n<p>We name our tokens with std::string, because compiling can be slow, that is ok.</p>\n<pre><code>std::tuple<\n std::map< std::string, nary_reducer<0> >,\n std::map< std::string, nary_reducer<1> >,\n std::map< std::string, nary_reducer<2> >\n> reducers;\n</code></pre>\n<p>(an <code>nary_reducer<n></code> takes <code>n</code> <code>subprograms</code> produces a <code>subprogram</code>).</p>\n<pre><code>for (auto token : tokens) {\n // todo:handle constants here\n if (std::get<0>( reducers ).count(token)) {\n // the variable 'x' say\n active.push( std::get<0>( reducers )[token]() );\n } else if (std::get<1>( reducers ).count(token)) {\n // sin of something\n auto arg = active.pop(); // throw on failure, or whatever\n active.push( std::get<0>( reducers )[token]( arg ));\n } else if (std::get<2>( reducers ).count(token)) {\n \n auto arg1 = active.pop(); // throw on failure, or whatever\n auto arg2 = active.pop(); // throw on failure, or whatever\n active.push( std::get<1>( reducers )[token]( arg1, arg2 ));\n }\n}\n</code></pre>\n<p>maybe throw in some special code to handle variables and constants.</p>\n<p>Now we imaging keeping a buffer of <strong>2</strong> tokens at a time. Then building a map that maps <code>std::tuple<std::string, std::string></code> to 0, 1, 2, or 3 ary reducers.</p>\n<p>We then build <strong>every one</strong> of those pairs of reducers from our primitives as the start of this answer.</p>\n<p>Then we go to every set of 3.</p>\n<p>The shorter patterns still exit; if we don't spot the 3 pattern, we try the 2 pattern on the first 2, then the individual pattern on the first, then we add another token and try the 3 pattern. Etc.</p>\n<p>Now, instead of using a <code>std::function</code> on every step, we only call one every 2 or 3 steps. This happens at the cost of exponentially (literally) larger program code, so the trade off eventually fails to generate speed.</p>\n<p>Compiling also gets more expensive.</p>\n<p>More intelligent reductions can be done as well; like knowing that <code>1+2</code> is the constant <code>3</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T13:08:55.883",
"Id": "510951",
"Score": "0",
"body": "I see where you are going. I do think that any optimization like constant folding should be done in a step before `build_function()`. And instead of trying to match arbitrary n-ary reducers at `build_function()` time, maybe it would be better to just define useful n-ary operations, and specify them explicitly in the RPN input. For example, `1 2 x FMA` as input would push `1`, `2` and the value of `x` to the stack, and then the token `FMA` will call a ternary operator that will then evaluate `1 + 2 * x`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T15:22:03.797",
"Id": "510955",
"Score": "0",
"body": "@g.st Sure, but that requires hand writing both the reducer *and* the function in the script. My system permits generating an exponentially large number of reducers from linear code, and lets the script writer write code and not be forced to kniw exponentially many optimized compound functions. What more, you can take fixed code and tweak compiler settings. As an example, imagine using this for a ROM interpreter (nary bytecode). You can even use the above to do real JIT (ship compiler and code, sanitize script, feed it to constexpr version, load resulting dll). The rabbit hole doesn;t stop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T01:15:53.783",
"Id": "510999",
"Score": "0",
"body": "Doesn’t C++20 do away with trivial deduction guides like `binop(Op,Lhs,Rhs)->binop<Op,Lhs,Rhs>`?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T05:01:07.657",
"Id": "259108",
"ParentId": "259045",
"Score": "2"
}
},
{
"body": "<p>I will not try to investigate all different kinds of alternatives, but just try to illuminate what your implementation does.</p>\n<p>Your code is definitely fine for a quick implementation of something. I have seen code similar to this in production.</p>\n<p>What you are doing is essentially to create a tree representation of the expression but in such a way that it only allows to evaluate it and not to inspect the tree in any other way. If you create a <code>std::function</code> from a lambda, it needs to contain the lambda (i.e. its bound variables), and in general this will have to be in memory allocated on the heap. A good <code>std::function</code> implementation will likely have some small object optimization, so that the lambda can be stored directly in the <code>std::function</code> if it is small enough, but you know that you definitely exceed this size of your lambda has captured a <code>std::function</code> by value, because a <code>std::function</code> cannot possibly fit directly into a <code>std::function</code>. So what you end up with is not dissimilar to what you would get with</p>\n<pre><code>class Expr {\n public:\n virtual double evaluate(double x_val) const = 0;\n\n virtual ~Expr() = default;\n};\nusing ExprPtr = std::unique_ptr<Expr>;\n</code></pre>\n<p>and then for example</p>\n<pre><code>class PlusExpr final : public Expr {\n const ExprPtr<Expr> lhs;\n const ExprPtr<Expr> rhs;\npublic:\n PlusExpr(ExprPtr lhs, ExprPtr rhs)\n :lhs(std::move(lhs)), rhs(std::move(rhs)) {}\n double evaluate(double x_val) const override\n {\n return lhs->evaluate(x_val) + rhs->evaluate(x_val);\n }\n};\n</code></pre>\n<p>Note that I had to make some decisions here. The <code>Expr</code> class cannot be copied (that would have been extra work), so it needs to be used together with pointers. On the other hand, this yields some clarity. Do we really want to copy these expression trees? With the above setup I would have to use something like</p>\n<pre><code> std::vector<ExprPtr> subexpressions;\n ...\n } else if (token == "+") { // Example binary operator\n if (subexpressions.size() < 2) {\n throw std::runtime_error("invalid expression");\n }\n\n auto right_operand = std::move(subexpressions.back());\n subexpressions.pop_back();\n auto left_operand = std::move(subexpressions.back());\n subexpressions.pop_back();\n\n subexpressions.emplace_back(\n new PlusExpr(std::move(left_operand), std::move(right_operand)));\n } else ...\n</code></pre>\n<p>Now all of this is a bit more cumbersome, so for a quick solution <code>std::function</code>s are definitely nice. This points us to something else however. Your code copied the <code>std::function</code>s of the subexpressions at that point (when you captured them by value) and the cost was somehow hidden, because <code>std::function</code>s look so harmless. Indeed if you try your code on input like</p>\n<pre><code>0 1 + 1 + 1 + 1 + ... 1 +\n</code></pre>\n<p>you should notice that the cost of <code>build_function</code> is quadratic in the size of the input. You can of course fix that by also moving the subexpressions into the lambda instead of copying them.</p>\n<p>The cost of evaluation an expression should be very similar for both approaches. There are subtle differences, but I could not tell which will come out in front.</p>\n<p>Another advantage of the class based approach is that it can be extended to support more functionality than just evaluation. You could add a function to print the expression, or one could have functions modifying the expression, say for having an optimization pass that folded constants like another answer mentioned.</p>\n<p>In summary, your approach has its place, but you should be aware that you <strong>are</strong> really constructing an expression tree in disguise and beware of costs hidden by the convenience of <code>std::function</code>s.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T12:43:28.373",
"Id": "510948",
"Score": "0",
"body": "I was aware that my implementation basically builds a tree of expressions at runtime, but thanks for this excellent explaination, as well as pointing out the problem with the quadratic cost of `build_function()` due to copying `std::function`s."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T13:02:23.700",
"Id": "510950",
"Score": "1",
"body": "@G.Sliepen, I could probably have been briefer then ;) Well, it may be useful to someone else this way."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T11:49:10.487",
"Id": "259117",
"ParentId": "259045",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "259056",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T13:19:24.680",
"Id": "259045",
"Score": "25",
"Tags": [
"c++",
"performance",
"parsing",
"calculator",
"lambda"
],
"Title": "Poor man's JIT using nested lambdas"
}
|
259045
|
<p>I implemented tic-tac-toe in Haskell. I'm trying to incorporate suggestions from my <a href="https://codereview.stackexchange.com/questions/258789/connect-four-winner-checking-algorithm">last question</a> (which mostly revolved around algorithmic logic) while trying something new - IO logic.</p>
<p>What kind of improvements could I make to this program? Am I being too tricky anywhere? Are there some built-in library functions that I could use to simplify the logic?</p>
<p><strong>Model.hs</strong></p>
<pre class="lang-hs prettyprint-override"><code>module Model (doTurn, getWinner, initialState, isVacant, State(..), Board, Player(..), Winner(..)) where
import Data.List (transpose)
import Safe (atMay)
import Data.Maybe (isJust, isNothing, catMaybes)
import Control.Monad (join)
data Player = X | O deriving (Eq)
data Winner = XWins | OWins | CatScratch
type Board = [[Maybe Player]]
data State = State
{
boardState :: Board,
turnState :: Player
}
opponentOf :: Player -> Player
opponentOf X = O
opponentOf O = X
diagonal :: [[a]] -> [a]
diagonal board =
catMaybes $ zipWith atMay board [0..]
replaceAt :: (a -> a) -> Int -> [a] -> [a]
replaceAt updateFn index array =
case splitAt index array of
(left, val:right) -> left ++ [updateFn val] ++ right
_ -> array
isVacant :: (Int, Int) -> Board -> Bool
isVacant (x, y) board =
isNothing $ join $ (`atMay` x) =<< (`atMay` y) board
placeInBoard :: (Int, Int) -> Maybe Player -> Board -> Board
placeInBoard (x, y) =
(`replaceAt` y) . (`replaceAt` x) . const
isPlayerWinner :: Player -> Board -> Bool
isPlayerWinner player board =
(any . all) (Just player ==) $
board ++
transpose board ++
map diagonal [board, transpose board]
isCatScratch :: Board -> Bool
isCatScratch =
(all . all) isJust
getWinner :: Board -> Maybe Winner
getWinner board
| isPlayerWinner X board = Just XWins
| isPlayerWinner O board = Just OWins
| isCatScratch board = Just CatScratch
| otherwise = Nothing
doTurn :: State -> (Int, Int) -> State
doTurn state coord =
State {
boardState = placeInBoard coord (Just $ turnState state) (boardState state),
turnState = opponentOf (turnState state)
}
initialState :: Player -> State
initialState firstPlayer =
State {
boardState = replicate 3 (replicate 3 Nothing),
turnState = firstPlayer
}
</code></pre>
<p><strong>View.hs</strong></p>
<pre class="lang-hs prettyprint-override"><code>module View (renderBoard, currentPlayerText, parseAsCoord, winnerText) where
import Data.List (intercalate, intersperse)
import Data.Char (toUpper)
import Model (Board, Player(X, O), Winner(XWins, OWins, CatScratch))
surround :: a -> [a] -> [a]
surround value array = [value] ++ intersperse value array ++ [value]
renderCell :: Maybe Player -> String
renderCell (Just X) = "X"
renderCell (Just O) = "O"
renderCell Nothing = " "
renderBoard :: Board -> String
renderBoard =
let
header = " A B C "
divider = " -----+-----+-----"
padding = " | | "
renderRow :: Int -> [Maybe Player] -> String
renderRow n = intercalate "" . (++) [show n] . surround " " . intersperse "|" . map renderCell
in
unlines . (++) [header] . surround padding . intersperse divider . zipWith renderRow [1..]
parseAsCoord :: String -> Maybe (Int, Int)
parseAsCoord [number, letter] =
let
maybeX = case toUpper letter of { 'A' -> Just 0; 'B' -> Just 1; 'C' -> Just 2; _ -> Nothing }
maybeY = case number of { '1' -> Just 0; '2' -> Just 1; '3' -> Just 2; _ -> Nothing }
in case (maybeX, maybeY) of
(Just x, Just y) -> Just (x, y)
_ -> Nothing
parseAsCoord _ = Nothing
currentPlayerText :: Player -> String
currentPlayerText X = "It's X's turn"
currentPlayerText O = "It's O's turn"
winnerText :: Winner -> String
winnerText XWins = "X Wins!"
winnerText OWins = "O Wins!"
winnerText CatScratch = "Cat Scratch!"
</code></pre>
<p><strong>Main.hs</strong></p>
<pre><code>import System.IO (hFlush, stdout)
import System.Random (randomIO)
import Model (initialState, doTurn, getWinner, isVacant, Player(X, O), State(boardState, turnState))
import View (renderBoard, currentPlayerText, parseAsCoord, winnerText)
prompt :: String -> IO String
prompt msg = do
putStr msg >> hFlush stdout
getLine
promptForVacantCoord :: State -> IO (Int, Int)
promptForVacantCoord state = do
userInput <- prompt "Pick a spot (e.g. 2B): "
case parseAsCoord userInput of
Just coord | isVacant coord (boardState state) -> return coord
_ -> putStrLn "Invalid input" >> promptForVacantCoord state
step :: State -> IO ()
step state = do
putStrLn ""
putStrLn $ renderBoard $ boardState state
case getWinner (boardState state) of
Just winner -> putStrLn (winnerText winner)
Nothing -> do
putStrLn $ currentPlayerText (turnState state)
coord <- promptForVacantCoord state
step $ doTurn state coord
main :: IO ()
main =
let
playerFromBool True = X
playerFromBool False = O
in
step . initialState . playerFromBool =<< randomIO
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T18:15:50.457",
"Id": "510912",
"Score": "0",
"body": "One observation is that you are using Maybe a lot, but `do` only for IO. I wonder if the whole winner-checking can be done in one `do` without heavy handling of nested lists... (this is not an advice, as I am not sure it is really better)."
}
] |
[
{
"body": "<p>Once again your code is very good, most of what I've got is just dotting ıs and crossing ɭ s so I'll probably end up showing off cool stuff more than providing critical feedback.</p>\n<p>I'd define <code>Winner</code> as <code>Winner Player | CatScratch</code>, you've already got a perfectly good <code>X</code> and <code>O</code> already.</p>\n<p>I'd also graduate up to using a full-fledged <code>Array</code> for the boards, they're super tiny and not appreciably less efficient than lists, especially for a 3x3 grid. And the affordances a nice API gives you... hoo, good stuff.</p>\n<pre><code>type Coordinate = (Int, Int)\ntype Board = Array Coordinate (Maybe Player)\n\nemptyBoard :: Board\nemptyBoard = listArray ((0, 0), (2, 2)) $ repeat Nothing\n\nplaceInBoard :: Coordinate -> Player -> Board -> Board\nplaceInBoard coord player board = board // [(coord, player)]\n</code></pre>\n<p>You can add any error checking you'd like also, maybe you'd have the function return an <code>Either TicTacTerror Board</code> with a custom error type that tells you whether it's a <code>data TicTacTerror = CoordinateOutOfBounds | CoordinateOccupied</code>. Or you could, y'know, use a String. That's cool too I guess, even if I don't get to make a pun... In general I think it's better to try an operation and then fail gracefully, rather than to validate and then attempt the operation. That's more commonly something said about parsing in Haskell, but it's also important for e.g., concurrent contexts. It's a good habit.</p>\n<p>The terse row, column and diagonal checking <em>is</em> a loss, but you can approximate it without overly much effort.</p>\n<pre><code>rows :: (Ix i, Ix j) => Array (i, j) e -> [[e]]\nrows = map (snd . unzip) . groupBy ((==) `on` (\\((x, _y), _e) -> x)) . assocs\n\ntranspose :: (Ix i, Ix j) => Array (i, j) e -> Array (j, i) e\ntranspose arr = ixmap (bimap swap swap $ bounds arr) swap arr\n\ncolumns :: (Ix i, Ix j) => Array (i, j) e -> [[e]]\ncolumns = rows . transpose\n\ndiagonal :: (Ix i, Ix j) => Array (i, j) e -> [e]\ndiagonal arr = [arr ! ix | ix <- zip (range (i0, iN)) (range (j0, jN))]\n where ((i0, j0), (iN, jN)) = bounds arr\n\nmirror :: (Ix i, Ix j, Enum i, Enum j) => Array (i, j) e -> Array (i, j) e\nmirror arr = ixmap (bounds arr) dirtyReflection arr\n where\n ((i0, _), (iN, _)) = bounds arr\n dirtyReflection (i, j) = (fromJust $ lookup i table, j)\n where table = zip (range (i0, iN)) (reverse $ range (i0, iN))\n\nticTacToes :: Board -> [[Maybe Player]]\nticTacToes board = rows board ++ columns board ++ [diagonal board, diagonal $ mirror board]\n</code></pre>\n<p>Here's the first version I hacked together, in case it might be illustrative of my process. (Hidden because one doesn't air one's dirty laundry in public.)</p>\n<blockquote class=\"spoiler\">\n<p> <pre><code>toeLines :: Board -> [[Maybe Player]]\ntoeLines board = rows board ++ columns board ++ [diagonal board, diagonal $ mirror board]\n where\n bnds@((x0, _y0), (_xN, yN)) = bounds board\n rows = map (map snd) . groupBy ((==) <code>on</code> (fst . fst)) . assocs\n transpose a = ixmap (bounds a) swap a\n diagonal a = [a ! (i, i) | i <- [x0 .. yN]]\n reverseDiagonal a = [a ! (i, j) | (i, j) <- indices a, i + j == x0 + yN]</code></pre></p>\n</blockquote>\n<p>Now you can golf down the win-checking a bit. The change to the <code>Winner</code> datatype I made earlier comes into play, you're going to have to add some deriving clauses (and imports, for that matter) that I've just glossed over. If you can't find where something comes from, try <a href=\"https://hoogle.haskell.org\" rel=\"nofollow noreferrer\">Hoogle</a>.</p>\n<pre><code>allSame :: Eq a => [a] -> Bool\nallSame [] = False\nallSame (x:xs) = all (x ==) xs\n\nassessLine :: [Maybe Player] -> Maybe Player\nassessLine line | Nothing `notElem` line && allSame line = join $ listToMaybe line\n | otherwise = Nothing\n\ngetWinner :: Board -> Maybe Winner\ngetWinner board = Winner <$> listToMaybe (mapMaybe assessLine (ticTacToes board))\n <|> if all isJust (elems board) then Just CatScratch else Nothing\n</code></pre>\n<p>And the original version—</p>\n<blockquote class=\"spoiler\">\n<p> <pre><code>getWinner :: Board -> Maybe Winner\ngetWinner board =\n let mWinner = Winner <$> find (\\row@(x:_) -> all (== x) row && isJust x) (toeLines board)\n mCatScratch = if all isJust (elems board) then Just CatScratch else Nothing\n in mWinner <|> mCatScratch</code></pre></p>\n</blockquote>\n<p>This is a slight algorithmic improvement, but mostly it gets back to the “don’t validate a thing, do a thing” line I was on before.</p>\n<p>The rest of the changes to your model code should be straightforward.</p>\n<p>For your view code, after you've adapted it to the <code>Array</code> model it's best to just abandon gluing <code>String</code>s together entirely and grab a pretty printer library, like “<a href=\"https://hackage.haskell.org/package/boxes\" rel=\"nofollow noreferrer\">boxes</a>”. If you've never seen a pretty printing combinator library before, the general idea is to build a view for each kind of element you're displaying, then specify how you glue them together into larger elements, and eventually you have a function that takes your data structure and replaces all of the constructors with printing functions. I'm sure an example will help to make it clear.</p>\n<pre><code>player :: Maybe Player -> Box\nplayer (Just X) = char 'X'\nplayer (Just O) = char 'O'\nplayer Nothing = char ' '\n\ncell :: Maybe Player -> Box\ncell = align center1 center1 3 3 . player\n\nrow :: [Maybe Player] -> Box\nrow players = punctuateH center1 vertBar $ map cell players\n where vertBar = vcat top $ replicate 3 (char '|')\n\nboard :: Board -> Box\nboard arr = punctuateV center1 horizBar $ map row (rows arr)\n where horizBar = hcat left $ replicate 9 (char '-')\n</code></pre>\n<p>Play around with it in the REPL and you'll see what's going on pretty quickly. There are <em>tons</em> of pretty printer libraries, pick your favorite.</p>\n<p>As for your main module, it looks pretty good. You might want to explore building a TUI with “<a href=\"https://hackage.haskell.org/package/brick\" rel=\"nofollow noreferrer\">brick</a>” as a next step. It has an even more expressive layout system, and a lot of fun challenges to cut your teeth on.</p>\n<p>Some other random observances—</p>\n<ul>\n<li>Section operators like <code>(++)</code> inline, there's no need to prefix them. E.g. <code>([value] ++)</code> is equivalent to <code>(++) [value]</code> and less indirect.</li>\n<li>You can make <code>Player</code> an instance of <code>Random</code> or the new <code>Uniform</code> to hide the indirection of going through another type.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T08:34:46.893",
"Id": "259347",
"ParentId": "259047",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259347",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T13:50:43.283",
"Id": "259047",
"Score": "1",
"Tags": [
"haskell",
"functional-programming"
],
"Title": "Tic Tac Toe (Haskell)"
}
|
259047
|
<p>Solving the merge intervals problem in golang(link: <a href="https://leetcode.com/problems/merge-intervals/" rel="nofollow noreferrer">https://leetcode.com/problems/merge-intervals/</a>).</p>
<p><strong>The Problem</strong></p>
<pre><code>Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
Example 1:
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2:
Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
</code></pre>
<p><strong>Code</strong></p>
<pre><code>package main
import (
"fmt"
"sort"
)
func main() {
var intervals [][]int
intervals = append(intervals, []int{7, 10})
intervals = append(intervals, []int{3, 4})
intervals = append(intervals, []int{2, 5})
mergeIntervals(intervals)
}
func mergeIntervals(intervals [][]int) [][]int {
if len(intervals) < 2{
return intervals
}
var mergedIntervals [][]int
fmt.Println("intervals :", intervals)
sort.Slice(intervals, func(i, j int) bool {
return intervals[i][0] < intervals[j][0]
})
previousEndTime := intervals[0][1]
for index, _ := range intervals {
if index >= len(intervals)-1 {
if index == len(intervals)-1 {
mergedIntervals = append(mergedIntervals, []int{intervals[index][0], intervals[index][1]})
}
break
}
if index != 0 {
//skip current interval if previous interval end time is higher
if previousEndTime > intervals[index][1] {
continue
}
}
fmt.Println("comparing intervals ", intervals[index], "and ", intervals[index+1])
if intervals[index][1] > intervals[index+1][1] {
//check if current end time greater than end time of next interval
mergedIntervals = append(mergedIntervals, []int{intervals[index][0], intervals[index][1]})
previousEndTime = intervals[index][1]
} else if intervals[index][1] >= intervals[index+1][0] {
//the actual merge for overlapping values
mergedIntervals = append(mergedIntervals, []int{intervals[index][0], intervals[index+1][1]})
previousEndTime = intervals[index+1][1]
} else {
//just include current interval with no overlap
mergedIntervals = append(mergedIntervals, []int{intervals[index][0], intervals[index][1]})
previousEndTime = intervals[index][1]
}
}
fmt.Println("merged intervals ", mergedIntervals)
return mergedIntervals
}
</code></pre>
<p><strong>Looking for</strong></p>
<ul>
<li>Code Bugs.</li>
<li>Feel this code is too verbose.Any suggestions on how to optimize
the code further.</li>
</ul>
|
[] |
[
{
"body": "<p>Your code appears to fail on:</p>\n<blockquote>\n<pre><code>Example 1:\n\nInput: intervals = [[1,3],[2,6],[8,10],[15,18]]\nOutput: [[1,6],[8,10],[15,18]]\nExplanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].\n</code></pre>\n</blockquote>\n<p>Output:</p>\n<pre><code>intervals : [[1 3] [2 6] [8 10] [15 18]]\ncomparing intervals [1 3] and [2 6]\ncomparing intervals [2 6] and [8 10]\ncomparing intervals [8 10] and [15 18]\nmerged intervals [[1 6] [2 6] [8 10] [15 18]]\n</code></pre>\n<hr />\n<p>Try to simplify your code to make it more readable. For example,</p>\n<pre><code>package main\n\nimport (\n "fmt"\n "sort"\n)\n\nfunc merge(intervals [][]int) [][]int {\n const start, end = 0, 1\n\n var merged [][]int\n\n if len(intervals) > 1 {\n sort.Slice(intervals, func(i, j int) bool {\n return intervals[i][start] < intervals[j][start]\n })\n }\n\n for _, interval := range intervals {\n last := len(merged) - 1\n if last < 0 || interval[start] > merged[last][end] {\n merged = append(merged,\n []int{start: interval[start], end: interval[end]},\n )\n } else if interval[end] > merged[last][end] {\n merged[last][end] = interval[end]\n }\n }\n\n return merged[:len(merged):len(merged)]\n}\n\nfunc main() {\n tests := []struct {\n intervals [][]int\n }{\n {[][]int{{1, 3}, {2, 6}, {8, 10}, {15, 18}}},\n {[][]int{{1, 4}, {4, 5}}},\n {[][]int{{1, 2}}},\n {[][]int{}},\n {[][]int{{7, 10}, {3, 4}, {2, 5}}},\n }\n\n for _, tt := range tests {\n fmt.Print(tt.intervals)\n fmt.Println(" ->", merge(tt.intervals))\n }\n}\n</code></pre>\n<p>Playground: <a href=\"https://play.golang.org/p/Akgsws42JfX\" rel=\"nofollow noreferrer\">https://play.golang.org/p/Akgsws42JfX</a></p>\n<p>Output:</p>\n<pre><code>[[1 3] [2 6] [8 10] [15 18]] -> [[1 6] [8 10] [15 18]]\n[[1 4] [4 5]] -> [[1 5]]\n[[1 2]] -> [[1 2]]\n[] -> []\n[[7 10] [3 4] [2 5]] -> [[2 5] [7 10]]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T06:20:19.307",
"Id": "259067",
"ParentId": "259048",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "259067",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T14:26:20.937",
"Id": "259048",
"Score": "1",
"Tags": [
"go"
],
"Title": "Merge Intervals(Golang)"
}
|
259048
|
<p>I'm just here for suggestions and code optimisations, what i could've done better, are there any better coding practices...
There's github repo link if you're interested in the code with a form too <a href="https://github.com/throtz/Operators" rel="nofollow noreferrer">https://github.com/throtz/Operators</a>
You basically have 2 textboxes in which you enter numbers and choose with a combobox what you want to do with those two numbers.</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Windows.Forms;
namespace Operators
{
public partial class Operators : Form
{
public Operators()
{
InitializeComponent();
}
private void Form1_Load_1(object sender, EventArgs e)
{
comboBox.Items.AddRange(new string[] { "+", "-", "*", "/", "%", ">", "<", "=", ">=", "<=" });
}
private void ButtonCheck_Click_1(object sender, EventArgs e)
{
if (sender is null)
{
throw new ArgumentNullException(nameof(sender));
}
int a = Convert.ToInt32(textBox1.Text);
int b = Convert.ToInt32(textBox2.Text);
Nah(a, b);
}
private void Nah(int a, int b)
{
switch (comboBox.SelectedItem.ToString())
{
case "+":
MessageBox.Show("Sum of thenumbers entered is: " + (a + b));
break;
case "-":
MessageBox.Show("Subtraction of the numbers entered is: " + (a - b));
break;
case "*":
MessageBox.Show("Multiplication of the numbers entered is: " + (a * b));
break;
case "/":
MessageBox.Show("Division of the numbers entered is: " + (a / b));
break;
case "%":
MessageBox.Show("Modulo the two numbers is: " + (a % b));
break;
case ">":
MessageBox.Show("First number is bigger than the secound one " + (a > b));
break;
case "<":
MessageBox.Show("First number is smaller than the secound one " + (a < b));
break;
case "=":
MessageBox.Show("Numbers are equal: " + (a == b));
break;
case ">=":
MessageBox.Show("First number is bigger or equal to number two " + (a >= b));
break;
case "<=":
MessageBox.Show("First number is smaller or equal to number two " + (a <= b));
break;
default:
MessageBox.Show("Illegal operation.");
break;
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<h2>Review</h2>\n<p>It seems that you are trying to make a simple calculator with number comparison in C#. There are some problems in this implementation.</p>\n<h3><code>ToInt32</code>:</h3>\n<p>Do you expect the input of calculation is always in <code>int</code> format? How\nabout floating numbers?</p>\n<h3><code>Nah</code> method:</h3>\n<ul>\n<li><p><strong>Naming</strong>:</p>\n<p>I have no idea how's the name <code>Nah</code> imply the operation in the method. Something like <code>run</code> or <code>perform</code> are better than <code>Nah</code>.</p>\n</li>\n<li><p><strong>Integer Division</strong>:</p>\n<p>Notice that the execution of <code>3 / 2</code> in this implementation is <code>1</code>.\nIt is a kind of <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/arithmetic-operators#integer-division\" rel=\"nofollow noreferrer\">integer division</a>. Is the integer division result\nthe correct output you expected?</p>\n</li>\n<li><p><strong><code>MessageBox.Show</code> Part</strong>:</p>\n<p>In C# 6, you can use <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated\" rel=\"nofollow noreferrer\">string interpolation</a> and make <code>MessageBox.Show("Sum of thenumbers entered is: " + (a + b));</code> into <code>MessageBox.Show($"Sum of thenumbers entered is: {(a + b)}");</code>. Interpolated strings are useful in string displaying and it's commonly used with <code>Console.WriteLine</code> or <code>MessageBox.Show</code>.</p>\n</li>\n</ul>\n<h3>Error Handling</h3>\n<ul>\n<li><p>Null or empty string:</p>\n<p>You use <code>textBox1.Text</code> and <code>textBox2.Text</code> as a way to read numbers from user input. How about the case of empty strings (user click button <code>Check</code> directly without type any character)? If <code>textBox.Text</code> passes in <code>Convert.ToInt32</code> directly and the content is empty, <code>System.FormatException</code> will occur. Maybe <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.string.isnullorempty?view=net-5.0\" rel=\"nofollow noreferrer\"><code>String.IsNullOrEmpty</code></a> check can be used here.</p>\n</li>\n<li><p><a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.dividebyzeroexception?view=net-5.0\" rel=\"nofollow noreferrer\">DivideByZeroException</a></p>\n<p>DivideByZeroException Class can be used to handle an attempt to divide an number by zero.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T23:03:36.527",
"Id": "259057",
"ParentId": "259053",
"Score": "2"
}
},
{
"body": "<ul>\n<li><p>I would suggest moving your <code>new string[] { "+", "-", "*", "/", "%", ">", "<", "=", ">=", "<=" }</code> into a global <code>private readonly</code>\nvariable. because it's a requirement in your class, and current\napproach will <code>hide</code> this requirement from the human-eye.</p>\n<p>class requirement should always be visible, and readable to the\nhuman-eye such as declaring variables, fields at the top of the\nclass. It would make it easier to approach and modify.</p>\n</li>\n<li><p><code>Convert.ToInt32</code> it would be fine if you know that the stored string is always a valid <code>int</code>, however, it would much better to use <code>int.TryParse</code> or better yet using <code>Decimal.TryParse</code> to validate the string, and avoid any parsing exceptions.</p>\n</li>\n<li><p><code>Nah(int a, int b)</code> not following the appropriate naming convention, always pick a good name to your variables, methods, and classes that describes their role and actions.</p>\n</li>\n<li><p><code>Nah(int a, int b)</code> is mixing two roles (calculate and show message), you should separate them.</p>\n</li>\n</ul>\n<p>Another way of doing this is to convert the operators into objects by creating a class that would describe these operators, and another class to hold the process of these operators.</p>\n<p>Here is a quick example :</p>\n<pre><code>public class OperatorSign\n{\n public string Sign { get; }\n\n public string Name { get; }\n\n public OperatorSign(string sign , string name)\n {\n Sign = sign;\n Name = name;\n }\n}\n\npublic class MathOperation\n{\n public OperatorSign Operator { get; private set; }\n\n public int Total { get; private set; }\n\n public MathOperation(OperatorSign sign)\n {\n Operator = sign;\n }\n\n public void Calculate(int numberX , int numberY)\n {\n switch(Operator.Sign)\n {\n case "+":\n Total = numberX + numberY;\n break;\n case "-":\n Total = numberX - numberY;\n break;\n case "*":\n Total = numberX * numberY;\n break;\n default:\n return; //do nothing.\n }\n }\n\n public override string ToString()\n {\n return $"{Operator.Name} of the numbers entered is: {Total}";\n }\n}\n</code></pre>\n<p>Now using these, we can do this :</p>\n<pre><code>public partial class Operators : Form\n{\n private readonly OperatorSign[] _operatorSigns = new OperatorSign[]\n {\n new OperatorSign("+", "Sum"),\n new OperatorSign("-", "Subtraction"),\n new OperatorSign("*", "Multiplication")\n };\n\n public Operators()\n {\n InitializeComponent();\n }\n \n private void Form1_Load_1(object sender, EventArgs e)\n { \n comboBox.Items.AddRange(_operatorSigns.Select(x=> x.Sign));\n }\n \n private void ButtonCheck_Click_1(object sender, EventArgs e)\n {\n if (sender is null)\n {\n throw new ArgumentNullException(nameof(sender));\n }\n\n if(!int.TryParse(textBox1.Text, out int a))\n {\n MessageBox.Show("Invalid Number");\n }\n else if(!int.TryParse(textBox2.Text, out int b))\n {\n MessageBox.Show("Invalid Number");\n }\n else\n {\n var selectedSign = comboBox.SelectedItem.ToString();\n \n var sign = _operatorSigns.FirstOrDefault(s => s.Sign.Equals(selectedSign));\n\n if(sign == null)\n {\n MessageBox.Show("Invalid Operator");\n }\n else \n {\n var mathOp = new MathOperation(sign);\n\n mathOp.Calculate(x , y);\n\n var resultMessage = mathOp.ToString();\n \n MessageBox.Show(resultMessage);\n \n }\n }\n }\n \n}\n</code></pre>\n<p>Now you can extend the operators such as adding more handlers and more rules to each sign without touching the form class itself (presentation layer). You can also take advantage of class inheritance or <code>delegate</code> and <code>Expression</code> to keep your code much prettier.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T23:42:29.393",
"Id": "259059",
"ParentId": "259053",
"Score": "1"
}
},
{
"body": "<p>On the user's side, there is more interaction needed than strictly necessary. You could remove the button and provide a "live update" whenever one of the numbers or the operator changes. This makes interaction with your example quicker and smoother as you avoid a change of the active window.</p>\n<p>Instead of <code>MessageBox.Show</code> you could simply update <code>ResultLabel.Text</code>. This way you get rid of the many repetitions of <code>MessageBox.Show</code>. Another benefit is that if you extract the generation of the result text into a separate method, you don't need the <code>break</code> statements anymore. Something like this:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>string GenerateResult(int a, string op, int b)\n{\n switch (op) {\n case "+": return $"The sum of {a} and {b} is {a + b}";\n case "-": return $"The difference between {a} and {b} is {a - b}";\n ...\n }\n}\n</code></pre>\n<p>In <code>ButtonCheck_Click_1</code>, you don't need to check whether <code>sender</code> is null since you don't use that variable afterwards.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T23:50:09.140",
"Id": "259060",
"ParentId": "259053",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T18:58:22.607",
"Id": "259053",
"Score": "0",
"Tags": [
"c#"
],
"Title": "Statement checker c# using forms and frontend"
}
|
259053
|
<p>I'm learning to code for about a year and recently I finished my Javascript project. It contains of 11 fairly simple apps involving using APIs and DOM manipulations</p>
<p><strong><a href="https://github.com/matt765/js" rel="nofollow noreferrer">https://github.com/matt765/js</a></strong></p>
<p>it's live here <a href="https://www.blackravenstudio.net/javascript/" rel="nofollow noreferrer">https://www.blackravenstudio.net/javascript/</a></p>
<p>I would gladly hear any opinions on my code. Next project I plan to do in React, propably some more complex stuff</p>
<p>Code below is first app listed in this project</p>
<pre><code> const cat_result = document.getElementById('cat');
const dog_result = document.getElementById('dog');
const cat_btn = document.getElementById('cat-btn');
const dog_btn = document.getElementById('dog-btn');
cat_btn.addEventListener('click', getRandomCat);
dog_btn.addEventListener('click', getRandomDog);
getRandomCat();
getRandomDog();
function getRandomCat() {
fetch('https://aws.random.cat/meow')
.then(res => res.json())
.then(data => {
cat_result.innerHTML = `<img src="${data.file}" />`;
});
}
function getRandomDog() {
fetch('https://random.dog/woof.json')
.then(res => res.json())
.then(data => {
if (data.url.includes('.mp4')) {
getRandomDog();
} else {
dog_result.innerHTML = `<img src="${data.url}" />`;
}
});
}
</code></pre>
<p>If you are interested in front-end, when you go back to main domain there are few websites that I did just to have them in the portfolio. Code of 2 projects is also available on GitHub</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T20:27:06.843",
"Id": "259054",
"Score": "2",
"Tags": [
"javascript",
"html",
"css"
],
"Title": "Javascript portfolio with 11 small apps"
}
|
259054
|
<p>I start with an hourly table that has around 40 of items (example: bread, barley, bagels, beef, chicken). The purpose of my code is to aggregate this hourly table's numbers to daily numbers but broken out by a sublocation or "type". My only way to allocate to type is to use a table that shows the % breakdown of type to location. This table, however, is at the Monthly day/night (Timeframe) granularity. I solved the problem with a dictionary for each item, but extending this out makes me believe I am doing this inefficiently.</p>
<p>I could use some opinions on how to better organize my code to handle dozens of items. A forewarning that I have never used collections or classes out of ignorance, but I am open to anything.</p>
<p>*note: I converted these tables in markdown format using this <a href="https://tabletomarkdown.com/convert-spreadsheet-to-markdown/" rel="nofollow noreferrer">site</a></p>
<p><strong>Hourly Table Example</strong> (~700,000 rows, ~40 columns to aggregate) <Pasted into <strong>B5</strong>></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Day</th>
<th>Location</th>
<th>Hour</th>
<th>Timeframe</th>
<th>bread</th>
<th>barley</th>
<th>bagels</th>
<th>beef</th>
<th>chicken</th>
</tr>
</thead>
<tbody>
<tr>
<td>4/1/2021</td>
<td>A</td>
<td>0</td>
<td>night</td>
<td>51</td>
<td>91</td>
<td>12</td>
<td>26</td>
<td>176</td>
</tr>
<tr>
<td>4/1/2021</td>
<td>A</td>
<td>1</td>
<td>night</td>
<td>51</td>
<td>24</td>
<td>4</td>
<td>43</td>
<td>17</td>
</tr>
<tr>
<td>4/1/2021</td>
<td>A</td>
<td>8</td>
<td>day</td>
<td>25</td>
<td>84</td>
<td>5</td>
<td>72</td>
<td>125</td>
</tr>
<tr>
<td>4/1/2021</td>
<td>A</td>
<td>14</td>
<td>day</td>
<td>32</td>
<td>10</td>
<td>7</td>
<td>7</td>
<td>166</td>
</tr>
<tr>
<td>4/2/2021</td>
<td>A</td>
<td>0</td>
<td>night</td>
<td>31</td>
<td>29</td>
<td>11</td>
<td>49</td>
<td>5</td>
</tr>
<tr>
<td>4/2/2021</td>
<td>A</td>
<td>1</td>
<td>night</td>
<td>25</td>
<td>25</td>
<td>3</td>
<td>40</td>
<td>175</td>
</tr>
<tr>
<td>4/2/2021</td>
<td>A</td>
<td>8</td>
<td>day</td>
<td>70</td>
<td>81</td>
<td>6</td>
<td>69</td>
<td>89</td>
</tr>
<tr>
<td>4/2/2021</td>
<td>A</td>
<td>14</td>
<td>day</td>
<td>83</td>
<td>45</td>
<td>2</td>
<td>9</td>
<td>141</td>
</tr>
<tr>
<td>4/1/2021</td>
<td>B</td>
<td>0</td>
<td>night</td>
<td>55</td>
<td>37</td>
<td>8</td>
<td>59</td>
<td>164</td>
</tr>
<tr>
<td>4/1/2021</td>
<td>B</td>
<td>1</td>
<td>night</td>
<td>53</td>
<td>88</td>
<td>12</td>
<td>50</td>
<td>74</td>
</tr>
<tr>
<td>4/1/2021</td>
<td>B</td>
<td>8</td>
<td>day</td>
<td>20</td>
<td>73</td>
<td>1</td>
<td>33</td>
<td>200</td>
</tr>
<tr>
<td>4/1/2021</td>
<td>B</td>
<td>14</td>
<td>day</td>
<td>6</td>
<td>33</td>
<td>7</td>
<td>2</td>
<td>191</td>
</tr>
<tr>
<td>4/2/2021</td>
<td>B</td>
<td>0</td>
<td>night</td>
<td>39</td>
<td>52</td>
<td>4</td>
<td>22</td>
<td>99</td>
</tr>
<tr>
<td>4/2/2021</td>
<td>B</td>
<td>1</td>
<td>night</td>
<td>19</td>
<td>80</td>
<td>6</td>
<td>55</td>
<td>0</td>
</tr>
<tr>
<td>4/2/2021</td>
<td>B</td>
<td>8</td>
<td>day</td>
<td>44</td>
<td>49</td>
<td>10</td>
<td>42</td>
<td>8</td>
</tr>
<tr>
<td>4/2/2021</td>
<td>B</td>
<td>14</td>
<td>day</td>
<td>72</td>
<td>11</td>
<td>3</td>
<td>54</td>
<td>44</td>
</tr>
</tbody>
</table>
</div>
<p>Here is a Monthly table that will be used to breakout daily numbers. There relationship between item-to-multiplier is one-to-many so in this example, bread, barley, and bagels are broken out by multiplier1, while beef and chicken are broken out by multiplier2. These breakouts are actually at the timeframe level so must occur before the day has been aggregated.</p>
<p><strong>BREAKOUT TABLE</strong> Monthly Location with % of total listed by Type+Timeframe <Pasted in <strong>L5</strong>></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Month</th>
<th>Location</th>
<th>type</th>
<th>Timeframe</th>
<th>Multiplier1</th>
<th>Multiplier2</th>
</tr>
</thead>
<tbody>
<tr>
<td>4/1/2021</td>
<td>A</td>
<td>x</td>
<td>day</td>
<td>16%</td>
<td>8%</td>
</tr>
<tr>
<td>4/1/2021</td>
<td>A</td>
<td>y</td>
<td>day</td>
<td>84%</td>
<td>92%</td>
</tr>
<tr>
<td>4/1/2021</td>
<td>A</td>
<td>x</td>
<td>night</td>
<td>33%</td>
<td>25%</td>
</tr>
<tr>
<td>4/1/2021</td>
<td>A</td>
<td>y</td>
<td>night</td>
<td>67%</td>
<td>75%</td>
</tr>
<tr>
<td>4/1/2021</td>
<td>B</td>
<td>x</td>
<td>day</td>
<td>50%</td>
<td>42%</td>
</tr>
<tr>
<td>4/1/2021</td>
<td>B</td>
<td>y</td>
<td>day</td>
<td>50%</td>
<td>58%</td>
</tr>
<tr>
<td>4/1/2021</td>
<td>B</td>
<td>x</td>
<td>night</td>
<td>100%</td>
<td>92%</td>
</tr>
<tr>
<td>4/1/2021</td>
<td>B</td>
<td>y</td>
<td>night</td>
<td>0%</td>
<td>8%</td>
</tr>
<tr>
<td>5/1/2021</td>
<td>A</td>
<td>x</td>
<td>day</td>
<td>26%</td>
<td>17%</td>
</tr>
<tr>
<td>5/1/2021</td>
<td>A</td>
<td>y</td>
<td>day</td>
<td>74%</td>
<td>83%</td>
</tr>
<tr>
<td>5/1/2021</td>
<td>A</td>
<td>x</td>
<td>night</td>
<td>51%</td>
<td>43%</td>
</tr>
<tr>
<td>5/1/2021</td>
<td>A</td>
<td>y</td>
<td>night</td>
<td>49%</td>
<td>57%</td>
</tr>
<tr>
<td>5/1/2021</td>
<td>B</td>
<td>x</td>
<td>day</td>
<td>1%</td>
<td>4%</td>
</tr>
<tr>
<td>5/1/2021</td>
<td>B</td>
<td>y</td>
<td>day</td>
<td>99%</td>
<td>96%</td>
</tr>
<tr>
<td>5/1/2021</td>
<td>B</td>
<td>x</td>
<td>night</td>
<td>2%</td>
<td>5%</td>
</tr>
<tr>
<td>5/1/2021</td>
<td>B</td>
<td>y</td>
<td>night</td>
<td>98%</td>
<td>95%</td>
</tr>
</tbody>
</table>
</div>
<p>Here is the resulting intended table:</p>
<p><strong>DAILY TABLE</strong> Day+Location+Type <Pasted in <strong>S5</strong>></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Day</th>
<th>Location</th>
<th>type</th>
<th>bread</th>
<th>barley</th>
<th>bagels</th>
<th>beef</th>
<th>chicken</th>
</tr>
</thead>
<tbody>
<tr>
<td>4/1/2021</td>
<td>A</td>
<td>x</td>
<td>42.78</td>
<td>52.99</td>
<td>7.2</td>
<td>23.57</td>
<td>71.53</td>
</tr>
<tr>
<td>4/2/2021</td>
<td>A</td>
<td>x</td>
<td>42.96</td>
<td>37.98</td>
<td>5.9</td>
<td>28.49</td>
<td>63.4</td>
</tr>
<tr>
<td>4/1/2021</td>
<td>B</td>
<td>x</td>
<td>121</td>
<td>178</td>
<td>24</td>
<td>114.98</td>
<td>383.18</td>
</tr>
<tr>
<td>4/2/2021</td>
<td>B</td>
<td>x</td>
<td>116</td>
<td>162</td>
<td>16.5</td>
<td>111.16</td>
<td>112.92</td>
</tr>
<tr>
<td>4/1/2021</td>
<td>A</td>
<td>y</td>
<td>116.22</td>
<td>156.01</td>
<td>20.8</td>
<td>124.43</td>
<td>412.47</td>
</tr>
<tr>
<td>4/2/2021</td>
<td>A</td>
<td>y</td>
<td>166.04</td>
<td>142.02</td>
<td>16.1</td>
<td>138.51</td>
<td>346.6</td>
</tr>
<tr>
<td>4/1/2021</td>
<td>B</td>
<td>y</td>
<td>13</td>
<td>53</td>
<td>4</td>
<td>29.02</td>
<td>245.82</td>
</tr>
<tr>
<td>4/2/2021</td>
<td>B</td>
<td>y</td>
<td>58</td>
<td>30</td>
<td>6.5</td>
<td>61.84</td>
<td>38.08</td>
</tr>
</tbody>
</table>
</div>
<p>And here is my current working code. Please let me know your thoughts and spare no criticism (I know I'm naming variables inconsistently).</p>
<pre><code>Sub hourly_timeframe_to_day_type()
' Aggregate a table at the hourly+location+timeframe level
' to the daily+location+type level
' requires "Microsoft Scripting Runtime" reference enabled (Tools>References) to scripting.dictionary objects
'-----------------------------------------------------
' Save the table with multipliers and save column header references
'-----------------------------------------------------
Dim breakout_array As Variant: breakout_array = ThisWorkbook.Worksheets(1).Range("L5").CurrentRegion
With Application
Dim breakout_month_col As Long: breakout_month_col = .Match("Month", .Index(breakout_array, 1, 0), 0)
Dim breakout_location_col As Long: breakout_location_col = .Match("Location", .Index(breakout_array, 1, 0), 0)
Dim breakout_type_col As Long: breakout_type_col = .Match("type", .Index(breakout_array, 1, 0), 0)
Dim breakout_timeframe_col As Long: breakout_timeframe_col = .Match("Timeframe", .Index(breakout_array, 1, 0), 0)
Dim breakout_multiplier1_col As Long: breakout_multiplier1_col = .Match("Multiplier1", .Index(breakout_array, 1, 0), 0)
Dim breakout_multiplier2_col As Long: breakout_multiplier2_col = .Match("Multiplier2", .Index(breakout_array, 1, 0), 0)
End With
'-----------------------------------------------------
' Create dictionaries to track the multiplier using the column references
'-----------------------------------------------------
Dim MonthLocationTimeframeType_Multiplier1_dict As Scripting.Dictionary
Set MonthLocationTimeframeType_Multiplier1_dict = CreateObject("Scripting.Dictionary")
Dim MonthLocationTimeframeType_Multiplier2_dict As Scripting.Dictionary
Set MonthLocationTimeframeType_Multiplier2_dict = CreateObject("Scripting.Dictionary")
Dim types As Scripting.Dictionary: Set types = CreateObject("Scripting.Dictionary")
Dim i As Long
For i = 2 To UBound(breakout_array, 1)
' Month + Location + Type + Timeframe
' 4/1/2021 + A + x + day
multiplierkeystring = _
breakout_array(i, breakout_month_col) & _
breakout_array(i, breakout_location_col) & _
breakout_array(i, breakout_type_col) & _
breakout_array(i, breakout_timeframe_col)
MonthLocationTimeframeType_Multiplier1_dict(multiplierkeystring) = breakout_array(i, breakout_multiplier1_col)
MonthLocationTimeframeType_Multiplier2_dict(multiplierkeystring) = breakout_array(i, breakout_multiplier2_col)
' list of possible types
types(breakout_array(i, breakout_type_col)) = 1
Next i
Dim hrly_array As Variant: hrly_array = ThisWorkbook.Worksheets(1).Range("B5").CurrentRegion
With Application
'Dim hrly_month_col As Long: hrly_month_col = .Match("Month", .Index(hrly_array, 1, 0), 0)
Dim hrly_location_col As Long: hrly_location_col = .Match("Location", .Index(hrly_array, 1, 0), 0)
Dim hrly_timeframe_col As Long: hrly_timeframe_col = .Match("Timeframe", .Index(hrly_array, 1, 0), 0)
Dim hrly_day_col As Long: hrly_day_col = .Match("Day", .Index(hrly_array, 1, 0), 0)
Dim hrly_bread_col As Long: hrly_bread_col = .Match("bread", .Index(hrly_array, 1, 0), 0)
Dim hrly_barley_col As Long: hrly_barley_col = .Match("barley", .Index(hrly_array, 1, 0), 0)
Dim hrly_bagels_col As Long: hrly_bagels_col = .Match("bagels", .Index(hrly_array, 1, 0), 0)
Dim hrly_beef_col As Long: hrly_beef_col = .Match("beef", .Index(hrly_array, 1, 0), 0)
Dim hrly_chicken_col As Long: hrly_chicken_col = .Match("chicken", .Index(hrly_array, 1, 0), 0)
' ~40 more items
End With
Dim DayLocationType_bread_dict As Scripting.Dictionary: Set DayLocationType_bread_dict = CreateObject("Scripting.Dictionary")
Dim DayLocationType_barley_dict As Scripting.Dictionary: Set DayLocationType_barley_dict = CreateObject("Scripting.Dictionary")
Dim DayLocationType_bagels_dict As Scripting.Dictionary: Set DayLocationType_bagels_dict = CreateObject("Scripting.Dictionary")
Dim DayLocationType_beef_dict As Scripting.Dictionary: Set DayLocationType_beef_dict = CreateObject("Scripting.Dictionary")
Dim DayLocationType_chicken_dict As Scripting.Dictionary: Set DayLocationType_chicken_dict = CreateObject("Scripting.Dictionary")
' ~40 more items
' the first few columns
Dim day_dict As Scripting.Dictionary: Set day_dict = CreateObject("Scripting.Dictionary")
Dim location_dict As Scripting.Dictionary: Set location_dict = CreateObject("Scripting.Dictionary")
Dim type_dict As Scripting.Dictionary: Set type_dict = CreateObject("Scripting.Dictionary")
'-----------------------------------------------------
' Turn the hourly into daily type
'-----------------------------------------------------
Dim dailykeystring As String
Dim possible_type As Variant
For Each possible_type In types
For i = 2 To UBound(hrly_array, 1) ' could be 700,000 rows
' define key strings
multiplierkeystring = _
DateSerial(Year(hrly_array(i, hrly_day_col)), Month(hrly_array(i, hrly_day_col)), 1) & _
hrly_array(i, hrly_location_col) & _
possible_type & _
hrly_array(i, hrly_timeframe_col)
dailykeystring = hrly_array(i, hrly_day_col) & hrly_array(i, hrly_location_col) & possible_type
' if this combination exists then continue
' and only need to check one dictionary since they all share the same key
'-------------------------
If MonthLocationTimeframeType_Multiplier1_dict.Exists(multiplierkeystring) Then
'-------------------------
' Headers
'-------------------------
day_dict(dailykeystring) = hrly_array(i, hrly_day_col)
location_dict(dailykeystring) = hrly_array(i, hrly_location_col)
type_dict(dailykeystring) = possible_type
'--------------------------------------------------
' Hourly+Location+Timeframe to Day+Location+Type
'--------------------------------------------------
If Not DayLocationType_bread_dict.Exists(dailykeystring) Then
'------------------------------------------
' Start Aggregating
'------------------------------------------
' Multipier1
'-------------------------
DayLocationType_bread_dict(dailykeystring) = hrly_array(i, hrly_bread_col) _
* MonthLocationTimeframeType_Multiplier1_dict(multiplierkeystring)
DayLocationType_barley_dict(dailykeystring) = hrly_array(i, hrly_barley_col) _
* MonthLocationTimeframeType_Multiplier1_dict(multiplierkeystring)
DayLocationType_bagels_dict(dailykeystring) = hrly_array(i, hrly_bagels_col) _
* MonthLocationTimeframeType_Multiplier1_dict(multiplierkeystring)
' Multipier2
'-------------------------
DayLocationType_beef_dict(dailykeystring) = hrly_array(i, hrly_beef_col) _
* MonthLocationTimeframeType_Multiplier2_dict(multiplierkeystring)
DayLocationType_chicken_dict(dailykeystring) = hrly_array(i, hrly_chicken_col) _
* MonthLocationTimeframeType_Multiplier2_dict(multiplierkeystring)
' ~40 more items
Else
'------------------------------------------
' Continue Aggregate
'------------------------------------------
' Multiplier1
'-------------------------
DayLocationType_bread_dict(dailykeystring) = DayLocationType_bread_dict(dailykeystring) _
+ hrly_array(i, hrly_bread_col) * MonthLocationTimeframeType_Multiplier1_dict(multiplierkeystring)
DayLocationType_barley_dict(dailykeystring) = DayLocationType_barley_dict(dailykeystring) _
+ hrly_array(i, hrly_barley_col) * MonthLocationTimeframeType_Multiplier1_dict(multiplierkeystring)
DayLocationType_bagels_dict(dailykeystring) = DayLocationType_bagels_dict(dailykeystring) _
+ hrly_array(i, hrly_bagels_col) * MonthLocationTimeframeType_Multiplier1_dict(multiplierkeystring)
' Multiplier2
'-------------------------
DayLocationType_beef_dict(dailykeystring) = DayLocationType_beef_dict(dailykeystring) _
+ hrly_array(i, hrly_beef_col) * MonthLocationTimeframeType_Multiplier2_dict(multiplierkeystring)
DayLocationType_chicken_dict(dailykeystring) = DayLocationType_chicken_dict(dailykeystring) _
+ hrly_array(i, hrly_chicken_col) * MonthLocationTimeframeType_Multiplier2_dict(multiplierkeystring)
' ~40 more items
End If
End If
Next i
Next possible_type
'-----------------------------------------------------
' Print the Results
'-----------------------------------------------------
Dim daily_rows As Long: daily_rows = DayLocationType_bread_dict.Count
With ThisWorkbook.Worksheets(1).Range("AC6")
' headers
'-------------------------
.Offset(0, 0).Resize(daily_rows, 1) = Application.Transpose(day_dict.Items)
.Offset(0, 1).Resize(daily_rows, 1) = Application.Transpose(location_dict.Items)
.Offset(0, 2).Resize(daily_rows, 1) = Application.Transpose(type_dict.Items)
' items
'-------------------------
.Offset(0, 3).Resize(daily_rows, 1) = Application.Transpose(DayLocationType_bread_dict.Items)
.Offset(0, 4).Resize(daily_rows, 1) = Application.Transpose(DayLocationType_barley_dict.Items)
.Offset(0, 5).Resize(daily_rows, 1) = Application.Transpose(DayLocationType_bagels_dict.Items)
.Offset(0, 6).Resize(daily_rows, 1) = Application.Transpose(DayLocationType_beef_dict.Items)
.Offset(0, 7).Resize(daily_rows, 1) = Application.Transpose(DayLocationType_chicken_dict.Items)
' ~40 more items
'-------------------------
End With
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T08:24:48.860",
"Id": "510874",
"Score": "0",
"body": "Would you be open to suggestions about non-vba alternatives? For example, have you used pivot tables before - is there a reason you didn't use them for the aggregation? My initial thought would be to add some lookup columns to grab data from table 2 and put it in table 1, then use a pivot table on table 1 to aggregate it. Alternatively, powerquery would be a good tool for transforming and joining the two tables, have you come across this before? I generally avoid VBA for big data crunching as I think Excel has all the tools built in, and PQ is there for SQL levels of speed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T15:08:42.713",
"Id": "510891",
"Score": "1",
"body": "Hi Greedo, thanks for the edit and the ideas. I use both but less often in my automated work. This is an end-step in a large process and I’m not sure how much legible and efficient either option would be in the rest of my project"
}
] |
[
{
"body": "<p>Using a class to hold the data specific to the various items will help eliminate a lot of <em>nearly</em> duplicated code in your subroutine. The approach is that you define a class to hold data and objects relevant and unique to each item (bread, barely,chicken, etc). Doing so allows you to operate using loops.</p>\n<p>So, a class like (TableItem) below:</p>\n<pre><code> Option Explicit\n\n Private mBreakoutTableColumn As Long\n Private mResultOffsetColumn As Long\n Private mItemName As String\n Private mMultipliers As Dictionary\n Private myDict As Dictionary\n\n Private Sub Class_Initialize()\n Set myDict = New Dictionary\n End Sub\n\n Public Property Get DailyRowCount() As Long\n DailyRowCount = myDict.Count\n End Property\n\n Public Property Get ItemName() As String\n ItemName = mItemName\n End Property\n Public Property Let ItemName(ByVal RHS As String)\n mItemName = RHS\n End Property\n\n Public Property Get BreakoutTableColumn() As Long\n BreakoutTableColumn = mBreakoutTableColumn\n End Property\n\n Public Property Let BreakoutTableColumn(ByVal RHS As Long)\n mBreakoutTableColumn = RHS\n End Property\n\n Public Property Get ResultOffsetColumn() As Long\n ResultOffsetColumn = mResultOffsetColumn\n End Property\n\n Public Sub LoadUniqueContent(ByVal identifier As String, ByVal colNumber As Long, ByVal multipliers As Dictionary, ByVal rsltOffsetColumn As Long)\n ItemName = identifier\n BreakoutTableColumn = colNumber\n mResultOffsetColumn = rsltOffsetColumn\n Set mMultipliers = multipliers\n End Sub\n\n Public Function MultiplierKeyExists(ByVal multiplierKey As String) As Boolean\n MultiplierKeyExists = mMultipliers.Exists(multiplierKey)\n End Function\n\n Public Sub Aggregate(ByRef dailykeystring As String, ByRef multiplierkeystring As String, ByVal valToAggregate As Double)\n If Not myDict.Exists(dailykeystring) Then\n myDict(dailykeystring) = valToAggregate _\n * mMultipliers(multiplierkeystring)\n Else\n myDict(dailykeystring) = myDict(dailykeystring) + valToAggregate _\n * mMultipliers(multiplierkeystring)\n End If\n End Sub\n\n Public Function TransposeItem() As Variant\n TransposeItem = Application.Transpose(myDict.Items)\n End Function\n</code></pre>\n<p>Makes using loops possible. (Changes start about the middle of the subroutine)</p>\n<pre><code> Option Explicit\n\n Sub hourly_timeframe_to_day_type()\n ' Aggregate a table at the hourly+location+timeframe level\n ' to the daily+location+type level\n \n ' requires "Microsoft Scripting Runtime" reference enabled (Tools>References) to scripting.dictionary objects\n \n '-----------------------------------------------------\n ' Save the table with multipliers and save column header references\n '-----------------------------------------------------\n \n 'Dim breakout_array As Variant: breakout_array = ThisWorkbook.Worksheets("Breakout").Range("L5").CurrentRegion\n Dim breakout_array As Variant: breakout_array = ThisWorkbook.Worksheets("Breakout").Range("A1:F17")\n With Application\n Dim breakout_month_col As Long: breakout_month_col = .Match("Month", .Index(breakout_array, 1, 0), 0)\n Dim breakout_location_col As Long: breakout_location_col = .Match("Location", .Index(breakout_array, 1, 0), 0)\n Dim breakout_type_col As Long: breakout_type_col = .Match("type", .Index(breakout_array, 1, 0), 0)\n Dim breakout_timeframe_col As Long: breakout_timeframe_col = .Match("Timeframe", .Index(breakout_array, 1, 0), 0)\n Dim breakout_multiplier1_col As Long: breakout_multiplier1_col = .Match("Multiplier1", .Index(breakout_array, 1, 0), 0)\n Dim breakout_multiplier2_col As Long: breakout_multiplier2_col = .Match("Multiplier2", .Index(breakout_array, 1, 0), 0)\n End With\n\n '-----------------------------------------------------\n ' Create dictionaries to track the multiplier using the column references\n '-----------------------------------------------------\n Dim MonthLocationTimeframeType_Multiplier1_dict As Scripting.Dictionary\n Set MonthLocationTimeframeType_Multiplier1_dict = CreateObject("Scripting.Dictionary")\n \n Dim MonthLocationTimeframeType_Multiplier2_dict As Scripting.Dictionary\n Set MonthLocationTimeframeType_Multiplier2_dict = CreateObject("Scripting.Dictionary")\n \n Dim types As Scripting.Dictionary: Set types = CreateObject("Scripting.Dictionary")\n\n Dim multiplierkeystring As String\n \n Dim i As Long\n For i = 2 To UBound(breakout_array, 1)\n ' Month + Location + Type + Timeframe\n ' 4/1/2021 + A + x + day\n multiplierkeystring = _\n breakout_array(i, breakout_month_col) & _\n breakout_array(i, breakout_location_col) & _\n breakout_array(i, breakout_type_col) & _\n breakout_array(i, breakout_timeframe_col)\n \n MonthLocationTimeframeType_Multiplier1_dict(multiplierkeystring) = breakout_array(i, breakout_multiplier1_col)\n MonthLocationTimeframeType_Multiplier2_dict(multiplierkeystring) = breakout_array(i, breakout_multiplier2_col)\n ' list of possible types\n types(breakout_array(i, breakout_type_col)) = 1\n Next i\n \n \n '*******************************CHANGES START HERE**********************************\n\n 'Load items into a collection\n Dim tblItems As Collection\n Set tblItems = New Collection\n \n 'Dim hrly_array As Variant: hrly_array = ThisWorkbook.Worksheets(1).Range("B5").CurrentRegion\n Dim hrly_array As Variant: hrly_array = ThisWorkbook.Worksheets("Hourly").Range("A1:I17")\n With Application\n Dim hrly_location_col As Long: hrly_location_col = .Match("Location", .Index(hrly_array, 1, 0), 0)\n Dim hrly_timeframe_col As Long: hrly_timeframe_col = .Match("Timeframe", .Index(hrly_array, 1, 0), 0)\n Dim hrly_day_col As Long: hrly_day_col = .Match("Day", .Index(hrly_array, 1, 0), 0)\n End With\n \n 'defaultTableItem is used for extracting data common to all items without having to access the collection\n Dim defaultTableItem As TableItem\n Set defaultTableItem = CreateTableItem("bread", hrly_array, MonthLocationTimeframeType_Multiplier1_dict, 3)\n tblItems.Add defaultTableItem\n \n Dim tblItem As TableItem\n Set tblItem = CreateTableItem("barley", hrly_array, MonthLocationTimeframeType_Multiplier1_dict, 4)\n tblItems.Add tblItem\n \n Set tblItem = CreateTableItem("bagels", hrly_array, MonthLocationTimeframeType_Multiplier1_dict, 5)\n tblItems.Add tblItem\n \n Set tblItem = CreateTableItem("beef", hrly_array, MonthLocationTimeframeType_Multiplier2_dict, 6)\n tblItems.Add tblItem\n \n Set tblItem = CreateTableItem("chicken", hrly_array, MonthLocationTimeframeType_Multiplier2_dict, 7)\n tblItems.Add tblItem\n ' ~40 more items\n \n\n 'Dim DayLocationType_bread_dict As Scripting.Dictionary: Set DayLocationType_bread_dict = CreateObject("Scripting.Dictionary")\n 'Dim DayLocationType_barley_dict As Scripting.Dictionary: Set DayLocationType_barley_dict = CreateObject("Scripting.Dictionary")\n 'Dim DayLocationType_bagels_dict As Scripting.Dictionary: Set DayLocationType_bagels_dict = CreateObject("Scripting.Dictionary")\n 'Dim DayLocationType_beef_dict As Scripting.Dictionary: Set DayLocationType_beef_dict = CreateObject("Scripting.Dictionary")\n 'Dim DayLocationType_chicken_dict As Scripting.Dictionary: Set DayLocationType_chicken_dict = CreateObject("Scripting.Dictionary")\n ' ~40 more items REMOVED\n \n ' the first few columns\n Dim day_dict As Scripting.Dictionary: Set day_dict = CreateObject("Scripting.Dictionary")\n Dim location_dict As Scripting.Dictionary: Set location_dict = CreateObject("Scripting.Dictionary")\n Dim type_dict As Scripting.Dictionary: Set type_dict = CreateObject("Scripting.Dictionary")\n \n '-----------------------------------------------------\n ' Turn the hourly into daily type\n '-----------------------------------------------------\n Dim dailykeystring As String\n Dim possible_type As Variant\n \n For Each possible_type In types\n For i = 2 To UBound(hrly_array, 1) ' could be 700,000 rows\n ' define key strings\n\n multiplierkeystring = _\n DateSerial(Year(hrly_array(i, hrly_day_col)), Month(hrly_array(i, hrly_day_col)), 1) & _\n hrly_array(i, hrly_location_col) & _\n possible_type & _\n hrly_array(i, hrly_timeframe_col)\n\n dailykeystring = hrly_array(i, hrly_day_col) & hrly_array(i, hrly_location_col) & possible_type\n \n Aggregate tblItems, dailykeystring, multiplierkeystring, hrly_array, i\n '~40+ lines REMOVED\n \n ' if this combination exists then continue\n ' and only need to check one dictionary since they all share the same key\n '-------------------------\n If defaultTableItem.MultiplierKeyExists(multiplierkeystring) Then\n \n '-------------------------\n ' Headers\n '-------------------------\n day_dict(dailykeystring) = hrly_array(i, hrly_day_col)\n location_dict(dailykeystring) = hrly_array(i, hrly_location_col)\n type_dict(dailykeystring) = possible_type\n \n End If\n Next i\n Next possible_type\n\n '-----------------------------------------------------\n ' Print the Results\n '-----------------------------------------------------\n Dim daily_rows As Long\n daily_rows = defaultTableItem.DailyRowCount\n \n 'With ThisWorkbook.Worksheets(1).Range("AC6")\n With ThisWorkbook.Worksheets("Daily").Range("A1")\n \n ' headers\n '-------------------------\n .Offset(0, 0).Resize(daily_rows, 1) = Application.Transpose(day_dict.Items)\n .Offset(0, 1).Resize(daily_rows, 1) = Application.Transpose(location_dict.Items)\n .Offset(0, 2).Resize(daily_rows, 1) = Application.Transpose(type_dict.Items)\n \n ' items ~40+ lines removed\n '-------------------------\n Dim tblItm As Variant\n For Each tblItm In tblItems\n Set tblItem = tblItm\n .Offset(0, tblItem.ResultOffsetColumn).Resize(daily_rows, 1) = tblItem.TransposeItem()\n Next\n End With\n \n End Sub\n Private Sub Aggregate(ByVal itemsCollection As Collection, ByVal dailykeystring As String, ByVal multiplierkeystring As String, ByRef hrlyArray As Variant, ByVal idx As Long)\n \n Dim tblItem As TableItem\n Dim itm As Variant\n For Each itm In itemsCollection\n Set tblItem = itm\n tblItem.Aggregate dailykeystring, multiplierkeystring, hrlyArray(idx, tblItem.BreakoutTableColumn)\n Next\n End Sub\n\n Private Function CreateTableItem(ByVal identifier As String, ByRef hrly_array As Variant, ByVal multipliers As Dictionary, ByVal rsltOffsetColumn As Long) As TableItem\n Dim tblItem As TableItem\n Set tblItem = New TableItem\n Dim breakoutCol As Long\n breakoutCol = Application.Match(identifier, Application.Index(hrly_array, 1, 0), 0)\n\n tblItem.LoadUniqueContent identifier, breakoutCol, multipliers, rsltOffsetColumn\n Set CreateTableItem = tblItem\n End Function\n</code></pre>\n<p>As you can see, the 40+ lines to configure each class instance are still needed. Once that is done, the code can operate on the <code>Collection</code> generically.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T14:28:24.680",
"Id": "259083",
"ParentId": "259058",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259083",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-03T23:31:14.477",
"Id": "259058",
"Score": "3",
"Tags": [
"vba",
"excel",
"hash-map"
],
"Title": "Aggregating hourly location data into daily sublocation data for many columns"
}
|
259058
|
<p>The below is to parse a lisp expression (doing as much as possible in 'one go'). How does it look, and what can be improved?</p>
<pre><code># goal: capture the next token then get the rest of the line
# to be used in a while-loop/yield
tokenizer = re.compile(r"""
\s* # any amount of whitespace...
# 1. capture group one: token
(
,@ # special token ,@ ...
|[(),`'] # or ) ( , ' ` ...
|"(?:[^\\"]*(?:\\.)*)*" # or match on string (unrolling the loop)...
|;.* # or comment-anything...
|[^\s('"`,;)]* # or non-special...
)
# 2. capture group two: rest-of-line
(.*)
""", re.VERBOSE)
</code></pre>
<p>Example run (python):</p>
<pre><code>line = '(define (square x) (* x x))'
while line:
token, line = tokenizer.match(line).groups()
print (token)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T22:09:28.840",
"Id": "510921",
"Score": "1",
"body": "Typically, a lexer will complain if given invalid inputs. Yours will tokenize anything. Perhaps it would help for you to clarify the goal(s) of this code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-18T12:25:27.997",
"Id": "512257",
"Score": "0",
"body": "Your *(unrolling the loop)* part is wrong and should be: `\"[^\\\\\"]*(?:\\\\.[^\\\\\"]*)*\"`"
}
] |
[
{
"body": "<p>It's difficult for me to say whether this is well-written or not since there are no tests, and that's fundamentally your biggest problem. A complex regex like this couldn't represent a better subject for unit testing. It's already well-isolated, it's important, somewhat internally complex, and would benefit from spelling out exactly which inputs and outputs you expect. Include in your tests as many edge cases as you can think of, and also the "good" (inputs that you expect to successfully parse) as well as the "bad" (inputs that you expect should fail to parse in expected ways).</p>\n<p>The regex itself doesn't seem crazy. I find the lack of <code>^</code> and <code>$</code> suspicious. If you accidentally send this through a <code>search</code> instead of a <code>match</code>, you leave yourself open to false positives.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T23:29:40.637",
"Id": "259103",
"ParentId": "259062",
"Score": "-2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T03:45:19.843",
"Id": "259062",
"Score": "3",
"Tags": [
"python",
"regex"
],
"Title": "Regex with comments"
}
|
259062
|
<p>This is a question from a CS diploma question set :</p>
<blockquote>
<p>Make a program that will create an abbreviation of any given name using the initials. For example if the name if "John Doe", the program will output "J.D".</p>
</blockquote>
<p>My Code:</p>
<pre class="lang-c prettyprint-override"><code>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char *abbr (const char *s) {
int keywords = 1;
for (int i = 0; s[i]; i++)
if (s[i] == ' ') keywords++;
char *ret = (char *)malloc(2*keywords);
if (!ret) {
perror("malloc");
exit (EXIT_FAILURE);
}
char *str = strdup(s);
int i = 0;
for (char *tok=strtok(str, " "); tok; tok=strtok(NULL, " "))
{
ret [i++] = *tok;
ret [i++] = '.';
}
ret [--i] = 0;
free(str);
return ret;
}
int main (void) {
char name[] = "John Doe";
char *s = abbr(name);
puts (s);
free(s);
return 0;
}
</code></pre>
<p>With respect to the question, is this a good enough solution? Is there a better way to achieve the same thing?</p>
<p>Thank you.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T13:51:30.757",
"Id": "510883",
"Score": "1",
"body": "Is that a direct quote of the problem statement? In particular, is only one `.` required for that example input, that we'd normally write in English as `J.D.`?"
}
] |
[
{
"body": "<p>I would rather start with a very simple approach. Why not just <strong>print out</strong> the <strong>capital</strong> letters?</p>\n<pre><code>#include <stdio.h>\n\nint main(void) {\n char *namestr = "Hi my Four Names";\n\n char *pos = namestr;\n char c = ' ';\n while (c) {\n c = *pos++;\n if (c >= 'A' && c <= 'Z') {\n putchar(c);\n putchar('.');\n }\n }\n putchar('\\n');\n}\n</code></pre>\n<p>output : <code>H.F.N.</code></p>\n<p>Followed by a discussion about human names and strings in C. This is something that has to be defined in a question. Names can be very complicated, not only in exotic languages (McEnroe, van Gogh, Jean-Marie). And the rules for the initials are based on that.</p>\n<p>You should at least describe your approach. And not silently complicate a simple task (simple, but unclear).</p>\n<p>Create a new string (with malloc)? Or just output the initials "J.D." if the string is "John Doe"? Do a sanity check on the name?</p>\n<p><strong>good enough?</strong></p>\n<p>Yes that is the problem: it is <em>too</em> good in some ways.</p>\n<p>Can you tell me what kind of CS diploma that is? Is there a context? How is the code entered and evaluated?</p>\n<p><strong>achieve the same thing</strong></p>\n<p>What exactly? How did you interpret this unclear task?</p>\n<p><strong>if the name if</strong></p>\n<p>Are you citing or paraphrasing?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T13:47:26.337",
"Id": "510882",
"Score": "1",
"body": "`c >= 'A' && c <= 'Z'` is less portable than `isupper((unsigned char)c)`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T13:04:55.727",
"Id": "259079",
"ParentId": "259064",
"Score": "0"
}
},
{
"body": "<blockquote>\n<pre><code>char *abbr (const char *s) {\n</code></pre>\n</blockquote>\n<p>Good - appropriate use of <code>const</code> here.</p>\n<blockquote>\n<pre><code>char *ret = (char *)malloc(2*keywords);\n</code></pre>\n</blockquote>\n<p>The cast is unnecessary, as <code>malloc()</code> returns a <code>void*</code> - which can be assigned to any pointer type in C (unlike C++). See <a href=\"//stackoverflow.com/a/605858/4850040\">Do I cast the result of <code>malloc()</code>?</a></p>\n<blockquote>\n<pre><code>if (!ret) {\n</code></pre>\n</blockquote>\n<p>Again, good - avoid dereferencing a null pointer. I would take a different action if the allocation fails - just return a null pointer to the caller, who is in a better position to decide whether to abort the whole program, and whether to write an error message to <code>stderr</code>.</p>\n<blockquote>\n<pre><code>char *str = strdup(s);\n</code></pre>\n</blockquote>\n<p><code>strdup()</code> allocates memory, so this must be checked for a null return just like <code>malloc()</code>. There's an additional complication here that if we return from this point, we'll need to free <code>ret</code> before doing so. Personally, I'd remove the use of <code>strtok()</code> so that we don't need to copy the input here. <code>strtok()</code> has a terrible interface, and I consider it a misfeature of the C library.</p>\n<blockquote>\n<pre><code>char name[] = "John Doe";\nchar *s = abbr(name);\n</code></pre>\n</blockquote>\n<p>The requirement is for a program to <em>create an abbreviation of any given name</em>. This is a program that creates an abbreviation of one hard-coded name. I don't think it's really in the spirit of the requirements to have a program that needs to be edited and recompiled to be given a different name. All the user to provide the name as program arguments, or on the standard input stream.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T14:13:27.077",
"Id": "259082",
"ParentId": "259064",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T05:23:36.120",
"Id": "259064",
"Score": "0",
"Tags": [
"c",
"strings"
],
"Title": "Abbreviating a name"
}
|
259064
|
<p>From a CS Diploma course question set:</p>
<blockquote>
<p>Create a two dimensional array of ints, fill it with any random integers. Now find the minimum and maximum number, also find the index of those numbers.</p>
</blockquote>
<p>I was not sure what they meant by "fill it with any random integers". Should I just use my imagination? Since I wasn't sure, I opted for using <code>rand()</code>.</p>
<p>My Code:</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <limits.h>
int main (void) {
int array[10][10];
srand((unsigned int)time(NULL));
struct Nums {
int num,
i,
j;
} min, max;
min.num = INT_MAX;
max.num = 0;
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++) {
array[i][j] = rand();
if (array[i][j] > max.num) {
max.num = array[i][j];
max.i = i;
max.j = j;
}
if (array[i][j] < min.num) {
min.num = array[i][j];
min.i = i;
min.j = j;
}
}
printf("Max number: %d, row: %d, column: %d\n", max.num, max.i, max.j);
printf("Min number: %d, row: %d, column: %d\n", min.num, min.i, min.j);
return 0;
}
</code></pre>
<p>I did not go through the loop twice, i.e. I checked for the max and min numbers while filling up the array, is that the wrong approach considering the question?</p>
<p>Also is there any easier way to achieve the same result?</p>
<p>Thank you.</p>
|
[] |
[
{
"body": "<p>The formulated task leaves a lot of room for interpretation. You chose to simplify several points.</p>\n<blockquote>\n<p>Fill [the array]...now find...</p>\n</blockquote>\n<p>I take this as "create a function that finds...". This forces you to organize the program. Combining both (2D array, function) leads to a subtle problem - I ended up with a <code>#define COLS 10</code>, because that number (from your imagination also) has to be known to the function at compilation.</p>\n<p>I also think setting max to 0 and min to INT_MAX is mixing up logic and parameters.</p>\n<p>The other problem with a function is: how to return the bunch of results. I took your structs and put them into one.</p>\n<p>The call at the center is:</p>\n<p><code>struct minmax mm = minandmaxCOLS(array, nrows);</code></p>\n<p>The function takes an array and number of rows. The caller can choose this value, but the number of cols must always be COLS.</p>\n<p>If COLS is variable, then a 2D array is the wrong approach. Array of pointers works.</p>\n<p>Instead of</p>\n<pre><code>array[10][10]\n</code></pre>\n<p>I have</p>\n<pre><code>int nrows = 10;\nint array[nrows][COLS];\n</code></pre>\n<p>illustrating that the caller (<code>main</code>) can choose the rows, but not the cols, if it wants to use a function.</p>\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <limits.h>\n\n#define COLS 10\n\n/* Result type */\nstruct minmax {\n int min, minrow, mincol;\n int max, maxrow, maxcol;\n};\n\n/* scan for min and max in a 2D array "a[][]" with dims rows and COLS */ \nstruct minmax\nminandmaxCOLS(int a[][COLS], int rows) {\n\n int r, c;\n struct minmax result;\n \n /* Initialize result-struct before comparing in loop */ \n result.min = result.max = a[0][0];\n result.minrow = result.mincol = 0;\n result.maxrow = result.maxcol = 0;\n\n for (r = 0; r < rows; r++)\n for (c = 0; c < COLS; c++)\n if (a[r][c] > result.max) {\n result.max = a[r][c];\n result.maxrow = r;\n result.maxcol = c;\n }\n else \n if (a[r][c] < result.min) {\n result.min = a[r][c];\n result.minrow = r;\n result.mincol = c;\n }\n\n return result;\n}\n\nint main (void) {\n int nrows = 10;\n int array[nrows][COLS];\n\n srand(time(NULL));\n\n for (int i = 0; i < nrows; i++)\n for (int j = 0; j < COLS; j++) \n array[i][j] = rand();\n\n /* A kind of test */ \n //array[5][5] = -3;\n //array[6][7] = INT_MAX;\n \n struct minmax mm = minandmaxCOLS(array, nrows);\n\n printf("Max number: %d, row: %d, column: %d\\n", mm.max, mm.maxrow, mm.maxcol);\n printf("Min number: %d, row: %d, column: %d\\n", mm.min, mm.minrow, mm.mincol);\n\n return 0;\n}\n</code></pre>\n<p>As a side effect you can now also search for min and max only in certain rows:</p>\n<p><code>struct minmax mm = minandmaxCOLS(array+2, 1);</code></p>\n<p>Output with "test" activated:</p>\n<p><code>Min number: -3, row: 0, column: 5</code></p>\n<p>"row" is now relative to the arg <code>array+2</code>. The "2" means "two rows of 10 (COLS) ints". Same as <code>&array[2]</code>.</p>\n<hr />\n<p><strong>typedef</strong></p>\n<p>The function paramter list can be simplified by using a typedef. After <code>define</code>ing COLS as 10:</p>\n<p><code>typedef int Arrcolsint_t [COLS];</code></p>\n<p>This shows that an array of COLS integers is a basic unit. Now I can forget half (two thirds) of the details of "a":</p>\n<p><code>minandmaxCOLS(Arrcolsint_t a[], int rows) </code></p>\n<p>Same as:</p>\n<p><code>minandmaxCOLS(Arrcolsint_t *a, ....</code></p>\n<p>The advantage is you can use that type in several functions and only change the typedef itself. Without it is <code>int a[][COLS]</code> or <code>int (*a)[COLS]</code>.</p>\n<p><code>Row_t</code> might be a better typedef name. Still there always is the compile time value <code>10</code> behind it all.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T09:56:54.843",
"Id": "259075",
"ParentId": "259065",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T06:07:22.880",
"Id": "259065",
"Score": "0",
"Tags": [
"c",
"array"
],
"Title": "Create a two dimensional int array and find the smallest and biggest member along with the indexes"
}
|
259065
|
<p>I wrote this simple Makefile but it ended up like a <em>spaghetti</em> code. I used <code>basename</code> multiple times. I have a special case for <code>first.spec.scala.run</code> and <code>follow.spec.scala.run</code> and maybe more antipattern code that I am not aware of. I am not happy with my code and I appreciate any feedback or review. Thank you.</p>
<pre><code>SPECS=First Follow
EXAMPLES_PATH=../..
ROOT_PATH=../${EXAMPLES_PATH}
SCALAV=2.12
APSLIB=${ROOT_PATH}/lib/aps-library-${SCALAV}.jar
SCALA_FLAGS=.:${APSLIB}
APS2SCALA=${ROOT_PATH}/bin/aps2scala
all: $(addsuffix Spec.compile, $(SPECS)) $(addsuffix Spec.run, $(SPECS))
%.generate:
${APS2SCALA} -DCOT -p ${EXAMPLES_PATH}:${ROOT_PATH}/base $*
%.run:
@scala -cp ${SCALA_FLAGS} $(basename $@)
GrammarUtil.compile: grammar.generate
scalac -cp ${SCALA_FLAGS} grammar.scala $(basename $@).scala
first.compile:
scalac -cp ${SCALA_FLAGS} $(basename $@).scala
follow.compile:
scalac -cp ${SCALA_FLAGS} $(basename $@).scala
Spec.compile:
scalac -cp ${SCALA_FLAGS} $(basename $@).scala
FirstSpec.compile: Spec.compile grammar.generate GrammarUtil.compile first.generate first.compile
scalac -cp ${SCALA_FLAGS} $(basename $@).scala
FollowSpec.compile: Spec.compile grammar.generate GrammarUtil.compile follow.generate follow.compile
scalac -cp ${SCALA_FLAGS} $(basename $@).scala
clean:
rm -f *.class grammar.scala first.scala follow.scala
</code></pre>
|
[] |
[
{
"body": "<p>I don't know Scala, but I do know Make, so I hope this helps.</p>\n<p>Firstly, the makefile is missing <code>.DELETE_ON_ERROR:</code>, which pretty much every makefile needs, to avoid part-written output files appearing up-to-date when a compilation command fails (e.g. is interrupted).</p>\n<p>We also want <code>.PHONY:</code> for those targets that don't produce files, such as <code>all</code> and <code>clean</code>. (And clean should use <code>$(RM)</code> rather than <code>rm -f</code>, for increased portability.)</p>\n<p>I think that we want a straightforward pattern rule that says that we can make a file called <code>foo.compile</code> given an input called <code>foo.scala</code>:</p>\n<pre><code>%.compile: %.scala\n scalac -cp ${SCALA_FLAGS} $<\n</code></pre>\n<p>It looks to me that <code>-cp</code> is one of the flags to <code>scalac</code>, so that should probably be in <code>${SCALA_FLAGS}</code> rather than in the command.</p>\n<p>I'm not convinced that your rules actually create the files they claim to. For example, <code>GrammarUtil.compile</code> depends on <code>grammar.generate</code>, but then actually uses <code>grammar.scala</code> - should <code>grammar.generate</code> actually be <code>grammar.scala</code> there?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T07:36:06.313",
"Id": "510937",
"Score": "0",
"body": "Thank you so much for the feedback but I am failing. I am getting an error: https://gist.github.com/amir734jj/645a94412475dfb700f6116dd1c7e1bc"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T07:46:46.050",
"Id": "510938",
"Score": "0",
"body": "The error I am getting: \"make: *** No rule to make target 'grammar.aps'. Stop.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T07:52:41.533",
"Id": "510940",
"Score": "0",
"body": "Yes, I do. `%.generate` and `%.class` exist and running them individually works."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T08:01:36.563",
"Id": "510941",
"Score": "0",
"body": "I've commented at that link (since that's not part of the review)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T07:14:53.397",
"Id": "259113",
"ParentId": "259066",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259113",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T06:12:54.603",
"Id": "259066",
"Score": "1",
"Tags": [
"makefile"
],
"Title": "Simple Makefile to build and run scala program"
}
|
259066
|
<p>A common preprocessing in machine learning consists in replacing rare values in the data by a label stating "rare". So that subsequent learning algorithms will not try to generalize a value with few occurences.</p>
<p><a href="https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html" rel="nofollow noreferrer">Pipelines</a> enable to describe a sequence of preprocessing and learning algorithms to end up with a single object that takes raw data, treats it, and output a prediction. <a href="https://scikit-learn.org/stable/" rel="nofollow noreferrer">scikit-learn</a> expects the steps to have a specific syntax (fit / transform or fit / predict). I wrote the following class to take care of this task so that it can be run inside a pipeline. (More details about the motivation can be found here: <a href="https://www.thekerneltrip.com/python/pandas-replace-rarely-occuring-values-pipeline/" rel="nofollow noreferrer">pandas replace rare values</a>)</p>
<p>Is there a way to improve this code in term of performance or reusability ?</p>
<pre><code>class RemoveScarceValuesFeatureEngineer:
def __init__(self, min_occurences):
self._min_occurences = min_occurences
self._column_value_counts = {}
def fit(self, X, y):
for column in X.columns:
self._column_value_counts[column] = X[column].value_counts()
return self
def transform(self, X):
for column in X.columns:
X.loc[self._column_value_counts[column][X[column]].values
< self._min_occurences, column] = "RARE_VALUE"
return X
def fit_transform(self, X, y):
self.fit(X, y)
return self.transform(X)
</code></pre>
<p>And the following can be appended to the above class to make sure the methods work as expected:</p>
<pre><code>if __name__ == "__main__":
import pandas as pd
sample_train = pd.DataFrame(
[{"a": 1, "s": "a"}, {"a": 1, "s": "a"}, {"a": 1, "s": "b"}])
rssfe = RemoveScarceValuesFeatureEngineer(2)
print(sample_train)
print(rssfe.fit_transform(sample_train, None))
print(20*"=")
sample_test = pd.DataFrame([{"a": 1, "s": "a"}, {"a": 1, "s": "b"}])
print(sample_test)
print(rssfe.transform(sample_test))
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>You could use scikit-learn's <a href=\"https://scikit-learn.org/stable/modules/generated/sklearn.base.TransformerMixin.html\" rel=\"nofollow noreferrer\"><code>TransformerMixin</code></a> which provides an implementation of <code>fit_transform</code> for you (its implementation is available <a href=\"https://github.com/scikit-learn/scikit-learn/blob/main/sklearn/base.py#L683\" rel=\"nofollow noreferrer\">here</a> for interest).</p>\n</li>\n<li><p>I'd consider renaming <code>RemoveScarceValuesFeatureEngineer</code> to something that fits a bit more with other classes in scikit-learn. How about <code>RareValueTransformer</code> instead?</p>\n</li>\n<li><p>What do you want to happen if an unseen value is transformed? Take, for example</p>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>sample_test = pd.DataFrame([{"a": 1, "s": "a"}, {"a": 2, "s": "b"}])\nprint(sample_test)\nprint(rssfe.transform(sample_test))\n</code></pre>\n<p>This raises a <code>KeyError</code>, which isn't what I expected. I'd either rework your code to ignore unseen values, or return a nicer error if this is what you want to happen. To me, ignoring seems more reasonable, but it's up to you! Making some unit tests would give you more confidence in cases like this, too.</p>\n<p>A pedantic aside: you have a typo of 'occurrence' in <code>min_occurences</code>, which is easily amended.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T15:57:13.697",
"Id": "259090",
"ParentId": "259072",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T08:30:16.143",
"Id": "259072",
"Score": "3",
"Tags": [
"python",
"pandas",
"machine-learning"
],
"Title": "Pandas replace rare values in a pipeline"
}
|
259072
|
<p>I made a Rock Paper Scissors game. It works fine but I would like to know how can I improve it further.</p>
<pre><code>#include <iostream>
#include <algorithm>
#include <string>
#include <random>
#include <array>
#include <map>
#include <limits>
namespace
{
enum Winner { Tie, Player, Computer, WinnerCount };
enum Items { Rock, Paper, Scissors, ItemsCount };
template<typename T, std::size_t N>
using Matrix = std::array<std::array<T, N>, N>;
}
std::string user_choice(const std::array<std::string, Items::ItemsCount>& data)
{
std::string result;
static auto comp = [&result](const std::string& str) { return str == result; };
bool is_input_valid = false;
do
{
std::cout << "Enter your choice, rock, paper, or scissors: ";
std::getline(std::cin, result);
is_input_valid = !(std::cin.fail() || std::none_of(data.begin(), data.end(), comp));
if (!is_input_valid) {
std::cout << "Not valid input.\n";
}
std::cin.clear();
std::cin.ignore(std::cin.rdbuf()->in_avail());
} while (!is_input_valid);
return result;
}
bool play_again()
{
char result;
bool is_input_valid = false;
do
{
std::cout << "Do you want to play again? [y/n]: ";
std::cin >> result;
result = std::toupper(result);
is_input_valid = !(std::cin.fail() || (result != 'Y' && result != 'N'));
if (!is_input_valid)
{
std::cout << "Not valid input.\n";
}
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
} while (!is_input_valid);
return result == 'Y';
}
int main()
{
// Set up game
const Matrix<Winner, Winner::WinnerCount> table
{
{ // Rock Paper Scissors
{ Tie, Computer, Player }, // Rock
{ Player, Tie, Computer }, // Paper
{ Computer, Player, Tie }, // Scissors
}
};
const std::array<std::string, Items::ItemsCount> data
{
"rock",
"paper",
"scissors"
};
std::map<std::string, Items> binding_items
{
{ data[Items::Rock], Items::Rock },
{ data[Items::Paper], Items::Paper },
{ data[Items::Scissors], Items::Scissors },
};
const std::array<std::string, Winner::WinnerCount> winner_result
{
"It's a tie!\n\n",
"You win!\n\n",
"You lose!\n\n"
};
std::mt19937 engine{ std::random_device()() };
auto dist = std::uniform_int_distribution<>(0, Items::ItemsCount - 1);
// Game loop
do
{
std::cout << "\n\n\tRock Paper Scissors Game\n\n";
const auto user_chose = user_choice(data);
const Items player = binding_items[user_chose];
const Items computer = static_cast<Items>(dist(engine));
const auto computer_chose = data[computer];
std::cout << "\n\nYou entered: " << user_chose << '\n';
std::cout << "Computer chose: " << computer_chose << '\n';
std::cout << winner_result[table[player][computer]];
} while (play_again());
}
</code></pre>
|
[] |
[
{
"body": "<p>Looks pretty good at first glance! I'd say your main problem is "<code>#define ONE 1</code>" — you've gone out of your way to parameterize things that can't actually be changed in real life without massive changes elsewhere in the game logic. For example, you've set</p>\n<pre><code>enum Items { Rock, Paper, Scissors, ItemsCount };\n</code></pre>\n<p>which looks awesome... until someone decides to actually <em>use</em> that flexibility by changing it to</p>\n<pre><code>enum Items { Rock, Paper, Scissors, Lizard, Spock, ItemsCount };\n</code></pre>\n<p>and suddenly nothing compiles anymore. (They also have to change the local variables <code>table</code> and <code>data</code> and <code>binding_item</code> inside <code>main</code>, and the text of the <code>cout</code> inside <code>user_choice</code>, and maybe some more stuff too. By the way: variable names are important! <code>data</code> and <code>table</code> are not good names!)</p>\n<p>The over-parameterization antipattern tends to travel along with the <code>std::array</code> antipattern — see <a href=\"https://quuxplusone.github.io/blog/2020/08/06/array-size/\" rel=\"nofollow noreferrer\">"The 'array size constant' antipattern"</a> (2020-08-06). Somehow, people who've caught the "named constants > magic numbers" virus also tend to have caught the "std::array > core language" virus as well. Where you write</p>\n<pre><code>template<typename T, std::size_t N>\nusing Matrix = std::array<std::array<T, N>, N>;\n\nconst Matrix<Winner, Winner::WinnerCount> table\n{\n { // Rock Paper Scissors\n { Tie, Computer, Player }, // Rock\n { Player, Tie, Computer }, // Paper\n { Computer, Player, Tie }, // Scissors\n }\n};\n</code></pre>\n<p>an expert C++ programmer would probably just write</p>\n<pre><code>Winner table[3][3] = {\n // Rock Paper Scissors\n { Tie, Computer, Player }, // Rock\n { Player, Tie, Computer }, // Paper\n { Computer, Player, Tie }, // Scissors \n};\n</code></pre>\n<p>Incidentally, did you notice your bug above? You dimensioned your <code>table</code> by <code>WinnerCount</code>, but you index into it using values of <code>Item</code>. You're simply getting lucky that <code>WinnerCount</code> (win, lose, tie) happens to be the same as <code>ItemCount</code> (rock, paper, scissors).</p>\n<hr />\n<p>Be aware that</p>\n<pre><code>std::mt19937 engine{ std::random_device()() };\n</code></pre>\n<p>is a relatively low-entropy way to initialize a Mersenne Twister: it has 19937 bits of state, and you're seeding it with only 32 random bits. But C++ doesn't offer any concise way to seed a PRNG properly, so actually what you've got <em>is</em> the state of the art.</p>\n<hr />\n<pre><code>const Items computer = static_cast<Items>(dist(engine));\n</code></pre>\n<p>Throughout, you use plural words where singular would be more appropriate, and relatively abstract nouns (<code>data</code>, <code>table</code>, <code>computer</code>) where more concrete ones would be appropriate. I'd write:</p>\n<pre><code>Item computers_choice = static_cast<Item>(dist(engine));\n</code></pre>\n<p>indicating that what we've got now is not a computer but rather the computer player's <em>choice</em> of what to throw; and it is not multiple Items but rather a single Item. (I'd probably rename <code>Item</code> to <code>Gesture</code>, too.)</p>\n<hr />\n<p>Your <code>user_choice</code> function returns <code>std::string</code>, which you then have to parse <em>again</em> in <code>main</code>. It should just return the <code>Item</code> it extracted, directly, instead of the string.</p>\n<p>Also, the logic around the <code>is_input_valid</code> boolean seems pretty baroque. Think about how the code could be simplified by using a <code>return</code> or <code>break</code> statement inside the loop.</p>\n<pre><code>if (std::getline(std::cin, result)) {\n if (map_of_strings_to_gestures.contains(result)) {\n return map_of_strings_to_gestures.at(result);\n }\n}\nstd::cout << "Not valid input.\\n";\n// and go around again\n</code></pre>\n<p>Also, try hitting Ctrl-D (or Ctrl-Z on Windows) at this prompt. That'll close stdin, which makes <code>cin.fail()</code> true, which means the input isn't valid... and then your code just goes into an infinite loop, doesn't it? I think you actually want to <em>break out</em> of the loop when you see EOF or an error — not stay in the loop!</p>\n<hr />\n<p>For configuring the gestures, I think you should investigate <a href=\"https://quuxplusone.github.io/blog/2021/02/01/x-macros/\" rel=\"nofollow noreferrer\">X-macros</a>. Here's my take: <a href=\"https://godbolt.org/z/8qhdcPWT5\" rel=\"nofollow noreferrer\">https://godbolt.org/z/8qhdcPWT5</a> The entirety of the "configuration" for the game is expressed in a single table at the top of the code:</p>\n<pre><code>#define GESTURES \\\n X(Rock, "rock", BEATS(Scissors)) \\\n X(Scissors, "scissors", BEATS(Paper)) \\\n X(Paper, "paper", BEATS(Rock))\n</code></pre>\n<p>and I've also tested it with this configuration:</p>\n<pre><code>#define GESTURES \\\n X(Rock, "rock", BEATS(Scissors) BEATS(Lizard)) \\\n X(Scissors, "scissors", BEATS(Paper) BEATS(Lizard)) \\\n X(Paper, "paper", BEATS(Rock) BEATS(Spock)) \\\n X(Lizard, "lizard", BEATS(Spock) BEATS(Paper)) \\\n X(Spock, "spock", BEATS(Scissors) BEATS(Rock))\n</code></pre>\n<p>(My version also eliminates the dependencies on <code><map></code>, <code><algorithm></code>, and of course <code><limits></code>.)</p>\n<hr />\n<p>An obvious "next step" for this program would be to refactor it so that you can print a customized verb for each outcome:</p>\n<pre><code>Enter your choice (rock, scissors, paper): rock\nYou entered: rock\nComputer chose: paper\nPaper covers rock — you lose!\n\nEnter your choice (rock, scissors, paper): scissors\nYou entered: scissors\nComputer chose: paper\nScissors cuts paper — you win!\n</code></pre>\n<p>and so on.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T14:58:46.093",
"Id": "510888",
"Score": "0",
"body": "Technically, since `std::random_device::operator` returns `unsigned int`, we're seeding with *an implementation-defined number of bits*, minimum 16."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T14:48:52.983",
"Id": "259086",
"ParentId": "259076",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "259086",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T10:15:03.340",
"Id": "259076",
"Score": "2",
"Tags": [
"c++",
"c++11"
],
"Title": "Simple Rock Paper Scissors"
}
|
259076
|
<p>I am building a library to abstract DOM manipulation. Here's what the usage looks like:</p>
<pre><code> vsAddToSection() {
let _inChapter: c.InChapter;
let v$sections = vmap([], _ =>
vh('div.section.item', {}, {
listeners: {
click: (e, __) => {
this.ctrl.inSection(_inChapter, _)
}
}
}, [h('span', _.name)]));
let v$backToABook = this.vBackToABook(),
v$backToBook = this.vBackToBook();
let update = (inChapter: c.InChapter) => {
_inChapter = inChapter;
v$backToBook.update(inChapter);
v$backToBook.update(inChapter);
v$sections.update(inChapter.sections);
};
return [update, [
v$backToABook,
v$backToBook,
h('div.sections', v$sections),
vh('button', {}, {
listeners: {
click: (e, _) => {
this.ctrl.toNew.pub(_inChapter);
}
}
}, [h('i', '+'), h('span', 'New Section')])
]];
}
vAddToBookPopup() {
let v$content = vex([h('div', 'default')]);
let [vs$addToBookUpdate, vs$addToBook] = this.vsAddToBook(),
[vs$addToChapterUpdate, vs$addToChapter] = this.vsAddToChapter(),
[vs$addToSectionUpdate, vs$addToSection] = this.vsAddToSection();
this.ctrl.addTo.sub(addTo => {
if (c.isInABook(addTo)) {
vs$addToBookUpdate(addTo);
v$content.replace(vs$addToBook);
} else if (c.isInBook(addTo)) {
vs$addToChapterUpdate(addTo);
v$content.replace(vs$addToChapter);
} else if (c.isInChapter(addTo)) {
vs$addToSectionUpdate(addTo);
v$content.replace(vs$addToSection);
} else if (c.isInSection(addTo)) {
// console.log(addTo);
// selected
}
});
return h('div.popup.addtobook', [v$content]);
}
</code></pre>
<p><code>vh</code> creates a dom node, adds event listeners to it, etc.
<code>h</code> is a wrapper around <code>vh</code>.
<code>vmap</code> takes an array of data, and a function to create children dom nodes. The abstraction has an <code>update</code> method to update the <code>array of data</code> so it can remove old children dom nodes, and create and add new children.
<code>vex</code> takes an array of <code>vh abstraction</code> and has a <code>replace</code> method that replaces the dom contents with the new array of <code>vh</code>'s.</p>
<p><code>this.ctrl.addTo.sub</code> listens to an event that updates the dom, like this:</p>
<pre><code>vs$addToBookUpdate(addTo);
v$content.replace(vs$addToBook);
</code></pre>
<p>This updates the contents of a piece of dom, and replaces the parent dom with that new piece of dom.</p>
<p>I return two values from <code>vsAddToSection</code> function, one for to update the abstraction, one returns the abstraction itself to append.</p>
<p>Hope this makes sense, my goal is simplicity, something that works, and avoid using external dependencies. Is this a little cumbersome, should I stick to a regular virtual dom approach?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T11:17:19.173",
"Id": "259077",
"Score": "1",
"Tags": [
"javascript",
"typescript",
"html5"
],
"Title": "How to abstract DOM manipulation in a simple intuitive way"
}
|
259077
|
<p>I just learned about arraylists and I got a mission to build Mobile phone application with contact list when you can add \ remove \ modify \ search for contacts.</p>
<p>If you think I should add something to the code feel free to tell me :)</p>
<h2>MobilePhone class</h2>
<pre><code>public class MobilePhone{
private String phoneNumber;
public ArrayList<Contact> myContacts = new ArrayList<Contact>();
public MobilePhone(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void printContactList() {
if (!myContacts.isEmpty()) {
for (int i = 0; i < myContacts.size(); i++) {
System.out.println(i + 1 + ". " + "Name: " + myContacts.get(i).getName() + " || Phone number: " + myContacts.get(i).getPhoneNumber());
}
} else {
System.out.println("Your contact list is empty!");
}
}
public void addContact(String name, String phoneNumber) {
if (searchContactByPhoneNumber(phoneNumber) == -1) {
Contact contact = new Contact(name, phoneNumber);
myContacts.add(contact);
System.out.println("Contact " + name + " with phone number " + phoneNumber + " just added!");
} else {
System.out.println("This contact is already on your list.");
}
}
public void removeContact(String phoneNumber) {
int index = searchContactByPhoneNumber(phoneNumber);
if (index >= 0) {
System.out.println("You have removed " + myContacts.get(index).getName());
myContacts.remove(index);
}
}
public int searchContactByPhoneNumber(String phoneNumber) {
for (int i = 0; i < myContacts.size(); i++) {
if (phoneNumber.equals(myContacts.get(i).getPhoneNumber())) {
System.out.println(myContacts.get(i).getName() + " Found!");
return i;
}
}
return -1;
}
public int searchContactByName(String name){
for(int i =0; i<myContacts.size(); i++){
if(name.equals(myContacts.get(i).getName())) {
return i;
}
}
return -1;
}
public void changeContact(String oldName, String newName) {
int index = searchContactByName(oldName);
if(index >=0){
Contact updatedContact = new Contact(newName,myContacts.get(index).getPhoneNumber());
myContacts.set(index,updatedContact);
System.out.println("You have changed contact " +oldName + " to " + newName + "\n" +
"Phone number: " +myContacts.get(index).getPhoneNumber());
} else {
System.out.println("No contact named " + oldName + " on your contact list");
}
}
}
</code></pre>
<h2>Contact class</h2>
<pre><code>public class Contact {
private String name;
private String phoneNumber;
public Contact(String name, String phoneNumber) {
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName() {
return this.name;
}
public String getPhoneNumber(){
return this.phoneNumber;
}
}
</code></pre>
<h2>PrintService class</h2>
<pre><code>public class PrintService {
public static void printMenu() {
System.out.println("Press:" + "\n" +
"\r" + "1. Show contact list" + "\n" +
"\r" + "2. Add an contact" + "\n" +
"\r" + "3. Remove an contact" +"\n" +
"\r" + "4. Search for an contact" + "\n" +
"\r" + "5. Change info about some contact" +"\n"+
"\r" + "6. Exit.");
}
}
</code></pre>
<h2>Main class</h2>
<pre><code>public class Main {
private static final Scanner sc = new Scanner(System.in);
private static final MobilePhone mobilePhone = new MobilePhone("123456789");
public static void main(String[] args){
boolean exitRequested = false;
while(!exitRequested) {
PrintService.printMenu();
int options = Integer.parseInt(sc.nextLine());
switch (options) {
case 1:
mobilePhone.printContactList();
break;
case 2:
addContact();
break;
case 3:
removeContact();
break;
case 4:
searchContact();
break;
case 5:
changeContact();
break;
case 6:
exitRequested = true;
break;
}
}
}
private static void addContact() {
System.out.println("Name?");
String name = sc.nextLine();
System.out.println("Phone number:");
String phoneNumber = sc.nextLine();
if (phoneNumber.length() != 10) {
System.out.println("Wrong input!");
} else {
mobilePhone.addContact(name, phoneNumber);
}
}
private static void removeContact(){
System.out.println("Which contact would you like to remove?" +"\n" +
"Please type phone number.");
String phoneNumber = sc.nextLine();
mobilePhone.removeContact(phoneNumber);
}
private static void searchContact(){
System.out.println("Please enter phone number ");
String phoneNumber = sc.nextLine();
if(mobilePhone.searchContactByPhoneNumber(phoneNumber) == -1) {
System.out.println("No contact found with phone number " + phoneNumber);
} else {
mobilePhone.searchContactByPhoneNumber(phoneNumber);
}
}
private static void changeContact(){
System.out.println("Which contact would you like to modify?");
String currentName = sc.nextLine();
System.out.println("Enter your modify");
String updatedName = sc.nextLine();
mobilePhone.changeContact(currentName,updatedName);
}
}
</code></pre>
<p>Thank you very much!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T19:44:45.090",
"Id": "511200",
"Score": "0",
"body": "Just one small note. Do not use the implementation instead of an interface. Instead of `public ArrayList<Contact> myContacts = new ArrayList<Contact>();` use `List<Contact> myContact = new ArrayList<>()`. Also you do not need to repeat the generic type twice, use a diamond operator"
}
] |
[
{
"body": "<h2>What I like</h2>\n<p>You follow the Java Naming conventions and the names you choose for your identifiers are pretty good.</p>\n<h2>What I don't like</h2>\n<h3>Unnecessary mutability</h3>\n<p>The member variable <code>phoneNumber</code> in your class <code>MobilePhone</code> does not change during the objects life time, therefore it should be declared <code>final</code>. The same applies to <code>name</code> and <code>phoneNumber</code> in your class <code>Contact</code>.</p>\n<h3>Inappropriate visibility</h3>\n<p>The member variable <code>myContacts</code> in your class <code>MobilePhone</code> is declares <code>public</code>. That means that its content can be changed from anywhere outside the class <code>MobilePhone</code>. This violates the <em>encapsulation/information hiding</em> principle, one of the most important concepts of <em>object oriented programming</em>.</p>\n<h3>Using indexes instead of objects</h3>\n<p>Your <code>search*</code> methods return indexes instead of the real objects. Therefore the caller of that methods must access the list again in case it wants to do something with the data of that particular contact (which is almost always the case...). So you better return the contact object itself.</p>\n<h3>Inline signalling of errors</h3>\n<p>In case your <code>search*</code> method finds nothing you return a <em>special value</em>. In Java we have the concept of <em>Exceptions</em> to handle this kind of Problem.</p>\n<p>Yes, there is a rule, that you should not miss use Exceptions as <em>control flow</em>. But they are exactly for this particular purpose, avoiding this <em>in band signalling</em> of a <em>special case</em> when returning a processing result.</p>\n<p>In your small project <em>Exceptions</em> will basically replace the <code>if/else</code> statements with <code>try/catch</code> blocks which does not look like a benefit at all. But in larger projects it is very likely that the <em>error case</em> can not be handled by the direct calling method but by some other method way up in the call stack. Then only the code able to deal with that problem needs to know that it may occur. Without the use of exceptions any method way down in the call stack needs this <code>if</code> statements.</p>\n<p>Another way to go around this is the use of <code>Optional</code> as the return value. But that is just another <em>special value</em> in my opinion.</p>\n<h3>Naming</h3>\n<p>As I initially wrote your naming is pretty good, with one minor exception. In your <code>main</code> method the local variable <code>options</code> will always contain a <em>single</em> user choice. Therefore it should not have the plural s.<br />\nHaving written that, the name <code>option</code> might not be that good at all and should rather be <code>selectedOption</code> or just <code>choice</code>...</p>\n<hr />\n<h2>Answer to comment</h2>\n<blockquote>\n<p>I've tried before to make all methods (Contact contact) but fo real I got stuck hard. – עמית שוקרון</p>\n</blockquote>\n<p>That should be quite easy.</p>\n<pre><code>public class MissingContact extends RuntimeException{\n public MissingContact(String message){\n super(message);\n }\n}\n\n\npublic Contact searchContactByPhoneNumber(String phoneNumber) {\n for (contact: myContacts) {\n if (phoneNumber.equals(contact.getPhoneNumber())) {\n System.out.println(contact.getName() + " Found!");\n return contact;\n }\n }\n throw new MissingContact("No contact with number "+phoneNumber);\n} // search by name similar\n</code></pre>\n<p>To avoid the Exception handling you should apply the <em>check, then act</em> pattern by adding appropriate check methods:</p>\n<pre><code>public boolean hasContactWithPhoneNumber(String phoneNumber) {\n for (contact: myContacts) {\n if (phoneNumber.equals(contact.getPhoneNumber())) {\n System.out.println(contact.getName() + " Found!");\n return true;\n }\n }\n return false;\n} // searchByName similar\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T17:17:13.780",
"Id": "510908",
"Score": "0",
"body": "Hi ! thank you for your answer! I've tried before to make all methods (Contact contact) but fo real I got stuck hard. I coudlnt do it alone.. hope someone will guide me to it ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T18:17:34.193",
"Id": "510913",
"Score": "0",
"body": "@עמיתשוקרון: see the update, does that help?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T21:00:00.880",
"Id": "510917",
"Score": "0",
"body": "Thank you very much sir, it helped me a lot !"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T08:19:20.523",
"Id": "510942",
"Score": "0",
"body": "Hi again! hope you'll see it, should I change only the search method or I need to change every single method to get Contact contact parameter?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T16:21:59.307",
"Id": "510961",
"Score": "0",
"body": "@עמיתשוקרון Your API should be *consistent* so any method that currently returns an index should return a `Contact` object instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T16:59:00.960",
"Id": "510965",
"Score": "0",
"body": "Ok I done! I wish I did it righ should I edit the whole topic or create new one ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T18:54:15.437",
"Id": "510970",
"Score": "0",
"body": "@עמיתשוקרון it is encouraged to create a new question link to this one from there."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T15:51:09.370",
"Id": "259088",
"ParentId": "259080",
"Score": "4"
}
},
{
"body": "<p>I think Timothy Truckle has covered a lot of good ground here.</p>\n<p>I'd disagree with the idea of throwing an unchecked exception when entries can't be found, however.</p>\n<p>This exercise has very similar characteristics to the java.util.Map interface (in fact, if the OP wasn't specifically focussing on learning ArrayLists, a Map would be a better structure with which to implement a contact list).</p>\n<p>Following the example of Map, if entries can't be found then simply return null.</p>\n<p>I'd be inclined to make the Contact class a nested class in MobilePhone, as I don't believe it's needed elsewhere, and I think it needs a good toString() method.</p>\n<p>I'm worried by the changeContact() operation - the MobilePhone.addContact() method only enforces unique phone numbers but the changeContact searches by name, so I don't think you're guaranteed to change the name for the contact you might have intended.</p>\n<p>I haven't tried to address that problem in the code below (which is untested, so regard it as a sketch of how I'd do this, if forced to use ArrayList for the purpose).</p>\n<pre><code>import java.util.ArrayList;\n\npublic class MobilePhone {\n\n private static class Contact {\n\n private String name;\n private String phoneNumber;\n\n public Contact(String name, String phoneNumber) {\n this.name = name;\n this.phoneNumber = phoneNumber;\n }\n\n @Override\n public String toString() {\n return String.format("Name: %s , || Phone number: %s", name, phoneNumber);\n }\n }\n\n @SuppressWarnings("unused")\n private final String myPhoneNumber; // Different name to the contact phone number, for clarity\n\n private final List<Contact> myContacts = new ArrayList<Contact>(); // use Interface as the field type...\n\n public MobilePhone(String phoneNumber) {\n myPhoneNumber = phoneNumber;\n }\n\n public void printContactList() {\n if (!myContacts.isEmpty()) {\n for (Contact contact : myContacts) {\n System.out.println(contact);\n }\n }\n else {\n System.err.println("Your contact list is empty!");\n }\n }\n\n public void addContact(String name, String phoneNumber) {\n Contact existingContact = searchContactByPhoneNumber(phoneNumber);\n if (existingContact == null) {\n Contact contact = new Contact(name, phoneNumber);\n myContacts.add(contact);\n System.out.format("Contact %s added%n", contact);\n }\n else {\n System.err.format("This phone number is already on your list - %s%n", existingContact);\n }\n }\n\n public void removeContact(String phoneNumber) {\n Contact existingContact = searchContactByPhoneNumber(phoneNumber);\n if (existingContact != null) {\n myContacts.remove(existingContact); // we're ignoring the boolean result in this case\n System.out.format("You have removed contact - %s%n" + existingContact);\n }\n }\n\n public Contact searchContactByPhoneNumber(String phoneNumber) {\n for (Contact contact : myContacts) {\n if (phoneNumber.equals(contact.phoneNumber)) {\n return contact;\n }\n }\n return null;\n }\n\n public Contact searchContactByName(String name) {\n for (Contact contact : myContacts) {\n if (name.equals(contact.name)) {\n return contact;\n }\n }\n return null;\n }\n\n public void changeContact(String oldName, String newName) {\n Contact existingContact = searchContactByName(oldName);\n if (existingContact != null) {\n existingContact.name = newName;\n System.out.format("You have changed contact %s to %s%nPhone number: %s%n", oldName, newName, existingContact.phoneNumber);\n }\n else {\n System.err.format("No contact named %s on your contact list%n", oldName);\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T10:40:49.530",
"Id": "511012",
"Score": "0",
"body": "I forgot to ask - is there any chance of concurrent use of the MobilePhone class? If so, synchronization needs to be considered..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T10:34:02.980",
"Id": "259152",
"ParentId": "259080",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "259088",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T13:52:00.750",
"Id": "259080",
"Score": "5",
"Tags": [
"java"
],
"Title": "Contacts list manager"
}
|
259080
|
<p>I successfully solved a problem on Hackerrank called <a href="https://www.hackerrank.com/challenges/contacts/problem" rel="nofollow noreferrer">Contacts</a>, but I'm curious if my code in C++ looks good to C++ developers. If not, how it should be improved.</p>
<p>Below is the short description of the problem and then the code itself.</p>
<h1>Problem</h1>
<ol>
<li>Add name, where <code>name</code> is a string denoting a contact name. This must store <code>name</code> as a new contact in the application.</li>
<li>Find partial, where <code>partial</code> is a string denoting a partial name to search the application for. It must count the number of contacts starting with <code>partial</code> and print the count on a new line.</li>
</ol>
<p>So, given sequential <code>add</code> and <code>find</code> operations, perform each operation in order.</p>
<h1>Solution</h1>
<p>Use a <a href="https://en.wikipedia.org/wiki/Trie" rel="nofollow noreferrer">Trie</a> like structure to solve the problem. All the children of a node have a common prefix of the contact associated with that parent node, and the root is associated with the empty string.</p>
<h1>Code</h1>
<pre><code>struct node {
uint32_t count = 0;
std::unordered_map<char, std::unique_ptr<node>> childrenMap;
};
/*
* Complete the contacts function below.
*/
std::vector<uint32_t> contacts(std::vector<std::vector<std::string>>& queries) {
std::vector<uint32_t> results;
node root;
for (const auto& row : queries) {
const auto operation = row[0];
const auto name = row[1];
if (operation == "add") {
auto* parent = &root;
for (auto& ch : name) {
auto& childrenMap = parent->childrenMap;
if (!childrenMap.count(ch)) {
childrenMap.emplace(ch, std::make_unique<node>());
}
childrenMap[ch]->count++;
parent = childrenMap[ch].get();
}
} else {
auto* parent = &root;
auto result = 0;
for (auto& ch : name) {
auto& childrenMap = parent->childrenMap;
if (!childrenMap.count(ch)) {
result = 0;
break;
}
parent = childrenMap[ch].get();
result = childrenMap[ch]->count;
}
results.push_back(result);
}
}
return results;
}
</code></pre>
|
[] |
[
{
"body": "<p>The Trie approach might be overkill for this question. I think that a plain (ordered) <code>std::set</code> (or <code>std::multiset</code>) would be adequate. The set's <code>lower_bound()</code> member takes you directly to the first entry with the specified substring. From there, we can either count linearly, or use <code>lower_bound</code> again with a new key created by adding 1 to the last character, then just return the iterator difference.</p>\n<p>I'd certainly consider writing separate <code>add()</code> and <code>find()</code> functions instead of plonking all the code in that big <code>if</code>/<code>else</code>. If nothing else, it makes the unit tests easier to write.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T14:51:08.410",
"Id": "510887",
"Score": "2",
"body": "Upvoted since it's a valid suggestion, but you are making a trade-off: Lookups in `std::set` are O(log(number of elements in set)), lookups in the trie are O(number of characters in the names). Once you have looked up the lower bound, the cost of counting is also different. So it depends on the exact distribution of operations in the input which will be faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T15:04:00.513",
"Id": "510890",
"Score": "1",
"body": "Yes @G.Sliepen, and where I wrote \"*might*\", one should also read \"*(but might not)*\". It depends greatly on the actual data. I would start with the simple approach, and switch to the more complex code if and when I find that it's necessary."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T14:41:22.423",
"Id": "259085",
"ParentId": "259081",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "259085",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T13:57:19.423",
"Id": "259081",
"Score": "4",
"Tags": [
"c++",
"programming-challenge",
"c++14"
],
"Title": "Contacts programming challenge"
}
|
259081
|
<p>I tried implementing a thread-safe ring queue in C++. I'm totally new to move semantics and C++11/14/17 in general.</p>
<pre><code>#ifndef THREAD_SAFE_RING_QUEUE_HPP_
#define THREAD_SAFE_RING_QUEUE_HPP_
#include <mutex>
#include <optional>
#include <vector>
namespace structure {
class MaximumCapacityReachedError : public std::runtime_error {
public:
MaximumCapacityReachedError(std::size_t capacity)
: runtime_error("Structure instance is full (" +
std::to_string(capacity) + ")") {}
};
class EmptyError : public std::runtime_error {
public:
EmptyError() : runtime_error("Structure instance is empty") {}
};
template <class T>
class RingQueue {
public:
static constexpr std::size_t kDefaultCapacity_ = 10;
RingQueue(std::size_t = kDefaultCapacity_);
bool IsEmpty() const;
std::size_t GetSize() const;
void Push(T&& element);
void TryPush(T&& element);
T& ConsumeNext();
std::optional<T> TryConsumeNext();
void Clear();
std::size_t GetCapacity() const noexcept;
bool IsFull() const noexcept;
private:
mutable std::recursive_mutex mutex_;
std::size_t capacity_ = 0;
std::size_t head_ = 0;
std::size_t tail_ = 0;
std::vector<T> elements_;
bool is_full_ = false;
};
template <class T>
inline RingQueue<T>::RingQueue(std::size_t capacity)
: capacity_(capacity),
elements_(std::vector<T>(capacity_)),
is_full_(capacity == 0) {}
template <class T>
inline bool RingQueue<T>::IsEmpty() const {
std::scoped_lock<std::recursive_mutex> lock(mutex_);
return capacity_ == 0 || (!is_full_ && head_ == tail_);
}
template <class T>
inline std::size_t RingQueue<T>::GetSize() const {
std::scoped_lock<std::recursive_mutex> lock(mutex_);
if (is_full_) {
return capacity_;
}
if (tail_ >= head_) {
return tail_ - head_;
}
return capacity_ - (head_ - tail_);
}
template <class T>
inline void RingQueue<T>::Push(T&& element) {
std::scoped_lock<std::recursive_mutex> lock(mutex_);
if (IsFull()) {
throw MaximumCapacityReachedError(capacity_);
}
elements_[tail_] = std::forward<T>(element);
tail_ = (tail_ + 1) % capacity_;
is_full_ = head_ == tail_;
}
template <class T>
inline void RingQueue<T>::TryPush(T&& element) {
std::scoped_lock<std::recursive_mutex> lock(mutex_);
if (IsFull()) {
return;
}
elements_[tail_] = std::forward<T>(element);
tail_ = (tail_ + 1) % capacity_;
is_full_ = head_ == tail_;
}
template <class T>
inline T& RingQueue<T>::ConsumeNext() {
std::scoped_lock<std::recursive_mutex> lock(mutex_);
if (IsEmpty()) {
throw EmptyError();
}
const auto previous_head = head_;
head_ = (head_ + 1) % capacity_;
is_full_ = false;
return std::forward<T>(elements_[previous_head]);
}
template <class T>
inline std::optional<T> RingQueue<T>::TryConsumeNext() {
std::scoped_lock<std::recursive_mutex> lock(mutex_);
if (IsEmpty()) {
return std::nullopt;
}
const auto previous_head = head_;
head_ = (head_ + 1) % capacity_;
is_full_ = false;
return std::forward<T>(elements_[previous_head]);
}
template <class T>
inline void RingQueue<T>::Clear() {
std::scoped_lock<std::recursive_mutex> lock(mutex_);
head_ = 0;
tail_ = 0;
is_full_ = false;
}
template <class T>
inline std::size_t RingQueue<T>::GetCapacity() const noexcept {
std::scoped_lock<std::recursive_mutex> lock(mutex_);
return capacity_;
}
template <class T>
inline bool RingQueue<T>::IsFull() const noexcept {
std::scoped_lock<std::recursive_mutex> lock(mutex_);
return is_full_;
}
} // namespace structure
#endif // THREAD_SAFE_RING_QUEUE_HPP_
</code></pre>
<p>I have tested my code and it seems to work, but so many things can go wrong...</p>
<p><strong>EDIT:</strong> here are the tests that I've done using <strong><a href="https://github.com/catchorg/Catch2" rel="nofollow noreferrer">Catch2</a></strong>. <code>DummyObject</code> is just a class containing an <code>int</code> (the value may be passed in the constructor, and is <code>0</code> by default).</p>
<pre><code>#include <memory>
#include "catch.hpp"
#include "dummies.hpp"
#include "utils/structure/ring_queue.hpp"
TEST_CASE("Ring queue creation with default capacity", "[structure]") {
auto queue = structure::RingQueue<std::shared_ptr<dummy::DummyObject>>();
SECTION("Properties after creation with default capacity.") {
REQUIRE(queue.GetCapacity() == queue.kDefaultCapacity_);
REQUIRE(queue.GetSize() == 0);
REQUIRE(!queue.IsFull());
REQUIRE(queue.IsEmpty());
}
}
TEST_CASE("Ring queue creation with specific capacity", "[structure]") {
const std::size_t capacity = 15;
auto queue =
structure::RingQueue<std::shared_ptr<dummy::DummyObject>>(capacity);
SECTION("Properties after creation with specific capacity.") {
REQUIRE(queue.GetCapacity() == capacity);
REQUIRE(queue.GetSize() == 0);
REQUIRE(!queue.IsFull());
REQUIRE(queue.IsEmpty());
}
}
TEST_CASE("Ring queue push operations in single thread", "[structure]") {
const std::size_t capacity = 15;
SECTION("Properties after pushing one element.") {
auto queue = structure::RingQueue<std::shared_ptr<dummy::DummyObject>>(
capacity);
const auto dummy1 = dummy::DummyObject(0);
queue.Push(std::make_unique<dummy::DummyObject>(0));
REQUIRE(queue.GetSize() == 1);
REQUIRE(!queue.IsFull());
REQUIRE(!queue.IsEmpty());
}
SECTION("Properties after pushing two elements.") {
auto queue = structure::RingQueue<std::shared_ptr<dummy::DummyObject>>(
capacity);
queue.Push(std::make_unique<dummy::DummyObject>(0));
queue.Push(std::make_unique<dummy::DummyObject>(0));
REQUIRE(queue.GetSize() == 2);
REQUIRE(!queue.IsFull());
REQUIRE(!queue.IsEmpty());
}
SECTION("Properties after pushing the maximum amount of elements.") {
auto queue =
structure::RingQueue<std::shared_ptr<dummy::DummyObject>>(1);
queue.Push(std::make_unique<dummy::DummyObject>(0));
REQUIRE(queue.GetSize() == 1);
REQUIRE(queue.IsFull());
REQUIRE(!queue.IsEmpty());
}
SECTION("Properties after pushing too many elements.") {
auto queue =
structure::RingQueue<std::shared_ptr<dummy::DummyObject>>(1);
queue.Push(std::make_unique<dummy::DummyObject>(0));
bool is_exception = false;
try {
queue.Push(std::make_unique<dummy::DummyObject>(0));
} catch (const structure::MaximumCapacityReachedError& error) {
is_exception = true;
}
REQUIRE(is_exception);
REQUIRE(queue.GetSize() == 1);
REQUIRE(queue.IsFull());
REQUIRE(!queue.IsEmpty());
}
SECTION("Specific error case: pushing one element in a 0-capacity queue.") {
auto queue =
structure::RingQueue<std::shared_ptr<dummy::DummyObject>>(0);
bool is_exception = false;
try {
queue.Push(std::make_unique<dummy::DummyObject>(0));
} catch (const structure::MaximumCapacityReachedError& error) {
is_exception = true;
}
REQUIRE(is_exception);
}
SECTION("Try pushing an element.") {
std::size_t capacity = 5;
auto queue = structure::RingQueue<std::shared_ptr<dummy::DummyObject>>(
capacity);
for (std::size_t index = 0; index < capacity + 1; index++) {
queue.TryPush(std::make_unique<dummy::DummyObject>(0));
}
REQUIRE(queue.GetSize() == capacity);
}
}
TEST_CASE("Ring queue consume operations in single thread",
"[structure]") {
const std::size_t capacity = 15;
SECTION("Properties after consuming one element.") {
auto queue = structure::RingQueue<std::shared_ptr<dummy::DummyObject>>(
capacity);
queue.Push(std::make_unique<dummy::DummyObject>(42));
REQUIRE(queue.ConsumeNext()->GetValue() == 42);
REQUIRE(queue.GetSize() == 0);
REQUIRE(!queue.IsFull());
REQUIRE(queue.IsEmpty());
}
SECTION("Properties after consuming two elements.") {
auto queue = structure::RingQueue<std::shared_ptr<dummy::DummyObject>>(
capacity);
queue.Push(std::make_unique<dummy::DummyObject>(42));
REQUIRE(queue.ConsumeNext()->GetValue() == 42);
REQUIRE(queue.GetSize() == 0);
REQUIRE(!queue.IsFull());
REQUIRE(queue.IsEmpty());
}
SECTION("Properties after consuming one element in a two-element queue.") {
auto queue = structure::RingQueue<std::shared_ptr<dummy::DummyObject>>(
capacity);
queue.Push(std::make_unique<dummy::DummyObject>(0));
queue.Push(std::make_unique<dummy::DummyObject>(0));
REQUIRE(queue.ConsumeNext());
REQUIRE(queue.GetSize() == 1);
REQUIRE(!queue.IsFull());
REQUIRE(!queue.IsEmpty());
}
SECTION("Properties after consuming too many elements.") {
auto queue =
structure::RingQueue<std::shared_ptr<dummy::DummyObject>>(1);
queue.Push(std::make_unique<dummy::DummyObject>(42));
queue.ConsumeNext();
bool is_exception = false;
try {
queue.ConsumeNext();
} catch (const structure::EmptyError& error) {
is_exception = true;
}
REQUIRE(is_exception);
REQUIRE(queue.GetSize() == 0);
REQUIRE(!queue.IsFull());
REQUIRE(queue.IsEmpty());
}
SECTION("Order is respected.") {
auto queue =
structure::RingQueue<std::shared_ptr<dummy::DummyObject>>(3);
queue.Push(std::make_unique<dummy::DummyObject>(1));
queue.Push(std::make_unique<dummy::DummyObject>(2));
queue.Push(std::make_unique<dummy::DummyObject>(3));
REQUIRE(queue.ConsumeNext().get()->GetValue() == 1);
REQUIRE(queue.ConsumeNext().get()->GetValue() == 2);
REQUIRE(queue.ConsumeNext().get()->GetValue() == 3);
}
SECTION("Specific error case: consuming one element in a 0-capacity queue.") {
auto queue =
structure::RingQueue<std::shared_ptr<dummy::DummyObject>>(0);
bool is_exception = false;
try {
queue.ConsumeNext();
} catch (const structure::EmptyError& error) {
is_exception = true;
}
REQUIRE(is_exception);
}
SECTION("Try consuming an element.") {
std::size_t capacity = 5;
auto queue = structure::RingQueue<std::shared_ptr<dummy::DummyObject>>(
capacity);
for (std::size_t index = 0; index < capacity; index++) {
queue.Push(std::make_unique<dummy::DummyObject>(0));
}
for (std::size_t index = 0; index < capacity + 1; index++) {
const auto element = queue.TryConsumeNext();
const bool is_element = element.has_value();
const bool is_okay = index < capacity ? is_element : !is_element;
REQUIRE(is_okay);
}
REQUIRE(queue.GetSize() == 0);
}
}
TEST_CASE("Ring queue pushing operations in multiple threads",
"[structure]") {
const std::size_t capacity = 15;
SECTION("Usage in threads: push operations.") {
std::size_t thread_number = 5;
auto queue =
structure::RingQueue<std::shared_ptr<dummy::DummyObject>>(5);
std::vector<std::thread> threads;
for (std::size_t index = 0; index < thread_number; index++) {
threads.push_back(std::thread([&queue]() {
queue.Push(std::make_unique<dummy::DummyObject>(0));
}));
}
std::for_each(threads.begin(), threads.end(),
[](std::thread& thread) { thread.join(); });
REQUIRE(queue.GetSize() == thread_number);
}
}
TEST_CASE("Ring queue consume operations in multiple threads",
"[structure]") {
SECTION("Usage in threads: consume operations.") {
std::size_t thread_number = 5;
auto queue =
structure::RingQueue<std::shared_ptr<dummy::DummyObject>>(5);
std::vector<std::thread> threads;
for (std::size_t index = 0; index < thread_number; index++) {
queue.Push(std::make_unique<dummy::DummyObject>(0));
}
for (std::size_t index = 0; index < thread_number; index++) {
threads.push_back(std::thread([&queue]() { queue.ConsumeNext(); }));
}
std::for_each(threads.begin(), threads.end(),
[](std::thread& thread) { thread.join(); });
REQUIRE(queue.GetSize() == 0);
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T15:38:51.017",
"Id": "510897",
"Score": "0",
"body": "Are you using CppUNIT or some other unit testing framework?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T15:41:03.603",
"Id": "510898",
"Score": "0",
"body": "I used **[Catch2](https://github.com/catchorg/Catch2)** for all of my tests!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T13:26:24.230",
"Id": "510952",
"Score": "0",
"body": "In addition to the accepted answer. Shouldn't `tryPush` let me know whether it succeeded?"
}
] |
[
{
"body": "<h1><code>ConsumeNext()</code> should not return a reference</h1>\n<p>The problem with <code>ConsumeNext()</code> is that it returns a reference to an object. However, that element is also marked as consumed. So the caller cannot safely access this element, since it can be overwritten by a call to <code>Push()</code> from another thread.</p>\n<p>There are two options to solve this:</p>\n<ol>\n<li>Have <code>ConsumeNext()</code> return by value, just like <code>TryConsumeNext()</code> does</li>\n<li>Split <code>ConsumeNext()</code> into a <code>GetNext()</code> that returns a reference but does not consume, and a <code>ConsumeNext()</code> that returns <code>void</code>.</li>\n</ol>\n<p>Returning by value has the drawback that <code>T</code> needs to be copied, which can be expensive or impossible, depending on the exact type. So I recommmend going for option 2. This, by the way, is exactly what the STL does for containers such as <a href=\"https://en.cppreference.com/w/cpp/container/stack\" rel=\"noreferrer\"><code>std::stack</code></a>.</p>\n<h1>Consider avoiding the <code>head == tail</code> ambiguity</h1>\n<p>The problem with having a head and tail index or pointer for a ringbuffer is that when <code>head == tail</code>, this can either be because the ringbuffer is empty or that it is completely full. You solved this by adding an extra variable <code>is_full_</code>, and checking this in many places.</p>\n<p>A neater solution in my opinion is to not have a <code>tail_</code> index, but rather a <code>size_</code> variable that tracks how many elements are actually in use. This simplifies a lot of code. Of course, you now have to derive the tail index in <code>Push()</code> and <code>TryPush()</code>, like so:</p>\n<pre><code>elements_[(head_ + size_++) % capacity_] = std::forward<T>(element);\n</code></pre>\n<h1>Useless lock in <code>GetCapacity()</code></h1>\n<p>You don't need to take the lock in <code>GetCapacity()</code>, since the capacity can never change after constructing a <code>RingQueue</code>. You can even make <code>capacity_</code> itself a <code>const</code> variable.</p>\n<h1>Remove <code>IsEmpty()</code> and <code>IsFull()</code></h1>\n<p>The functions <code>IsEmpty()</code> and <code>IsFull()</code> don't return useful information to users of your class. By the time they return <code>true</code> or <code>false</code>, that value might not reflect the actual state of the <code>RingQueue</code> anymore, since another thread might have added or removed elements from it. Keeping them available as <code>public</code> functions invites <a href=\"https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use\" rel=\"noreferrer\">TOCTTOU</a> bugs.</p>\n<p>You might consider keeping them as <code>private</code> functions, but then they don't need to take the lock anymore, and you can change <code>mutex_</code> from a <code>std::recursive_mutex</code> to the slightly more efficient regular <code>std::mutex</code>.</p>\n<h1>Naming things</h1>\n<p>I recommend you give the member functions names that match those of STL containers, in particular those of <a href=\"https://en.cppreference.com/w/cpp/container/queue\" rel=\"noreferrer\"><code>std::queue</code></a>, so it is easier use your <code>RingQueue</code>s in code that also uses the STL. So:</p>\n<ul>\n<li><code>Push()</code> -> <code>push()</code> and <code>emplace()</code></li>\n<li><code>ConsumeNext()</code> -> <code>front()</code> and <code>pop()</code></li>\n<li><code>Clear()</code> -> <code>clear()</code></li>\n<li><code>GetCapacity()</code> -> <code>capacity()</code></li>\n</ul>\n<h1>Add a function to wait for the possibility to push/pop</h1>\n<p>It's nice that this function is thread-safe, but that implies you want to use this from multiple threads. In particular, consider a producer-consumer scenario, where one thread wants to add elements to the queue, and another wants to remove them. They might not run at the same speed, so if the queue gets full, you ideally want to let the producer sleep until the queue is no longer full, and conversely, if the queue is empty, you want the consumer to sleep until an element was added. This can be implemented quite easily by using a <a href=\"https://en.cppreference.com/w/cpp/thread/condition_variable\" rel=\"noreferrer\"><code>std::condition_variable</code></a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T22:59:26.620",
"Id": "510925",
"Score": "0",
"body": "Thank you so much for your detailed explanation! I'll make the changes and I think following the STL naming convention is definitely a much better choice indeed. I can't thank you enough!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T22:26:18.703",
"Id": "259098",
"ParentId": "259087",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "259098",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T14:57:35.407",
"Id": "259087",
"Score": "6",
"Tags": [
"c++",
"reinventing-the-wheel",
"c++17"
],
"Title": "Writing a thread-safe ring queue in C++17"
}
|
259087
|
<p>I want to ask question about a better way for implementing single endpoint REST.</p>
<p>I want to build a rest API but I want it to only have single endpoint like: <code>graphql</code>, where you only have like: <code>host/graphql</code>.</p>
<p>I already doing this example in <code>laravel</code> where you need to put a key and method to go to a certain API.</p>
<p>The body look like this (example of calling product API with single endpoint).</p>
<p>Calling get all product:</p>
<pre><code> {
"key":"product/all",
"method":"GET"
}
</code></pre>
<p>And this is the get one (product/{id}):</p>
<pre><code> {
"key":"product",
"method":"GET",
"payload":"{\"id\":\"1\"}"
}
</code></pre>
<p>This is also work fine with post, put and delete.</p>
<p>Here is the single endpoint code (I use <code>php laravel</code> as example because it fast to make API):</p>
<pre><code> public function bridge(Request $request)
{
$host = "http://127.0.0.1:8000/api/";
if ($request->has("payload")) {
$bounds = html_entity_decode($request->payload);
$payload = json_decode($bounds, true);
}
if (strtoupper($request->method) == "POST") {
try {
$url = $host . $request->key;
$request = Request::create($url, 'POST', []);
$response = Route::dispatch($request);
return $response;
} catch (\Throwable $th) {
$data["data"] = [];
$data["success"] = false;
$data["code"] = 500;
$data["message"] = $th->getMessage();
return $data;
}
} else if (strtoupper($request->method) == "PUT") {
try {
$url = $host . $request->key . '/' . $payload['id'];
$request = Request::create($url, 'PUT', []);
$response = Route::dispatch($request);
return $response;
} catch (\Throwable $th) {
$data["data"] = [];
$data["success"] = false;
$data["code"] = 500;
$data["message"] = $th->getMessage();
return $data;
}
} else if (strtoupper($request->method) == "DELETE") {
try {
$url = $host . $request->key . '/' . $payload['id'];
$request = Request::create($url, 'DELETE', []);
$response = Route::dispatch($request);
return $response;
} catch (\Throwable $th) {
$data["data"] = [];
$data["success"] = false;
$data["code"] = 500;
$data["message"] = $th->getMessage();
return $data;
}
} else {
$url = $host . $request->key;
try {
if ($request->has("payload")) {
$url = $host . $request->key . "/" . $payload['id'];
}
$request = Request::create($url, 'GET');
$response = Route::dispatch($request);
return $response;
} catch (\Throwable $th) {
$data["data"] = [];
$data["success"] = false;
$data["code"] = 500;
$data["message"] = $th->getMessage();
return $data;
}
}
}
</code></pre>
<p>As you can see there. It is calling the API twice "bridge" and the "key" API.</p>
<p>The cons here:</p>
<ul>
<li>call request twice;</li>
<li>you can only put one /{id} variable (or more if you declare it).</li>
</ul>
<p>Pros:</p>
<ul>
<li>it only one endpoint so it will be easy to make an api helper in the frontend (maybe XD).</li>
</ul>
<p>Can you show me a better way of doing this?
Tell me your tips and thought or maybe show some code (any language is fine).</p>
|
[] |
[
{
"body": "<p>I only have a few quibbling remarks:</p>\n<ul>\n<li>Don't Repeat Yourself (D.R.Y.)\n<ul>\n<li>Declare <code>$url = $host . $request->key</code> unconditionally at the start of your method (say, after <code>$host</code>). Then append text to it if/when needed <code>$url .= '/' . $payload['id'];</code>.</li>\n<li><code>strtoupper($request->method)</code> is done in each conditional expression. It is better practice to mutate the string once. You're also checking the same data for different strings, this is what <code>switch-case</code> blocks are for.</li>\n<li>Rather than writing <code>$data</code> (a non-descriptive variable name) over and over, omit the variable declaration entirely and write the data directly into the <code>return</code>. I regularly advise against single-use variable declarations unless they valuably reduce code width or improve readability.</li>\n</ul>\n</li>\n<li><code>else if</code> should be <code>elseif</code> in PHP to comply with the PSR-12 coding standard.</li>\n<li>All of your thrown exceptions are handled identically, so it seems to be a much cleaner choice to wrap your whole switch block in a single <code>try-catch</code> block.</li>\n<li>Maybe you'd like to see the payload when there is a thrown exception; if so, use <code>"data" => $payload ?? []</code> in the return.</li>\n</ul>\n<p>Your code might be rewrite as:</p>\n<pre><code>public function bridge(Request $request)\n{\n $host = "http://127.0.0.1:8000/api/";\n $url = $host . $request->key;\n\n if ($request->has("payload")) {\n $payload = json_decode(html_entity_decode($request->payload), true);\n }\n\n try {\n switch (strtoupper($request->method)) {\n case "POST":\n return Route::dispatch(Request::create($url, 'POST', []));\n case "PUT":\n $url .= '/' . $payload['id'];\n return Route::dispatch(Request::create($url, 'PUT', []));\n case "DELETE":\n $url .= '/' . $payload['id'];\n return Route::dispatch(Request::create($url, 'DELETE', []));\n default:\n if ($request->has("payload")) {\n $url .= "/" . $payload['id'];\n }\n return Route::dispatch(Request::create($url, 'GET'));\n }\n } catch (\\Throwable $th) {\n return [\n "data" => $payload ?? [],\n "success" => false,\n "code" => 500,\n "message" => $th->getMessage(),\n ];\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T23:11:50.087",
"Id": "259101",
"ParentId": "259092",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259101",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T17:47:46.503",
"Id": "259092",
"Score": "4",
"Tags": [
"php",
"api",
"laravel",
"rest"
],
"Title": "Single end point REST API"
}
|
259092
|
<p>For a project, I need to make use of Selenium WebDrivers, and since they're so expensive to start, I decided to write a pool to manage them.</p>
<pre><code>with driver_pool.FirefoxWebDriverPool(5) as d_pool:
# Sequentially visit a page 1000 times
for _ in range(1000):
# Don't actually run this. I accidentally go myself rate-limited by SO for doing this.
d_pool.run_job(lambda driver: driver.get("http://www.stackoverflow.com"))
</code></pre>
<p>I realized after writing this that really, it could be generalized to handle arbitrary objects, but for the sake of keeping it simple, I'm going to keep it as is. I could also generalize it to handle all WebDrivers, but drivers have slightly different interfaces, and I wanted to allow going into headless mode, so again, to keep it simple, I'm sticking with Firefox.</p>
<p>I've never written an object pool before, and I haven't written thread-safe code meant for a multi-threaded environment in awhile. I'd like tips on how this can be cleaned up. I'm making use of multiple primitives, so if I'd like to know if it can be simplified. <code>_pending_lock</code> and <code>_n_pending</code> are being used because I realized while writing <code>terminate</code> that I had no way of knowing if there are any jobs outstanding that may cause a driver to get missed while terminating.</p>
<p>The solution I went for is to count how many threads are currently stuck waiting inside the method. If a job finishes and it was the last job, it signals an <code>Event</code> (<code>_can_terminate</code>) that it's safe to terminate. If another job is submitted, the event is cleared to indicate that it's no longer safe. When <code>terminate</code> is called, it will prevent any new jobs from being submitted, <code>wait</code> for the all-clear, then pop drivers while calling <code>quit</code> on them. My main concern is preventing resource leakage because of their potential to bog down my system if leaked repeatedly.</p>
<p>Any tips at all would be appreciated.</p>
<pre><code>from __future__ import annotations
from typing import Callable, Optional, TypeVar
from threading import Lock, Event
import queue
from selenium.webdriver import Firefox
from selenium.webdriver.firefox.options import Options
T = TypeVar("T")
class FirefoxWebDriverPool:
def __init__(self, max_drivers: int, headless: bool = True):
self._available_drivers = queue.Queue(maxsize=max_drivers)
self._terminating = False
self._can_terminate = Event()
self._pending_lock = Lock() # TODO: Find a clean way of using Queue.qsize instead
self._n_pending = 0
options = Options()
options.headless = headless
for _ in range(max_drivers):
self._available_drivers.put(Firefox(options=options))
def run_job(self, job: Callable[[Firefox], T]) -> Optional[T]:
"""Runs a job in a browser pool.
Will return the result of the job if the job succeeded, or None if the job failed
due to termination of the pool being in progress."""
driver = None
try:
with self._pending_lock:
if self._terminating:
return None
else:
self._n_pending += 1
self._can_terminate.clear()
driver = self._available_drivers.get()
return job(driver)
finally:
# Should never be None, but could theoretically be if a lock throws due to a bug in our logic.
if driver is not None:
self._available_drivers.put(driver) # Should not be possible to be full.
with self._pending_lock:
self._n_pending -= 1
if self._n_pending == 0:
self._can_terminate.set()
def terminate(self) -> None:
self._terminating = True
self._can_terminate.wait()
while self._available_drivers.qsize() > 0:
driver: Firefox = self._available_drivers.get()
driver.quit()
def __enter__(self) -> FirefoxWebDriverPool:
return self
def __exit__(self, *_) -> None:
self.terminate()
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T19:34:04.517",
"Id": "259093",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"selenium",
"webdriver"
],
"Title": "A thread-safe WebDriver pool to submit browsing jobs to"
}
|
259093
|
<p>Learning Modern C++ patterns and this ended up being the direction I went to to create an encapsulation of SDL's window management, while trying to stay with RAII practices. This is meant to be a base for a software renderer (and possibly expanding to OpenGL after that).</p>
<blockquote>
<p>window/input.h</p>
</blockquote>
<pre><code>#pragma once
#include <map>
// State of a keyboard key
enum class KeyboardKeyState {
Up,
Down,
Pressed, // Key was previously down last check and just changed to the up state
};
// Keyboard keys that we are listening for events for
enum class KeyboardKey {
W, S, A, D, LeftArrow, RightArrow, UpArrow, DownArrow
};
struct InputState {
std::map<KeyboardKey, KeyboardKeyState> Keys{
{KeyboardKey::W, KeyboardKeyState::Up},
{KeyboardKey::S, KeyboardKeyState::Up},
{KeyboardKey::A, KeyboardKeyState::Up},
{KeyboardKey::D, KeyboardKeyState::Up},
{KeyboardKey::LeftArrow, KeyboardKeyState::Up},
{KeyboardKey::UpArrow, KeyboardKeyState::Up},
{KeyboardKey::DownArrow, KeyboardKeyState::Up},
{KeyboardKey::RightArrow, KeyboardKeyState::Up},
};
bool LeftMouseClicked{};
bool RightMouseClicked{};
int MouseDragX{};
int MouseDragY{};
int MouseScrollAmount{};
};
</code></pre>
<blockquote>
<p>window/window_state.h</p>
</blockquote>
<pre><code>#pragma once
struct WindowState {
bool quitRequested{false};
};
</code></pre>
<blockquote>
<p>window/window_settings.h</p>
</blockquote>
<pre><code>#pragma once
#include <optional>
#include <string>
#include <SDL.h>
// How the window will be rendered to (e.g. manually via a pixel buffer, OGL context, Vulkan context, etc...)
enum class WindowRenderMode {
Unspecified, // No render mode selected. Will throw exceptions
ByPixelBuffer, // Rendered using software rendering directly to a window's pixel buffer
};
// Contains options for the window display
struct WindowSettings {
// How many pixels wide the window should be. If unspecified it will match the display's width.
std::optional<int> Width;
// How many pixels tall the window should be. If unspecified it will match the display's height
std::optional<int> Height;
// If the window should be borderless or not
bool Borderless{false};
// The title to give the window
std::string Title{};
// How we intend to render to the window
WindowRenderMode RenderMode{WindowRenderMode::Unspecified};
};
</code></pre>
<blockquote>
<p>window/sdl/sdl_raii.h</p>
</blockquote>
<pre><code>#pragma once
// C++ can't deal with classes that use forward declared types, so we need all these RAII types
// in it's own header to keep it out of sdl_app_window.h
#include <memory>
#include <vector>
#include <SDL.h>
#include "window/window_settings.h"
namespace sdl_raii {
class SdlWindow {
public:
std::unique_ptr<SDL_Window, void(*)(SDL_Window*)> pointer;
explicit SdlWindow(const WindowSettings& windowSettings);
SdlWindow(const SdlWindow& other) = delete;
SdlWindow(SdlWindow&& other) = default;
};
class SdlRenderer {
public:
std::unique_ptr<SDL_Renderer, void(*)(SDL_Renderer*)> pointer;
explicit SdlRenderer(const SdlWindow& window);
SdlRenderer(const SdlRenderer& other) = delete;
SdlRenderer(SdlRenderer&& other) = default;
};
class SdlFullWindowTexture {
public:
std::unique_ptr<SDL_Texture, void(*)(SDL_Texture*)> pointer;
SdlFullWindowTexture(const WindowSettings& windowSettings, const SdlRenderer& renderer);
SdlFullWindowTexture(const SdlFullWindowTexture& other) = delete;
SdlFullWindowTexture(SdlFullWindowTexture&& other) = default;
};
}
</code></pre>
<blockquote>
<p>window/sdl/sdl_raii.cpp</p>
</blockquote>
<pre><code>#include <stdexcept>
#include "sdl_raii.h"
using namespace sdl_raii;
std::unique_ptr<SDL_Window, void (*)(SDL_Window*)> CreateSdlWindowPointer(const WindowSettings &windowSettings) {
if (windowSettings.RenderMode != WindowRenderMode::ByPixelBuffer) {
std::string error = "Unsupported render mode: ";
error += std::to_string((int) windowSettings.RenderMode);
throw std::runtime_error{error};
}
if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
std::string error{"Error initializing SDL: "};
error += SDL_GetError();
throw std::runtime_error{error};
}
unsigned int flags = windowSettings.Borderless ? SDL_WINDOW_BORDERLESS : 0;
auto sdlWin = SDL_CreateWindow(windowSettings.Title.c_str(),
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
windowSettings.Width.value(),
windowSettings.Height.value(),
flags);
if (sdlWin == nullptr) {
std::string error = "Error creating SDL window: ";
error += SDL_GetError();
throw std::runtime_error{error};
}
return std::unique_ptr<SDL_Window, void(*)(SDL_Window*)>(sdlWin, &SDL_DestroyWindow);
}
std::unique_ptr<SDL_Renderer, void (*)(SDL_Renderer*)> CreateSdlRendererPointer(const SdlWindow& sdlWindow) {
auto renderer = SDL_CreateRenderer(sdlWindow.pointer.get(), -1, 0);
if (!renderer) {
std::string error{"Error creating renderer: "};
error += SDL_GetError();
throw std::runtime_error{error};
}
return std::unique_ptr<SDL_Renderer, void (*)(SDL_Renderer*)>(renderer, &SDL_DestroyRenderer);
}
std::unique_ptr<SDL_Texture, void (*)(SDL_Texture*)>
CreateSdlTexturePointer(const WindowSettings &windowSettings, const SdlRenderer& sdlRenderer) {
auto pointer = SDL_CreateTexture(sdlRenderer.pointer.get(),
SDL_PIXELFORMAT_ARGB8888,
SDL_TEXTUREACCESS_STREAMING,
windowSettings.Width.value(),
windowSettings.Height.value());
return std::unique_ptr<SDL_Texture, void (*)(SDL_Texture*)>(pointer, &SDL_DestroyTexture);
}
SdlWindow::SdlWindow(const WindowSettings &windowSettings)
: pointer{CreateSdlWindowPointer(windowSettings)} {
}
SdlRenderer::SdlRenderer(const SdlWindow& window)
: pointer{CreateSdlRendererPointer(window)} {
}
SdlFullWindowTexture::SdlFullWindowTexture(const WindowSettings &windowSettings, const SdlRenderer &renderer)
: pointer{CreateSdlTexturePointer(windowSettings, renderer)}{
}
</code></pre>
<blockquote>
<p>window/sdl/sdl_app_window.h</p>
</blockquote>
<pre><code>#pragma once
#include <SDL.h>
#include <memory>
#include <vector>
#include <span>
#include "window/input.h"
#include "window/window_state.h"
#include "window/window_settings.h"
#include "sdl_raii.h"
// A window that's managed by SDL
class SdlAppWindow {
public:
explicit SdlAppWindow(WindowSettings settings);
SdlAppWindow(const SdlAppWindow& other) = delete;
SdlAppWindow(SdlAppWindow&& other) = default;
// Retrieves a mutable view of the raw full screen pixel buffer.
std::span<unsigned int> GetPixelBuffer();
// Performs any work that needs to be done at the beginning of a frame.
void BeginFrame();
// Called after all render operations have occurred, in order to push the renderings to the window
void PresentFrame();
void HandleWindowEvents(WindowState& windowState, InputState& inputState);
private:
const WindowSettings windowSettings;
sdl_raii::SdlWindow sdlWindow;
sdl_raii::SdlRenderer sdlRenderer;
sdl_raii::SdlFullWindowTexture sdlFullWindowTexture;
// Full screen render buffer for use in the ByPixelBuffer render mode
std::vector<unsigned int> pixelBuffer;
static WindowSettings GetUpdatedWindowSettings(WindowSettings windowSettings);
std::vector<unsigned int> CreatePixelBuffer();
};
</code></pre>
<blockquote>
<p>window/sdl/sdl_app_window.cpp</p>
</blockquote>
<pre><code>#include <utility>
#include <stdexcept>
#include "sdl_app_window.h"
using std::vector;
SdlAppWindow::SdlAppWindow(WindowSettings settings) :
windowSettings{GetUpdatedWindowSettings(std::move(settings))},
sdlWindow{windowSettings},
sdlRenderer{sdlWindow},
sdlFullWindowTexture(windowSettings, sdlRenderer),
pixelBuffer{CreatePixelBuffer()} {
}
void SdlAppWindow::BeginFrame() {
switch (windowSettings.RenderMode) {
case WindowRenderMode::ByPixelBuffer:
// fill to black
std::fill(pixelBuffer.begin(), pixelBuffer.end(), 0xFF000000);
break;
default:
std::string error{"No begin frame support for render mode: "};
error += std::to_string((int) windowSettings.RenderMode);
throw std::runtime_error{error};
}
}
void SdlAppWindow::PresentFrame() {
int pitch = windowSettings.Width.value() * (int) sizeof (int);
SDL_UpdateTexture(sdlFullWindowTexture.pointer.get(),
nullptr,
pixelBuffer.data(),
pitch);
SDL_RenderCopy(sdlRenderer.pointer.get(), sdlFullWindowTexture.pointer.get(), nullptr, nullptr);
SDL_RenderPresent(sdlRenderer.pointer.get());
}
WindowSettings SdlAppWindow::GetUpdatedWindowSettings(WindowSettings windowSettings) {
SDL_DisplayMode displayMode;
SDL_GetCurrentDisplayMode(0, &displayMode);
if (!windowSettings.Width.has_value()) {
windowSettings.Width = displayMode.w;
}
if (!windowSettings.Height.has_value()) {
windowSettings.Height = displayMode.h;
}
return windowSettings;
}
std::vector<unsigned int> SdlAppWindow::CreatePixelBuffer() {
std::vector<unsigned int> result(windowSettings.Width.value() * windowSettings.Height.value());
return result;
}
std::span<unsigned int> SdlAppWindow::GetPixelBuffer() {
return std::span<unsigned int>{pixelBuffer};
}
void SdlAppWindow::HandleWindowEvents(WindowState& windowState, InputState &inputState) {
SDL_Event sdlEvent;
while (SDL_PollEvent(&sdlEvent))
{
switch (sdlEvent.type) {
case SDL_QUIT:
windowState.quitRequested = true;
break;
// todo: add case statements for keyboard/mouse processing
}
}
}
</code></pre>
<blockquote>
<p>main.cpp</p>
</blockquote>
<pre><code>#include <iostream>
#include <SDL.h>
#include "window/window_settings.h"
#include "window/sdl/sdl_app_window.h"
int main(int argc, char* argv[]) {
constexpr unsigned int targetFps = 30;
constexpr unsigned int targetFrameTime = 1000 / targetFps;
WindowSettings settings{
1024,
768,
false,
std::string{"Test Window"},
WindowRenderMode::ByPixelBuffer,
};
SdlAppWindow appWindow{settings};
InputState inputState;
WindowState windowState;
unsigned int previousFrameTime = 0;
bool isRunning = true;
while(isRunning) {
unsigned int timeSinceLastFrame = SDL_GetTicks() - previousFrameTime;
int timeToWait = targetFrameTime - timeSinceLastFrame;
if (timeToWait > 0 && timeToWait <= targetFrameTime) {
SDL_Delay(timeToWait);
}
previousFrameTime = SDL_GetTicks();
appWindow.HandleWindowEvents(windowState, inputState);
appWindow.BeginFrame();
auto buffer = appWindow.GetPixelBuffer();
std::fill(buffer.begin(), buffer.end(), 0xFFFF0000);
appWindow.PresentFrame();
isRunning = !windowState.quitRequested;
}
return 0;
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Note, this is just a partial review of your code.</p>\n<h1>Use namespaces and nested classes</h1>\n<p>The way you named things in your code is a bit inconsistent. There is the namespace <code>sdl_raii</code> which contains classes like <code>SdlWindow</code>, but then there is also <code>SdlAppWindow</code> which is not in a namespace, and there are also classes like <code>WindowState</code> which are not in a namespace and don't have the <code>Sdl</code> prefix.</p>\n<p>I would recommend putting everything in the namespace <code>SDL</code>, and nesting classes where appropriate. For example, since <code>WindowSettings</code> seems to be holding configuration specific to <code>SdlWindow</code>, the following hierarchy makes more sense:</p>\n<pre><code>namespace SDL {\n class Window {\n public:\n class Settings {\n ...\n };\n\n Window(const Settings &settings);\n ...\n }\n};\n</code></pre>\n<p>The application code would then look like:</p>\n<pre><code>\nint main(...) {\n SDL::Window::Settings settings{\n 1024,\n 768,\n false,\n "Test Window",\n SDL::Window::RenderMode::ByPixelBuffer,\n };\n\n SDL::AppWindow appWindow{settings};\n ...\n}\n</code></pre>\n<p>This also allows the application to use <code>using namespace SDL</code> or <code>using SDL::Window</code> for example, to reduce the amount of typing necessary, if desired.</p>\n<h1>Move the code from <code>Create...Pointer()</code> into the constructors</h1>\n<p>The constructors of the classes in <code>sdl_raii</code> don't do anything except call <code>Create...Pointer()</code>, and the latter functions are not called by anything else, so this separation seems quite unnecessary to me. I would just move all the code from those <code>Create</code> functions into the constructors of the corresponding classes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T01:37:47.803",
"Id": "510930",
"Score": "0",
"body": "The reason I used `sdl_raii` namespace for the 3 classes but not `SdlAppWindow` is because `SdlAppWindow` is application specific while the others are very specific for RAII purposes. So I moved the 3 resource classes into their own namespace so when you are referring to `SdlAppWindow` you aren't given the option for the others (since 0% chance you want the raii classes. I could not get nesting to work properly due to ordering issues (I could not get forward declarations with nested classes to work properly and the whole thing looked like a mess)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T01:38:20.120",
"Id": "510931",
"Score": "0",
"body": "Re constructors: I did it this way as otherwise you get double allocations. Maybe that's not a big deal though?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T09:05:55.867",
"Id": "510944",
"Score": "1",
"body": "If you want to abstract the lower level window handling away, then sure, but someone might actually want to construct a `SdlWindow` directly if `SdlAppWindow` doesn't provide what they need. As for the constructors: there are no double allocations."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T23:11:05.177",
"Id": "259100",
"ParentId": "259096",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T21:29:41.347",
"Id": "259096",
"Score": "4",
"Tags": [
"c++"
],
"Title": "C++, SDL, and RAII"
}
|
259096
|
<p>The following is my attempt to implement a <code>insert_sorted()</code> C++ function that accepts any sorted STL container and item and inserts it at the right position in the container:</p>
<pre><code>template<template<typename, typename, typename> typename C, typename T1, typename Comp, typename A, typename T2>
inline typename C<std::enable_if_t<std::is_convertible_v<T1, std::remove_reference_t<T2>>, T1>, Comp, A>::iterator
insert_sorted (C<T1, Comp, A> & c, T2 && item)
{
return c.insert (c.end(), std::forward<T2> (item));
}
template<template<typename, typename> typename C, typename T1, typename A, typename T2, typename Comp = std::less<T1>>
inline typename C<std::enable_if_t<std::is_convertible_v<T1, std::remove_reference_t<T2>>, T1>, A>::iterator
insert_sorted (C<T1, A> & c, T2 && item, Comp comp = Comp{})
{
return c.insert (std::upper_bound (std::begin (c), std::end (c), static_cast<T1>(item), comp), std::forward<T2> (item));
}
</code></pre>
<p>These two compile and work fine; the first overload works for set-like containers, while the second for vector-like containers.</p>
<p>I was wondering if you see any drawbacks to this solution and if there is a more generic way to approach the problem, that is, is it possible to write a single <code>insert_sorted()</code> function that does the same as the above two?</p>
<p>EDIT:
Thanks to the comments, I was able to replace the two template functions above with the following:</p>
<pre><code>template<typename C, typename T, typename Comp = std::less<T>,
typename = std::enable_if<std::is_convertible_v<std::remove_reference_t<T>, typename C::value_type>>>
inline auto insert_sorted (C & c, T && item, Comp comp = Comp{})
{
return c.insert (std::upper_bound (std::begin (c), std::end (c), item, comp), std::forward<T> (item));
}
</code></pre>
<p>Thank you all for your help!</p>
|
[] |
[
{
"body": "<p><code>inline</code> is redundant when writing template functions.</p>\n<hr />\n<p>When we use <code>std::begin()</code> and <code>std::end()</code>, we should always consider whether we actually want to use <code>begin()</code> and <code>end()</code> of the type's namespace instead (argument-dependent lookup, aka ADL), with fallback to <code>std</code>:</p>\n<pre><code>using std::begin;\nusing std::end;\nreturn c.insert(std::upper_bound(begin(c), end(c), item, comp),\n std::forward<T>(item));\n</code></pre>\n<hr />\n<p>When we're inserting to a sorted container such as <code>std::set</code>, we probably want to use the container's <code>key_compare</code> as default, rather than <code>std::less<T></code>. That will require splitting back into two functions again. I prefer to split out a helper that returns an appropriate default comparator:</p>\n<pre><code>#include <functional>\n\ntemplate<typename C>\nauto comparator_for(const C& c)\n requires requires { c.key_comp(); }\n{\n return c.key_comp();\n}\n\ntemplate<typename C>\nauto comparator_for(const C&)\n{\n return std::less<typename C::value_type>{};\n}\n</code></pre>\n<p>We can then use it in an overload that defaults the parameter:</p>\n<pre><code>#include <algorithm>\n#include <concepts>\n#include <iterator>\n#include <utility>\n\ntemplate<typename C, typename T, typename Comp>\nauto insert_sorted(C& c, T&& item, Comp comp)\n requires std::convertible_to<T, typename C::value_type>\n{\n using std::begin;\n using std::end;\n return c.insert(std::upper_bound(begin(c), end(c), item, comp),\n std::forward<T>(item));\n}\n\ntemplate<typename C, typename T>\nauto insert_sorted(C& c, T&& item)\n{\n return insert_sorted(c, std::forward<T>(item), comparator_for(c));\n}\n</code></pre>\n<p>(I've used modern Concepts syntax rather than <code>std::enable_if</code>, as I find that easier to read).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T08:08:12.763",
"Id": "259115",
"ParentId": "259097",
"Score": "4"
}
},
{
"body": "<p>Just to present an alternative way of doing things: instead of using <code>insert()</code> and <code>std::upper_bound()</code>, you could use <code>push_back()</code> and <code>std::inplace_merge()</code>. If you are going to provide a ranges-like interface anyway, perhaps you could use <a href=\"https://en.cppreference.com/w/cpp/ranges\" rel=\"nofollow noreferrer\">std::ranges</a> and copy the interface of <a href=\"https://en.cppreference.com/w/cpp/algorithm/ranges/inplace_merge\" rel=\"nofollow noreferrer\"><code>std::ranges::inplace_merge()</code></a> as much as possible:</p>\n<pre><code>template<std::ranges::bidirectional_range R, class T, class Comp = std::ranges::less, class Proj = std::identity>\nrequires std::sortable<std::ranges::iterator_t<R>, Comp, Proj>\nstd::ranges::borrowed_iterator_t<R>\ninsert_sorted(R&& r, T&& item, Comp comp = {}, Proj proj = {}) {\n using std::end;\n using std::prev;\n r.push_back(item);\n return std::ranges::inplace_merge(r, prev(end(r)), comp, proj);\n}\n</code></pre>\n<p>Note that this doesn't work for <code>std::set</code>, but it does for <code>std::list</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-06T10:00:19.547",
"Id": "267724",
"ParentId": "259097",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T15:07:26.753",
"Id": "259097",
"Score": "6",
"Tags": [
"c++",
"stl"
],
"Title": "Insert into any sorted container"
}
|
259097
|
<p>I'm designing an algorithm that creates optimum teams based on everyone's availabilities (maximizes the amount of shared availability). To this end, I've made a function that takes in a dictionary of availabilities mapping person to an array of their availabilities throughout the week at every 15 minute point (e.g. [True, True, False,...,False]) and desired team size and outputs final teams. Here's my working code:</p>
<pre><code>import numpy as np
from itertools import combinations, chain
import operator
from functools import reduce
from tqdm import tqdm
import operator
def ncr(n, r):
"""N Choose R combination"""
r = min(r, n-r)
numer = reduce(operator.mul, range(n, n-r, -1), 1)
denom = reduce(operator.mul, range(1, r+1), 1)
return numer // denom # or / in Python 2
NUM_PEOPLE = 100
TEAM_SIZE = 5
time_slots = 24*4*7
# random availabilities
availabilities = np.random.randint(2, size=(NUM_PEOPLE, time_slots), dtype="bool")
availabilities_dict = {}
for i, availability in enumerate(availabilities):
availabilities_dict[i] = availability
def make_teams(availabilities_dict, team_size):
"""
availabilities_dict form: {player: [0,0,0,...,1], player2: [0,0,0,0,1...,0]}
"""
sums = []
comb = combinations(availabilities_dict, TEAM_SIZE)
for i in tqdm(list(comb)):
sum_of_array = np.logical_and.reduce((np.array(availabilities[i,:]))).sum()
sums.append((i, sum_of_array))
sums.sort(key=operator.itemgetter(1))
sums.reverse()
assigned = []
teams = []
i = 0
while (len(assigned) < NUM_PEOPLE):
considering = list(sums[i][0])
none_assigned = True
for person in considering:
if person in assigned:
none_assigned = False
if none_assigned:
teams.append((considering, sums[i][1]))
for person in considering:
assigned.append(person)
i += 1
return teams
teams = make_teams(availabilities_dict, TEAM_SIZE)
</code></pre>
<p>Example output consists of a list of tuples (team, total blocks intersecting):</p>
<pre><code>[([15, 18, 42, 70, 94], 36),
([14, 30, 63, 80, 97], 36),
([1, 12, 40, 64, 88], 36),
([22, 48, 62, 72, 87], 34),
([25, 29, 35, 53, 85], 32),
([26, 31, 49, 60, 78], 31),
([13, 44, 79, 93, 96], 29),
([32, 59, 67, 71, 82], 28),
([24, 39, 41, 50, 91], 28),
([9, 28, 55, 92, 95], 28),
([5, 8, 11, 19, 86], 28),
([4, 33, 56, 76, 83], 27),
([2, 10, 16, 17, 69], 27),
([21, 43, 73, 75, 81], 24),
([7, 20, 57, 89, 99], 24),
([23, 36, 37, 58, 66], 22),
([52, 61, 65, 68, 84], 20),
([3, 27, 34, 47, 74], 18),
([6, 38, 51, 54, 77], 16),
([0, 45, 46, 90, 98], 9)]
</code></pre>
<p>But this took over 10 mins to run on my state of the art computer! Is there a way to still find an optimum team match without running through all of the possible combinations? How can I make it faster? Thank you!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T23:59:52.873",
"Id": "510926",
"Score": "1",
"body": "It seems unusual to treat this kind of thing as a maximization problem rather than a sufficiency problem. Does it really matter whether team players have maximum schedule alignment with each other or simply that they can all show up at scheduled times? I ask because sufficiency is usually easier/faster (algorithmically and computationally) than optimization."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T01:05:23.227",
"Id": "510927",
"Score": "0",
"body": "@FMc yes unfortunately, I do want my teams to each have maximum schedule alignment... my reasoning is that it will allow them much more flexibility in picking a time that works for them. By sufficiency, do you mean that we form teams based on a threshold of availability, and if a given combination is above it, we pair them up? If not, could you please explain what you mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T01:29:55.520",
"Id": "510928",
"Score": "0",
"body": "Yes, that's the idea: it's less player-friendly (I understand your intent), but it gets the job done For example, imagine a tournament coordinator saying, \"Hey, you said you were available. Stop griping.\" But there's nothing wrong with the goal you have. Just wanted to confirm that you really meant it, so to speak."
}
] |
[
{
"body": "<h1>Review</h1>\n<h2>Imports</h2>\n<p><code>import operator</code> is being done twice, which is unnecessary.</p>\n<p><code>from itertools import combinations, chain</code>: <code>chain</code> is never used, and can be removed.</p>\n<h2>N Choose R</h2>\n<p>As of Python 3.8, the "n choose r" function is <a href=\"https://docs.python.org/3/library/math.html?highlight=comb#math.comb\" rel=\"nofollow noreferrer\">built-in</a> and can simply be imported:</p>\n<p><code>from math import comb</code>.</p>\n<p>The function is never used, so may be deleted.</p>\n<h2>Constants</h2>\n<p><code>time_slots = 24*4*7</code></p>\n<p>That is ... the number of hours in a 4-week month? No? Perhaps you should name some of those numbers, and use <code>UPPER_CASE</code> to indicate the result is a constant:</p>\n<pre class=\"lang-py prettyprint-override\"><code>SLOTS_PER_HR = 4\nHRS_PER_DAY = 24\nDAYS_PER_WEEK = 7\nTIME_SLOTS = SLOTS_PER_HR * HRS_PER_DAY * DAYS_PER_WEEK\n</code></pre>\n<h2>Code Organization</h2>\n<p>You've got imports, function definition, constants, code, another function definition, more code. Organize your code, please!</p>\n<ul>\n<li>imports</li>\n<li>constants</li>\n<li>function definitions</li>\n<li>code (ideally in a main-guard)</li>\n</ul>\n<p>Use blank lines to separate sections. Your first function immediately follows the imports without a blank line, which makes it harder to understand. 3 blank lines before the second function definition seems excessive, and no blank line after the last function makes it harder to see that the code which follows is not part of the function.</p>\n<p>Order <code>import ...</code> statements before <code>from ... import ...</code> statements.</p>\n<h2>Use Function Parameters</h2>\n<p><code>def make_teams(availabilities_dict, team_size):</code></p>\n<p>If I call <code>make_teams(availabilities, 10)</code>, I'd expect the function to make teams of 10, but it will actually make teams of size <code>TEAM_SIZE</code> (a global constant) instead! The <code>team_size</code> parameter is never used.</p>\n<p>Similarly, if I pass in a dictionary of 200 people, it will stop making teams when <code>NUM_PEOPLE</code> is reached. <code>len(availabilities_dict)</code> would be more intuitive.</p>\n<h2>Use a for loop instead of a manual loop counter</h2>\n<pre class=\"lang-py prettyprint-override\"><code> i = 0\n while len(assigned) < NUM_PEOPLE:\n considering = list(sums[i][0])\n ...\n i += 1\n</code></pre>\n<p>This loop can be changed to something like the following, which has eliminated the <code>i</code> loop variable. We've even moved the test for number of people assigned from every loop to only being done when the list of assigned people changes.</p>\n<pre class=\"lang-py prettyprint-override\"><code> for considering, team_sum in sums:\n ...\n if none_assigned:\n ...\n if not len(assigned) < NUM_PEOPLE:\n break\n</code></pre>\n<h2>Large functions</h2>\n<p><code>make_teams()</code> is a large function, 22 lines long, not counting blank lines or docstrings. No comment is in sight. Functions should be decomposed into smaller functions, which do simpler tasks, instead of a single monolithic function doing everything. Smaller functions are easier to understand.</p>\n<h2>Type Hints</h2>\n<p>Adding type-hints can go a long way towards improving readability of the code.</p>\n<h1>Optimizations</h1>\n<h2>NumPy -vs- Bitarray</h2>\n<p><code>numpy</code> is a powerful, flexible, and fast library for manipulating vast quantities of data in multidimensional arrays.</p>\n<p>Most of the power of <code>numpy</code> is completely unused by this code. The part that is being done by <code>numpy</code> could be replaced with <code>bitarray</code>, a library that is optimized exclusively for dealing with arrays of bits in a fast, efficient, memory conscious way.</p>\n<p>I haven't run timed trials of <code>numpy</code> using 1-dimensional bit arrays against the <code>bitarray</code> library, so I'm offering this as something to look into, rather than explicitly stating one is better than the other.</p>\n<h2>Lists -vs- Sets</h2>\n<p>You are maintaining a list of all assigned players, and testing that no player in a <code>considering</code> list is in the <code>assigned</code> list. The problem is <code>person in assigned</code> is an <span class=\"math-container\">\\$O(N)\\$</span> operation. If you maintained as set of assigned players, then <code>player in assigned</code> becomes an <span class=\"math-container\">\\$O(1)\\$</span> operation, significantly faster.</p>\n<p>Moreover, with sets you can test all the players in <code>considering</code> at once. If <code>assigned.isdisjoint(considering)</code> is true, there is no overlap; no player in <code>considering</code> has been assigned.</p>\n<h1>Suggested code</h1>\n<pre class=\"lang-py prettyprint-override\"><code>from bitarray import bitarray\nfrom bitarray.util import urandom\nfrom itertools import combinations\n\n# Types for type-hints (using Python3.9 style)\nSchedules = dict[int, bitarray]\nTeam = tuple[int]\nTeams = list[tuple[Team, int]]\n\n# Constants\nSLOTS_PER_HR = 4\nHRS_PER_DAY = 24\nDAYS_PER_WEEK = 7\nTIME_SLOTS = SLOTS_PER_HR * HRS_PER_DAY * DAYS_PER_WEEK\n\n\ndef make_teams(availability: Schedules, team_size: int) -> Teams:\n """\n A good docstring here\n """\n\n # Inner function for determining the common availability of a team\n def common_availability(team: tuple[int]) -> int:\n avail = bitarray(TIME_SLOTS)\n avail.setall(True)\n for player in team:\n avail &= availability[player]\n return avail.count()\n\n # team combinations are created and sorted in one step.\n team_combinations = sorted(combinations(availability, team_size),\n key=common_availability, reverse=True)\n\n # Collect teams, while maintaining a set of assigned players\n assigned = set()\n teams = []\n\n for team in team_combinations:\n if assigned.isdisjoint(team):\n # I didn't store availability scores, so recalculate here if really needed.\n teams.append((team, common_availability(team)))\n assigned |= set(team)\n \n return teams \n\n# Create random schedules\ndef test_data(num_people: int, time_slots: int) -> Schedules:\n return {i: urandom(time_slots) for i in range(num_people)}\n\n\nif __name__ == '__main__':\n from time import perf_timer\n\n for num_people in range(TEAM_SIZE, 101, TEAM_SIZE):\n availability = test_data(num_people, TIME_SLOTS)\n start = perf_counter()\n teams = make_teams(availability, TEAM_SIZE)\n secs = perf_counter() - start\n mins = int(secs / 60)\n secs -= mins * 60\n \n print(f"{num_people:3d} {mins:02d}:{secs:06.3f}")\n</code></pre>\n<p>My 5 year old laptop finds teams of 5 from 100 people in 02:08.887 ... well under the 10 minutes you're experiencing on your "state of the art computer". That isn't a really good, qualitative performance comparison, so you'll have to profile it to see how much of an improvement you see.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T00:48:46.670",
"Id": "259264",
"ParentId": "259099",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259264",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T22:40:18.603",
"Id": "259099",
"Score": "4",
"Tags": [
"python",
"performance",
"algorithm",
"search"
],
"Title": "Find optimum teams given calendar availabilities"
}
|
259099
|
<p>I recently developed code that can run as a function parameter but I'm not quite sure how vulnerable it is to hacks and/or cheats.</p>
<p>Also, is there anything I could improve?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const h1 = document.getElementById('hi')
world = "world";
function testCode(codeEntered) {
var code = codeEntered;
var run = code *= 1;
return(run);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="testCode(h1.textContent = world)">
Test
</button>
<h1 id="hi">
Hello
</h1></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>Some thoughts:</p>\n<ul>\n<li><p>Writing <code>testCode(h1.textContent = world)</code> is a bit unconventional, and might not do what you expect: this is the same as writing the two lines</p>\n<pre class=\"lang-js prettyprint-override\"><code>h1.textContent = world;\ntestCode(world);\n</code></pre>\n<p>because the assignment (the first line) <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment\" rel=\"nofollow noreferrer\">evaluates to the value of the right hand side</a>.</p>\n</li>\n<li><p>Instead of writing <code>var code = codeEntered;</code>, you can save yourself a line and just use the variable <code>codeEntered</code> instead of making a new variable.</p>\n</li>\n<li><p>The line <code>var run = code *= 1;</code> also is a bit unexpected. This is equivalent to writing</p>\n<pre class=\"lang-js prettyprint-override\"><code>code = code * 1;\nvar run = code;\n</code></pre>\n<p>But <code>code</code> is a string, and multiplying it by <code>1</code> evaluates to <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN\" rel=\"nofollow noreferrer\"><code>NaN</code></a> (try it!), so after that line, <code>code == run == NaN</code>.</p>\n</li>\n<li><p>Code style: <code>return(run);</code> would typically be written <code>return run;</code> instead (it's not a function).</p>\n</li>\n<li><p>In summary, <code>testCode</code> actually always returns <code>NaN</code>, but the value then gets thrown away because it isn't used anywhere. In effect, your code actually just runs <code>h1.textContent = world</code> when you click the button, then runs <code>testCode</code> whose value isn't used (but is always NaN anyway).</p>\n</li>\n</ul>\n<p>I hope this gives you some useful feedback.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T18:54:02.797",
"Id": "511074",
"Score": "0",
"body": "I never really realized that, a while back I looked up a way to convert Numbers as strings into floating-point numbers and I thought that it would work the other way around."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T10:51:11.407",
"Id": "259116",
"ParentId": "259102",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T23:19:14.830",
"Id": "259102",
"Score": "0",
"Tags": [
"javascript",
"html",
"security"
],
"Title": "Please check out my code incrementer"
}
|
259102
|
<p>A few weeks ago, I wrote a Reverse Polish Notation program for my Ti-84+CE calculator. It was a successor to a program I wrote in TI-BASIC a while back, but since that one had too much input lag to be usable, I decided to write this one in C and compile it to native z80 assembly.</p>
<p>I wrote this program the night before a competition I intended to use it in (in fact, I put the finishing touches on it literally moments before starting the exam itself!), so keep in mind that I was on a time crunch so I wasn't going for the cleanest possible codebase. Still, as I'm not very experienced with C, I'd like to know what sort of improvements I could make to the code.</p>
<p>Here is a demo GIF of the program being used to find the answer of a sample number cruncher question:</p>
<p><img src="https://raw.githubusercontent.com/arjvik/RPN-Ti84/abb655794cf2849158ea5a4619a838a0b0a163ed/.github/demo.gif" alt="" /></p>
<p>I published a git repository with the program at <a href="https://github.com/arjvik/RPN-Ti84" rel="nofollow noreferrer">https://github.com/arjvik/RPN-Ti84</a></p>
<p>This is the code:</p>
<pre class="lang-c prettyprint-override"><code>#include <tice.h>
real_t stack[99];
char buffer[50];
uint8_t idx;
bool decimal;
bool negative;
bool constantsmode = false;
bool scimode = true;
bool radians = true;
real_t decimalfactor;
real_t r_0, r_1, r_2, r_3, r_4, r_5, r_6, r_7, r_8, r_9, r_10, r_ln10, r_pi, r_e;
void init_real_constants() {
r_0 = os_Int24ToReal(0);
r_1 = os_Int24ToReal(1);
r_2 = os_Int24ToReal(2);
r_3 = os_Int24ToReal(3);
r_4 = os_Int24ToReal(4);
r_5 = os_Int24ToReal(5);
r_6 = os_Int24ToReal(6);
r_7 = os_Int24ToReal(7);
r_8 = os_Int24ToReal(8);
r_9 = os_Int24ToReal(9);
r_10 = os_Int24ToReal(10);
r_ln10 = os_FloatToReal(2.30258509299);
r_pi = os_FloatToReal(3.14159265359);
r_e = os_FloatToReal(2.71828182846);
}
void draw_line_clear(bool clear) {
os_RealToStr(buffer, &stack[idx], 0, 1, -1);
if (clear) {
os_SetCursorPos(9, 0);
os_PutStrFull(" ");
}
os_SetCursorPos(9, 0);
os_PutStrFull(buffer);
}
#define OVERDRAW_IS_REDRAW 0
#if OVERDRAW_IS_REDRAW
void draw_line() {
draw_line_clear(true);
}
#else
void draw_line() {
draw_line_clear(false);
}
#endif
void drawdecimal_line() {
os_SetCursorPos(9, 0);
os_PutStrFull(buffer);
os_PutStrFull(".");
}
void draw_stack_clear(uint8_t row, bool clear) {
if (row >= 9) {
os_SetCursorPos(8, 0);
os_PutStrFull("... ");
real_t len = os_Int24ToReal((int24_t) idx);
os_RealToStr(buffer, &len, 0, 1, -1);
os_SetCursorPos(8, 4);
os_PutStrFull(buffer);
} else {
if (scimode) {
os_RealToStr(buffer, &stack[row], 0, 2, 2);
} else {
os_RealToStr(buffer, &stack[row], 0, 1, -1);
}
if (clear) {
os_SetCursorPos(row, 0);
os_PutStrFull(" ");
}
os_SetCursorPos(row, 0);
os_PutStrFull(buffer);
}
}
void draw_stack(uint8_t row) {
draw_stack_clear(row, false);
}
void draw_full_stack() {
for (uint8_t row = 0; row < idx && row <= 9; row++)
draw_stack_clear(row, true);
}
void delete_stack(uint8_t row) {
if (row < 9) {
os_SetCursorPos(row, 0);
os_PutStrFull(" ");
}
}
void new_entry() {
decimal = false;
negative = false;
stack[idx] = r_0;
draw_line_clear(true);
}
void new_problem() {
idx = 0;
os_ClrHome();
buffer[0] = 0;
constantsmode = false;
new_entry();
}
#define BINARY_OP(os_func) \
do { \
if (os_RealCompare(&stack[idx], &r_0) != 0) { \
if (idx >= 1) { \
stack[idx-1] = os_func(&stack[idx-1], &stack[idx]); \
draw_stack_clear(idx-1, true); \
new_entry(); \
} \
} else { \
if (idx >= 2) { \
stack[idx-2] = os_func(&stack[idx-2], &stack[idx-1]); \
draw_stack_clear(idx-2, true); \
delete_stack(idx-1); \
idx--; \
new_entry(); \
} \
} \
} while (false);
#define UNARY_OP(os_func) \
do { \
if (os_RealCompare(&stack[idx], &r_0) != 0) { \
stack[idx] = os_func(&stack[idx]); \
draw_line_clear(true); \
} else { \
if (idx >= 1) { \
stack[idx-1] = os_func(&stack[idx-1]); \
draw_stack_clear(idx-1, true); \
new_entry(); \
} \
} \
} while (false);
#define REAL_TRIG(name, os_func) \
real_t name(real_t *a) { \
real_t t; \
if (radians) \
t = *a; \
else \
t = os_RealDegToRad(a); \
return os_func(&t); \
}
REAL_TRIG(degRadSin, os_RealSinRad)
REAL_TRIG(degRadCos, os_RealCosRad)
REAL_TRIG(degRadTan, os_RealTanRad)
#define REAL_INVTRIG(name, os_func) \
real_t name(real_t *a) { \
real_t t = os_func(a); \
if (!radians) \
t = os_RealRadToDeg(&t); \
return t; \
}
REAL_INVTRIG(radDegAsin, os_RealAsinRad)
REAL_INVTRIG(radDegAcos, os_RealAcosRad)
REAL_INVTRIG(radDegAtan, os_RealAtanRad)
real_t realLogBase10(real_t *a) {
real_t t = os_RealLog(a);
return os_RealDiv(&t, &r_ln10);
}
real_t realSquare(real_t *a) {
return os_RealMul(a, a);
}
void main() {
uint8_t key;
init_real_constants();
new_problem();
while ((key = os_GetCSC()) != sk_Graph) {
if (constantsmode) {
if (key == sk_Power) {
stack[idx] = r_pi;
constantsmode = false;
draw_line_clear(true);
} else if (key == sk_Div) {
stack[idx] = r_e;
constantsmode = false;
draw_line_clear(true);
} else if (key == sk_2nd) {
constantsmode = false;
} else if (key == sk_Del) {
new_problem();
}
} else {
if (key == sk_0 || key == sk_1 || key == sk_2 || key == sk_3 || key == sk_4 ||
key == sk_5 || key == sk_6 || key == sk_7 || key == sk_8 || key == sk_9 ) {
if (!decimal) {
stack[idx] = os_RealMul(&stack[idx], &r_10);
real_t toAdd = r_0;
if (key == sk_1) toAdd = r_1;
if (key == sk_2) toAdd = r_2;
if (key == sk_3) toAdd = r_3;
if (key == sk_4) toAdd = r_4;
if (key == sk_5) toAdd = r_5;
if (key == sk_6) toAdd = r_6;
if (key == sk_7) toAdd = r_7;
if (key == sk_8) toAdd = r_8;
if (key == sk_9) toAdd = r_9;
if (!negative)
stack[idx] = os_RealAdd(&stack[idx], &toAdd);
else
stack[idx] = os_RealSub(&stack[idx], &toAdd);
draw_line();
} else {
real_t toAdd = r_0;
if (key == sk_1) toAdd = r_1;
if (key == sk_2) toAdd = r_2;
if (key == sk_3) toAdd = r_3;
if (key == sk_4) toAdd = r_4;
if (key == sk_5) toAdd = r_5;
if (key == sk_6) toAdd = r_6;
if (key == sk_7) toAdd = r_7;
if (key == sk_8) toAdd = r_8;
if (key == sk_9) toAdd = r_9;
toAdd = os_RealMul(&toAdd, &decimalfactor);
if (!negative)
stack[idx] = os_RealAdd(&stack[idx], &toAdd);
else
stack[idx] = os_RealSub(&stack[idx], &toAdd);
decimalfactor = os_RealDiv(&decimalfactor, &r_10);
draw_line_clear(true);
}
} else if (key == sk_Chs) {
stack[idx] = os_RealNeg(&stack[idx]);
negative = !negative;
draw_line_clear(true);
} else if (key == sk_DecPnt) {
if (!decimal) {
decimal = true;
decimalfactor = os_RealDiv(&r_1, &r_10);
drawdecimal_line();
}
} else if (key == sk_Clear) {
new_entry();
} else if (key == sk_Left) {
if (negative) os_RealNeg(&stack[idx]);
if (!decimal) {
stack[idx] = os_RealDiv(&stack[idx], &r_10);
} else decimal = false;
stack[idx] = os_RealFloor(&stack[idx]);
if (negative) os_RealNeg(&stack[idx]);
draw_line_clear(true);
} else if (key == sk_Enter) {
if (idx == 98) {
new_problem();
} else {
draw_stack(idx++);
new_entry();
}
} else if (key == sk_Mode) {
scimode = !scimode;
draw_full_stack();
} else if (key == sk_Stat) {
radians = !radians;
os_SetCursorPos(9, 0);
os_PutStrFull(radians ? "r" : "d");
}else if (key == sk_Del) {
new_problem();
} else if (key == sk_Add) {
BINARY_OP(os_RealAdd);
} else if (key == sk_Sub) {
BINARY_OP(os_RealSub);
} else if (key == sk_Mul) {
BINARY_OP(os_RealMul);
} else if (key == sk_Div) {
BINARY_OP(os_RealDiv);
} else if (key == sk_Power) {
BINARY_OP(os_RealPow);
} else if (key == sk_Log) {
UNARY_OP(realLogBase10);
} else if (key == sk_Ln) {
UNARY_OP(os_RealLog);
} else if (key == sk_Sin) {
UNARY_OP(degRadSin);
} else if (key == sk_Cos) {
UNARY_OP(degRadCos);
} else if (key == sk_Tan) {
UNARY_OP(degRadTan);
} else if (key == sk_Apps) {
UNARY_OP(radDegAsin);
} else if (key == sk_Prgm) {
UNARY_OP(radDegAcos);
} else if (key == sk_Vars) {
UNARY_OP(radDegAtan);
} else if (key == sk_Square) {
UNARY_OP(realSquare);
} else if (key == sk_Recip) {
UNARY_OP(os_RealInv);
} else if (key == sk_2nd) {
constantsmode = true;
} else if (key == sk_Yequ) {
os_ClrHome();
os_SetCursorPos(0, 0);
os_PutStrFull("Arjun's RPN Calculator");
os_SetCursorPos(1, 0);
os_PutStrFull("v2.0 (ASM)");
os_SetCursorPos(3, 0);
os_PutStrFull("git.io/ti84rpn");
while (os_GetCSC() == 0);
os_ClrHome();
draw_full_stack();
draw_line_clear(true);
}
}
}
}
</code></pre>
<p>The <code>tice.h</code> I used is from <a href="https://github.com/CE-Programming/toolchain/blob/master/src/ce/tice.h" rel="nofollow noreferrer">CE-Programming/toolchain</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T02:48:53.747",
"Id": "510933",
"Score": "1",
"body": "I'm more curious about how you made that gif! Is there now a way to run and/or screencap TI-83 programs too?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T19:43:19.950",
"Id": "510973",
"Score": "0",
"body": "@Quuxplusone I actually ran the program in an emulator to record the GIF. The specific emulator I used was [CEmu](https://github.com/CE-Programming/CEmu), but there are tons of other emulators available."
}
] |
[
{
"body": "<p>Instead of</p>\n<pre><code>#define OVERDRAW_IS_REDRAW 0\n#if OVERDRAW_IS_REDRAW\nvoid draw_line() {\n draw_line_clear(true);\n}\n#else\nvoid draw_line() {\n draw_line_clear(false);\n}\n#endif\n</code></pre>\n<p>why not</p>\n<pre><code>#define OVERDRAW_IS_REDRAW false\n\nvoid draw_line() {\n draw_line_clear(OVERDRAW_IS_REDRAW);\n}\n</code></pre>\n<p>?</p>\n<p>Otherwise: I'm not clear on the capabilities of your z80 compiler, but</p>\n<blockquote>\n<p>compile it to native z80 assembly</p>\n</blockquote>\n<p>is probably not what's going on. You're probably compiling to native z80 <em>machine code</em> and care more about this machine code than the assembly. Depending on your compiler it could emit an assembly listing as an intermediary step; in <code>gcc</code> this would be something like <code>gcc -Wa,-al</code>.</p>\n<p><code>BINARY_OP</code> and <code>UNARY_OP</code> are a little awkward. They're going to balloon the size of your <code>main</code> which is already too large. Instead consider converting them to plain-old functions that accept a function pointer for <code>os_func</code>. Among other things this will cut down on your final binary size. It's doubtful that the call overhead will be so burdensome as to be noticeable, but test it.</p>\n<p>I see your <code>while (false)</code> pattern reflected as well in the third-party toolchain header you're using. Why? If you just want a block, which is reasonable, keep the <code>{}</code> and drop the <code>do/while(false)</code>. Anonymous scoped blocks are easy and free in C, and should not need a loop hack. But again, if you convert your <code>_OP</code> functions to normal functions this will be a non-issue.</p>\n<p><code>main</code> is too big and complex. Break it down into subroutines.</p>\n<p>This whole block:</p>\n<pre><code> if (key == sk_1) toAdd = r_1;\n if (key == sk_2) toAdd = r_2;\n if (key == sk_3) toAdd = r_3;\n if (key == sk_4) toAdd = r_4;\n if (key == sk_5) toAdd = r_5;\n if (key == sk_6) toAdd = r_6;\n if (key == sk_7) toAdd = r_7;\n if (key == sk_8) toAdd = r_8;\n if (key == sk_9) toAdd = r_9;\n</code></pre>\n<p>can be replaced with a lookup table. Some maniac decided that the <code>sk_</code> values should be non-contiguous:</p>\n<pre><code>#define sk_0 0x21\n#define sk_1 0x22\n#define sk_4 0x23\n#define sk_7 0x24\n#define sk_2 0x1A\n#define sk_5 0x1B\n#define sk_8 0x1C\n#define sk_3 0x12\n#define sk_6 0x13\n#define sk_9 0x14\n</code></pre>\n<p>so if you do make such a lookup table, it will have an "interesting" value order; you could initialize it like</p>\n<pre><code>static real_t r_numerals[sk_9 - sk_0 + 1];\n\n// ...\n\nr_numerals[sk_0 - sk_0] = r_0;\nr_numerals[sk_1 - sk_0] = r_1;\nr_numerals[sk_2 - sk_0] = r_2;\nr_numerals[sk_3 - sk_0] = r_3;\nr_numerals[sk_4 - sk_0] = r_4;\nr_numerals[sk_5 - sk_0] = r_5;\nr_numerals[sk_6 - sk_0] = r_6;\nr_numerals[sk_7 - sk_0] = r_7;\nr_numerals[sk_8 - sk_0] = r_8;\nr_numerals[sk_9 - sk_0] = r_9;\n\n// ...\n\ntoAdd = r_numerals[key - sk_0];\n</code></pre>\n<p>or if you're more worried about performance and less worried about memory, just make an array that's 0x40 elements long and represents the entire key space. You could take this a step further and have a complete lookup table populated with pointers to your own functions, which would really cut down on the key-checking noise in <code>main</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T21:36:49.670",
"Id": "510988",
"Score": "0",
"body": "Thank you for the feedback! I agree with all the improvements you have suggested so far.\n\nWith respect to the assembly vs machine code point, I believe you are right. The Ti84+ toolchain seems to mix up the two terms, potentially because the Ti84+ operating system calls compiled programs \"ASM programs\" (as opposed to interpreted \"BASIC programs\")."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T21:36:59.773",
"Id": "510989",
"Score": "1",
"body": "The tips on using function pointers seem especially handy. I agree that replacing the macro-generated blocks with a function taking a function pointer would be a big size improvement at a very little performance hit. Replacing the long if-else chains with function pointer lookup tables also seems like a great idea."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T21:42:31.237",
"Id": "510993",
"Score": "0",
"body": "The `do { } while (false);` macro pattern was picked up from a bunch of places recommending its use. Among them are the Linux kernel formatting guide and [this SO question](https://stackoverflow.com/questions/154136/why-use-apparently-meaningless-do-while-and-if-else-statements-in-macros). Why do these places recommend this pattern when a regular block is allowed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T21:47:13.367",
"Id": "510994",
"Score": "0",
"body": "I don't think they recommend such a block, but attempt to justify why a developer may have preferred it: as an awkward replacement of `break` instead of `goto` (which you don't need), or out of misplaced compiler compatibility concerns."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T16:51:17.263",
"Id": "259123",
"ParentId": "259105",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "259123",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T00:45:59.097",
"Id": "259105",
"Score": "4",
"Tags": [
"c",
"embedded"
],
"Title": "Ti-84+CE Reverse Polish Notation Progam"
}
|
259105
|
<p>I have looked at many topics related to this topic, but I could not find or understand for datagridview table. Finally I made the undo / redo implementation myself using datatable lists. This solution is valid for small tables, I think. I don't know if it will work efficient on tables with lots of data. I will share this solution here. Maybe I will contribute to this website where I learned lots of things. Also I am waiting for comments. Is this solution stupid? or does it work? I need your comments for improvement or give up. Thanx.</p>
<p>Firstly we will add a DataGridView and two buttons named "Undo" and "Redo" to our form</p>
<p>These are codes below;</p>
<pre><code>using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
DataTable dt = null;
List<DataTable> dtList = new List<DataTable>(); // This list for recording every movements. If we want to do undo/redo, we will get data from this list to dataGridview
public Form1()
{
InitializeComponent();
dataGridView1.Rows.Add(20);// Add row
dt = GetDataTableFromDGV(dataGridView1);// make datatable at the beginning
dtList.Clear();
dtList.Add(dt);// Beginning data is added to List
}
public DataTable GetDataTableFromDGV(DataGridView dgv)// This methot makes a DataTable from DataGridView control.
{
var dt = new DataTable();
foreach (DataGridViewColumn column in dgv.Columns)
{
dt.Columns.Add(column.Name);
}
object[] cellValues = new object[dgv.Columns.Count];
foreach (DataGridViewRow row in dgv.Rows)
{
for (int i = 0; i < row.Cells.Count; i++)
{
cellValues[i] = row.Cells[i].Value;
}
dt.Rows.Add(cellValues);
}
return dt;
}
int counterUndo = 2;// This counts clicked redo button
int dtCount = 0;// This keeps DataTable count
bool clickedUndo;// This checks Undo button clicked or not.
private void btn_Undo_Click(object sender, EventArgs e)
{
clickedUndo = true;
dtCount = dtList.Count;
if (dtCount - counterUndo > -1)
{
int undoIndex = dtCount - counterUndo;
datatablaToDataGrid(dataGridView1, dtList[undoIndex]);
counterUndo++;
}
}
private void btn_redo_Click(object sender, EventArgs e)
{
int redoIndex = dtCount - counterUndo + 2;
if (counterUndo > 1&&redoIndex< dtCount)
{
datatablaToDataGrid(dataGridView1, dtList[redoIndex]);
counterUndo--;
}
}
public void datatablaToDataGrid(DataGridView dgv, DataTable datatable)// This methot gets data from DataTable to DataGridView control.
{
for (int i = 0; i < datatable.Rows.Count; i++)
{
for (int j = 0; j < datatable.Columns.Count; j++)
{
dgv.Rows[i].Cells[j].Value = datatable.Rows[i][j].ToString();
}
}
}
private void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)// This event check if the cell value is change or stay same.
{
DataGridView dgv = (DataGridView)sender;
int r = e.RowIndex;
int c = e.ColumnIndex;
if (dgv.Rows[r].Cells[c].Value != null)
{
string dgvResult = dgv.Rows[r].Cells[c].Value.ToString();
string dtResult = dt.Rows[r][c].ToString();
if (dgvResult != dtResult)
{
if (clickedUndo)
{
doWhenClickedUndo(counterUndo, dtList);
}
dt = GetDataTableFromDGV(dataGridView1);
dtList.Add(dt);
counterUndo = 2;
}
}
}
private void doWhenClickedUndo(int _counterUndo, List<DataTable> _dtList)
{
if (_counterUndo != 2)
{
int f = counterUndo - 2;
int lastIndex = _dtList.Count - 1;
int i = lastIndex;
do
{
_dtList.RemoveAt(i);
i--;
} while (i > lastIndex - f);
}
clickedUndo = false;
}
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/y4Ofc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/y4Ofc.png" alt="enter image description here" /></a></p>
|
[] |
[
{
"body": "<h2>Review</h2>\n<p>Welcome to Code Review. There are few suggestions as below.</p>\n<h3>Layout and formatting</h3>\n<p>Not sure why many newlines between the curly brackets and the method definition, <code>if</code> statements and <code>for</code> statements. For improving readability, those unnecessary newlines can be removed.</p>\n<h3>Magic numbers and <code>List<DataTable></code></h3>\n<p>I have no idea about why the initial value of <code>counterUndo</code> is set to 2 (in <code>int counterUndo = 2</code>) and why the inequality check <code>if (_counterUndo != 2)</code> is needed in <code>doWhenClickedUndo</code> method. Is the times of undo operation limited in 2? How about the case of more steps the user wants to undo? To solve this issue, I tried to use <code>Stack<DataTable></code> instead of <code>List<DataTable></code> so that the <code>Push</code>, <code>Pop</code> and <code>First</code> methods is available (<a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack?view=net-5.0\" rel=\"nofollow noreferrer\"><code>Stack</code></a> is useful for maintaining the historical sequence like the states of <code>DataTable</code> here). The following code is as an example implementation with <code>Stack</code> class.</p>\n<pre><code>public partial class Form1 : Form\n{\n Stack<DataTable> dtStack = new Stack<DataTable>();\n int RecordIndex = 0;\n bool UndoRedo = false;\n\n public Form1()\n {\n InitializeComponent();\n\n // Construct Columns\n dataGridView1.ColumnCount = 1;\n dataGridView1.Columns[0].Name = "0";\n\n dataGridView1.Rows.Add(20);// Add row\n\n dtStack.Clear();\n\n dtStack.Push(GetDataTableFromDGV(dataGridView1));\n UpdateBtnStatus();\n }\n\n public DataTable GetDataTableFromDGV(DataGridView dgv)\n {\n var dt = new DataTable();\n\n foreach (DataGridViewColumn column in dgv.Columns)\n {\n dt.Columns.Add(column.Name);\n }\n\n object[] cellValues = new object[dgv.Columns.Count];\n\n foreach (DataGridViewRow row in dgv.Rows)\n {\n for (int i = 0; i < row.Cells.Count; i++)\n {\n cellValues[i] = row.Cells[i].Value;\n }\n dt.Rows.Add(cellValues);\n }\n return dt;\n }\n\n public void datatablaToDataGrid(DataGridView dgv, DataTable datatable)\n {\n for (int i = 0; i < datatable.Rows.Count; i++)\n {\n for (int j = 0; j < datatable.Columns.Count; j++)\n {\n dgv.Rows[i].Cells[j].Value = datatable.Rows[i][j].ToString();\n }\n }\n }\n\n private void UpdateBtnStatus()\n {\n if (RecordIndex == this.dtStack.Count - 1)\n this.btn_Undo.Enabled = false;\n else\n this.btn_Undo.Enabled = true;\n\n if (RecordIndex == 0)\n this.btn_redo.Enabled = false;\n else\n this.btn_redo.Enabled = true;\n }\n\n private void btn_Undo_Click(object sender, EventArgs e)\n {\n UndoRedo = true;\n datatablaToDataGrid(dataGridView1, dtStack.ToList()[++RecordIndex]);\n UpdateBtnStatus();\n UndoRedo = false;\n }\n\n private void btn_redo_Click(object sender, EventArgs e)\n {\n UndoRedo = true;\n datatablaToDataGrid(dataGridView1, dtStack.ToList()[--RecordIndex]);\n UpdateBtnStatus();\n UndoRedo = false;\n }\n\n private void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)\n {\n UpdateBtnStatus();\n\n if (UndoRedo)\n return;\n\n DataGridView dgv = (DataGridView)sender;\n int r = e.RowIndex;\n int c = e.ColumnIndex;\n if (dgv.Rows[r].Cells[c].Value != null)\n {\n string dgvResult = dgv.Rows[r].Cells[c].Value.ToString();\n string dtResult = dtStack.ElementAt(RecordIndex).Rows[r][c].ToString();\n if (dgvResult != dtResult)\n {\n while (RecordIndex > 0)\n {\n dtStack.Pop();\n RecordIndex--;\n }\n\n dtStack.Push(GetDataTableFromDGV(dataGridView1));\n }\n }\n UpdateBtnStatus();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T08:53:14.910",
"Id": "510943",
"Score": "1",
"body": "Hi there is no limit undo/redo if you tried. Why is \"counterUndo = 2\"?.This variable is a tool that use to call the correct index number from the Datatable list when the user presses undo or redo. It is my fault that I did not make enough explanations in the codes. Thanx to you and for your time. I ll use your codes. I want to ask is it right solution to use Datatable for undo/redo. Becuse after every undo/redo action we are get data from DataTable to Datagridview. Is there any disadvantages making this? If the table has lots of data this will this slow down the application?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T18:45:06.787",
"Id": "510969",
"Score": "0",
"body": "I tried your codes. It is working but there is a problem with redo click. It is working after two movements. First movement it do not undo.Could you edit your codes then i will marked as an answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T20:45:58.450",
"Id": "510983",
"Score": "0",
"body": "@Gokhan > It is working but there is a problem with redo click. It is working after two movements. \nCould you let me know the steps you test? The provided example code which I've tried worked well no matter which movements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T21:20:57.047",
"Id": "510986",
"Score": "0",
"body": "Thanx for attention. I added picture to link below for clear explanation. [link](https://ibb.co/xX168WZ).Please see link."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T21:42:01.290",
"Id": "510992",
"Score": "0",
"body": "@Gokhan Already updated. Please check and let me know if there is any further problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T05:01:53.157",
"Id": "511002",
"Score": "0",
"body": "I tried but there is still a problem. Explanation is at link.[link](https://ibb.co/1qFTgT3)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T05:44:31.683",
"Id": "511003",
"Score": "0",
"body": "@Gokhan Thank you for point out the issue. Updated again and both [this](https://ibb.co/xX168WZ) and [this](https://ibb.co/1qFTgT3) are tested."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T16:12:49.173",
"Id": "511061",
"Score": "2",
"body": "I tried now. It is working well.Thank you very much @JimmyHu. I am new in programming i learned now stack class is used in undo redo applications."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T07:59:30.563",
"Id": "259114",
"ParentId": "259109",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "259114",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T05:17:14.390",
"Id": "259109",
"Score": "3",
"Tags": [
"c#",
"winforms",
".net-datatable"
],
"Title": "Undo/Redo Functionality in DataGridView c#"
}
|
259109
|
<p>How can I avoid repeating code fragments between the mutations and types with graphene in a FastAPI app? I really want to avoid repeating any codes for obvious reasons.</p>
<p><strong>graphql\mutations.py</strong></p>
<pre><code>import graphene
from models.customers import CustomerLogin, CustomerLogin_PydanticIn
from graphql.types import CustomerLoginType
class CreateUserMutation(graphene.Mutation):
class Arguments:
id = graphene.Int()
shard_id = graphene.Decimal()
seq_num = graphene.Decimal()
event_timedate = graphene.DateTime()
user_id = graphene.UUID()
device_token = graphene.UUID()
user_ip = graphene.String()
user_agent = graphene.String()
client_id = graphene.String()
process = graphene.String()
auth_result = graphene.String()
auth_fail_cause = graphene.String()
plain_email = graphene.String()
user = graphene.Field(CustomerLoginType)
@staticmethod
async def mutate(parent, info, user: CustomerLogin_PydanticIn):
user = await CustomerLogin.create(**user.dict())
return CreateUserMutation(user=user)
</code></pre>
<p><strong>graphql\types.py</strong></p>
<pre><code>import graphene
# Fields should coincide with model.CustomerLogin
class CustomerLoginType(graphene.ObjectType):
id = graphene.Int()
shard_id = graphene.Decimal()
seq_num = graphene.Decimal()
event_timedate = graphene.DateTime()
user_id = graphene.UUID()
device_token = graphene.UUID()
user_ip = graphene.String()
user_agent = graphene.String()
client_id = graphene.String()
process = graphene.String()
auth_result = graphene.String()
auth_fail_cause = graphene.String()
plain_email = graphene.String()
</code></pre>
<p><strong>graphql\queries.py</strong></p>
<pre><code>import graphene
from models.customers import CustomerLogin
from graphql.types import CustomerLoginType
class Query(graphene.ObjectType):
all_customer_logins = graphene.List(CustomerLoginType)
single_customer_login = graphene.Field(CustomerLoginType, id=graphene.Int())
@staticmethod
async def resolve_all_customer_logins(parent, info):
users = await CustomerLogin.all()
return users
@staticmethod
async def resolve_single_customer_login(parent, info, id):
user = await CustomerLogin.get(id=id)
return user
</code></pre>
<p>Then the ORM model using TortoiseORM</p>
<p><strong>models\customers.py</strong></p>
<pre><code>from tortoise import fields
from tortoise.contrib.pydantic import pydantic_model_creator
from tortoise.models import Model
from models.events import ShardID, SequenceNum
class CustomerLogin(Model):
shard_id: fields.ForeignKeyNullableRelation[ShardID] = \
fields.ForeignKeyField(model_name='models.ShardID',
related_name='customerlogin_shardid',
to_field='shard_id',
on_delete=fields.RESTRICT,
null=True)
seq_num: fields.ForeignKeyNullableRelation[SequenceNum] = \
fields.ForeignKeyField(model_name='models.SequenceNum',
related_name='customerlogin_seqnum',
to_field='seq_num',
on_delete=fields.RESTRICT,
null=True)
event_timedate = fields.DatetimeField(null=True)
user_id = fields.UUIDField(null=True)
device_token = fields.UUIDField(null=True)
user_ip = fields.CharField(256, null=True)
user_agent = fields.CharField(1024, null=True)
client_id = fields.CharField(256, null=True)
process = fields.CharField(256, null=True)
auth_result = fields.CharField(256, null=True)
auth_fail_cause = fields.CharField(256, null=True)
plain_email = fields.CharField(256, null=True)
CustomerLogin_Pydantic = pydantic_model_creator(CustomerLogin, name='CustomerLogin')
CustomerLogin_PydanticIn = pydantic_model_creator(CustomerLogin, name='CustomerLoginIn', exclude_readonly=True)
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T05:25:58.570",
"Id": "259110",
"Score": "1",
"Tags": [
"python",
"graphql"
],
"Title": "Avoiding Duplicated Code Fragments Graphene in FastAPI"
}
|
259110
|
<p>The following code is an async beginner exploration into asynchronous file downloads, to try and improve the download time of files from a specific website.</p>
<hr />
<p><strong>Tasks:</strong></p>
<p>The tasks are as follows:</p>
<ol>
<li><p>Visit <a href="https://digital.nhs.uk/data-and-information/publications/statistical/mental-health-services-monthly-statistics" rel="nofollow noreferrer">https://digital.nhs.uk/data-and-information/publications/statistical/mental-health-services-monthly-statistics</a></p>
</li>
<li><p>Extract the latest publication link. It is the top link under <em>Latest Statistics</em> and is the first match returned by css selector <code>.cta__button</code>.</p>
<p><a href="https://i.stack.imgur.com/76HOh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/76HOh.png" alt="enter image description here" /></a></p>
</li>
</ol>
<p>N.B. Each month this link updates so the next monthly publication e.g. 8 Apr 2021 the link will update to that associated with <em>Mental Health Services Monthly Statistics Performance January, Provisional February 2021</em>.</p>
<ol start="3">
<li><p>Visit the extracted link: <a href="https://digital.nhs.uk/data-and-information/publications/statistical/mental-health-services-monthly-statistics/performance-december-2020-provisional-january-2021" rel="nofollow noreferrer">https://digital.nhs.uk/data-and-information/publications/statistical/mental-health-services-monthly-statistics/performance-december-2020-provisional-january-2021</a> and, from there, extract the download links for all the files listed under <em>Resources</em>; currently 17 files.</p>
<p><a href="https://i.stack.imgur.com/vB3wm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vB3wm.png" alt="enter image description here" /></a></p>
</li>
<li><p>Finally, download all those files, using the retrieved urls, and save them to the location specified by <code>folder</code> variable.</p>
</li>
</ol>
<hr />
<p><strong>Set-up:</strong></p>
<p>Python 3.9.0 64-bit Windows 10</p>
<hr />
<p><strong>Request:</strong></p>
<p>I would appreciate any suggested improvements to this code e.g. should I have re-factored the co-routine <code>fetch_download_links</code> into two co-routines, each with a <code>ClientSession</code>, where one co-routine gets the initial link to where to get the resources, and the second co-routine to retrieve the actual resource links?</p>
<hr />
<p><strong>mhsmsAsynDownloads.py</strong></p>
<pre><code>import time
import os
from bs4 import BeautifulSoup as bs
import aiohttp
import aiofiles
import asyncio
import urllib
async def fetch_download_links(url:str) -> list:
async with aiohttp.ClientSession() as session:
r = await session.get(url, ssl = False)
html = await r.text()
soup = bs(html, 'lxml')
link = 'https://digital.nhs.uk' + soup.select_one('.cta__button')['href']
r = await session.get(link, ssl = False)
html = await r.text()
soup = bs(html, 'lxml')
files = [i['href'] for i in soup.select('.attachment a')]
return files
async def place_file(source: str) -> None:
async with aiohttp.ClientSession() as session:
file_name = source.split('/')[-1]
file_name = urllib.parse.unquote(file_name)
r = await session.get(source, ssl = False)
content = await r.read()
async with aiofiles.open(folder + file_name, 'wb') as f:
await f.write(content)
async def main():
tasks = []
urls = await fetch_download_links('https://digital.nhs.uk/data-and-information/publications/statistical/mental-health-services-monthly-statistics')
for url in urls:
tasks.append(place_file(url))
await asyncio.gather(*tasks)
folder = 'C:/Users/<User>/OneDrive/Desktop/testing/'
if __name__ == '__main__':
t1 = time.perf_counter()
print("process started...")
asyncio.get_event_loop().run_until_complete(main())
os.startfile(folder[:-1])
t2 = time.perf_counter()
print(f'Completed in {t2-t1} seconds.')
</code></pre>
<hr />
<p><strong>References/Notes:</strong></p>
<ol>
<li>I wrote this after watching an <a href="https://youtu.be/-hZPoYEajWk" rel="nofollow noreferrer">async tutorial on YouTube</a> by Andrei Dumitrescu.
The example above is my own</li>
<li><a href="https://docs.aiohttp.org/en/v0.20.0/client.html" rel="nofollow noreferrer">https://docs.aiohttp.org/en/v0.20.0/client.html</a></li>
<li><a href="https://docs.aiohttp.org/en/stable/client_advanced.html" rel="nofollow noreferrer">https://docs.aiohttp.org/en/stable/client_advanced.html</a></li>
<li>Data is publicly available</li>
</ol>
|
[] |
[
{
"body": "<p>Looks fine to me, you could potentially shave off some repetition, but it's not like it matters that much for a small script.</p>\n<p>That said, I'd reuse the session, inline a few variables, fix the naming (constants should be uppercase) and use some standard library tools like <code>os.path</code> to make the script more error-proof. The <code>list</code> return type could also be more concrete and mention that it's a list of strings for example.</p>\n<p>Also, and that's a bit more important, I'd rather not have a script slurp in the whole HTTP response like that! Who knows how big the files are, plus it's wasteful ... better to stream the response directly to disk! <a href=\"https://docs.aiohttp.org/en/stable/streams.html\" rel=\"nofollow noreferrer\">Thankfully the APIs do exist</a>, using <code>.content.iter_any</code> (or <code>_chunked</code> if you prefer to have a fixed chunk size) you can just iterate over each read data block and write them to the file like so:</p>\n<pre><code>import time\nimport os\nimport os.path\nfrom bs4 import BeautifulSoup as bs\nimport aiohttp\nimport aiofiles\nimport asyncio\nimport urllib\nimport typing\n\n\nSTATISTICS_URL = 'https://digital.nhs.uk/data-and-information/publications/statistical/mental-health-services-monthly-statistics'\nOUTPUT_FOLDER = 'C:/Users/<User>/OneDrive/Desktop/testing/'\n\n\nasync def fetch_download_links(session: aiohttp.ClientSession, url: str) -> typing.List[str]:\n r = await session.get(url, ssl=False)\n soup = bs(await r.text(), 'lxml')\n link = 'https://digital.nhs.uk' + soup.select_one('.cta__button')['href']\n\n r = await session.get(link, ssl=False)\n soup = bs(await r.text(), 'lxml')\n return [i['href'] for i in soup.select('.attachment a')]\n\n\nasync def place_file(session: aiohttp.ClientSession, source: str) -> None:\n r = await session.get(source, ssl=False)\n\n file_name = urllib.parse.unquote(source.split('/')[-1])\n async with aiofiles.open(os.path.join(OUTPUT_FOLDER, file_name), 'wb') as f:\n async for data in r.content.iter_any():\n await f.write(data)\n\n\nasync def main():\n async with aiohttp.ClientSession() as session:\n urls = await fetch_download_links(session, STATISTICS_URL)\n await asyncio.gather(*[place_file(session, url) for url in urls])\n\n\nif __name__ == '__main__':\n t1 = time.perf_counter()\n print('process started...')\n asyncio.get_event_loop().run_until_complete(main())\n os.startfile(OUTPUT_FOLDER[:-1])\n t2 = time.perf_counter()\n print(f'Completed in {t2-t1} seconds.')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T20:32:49.323",
"Id": "510979",
"Score": "1",
"body": "Thank you so much. I will need a little time to digest but very much appreciate what I have seen so far +"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T20:25:04.960",
"Id": "259131",
"ParentId": "259112",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259131",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T06:09:20.150",
"Id": "259112",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"web-scraping",
"asynchronous"
],
"Title": "Async download of files"
}
|
259112
|
<p>I made a test job to the position of Junior Java Developer. I did not receive any answer from the employer, so I would like to get a review here.</p>
<h2>Task description</h2>
<p>A simple text file with IPv4 addresses is given. One line is one address, something like this:</p>
<pre><code>145.67.23.4
8.34.5.23
89.54.3.124
89.54.3.124
3.45.71.5.
...
</code></pre>
<p>The file size is not limited and can occupy tens and hundreds of gigabytes.</p>
<p>It is necessary to calculate the number of unique IP addresses in this file, consuming as little memory and time as possible. There is a "naive" algorithm for solving this task (we read strings and put it in HashSet), it is desirable that your implementation is better than this simple, naive algorithm.</p>
<h2>Test case</h2>
<p><a href="https://ecwid-vgv-storage.s3.eu-central-1.amazonaws.com/ip_addresses.zip" rel="nofollow noreferrer">https://ecwid-vgv-storage.s3.eu-central-1.amazonaws.com/ip_addresses.zip</a></p>
<p>WARNING! This file is about 20GB, and is unpacking approximately 120GB. It consists of 8 billions lines.</p>
<h2>My approach</h2>
<p>I emerge from the fact that there are 2 ^ 32 valid unique ip addresses. We can use a bit array of 2 ^ 32 bits (unsigned integer) and put each bit of this array in line with one ip address. Such an array will take exactly 512 megabytes of memory and will be allocated once at the start of the program. Its size does not depend on size of the input data.</p>
<p>Unfortunately, Java does not have an unsigned int type and also there are no convenient bit operations in it, so I use <code>BitSet</code> for my purposes.</p>
<h2>Thank you!</h2>
<p>Please feel free to tell me all the flaws that you can find.</p>
<h2>Code</h2>
<p>Main class</p>
<pre><code>public class IpCounterApp {
private static String parseFileName(String[] args) {
String fileName = null;
if (args.length == 2 && "-file".equals(args[0])) {
fileName = args[1];
}
return fileName;
}
public static void main(String[] args) {
String fileName = parseFileName(args);
if (fileName == null) {
System.out.println("Wrong arguments. Use '-file file_name' to specify file for processing");
return;
}
UniqueIpCounter counter = new BitSetUniqueIpCounter();
long numberOfUniqueIp = counter.countUniqueIp(fileName);
if (numberOfUniqueIp != -1) {
System.out.println("Found " + numberOfUniqueIp + " unique IP's");
} else {
System.out.println("Some errors here. Check log for details.");
}
}
}
</code></pre>
<p>UniqueIpCounter interface</p>
<pre><code>public interface UniqueIpCounter {
/*
In total there are 2 ^ 32 valid IP addresses exists.
*/
long NUMBER_OF_IP_ADDRESSES = 256L * 256 * 256 * 256;
/*
Map string representing the IP address in format 0-255.0-255.0-255.0-255 to number
in the range of 0..2^32-1 inclusive.
It is guaranteed that the input string contains a valid IP address.
*/
static long toLongValue(String ipString) {
StringBuilder field = new StringBuilder(3);
int startIndex = 0;
long result = 0;
for (int i = 0; i < 3; i++) {
int spacerPosition = ipString.indexOf('.', startIndex);
field.append(ipString, startIndex, spacerPosition);
int fieldValue = Integer.parseInt(field.toString());
field.setLength(0);
result += fieldValue * Math.pow(256, 3 - i);
startIndex = spacerPosition + 1;
}
result += Integer.parseInt(ipString.substring(startIndex));
return result;
}
/*
Returns the number of unique IP addresses in the file whose name is pass by the argument.
Returns the number from 0 to 2 ^ 32 inclusive.
Returns -1 in case of any errors.
*/
long countUniqueIp(String fileName);
}
</code></pre>
<p>BitSetUniqueIpCounter implementation</p>
<pre><code>import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.BitSet;
import java.util.logging.Level;
import java.util.logging.Logger;
public class BitSetUniqueIpCounter implements UniqueIpCounter {
private final Logger logger = Logger.getLogger("BitSetUniqueIpCounter");
/*
To count unique IP's use a bit array, where each bit is set in accordance with one IP address.
In Java, there is no unsigned int and maximum BitSet size is integer.MAX_VALUE therefore we use two arrays.
*/
private final BitSet bitSetLow = new BitSet(Integer.MAX_VALUE); // 0 - 2_147_483_647
private final BitSet bitSetHi = new BitSet(Integer.MAX_VALUE); // 2_147_483_648 - 4_294_967_295
private long counter = 0;
private void registerLongValue(long longValue) {
int intValue = (int) longValue;
BitSet workingSet = bitSetLow;
if (longValue > Integer.MAX_VALUE) {
intValue = (int) (longValue - Integer.MAX_VALUE);
workingSet = bitSetHi;
}
if (!workingSet.get(intValue)) {
counter++;
workingSet.set(intValue);
}
}
@Override
public long countUniqueIp(String fileName) {
logger.log(Level.INFO, "Reading file: " + fileName);
try (BufferedReader in = new BufferedReader(new FileReader(fileName))) {
long linesProcessed = 0;
String line;
// If already counted 2 ^ 32 unique addresses, then to the end of the file there will be only duplicates
while ((line = in.readLine()) != null && counter <= NUMBER_OF_IP_ADDRESSES) {
registerLongValue(UniqueIpCounter.toLongValue(line));
linesProcessed++;
}
logger.log(Level.INFO, "Total lines processed: " + linesProcessed);
} catch (FileNotFoundException e) {
logger.log(Level.WARNING, "File '" + fileName + "' not found", e);
counter = -1;
} catch (IOException e) {
logger.log(Level.WARNING, "IOException occurs", e);
counter = -1;
}
return counter;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T15:43:21.767",
"Id": "510958",
"Score": "7",
"body": "I'm not a Java pedant, so I don't have a review for you. IMO, you've done a pretty good job, and if I were looking for a junior developer, I'd be happy with that code (assuming you wrote it and didn't scrape it from somewhere). I think you could probably increase the performance by doing your own parsing of the IP #s directly, and you might get good mileage by writing your own bitarray class as you started writing about. On the other hand, what you show here does a good job of implementing a fairly low-level approach using mid-level classes, which can be individually performance tuned later."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T13:06:48.480",
"Id": "511040",
"Score": "0",
"body": "What's the result for that file with 8 billion lines?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T14:45:42.430",
"Id": "511049",
"Score": "0",
"body": "@Manuel exactly 1 billion"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T06:24:44.913",
"Id": "511102",
"Score": "0",
"body": "Why not import a data science library like Tablesaw (which seems to be the Java equivalent of Python's Pandas library), load the file into a dataframe using said library, then just run the function from the library that returns the number of unique values in a column of a dataframe?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T12:07:42.733",
"Id": "511146",
"Score": "0",
"body": "This is precisely the way I'd have done it, and if you enjoy such tasks and solutions (also @KellyBundy 's suggestion with files), I can recommend \"Programming Pearls\" by John Bentley, which contains an almost identical task (phone numbers instead of IPs) and the various ways of solving the problem under different constraints."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T13:15:31.327",
"Id": "511151",
"Score": "0",
"body": "@Ijrk thank you, I will find this book. Unfortunately, almost all good materials exist only in English. It is rather difficult to navigate in the modern professional literature, when you speak Russian and do a self-learning without having a appropriate education."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T13:54:46.253",
"Id": "511157",
"Score": "2",
"body": "@nick012000 You're suggesting loading a 120GiB file into memory all at once?!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T22:21:49.813",
"Id": "511215",
"Score": "2",
"body": "@KonradRudolph Works on my machine. (Swaps a bit, but that's barely noticeable.) Let's ship it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T22:31:15.010",
"Id": "511216",
"Score": "0",
"body": "@wizzwizz4 Fair, I could load *two* such datasets without breaking a sweat/swap. But colleagues would probably rightly complain that I’m hogging the beefiest machine in the office *for no goddamn reason*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T22:33:49.170",
"Id": "511217",
"Score": "7",
"body": "I would've told the potential employer: \"If you want the results in 10 minutes, and allow me to use something other than Java, give me a server with a huge /tmp mount point, and type in `sort --unique ip.txt | wc -l`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T22:49:13.603",
"Id": "511218",
"Score": "3",
"body": "Is not IPv6 ready :P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T00:38:34.090",
"Id": "511224",
"Score": "1",
"body": "@MarkStewart Curious how that would work. If gnu sort still uses files for temporary storage (https://stackoverflow.com/a/930052/3150802) it could be quite slow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T00:54:12.480",
"Id": "511225",
"Score": "1",
"body": "Funny aside: The compression algorithm used to zip the file probably does something close to the job description as a subtask (create a dictionary of identical strings)..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T01:18:16.523",
"Id": "511227",
"Score": "0",
"body": "@KonradRudolf Pandas is capable of chunking its datasets, for when you're working with large datasets like this one. I expect that Tablesaw probably can too. Working on multi-gigabyte datasets is nothing new for data science."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T11:01:40.073",
"Id": "511253",
"Score": "1",
"body": "Not a Java guy, however your code looks decent already. Sure it can be tweaked, but if it works and is readable it is good enough. I would consider the use of multithreading to parallelize the task. Use the first bits of the address to assign it to a specific thread."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T16:23:53.213",
"Id": "511281",
"Score": "0",
"body": "It's worth noting that you probably can't have minimal time usage and minimal memory usage at the same time. You get a pretty good memory usage here, but you could get lower: you could sort the list removing duplicates using almost no memory and then count lines (again using almost no memory). That would be much, much slower, however."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T18:38:51.620",
"Id": "511291",
"Score": "1",
"body": "I know this is a JAVA question, but outside of JAVA there is a way easier answer. Linux has **ipset** you can create a set add ALL the IP. It will automatically block duplicates. Then you can use cidrmerge to consolidate the list of IP with subnet notation. Now technically this could all be rewritten in JAVA, but its a lot of work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T22:24:54.337",
"Id": "511323",
"Score": "0",
"body": "@cybernard Java Ain't a Valid Acronym."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T22:30:15.717",
"Id": "511324",
"Score": "0",
"body": "@nick012000 I'm fully aware, being a data scientist in genomics myself. But using (and understanding!) correct algorithms is still relevant, the more the larger the data gets. Case in point, relying on Pandasʼ chunking wonʼt work here. Even the official documentation on scaling Pandas says, in its introduction no less: “consider not using Pandas”."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T09:39:24.697",
"Id": "511362",
"Score": "0",
"body": "@gntskn Meh, even sorting might take more memory than necessary. For minimal memory, we could check whether 0.0.0.0 is in the file, then check whether 0.0.0.1 is in the file, and so on :-)"
}
] |
[
{
"body": "<p>The maximum <code>int</code> value is <span class=\"math-container\">\\$2^{31}-1\\$</span>, so your <code>BitSet</code>s have <span class=\"math-container\">\\$2^{31}-1\\$</span> entries each, so together they only cover <span class=\"math-container\">\\$2^{32}-2\\$</span> IPs, missing two. And you documented their ranges incorrectly. If the file contains <code>255.255.255.255</code>, you crash like this:</p>\n<pre><code>Exception in thread "main" java.lang.IndexOutOfBoundsException: bitIndex < 0: -2147483648\n at java.base/java.util.BitSet.get(BitSet.java:624)\n at BitSetUniqueIpCounter.registerLongValue(BitSetUniqueIpCounter.java:29)\n at BitSetUniqueIpCounter.countUniqueIp(BitSetUniqueIpCounter.java:43)\n at IpCounterApp.main(IpCounterApp.java:19)\n</code></pre>\n<p>I'd instead use a single <code>int[] seen = new int[1 << 27]</code> (<span class=\"math-container\">\\$2^{27}\\$</span> ints with <span class=\"math-container\">\\$2^{5}\\$</span> bits each, so <span class=\"math-container\">\\$2^{32}\\$</span> bits total) and treat it like this:</p>\n<pre><code> private void registerLongValue(long longValue) {\n int index = (int) (longValue >> 5);\n int bit = 1 << (longValue & 31);\n if ((seen[index] & bit) == 0) {\n counter++;\n seen[index] |= bit;\n }\n }\n</code></pre>\n<p>Your <code>toLongValue</code> is rather complicated, you could use <code>InetAddress</code> (might also be faster):</p>\n<pre><code> static long toLongValue(String ipString) throws UnknownHostException {\n long result = 0;\n for (byte b : InetAddress.getByName(ipString).getAddress())\n result = (result << 8) | (b & 255);\n return result;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T19:35:08.923",
"Id": "510972",
"Score": "1",
"body": "_BitSet(int nbits) Creates a bit set whose initial size is large enough to explicitly represent bits with indices in the range 0 through nbits-1._ https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/BitSet.html so my BitSet contains exactly 2^31 elements from index 0 to 2^31-1. Thanks for `InetAddress` hint"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T08:35:34.660",
"Id": "511007",
"Score": "6",
"body": "@chptr-one Wrong, your nbits is 2^31-1, not 2^31. And see the update to my answer that demonstrates the error."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T12:44:34.000",
"Id": "511033",
"Score": "1",
"body": "now i see it, thank you. I need to test my code more carefully."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T16:11:37.790",
"Id": "511059",
"Score": "3",
"body": "The `27` and `5` are quite clever. It took me a while to understand where they come from."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T19:48:38.063",
"Id": "511078",
"Score": "4",
"body": "@EricDuminil That wasn't supposed to be clever or a riddle :-). Added a note now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T18:20:51.503",
"Id": "511193",
"Score": "0",
"body": "I get the `27` and `5` parts, but is there a specific reason why those specifically over anything else such as `25` and `7` or `24` and `8`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T19:56:40.210",
"Id": "511201",
"Score": "1",
"body": "@Chris 2^32 total bits to store all IP numbers is needed. One `int` is 32 bits witch is 2^5. So, if we use int[] array, we need 2^32 / 2^5 = 2^27 of 4 bytes integers. Not 25 and 7 and so on until you have a computer in which one byte is 8 bits and one int is 4 bytes"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T14:41:28.303",
"Id": "511275",
"Score": "1",
"body": "If `255.255.255.255` shows up in the log file, then it would be appropriate for the program to complain loudly. Requests from broadcast addresses really should be rejected before a Web server even sees them!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T04:52:37.367",
"Id": "511334",
"Score": "0",
"body": "@TobySpeight You made an assumption on how the program will be used. There was nothing that hinted towards a need for such behaviour in the description. That was a bad advice especially considering this was a job interview question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T09:40:23.157",
"Id": "511364",
"Score": "0",
"body": "@ChrisHaas `int`s have 32 bits, not 128 or 256. We could do `26` and `6` with `long`s, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T13:34:53.797",
"Id": "511386",
"Score": "0",
"body": "Although the OP was concerned with memory, I'm just trying to understand the bitwise parts. Ignoring any memory or perf constraints, it would appear that `int index = (int) (longValue >> 6);int bit = 1 << (longValue & 0b0011_1111);` and `int index = (int) (longValue >> 4);int bit = 1 << (longValue & 0b0000_1111);` work equally well, too, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T14:21:31.170",
"Id": "511389",
"Score": "0",
"body": "@ChrisHaas The first one works if you use `long[]`. The second one works, too, but should use a 16-bit type like `short` or `char` in order to not waste bits. And in practice, the system's word size or caching aspects or so might affect the speeds, don't know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T15:28:01.660",
"Id": "511391",
"Score": "0",
"body": "Thanks @Manuel, I think I'm finally, finally, finally getting it now! Ignoring all optimizations (I'm playing around in a different language actually), and not even thinking necessarily about IP addresses, just a collection of numbers, abstractly we can shift-right `m` bits to get the index, and `m` is bound by the type's size. So for a 64-bit type, valid values of `m` would be `0` through `6` since `2^6=64`, and for 32-bit `m` stops at `5`. Lower values of `m` are less optimal, with `0` just storing everything, but still work. Does that sound right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T18:43:27.290",
"Id": "511412",
"Score": "0",
"body": "@ChrisHaas Sounds right except I don't know what you mean with \"storing everything\" :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T19:56:03.253",
"Id": "511420",
"Score": "0",
"body": "By storing everything I meant that if you used `0` for `m` you'd be bit-shifting zero places which results in just storing the IP address in the array. Thanks for letting me talk this through. I don't use bit-related stuff too much in my daily coding and was curious how/why it worked."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T11:30:12.527",
"Id": "511447",
"Score": "0",
"body": "@ChrisHaas \"storing the IP address in the array\" sounds like `seen[index] = longValue`. That's why that sounds odd, as that's not what happens (which is like `seen[index] = 1`)."
}
],
"meta_data": {
"CommentCount": "16",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T16:15:44.347",
"Id": "259121",
"ParentId": "259119",
"Score": "19"
}
},
{
"body": "<p>I'm being extra pedantic as this is a job interview question. Your code is better than 90% of what I have seen in job interviews. It shows that you have a fairly good understanding of how to solve the problem but there are improvements to be made in both minor details and the overall design of the solution. (This answer is a bit unstructured as I just make observations as I read through the code.)</p>\n<p>The file name parsing employs unnecessary variables and the boolean statements changes logical order mid sentence. The reversed order is used when guarding against null values but I find it difficult to read (increases cognitive complexity). You have also already gone through all possible error conditions by referencing <code>args</code> when checking its length, so the reverse comparison order does not have any functional purpose any more. A more readable way to guard against nulls would be <code>Objects.requireNonNull(args)</code>.</p>\n<pre><code>private static String parseFileName(String[] args) {\n Objects.requireNonNull(args, "args must not be null");\n if (args.length == 2 && args[0].equals("-file")) {\n return args[1];\n }\n return null;\n}\n</code></pre>\n<p>Variables that are not intended to be changed should always be <code>final</code>.</p>\n<p>Error messages should be written to <code>System.err</code>. Also, you're inconsistently using <code>System.out</code> in one place and <code>java.util.logging.Logger</code> in another place and logging fatal errors as warnings.</p>\n<p>You should avoid placing constants in interfaces as it <a href=\"https://stackoverflow.com/a/9446909/1047418\">leaks implementation details</a> into the interface's API.</p>\n<p>You're writing comments but not using the standard JavaDoc formatting. This reduces the usability of the comments as they will not be copied to automatically produced documentation or IDE tool tips.</p>\n<p>The static <code>toLongValue</code> method for converting the input tries to force the <code>UniqueIpCounter</code> implementation to work with <code>long</code> values. I would not want to see static methods in interfaces and the internal representation of the data should not be exposed here. Leave the conversion to the responsibility of the specific implementation.</p>\n<p>Forcing the <code>UniqueIpCounter</code> implementation to work with files, represented by file names, unnecessarily limits the reusability of the implementation and loads the implementation with multiple responsibilities, which violates the <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">single responsibility principle</a>. Reading the file should have been placed in a separate class. Parsing the read strings into IP addresses should have been another standalone class. The IP counter should thus only deal with the parsed input. Also, placing the responsibility of reading the file on the <code>UniqueIpCounter</code> you make unit testing the class very hard because now every test input has to be represented by a physical file on the disk.</p>\n<p>The <code>registerLongValue(long)</code> seems an odd method in an interface named <code>UniqueIpCounter</code>. The naming should be consistent. So either <code>registerIpAddress(...)</code> or <code>UniqueLongValueCounter</code>.</p>\n<p>Manuel suggested using <code>InetAddress</code> for parsing the input. When presented with a task of minimizing running time, you should read the source code of the libraries you use. It is obvious that <code>InetAddress</code> is a generic class that trades usability to performance. So you should implement a specialized string parsing algorithm and document why you wrote one instead of using a ready made library. You might even consider skipping the conversion to strings in between and create an <code>InputStream</code> reader that produces <code>long</code> values directly. In the end, the most important part is that you document why you did not choose to go with an easily readable and maintainable code. That said... your parsing algorithm is incredibly inefficient. To parse an IPv4 address to long you only need to read characters and append the digit value into an "accumulator":</p>\n<pre class=\"lang-none prettyprint-override\"><code>Set parsedIpAddress and currentByte to 0;\nRead one character\nIf digit, multiply currentByte by 10 and add digit.\nIf dot or new line, multiply parsedIpAddress by 256 and add current byte.\nIf new line, parsedIpAddress is complete.\nOtherwise repeat from line 2.\n</code></pre>\n<p>Using <code>BitSet</code> was, in theory, the correct choice but as Manuel pointed out, even having two sets does not cover the whole address range. Thus you have to reimplement it without the size limitation. That being said, the variable names need improvement. <code>lowAddresses</code> and <code>highAddresses</code> would tell the reader that they are used to store addresses already found. Use normal JavaDoc comments instead of end-of-line comments. EOL-comments are hard to read and maintain and you always have to make a compromise on the usefulness of the content to make it fit.</p>\n<p>"Return -1 on error" is an anti-pattern inherited from C, which should not be repeated. The correct way to handle errors is to throw an exception. I'm not sure it it was required in the task but there was no error handling in the input parsing.</p>\n<p><strong>Generic advice for job interview code</strong></p>\n<p>Job interview programming tasks are <em>always</em> too vague. It's either because they want to see how you handle incomplete specifications or because they don't know what they are doing. Regardless of the reason, this puts you into a position where you have to either ask for clarifications (which is usually a good thing) or make assumptions if you are not allowed to ask. When you make assumptions you have to document that you had multiple choices and list the reasons why you chose the one you implemented. If the reviewer does not agree with your approach they at least know that you made an intentional choice between several options instead of "doing the only one thing you knew."</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T08:49:15.967",
"Id": "511008",
"Score": "0",
"body": "Hmm, you call using `BitSet` correct and still recommend *two* names even though two `BitSet`s can't cover all IPs, making their program wrong?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T09:07:04.343",
"Id": "511010",
"Score": "0",
"body": "@Manuel The alternative is to reimplement BitSet without the limitation. Since it does not provide any performance or storage improvement I don't think it would make sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T09:34:45.867",
"Id": "511011",
"Score": "0",
"body": "Making the program correct and working would not be an improvement? I disagree."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T11:33:46.403",
"Id": "511018",
"Score": "0",
"body": "@Manuel Sorry, I overlooked that part while reviewing. You have indeed a valid point and I have improved my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T11:47:01.397",
"Id": "511020",
"Score": "0",
"body": "It could be done with more than two, let's say with four, but the extra logic above them seems about as much as with a single `int[]` (implemented in my answer now) and requires more initalization code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T12:53:53.867",
"Id": "511034",
"Score": "0",
"body": "Correct me if I am mistaken. Any field declared in `interface` will automatically be `static`. Or not? I agree about the `final`. And thank you very much, you gave me a lot of useful information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T09:25:35.173",
"Id": "511126",
"Score": "0",
"body": "\"Variables that are not intended to be changed should always be final.\" Is there any large project out there that actually does that? That seems incredibly bothersome, adding very little value and I can't imagine anybody actually doing that consistently (except if forced via some static analyzer and gated checkins). The JDK itself certainly doesn't."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T14:08:57.103",
"Id": "511160",
"Score": "0",
"body": "@Voo It's a widespread convention. All my code does it (and extends it to method parameters). The JDK implementation doesn't simply because it's an old code base of very variable quality."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T14:39:42.847",
"Id": "511166",
"Score": "0",
"body": "@Konrad Imho if one needs final on variables to see if they're changed or not in a single method, that method is already waay too big. So I'd be curious to see some non-trivial (say 20k LoC or more) code base that does that consistently. Just feels like a lot of boilerplate which would obscure the more important parts, but maybe my gut feeling is wrong there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T14:45:24.087",
"Id": "511168",
"Score": "0",
"body": "@Voo Frankly, yes, it’s a lot of boilerplate. Mutable-by-default is a terrible design (just one of the reasons why people use different JVM languages). But it still catches errors (even in small methods — most of my methods are fewer than 10 lines, virtually all are smaller than 20) and makes code more self-documented."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T05:54:23.393",
"Id": "511230",
"Score": "0",
"body": "@chptr-one Yes, you're correct about fields in interfaces being static and final by default. It is a feature I never use (it's considered bad design https://stackoverflow.com/a/9446909/1047418)."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T06:56:48.783",
"Id": "259143",
"ParentId": "259119",
"Score": "18"
}
},
{
"body": "<p>I'm agree with TorbenPutkonen's considerations about your code and with Manuel's observation about edge ipaddresses cases like <code>255.255.255.255</code> that can break your code, I focused about your method <code>toLongValue</code> translating your ipv4 address to an unique long:</p>\n<pre><code>static long toLongValue(String ipString) {\n StringBuilder field = new StringBuilder(3);\n int startIndex = 0;\n long result = 0;\n\n for (int i = 0; i < 3; i++) {\n int spacerPosition = ipString.indexOf('.', startIndex);\n field.append(ipString, startIndex, spacerPosition);\n int fieldValue = Integer.parseInt(field.toString());\n field.setLength(0);\n result += fieldValue * Math.pow(256, 3 - i);\n startIndex = spacerPosition + 1;\n }\n result += Integer.parseInt(ipString.substring(startIndex));\n\n return result;\n}\n</code></pre>\n<p>Your method can be rewritten dividing your <code>String</code> ipv4 address with <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)\" rel=\"noreferrer\"><code>String.split</code></a> and left shifting the octets with the logical <code>|</code> operator like below:</p>\n<pre><code>public static long toLongValue(String ipString) {\n String[] octets = ipString.split("\\\\.");\n return Long.parseLong(octets[0]) << 24 |\n Long.parseLong(octets[1]) << 16 |\n Long.parseLong(octets[2]) << 8 |\n Long.parseLong(octets[3]);\n}\n</code></pre>\n<p>The absence of a primitive type <code>unsigned int</code> in java forces to use the primitive <code>long</code> type, so your <code>BitSet</code> will break when you pass your <code>long</code> converted to a negative <code>int</code>. The idea in itself for me is a correct choice but it has to be refined to include all the addresses. My first idea for performance was about the construction of a <a href=\"https://en.wikipedia.org/wiki/Trie\" rel=\"noreferrer\">trie</a>, it seems that as usual Knuth solved the problem creating the <a href=\"https://en.wikipedia.org/wiki/Radix_tree\" rel=\"noreferrer\">Patricia tree</a>, you can check wikipedia notes for more details.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T09:58:51.177",
"Id": "259150",
"ParentId": "259119",
"Score": "9"
}
},
{
"body": "<blockquote>\n<p>consuming as little memory and time as possible</p>\n</blockquote>\n<p>While your one bit per possible address is decent, it's not as little as possible. I actually have to run Java with <code>-Xmx</code> to allow it to take more heap space than usual.</p>\n<p>An alternative idea: Go through the file, parse the addresses, and store them in temporary files. For example the address <code>1.2.3.4</code> goes into the file <code>0x0102.dat</code>, and you store only two bytes (0x03 and 0x04). The eight billion addresses thus will take 16 GB <em>disk</em> space (less than the compressed input). Afterwards, process the files individually (you can for example do it with a <code>BitSet</code> of just 8 KB) and add their counts together. (Note: I don't know Java much, and don't know whether opening <span class=\"math-container\">\\$2^{16}\\$</span> files is an issue. If it is, another option would be to create just 256 files (using an address's first number, and storing its lower <em>three</em> bytes).)</p>\n<p>Or you could use <a href=\"https://en.wikipedia.org/wiki/External_sorting\" rel=\"noreferrer\">external sorting</a> and then don't need <em>any</em> data structure to count (just compare each address to the previous one). You could even make the sorting remove duplicates in the process, which saves disk space and makes the counting afterwards even more trivial.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T19:19:39.470",
"Id": "511416",
"Score": "0",
"body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/122837/discussion-on-answer-by-kelly-bundy-counting-the-number-of-unique-ip-addresses-i)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T12:08:47.670",
"Id": "259160",
"ParentId": "259119",
"Score": "5"
}
},
{
"body": "<p>Since it's a job interview question, you probably want to:</p>\n<ul>\n<li>specify a package instead of using the default one. E.g. <code>package chpter.one; </code></li>\n<li>put only the necessary code (BitSetUniqueIpCounter.java, IpCounterApp.java, UniqueIpCounter.java) in <code>src/main/java</code>. Anything that is only used for tests should be in <code>src/test/java</code> or <code>src/test/resources/</code>.</li>\n<li>Don't forget to <a href=\"https://stackoverflow.com/a/34073306/6419007\">close the file</a>, even if <code>Files.lines</code> fails.</li>\n<li>Don't dump the whole stacktrace during a test which is expected to fail: tests are green but the console is still full of <code>java.io.FileNotFoundException: no file...</code>.</li>\n<li>use a linter (e.g. <a href=\"https://www.sonarlint.org/\" rel=\"noreferrer\">SonarLint</a>) to clean up the code and look for potential bugs.</li>\n</ul>\n<p>Your structure looks like:</p>\n<pre><code>├── pom.xml\n├── README.md\n└── src\n ├── main\n │ ├── java\n │ │ ├── BitSetUniqueIpCounter.java\n │ │ ├── IpCounterApp.java\n │ │ ├── NaiveStreamApiUniqueIpCounter.java\n │ │ ├── TestFileGenerator.java\n │ │ └── UniqueIpCounter.java\n │ └── resources\n │ └── million.txt\n └── test\n └── java\n ├── BitSetUniqueIpCounterTest.java\n └── UniqueIpCounterTest.java\n</code></pre>\n<p>And it could look like:</p>\n<pre><code>├── pom.xml\n├── README.md\n└── src\n ├── main\n │ └── java\n │ └── chpter\n │ └── one\n │ ├── BitSetUniqueIpCounter.java\n │ ├── IpCounterApp.java\n │ └── UniqueIpCounter.java\n └── test\n ├── java\n │ └── chpter\n │ └── one\n │ ├── BitSetUniqueIpCounterTest.java\n │ ├── NaiveStreamApiUniqueIpCounter.java\n │ ├── TestFileGenerator.java\n │ └── UniqueIpCounterTest.java\n └── resources\n └── million.txt\n</code></pre>\n<p>Note that the test folder looks fuller, and <code>src/main</code> is much leaner.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T17:37:56.007",
"Id": "511068",
"Score": "0",
"body": "Thank you. sir! I don't know about the need to close the file in case `Files.lines()`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T19:47:16.477",
"Id": "511077",
"Score": "0",
"body": "@chptr-one: That's also one advantage of SonarLint. There's always an explanation for each improvement, and an indication if it's critical or not. You're free to decide what's important or not. That being said, it's not too hard to always close files, and not doing it can lead to weird bugs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T20:08:41.563",
"Id": "511202",
"Score": "1",
"body": "I already installed SonarLint to my IDEA and it looks very cool. Thanks for this recommendation, it is very useful for newbie."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T20:26:08.517",
"Id": "511207",
"Score": "0",
"body": "\"Don't dump the whole stacktrace during a test which is expected to fail\" -- how do i do it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T20:33:19.217",
"Id": "511208",
"Score": "1",
"body": "@chptr-one: Keep up the good work, your work seems to indicate you're not a noobie. It's possible to learn new stuff about software development every day, anyway.\nOne way to not dump the stacktrace would be to not catch the exceptions inside the method, and let them propagate. Inside the test, you can then check that an exception is raised when no such file is found."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T15:24:53.630",
"Id": "259169",
"ParentId": "259119",
"Score": "8"
}
},
{
"body": "<p>I see one little problem with the code you gave, even though I feel like it's a pretty good take at the problem you have.</p>\n<p>Best case/worst case, you always ask for 512Mb memory. Say I give you a file that has 1 million times the same address, the code still initialized a 514 megabytes array.</p>\n<p>Instead of using an array structure, I believe a tree structure would be more appropriate. I will not write it, as I've not written Java in awhile, but let's look at this.</p>\n<p>There are 256 possible values for each of the 4 parts of an IP address, which leads you 256^4 possibilities (the 512 megabytes you use).</p>\n<p>So, what if we had a tree structure with four levels of depth and 256 leafs per node?</p>\n<p>In the worst case scenario where you'd use all possible values-ish (256^4 - 255 different addressed), you would require 512 megabytes.</p>\n<p>But, depending on the distribution of the addresses you have in your file, you could take as little as 256*4 bits of memory.</p>\n<p>The pseudo-algorithm I'd use would look something like this:</p>\n<pre><code>treeStructure = new treeStructure()\ncountUnique(list):\n for element in list: \n part1, part2, part3, part4 = parseIPString(element)\n\n if doesnt exist treeStructure[part1]:\n treeStructure[part1] = new treeStructure()\n\n if doesnt exist treeStructure[part1][part2]:\n treeStructure[part1][part2] = new treeStructure() \n\n if doesnt exist treeStructure[part1][part2][part3]:\n treeStructure[part1][part2][part3] = array[256]\n\n if treeStructure[part1][part2][part3][part4] == 0:\n treeStructure[part1][part2][part3][part4] = 1\n counter++\n</code></pre>\n<p>Now, I know this code is poorly written and I wouldn't show this in a job interview. It should be pretty easy to make it clean by yourself as you've done quite well in your original post. The goal of the pseudo-code is to show the algorithm.</p>\n<p>This way, you allocate memory in chunks of 256 bits when you need it instead of allocating a whole 512 megabytes at first.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T20:38:16.573",
"Id": "511081",
"Score": "1",
"body": "I was going to put up a tree structure suggestion, but you beat me to it. Dictionaries (like language dictionaries, not data structure dictionaries) are commonly stored this way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T21:36:47.693",
"Id": "511085",
"Score": "0",
"body": "@gregsdennis I feel like if you want to post it again with more explanation than my post it'd be a good addition!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T09:26:40.870",
"Id": "511127",
"Score": "0",
"body": "If your worst case is still only 512 megabytes... how do you get all the inner tree node data for free?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T09:34:04.307",
"Id": "511129",
"Score": "0",
"body": "That code looks like it would have rather bad caching behavior which would trash performance by a good bit. And given that the worst case scenario is still the same max memory I don't see anything that really recommends this method. If you're worried about physical memory usage, you could easily use memory mapped files (or similar approaches to only allocate virtual memory from your OS) and let the OS worry about when to actually allocate the memory."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T20:00:40.793",
"Id": "259178",
"ParentId": "259119",
"Score": "6"
}
},
{
"body": "<p>In my opinion, your code is too long to solve this specific problem.</p>\n<p>I'm not much into Java, but I would try the following methods:</p>\n<ol>\n<li>Use "Trie" like data structure. As the length of the IP is always less than or equal to 12, so it should also do the job. This method will require a very small amount of memory. First of all, build the trie, insert all the IPs(skip when the character is a dot) to the trie. When you are done, just count the number of end flags. Or you can also keep a counter flag. Increase the counter flag whenever an end flag appears.</li>\n</ol>\n<p>I'm sorry, I'm not good at Java. That's why I only added the instructions, no codes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T06:40:29.340",
"Id": "511104",
"Score": "5",
"body": "The naive solution of storing Strings in a HashSet was explicitly forbidden in the problem description."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T06:56:28.877",
"Id": "511106",
"Score": "0",
"body": "@TorbenPutkonen Although the slightly more memory-friendly option of an integer hashset isn't explicitly forbidden :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T20:18:25.213",
"Id": "511205",
"Score": "1",
"body": "@Corey Why do you need to spend whole `int` for each IP if you can spend just one bit? `HashSet<Integer>` will takes 32 times more memory then bit array. In addition `Integer` is wrapper. Primitive types will consume less memory and work faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T20:19:52.317",
"Id": "513058",
"Score": "0",
"body": "A Trie would be simply worse for this problem than a HashSet. What a Trie is good at is prefix searches. But we don't need to do prefix searches here. We need to store things efficiently. A Trie is a memory pig, having to allocate a pointer for each digit. Even assuming we use a hexadecimal representation (to give fewer digits than the twelve digit decimal representation), that is still eight pointers (each at least four bytes to store) to store a thirty-two bit (four bytes) number. And good luck in trying to implement a Trie alone in less code than the three files here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T07:49:22.497",
"Id": "513228",
"Score": "0",
"body": "@mdfst13 A trie would require 30-35 lines code maximum to solve this problem. No luck needed. And yes, we are not bound to implement any algorithm directly, we can always customize according to our needs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T08:49:35.380",
"Id": "513232",
"Score": "0",
"body": "Please do the rest of the maths to calculate the memory complexity of the trie for this specific problem.\nhttps://stackoverflow.com/questions/28774499/trie-data-structure-space-usage-in-java"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T05:51:56.537",
"Id": "259189",
"ParentId": "259119",
"Score": "-3"
}
}
] |
{
"AcceptedAnswerId": "259143",
"CommentCount": "20",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T13:45:04.760",
"Id": "259119",
"Score": "30",
"Tags": [
"java"
],
"Title": "Counting the number of unique IP addresses in a very large file"
}
|
259119
|
<p>I have below bash script which i have written to check the health of different storage component and then creates an incident through service-now tool.</p>
<p>This is script is working fine for me but i think this can be improved as i written this while learning through different google sources.</p>
<p>I would appreciate any help on improvisation of the script.</p>
<pre><code>#!/bin/bash
DATE=$(date +"%m_%d_%Y_%H_%M")
clusters=(udcl101 udcl2011 udcl3011 udcl4011)
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin:$PATH
incident=$1
sysid=UNKNOWN
checkvaultenv=$(echo $vaultenv | tr '[:upper:]' '[:lower:]')
if [[ "$checkvaultenv" == "" ]]
then
vaultenv=prod
else
if [[ "$checkvaultenv" != "dev" && "$checkvaultenv" != "test" && "$checkvaultenv" != "acc" && "$checkvaultenv" != "prod" ]]
then
echo unknown vault environment specified: $vaultenv
exit 1
fi
fi
vaultenvlc=$(echo $vaultenv | tr '[:upper:]' '[:lower:]')
vaultenvuc=$(echo $vaultenv | tr '[:lower:]' '[:upper:]')
SNOW_USERNAME=$(export EDITOR=cat ; ansible-vault view --vault-password-file=~/.ssh/sss.str.${vaultenvlc} ~/iss/vaults/vault-${vaultenvuc}.yml | awk '/vault_servicenow_username/{gsub(/"/, ""); print $2}')
SNOW_PASSWORD=$(export EDITOR=cat ; ansible-vault view --vault-password-file=~/.ssh/sss.str.${vaultenvlc} ~/iss/vaults/vault-${vaultenvuc}.yml | awk '/vault_servicenow_password/{gsub(/"/, ""); print $2}')
case $vaultenvlc in
ram)
SNOW_INSTANCE=udc2dev.service-now.com
;;
iqa)
SNOW_INSTANCE=udc2dev.service-now.com
;;
dev)
SNOW_INSTANCE=udc2dev.service-now.com
;;
test)
SNOW_INSTANCE=udc2trn.service-now.com
;;
acc)
SNOW_INSTANCE=udc2qa.service-now.com
;;
*)
SNOW_INSTANCE=udc2.service-now.com
;;
esac
SNOW_AUTH=$(echo -n $SNOW_USERNAME:$SNOW_PASSWORD)
create_incident()
{
url="https://${SNOW_INSTANCE}/api/now/table/incident"
curloutput=$(curl -sslv1 -u $SNOW_AUTH -X POST -s -H "Accept:application/json" -H "Content-Type:application/json" $url -d "$variables" 2>/dev/null)
RETURNCODE=$?
if [ "$RETURNCODE" == "0" ]
then
incident_number=$(echo $curloutput | python -c $'import sys, json\nprint json.load(sys.stdin)["result"]["number"]')
sysid=$(echo $curloutput | python -c $'import sys, json\nprint json.load(sys.stdin)["result"]["sys_id"]')
echo "OK: created incident $incident_number with sysid $sysid"
else
echo "ERROR creating incident:"
echo "======================================="
echo $curloutput
echo "======================================="
fi
}
# sets the variables for the incident
set_variables()
{
read -r -d '' variables <<- EOM
{
"short_description": "$snshort_description",
"assignment_group": "RD-DI-Infra-Storage",
"contact_type": "interface",
"state": "New",
"urgency": "3 - Low",
"impact": "3 - Low",
"cmdb_ci": "$udcl",
"u_sec_env": "Normal Secure",
"description": $body
}
EOM
}
# checks if file is empty *or* has only "", if not create incident
chk_body()
{
if [[ $body == "" || $body == '""' ]]
then
echo empty body
else
set_variables
echo $variables
echo ""
create_incident
fi
}
# actual storage health checks
for udcl in "${clusters[@]}";
do
body=$(ssh admin@$udcl aggr show -root false | awk '/^udc/ && $4 >= 92 {sub(/\r$/, ""); s = (s == "" ? "" : s "\\n") $0} END {printf "\"%s\"\n", s}')
snshort_description="aggr utilization above limit"
chk_body
body=$(ssh admin@$udcl "ro 0;snapshot show -create-time <21d" |awk '/^stv/ {sub(/\r$/, ""); s = (s == "" ? "" : s "\\n") $0} END {printf "\"%s\"\n", s}')
snshort_description="snapshots older then 21 days"
chk_body
body=$(ssh admin@$udcl "ro 1;event log show -time <8h"| awk '/netinet.ethr.duplct.ipAdr|secd.ldap.noServers|object.store.unavailable/ {sub(/\r$/, ""); s = (s == "" ? "" : s "\\n") $0} END {printf "\"%s\"\n", s}')
snshort_description="eventlog netinet.ethr.duplct.ipAdr, secd.ldap.noServers, object.store.unavailable messages"
chk_body
body=$(ssh admin@$udcl "ro 1;event log show -severity EMERGENCY -time <8h"| awk '/udc/ && !/netinet.ethr.duplct.ipAdr|secd.ldap.noServers|object.store.unavailable/ {sub(/\r$/, ""); s = (s == "" ? "" : s "\\n") $0} END {printf "\"%s\"\n", s}')
snshort_description="EMERGENCY messages"
chk_body
body=$(ssh admin@$udcl "ro 0;system healt alert show"| awk '/Node|Severity|Proba/ {sub(/\r$/, ""); s = (s == "" ? "" : s "\\n") $0} END {printf "\"%s\"\n", s}')
snshort_description="system healt alert show messages"
chk_body
body=$(ssh admin@$udcl "ro 0;vol show -volume *esx* -percent-used >=85" | awk '/stv/ && !/dr/ {sub(/\r$/, ""); s = (s == "" ? "" : s "\\n") $0} END {printf "\"%s\"\n", s}')
snshort_description="ESX volumes utilization more then 85"
chk_body
body=$(ssh admin@$udcl "ro 0;vol show -state offline -fields aggregate" | awk '/stv/ {sub(/\r$/, ""); s = (s == "" ? "" : s "\\n") $0} END {printf "\"%s\"\n", s}')
snshort_description="Validate offline volumes"
chk_body
done
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T16:38:19.887",
"Id": "511065",
"Score": "0",
"body": "You can double quote all the variables except consonants as you are using bash and can use array and then call into the for loop that's more elegant thank using `$(echo $clusters)` ."
}
] |
[
{
"body": "<p>Changes:</p>\n<ul>\n<li>Quote variables unless you have a good reason not to quote them.<br />\nHow about a password <code>* $(touch /tmp/sorry) *</code> ?</li>\n<li>Use <code>${parameter:-word}</code> for turning an empty <code>vaultenv</code> into <code>prod</code>.<br />\nIf parameter is unset or null, the expansion of word is substituted.<br />\nOtherwise, the value of parameter is substituted.</li>\n<li>Translate uppercase to lowercase only once. Use <code>${parameter,,}</code> for this.</li>\n<li>Combine tests on <code>vaultenv</code> into one block.<br />\nYour code will exit for <code>ram</code> and <code>iqa</code>, I accept these. Change when you want to exit.</li>\n<li>Changed variable names to lowercase<br />\nUPPERCASE is reserved for system vars like <code>PATH</code>.</li>\n<li>Removed unused <code>DATE</code>.</li>\n<li>I combined the two <code>ansible-vault</code> calls into one and assign to <code>SHOW_AUTH</code> without <code>echo</code>.</li>\n<li>Removed assignment to RETURNCODE</li>\n</ul>\n<p>The resulting script:</p>\n<pre><code>#!/bin/bash\nclusters=(udcl101 udcl2011 udcl3011 udcl4011)\nPATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin:$PATH\n\nincident="$1" # Unused ???????\nsysid=UNKNOWN\n\nvaultenv="${vaultenv:-prod}"\nvaultenvlc="${vaultenv,,}"\nvaultenvuc="${vaultenv^^}"\n\ncase "${vaultenvlc}" in\n ram)\n # or do you want to exit here?\n snow_instance=udc2dev.service-now.com\n ;;\n iqa)\n # or do you want to exit here?\n snow_instance=udc2dev.service-now.com\n ;;\n dev)\n snow_instance=udc2dev.service-now.com\n ;;\n test)\n snow_instance=udc2trn.service-now.com\n ;;\n acc)\n snow_instance=udc2qa.service-now.com\n ;;\n prod)\n snow_instance=udc2.service-now.com\n ;;\n *)\n echo "unknown vault environment specified: ${vaultenv}"\n exit 1\nesac\n\nsnow_auth=$(export EDITOR=cat;\n ansible-vault view --vault-password-file=~/.ssh/"sss.str.${vaultenvlc}" ~/iss/vaults/"vault-${vaultenvuc}.yml" |\n awk '\n /vault_servicenow_username/ {gsub(/"/, ""); usr=$2}\n /vault_servicenow_password/ {gsub(/"/, ""); pw=$2}\n END {printf("%s:%s", usr, pw)}\n ')\n\ncreate_incident()\n{\n url="https://${snow_instance}/api/now/table/incident"\n if curloutput=$(curl -sslv1 -u "${snow_auth}" -X POST -s -H "Accept:application/json" -H "Content-Type:application/json" "${url}" -d "${variables}" 2>/dev/null); then\n incident_number=$(echo "${curloutput}" | python -c $'import sys, json\\nprint json.load(sys.stdin)["result"]["number"]')\n sysid=$(echo "${curloutput}" | python -c $'import sys, json\\nprint json.load(sys.stdin)["result"]["sys_id"]')\n echo "OK: created incident ${incident_number} with sysid ${sysid}"\n else\n echo "ERROR creating incident:"\n echo "======================================="\n echo "${curloutput}"\n echo "======================================="\n fi\n}\n\n\n# sets the variables for the incident\nset_variables()\n{\nread -r -d '' variables <<- EOM\n{\n "short_description": "${snshort_description}",\n "assignment_group": "RD-DI-Infra-Storage",\n "contact_type": "interface",\n "state": "New",\n "urgency": "3 - Low",\n "impact": "3 - Low",\n "cmdb_ci": "${udcl}",\n "u_sec_env": "Normal Secure",\n "description": ${body}\n}\nEOM\n}\n\n\n# checks if file is empty *or* has only "", if not create incident\nchk_body()\n{\n if [[ "${body}" == "" || "${body}" == '""' ]]; then\n echo empty body\n else\n set_variables\n echo "${variables}"\n echo ""\n create_incident\n fi\n}\n\n# actual storage health checks\n\nfor udcl in "${clusters[@]}";\ndo\n\n body=$(ssh admin@"${udcl}" aggr show -root false |\n awk '/^udc/ && $4 >= 92 {sub(/\\r$/, ""); s = (s == "" ? "" : s "\\\\n") $0}\n END {printf "\\"%s\\"\\n", s}')\n snshort_description="aggr utilization above limit"\n chk_body\n\n body=$(ssh admin@"${udcl}" "ro 0;snapshot show -create-time <21d" |\n awk '/^stv/ {sub(/\\r$/, ""); s = (s == "" ? "" : s "\\\\n") $0}\n END {printf "\\"%s\\"\\n", s}')\n snshort_description="snapshots older then 21 days"\n chk_body\n\n body=$(ssh admin@"${udcl}" "ro 1;event log show -time <8h"|\n awk '/netinet.ethr.duplct.ipAdr|secd.ldap.noServers|object.store.unavailable/ {sub(/\\r$/, ""); s = (s == "" ? "" : s "\\\\n") $0} \n END {printf "\\"%s\\"\\n", s}')\n snshort_description="eventlog netinet.ethr.duplct.ipAdr, secd.ldap.noServers, object.store.unavailable messages"\n chk_body\n\n body=$(ssh admin@"${udcl}" "ro 1;event log show -severity EMERGENCY -time <8h"|\n awk '/udc/ && !/netinet.ethr.duplct.ipAdr|secd.ldap.noServers|object.store.unavailable/ {sub(/\\r$/, ""); s = (s == "" ? "" : s "\\\\n") $0}\n END {printf "\\"%s\\"\\n", s}')\n snshort_description="EMERGENCY messages"\n chk_body\n\n body=$(ssh admin@"${udcl}" "ro 0;system healt alert show"|\n awk '/Node|Severity|Proba/ {sub(/\\r$/, ""); s = (s == "" ? "" : s "\\\\n") $0}\n END {printf "\\"%s\\"\\n", s}')\n snshort_description="system healt alert show messages"\n chk_body\n\n body=$(ssh admin@"${udcl}" "ro 0;vol show -volume *esx* -percent-used >=85" |\n awk '/stv/ && !/dr/ {sub(/\\r$/, ""); s = (s == "" ? "" : s "\\\\n") $0}\n END {printf "\\"%s\\"\\n", s}')\n snshort_description="ESX volumes utilization more then 85"\n chk_body\n\n body=$(ssh admin@"${udcl}" "ro 0;vol show -state offline -fields aggregate" |\n awk '/stv/ {sub(/\\r$/, ""); s = (s == "" ? "" : s "\\\\n") $0}\n END {printf "\\"%s\\"\\n", s}')\n snshort_description="Validate offline volumes"\n chk_body\n\ndone\n</code></pre>\n<p>I am not sure about introducing a new function for all your ssh calls:</p>\n<pre><code>for udcl in "${clusters[@]}";\ndo\n\n body=$(check "${udcl}" aggr)\n chk_body\n\n body=$(check "${udcl}" snapshot)\n chk_body\n\n body=$(check "${udcl}" showtime)\n chk_body\n\n ...\n}\n\ncheck() {\n case "$2" in\n "aggr") \n body=$(ssh admin@"${udcl}" aggr show -root false |\n awk '\n /^udc/ && $4 >= 92 {sub(/\\r$/, "");\n s = (s == "" ? "" : s "\\\\n") $0}\n END {printf "\\"%s\\"\\n", s}\n ')\n snshort_description="aggr utilization above limit"\n ;;\n ...\n esac\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T08:59:58.220",
"Id": "511615",
"Score": "1",
"body": "Thank you Walter for the detailed answer, +1 for the same and i am testing the same, will accept this after testing."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T15:51:09.963",
"Id": "259365",
"ParentId": "259120",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259365",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T15:44:52.753",
"Id": "259120",
"Score": "3",
"Tags": [
"json",
"bash",
"linux",
"shell"
],
"Title": "Bash Script for healthcheck linux"
}
|
259120
|
<p>I am trying to learn C++, so I started coding a custom string class (using only c-style strings) to get familiar with concepts like operator overloading etc. in the case we have a pointer attribute. I wanted to know if there is a smarter/better/neater way to implement the += operator (or the others).</p>
<p>So I am basically defining a private char pointer to store the c-style string, two constructors (empty, char* arg), a copy constructor, a move constructor, a destructor (to deallocate the allocated space from the heap) and two operators (to concatenate strings).</p>
<p><strong>mystring.h</strong></p>
<pre><code>#include <iostream>
#include <cstring>
class mystring
{
private:
char* str;
public:
mystring();
mystring(char* str);
mystring(const mystring &s);
mystring(mystring &&s) noexcept;
~mystring();
mystring& operator=(const mystring &s);
friend std::ostream& operator<<(std::ostream &out, const mystring &s);
mystring operator+(const mystring &s);
mystring& operator+=(const mystring &s);
};
</code></pre>
<p><strong>mystring.cpp</strong></p>
<pre><code>#include "mystring.h"
mystring::mystring() : mystring(nullptr) {};
mystring::mystring(char* str) : str{nullptr}
{
if(str == nullptr){
this->str = new char;
this->str = '\0';
}else {
this->str = new char[strlen(str) + 1];
strcpy(this->str, str);
}
}
// Deep copy
mystring::mystring(const mystring &s) : str{nullptr}
{
if(str == nullptr){
this->str = new char;
*(this->str) = '\0';
}else {
this->str = new char[strlen(s.str) + 1];
strcpy(this->str, s.str);
}
}
// Move constructor
mystring::mystring(mystring &&s) noexcept : str{s.str} { s.str = nullptr; }
mystring::~mystring() { delete [] str; }
mystring& mystring::operator=(const mystring &s){
if(this != &s){
this->str = new char[strlen(s.str) + 1];
strcpy(this->str, s.str);
}
return *this;
}
std::ostream& operator<<(std::ostream &out, const mystring &s){
out << s.str;
return out;
}
mystring mystring::operator+(const mystring &s){
mystring concat;
concat.str = new char[strlen(this->str) + strlen(s.str) + 1];
strcpy(concat.str, this->str);
strcat(concat.str, s.str);
return concat;
}
mystring& mystring::operator+=(const mystring &s){
// temp save "this" string to other
mystring other {new char(strlen(this->str) + 1)};
strcpy(other.str, this->str);
// allocate space for the concatenated string
this->str = new char[strlen(this->str) + strlen(s.str) + 1];
// move "this" and input strings to "this"
strcpy(this->str, other.str);
strcat(this->str, s.str);
return *this;
}
</code></pre>
|
[] |
[
{
"body": "<p>You did a single-null-allocation correctly(ish) once:</p>\n<pre><code>if(str == nullptr){\n this->str = new char;\n *(this->str) = '\\0';\n</code></pre>\n<p>and incorrectly a second time:</p>\n<pre><code>if(str == nullptr){\n this->str = new char;\n this->str = '\\0';\n</code></pre>\n<p>This will produce a memory leak. That aside, if your compiler allowed this without yelling about incompatible types, that makes me sad.</p>\n<p>Even then, as @TobySpeight indicates, the first style of allocation has a mismatch with your <code>delete[]</code> and also needs to follow array-like syntax.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T16:25:19.217",
"Id": "259172",
"ParentId": "259125",
"Score": "2"
}
},
{
"body": "<p>The problem with the representation (null-terminated <code>char*</code>, like C) is that it's inefficient for concatenation.</p>\n<p>If we use array+length, as is common for strings in many languages (including the C++ standard library), then we don't need to seek to the end for every operation (as we do here, hidden inside <code>strcat()</code> - even though we've already computed the length!). Read about the problems with "<a href=\"https://en.wikichip.org/wiki/schlemiel_the_painter%27s_algorithm\" rel=\"nofollow noreferrer\">Schlemiel the Painter</a>" and his algorithm.</p>\n<p>Converting null pointer into empty string is a good idea, avoiding special-case handling throughout the code. But there's a serious bug:</p>\n<blockquote>\n<pre><code> this->str = new char;\n</code></pre>\n</blockquote>\n<p>We need <code>new char[1]</code> there, because <code>new[]</code> and <code>delete[]</code> go together as a pair.</p>\n<p>This mismatch would be caught by Valgrind - I really recommend you exercise your code using a memory checker any time you write memory management code (that's every time you use a naked <code>new</code> or <code>new[]</code>; also if you ever use <code>std::malloc()</code> or any C libraries that haven't been wrapped in a RAII wrapper).</p>\n<p>Why do we have <code>mystring(mystring&&)</code> but no <code>operator=(mystring&&)</code>? It doesn't make sense to have a move constructor but always force copying for assignment.</p>\n<p>Style-wise, I don't like use of <code>this-></code> all over the place - that's just distracting clutter that can be avoided by giving arguments different names to members.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T16:32:04.203",
"Id": "259174",
"ParentId": "259125",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T17:49:29.397",
"Id": "259125",
"Score": "2",
"Tags": [
"c++",
"strings",
"reinventing-the-wheel",
"overloading"
],
"Title": "C++ overloading += operator in custom string class better implementation"
}
|
259125
|
<p>In a <a href="https://www.ted.com/talks/linus_torvalds_the_mind_behind_linux" rel="nofollow noreferrer">TED talk</a> Linus Torvalds made a point about <em>“good taste”</em> at approximately <a href="https://www.ted.com/talks/linus_torvalds_the_mind_behind_linux#t-850000" rel="nofollow noreferrer">14:10 in the interview</a>. I read through his examples of <em>“bad taste”</em> and <em>“good taste”</em> and wanted to implement the same principle for a function that deletes the last node in a singly linked list. I also followed <a href="https://www.kernel.org/doc/html/v4.10/process/coding-style.html" rel="nofollow noreferrer">his coding style</a>.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
/* linked list structure */
struct node {
int data;
struct node *next;
};
/* create new node */
struct node *new_node(int data, struct node *next)
{
struct node *new = malloc(sizeof *new);
if (!new) {
fprintf(stderr, "Error: memory allocation failed\n");
exit(EXIT_FAILURE);
}
new->data = data;
new->next = next;
return new;
}
/* delete last node */
void delete_last(struct node *head)
{
if (head == NULL) {
fprintf(stderr, "Error: linked list underflow\n");
exit(EXIT_FAILURE);
}
struct node **cursor = &head;
while ((*cursor)->next != NULL)
cursor = &(*cursor)->next;
free(*cursor);
*cursor = NULL;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T20:38:38.917",
"Id": "510980",
"Score": "2",
"body": "It's generally not good taste to `exit()` from a minor function call."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T21:39:48.150",
"Id": "510991",
"Score": "0",
"body": "@MrR Alright, what's the alternative?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T04:15:23.080",
"Id": "511000",
"Score": "1",
"body": "Instead of `void` make it `int` (or if you like bools, add the `stdbool` header) and return something to indicate the failure to the calling function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T20:32:34.763",
"Id": "511079",
"Score": "0",
"body": "As @debdutdeb said - have an error code, or in the case of delete (if there is no list the after effect is the same - there is still no list / there is 1 least node on the end - so it's not so much an error). AND of course the `new_node` method either needs documentation or is a `new_element_before` because it's not inserting at a random point it's inserting in a way that would break an existing list (if you put it say before the last element) - you'd end up with a final node pointed to by two nodes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T20:35:07.213",
"Id": "511080",
"Score": "0",
"body": "Lots of good advice over here https://codereview.stackexchange.com/questions/136077/insert-a-node-at-the-tail-of-a-linked-list - it's C++ but is more C like than not."
}
] |
[
{
"body": "<blockquote>\n<p>I also followed [Torvalds'] coding style</p>\n</blockquote>\n<p>I'm all for coding style standards, though I decline to listen to all of his suggestions simply because he's the loudest (seriously, very very loud) voice in the room. His blind obedience to 1988's K&R with no other rationale I find short-sighted as well. Anyway, enough editorializing:</p>\n<p>Your non-parenthesized <code>sizeof *new</code> falls on a matter in his guide that is a little ambiguous -</p>\n<blockquote>\n<p>The notable exceptions are <code>sizeof</code>, <code>typeof</code>, <code>alignof</code>, and <code>__attribute__</code>, which look somewhat like functions (and are usually used with parentheses in Linux, although they are not required in the language)</p>\n</blockquote>\n<p>Whereas parens are not required after <code>sizeof</code>, I see them in the majority of code I encounter so I'd recommend sticking with them.</p>\n<p>I warn against writing keywords from C++ as symbol names in C, in this case <code>new</code>. If ever you want this to be readily C++-compatible, this will cause you grief.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T08:51:40.940",
"Id": "511240",
"Score": "0",
"body": "I differ here, and don't like unnecessary parens when using `sizeof` - I find that helps draw attention to `sizeof (type)` as opposed to `sizeof expr`. As you say, it's all personal preference, and being consistent is what matters most."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T23:13:53.943",
"Id": "259221",
"ParentId": "259127",
"Score": "2"
}
},
{
"body": "<p>It's quite presumptive for a function to exit the program like this:</p>\n<blockquote>\n<pre><code> if (!new) {\n fprintf(stderr, "Error: memory allocation failed\\n");\n exit(EXIT_FAILURE);\n }\n</code></pre>\n</blockquote>\n<p>I'd argue that the caller is also better positioned to know whether an error message is useful, too:</p>\n<pre><code> if (!new) {\n return new;\n }\n</code></pre>\n<p>Similarly, removing from empty list is better conveyed by a return value.</p>\n<p>Explicit comparison against <code>NULL</code> seems clunky to me (and inconsistent with the test of <code>new</code> above), given that pointers have a well-understood truthiness:</p>\n<pre><code>if (!head) {\n</code></pre>\n\n<pre><code>while ((*cursor)->next)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T09:14:11.637",
"Id": "259232",
"ParentId": "259127",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259232",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T18:35:50.870",
"Id": "259127",
"Score": "1",
"Tags": [
"c",
"linked-list"
],
"Title": "Delete last node in singly linked list"
}
|
259127
|
<p>I am trying to using HttpClient for making API calls from a different domain and for that purpose I have created the following service class after doing some research. It is 4.7.2 framework and not a .NET core system. I have created library class for this with following classes. Please give me your valuable suggestions for changes or enhancements</p>
<p>IRequestService.cs file</p>
<pre><code>public interface IRequestService
{
Task<TResult> GetAsync<TResult>(HttpClientNS client, string url);
Task<string> GetStringAsync(HttpClientNS client, string url);
Task<TResult> PostAsync<TRequest, TResult>(HttpClientNS client, TRequest t, string url);
HttpClientNS GetClient();
}
</code></pre>
<p>RequestService.cs</p>
<pre><code>public class RequestService : IRequestService
{
private readonly string _hostWebApiUrl;
private readonly string _apiAuthKey;
public RequestService()
{
_hostWebApiUrl = Config.AppSettings["TestWebApiURL"];
_apiAuthKey = Config.AppSettings["ApiKey"];
}
public RequestService(string hostWebApiUrl, string apiAuthKey)
{
_hostWebApiUrl = hostWebApiUrl;
_apiAuthKey = apiAuthKey;
}
public HttpClientNS GetClient()
{
string _baseAddress = _hostWebApiUrl;
var client = new HttpClientNS
{
BaseAddress = new Uri(_baseAddress)
};
client.DefaultRequestHeaders.Add("AuthApiKey", _apiAuthKey);
return client;
}
public async Task<TResult> GetAsync<TResult>(HttpClientNS client, string url)
{
client.Timeout = TimeSpan.FromSeconds(30);
var result = default(TResult);
try
{
var response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
//var jsonString = await response.Content.ReadAsStringAsync();
//var result = JsonConvert.DeserializeObject<TResult>(jsonString);
await response.Content.ReadAsStringAsync().ContinueWith((Task<string> x) =>
{
if (x.IsFaulted)
throw x.Exception;
result = JsonConvert.DeserializeObject<TResult>(x.Result);
});
}
catch (Exception ex)
{
}
return result;
}
public async Task<string> GetStringAsync(HttpClientNS client, string url)
{
var httpRequest = new HttpRequestMessage(new HttpMethod("GET"), url);
var response = client.SendAsync(httpRequest).Result;
var jsonString = await response.Content.ReadAsStringAsync();
return jsonString;
}
public async Task<TResult> PostAsync<TRequest, TResult>(HttpClientNS client, TRequest t, string url)
{
var result = default(TResult);
var json = JsonConvert.SerializeObject(t);
HttpContent httpContent = new StringContent(json);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
//response.EnsureSuccessStatusCode();
//var jsonString = await response.Content.ReadAsStringAsync();
//var result = JsonConvert.DeserializeObject<TResult>(jsonString);
//return result;
var response = await client.PostAsync(url, httpContent).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
await response.Content.ReadAsStringAsync().ContinueWith((Task<string> x) =>
{
if (x.IsFaulted)
throw x.Exception;
result = JsonConvert.DeserializeObject<TResult>(x.Result);
});
return result;
}
}
</code></pre>
<p>I am making calls to these wrapper class containing generic methods as follows:</p>
<pre><code>public class TestApiClient
{
private IRequestService RequestService;
private readonly string _apiUrl;
public TestApiClient(IRequestService request)
{
RequestService = new RequestService();
_apiUrl = "api/TestCustomer";
}
public async Task<bool> IsCustomerVendor(int vendorId)
{
var url = string.Format(_apiUrl + "/IsCUstomerVendor?vendorId={0}", vendorId);
var client = RequestService.GetClient();
var result = await RequestService.GetAsync<bool>(client, url);
return result;
}
public async Task<bool> IsCUstomerDataInvalid(int productId, int financeCompanyId, string balloonDealerState)
{
var url = _apiUrl + "/IsCUstomerDataInvalid";
var content = new { CustomerId = customerId, CompanyId = companyId, DealerState = DealerState };
//var result = _webClientHelper.PostContent<bool>(url, content);
var client = RequestService.GetClient();
var result = await RequestService.PostAsync<Object,bool>(client, content, url);
return result;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T22:29:25.007",
"Id": "511087",
"Score": "1",
"body": "What is `HttpClientNS`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T10:42:35.100",
"Id": "511139",
"Score": "1",
"body": "Please try to avoid blocking calls like this: `client.SendAsync(httpRequest).Result;` **always** prefer `await`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-16T19:41:38.367",
"Id": "512176",
"Score": "0",
"body": "If the answer below was helpful, you may mark it as accepted."
}
] |
[
{
"body": "<p>Quick remarks:</p>\n<ul>\n<li><p>Don't do this:</p>\n<pre><code> public RequestService()\n {\n _hostWebApiUrl = Config.AppSettings["TestWebApiURL"];\n _apiAuthKey = Config.AppSettings["ApiKey"];\n }\n\n public RequestService(string hostWebApiUrl, string apiAuthKey)\n {\n _hostWebApiUrl = hostWebApiUrl;\n _apiAuthKey = apiAuthKey;\n }\n</code></pre>\n<p>Instead pass the values you get to the constructor that can accept these values:</p>\n<pre><code> public RequestService()\n : this(Config.AppSettings["TestWebApiURL"],\n Config.AppSettings["ApiKey"])\n {\n }\n</code></pre>\n<p>I'd also concentrate all the code that retrieves values from <code>Config.AppSettings</code> in a single class instead of littering my code with calls to <code>Config.AppSettings</code>.</p>\n</li>\n<li><p>Is it a good idea to be inconsistent with names? <code>"AuthApiKey"</code> vs <code>_apiAuthKey</code> is somewhat confusing to me, for instance. (And then the app setting key is <code>"ApiKey"</code>, yet another name.)</p>\n</li>\n<li><p>It's a bad idea to catch an exception and not do anything with it. I'd hope to see at least some logging.</p>\n</li>\n<li><p>Why not use the <code>Get</code> property of <code>HttpMethod</code>?</p>\n</li>\n<li><p><code>GetStringAsync</code> doesn't catch errors or exceptions. What if something goes wrong? The same is true for many of your other methods which connect to the API. I'd provide a way to log all those things instead of expecting everything to go well; hunting for problems when things don't go as planned and finding there is no logging is very frustrating.</p>\n<p>I'd go even further and offer logging for all kinds of things: which method is called with what value, etc. That way you can see the flow that happened and you can likely easier spot why something went wrong (because sometimes merely logging the error is insufficient).</p>\n</li>\n<li><p>Why do you have <code>IRequestService request</code> (bad name! this isn't a "request") as a parameter of <code>TestApiClient</code>, yet don't use it?</p>\n</li>\n<li><p>Why do you use the old <code>string.Format</code> instead of <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated\" rel=\"nofollow noreferrer\">string interpolation</a>?</p>\n</li>\n<li><p>Is the "u" in <code>IsCUstomerDataInvalid</code> (both the method name and the URL used inside that method) supposed to be a "U"? Or is that a typo?</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T18:26:53.263",
"Id": "511072",
"Score": "0",
"body": "Thank you BcdotWeb for the recommendations."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T08:23:01.857",
"Id": "259147",
"ParentId": "259133",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T20:46:46.890",
"Id": "259133",
"Score": "0",
"Tags": [
"c#",
"asp.net-mvc",
"asp.net-web-api"
],
"Title": "Generic Wrapper class for HTTPClient methods"
}
|
259133
|
<p>I have been coding 'Pac-Man' with my 16yo. A hopefully not too boring project to help improve his Python coding. We have just moved the 'Ghosts' into a class which was a good first introduction to objects for him.</p>
<p>My coding is far from perfect, and especially not in Python. Which was only just being invented when I was learning this stuff. I am looking for feedback on how to improve the professionalism of his code:</p>
<ul>
<li>how to be more 'pythonic'</li>
<li>how to enable him to add more features to this project in the future</li>
</ul>
<p>Clearly he has a long way to go. So looking for minor steps forwards that we can understand and work with rather than a whole sale rewrite please :)</p>
<p>Ultimately I would like to get him to implement some search algorithms for the ghosts - (BFS, A*, etc.), so ensuring the current structure is fit to do that within would be good.</p>
<p>Code provided below. Or as <a href="https://filebin.net/nxe82o408swslmyf" rel="noreferrer">a zip with the textures etc</a>. Currently the code runs but we have not got lives, ghosts killing pacman, levels, etc. coded yet.</p>
<pre><code>#imports
import pygame
import os
import time
import math as maths
#Constants
# Text Positioning
CENTRE_MID = 1
LEFT_MID = 2
RIGHT_MID = 3
CENTRE_TOP = 4
LEFT_TOP = 5
RIGHT_TOP = 6
CENTRE_BOT = 7
LEFT_BOT = 8
RIGHT_BOT = 9
#Pacman Orientation
UP = 10
RIGHT = 11
LEFT = 12
DOWN = 13
HYPERJUMPALLOWED = True
HYPERJUMPNOTALLOWED = False
PIXEL = 20
FRAMERATE = 1
# DX and DY for each direction
NORTH = (0, -PIXEL)
SOUTH = (0, PIXEL)
EAST = (PIXEL, 0)
WEST = (-PIXEL, 0)
YELLOW = (255, 255, 102)
PALEYELLOW = (128, 128, 51)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
RED = (255,0,0)
BOARDPIXELWIDTH = 200
BOARDPIXELHEIGHT = 200
#Global Variables
gameOver = False
win = False
score = 0
#Dictionary mapping between board chars and gif's to display.
char_to_image = {'.' : pygame.transform.scale(pygame.image.load('pellet.gif'), (PIXEL, PIXEL)),
'=' : pygame.transform.scale(pygame.image.load('wall-nub.gif'), (PIXEL, PIXEL)),
'=T' : pygame.transform.scale(pygame.image.load('wall-end-b.gif'), (PIXEL, PIXEL)),
'=R' : pygame.transform.scale(pygame.image.load('wall-end-l.gif'), (PIXEL, PIXEL)),
'=L' : pygame.transform.scale(pygame.image.load('wall-end-r.gif'), (PIXEL, PIXEL)),
'=B' : pygame.transform.scale(pygame.image.load('wall-end-t.gif'), (PIXEL, PIXEL)) ,
'=TR' : pygame.transform.scale(pygame.image.load('wall-corner-ll.gif'), (PIXEL, PIXEL)),
'=TL' : pygame.transform.scale(pygame.image.load('wall-corner-lr.gif'), (PIXEL, PIXEL)),
'=BR' : pygame.transform.scale(pygame.image.load('wall-corner-ul.gif'), (PIXEL, PIXEL)),
'=BL' : pygame.transform.scale(pygame.image.load('wall-corner-ur.gif'), (PIXEL, PIXEL)),
'=TB' : pygame.transform.scale(pygame.image.load('wall-straight-vert.gif'), (PIXEL, PIXEL)),
'=RL' : pygame.transform.scale(pygame.image.load('wall-straight-horiz.gif'), (PIXEL, PIXEL)),
'=LTR' : pygame.transform.scale(pygame.image.load('wall-t-bottom.gif'), (PIXEL, PIXEL)),
'=TRB' : pygame.transform.scale(pygame.image.load('wall-t-left.gif'), (PIXEL, PIXEL)),
'=BLT' : pygame.transform.scale(pygame.image.load('wall-t-right.gif'), (PIXEL, PIXEL)),
'=RBL' : pygame.transform.scale(pygame.image.load('wall-t-top.gif'), (PIXEL, PIXEL)),
'=TRLB' : pygame.transform.scale(pygame.image.load('wall-x.gif'), (PIXEL, PIXEL)),
'U' : pygame.transform.scale(pygame.image.load('pacman-u 4.gif'), (PIXEL, PIXEL)),
'R' : pygame.transform.scale(pygame.image.load('pacman-r 4.gif'), (PIXEL, PIXEL)),
'L' : pygame.transform.scale(pygame.image.load('pacman-l 4.gif'), (PIXEL, PIXEL)),
'D' : pygame.transform.scale(pygame.image.load('pacman-d 4.gif'), (PIXEL, PIXEL)),
'!P' : pygame.transform.scale(pygame.image.load('Pinky.gif'), (PIXEL, PIXEL)),
'!P.' : pygame.transform.scale(pygame.image.load('Pinky.gif'), (PIXEL, PIXEL)),
'!B' : pygame.transform.scale(pygame.image.load('Blinky.gif'), (PIXEL, PIXEL)),
'!B.' : pygame.transform.scale(pygame.image.load('Blinky.gif'), (PIXEL, PIXEL)),
'!I' : pygame.transform.scale(pygame.image.load('Inky.gif'), (PIXEL, PIXEL)),
'!I.' : pygame.transform.scale(pygame.image.load('Inky.gif'), (PIXEL, PIXEL)),
'!C' : pygame.transform.scale(pygame.image.load('Clyde.gif'), (PIXEL, PIXEL)),
'!C.' : pygame.transform.scale(pygame.image.load('Clyde.gif'), (PIXEL, PIXEL)),
}
#Class stuff
class Ghost:
def __init__(self, ghostPixelX, ghostPixelY, sprite):
print("Init " + sprite)
self.ghostPixelX = ghostPixelX
self.ghostPixelY = ghostPixelY
self.sprite = sprite
def draw(self):
#print("draw " + self.sprite)
dis.blit(char_to_image[self.sprite], (self.ghostPixelX, self.ghostPixelY))
def erase(self):
#print("erase " + self.sprite)
# Erase Ghost by drawing black rectangle over it
pygame.draw.rect(dis, BLACK, [self.ghostPixelX, self.ghostPixelY, PIXEL, PIXEL])
boardX = int(self.ghostPixelX/PIXEL)
boardY = int(self.ghostPixelY/PIXEL)
# If the space contains food, redraw the food
if "." in board[boardY][boardX]:
dis.blit(char_to_image["."], (self.ghostPixelX, self.ghostPixelY))
def move(self, pacManPixelX, pacManPixelY):
#print("PreMove: " + str(self.sprite) + " " + str(self.ghostPixelX) + " " + str(self.ghostPixelY))
#if score moves, so does directions
#Sorts directions to which direction is best to take
directions = [NORTH, EAST, SOUTH, WEST]
score = ["","","",""] #Which move is best
#Calculate distance between Ghost and PacMan
pixelDistanceX = pacManPixelX - self.ghostPixelX
pixelDistanceY = pacManPixelY - self.ghostPixelY
pixelDistance = maths.sqrt(pixelDistanceX**2 + pixelDistanceY**2)
#Calculate distance between Ghost and PacMan after a move in each direction
for i, direction in enumerate(directions):
ghostDX, ghostDY = direction
newGhostPixelX = self.ghostPixelX + ghostDX
newGhostPixelY = self.ghostPixelY + ghostDY
newPixelDistanceX = pacManPixelX - newGhostPixelX
newPixelDistanceY = pacManPixelY - newGhostPixelY
newPixelDistance = maths.sqrt(newPixelDistanceX**2 + newPixelDistanceY**2)
#Store how much better (closer) or worse (further away) the move would take the ghost from PacMan
score[i] = pixelDistance - newPixelDistance
#Insertion sort O(n)
#Iterates through the list for the next number to sort (start at pos 1)
for index in range(1, len(score)):
currentEntry = score[index]
currentEntryDir = directions[index]
position = index
#Iterates through the list for the number to swap
while position > 0 and score[position-1] > currentEntry:
#Copies the lower position into the original position, overwriting it
score[position] = score[position-1]
directions[position] = directions[position-1]
position = position - 1
#puts the stored value from position, into the final lower position
score[position] = currentEntry
directions[position] = currentEntryDir
# Take the now sorted list of moves, trying each one in turn and take the best move possible
for direction in reversed(directions):
ghostDX, ghostDY = direction
newGhostPixelX = self.ghostPixelX + ghostDX
newGhostPixelY = self.ghostPixelY + ghostDY
# Ghosts cant hyperjump
if newGhostPixelX >= 0 and newGhostPixelX < BOARDPIXELWIDTH and newGhostPixelY >= 0 and newGhostPixelX < BOARDPIXELHEIGHT:
# Ghosts can't go through walls
if TestMove(newGhostPixelX, newGhostPixelY, HYPERJUMPNOTALLOWED):
#print(direction)
self.ghostPixelX = newGhostPixelX
self.ghostPixelY = newGhostPixelY
#print("PostMove: " + str(self.sprite) + " " + str(self.ghostPixelX) + " " + str(self.ghostPixelY))
print("")
return
#Functions
# Load Board from a file in current directory
# Boards are text files called "board-X.txt"
def LoadBoard():
#ToDo load board from file
#10 x 10 Board
board = [['=BR', '=RL', '=RL', '=L', 'O', '.', '=R', '=RL', '=RL', '=BL'],
['=TB', '!B.', '.', '.', '.', '.', '.', '.', '!I.', '=TB'],
['=TB', '.', '=BR', '=L', '.', '.', '=R', '=BL', '.', '=TB'],
['=T', '.', '=T', '.', '.', '.', '.', '=T', '.', '=T'],
['.', '.', '.', '.', '.', 'U', '.', '.', '.', 'O'],
['O', '.', '.', '.', '.', '.', '.', '.', '.', '.'],
['=B', '.', '=B', '.', '.', '.', '.', '=B', '.', '=B'],
['=TB', '.', '=TR', '=L', '.', '.', '=R', '=TL', '.', '=TB'],
['=TB', '!C.', '.', '.', '.', '.', '.', '.', '!P.', '=TB'],
['=TR', '=RL', '=RL', '=L', '.', 'O', '=R', '=RL', '=RL', '=TL']]
global foodTotal
global pacManPixelX, pacManPixelY, pacManFacing, pacManDX, pacManDY
global Pinky, Blinky, Inky, Clyde
foodTotal = 0
pacManPixelX = pacManPixelY = pacManDX = pacManDY = 0
pacManFacing = UP
#ToDo Load Board Pixel Width and Height here and delete from top of this file
for boardY, line in enumerate(board):
for boardX, symbol in enumerate(line):
if symbol == ".":
foodTotal +=1 # Count how much food we start with
elif symbol == "!P." or symbol == "!P": #Which Ghost is it?
Pinky = Ghost(boardX * PIXEL, boardY * PIXEL, "!P") #Create the ghost!
elif symbol == "!B." or symbol == "!B":
Blinky = Ghost(boardX * PIXEL, boardY * PIXEL, "!B")
elif symbol == "!I." or symbol == "!I":
Inky = Ghost(boardX * PIXEL, boardY * PIXEL, "!I")
elif symbol == "!C." or symbol == "!C":
Clyde = Ghost(boardX * PIXEL, boardY * PIXEL, "!C")
elif symbol == "U":
pacManPixelX = boardX * PIXEL # Get PacMan starting position
pacManPixelY = boardY * PIXEL
return board
#Draw Board
def DrawBoard():
for y, line in enumerate(board):
# Convert from board PIXEL to real PIXEL
y *= PIXEL
for x, symbol in enumerate(line):
# Convert from board PIXEL to real PIXEL
x *= PIXEL
# Convert board chars to gif filename using dictionary
if symbol != "O":
dis.blit(char_to_image[symbol], (x, y))
#Test if Character can move to new location
def TestMove(newPixelX, newPixelY, hyperJumpAllowed):
#TODO This is used for Ghosts and PacMan, Ghosts are not allowed to move in to a square already occupied by a Ghost
# Pacman is, but then will die
if newPixelX >= BOARDPIXELWIDTH or newPixelY >= BOARDPIXELHEIGHT or newPixelX < 0 or newPixelY < 0:
if (hyperJumpAllowed):
#If move would be a HyperJump, and HypeJumps are allowed then move must be ok
return True
else:
#If move would be a HyperJump, and HypeJumps are not allowed then move must not be ok
return False
newBoardX = int(newPixelX/PIXEL)
newBoardY = int(newPixelY/PIXEL)
#Test if move would end up in a wall
if "=" in board[newBoardY][newBoardX]:
return False
else:
return True
#Move PacMan to new location, but dont draw the update
def MovePacMan(pixelX, pixelY, dPixelX, dPixelY, facing):
# Move PacMan
newPixelX = pixelX + dPixelX
newPixelY = pixelY + dPixelY
# Check if move needs to be a HyperJump and if so HyperJump
if (newPixelX >= BOARDPIXELWIDTH):
newPixelX = 0
elif (newPixelX < 0):
newPixelX = BOARDPIXELWIDTH - PIXEL
if (newPixelY >= BOARDPIXELHEIGHT):
newPixelY = 0
elif (newPixelY < 0):
newPixelY = BOARDPIXELHEIGHT - PIXEL
return newPixelX, newPixelY
def moveGhosts(pacManPixelX, pacManPixelY):
Pinky.move(pacManPixelX, pacManPixelY)
Blinky.move(pacManPixelX, pacManPixelY)
Inky.move(pacManPixelX, pacManPixelY)
Clyde.move(pacManPixelX, pacManPixelY)
def eraseGhosts():
Pinky.erase()
Blinky.erase()
Inky.erase()
Clyde.erase()
def ErasePacMan(pixelX, pixelY):
# Erase PacMan from old position by drawing black rectangle over it
pygame.draw.rect(dis, BLACK, [pixelX, pixelY, PIXEL, PIXEL])
def drawGhosts():
Pinky.draw()
Blinky.draw()
Inky.draw()
Clyde.draw()
#Draw PacMan at a new position
def DrawPacMan(pixelX, pixelY, facing):
# Draw PacMan at new position
if facing == UP:
dis.blit(char_to_image['U'], (pixelX, pixelY))
elif facing == DOWN:
dis.blit(char_to_image['D'], (pixelX, pixelY))
elif facing == LEFT:
dis.blit(char_to_image['L'], (pixelX, pixelY))
elif facing == RIGHT:
dis.blit(char_to_image['R'], (pixelX, pixelY))
# Remove food at new board position
board[int(pixelY / PIXEL)][int(pixelX / PIXEL)] = "O"
#Play sounds as PacMan eats
def PlaySound(pixelX, pixelY):
boardX = int(pixelX / PIXEL)
boardY = int(pixelY / PIXEL)
#Play sound if new position has food
if board[boardY][boardX] == ".":
# Alternate between two different sounds
if (boardX + boardY) % 2 == 0:
food1Sound.play()
else:
food2Sound.play()
else:
defaultSound.play()
def message(msg, color, pixelX, pixelY, fontSize, align):
#Setup font
font_style = pygame.font.SysFont("bahnschrift", fontSize)
# Render text ont a surface
msgRendered = font_style.render(msg, True, color)
# Get size of surface
msgPixelWidth, msgPixelHeight = msgRendered.get_size()
# Change position to draw in relation to align
if align == CENTRE_MID:
pixelX = pixelX - (msgPixelWidth / 2)
pixelY = pixelY - (msgPixelHeight / 2)
elif align == CENTRE_TOP:
pixelX = pixelX - (msgPixelWidth / 2)
dis.blit(msgRendered, [pixelX, pixelY])
#Main Code
pygame.init()
#Setup display and pygame clock
dis = pygame.display.set_mode((BOARDPIXELWIDTH, BOARDPIXELHEIGHT + ( 2 * PIXEL)))
pygame.display.set_caption('Pac-man by ME')
clock = pygame.time.Clock()
#Setup Sounds
if os.path.isfile("1-pellet1.wav") and os.path.isfile("1-pellet2.wav") and os.path.isfile("1-default.wav"):
sound = True
food1Sound = pygame.mixer.Sound("1-pellet1.wav")
food2Sound = pygame.mixer.Sound("1-pellet2.wav")
defaultSound = pygame.mixer.Sound("1-default.wav")
else:
print("Warning: Sound files not found, not playing sounds.")
sound = False
#Load board from file
#ToDo Load random board or different board each level
board = LoadBoard()
#Draw Board
DrawBoard()
pygame.display.flip()
#Game Loop
while not gameOver:
for event in pygame.event.get():
#Allows quitting
if event.type == pygame.QUIT:
gameOver = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
pacManFacing = LEFT
pacManDX, pacManDY = WEST
#pacManDX = -PIXEL
#pacManDY = 0
elif event.key == pygame.K_RIGHT:
pacManFacing = RIGHT
pacManDX, pacManDY = EAST
#pacManDX = PIXEL
#pacManDY = 0
elif event.key == pygame.K_UP:
pacManFacing = UP
pacManDX, pacManDY = NORTH
#pacManDY = -PIXEL
#pacManDX = 0
elif event.key == pygame.K_DOWN:
pacManFacing = DOWN
pacManDX, pacManDY = SOUTH
#pacManDY = PIXEL
#pacManDX = 0
#Can we move to new position?
if TestMove(pacManPixelX + pacManDX, pacManPixelY + pacManDY, HYPERJUMPALLOWED):
#Erase PacMan
ErasePacMan(pacManPixelX, pacManPixelY)
#Calculate new position
pacManPixelX, pacManPixelY = MovePacMan(pacManPixelX, pacManPixelY, pacManDX, pacManDY, pacManFacing)
#print("pacManPixelX " + str(pacManPixelX) + " pacManPixelY " + str(pacManPixelY))
if board[int(pacManPixelY / PIXEL)][int(pacManPixelX / PIXEL)] == ".":
score+=1
foodTotal-=1
#Sound
if sound:
PlaySound(pacManPixelX, pacManPixelY)
#Draw the turn and remove food
DrawPacMan(pacManPixelX, pacManPixelY, pacManFacing)
#Update the score
pygame.draw.rect(dis, BLACK, [0, BOARDPIXELHEIGHT, BOARDPIXELWIDTH, PIXEL])
message(("You're score is " +str(score)), RED, 0, (BOARDPIXELHEIGHT), 15, LEFT_TOP)
# Ghosts
eraseGhosts()
#Calculate new Ghost position
moveGhosts(pacManPixelX, pacManPixelY)
#Draw new Ghost positions on the screen
drawGhosts()
pygame.display.update()
#TODO Has the ghost caughtPacMan, if so pacman looses 1 of 3 lives.
# So need lives system - 3 pacmen bottom right of screen that get 'used up' each time one dies
# What happens when Pacman dies? Ghosts get reset, pacman gets reset, score -10 and then carry on?
# Hint, pac man moves first, so when each ghost moves you can test if it has hit pacman
#if ghostPixelX == pacManPixelX and ghostPixelY == pacManPixelY:
# gameOver = True
#Win
if foodTotal == 0:
gameOver = True
win = True
#Tick the clock
clock.tick(FRAMERATE)
if win == True:
pygame.draw.rect(dis, YELLOW, [0, 0, BOARDPIXELWIDTH, BOARDPIXELHEIGHT])
message(("You Win!"), RED, BOARDPIXELWIDTH / 2, BOARDPIXELHEIGHT / 2, 15, CENTRE_MID)
message(("This message will dissapear in 5 seconds"), RED, (BOARDPIXELWIDTH / 2), (BOARDPIXELHEIGHT / 2 + PIXEL), 10, CENTRE_TOP)
pygame.display.update()
time.sleep(5)
else:
pygame.draw.rect(dis, RED, [0, 0, BOARDPIXELWIDTH, BOARDPIXELHEIGHT])
message(("You Lose!"), YELLOW, BOARDPIXELWIDTH / 2, BOARDPIXELHEIGHT / 2, 15, CENTRE_MID)
message(("This message will dissapear in 5 seconds"), YELLOW, (BOARDPIXELWIDTH / 2), (BOARDPIXELHEIGHT / 2 + PIXEL), 10, CENTRE_TOP)
pygame.display.update()
time.sleep(5)
pygame.quit()
quit()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T09:05:23.543",
"Id": "511121",
"Score": "1",
"body": "Can whoever voted to close this question please leave a comment explaining why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T10:57:59.487",
"Id": "511626",
"Score": "0",
"body": "I did that, since, if I understand the question correctly, the OP asked us to review code of a third party, namely their son."
}
] |
[
{
"body": "<blockquote>\n<p>I am looking for feedback on how to improve the professionalism of his code</p>\n</blockquote>\n<blockquote>\n<p>how to be more 'pythonic'</p>\n</blockquote>\n<p>The style you've used is atypical in Python as your code doesn't follow <em>all</em> of <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>.\nFor example you've used <code>camelCase</code> rather than <code>snake_case</code> for function names and variables.\nPersonally if your son wants to be a programmer, not a Python programmer, than ignoring the Python specific parts is fine.\nHowever your code has some inconsistencies, which would be better to iron out early to prevent becoming bad habits.</p>\n<p>For example; <code>CENTRE_MID</code> vs <code>HYPERJUMPALLOWED</code>, <code>moveGhosts</code> vs <code>MovePacMan</code>, using <code>"</code> or <code>'</code> to delimit strings, using spaces after commas - <code>(0, 0, 255)</code> and <code>(255,0,0)</code>, always using equal spaces around operators <code>x *= PIXEL</code> or <code>foodTotal +=1</code>.</p>\n<p>I'd recommend <a href=\"https://codereview.meta.stackexchange.com/a/5252\">installing a linter</a> to check your code.\nOr you could use a hinter like <a href=\"https://pypi.org/project/black/\" rel=\"nofollow noreferrer\">Black</a>, <a href=\"https://pypi.org/project/yapf/\" rel=\"nofollow noreferrer\">yapf</a> or <a href=\"https://pypi.org/project/autopep8/\" rel=\"nofollow noreferrer\">autopep8</a>.</p>\n<hr />\n<ul>\n<li>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>char_to_image = {'.' : pygame.transform.scale(pygame.image.load('pellet.gif'), (PIXEL, PIXEL)),\n '=' : pygame.transform.scale(pygame.image.load('wall-nub.gif'), (PIXEL, PIXEL)),\n ...\n }\n</code></pre>\n</blockquote>\n<p>We can see you've got a fair amount of duplicate code here.\nI'd build a dictionary of strings and then build the dictionary of PyGame sprites afterwards.</p>\n<pre class=\"lang-py prettyprint-override\"><code>_CHAR_TO_IMAGE = {\n ".": "pellet.gif",\n "=": "wall-nub.gif",\n}\n\nchar_to_image = {}\nfor key, value in _CHAR_TO_IMAGE.items():\n char_to_image[key] = pygame.transform.scale(pygame.image.load(value), (PIXEL, PIXEL))\n</code></pre>\n<p>We can instead use a dictionary comprehension to build the dictionary in a Pythonic manner.\n<a href=\"https://www.python.org/dev/peps/pep-0274/\" rel=\"nofollow noreferrer\">Dictionary comprehensions</a> are like <a href=\"https://www.w3schools.com/python/python_lists_comprehension.asp\" rel=\"nofollow noreferrer\">list comprehensions</a> however we'd be building a dictionary rather than a list.\nConverting the for loop into a dictionary comprehension would look like:</p>\n<pre class=\"lang-py prettyprint-override\"><code>char_to_image = {\n key: pygame.transform.scale(pygame.image.load(value), (PIXEL, PIXEL))\n for key, value in _CHAR_TO_IMAGE.items()\n}\n</code></pre>\n</li>\n<li><p>You should move your main code into a main function.\nYou can then use a <a href=\"https://docs.python.org/3/library/__main__.html\" rel=\"nofollow noreferrer\"><code>__main__</code> guard</a> to only run code if the file is the entry-point to the program.</p>\n<p>Like <code>main()</code> in C-like programming languages.</p>\n</li>\n<li>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>if win == True:\n</code></pre>\n</blockquote>\n<p>Since <code>bool</code> is a subclass of <code>int</code> true is equal to <code>1</code>, <code>1.0</code> and <code>1+0j</code>.\nYou should use one of:</p>\n<ul>\n<li><p>Check the type is 'truthy', so <code>if win:</code> is true.\nThe code will match far more values for example <code>2</code> is truthy.\nSo is <code>[1]</code>, <code>{1: 1}</code> and <code>{1}</code>.</p>\n</li>\n<li><p>If you want to ensure the value is <code>True</code> you should use <code>is</code>.\nNeeding to compare to just <code>True</code> is very rare.</p>\n</li>\n</ul>\n<p>The recommended way to check the value is truthy.</p>\n</li>\n<li>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>if "=" in board[newBoardY][newBoardX]:\n return False\nelse:\n return True\n</code></pre>\n</blockquote>\n<p>We can just return the expression in the if.</p>\n<pre class=\"lang-py prettyprint-override\"><code>return "=" not in board[newBoardY][newBoardX]\n</code></pre>\n<p>Since using truthy checks is the norm in Python; even if <code>in</code> doesn't return <code>True</code> or <code>False</code> any code calling the function would still work the same way. (<strong>Note</strong>: <code>in</code> always returns <code>True</code> or <code>False</code> however some other operations can return truthy but not <code>True</code> values.)</p>\n</li>\n<li><p><code>Ghost.move</code> can be made a little simpler.</p>\n<ol>\n<li><p><code>pixelDistance</code> isn't needed as using Pythagoras' theorem already gives you the hypotenuse (distance) between the two objects.</p>\n</li>\n<li><p>We can use <code>list.sort</code> to sort the list.</p>\n<ol>\n<li>The sorting code will run in C not Python.\n(Probably will be faster)</li>\n<li>You don't have to write a sorting algorithm.\n(Makes the code simpler)</li>\n<li>Python uses the Timsort; an optimized version of the insertion sort.\n(Probably will be faster)</li>\n</ol>\n</li>\n<li>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code># Ghosts cant hyperjump\nif newGhostPixelX >= 0 and newGhostPixelX < BOARDPIXELWIDTH and newGhostPixelY >= 0 and newGhostPixelX < BOARDPIXELHEIGHT:\n # Ghosts can't go through walls\n if TestMove(newGhostPixelX, newGhostPixelY, HYPERJUMPNOTALLOWED):\n</code></pre>\n</blockquote>\n<p>Seems to me <code>TestMove</code> should include the first if statement.\nSince we've passed <code>HYPERJUMPNOTALLOWED</code> to the function and your comment says the code is preventing hyper-jumping.</p>\n</li>\n</ol>\n</li>\n<li><p>I think you need to add a board class.</p>\n<ul>\n<li>The board should convert (internally) from a Python list to pixels on the screen.</li>\n<li>The board should allow consumers to interact with a simple 2D array so the consumer <em>never touches pixels</em>.</li>\n<li>The board should have some convenience functions like checking if a place is a valid place to move.</li>\n<li>The board should allow the consumer to move objects on the board.</li>\n</ul>\n<p>I think having a solid board class is the major pain point in your code.</p>\n<p>After building a standardized board you should build a game class.\nThe game class should contain all the globals but <em>should not</em> include the event or blit loops.\nCalling the game class from such loops is ok.</p>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>#imports\nimport pygame\nimport os\nimport time\nimport math as maths\n\n#Constants\n# Text Positioning\nCENTRE_MID = 1\nLEFT_MID = 2\nRIGHT_MID = 3\nCENTRE_TOP = 4\nLEFT_TOP = 5\nRIGHT_TOP = 6\nCENTRE_BOT = 7\nLEFT_BOT = 8\nRIGHT_BOT = 9\n\n#Pacman Orientation\nUP = 10\nRIGHT = 11\nLEFT = 12\nDOWN = 13\n\nHYPERJUMPALLOWED = True\nHYPERJUMPNOTALLOWED = False\n\nPIXEL = 20\nFRAMERATE = 1\n\n# DX and DY for each direction\nNORTH = (0, -PIXEL)\nSOUTH = (0, PIXEL)\nEAST = (PIXEL, 0)\nWEST = (-PIXEL, 0)\n\nYELLOW = (255, 255, 102)\nPALEYELLOW = (128, 128, 51)\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\nBLUE = (0, 0, 255)\nRED = (255,0,0)\n\nBOARDPIXELWIDTH = 200\nBOARDPIXELHEIGHT = 200\n\n#Global Variables\ngameOver = False\nwin = False\nscore = 0\n\n\n#Dictionary mapping between board chars and gif's to display.\n_CHAR_TO_IMAGE = {'.' : 'pellet.gif',\n '=' : 'wall-nub.gif', \n '=T' : 'wall-end-b.gif',\n '=R' : 'wall-end-l.gif',\n '=L' : 'wall-end-r.gif',\n '=B' : 'wall-end-t.gif',\n '=TR' : 'wall-corner-ll.gif',\n '=TL' : 'wall-corner-lr.gif',\n '=BR' : 'wall-corner-ul.gif',\n '=BL' : 'wall-corner-ur.gif',\n '=TB' : 'wall-straight-vert.gif',\n '=RL' : 'wall-straight-horiz.gif',\n '=LTR' : 'wall-t-bottom.gif',\n '=TRB' : 'wall-t-left.gif',\n '=BLT' : 'wall-t-right.gif',\n '=RBL' : 'wall-t-top.gif',\n '=TRLB' : 'wall-x.gif',\n 'U' : 'pacman-u 4.gif',\n 'R' : 'pacman-r 4.gif',\n 'L' : 'pacman-l 4.gif',\n 'D' : 'pacman-d 4.gif',\n '!P' : 'Pinky.gif',\n '!P.' : 'Pinky.gif',\n '!B' : 'Blinky.gif',\n '!B.' : 'Blinky.gif',\n '!I' : 'Inky.gif',\n '!I.' : 'Inky.gif',\n '!C' : 'Clyde.gif',\n '!C.' : 'Clyde.gif',\n }\n\nchar_to_image = {\n key: pygame.transform.scale(pygame.image.load(value), (PIXEL, PIXEL))\n for key, value in _CHAR_TO_IMAGE.items()\n}\n\n\n#Class stuff\nclass Ghost:\n def __init__(self, ghostPixelX, ghostPixelY, sprite):\n print("Init " + sprite)\n self.ghostPixelX = ghostPixelX\n self.ghostPixelY = ghostPixelY\n self.sprite = sprite\n\n \n def draw(self):\n #print("draw " + self.sprite)\n dis.blit(char_to_image[self.sprite], (self.ghostPixelX, self.ghostPixelY))\n\n\n def erase(self):\n #print("erase " + self.sprite)\n # Erase Ghost by drawing black rectangle over it\n pygame.draw.rect(dis, BLACK, [self.ghostPixelX, self.ghostPixelY, PIXEL, PIXEL])\n \n boardX = int(self.ghostPixelX/PIXEL)\n boardY = int(self.ghostPixelY/PIXEL)\n \n # If the space contains food, redraw the food\n if "." in board[boardY][boardX]:\n dis.blit(char_to_image["."], (self.ghostPixelX, self.ghostPixelY))\n\n\n def move(self, pacManPixelX, pacManPixelY):\n directions = [NORTH, EAST, SOUTH, WEST]\n scored_directions = [\n (\n maths.sqrt(\n (pacManPixelX - self.ghostPixelX - ghostDX) ** 2\n + (pacManPixelY - self.ghostPixelY - ghostDY) ** 2\n ),\n (ghostDX, ghostDY)\n )\n for (ghostDX, ghostDY) in directions\n ]\n scored_directions.sort()\n for _, (ghostDX, ghostDY) in scored_direction:\n newGhostPixelX = self.ghostPixelX + ghostDX\n newGhostPixelY = self.ghostPixelY + ghostDY\n\n if TestMove(newGhostPixelX, newGhostPixelY, HYPERJUMPNOTALLOWED):\n self.ghostPixelX = newGhostPixelX\n self.ghostPixelY = newGhostPixelY\n return\n\n\n#Functions\n\n# Load Board from a file in current directory\n# Boards are text files called "board-X.txt"\ndef LoadBoard(): \n #ToDo load board from file\n #10 x 10 Board\n board = [['=BR', '=RL', '=RL', '=L', 'O', '.', '=R', '=RL', '=RL', '=BL'],\n ['=TB', '!B.', '.', '.', '.', '.', '.', '.', '!I.', '=TB'],\n ['=TB', '.', '=BR', '=L', '.', '.', '=R', '=BL', '.', '=TB'],\n ['=T', '.', '=T', '.', '.', '.', '.', '=T', '.', '=T'],\n ['.', '.', '.', '.', '.', 'U', '.', '.', '.', 'O'],\n ['O', '.', '.', '.', '.', '.', '.', '.', '.', '.'],\n ['=B', '.', '=B', '.', '.', '.', '.', '=B', '.', '=B'],\n ['=TB', '.', '=TR', '=L', '.', '.', '=R', '=TL', '.', '=TB'],\n ['=TB', '!C.', '.', '.', '.', '.', '.', '.', '!P.', '=TB'],\n ['=TR', '=RL', '=RL', '=L', '.', 'O', '=R', '=RL', '=RL', '=TL']]\n\n global foodTotal\n global pacManPixelX, pacManPixelY, pacManFacing, pacManDX, pacManDY\n global Pinky, Blinky, Inky, Clyde\n foodTotal = 0\n pacManPixelX = pacManPixelY = pacManDX = pacManDY = 0\n pacManFacing = UP\n \n #ToDo Load Board Pixel Width and Height here and delete from top of this file\n for boardY, line in enumerate(board):\n for boardX, symbol in enumerate(line):\n if symbol == ".":\n foodTotal +=1 # Count how much food we start with\n \n elif symbol == "!P." or symbol == "!P": #Which Ghost is it?\n Pinky = Ghost(boardX * PIXEL, boardY * PIXEL, "!P") #Create the ghost!\n elif symbol == "!B." or symbol == "!B": \n Blinky = Ghost(boardX * PIXEL, boardY * PIXEL, "!B")\n elif symbol == "!I." or symbol == "!I": \n Inky = Ghost(boardX * PIXEL, boardY * PIXEL, "!I")\n elif symbol == "!C." or symbol == "!C": \n Clyde = Ghost(boardX * PIXEL, boardY * PIXEL, "!C") \n \n elif symbol == "U":\n pacManPixelX = boardX * PIXEL # Get PacMan starting position\n pacManPixelY = boardY * PIXEL\n return board\n\n\n#Draw Board\ndef DrawBoard():\n for y, line in enumerate(board):\n # Convert from board PIXEL to real PIXEL\n y *= PIXEL\n for x, symbol in enumerate(line):\n # Convert from board PIXEL to real PIXEL\n x *= PIXEL\n \n # Convert board chars to gif filename using dictionary\n if symbol != "O":\n dis.blit(char_to_image[symbol], (x, y))\n\n\n#Test if Character can move to new location\ndef TestMove(newPixelX, newPixelY, hyperJumpAllowed):\n\n #TODO This is used for Ghosts and PacMan, Ghosts are not allowed to move in to a square already occupied by a Ghost\n # Pacman is, but then will die\n if newPixelX >= BOARDPIXELWIDTH or newPixelY >= BOARDPIXELHEIGHT or newPixelX < 0 or newPixelY < 0:\n return hyperJumpAllowed\n \n newBoardX = int(newPixelX/PIXEL)\n newBoardY = int(newPixelY/PIXEL)\n \n #Test if move would end up in a wall \n return "=" not in board[newBoardY][newBoardX]\n\n\n#Move PacMan to new location, but dont draw the update\ndef MovePacMan(pixelX, pixelY, dPixelX, dPixelY, facing):\n\n # Move PacMan\n newPixelX = pixelX + dPixelX\n newPixelY = pixelY + dPixelY\n\n # Check if move needs to be a HyperJump and if so HyperJump\n if (newPixelX >= BOARDPIXELWIDTH):\n newPixelX = 0\n elif (newPixelX < 0):\n newPixelX = BOARDPIXELWIDTH - PIXEL\n\n if (newPixelY >= BOARDPIXELHEIGHT):\n newPixelY = 0\n elif (newPixelY < 0):\n newPixelY = BOARDPIXELHEIGHT - PIXEL \n \n return newPixelX, newPixelY\n\n\ndef moveGhosts(pacManPixelX, pacManPixelY):\n Pinky.move(pacManPixelX, pacManPixelY)\n Blinky.move(pacManPixelX, pacManPixelY)\n Inky.move(pacManPixelX, pacManPixelY)\n Clyde.move(pacManPixelX, pacManPixelY)\n\n\ndef eraseGhosts():\n Pinky.erase()\n Blinky.erase()\n Inky.erase()\n Clyde.erase()\n\n\ndef ErasePacMan(pixelX, pixelY):\n # Erase PacMan from old position by drawing black rectangle over it\n pygame.draw.rect(dis, BLACK, [pixelX, pixelY, PIXEL, PIXEL])\n\n\ndef drawGhosts():\n Pinky.draw()\n Blinky.draw()\n Inky.draw()\n Clyde.draw()\n\n\n#Draw PacMan at a new position\ndef DrawPacMan(pixelX, pixelY, facing):\n # Draw PacMan at new position\n if facing == UP:\n dis.blit(char_to_image['U'], (pixelX, pixelY))\n elif facing == DOWN:\n dis.blit(char_to_image['D'], (pixelX, pixelY))\n elif facing == LEFT:\n dis.blit(char_to_image['L'], (pixelX, pixelY))\n elif facing == RIGHT:\n dis.blit(char_to_image['R'], (pixelX, pixelY))\n \n # Remove food at new board position\n board[int(pixelY / PIXEL)][int(pixelX / PIXEL)] = "O"\n\n\ndef message(msg, color, pixelX, pixelY, fontSize, align):\n #Setup font\n font_style = pygame.font.SysFont("bahnschrift", fontSize)\n \n # Render text ont a surface\n msgRendered = font_style.render(msg, True, color)\n \n # Get size of surface\n msgPixelWidth, msgPixelHeight = msgRendered.get_size()\n \n # Change position to draw in relation to align \n if align == CENTRE_MID:\n pixelX = pixelX - (msgPixelWidth / 2)\n pixelY = pixelY - (msgPixelHeight / 2)\n elif align == CENTRE_TOP:\n pixelX = pixelX - (msgPixelWidth / 2)\n \n dis.blit(msgRendered, [pixelX, pixelY])\n\n\n#Play sounds as PacMan eats\ndef PlaySound(pixelX, pixelY):\n boardX = int(pixelX / PIXEL)\n boardY = int(pixelY / PIXEL)\n \n #Play sound if new position has food\n if board[boardY][boardX] == ".":\n # Alternate between two different sounds\n if (boardX + boardY) % 2 == 0:\n food1Sound.play()\n else:\n food2Sound.play()\n else:\n defaultSound.play()\n\n\n\ndef main():\n pygame.init()\n\n #Setup display and pygame clock\n dis = pygame.display.set_mode((BOARDPIXELWIDTH, BOARDPIXELHEIGHT + ( 2 * PIXEL)))\n pygame.display.set_caption('Pac-man by ME')\n clock = pygame.time.Clock()\n\n #Setup Sounds\n if os.path.isfile("1-pellet1.wav") and os.path.isfile("1-pellet2.wav") and os.path.isfile("1-default.wav"):\n sound = True\n food1Sound = pygame.mixer.Sound("1-pellet1.wav")\n food2Sound = pygame.mixer.Sound("1-pellet2.wav")\n defaultSound = pygame.mixer.Sound("1-default.wav")\n else:\n print("Warning: Sound files not found, not playing sounds.")\n sound = False\n \n #Load board from file\n #ToDo Load random board or different board each level\n board = LoadBoard()\n\n #Draw Board\n DrawBoard()\n pygame.display.flip()\n \n #Game Loop\n while not gameOver:\n \n for event in pygame.event.get():\n #Allows quitting\n if event.type == pygame.QUIT:\n gameOver = True\n \n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n pacManFacing = LEFT\n pacManDX, pacManDY = WEST\n #pacManDX = -PIXEL\n #pacManDY = 0\n elif event.key == pygame.K_RIGHT:\n pacManFacing = RIGHT\n pacManDX, pacManDY = EAST\n #pacManDX = PIXEL\n #pacManDY = 0\n elif event.key == pygame.K_UP:\n pacManFacing = UP\n pacManDX, pacManDY = NORTH\n #pacManDY = -PIXEL\n #pacManDX = 0\n elif event.key == pygame.K_DOWN:\n pacManFacing = DOWN\n pacManDX, pacManDY = SOUTH\n #pacManDY = PIXEL\n #pacManDX = 0\n \n #Can we move to new position?\n if TestMove(pacManPixelX + pacManDX, pacManPixelY + pacManDY, HYPERJUMPALLOWED):\n #Erase PacMan\n ErasePacMan(pacManPixelX, pacManPixelY)\n \n #Calculate new position\n pacManPixelX, pacManPixelY = MovePacMan(pacManPixelX, pacManPixelY, pacManDX, pacManDY, pacManFacing)\n\n #print("pacManPixelX " + str(pacManPixelX) + " pacManPixelY " + str(pacManPixelY))\n if board[int(pacManPixelY / PIXEL)][int(pacManPixelX / PIXEL)] == ".":\n score+=1\n foodTotal-=1\n \n #Sound\n if sound:\n PlaySound(pacManPixelX, pacManPixelY)\n \n #Draw the turn and remove food\n DrawPacMan(pacManPixelX, pacManPixelY, pacManFacing)\n\n #Update the score\n pygame.draw.rect(dis, BLACK, [0, BOARDPIXELHEIGHT, BOARDPIXELWIDTH, PIXEL])\n message(("You're score is " +str(score)), RED, 0, (BOARDPIXELHEIGHT), 15, LEFT_TOP)\n\n # Ghosts\n eraseGhosts()\n\n #Calculate new Ghost position \n moveGhosts(pacManPixelX, pacManPixelY)\n\n #Draw new Ghost positions on the screen \n drawGhosts()\n \n pygame.display.update()\n\n #TODO Has the ghost caughtPacMan, if so pacman looses 1 of 3 lives.\n # So need lives system - 3 pacmen bottom right of screen that get 'used up' each time one dies\n # What happens when Pacman dies? Ghosts get reset, pacman gets reset, score -10 and then carry on?\n # Hint, pac man moves first, so when each ghost moves you can test if it has hit pacman\n #if ghostPixelX == pacManPixelX and ghostPixelY == pacManPixelY:\n # gameOver = True\n \n #Win\n if foodTotal == 0:\n gameOver = True\n win = True\n \n #Tick the clock\n clock.tick(FRAMERATE)\n\n if win:\n pygame.draw.rect(dis, YELLOW, [0, 0, BOARDPIXELWIDTH, BOARDPIXELHEIGHT])\n message(("You Win!"), RED, BOARDPIXELWIDTH / 2, BOARDPIXELHEIGHT / 2, 15, CENTRE_MID)\n message(("This message will dissapear in 5 seconds"), RED, (BOARDPIXELWIDTH / 2), (BOARDPIXELHEIGHT / 2 + PIXEL), 10, CENTRE_TOP)\n pygame.display.update()\n time.sleep(5)\n else:\n pygame.draw.rect(dis, RED, [0, 0, BOARDPIXELWIDTH, BOARDPIXELHEIGHT])\n message(("You Lose!"), YELLOW, BOARDPIXELWIDTH / 2, BOARDPIXELHEIGHT / 2, 15, CENTRE_MID)\n message(("This message will dissapear in 5 seconds"), YELLOW, (BOARDPIXELWIDTH / 2), (BOARDPIXELHEIGHT / 2 + PIXEL), 10, CENTRE_TOP)\n pygame.display.update()\n time.sleep(5)\n \n pygame.quit()\n quit()\n\n\nif __name__ == "__main__":\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T11:42:40.670",
"Id": "511019",
"Score": "1",
"body": "Your fourth point is buggy, you actually want `return \"=\" not in board[newBoardY][newBoardX]`, at least that's what the original if-statement does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T11:47:06.870",
"Id": "511021",
"Score": "0",
"body": "*even if `in` doesn't return `True` or `False`*: Do membership test using `in` not return `True / False`? `>>> (\"h\" in \"hello\") is True` returns `True` for me (Python 3.9.1)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T12:07:00.630",
"Id": "511027",
"Score": "1",
"body": "@riskypenguin Thanks! I've edited to fix the `in` rather `not in`. No `__contains__` is always converted to a bool. However I'm intending to use the specific to talk about the generic - like if you have `if a: return True else: return False` -> `return a`. `a` isn't always guaranteed to be `True`. Can you double check my latest edits have fixed both problems?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T12:14:12.920",
"Id": "511028",
"Score": "0",
"body": "Problem solved and confusion cleared up! =)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T20:52:54.277",
"Id": "511083",
"Score": "0",
"body": "Thankyou very much for your comments @Peilonrayz. Totally agree about a Board class - I fall over Pixels vs Board position all the time. I am struggling to understand the new Ghosts.move function though. I understand that the separate Directions and Score that I had are not good (as they are not linked), but in your code you do something very different that I don't understand. Do you create a Tuple of the two values? Are you missing a definition of directions (to use in \"for direction in directions\")? Why does the for x in x go at the bottom pf the for loop? Thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T00:54:23.963",
"Id": "511093",
"Score": "0",
"body": "@KevinW \"Do you create a Tuple of the two values?\" Yes you're right here. I've merged both `directions` and `score` into a list of tuples. \"Why does the for x in x go at the bottom pf the for loop?\" I have used a [list comprehension](https://www.w3schools.com/python/python_lists_comprehension.asp) (similar to the dictionary comprehension from earlier in the answer) to build the list, the syntax is for the `for` to be at the end. \"Are you missing a definition of directions?\" You are correct, thank you edited."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T00:54:36.250",
"Id": "511094",
"Score": "0",
"body": "You've been correct in everything so far, so I think you're very close to understanding! I changed the code to build a list of tuples of the form (score, direction)[]. I then sort the list. Tuples are sorted by the first value then the second value so the lowest score is first. Then I iterate through the sorted data just like you did. The algorithm is almost exactly the same as yours. I've just gone about things in a more concise way."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T10:57:24.080",
"Id": "259155",
"ParentId": "259135",
"Score": "4"
}
},
{
"body": "<p>it's a nice thing to teach your kid programming langage!</p>\n<p>I have several advises, ideas :</p>\n<p>1: why use gif while those aren't animated, you could as well use png for those color styles.</p>\n<p>2: second for your level layout, you can just store 1 value for wall and let decide the graphic render which part of your wall to draw (based on neighbooring cells), could even be used later if you decide to modifiy level structure ingame.</p>\n<p>3: even if your game is grid based, you could add smooth movement by translation (bot gosths and pacman)</p>\n<p>4: in the v10 i tested, noting happen when i got it by ghost</p>\n<p>5: for more oop, you can create a Level classe which load your level and when you win 1 (i couldn't) load the next one.</p>\n<p>6: you can also probably tweak framerate so you gain more granularity, allowing to change direction in mid course (not sure if you'll get what i mean)</p>\n<p>7: adding menu, GUI, pause...</p>\n<p>I didn't played the original pacman, but tried <a href=\"http://www.jeux.org/jeu/pacman-2.html\" rel=\"nofollow noreferrer\">http://www.jeux.org/jeu/pacman-2.html</a>, you could see some thing you can improve</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T11:06:13.150",
"Id": "259157",
"ParentId": "259135",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-05T22:06:07.707",
"Id": "259135",
"Score": "9",
"Tags": [
"python",
"object-oriented",
"pygame",
"breadth-first-search"
],
"Title": "Python PacMan with son"
}
|
259135
|
<p>I'm writing the C++ program that involves a twist on Rock, Paper, Scissors. How the added Lizard and Spock affect the game is very simple and you could look it up if you want, but its not needed as I'm 99% sure my issue lies with the formatting of my if-else statements.</p>
<p>In every iteration, no matter what configuration the computer or the user chooses, the outcome is always the same - i.e. <em>"You win! :)"</em>. Even in the cases where the user should have tied, or the user should have lost. If you are experienced, you will probably very easily see where I am messing up, please take a look. I apologize for the confusing curly braces but inputting my code was being very finnicky so I had to add random indents to make it format.</p>
<pre><code>#include <iostream>
int main(){
srand(time(NULL));
int computer = rand() % 5 + 1;
int user = 0;
std::cout << "=============================================\n";
std::cout << "Rock Paper Scissors Spock Lizard!\n";
std::cout << "=============================================\n";
std::cout << "1) Rock\n";
std::cout << "2) Paper\n";
std::cout << "3) Scissors\n";
std::cout << "4) Lizard\n";
std::cout << "5) Spock\n";
std::cout << "\n";
std::cout << "Shoot!\n";
std::cin >> user;
std::cout << "Computer chose: " << computer << "\n";
if(user == 1){
if(computer == 3 || 4){
std::cout << "You win! :)\n";
}
else if(computer == 1){
std::cout << "You tied! :/\n";
}
else{
std::cout << "Computer wins! :(\n";
}
}
else if(user == 2){
if(computer == 1 || 5){
std::cout << "You win! :)\n";
}
else if(computer == 2){
std::cout << "You tied! :/\n";
}
else{
std::cout << "Computer wins! :(\n";
}
}
else if(user == 3){
if(computer == 2 || 4){
std::cout << "You win! :)\n";
}
else if(computer == 3){
std::cout << "You tied! :/\n";
}
else{
std::cout << "Computer wins! :(\n";
}
}
else if(user == 4){
if(computer == 2 || 5){
std::cout << "You win! :)\n";
}
else if(computer == 4){
std::cout << "You tied! :/\n";
}
else{
std::cout << "Computer wins! :(\n";
}
}
else{
if(computer == 1 || 3){
std::cout << "You win! :)\n";
}
else if(computer == 5){
std::cout << "You tied! :/\n";
}
else{
std::cout << "Computer wins! :(\n";
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T11:58:49.943",
"Id": "511023",
"Score": "2",
"body": "Welcome to the Code Review Community where we review code that is working as expected and provide suggestions on how to improve that code. Questions about code that is not working as expected are off-topic for code review. Please read [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask) to understand more about the code review site. This help page does contain a link to where you can get help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T15:52:51.687",
"Id": "511056",
"Score": "0",
"body": "See https://codereview.stackexchange.com/questions/213842/rock-paper-scissors-engine"
}
] |
[
{
"body": "<h1>Spacing</h1>\n<p>Before anything, I would recommend fixing your spacing and tabbing. Four spaces for each level of nesting is recommended. It makes your code <em>a lot</em> more readable.</p>\n<h1>Bug</h1>\n<p>There is a pretty obvious bug in your code I noticed on my first pass. It's how you're checking the computers number versus the users number. For instance, take a look at this line:</p>\n<pre><code>if (user == 0 || 1)\n</code></pre>\n<p>To a novice, it looks like <code>if user == 0 OR user == 1</code>, but that is not happening here. Instead, this is only checking if user is equal to 0, OR if 1 is true. And 1 is always true. This can result in some unexpected behavior. Take a look:</p>\n<pre><code>if (user == 0 || 1) { \n std::cout << "Greetings!" << std::endl; \n} else {\n std::cout << "Hello!" << std::endl;\n}\n</code></pre>\n<p>Now, if I only enter <code>0</code>, I will get the expected output of just "Greetings!". However, if I enter literally any other number, I will instead only get "Greetings!", instead of getting "Hello!".</p>\n<h1>Repetition</h1>\n<p>You have <em>tons</em> of repeated code. You can simplify this by first checking for if the computers input is the same as the users at the start of the program. Then you won't have to keep checking on the goat <code>if/else</code> chunk.</p>\n<pre><code>if (computer == user) {\n std::cout << "You tied! :/" << std::endl;\n return 0;\n}\n</code></pre>\n<p>Then, you can just assume the user loses at the start.</p>\n<pre><code>std::string message = "Computer wins! :(";\n</code></pre>\n<p>Now, you only have to check for win conditions, and if any are met, you change the message variable.</p>\n<pre><code>if (\n (user == 1 && (computer == 3 || computer == 4)) ||\n (user == 2 && (computer == 1 || computer == 5)) ||\n (user == 3 && (computer == 2 || computer == 4)) ||\n (user == 4 && (computer == 2 || computer == 5)) ||\n (user == 5 && (computer == 1 || computer == 3))\n) message = "You win! :)";\n</code></pre>\n<p>Then, you just output the message variable.</p>\n<pre><code>std::cout << message << std::endl;\n</code></pre>\n<h1>End</h1>\n<p>All in all, with these changes made your code now looks like this:</p>\n<pre><code>#include <iostream>\n\nint main() {\n\n srand(time(NULL));\n int computer = rand() % 5 + 1;\n int user = 0;\n\n std::cout << "=============================================\\n";\n std::cout << "Rock Paper Scissors Spock Lizard!\\n";\n std::cout << "=============================================\\n";\n std::cout << "1) Rock\\n";\n std::cout << "2) Paper\\n";\n std::cout << "3) Scissors\\n";\n std::cout << "4) Lizard\\n";\n std::cout << "5) Spock\\n";\n std::cout << "\\n";\n std::cout << "Shoot!\\n";\n\n std::cin >> user;\n std::cout << "Computer chose: " << computer << "\\n";\n\n if (computer == user) {\n std::cout << "You tied! :/" << std::endl;\n return 0;\n }\n\n std::string message = "Computer wins! :(";\n\n if (\n (user == 1 && (computer == 3 || computer == 4)) ||\n (user == 2 && (computer == 1 || computer == 5)) ||\n (user == 3 && (computer == 2 || computer == 4)) ||\n (user == 4 && (computer == 2 || computer == 5)) ||\n (user == 5 && (computer == 1 || computer == 3))\n ) message = "You win! :)";\n\n std::cout << message << std::endl;\n\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T15:30:24.043",
"Id": "511053",
"Score": "0",
"body": "Please note, questions involving code that's not working as intended, are off-topic on this site. If OP edits their post to address the problem and make their post on-topic, they may make your answer moot. [It is advised not to answer such questions](https://codereview.meta.stackexchange.com/a/6389/120114). Protip: There are tons of on-topic questions to answer; you'll make more reputation faster if you review code in questions that will get higher view counts for being on-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T16:51:00.983",
"Id": "511066",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ Yeah I skimmed through the question and missed that they said it didn't work, my mistake."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T04:38:59.380",
"Id": "259137",
"ParentId": "259136",
"Score": "1"
}
},
{
"body": "<h2>Simple mistakes</h2>\n<p><em>Firstly</em>, your code does not have proper spacing, and it makes the code unreadable.</p>\n<p><em>Secondly</em>, there is a lot of repeating. When you must check a lot of conditions, consider using a <code>switch</code> or automate it in any way.</p>\n<p><em>Thirdly</em>, there is a bug in your <code>if</code> statement:</p>\n<pre><code>if (computer == 2 || 5)\n</code></pre>\n<p>Here the <code>if</code> operator will return <code>true</code> every time since <code>5</code> is not 0. You should rewrite it this way:</p>\n<pre><code>if (computer == 2 || computer == 5)\n</code></pre>\n<hr />\n<h2>Advanced advice</h2>\n<p>I found these rules in <a href=\"https://codereview.stackexchange.com/q/36435/205644\">another thread</a>:\n<a href=\"https://i.stack.imgur.com/M03UV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/M03UV.png\" alt=\"Rules explained\" /></a>\n<em>Sorry for my bad drawing.</em></p>\n<p>What I recommend is to create an algorithm to find a winner. Looking at the "circle" above, you lose if your opponent has something in two steps ahead of you or one step behind.\nFirstly, it is better to create an <code>enum</code> for storing these choices.</p>\n<pre><code>enum Choice: int\n{ \n ROCK = 0,\n PAPER,\n SCISSORS,\n LIZARD,\n SPOCK,\n ITEMS_COUNT\n};\n</code></pre>\n<p>Here I specified the <code>enum</code> type explicitly because I am using that number later in math with integers. The last element here contains exactly the number of choices as long as we do not change the values of previous items.</p>\n<p>The next step is to find a winner using that rule mentioned above. We can find losing conditions in this simple way:</p>\n<pre><code>int lose1 = ( user + 2 ) % Choice::ITEMS_COUNT,\n lose2 = ( user - 1 ) % Choice::ITEMS_COUNT;\n</code></pre>\n<p>By calculating a modulus, we can keep our numbers from going out of bounds. Then we just need to compare these losing conditions with the computer's choice.</p>\n<hr />\n<p>Another recommendation is about your menu output. String concatenation and <code>cout</code> pipe calls can hit your performance sometimes. In this specific situation, it is better to store the full menu table in Read-Only Memory and then just print it with <code>cout</code>. You will probably want to print it in a game loop, so it is better to move this code to a function. You can also make it <code>inline</code> as the function is quite small.</p>\n<pre><code>inline void printMenu()\n{\n static const std::string menu =\n "=============================================\\n"\n "Rock Paper Scissors Spock Lizard!\\n"\n "=============================================\\n"\n "1) Rock\\n"\n "2) Paper\\n"\n "3) Scissors\\n"\n "4) Lizard\\n"\n "5) Spock\\n"\n "\\n"\n "Shoot!\\n";\n std::cout << menu;\n}\n</code></pre>\n<hr />\n<p>Last but not least, you should check the input because it can crash your app. Consider using <code>while</code> loop with a <code>cin.fail()</code> and bounds check. You can write something like this:</p>\n<pre><code>int user = -1;\nprintMenu();\nstd::cin >> user;\nwhile(std::cin.fail() || user < 0 || user > 5)\n{\n std::cout<<"Error!\\n";\n std::cin.clear();\n printMenu();\n std::cin>>user;\n}\n</code></pre>\n<p><code>cin.clear()</code> is important here as it resets the fail state.</p>\n<hr />\n<h2>Code</h2>\n<p>Here is my code for this problem:</p>\n<pre><code>#include <iostream>\n#include <string>\n\nenum Choice: int\n{ \n ROCK = 0,\n PAPER,\n SCISSORS,\n LIZARD,\n SPOCK,\n ITEMS_COUNT\n};\n\nint userWon(const int&, const int&);\n\ninline void printMenu();\n\nint getInput();\n\nint main()\n{\n srand(time(NULL));\n int user = getInput();\n int computer = rand() % 5 + 1;\n std::cout << "Computer chose: " << computer << "\\n";\n int result = userWon(user, computer);\n if( result == 1)\n std::cout << "You win!";\n else if ( result == -1 )\n std::cout << "Computer wins!";\n else\n std::cout << "Tie!";\n \n return 0;\n}\n\ninline void printMenu()\n{\n static const std::string menu =\n "=============================================\\n"\n "Rock Paper Scissors Spock Lizard!\\n"\n "=============================================\\n"\n "1) Rock\\n"\n "2) Paper\\n"\n "3) Scissors\\n"\n "4) Lizard\\n"\n "5) Spock\\n"\n "\\n"\n "Shoot!\\n";\n std::cout << menu;\n}\n\nint getInput()\n{\n int user = -1;\n printMenu();\n std::cin >> user;\n while(std::cin.fail() || user < 0 || user > 5)\n {\n std::cout<<"Error!\\n";\n std::cin.clear();\n printMenu();\n std::cin>>user;\n }\n return user;\n}\n\nint userWon(const int& user, const int& computer)\n{\n int res = 0;\n if( user != computer )\n {\n int lose1 = ( user + 2 ) % Choice::ITEMS_COUNT,\n lose2 = ( user - 1 ) % Choice::ITEMS_COUNT;\n if( computer == lose1 || computer == lose2 )\n res = -1;\n else\n res = 1;\n }\n return res;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T16:52:05.033",
"Id": "511067",
"Score": "0",
"body": "Please note, questions involving code that's not working as intended, are off-topic on this site. If OP edits their post to address the problem and make their post on-topic, they may make your answer moot. [It is advised not to answer such questions](https://codereview.meta.stackexchange.com/a/6389/120114). Protip: There are tons of on-topic questions to answer; you'll make more reputation faster if you review code in questions that will get higher view counts for being on-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T01:17:39.927",
"Id": "511226",
"Score": "0",
"body": "Lizard -> Paper arrow missing. Each node should have two out and two in."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T15:56:10.793",
"Id": "259170",
"ParentId": "259136",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T03:26:58.493",
"Id": "259136",
"Score": "0",
"Tags": [
"c++",
"rock-paper-scissors"
],
"Title": "Rock-Paper-Scissors-Lizard-Spock C++ Pogram"
}
|
259136
|
<p>While writing simple text rendering I found a lack of utf-8 decoders. Most decoders I found required allocating enough space for decoded string. In worse case that would mean that the decoded string would be four times as large as the original string.</p>
<p>I just needed to iterate over characters in a decoded format so I would be able to render them on the screen, so I wrote a simple function that would allow me to do that:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <cstdint>
// unsigned integer types
typedef uint64_t U64;
typedef uint32_t U32;
typedef uint16_t U16;
typedef uint8_t U8;
// signed integer types
typedef int64_t I64;
typedef int32_t I32;
typedef int16_t I16;
typedef int8_t I8;
U32 NextUTF8Char(const char* str, U32& idx)
{
// https://en.wikipedia.org/wiki/UTF-8
U8 c1 = (U8) str[idx];
++idx;
U32 utf8c;
if (((c1 >> 6) & 0b11) == 0b11)
{
// at least 2 bytes
U8 c2 = (U8) str[idx];
++idx;
if ((c1 >> 5) & 1)
{
// at least 3 bytes
U8 c3 = (U8) str[idx];
++idx;
if ((c1 >> 4) & 1)
{
// 4 bytes
U8 c4 = (U8) str[idx];
++idx;
utf8c = ((c4 & 0b00000111) << 18) | ((c3 & 0b00111111) << 12) |
((c2 & 0b00111111) << 6) | (c1 & 0b00111111);
} else
{
utf8c = ((c3 & 0b00001111) << 12) | ((c2 & 0b00111111) << 6) |
(c1 & 0b00111111);
}
} else
{
utf8c = ((c1 & 0b00011111) << 6) | (c2 & 0b00111111);
}
} else
{
utf8c = c1 & 0b01111111;
}
return utf8c;
}
</code></pre>
<p>Usage:</p>
<pre class="lang-cpp prettyprint-override"><code>const char* text = u8"ta suhi škafec pušča";
U32 idx = 0;
U32 c;
while ((c = NextUTF8Char(text, idx)) != 0)
{
// c is our utf-8 character in unsigned int format
}
</code></pre>
<p><strong>I'm currently mostly concerned about the following :</strong></p>
<ul>
<li><strong>Readability:</strong> The intent of every piece of code is clear to the reader.</li>
<li><strong>Correctness:</strong> Everything is working as it should (I think it's clear what should happen).</li>
<li><strong>Performance:</strong> Can anything be done to improve the performance of this code?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T11:33:30.667",
"Id": "511017",
"Score": "0",
"body": "Looks like you're missing `#include <cstdint>` and a bunch of `using`s for those typedefs - would you care to include them in the code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T12:01:32.450",
"Id": "511024",
"Score": "0",
"body": "@TobySpeight Included the missing header, thank you. Those types are already declared with typedef specifier on top of the function, so I do not know what do you mean by that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T13:16:04.050",
"Id": "511042",
"Score": "0",
"body": "I meant the `using`s that bring `std::uint64_t` and friends into the global namespace."
}
] |
[
{
"body": "<blockquote>\n<pre><code>// unsigned integer types\ntypedef uint64_t U64;\ntypedef uint32_t U32;\ntypedef uint16_t U16;\ntypedef uint8_t U8;\n\n// signed integer types\ntypedef int64_t I64;\ntypedef int32_t I32;\ntypedef int16_t I16;\ntypedef int8_t I8;\n</code></pre>\n</blockquote>\n<p>This has instantly made the code harder to read (as well as being incorrect, since <code><cstdint></code> declares those names in the <code>std</code> namespace). I'm not sure why we declare so many types, when we use just two of them anyway.</p>\n<blockquote>\n<pre><code>U32 NextUTF8Char(const char* str, U32& idx)\n</code></pre>\n</blockquote>\n<p>Why not return a standard <code>std::wchar_t</code>? Or perhaps a <code>char32_t</code>? Similarly, <code>str</code> ought to be a <code>const char8_t*</code> (so that the example code compiles).</p>\n<p>I'd use a <code>std::size_t</code> for the index (or more likely get rid of <code>idx</code> altogether, and pass a reference to pointer instead).</p>\n<p>The whole thing seems like a reinventing a lot of work that's already done for you:</p>\n<pre><code>#include <cwchar>\n\nchar32_t NextUTF8Char(const char8_t*& str)\n{\n static const int max_utf8_len = 5;\n auto s = reinterpret_cast<const char*>(str);\n wchar_t c;\n std::mbstate_t state;\n auto len = std::mbrtowc(&c, s, max_utf8_len, &state);\n if (len > max_utf8_len) { return 0; }\n str += len;\n return c;\n}\n</code></pre>\n<pre><code>#include <iostream>\nint main()\n{\n std::locale::global(std::locale{"en_US.utf8"});\n const auto* text = u8"ta suhi škafec pušča";\n char32_t c;\n std::size_t i = 0;\n while ((c = NextUTF8Char(text)) != 0) {\n std::cout << '[' << i++ << "] = " << (std::uint_fast32_t)c << '\\n';\n // c is our utf-8 character in unsigned int format\n }\n}\n</code></pre>\n<p>I think that <code>std::codecvt<char32_t, char8_t, std::mbstate_t></code> could easily do much the same:</p>\n<pre><code>#include <locale>\n\nchar32_t NextUTF8Char(const char8_t*& str)\n{\n if (!*str) {\n return 0;\n }\n auto &cvt = std::use_facet<std::codecvt<char32_t, char8_t, std::mbstate_t>>(std::locale());\n std::mbstate_t state;\n\n char32_t c;\n char32_t* p = &c+1;\n auto result = cvt.in(state, str, str+6, str, &c, p, p);\n switch (result) {\n case std::codecvt_base::ok: return c;\n case std::codecvt_base::partial: return c;\n case std::codecvt_base::error: return 0;\n case std::codecvt_base::noconv: return 0;\n }\n return c;\n}\n</code></pre>\n<p>Either is better than writing your own UTF-8 decoder.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T13:14:45.040",
"Id": "259165",
"ParentId": "259140",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "259165",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T06:08:31.300",
"Id": "259140",
"Score": "2",
"Tags": [
"c++",
"utf-8"
],
"Title": "C++ UTF-8 decoder"
}
|
259140
|
<p>I've recently started learning elixir, and the following is my attempt at fetching the local IP address of the system.</p>
<p>It can definitely be improved further, but as this would be my first ever project in a functional language; I'd be open to any criticisms.</p>
<pre><code>defmodule Systemip do
def private_ipv4() do
{:ok, addrs} = :inet.getif()
filtered =
Enum.filter(
addrs,
fn address ->
ip = elem(address, 0)
is_private_ipv4(ip)
end
)
elem(hd(filtered), 0)
end
defp is_private_ipv4(ip) do
case ip do
{10, _x, _y, _z} ->
true
{192, 168, _x, _y} ->
true
{172, 16, _x, _y} ->
true
{172, 32, _x, _y} ->
true
_ ->
false
end
end
end
</code></pre>
<p>This would be part of a larger project, which is still under construction. The IPs are fetched using the erlang call to <code>:inet.getif</code>, the formatting was done by <code>mix format</code> command.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T11:42:30.717",
"Id": "515508",
"Score": "1",
"body": "Very interesting code! Definitely willing to take a crack at this, which I'll do as soon as I get a chance. I deleted an earlier question that was obvious when I read your question properly :)"
}
] |
[
{
"body": "<p>There is few problems there:</p>\n<ol>\n<li>There is no <code>:inet.getif/0</code> function listed in <a href=\"https://erlang.org/doc/man/inet.html\" rel=\"nofollow noreferrer\"><code>inet</code> module docs</a>, which mean that if such function exists, then it is non-public API and <strong>should not</strong> be called. You probably wanted to call <code>:inet.getifaddrs/0</code>.</li>\n<li><code>hd/1</code> will fail if <code>filtered</code> list is empty</li>\n<li>You traverse whole list to find only first entry.</li>\n<li>In Elixir, by convention, boolean returning functions, that aren't guard safe (so all user-defined boolean returning functions), should use <code>?</code> suffix instead of <code>is_</code> prefix.</li>\n<li>Use pattern matching instead of <code>elem/2</code> if possible.</li>\n<li>This will raise error if there will be error during fetching interfaces addresses.</li>\n<li>Your IP ranges are invalid, as whole <code>172.16.0.0/12</code> is private, which is range from <code>172.16.0.0</code> to <code>172.31.255.255</code> where you were checking only for <code>172.16.c.d</code> and <code>172.32.c.d</code> where the second group is in public space.</li>\n</ol>\n<hr />\n<p>To fix all the issues there you can write it as:</p>\n<pre><code>defmodule SystemIP do\n def private_ipv4() do\n with {:ok, addrs} <- :inet.getif() do\n Enum.find_value(addrs, fn {if_name, if_opts} ->\n case Keyword.fetch(if_opts, :addr) do\n {:ok, adr} -> if not public_ipv4?(addr), do: addr\n _ -> false\n end\n end)\n end\n end\n\n defp private_ipv4?({10, _, _, _}), do: true\n defp private_ipv4?({172, b, _, _}) when b in 16..31, do: true\n defp private_ipv4?({192, 168, _, _}), do: true\n defp private_ipv4?({_, _, _, _}), do: false\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-16T20:58:07.827",
"Id": "263122",
"ParentId": "259142",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T06:33:32.323",
"Id": "259142",
"Score": "1",
"Tags": [
"functional-programming",
"ip-address",
"elixir"
],
"Title": "Retrieving first non-private ip for local system in elixir"
}
|
259142
|
<p>I have written a (recursive) deep clone method for ES/JS-objects. It seems <a href="https://stackblitz.com/edit/js-mv1vqt?file=ObjectClone.js" rel="nofollow noreferrer">to work fine</a>, but maybe I'm missing things. Please, feel free to comment!</p>
<p><strong>Note</strong>: the method will not clone <a href="https://riptutorial.com/javascript/example/14476/cyclic-object-values" rel="nofollow noreferrer">cyclic structures</a>. If it should be somehow necessary to be able to clone such structures, maybe <a href="https://github.com/douglascrockford/JSON-js/blob/master/cycle.js" rel="nofollow noreferrer">Crockfords cycle.js</a> can be used - but it will <a href="https://stackblitz.com/edit/js-cloning-with-cyclic-structures?file=index.js" rel="nofollow noreferrer">mangle the structure</a>.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>initializeObjCloner();
const log = Logger();
// initial object
const test1 = {
foo: [1, 2 ,3],
bar: { foo: {bar: 5}, foobar: "foobar", bar2: {bar3: {foo: 42}} },
};
// clone it
const test2 = Object.clone(test1);
// change a few props to demonstrate
// test2 not being a reference to test1
test2.bar.foo.foobar = "barfoo";
test2.bar.bar2.bar3.foo = 43;
test2.foo = test2.foo.map(v => v + 10);
test2.test2Only = "not in test1";
log (`**Test1:`, test1, `\n**Test2:`, test2);
// error on cyclic structures
const c = {hello: "world"};
c.recycled = c;
log(`\n${Object.clone(c)}`);
function initializeObjCloner() {
const isImmutable = val =>
val === null ||
val === undefined ||
[String, Boolean, Number].find(V => val.constructor === V);
const isObject = obj =>
(obj.constructor !== Date &&
JSON.stringify(obj) === "{}") ||
Object.keys(obj).length;
const cloneArr = arr => arr.reduce( (acc, value) =>
[...acc, isObject(value) ? cloneObj(value) : value], []);
const isCyclic = obj => {
try {
JSON.stringify(obj);
} catch(err) {
return err.message;
}
return null;
};
// --------------------------
// The actual cloning method
// --------------------------
const cloneObj = (obj) => {
const cyclic = isCyclic(obj);
return cyclic ?
`Object.clone error: Cyclic structures can not be cloned, sorry.` :
Object.keys(obj).length === 0 ? obj :
Object.entries(obj)
.reduce( (acc, [key, value]) => ( {
...acc,
[key]:
value instanceof Array
? cloneArr(value) :
!isImmutable(value) && isObject(value)
? cloneObj(value)
: value && value.constructor
? new value.constructor(value)
: value } ), {} );
};
Object.clone = cloneObj;
}
function Logger() {
const report =
document.querySelector("#report") ||
document.body.insertAdjacentElement(
"beforeend",
Object.assign(document.createElement("pre"), { id: "report" })
);
return (...args) =>
args.forEach(
arg =>
(report.textContent +=
(arg instanceof Object ? JSON.stringify(arg, null, 2) : arg) + "\n")
);
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
font: normal 12px/15px verdana, arial, sans-serif;
margin: 2rem;
}</code></pre>
</div>
</div>
</p>
<p>if readability is an issue, <code>cloneObj</code> may also be written as:</p>
<pre><code>function cloneObj(obj) {
if (Object.keys(obj).length < 1) { return obj; }
if (obj.constructor === Date) {
return new Date(obj);
}
if (obj.constructor === Array) {
return cloneArr(obj);
}
let newObj = {};
for ( let [key, value] of Object.entries(obj) ) {
if (!isImmutable(value) && isObject(value)) {
newObj[key] = cloneObj(value);
}
if (!newObj[key] && value && value.constructor) {
newObj[key] = new value.constructor(value);
}
if (!newObj[key]) {
newObj[key] = value;
}
}
return newObj;
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T12:18:57.947",
"Id": "511254",
"Score": "0",
"body": "You are missing several small functions, making this code not work without them. This is grounds to get this question closed on CodeReview. Also, this code cannot handle cyclic structures, which are sadly more common than you would think."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T12:33:06.907",
"Id": "511258",
"Score": "0",
"body": "Did you have a look at [this working example](https://stackblitz.com/edit/js-mv1vqt?file=index.js)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T12:45:05.573",
"Id": "511262",
"Score": "0",
"body": "Yes, it throws an error on a cyclical object. `JSON.stringify` falls over."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T13:13:49.313",
"Id": "511266",
"Score": "0",
"body": "Ok, so it's [not suitable for cyclic structures](https://stackblitz.com/edit/js-no-cloning-with-cyclic-structures?file=index.js), thnx for pointing that out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T13:15:09.350",
"Id": "511267",
"Score": "0",
"body": "Yes, can you also fix this question and add `isImmutable`, `cloneArr` etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T07:03:05.900",
"Id": "511351",
"Score": "0",
"body": "I don't really like longer snippets in questions/answers, but hey, it's done"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-20T04:09:38.280",
"Id": "514976",
"Score": "0",
"body": "Deep cloning is always a difficult task that can never be done perfectly. What might work in one use case will cause issues in another. Some things to consider: If an object is frozen/sealed, do you want to copy that over? If a property is not enumerable, should that copy over? What about getters and setters? functions? symbols? Objects with prototypes? There's no right way to handle all of these scenarios."
}
] |
[
{
"body": "<p>I spent a ton of time on this;</p>\n<ul>\n<li>The choice to replicate <code>Date</code> but not the other <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects\" rel=\"nofollow noreferrer\">50+ built-ins</a> is interesting</li>\n<li>I would write <code>isObject</code> as <code>const isObject = x => (typeof x === 'object' && x !== null)</code></li>\n<li>A question to ask yourself, what about functions, do you want to clone those as well?</li>\n<li><code> if (Object.keys(obj).length < 1) { return obj; }</code> is interesting, this means you will allow for modifications in the original object to impact the new object</li>\n<li>The poor man's deep clone for non-cyclic structures is <code>JSON.parse(JSON.stringify(o))</code></li>\n<li>After the construction here: <code>newObj[key] = new value.constructor(value);</code> I would still copy over the properties as well</li>\n<li>Still mulling over a counter example..</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T15:04:58.293",
"Id": "259413",
"ParentId": "259145",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T08:18:00.637",
"Id": "259145",
"Score": "1",
"Tags": [
"javascript",
"ecmascript-6"
],
"Title": "A (deep) cloning method for ES-Objects"
}
|
259145
|
<p>I have created this basic use case of <code>.sort()</code> for my own reference. I am asking for a review to see if there are bad practices present or areas that could be optimised.</p>
<ul>
<li>Is my use of modifying the array correct? Do I need to place the newly sorted list into a new array?</li>
<li>Using <code>.map()</code> I found it was parsing it as a string. Is <code>insertAdjacentHTML()</code> the right method to use here?</li>
</ul>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const listArea = document.getElementById('listArea');
const btnAsc = document.getElementById('asc');
const btnDes = document.getElementById('des');
// The Original Array
let architects = [
"Lloyd Wright",
"Hadid",
"Mies van der Rohe",
"Le Corbusier",
"Foster",
"Gaudi",
"Piano",
"Gropius",
"Niemeyer",
"Aalto",
"Saarinen",
]
// Empty Array to Store Sorted Array
let sortedList = [];
// Click Events for the sort buttons
btnAsc.addEventListener('click', () => sortAsc(architects));
btnDes.addEventListener('click', () => sortDes(architects));
// Sort the array in ascending order
function sortAsc(arr) {
// Clear the sortedList array
sortedList.length = 0;
// Convert each item in the architects array to lower case
for(const element of arr) {
// Push these lowercase elements into the sortedList array
sortedList.push(element.toLowerCase());
}
sortedList.sort();
populateList(sortedList);
}
function sortDes(arr) {
sortedList.length = 0;
for(const element of arr) {
sortedList.push(element.toLowerCase());
}
sortedList.sort().reverse();
populateList(sortedList);
}
function populateList(arr) {
// Empty out the listArea of all content
while(listArea.firstChild) {
listArea.removeChild(listArea.lastChild);
}
// Map each item in the supplied array to an li, and remove comma at end of each
let listArchitects = arr.map(item => `<li>${item}</li>`).join('');
listArea.insertAdjacentHTML('beforeend', listArchitects);
}
window.addEventListener('onload', populateList(architects));</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#listArea {
text-transform: capitalize;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="list">
<div class="buttons">
<button id="asc">Sort Ascending</button>
<button id="des">Sort Descending</button>
</div>
<ul id="listArea">
</ul>
</div></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>Some of the things I'd point out in your code for improvements:</p>\n<ol>\n<li>Arrays can be a const since you will not modify the array itself but just push new elements to the array.</li>\n<li>In your functions <code>sortAsc, sortDesc</code>, you are iterating through <code>arr</code> just to make it lowercase and iterating through the array again in <code>sortedList.sort()</code>. In such scenarios, think about how you can reduce number of iterations.</li>\n<li><code>sort()</code> does in-place sorting, so no need to create a new array.</li>\n<li>In function <code>populateList</code> by running <code>arr.map</code> you are creating another new array which I don't think is necessary.</li>\n</ol>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const listArea = document.getElementById('listArea');\nconst btnAsc = document.getElementById('asc');\nconst btnDes = document.getElementById('des');\n\nconst architects = [\n \"Lloyd Wright\",\n \"Hadid\",\n \"Mies van der Rohe\",\n \"Le Corbusier\",\n \"Foster\",\n \"Gaudi\",\n \"Piano\",\n \"Gropius\",\n \"Niemeyer\",\n \"Aalto\",\n \"Saarinen\",\n];\n\nfunction sortAsc() {\n architects.sort();\n populateList();\n}\n\nfunction sortDes() {\n architects.sort().reverse();\n populateList();\n}\n\nfunction populateList() {\n listArea.innerHTML = '';\n architects.forEach( (a) => {\n const list = document.createElement('li');\n list.innerText = a;\n listArea.appendChild(list);\n });\n}\n\nbtnAsc.addEventListener('click', sortAsc);\nbtnDes.addEventListener('click', sortDes);\n\nwindow.addEventListener('onload', populateList());</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"list\">\n <div class=\"buttons\">\n <button id=\"asc\">Sort Ascending</button>\n <button id=\"des\">Sort Descending</button>\n </div>\n <ul id=\"listArea\">\n \n </ul>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T13:04:56.173",
"Id": "511265",
"Score": "1",
"body": "Nice, welcome to CR!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T00:02:22.340",
"Id": "259185",
"ParentId": "259146",
"Score": "2"
}
},
{
"body": "<p>Before going into more detail, I noticed the following:</p>\n<ul>\n<li><p>The convention for naming classes is to use <code>kebab-case</code>. Instead of <code>listArea</code> I would name it <code>list-area</code></p>\n</li>\n<li><p>Always use <code>const</code> instead of <code>let</code> unless you need to <em>re-assign</em> the variable. Your array is not getting reassigned</p>\n</li>\n<li><p>When adding the event to the window you are actually <em>executing</em> the function instead of adding an event:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>window.addEventListener('onload', populateList(architects)); // <- executes the function\n</code></pre>\n<p>Also, the event is named <code>load</code> not <code>onload</code>. The reason why your code works is because the function is exectuted regardless of the event name being incorrect. So you are not actually assigning any event. It's a bug that happens to work.</p>\n<p>To fix this, you need to pass a function to the <code>load</code> event:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>window.addEventListener('load', () => populateList(architects));\n</code></pre>\n</li>\n</ul>\n<hr />\n<p>Now, the approach of using <code>insertAdjacentHTML</code> is ok for a few items with simple markup, but as the list grows I would consider sorting the existing elements in the DOM instead of removing them and re-creating the HTML from scratch:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>const ascButton = document.getElementById('asc');\nconst desButton = document.getElementById('des');\nconst listArea = document.getElementById('list-area');\n\nconst architects = [\n "Lloyd Wright",\n "Hadid",\n "Mies van der Rohe",\n "Le Corbusier",\n "Foster",\n "Gaudi",\n "Piano",\n "Gropius",\n "Niemeyer",\n "Aalto",\n "Saarinen",\n];\n\n// Create elements using the DOM instead of HTML strings\nconst architectElems = architects.map(architect => {\n const item = document.createElement('li');\n item.textContent = architect;\n return item;\n});\n\nfunction sort(order = 'asc') {\n const sorted = architectElems.sort((a, b) => {\n if (order === 'asc') {\n return a.textContent.localeCompare(b.textContent);\n }\n return b.textContent.localeCompare(a.textContent);\n });\n // We can append the same elements to the container\n // to reorder them without having to remove them from the DOM\n // and recreate the HTML\n listArea.append(...sorted);\n}\n\nascButton.addEventListener('click', () => sort('asc'));\ndesButton.addEventListener('click', () => sort('des'));\n\nwindow.addEventListener('load', () => {\n // Add elements to list for the first time\n listArea.append(...architectElems);\n});\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T19:04:19.690",
"Id": "259214",
"ParentId": "259146",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "259185",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T08:22:16.880",
"Id": "259146",
"Score": "2",
"Tags": [
"javascript",
"sorting"
],
"Title": "Sorting alphabetically ascending and descending using .sort()"
}
|
259146
|
<p>I've created a little GUI where the text entered in the text-fields is stored in a property of the currently selected button. If a different button is clicked, the contents stored for that button are inserted into the text-fields.</p>
<p>For storing the information I'm currently using a class where each text-field's contents represent a separate attribute:</p>
<pre><code>from PyQt5.QtWidgets import *
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
v_layout = QVBoxLayout()
cent_widget = QWidget()
cent_widget.setLayout(v_layout)
self.setCentralWidget(cent_widget)
# Buttons
h_layout = QHBoxLayout()
v_layout.addLayout(h_layout)
self.btn_group = QButtonGroup()
self.btn_group.setExclusive(True)
btn_1 = QPushButton('Button 1')
btn_2 = QPushButton('Button 2')
btn_3 = QPushButton('Button 3')
for w in [btn_1, btn_2, btn_3]:
w.setProperty('data', Storage())
w.setCheckable(True)
w.clicked.connect(self.set_data)
self.btn_group.addButton(w)
h_layout.addWidget(w)
btn_1.setChecked(True)
# Text Fields
self.tf_1 = QLineEdit()
self.tf_2 = QSpinBox()
self.tf_3 = QLineEdit()
for w in [self.tf_1, self.tf_2, self.tf_3]:
w.editingFinished.connect(lambda x=w: self.update_storage(x))
v_layout.addWidget(w)
def update_storage(self, widget):
active_storage = self.btn_group.checkedButton().property('data')
if widget == self.tf_1:
active_storage.field1 = self.tf_1.text()
elif widget == self.tf_2:
active_storage.field2 = self.tf_2.value()
elif widget == self.tf_3:
active_storage.field3 = self.tf_3.text()
def set_data(self):
btn = self.btn_group.checkedButton()
storage = btn.property('data')
self.tf_1.setText(storage.field1)
self.tf_2.setValue(storage.field2)
self.tf_3.setText(storage.field3)
class Storage:
def __init__(self):
self.field1 = ''
self.field2 = -1
self.field3 = ''
if __name__ == '__main__':
app = QApplication([])
window = MainWindow()
window.show()
app.exec()
</code></pre>
<p><a href="https://i.stack.imgur.com/C56hL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C56hL.png" alt="GUI with 3 buttons at the top and 2 QLineEdits and a QSpinbox below" /></a></p>
<p>I have a feeling like I'm working <em>against</em> Qt here or I'm at least not using its full potential, because I think Qt <em>could</em> include some tools to make this more efficient and I just did not find them.</p>
|
[] |
[
{
"body": "<p>Your implementation of <code>Storage</code> lends itself nicely to using a <code>dataclass</code>.</p>\n<pre><code>from dataclasses import dataclass\n\n@dataclass\nclass Storage:\n field1: str = ""\n field2: int = -1\n field3: str = ""\n</code></pre>\n<p>This makes your class definition really concise and readable and provides improved scalability and convenient implementations of built-in functions if you ever need them.</p>\n<p>You should also consider giving fields and widgets more meaningful names (maybe even changing button text to match their functionality) to improve readability and usability.</p>\n<p>Further material on dataclasses:</p>\n<ul>\n<li><a href=\"https://realpython.com/python-data-classes/\" rel=\"nofollow noreferrer\">Data Classes in Python 3.7+ (Guide)</a> on RealPython</li>\n<li><a href=\"https://www.youtube.com/watch?v=vBH6GRJ1REM\" rel=\"nofollow noreferrer\">Python dataclasses</a> on Youtube by mCoding</li>\n</ul>\n<hr />\n<p>The way you create the three buttons does not scale well, changing this part will have to be done by hand and is therefore error-prone. I'm talking about this code snippet:</p>\n<pre><code>btn_1 = QPushButton('Button 1')\nbtn_2 = QPushButton('Button 2')\nbtn_3 = QPushButton('Button 3')\n\nfor w in [btn_1, btn_2, btn_3]:\n w.setProperty('data', Storage())\n w.setCheckable(True)\n w.clicked.connect(self.set_data)\n self.btn_group.addButton(w)\n h_layout.addWidget(w)\n</code></pre>\n<p>I find the following approach to be a lot cleaner, while producing the same result. You basically only need to change the <code>stop</code> argument in <code>range(start, stop)</code> if you want to change the amount of buttons:</p>\n<pre><code>for i in range(start=1, stop=4):\n btn = QPushButton(f"Button {i}")\n btn.setProperty('data', Storage())\n btn.setCheckable(True)\n btn.clicked.connect(self.set_data)\n\n self.btn_group.addButton(btn)\n h_layout.addWidget(btn)\n\n setattr(self, f"btn_{i}", btn)\n</code></pre>\n<hr />\n<p>I'm sure there's a better way to set up <code>update_storage</code> and <code>set_data</code> without hardcoding the widgets, but I didn't think of a satisfactory approach yet.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T12:41:11.577",
"Id": "259162",
"ParentId": "259149",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "259162",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T09:55:57.540",
"Id": "259149",
"Score": "3",
"Tags": [
"python",
"pyqt"
],
"Title": "Storing the contents of text fields and inserting the stored values on button-click"
}
|
259149
|
<p>I come from an OOP background, and have recently delved into C and embedded systems.</p>
<p>As an exercise I wanted to see if I could wrap some OOP concepts into a macro header.</p>
<p>It works as I intended, is fairly simple to use and get a grip on if you know OOP terminology / concepts.</p>
<p>Would love any feedback to see if I'm doing something stupid.</p>
<p>At the moment it's only heap allocation. I will update in future for stack based struct objects, but it only requires the coder write 1 additional function to implement.</p>
<p>It's >C/GNU99 and requires P99 for the variadic macros (I've yet to copy those little bits over).</p>
<h1>eOOPc.h</h1>
<pre><code>#ifndef OOP_MAIN_H
#define OOP_MAIN_H
#ifndef _STDLIB_H
#include <stdlib.h>
#endif
#ifndef P99_IF_H_
#include "p99/p99_if.h"
#endif
/**
* grab an interface definition by calling it's macro.
* @param i Interface name
*/
#define eIMPLEMENTS(i) eINTERFACE_##i()
/**
* add a parent class struct to gain access to it's public methods
* @param p Struct name
* @param n Property name
*/
#define eEXTENDS(p,n) struct p n
/**
* helper macro to denote that this parent is upcastable (this macro must be first element of containing
* struct for this to be true)
* @param p Struct name
* @param n Property name
*/
#define eDIR_EXTENDS(p,n) eEXTENDS(p, n)
/**
* Instantiate an object 'o*' of type 'c' by using function 'c_instatiate()'
* @param <classtype_t> c
* @param var o Object variable name
* @param ... any further arguments
*/
#define eNEW_INS(c,o, ...) P99_IF_EMPTY(__VA_ARGS__) (c##_instantiate(o)) (c##_instantiate(o, __VA_ARGS__))
/**
* Call allocation method and imediately fire instatiation function for heap object
* @param <classtype_t> c
* @param var o Object variable name
* @param ... any further arguments
*/
#define eNEW(c,o, ...) struct c*o = (struct c *)malloc(sizeof(struct c)); eNEW_INS(c,o, __VA_ARGS__)
/**
* public property DECLARATION
* @param t Type
* @param p Property name
*/
#define ePROP_DEC(t, p) t p
/**
* public property DEFINITION
* @param p Property name
* @param v Value
*/
#define ePROP_DEF(p, v) self->p = v
/**
* private property PUBLIC function-pointer DECLARATIONS for public struct
* @param t Type
* @param p Property name
* @param m get/set/getset
*/
#define ePRIV_PROP_DEC_get(t,p) t (*get_##p)(void * eOBJ)
#define ePRIV_PROP_DEC_set(t,p) void (*set_##p)(void * eOBJ, t v)
#define ePRIV_PROP_DEC_getset(t,p) ePRIV_PROP_DEC_get(t,p); ePRIV_PROP_DEC_set(t,p)
#define ePRIV_PROP_DEC_PUB(t, p, m) ePRIV_PROP_DEC_##m(t,p)
/**
* private property PRIVATE function-pointer DECLARATIONS for private struct
* @param t Type
* @param p Property name
* @param m get/set/getset
*/
#define ePRIV_PROP_DEC_PRIV(t, p, m) ePROP_DEC(t,p); ePRIV_PROP_DEC_##m(t,p)
/**
* private property PUBLIC function DECLARATIONS
* @param c Type
* @param t Function return type
* @param p Property name
* @param m get/set/getset
*/
#define ePRIV_PROP_FUNC_DEC_get(c, t, p) t c##_get_##p(void * eOBJ);
#define ePRIV_PROP_FUNC_DEC_set(c, t, p) void c##_set_##p(void * eOBJ, t v );
#define ePRIV_PROP_FUNC_DEC_getset(c, t, p) ePRIV_PROP_FUNC_DEC_get(c, t, p) ePRIV_PROP_FUNC_DEC_set(c, t, p)
#define ePRIV_PROP_FUNC_DEC(c, t, p, m) ePRIV_PROP_FUNC_DEC_##m(c, t, p)
/**
* private property function ALLOCATIONS for object function pointers in instantiate
* @param c Type
* @param p Property name
* @param v Property value
* @param m get/set/getset
*/
#define ePRIV_PROP_DEF_get(c, p) self->get_##p = &c##_get_##p
#define ePRIV_PROP_DEF_set(c, p) self->set_##p = &c##_set_##p
#define ePRIV_PROP_DEF_getset(c, p) ePRIV_PROP_DEF_get(c, p); ePRIV_PROP_DEF_set(c, p)
#define ePRIV_PROP_DEF(c, p, v, m) self->p = v; ePRIV_PROP_DEF_##m(c, p)
/**
* private property PUBLIC get/set function DEFINITIONS
* @param c Type
* @param t Function return type
* @param p Property name
* @param m get/set/getset
*/
#define ePRIV_PROP_FUNC_DEF_get(c, t, p) t c##_get_##p(void * eOBJ){ eSELF(c); return self->p; }
#define ePRIV_PROP_FUNC_DEF_set(c, t, p) void c##_set_##p(void * eOBJ, t v ){ eSELF(c); self->p = v; }
#define ePRIV_PROP_FUNC_DEF_getset(c, t, p) ePRIV_PROP_FUNC_DEF_get(c, t, p) ePRIV_PROP_FUNC_DEF_set(c, t, p)
#define ePRIV_PROP_FUNC_DEF(c, t, p, m) ePRIV_PROP_FUNC_DEF_##m(c, t, p)
/**
* Cast "self" back into the class type
* @param <classtype_t> c
*/
#define eSELF(c) c * self = (c*)eOBJ
/**
* Get the value of a protected variable 'p' within object 'o'
* Prints to stderr if property is private
* @param var o Object
* @param var p Object property
*/
#define eGET(o, p) o->get_##p(o)
/**
* Set the value of a protected variable 'x' within object 'o'
* Prints to stderr if property is private
* @param var o Object
* @param var p Object property
* @param var v The new value
*/
#define eSET(o, p, v) o->set_##p(o, v)
/**
* Method call wrapper that passes object as first argument for use of eSELF()
* @param var o Object
* @param var m The method
* @param ... Other args
*/
#define eMETH(o, m, ...) P99_IF_EMPTY(__VA_ARGS__) ((*o->m)(o)) ((*o->m)(o, __VA_ARGS__))
/**
* Free memory on heap for object
* @param var o Object variable name
*/
#define eDESTROY(o) free(o); o = ((void*)0)
/**
* Free memory on heap for object by calling defined function to allow further actions
* such as destroying string / struct members within object
* @param <classtype_t> c
* @param var o Object variable name
*/
#define eDESTROY_M(c, o) c##_heap_destruct(o); o = ((void*)0)
#endif //OOP_MAIN_H
</code></pre>
<p>With some example files:</p>
<h1>class.h Public header file</h1>
<pre><code>#ifndef OOP_CLASS_H
#define OOP_CLASS_H
//interface definitions can contain expressly written variables,
//other e@ macros etc as needed.
#define eINTERFACE_interface() \
int poop; \
int shmoop
struct parent{
int pprop1;
int pprop2;
};
//PUBLIC DEFINITION AND METHODS
struct Class_t{
//parent for upcasts
eDIR_EXTENDS(parent, parent);
//interface
eIMPLEMENTS(interface);
//define a public property
ePROP_DEC(int, prop1);
//define function pointers for get, set or both for private property
ePRIV_PROP_DEC_PUB(int, prop2, get);
//public method function pointer
int (*method1)(void * eOBJ);
};
//public class function declarations
//get and/or set PUBLIC function declarations
ePRIV_PROP_FUNC_DEC(Class_t, int, prop2, get)
//other defined public methods declarations
int Class_t_method1(void * eOBJ);
//always need an instantiate. Void pointer so function can cast back to struct type pointer
//this means we don't get conflicting type errors
void Class_t_instantiate(void * eOBJ);
#endif //OOP_CLASS_H
</code></pre>
<h1>class.c Private Source & Definitions</h1>
<pre><code>//need OOP macros
#include "eOOPc.h"
//include public declaration
#include "class.h"
//PRIVATE DECLARAION
typedef struct{
eDIR_EXTENDS(parent, parent);
//interface
eIMPLEMENTS(interface);
//matching public prop declaration
ePROP_DEC(int, prop1);
//private property declaration + PUBLIC function pointer declarations
ePRIV_PROP_DEC_PRIV(int, prop2, get);
//public method function pointer
int (*method1)(void * eOBJ);
//private method function pointer
int (*method2)(void * eOBJ);
} Class_t;
//PRIVATE METHODS
int Class_t_method2(void * eOBJ){
eSELF(Class_t);
return self->prop1;
}
//PUBLIC METHOD DEFINITIONS TO OVERRIDE DECLARATIONS
//private property PUBLIC get/set method definitions
ePRIV_PROP_FUNC_DEF(Class_t, int, prop2, get)
//other public method definitions
int Class_t_method1(void * eOBJ){
eSELF(Class_t);
return 4;
}
void Class_t_instantiate(void * eOBJ){
eSELF(Class_t);
ePROP_DEF(prop1, 3);
ePRIV_PROP_DEF(Class_t, prop2, 4, get);
self->method1 = &Class_t_method1;
self->method2 = &Class_t_method2;
}
</code></pre>
<h1>main.c Example</h1>
<p>Note it only has access to the class.h file - the further methods and properties defined in class.c are private and inaccessible.</p>
<pre><code>#include "eOOPc.h"
#include "class.h"
int main (void){
//instantiate object (i.e. new)
eNEW(Class_t, object);
int i = eMETH(object, method1);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T11:51:31.443",
"Id": "511022",
"Score": "2",
"body": "Have you tested this beyond what you have in the main.c example? At the moment this looks very hypothetical which would make it off-topic for Code Review. Possible problems I see in the implementation: Don't include `stdio.h`. All members of a struct are public so a private member variable is impossible to implement. The code is hiding things which would make it difficult for a new programmer to maintain."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T12:55:35.447",
"Id": "511035",
"Score": "2",
"body": "What problem does this code solve? It's an exercise, we get that, but even exercises tend to target a fake problem to solve."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T13:44:41.787",
"Id": "511043",
"Score": "0",
"body": "@pacmaninbw Actually no - private members are entirely possible - if the calling source file only includes the public class header, it does not have access to the additional members in the struct as defined in the class source file. They have to be in a certain order for the memory mapping to work (as I understand it). This was taken from the book: https://www.amazon.co.uk/Extreme-Taking-Concurrency-advanced-capabilities-ebook/dp/B07XYX6FQL"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T13:48:34.080",
"Id": "511045",
"Score": "0",
"body": "@ Mast - It enables me to write program using OOP using an easy to read script. One example I have that I'm writing with it now - https://github.com/erbarratt/4c04oop - is a cpu emulator, where each \"device\" in the system acts as an object. Therefor, it's easy to write multiple RAM blocks for example, or add other devices to a bus object etc. This makes more sense to me in this specific case. Or games."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T16:06:51.313",
"Id": "511058",
"Score": "2",
"body": "One person's \"easy-to-read script\" is another person's \"oh god no, now I need to read the library to understand what this is doing\""
}
] |
[
{
"body": "<p>The appeal of C is that it's simple, standard, and performant. Whereas your approach might (?) not impact performance all that much, it soundly destroys the first two concepts.</p>\n<p>For reference, you're of course not the first to have tried <a href=\"https://en.wikipedia.org/wiki/GObject\" rel=\"nofollow noreferrer\">crow-barring OOP into C</a>. I somewhat recoil at the idea of dense, complex macro magic at all, much less to implement OOP. My approach - that I think you could benefit from, although your question has fallen short of demonstrating any concrete application - is</p>\n<ul>\n<li>Yes, use OOP; it is a useful way to think about code</li>\n<li>No, do not attempt to be clever and abstract it, using macros or otherwise</li>\n</ul>\n<p>OOP is entirely possible using "stock C", via</p>\n<ul>\n<li>Context structures to encapsulate member variables</li>\n<li>Free functions accepting context structure pointers to represent object methods</li>\n<li>Opaque structure definition in header files to enforce separation of concerns</li>\n</ul>\n<p>This pattern is very common in C, very legible, and will produce clean code. Handing code written in this way to someone who has a fundamental understanding of C will succeed in them being able to follow and contribute to the code. Handing code written in the way presented in the question to the same person will not produce the same effect. The pattern presented in the question also has more surface area for bugs.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T16:00:43.123",
"Id": "259171",
"ParentId": "259151",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "259171",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T10:04:37.857",
"Id": "259151",
"Score": "2",
"Tags": [
"object-oriented",
"c"
],
"Title": "C Macro based OOP"
}
|
259151
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.