Improved stack implementation using a linked list

Don't repeat code:

template<class T>
Stack<T>& Stack<T>::operator=(const Stack& s) {
    for (auto t = s.first; t != nullptr; t = t->next) {
        push(t->item);
    }
    return *this;
}

This is not really an assignment but an append. I think most people would not expect that. You should probably release the original list before copying over the source into this object.

An easier way to implement the assignment operator is to use the copy and swap idiom.

// Notice the pass by value creates an implicit copy.
// You then just swap the content of the current object
// with the parameter s.
// When the parameter goes out of scope it deletes the old
// data stack.
Stack<T>& Stack<T>::operator=(Stack s) {
    std::swap(first,   s.first);
    std::swap(n,       s.n);
    return *this;
}

You move assignment leaks:

template<class T>
Stack<T>& Stack<T>::operator=(Stack&& s) {
    first = s.first;
    n = s.n;
    s.first = nullptr;
    s.n = 0;
    return *this;
}

The current value of first is leaked. The best way to do this is to swap the content of this object with the incomming object.

template<class T>
Stack<T>& Stack<T>::operator=(Stack&& s) {
    std::swap(first,   s.first);
    std::swap(n,       s.n);
    return *this;
}

Let the other object do the clean up when it goes out of scope.

You implemented a push by copy:

void push(const T&);

Why not have a push by move:

void push(T&&);

I would make the Node structure a private implementation detail of stack. That way other people can not rely on that detail when they use your code.

template<class T>
class Stack {
     struct Node {....}
};

Your peak creates a copy of the object.

   T Stack<T>::peek() const {
// ^ Return by value creates a copy.

I would return by reference. I would also rovide two version. One to return by const reference (for const version of the stack), and a normal return by reference so you can look at the top value and potentially alter it without removing it from the stack:

T const& Stack<T>::peek() const { ....
T&       Stack<T>::peek()       { ....

Your destructor checks empty() then calls pop() which checks empty(). This is a bit redundant. You could have a private version of pop that does not check empty.

~Stack() {
    while (!empty()) {
        noneCheckedPop();
    }

void Stack<T>::pop() {
    if (empty()) {
        throw std::out_of_range("underflow");
    }
    noneCheckedPop();
}

private:
void Stack<T>::noneCheckedPop() {
    Node<T>* oldfirst = first;
    first = first->next;
    delete oldfirst;
    --n;
}


Getting rid of goto without duplication in Go

You could use defer along with named return values.

E.g.:

listener, err := net.Listen("unixpacket", path)
if err != nil {
    return nil, err
}
defer func() {
    if err != nil {
        listener.Close()
    }
}()

// rest of function that just does "return nil, err" as needed

A runnable playground version of this:
https://play.golang.org/p/lKnGyzbp_3

Note, normally you'll see things like this in Go:

f, err := os.Open("somefile")
if err != nil {
    return err
}
defer f.Close()

That is easier and works for the common case where the thing (a file here) is being used just inside the function itself and needs to always be closed before returning to the caller. In the question however, the listening socket needs to be closed only if there is a error after it was opened. If there is no error it needs to be left open and returned to the caller. That's why the defer'ed function checks err (which it can do as long as it's a named returned value; you can even change named return values in a defer'ed function).


Your code actually doesn't work, because you use replaceAll. This means that your pattern will allow you to match ../../ and replace it with , resulting in a lost double-back. You can fix this two ways:

You could change the replaceAll to replaceFirst
You could change the pattern to exclude ../../ ([^/.]+/\\.\\./? works)

You can then simplify your loop since the ONE_DOT case will be matched properly so you don't need to split out a check for minimization.

Thus I would suggest:

private static final Pattern ONE_DOT = Pattern.compile("/\\./");
private static final Pattern TWO_DOTS = Pattern.compile("([^/.]+/\\.\\.)+/?");

public static String minimize(final String in) {
    String tmp = in;

    tmp = ONE_DOT.matcher(tmp).replaceAll("/");

    while (TWO_DOTS.matcher(tmp).matches())
        tmp = TWO_DOTS.matcher(tmp).replaceAll("");

    return tmp;
}

At least as a first-pass improvement. There may be a way to do it without the loop using some kind of counting regular expression, but off the top of my head I'm not sure.


A method that generates a Comparator using lambda expression

This seems as efficient as it gets, to me.

In terms of elegance, Joshua Bloch (in Effective Java) recommends to stop using bit fields, use EnumSet instead.

The first step is to change your bit fields to an enum:

public enum Mode {
    COMPARE_REVERSED,
    COMPARE_CASE_INSENSITIVE,
    COMPARE_SPACE_INSENSITIVE
}

Next, change your method to take a Set instead of an int:

public static Comparator<String> getComparator(Set<Mode> flags) {
    return (s1, s2) -> {
        if (flags.contains(Mode.COMPARE_REVERSED)) {
            String temp = s1;
            s1 = s2;
            s2 = temp;
        }
        if (flags.contains(Mode.COMPARE_SPACE_INSENSITIVE)) {
            s1 = s1.replaceAll("\\s", "");
            s2 = s2.replaceAll("\\s", "");
        }
        if (flags.contains(Mode.COMPARE_CASE_INSENSITIVE)) {
            return s1.compareToIgnoreCase(s2);
        }
        return s1.compareTo(s2);
    };
}

You could call this method with any Set, but it will be best to call with an EnumSet, for example:

getComparator(EnumSet.of(Mode.COMPARE_CASE_INSENSITIVE, Mode.COMPARE_SPACE_INSENSITIVE));

Why is this better?

You don't need to worry about setting the bit fields correctly to be mutually exclusive
You don't need the has method anymore, now you can use simple Set.contains
You don't need the ... | ... bit operations anymore, EnumSet.of(...) is simple and clean

In short (quoted from the book):

  No more bit twiddling, EnumSet does all the hard work for you.

I would also add a convenience method for the case of no flags:

public static Comparator<String> getComparator() {
    return getComparator(Collections.<Mode>emptySet());
}

And of course, a bunch of unit tests, for example:

@Test
public void testNormalComparator() {
    Comparator<String> comparator = ComparatorGenerator.getComparator();
    assertNotEquals(0, comparator.compare("hello", "Hello"));
    assertEquals(0, comparator.compare("hello", "hello"));
}

@Test
public void testCaseInsensitiveComparator() {
    Comparator<String> comparator = ComparatorGenerator.getComparator(EnumSet.of(ComparatorGenerator.Mode.COMPARE_CASE_INSENSITIVE));
    assertNotEquals(0, comparator.compare("hello", "xHello"));
    assertEquals(0, comparator.compare("hello", "Hello"));
    assertEquals(0, comparator.compare("hello", "hello"));
}

@Test
public void testReversedComparator() {
    Comparator<String> comparator1 = ComparatorGenerator.getComparator();
    assertEquals(-1, comparator1.compare("hello1", "hello2"));
    Comparator<String> comparator2 = ComparatorGenerator.getComparator(EnumSet.of(ComparatorGenerator.Mode.COMPARE_REVERSED));
    assertEquals(1, comparator2.compare("hello1", "hello2"));
}

@Test
public void testCaseAndSpaceInsensitiveComparator() {
    Comparator<String> comparator = ComparatorGenerator.getComparator(EnumSet.of(ComparatorGenerator.Mode.COMPARE_CASE_INSENSITIVE, ComparatorGenerator.Mode.COMPARE_SPACE_INSENSITIVE));
    assertNotEquals(0, comparator.compare("hello there", "x hello there"));
    assertEquals(0, comparator.compare("HELLO there", "h e llo there"));
}


Generally speaking, you should keep your markup and your PHP logic separate.

And the intermediate variables don't really have a purpose, just use the values from the array.

You've got two opening form tags and no closing form tags.

Your first condition (i there are records in the table) does not close the thead or the create a tbody.

Your delete button is no button at all, it's an input wrapped in an anchor tag (). That's why it's not working as expected. Either remove the anchor and give the input a type attribute of "button", or remove the input and put some text in there instead.

Use a prepared statement. It's not cool to throw variables into your queries all willy-nilly. You will anger the code gods.

Here's a quick re-write (assumes you're using PDO - If you're using MySQLi, see the docs to convert the prepared statement to MySQLi)

I'm just going to go ahead and post this since i spend three or four minutes on it, but after looking at this code, there is no way this was working as you had it. This site is for reviewing working code, not fixing broken code. If your code doesn't work you need to ask on StackOverflow in the future.

<?php

    // Do all the PHP stuff before you start ouputting
    $noLists = "
You have no lists. Why dont you create one?
";

    if ($db->connect_error) {
        die("Connection failed: " . $db->connect_error);
    }

    $sql = "SELECT DISTINCT lists.id, lists.listdescription, lists.createdon, lists.createdby, lists.sharedlist FROM lists INNER JOIN users ON users.fname = ? AND users.fname = lists.createdby";
    $result = $db->prepare($sql);
    $result->execute(array($displayname));
    $output = array();
    if ($result->rowCount() > 0) {
        // output data of each row

        $output[] = "
";
        $output[] = "
";

        while($row = $result->fetch(PDO::FETCH_ASSOC)) {

            $output[] = "
";
            $output[] = "{$row["listdescription"]}	";
            $output[] = "{$row["createdon"]}	";
            $output[] = "{$createdBy}	";
            $output[] = "";
            $output[] = "<form action='account.php' method='post'>";
            $output[] = "<input class=\"btn btn-success\" type=\"submit\" name=\"\" value=\"Edit\">";
            $output[] = "</form>";
            $output[] = "Delete	";
        }

        $output[] = "
";
        $output[] = "
";

    } else {
        $output[] = "
";
        $output[] = "
";
        $output[] = "
";
        $output[] = "
";
        $output[] = "
 $noLists
";
    }
    $db->close();

    // Turn the output array back into a string
    $output = implode('', $output);

?>

                    Description

                    Date Created

                    Created By

                    Edit - Delete

        <?php echo $output; ?>

Edit... you're not closing your table row in the loop either. I'm not gonna bother updating the code snippet.


Performance for creating millions of database entries

Prepare once. That's the very idea behind a prepared statement. It should give you like 5% gain.

Wrap all batches in a single transaction. It could also help you in several ways. In case your engine is myisam, consider dropping all indexes before inserts and adding them back after.

Reduce the record size. 'parent' is 5 megabytes written on the disk for 1 mil records 1 megabyte if your value is 1.


Django template filter - sort by multiple keys

keys is already visible in compare, so you can even do the splitting
outside of compare and still use it inside of it.  And the duplication
of code for the else branch should be eliminated, by only doing the
comparison once (cmp should work I guess) and then negating the
result if necessary.  This means processing all the keys before
running the sorting into a useful data-structure.  You want to compare
in the order they are specified, so a list of tuples will do fine.

Then, by using cmp instead of normal comparisons three lines per
branch are eliminated.  Also, which is maybe more important, you don't
have to worry about the comparisons and what -1/1, which personally
takes me way to long all the time while reading comparison functions
like this.

The two branches are also unnecessary, since you can just negate the
result depending on the sort key (factor in the following code).

So I arrive at this, untested of course.

@register.filter
def sort_by_keys(value, keys):
    transformed = []
    for key in keys.split(','):
        factor = 1
        if key.startswith('-'):
            key = key.replace('-', '')
            factor = -1
        transformed.append((key, factor))

    def compare(item1, item2):
        for (key, factor) in transformed:
            result = factor * cmp(getattr(item1, key), getattr(item2, key))
            if result != 0:
                return result
        return 0

    return sorted(list(value), cmp=compare)

It looks like you can't use sort directly on the input value?
Otherwise I'd suggest to do that as well.

Apart from completely compiling the sort function beforehand (using
lambdas), this seems the most compact I think.


C++ Read/write (shared) spinlock implementation

I'm fairly certain that you have a one-character typo-bug here:

    while (!write_now.exchange(true, std::memory_order_acquire)){

This should read

    while (write_now.exchange(true, std::memory_order_acquire)) {

— that is, "Put true into the write_now bit; and if it was already true, then wait. Only proceed if the old value was actually false."

What you have with the ! is "Put true into the write_now bit; and if it was already true, then continue (oops!). Otherwise, yield once, and then continue anyway because now it'll be true for sure." ["For sure" here being a relative term. Obviously it won't be true if the old writer managed to finish and release the lock in the time we spent yielding.]

Performance nitpick: I've heard that it is useful to put one cache-line's worth of padding in between your two atomic variables, to eliminate false sharing. Of course if you do that then your shared_spinlock class gets much bigger.

But if you don't do that, then all this fiddling with memory orders is useless, because your few seq_cst accesses to the shared cache line in lock and lock_shared will effectively seq_cst all your accesses in those functions.

As usual, I advise staying away from memory orders unless you're sure that you know what you're doing. That said, I think you're using them correctly here.

            if (write_now){

You might consider making this

            if (write_now.load(std::memory_order_seq_cst)) {

and likewise every other time you load an atomic variable without a memory order. As I said, normally I advise not to use memory orders other than seq_cst at all; but since you are using them, maybe it would be a good idea to mark every single load and store, consistently?

I also suspect that that particular load could be memory_order_acquire maybe, but seriously don't quote me on that. I have no idea.

    // unique_lock have priority

This comment should say lock have priority, or simply writers have priority.

C++ nitpick: Consider marking all of these member functions noexcept.

Functionality suggestion: Consider providing a way for a writer to atomically demote itself to a reader, without releasing the lock (i.e., without allowing some other writer B to sneak in and change the value that A just wrote). This should be possible, I think; and it's definitely not possible for anyone but you, the author of the mutex, to provide this functionality.

I think it's as simple as this:

void unlock_and_lock_shared() {
    readers_count.fetch_add(1, std::memory_order_acquire);
    write_now.store(false, std::memory_order_release);
}

The naming convention comes from Boost.


Looks like a good bottom-up merge. A bit heavy on the memory at the first glance though.
if (a[0] < b[0]) loses stability. The main advantage of the merge sort is is that it retains the order of elements which compare equal (for sorting integers it is irrelevant, but think of sorting structures). Your code merges b[0] first. Consider a[0] <= b[0] instead.
Handling the unlikely conditions such as a.size() == 0 and b.size() == 0 better be done outside of the loop. Consider instead

while (a.size() > 0 && b.size() > 0) {
    do_actual_merge();
}
ret.insert(ret.end(), a.begin(), a.end());  // No-op if a.size() == 0
ret.insert(ret.end(), b.begin(), b.end());  // No-op if b.size() == 0
return ret;

I am not sure that chunks.size() % 2 == 1 is the best way to express your intentions. I'd go for i < chunks.size(), even though it lifts a declaration of i out of the loop.


Enigma questions from "ANSI Common Lisp"

I'm also huge fan of recursion, and the best book on recursion I know is "Little Schemer". I highly recommend it! It looks "slow" and repetitive, but that's how you learn (at least this approach was great for me).

In my opinion it's hard to read code when you find pattern you didn't knew before. It takes a lot of time and is highly frustrating to figure out what's happening inside, and often you still don't fully get why it was written this way (and if it's even correct). So the best advise I can give is - learn how to write code, reading will come naturally. You know what you are looking for.

In recursion, most important part is - when to stop and what to do (return) in that case.

Your mystery function stops when:

y is nil (it returns nil) - first if
or
first element of y is eql to x (it returns 0) - second if

It will also return logical "something and something" - the last line - but we will talk about it later.

From the above, we know that:

y should be some list, since it's user with car and cdr functions, and tested for empty list (null y)
x should be some atom, simple one, since it's compared to every element of y list with eql, which works fine with things like symbols and numbers, but not more complicated things like strings or lists

OK, we know what to pass to mystery functions (roughly). Now - what this last part with let and and do? Apparently let is used here to store result of recursive call only to speed thing up. It could also be written as:

(and (mystery x (cdr y))
     (1+ (mystery x (cdr y))))

We know what mystery function can return: nil or 0. Last thing to do is to analyse what and can return:

first argument if it evaluates to false
second argument otherwise.

As you can see there is no magical trick to help reading code. When you use some pattern (recursion in this case) long enough, you learn what are the important things to look for, and what are just common construction parts.

When you have some idea how function works, you can call it with some parameters just to verify your understanding, but I don't think you should begin with that. Pan and paper method can be a lot better, especially when you start with simple cases, like what will happen if I pass an empty list and empty list? Or zero and one element list? Calling function you don't know and observing results is called "black box testing" and is more hackerish activity. You have all the information you need - code of the function - so it's easier to read and reason about its behaviour.

When you stuck and don't know how to proceed, try to reformat the code. Rewrite the parts you understand. It might look silly and like wasting your time, but I find it helpfull.

If something is not clear, I'm happy to expand my answer, just post a comment :)


computeSwappedNodes (root, new PrevNode(null), list);

Unneeded space between function name and parentheses with arguments. You do this multiple times.

/**
 * Returns the 2 nodes which if swapped results in binary search tree.
 */
public int[] getSwappedNode( ) {

No, you return the items stored within. Not the nodes. You don't fulfill the assignment as stated. Additionally, you return multiple nodes, so name the method getSwappedNodes. Lastly, no need for a space in an empty set of parentheses.


Style
You've done a great job of style from a technical point of view.

You're following PEP-8 guidelines.
The functions have type-hints
The functions have docstrings

Defects:

The docstrings aren't very useful:
>>> help(get_factors)

Help on function get_factors in module __main__:

get_factors(number: int) -> List[List[int]]
    Returns all the factors of a number.

This doesn't explain what the factors are going to be.  A list of list of integers, yes, but no clue what that means, or to expect that [1, x] will be excluded.

the determine_factors method is a wall of code, with not a single comment insight describing how it is supposed to work.

is_perfect()
This is actually pretty close to perfect.  :-)
get_factors()
You are (without any indication to the caller) omitting [1, x] (should be at least mentioned in the docstring.
You are finding all factors from 2 up to (and including!) number, which means the last pair generated is [number, 1].  Why do you skip generating [1, number] by starting at 2, yet continue up to number + 1?
How does factors[:len(factors) // 2] remove duplicates, when it is using truncating integer division, and you can have an odd number of factor pairs?
Why bother generating the factor pairs if you are just going to discard half of them anyway?  Just iterate from 2 up to (and including) isqrt(number).  Way more efficient.
determine_factors()
I have no idea how this function works.  simplified += ... and remainder += ...?  Multiplication of factors is not additive, so this doesn't make sense.
Moreover, the function doesn't work.  -54 and -96 return nothing:
>>> solve(-54)
>>> solve(-96)

A better algorithm
Instead of computing all of the factors of number, determine the prime factorization of number.  For instance:
$$ \sqrt {96} = \sqrt { 2^5 * 3^1 } $$
Any odd power will result in that factor to the power of 1 under the square root.  After removing those, you've got primes raised to even powers, which can all be divided by two, and moved out from the square-root:
$$ \sqrt {96} = \sqrt { 2^4 } * \sqrt {2^1 * 3^1} = 2^2 * \sqrt {2^1 * 3^1} $$


The Collection is not really immutable if you can add items to it :)

You should explicitly define either abstract or simple default implementation (i.e. that doesn't enforce return data type) for current() method on Collection.

I would suggest using $this->key() within valid()

public function valid()
{
    return isset($this->items[$this->key()]);
}

This is consistent with your usage in current() in inheriting classes and consistent with iterator interface.  This also allows for override of key() in inheriting classes if there ever was such a need for this.

Consider explicitly specifying abstract constructor in Collection class (or again a simple default constructor (i.e. just setting position to O)).  You should explicitly set position to 0 in constructor in some manner.

You might consider exposing a length() function on your collection since you are providing functionality beyond basic iteration.  This would allow you to do things like perhaps return new index value to caller on add().

public function length() {
    return count($this->items[]);
}

protected function add($item)
{
    $this->items[] = $item;
    // return index of new item
    return $this->length() - 1;
}

You also should consider validating input parameter passed to get against valid method as being within range of keys.

protected function get($index)
{
    if(!$this->valid($index)) {
        throw new OutOfBoundsException(
            'Index passed to get() is invalid.'
        );
    }
    return $this->items[$index];
}


Naming of variables is perfect and you are following the python convention - and that is really good because it makes the code easier to read.
I've executed the code and I've noticed that when you insert an invalid input two things may happen

Input "1A"; Output:  "Invalid format. That spot is already taken."
Input "X"; Output: Application crash

So that's a bug that we need to address.
Biggest problems in the code are

Use of global scope (that is, putting variables outside of methods)
Code duplication

About the first one, we need to put everything inside a method. This is better because you will constraint the scope of variables, make things easier to read and the intention of each line will be clearer. Also it's always better to define all the methods at the beginning and then the code that needs to be executed (that should be in a main method, normally).
If I would do it I would create a Board class but there is no particular reason to use Object Oriented Programming here so I will try to follow your way of reasoning.
At first we are initializing the board so
def create_board():
    board = []
    for _ in range(3):
        board.append([' '] * 3)
    return board

You were not actually using the x variable in the loop so I've renamed to _, which is a convention to say that you're not actually interested in that variable. To have magic numbers, like 3 in this case, is bad because someday you may ask "Why 3?". Now it pretty obvious, but it might get more complex, an easy way to fix that is
def create_board(size=3):
    board = []
    for _ in range(size):
        board.append([' '] * size)
    return board

The behavior is the same but now everybody will know what is 3. Is quite useless to have a parametric sized board, because you can play Tic-Tac-Toe only with 3x3 boards, but I'm using that as a way to show you how to be prepared for later improvements (Connect-Four? :) ).
Now let's print the board. You're code was actually pretty good, I wanted to add a variable size board because, in your code, you're using the fact that the board is 3x3 in many hidden ways. (For example if dashes <= 1:).
def print_board(board):
    board_size = len(board)
    cols = [chr(i) for i in range(ord('A'), ord('A') + board_size)]
    print()
    print(f"    {'   '.join(cols)}")
    print()
    row_label = 1
    for row in board:
        print(row_label, ' ', ' | '.join(row))
        if row_label < board_size:
            print(' ', ' -' * (2 * board_size))
        row_label += 1
    print()

x became row_label because that what it is. I've added the print() before and after, because they are, in fact, part of the print of the board.
The split method is not useful, characters in string can be already accessed by index. So we can get rid of it and the game will work as before.
As I was saying, there a few duplications in the code, and they are in the game loop, let's try to refactor that part, starting from the user input:
def ask_value(player_name, player_symbol, board):
    board_size = len(board)
    while True:
        player_input = input(f"{player_name}, where would you like to place a {player_symbol}").lower()
        try:
            col_let = player_input[0]
            row = int(player_input[1]) - 1  # [REVIEW COMMENT] we use 0 based indexes, the user doesn't
            col = int(ord(col_let) - ord('a'))
            if (not (0 <= col < board_size)) or (not (0 <= row < board_size)):
                raise ValueError("Index out of board")
            if board[row][col] != ' ':
                print('That spot is already taken.')
                raise ValueError("Spot already taken")
            return row, col
        except (ValueError, IndexError):
            print('Invalid format.')

This method will replace the duplication of code for the input. I've added a range check to avoid going outside of the board and now the input validation bug is fixed.
Avoid to use non-zero based index; it is not the normal approach and you will get rid of all those - 1 all over the code.
The part where you check who won is a bit cumbersome and is using more developer time than cpu time (how long it took to check all the boolean conditions? :) ) also it doesn't scale with the board size (I understand that this wasn't a problem for you).
I'm not going to write how to check who won but I will suggest you a way to structure your code:
def check_winner(board, symbol):
   if check_rows(board, symbol):
       return symbol
   if check_cols(board, symbol):
       return symbol
   if check_diagonals(board, symbol):
       return symbol
   if check_tie():
       return '#'
   return None

So the main loop will become:
def main():
    board = create_board()
    print('This is Tic Tac Toe.')
    print('Player 1 will be X and Player 2 will be O.')
    players = [{"name": "Player 1", "symbol": "X"}, {"name": "Player 2", "symbol": "O"}]
    end = False
    while not end:  # [REVIEW COMMENT] this is more pythonish than "win != True"
        print_board(board)
        for player in players:
            symbol = player["symbol"]
            row, col = ask_value(player["name"], symbol, board)
            board[row][col] = symbol
            winning_symbol = check_winner(board, symbol)
            if winning_symbol == '#':
                print("It is a tie!")
                end = True
                break
            elif winning_symbol:
                print(f"{player['name']} has won!!")
                end = True
                break

if __name__ == '__main__':
    main()


Parsing nested JSON with Haskell and Aeson

You should really use an algebraic data type to implement your JSON interface. You can even automatically derive FromJSON instances with DeriveGeneric GHC extension, e.g.

{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}

import GHC.Generics
import Data.Aeson
import Data.ByteString.Lazy (ByteString)

data Query = Query { items :: [Entity] }
             deriving (Show, Generic)

instance FromJSON Query -- automatically derived instance by DeriveGeneric

data Entity = Entity { uuid :: String }
              deriving (Show)

instance FromJSON Entity where
    parseJSON = withObject "Entity" $ \v -> do
        -- as your json data is additionally nested with an entity object
        -- extract the entity object first
        obj <- v .: "entity"
        -- then extract the uuid field from the entity object
        uid <- obj .: "uuid"
        return $ Entity uid

testVal :: ByteString
testVal = "{\"items\": [{\"entity\": {\"uuid\": \"needed-value1\"}}, {\"entity\": {\"uuid\": \"needed-value2\"}}]}"

main :: IO ()
main = do
    let mayQuery = decode testVal
    case mayQuery of
        Just query -> print $ map uuid $ items query
        Nothing -> putStrLn "JSON parsing error"

I transformed your sample Value into a JSON string, to make the parsing clearer.

The FromJSON instance for Query is automatically derived, if you want to write it by hand, you can do this in analogy to the FromJSON instance of Entity.

This way of parsing your JSON data is very scalable, as you can easily add new fields to your data types, without complicating your code.


Builder pattern for Codeigniter ActiveRecord queries

Well, for a kickoff, you're concerned about your code's reusability can trump its undeniable downsides. But, if you look at one or two things more closely, your code isn't as reusable as perhaps you think it is:

// Parsing arguments
$params = (isset($args[0])) ? $args[0] : array();
$single = (isset($args[1])) ? $args[1] : false;
$count = (isset($args[2])) ? $args[2] : false;
$page = (isset($args[3])) ? $args[3] : '';
$per_page = (isset($args[4])) ? $args[4] : '';

This is just a series of hard-coded statements, with a specific goal in mind. This isn't as generic as your object, called ORMModel would have you believe.
You're also being lead astray by CI's rather confusing name ActiveRecord, which actually doesn't implement the ActiveRecord pattern.

Your code shows signs of a nasty habbit, too, in the sense that you're using magic methods and object overloading. Avoid these things as much as possible, it'll slow your app down when you're accessing/setting properties, and even more so if that requires one or more magic method calls.

There's another issue with using __call too often: it can bypass the access modifiers:

class Unsafe
{
    private function mayOnlyBeCalledInternally()
    {
        //do risky things
    }
    public function __call($method, array $args)
    {
        if (method_exists($this, $method))
        {
            return call_usr_func_array(array($this, $method), $args);
            return $this->{$method}($args);//BTW: this is WRONG
        }
    }
}
$expose = new Unsafe;
$expose->mayOnlyBeCalledInternally();//WORKS!!!!

You're, essentially, exposing all private and protected methods through this __call method. Just don't!
As you may have noticed, I'm calling the methods using call_usr_func_array. The __call method receives the arguments as an array, but that doesn't mean the called method accepts an array. It could well be that this method expects three distinct arguments, not 1 array. The way you're calling existing methods:

if (method_exists($this, $name)) {
    $this->{$name}($params);
}

Will give you grief in such cases, but I'm going off topic slightly...

Basically, you've observed the limitations of CI's ActiveRecord and set about building something a bit more powerful. Now that's not a bad idea, except for one thing: It's all been done before, and (without wanting to suggest you're a bad dev) better than you'll be able to implement it. You're just 1 person, writing your own thing, Doctrine and the like have been around for some time, and have been worked on by many people. You can't compete with them.

If, however, you're not quite ready to switch to an existing sollution, I'd split your __call method into truly defined functions. For example, the call getOrder is being translated into get and Order, where Order is the tbl/object name. Why don't you just create a method like:

public function getFrom($tbl, array $params)
{
    $this->db->from($tbl);
    foreach($params as $field => $value)
    {
        $this->where{$field}($value);
    }
    //... and so on
}

In give time, you might find yourself creating an abstract model for your tables, and passing table objects to this function:

abstract class TableObject
{
    private $name = null;
    protected $fields = array();
    abstract public function __construct($name);
    final protected function _setName($name)
    {
        if ($this->name !== null)
        {
            throw new BadMethodCallExcpetion('Can\'t change tbl name once instance is created');
        }
        $this->name = $name;
        return $this;
    }
    final public function _getName()
    {
        return $this->name;
    }
    //bulk setter
    final public function setByRow(stdClass $record)
    {//or hint for array, or Traversable, or whatever
        foreach($record as $name => $value)
        {
            if (method_exists($this, 'set'.ucfirst($name)))
            {
                $this->{'set'.ucfirst($name)}($value);
            }
        }
    }
    //get object values as array
    final public funtion toArray()
    {
        $array = array();
        foreach($this->fields as $name)
        {
            $array[$name] = $this->{'get'.ucfirst($name)}();
        }
        return array_filter($array);
    }
}
//then
class Order extends TableObject
{
    public function __construct()
    {
        //set $this->fields here, if not in definition
        $this->_setName('Order');
    }
}

In accordance with my linked answers, it goes without saying that I'd strongly suggest your declaring all properties explicitly, and implementing a getter and setter for each property, too.
Anyhow, if you've done that, you can change the getObject method to:

public function getObject(TableObject $model)
{
    $this->db->form($model->_getName());
    $asArray = $model->toArray();//treat as $params in the snippet above
}

Now this is a more generic, and OO way of working. You could also create an TblArguments object, instead of using an array to determine if there is to be a limit, group by, count set/returned... But if I were you, I'd create specifc methods for count and single and per_page, really...

But really, read through a couple of my more verbose answers on this site, and perhaps on SO, too, I've given more detailed code examples of this approach before, and expanded on certain other benefits, too. But to recap: Your code is not terrible, not at all... it didn't make my eyes water or anything. But your __call method is doing more than it should be doing: it's checking if the particular call was meant to do a specific thing.
If you know that get + someString is meant to be a query, why bother relying on __call, why not implement a generic method for just that purpouse? it'll clean up your code, it'll be more maintainable, and even more reusable.


In matrix of sub-matrices, select diagonal indices of off-diagonal submatrices

I'm sure there are other ways, but in the meantime, how about this:

my_matrix = np.tile(np.eye(submatrix_size), (n_submatrix, n_submatrix))
np.fill_diagonal(my_matrix, 0)

Then again, the concatenation of matrixes might not be particularly
efficient, so instead I'd rather compute the target indexes directly,
fill them, and possibly clear out the diagonal again (all destructive on
a previously allocated matrix):

cells = n_submatrix * submatrix_size
my_matrix = np.zeros((cells, cells))

for x in range(n_submatrix):
    for y in range(submatrix_size):
        r = range(y, n_submatrix * submatrix_size, submatrix_size)
        my_matrix[x * submatrix_size + y, r] = 1

np.fill_diagonal(my_matrix, 0)

That is still easily explained:  we step first by number of submatrixes
(because that's where the pattern repeats), then for each row we set all
indexes in that row at once, offset by the current step in the
submatrix.

Again, that seems less efficient than calculating indexes at once.  I
ended up with the following:

cells = n_submatrix * submatrix_size
my_matrix = np.zeros((cells, cells))

for y in range(submatrix_size):
    r = range(y, n_submatrix * submatrix_size, submatrix_size)
    my_matrix[np.ix_(r, r)] = 1

np.fill_diagonal(my_matrix, 0)

To be fair, the documentation for numpy.ix_ and
indexing
isn't particularly intuitive, but basically I was looking for a way to
compress the notion of "for each of these rows, select all the indexes
in that row" and then setting them all at once.  Now there is only one
loop for each row in the submatrix and I'm out of ideas.

There might be a clever formula to generate all of the indexes in one go
(by calculating them modulo some number) for all the diagonals though.

Btw. for your code I'd suggest extracting expressions as variables (like
cells above) and possibly a bit more succinct names, but that's just
me.


Python webscraping for lists of company names and details using BeautifulSoup

It seems like you are creating a kind of a crawler. To improve on performance, you can use a Session object. It will utilize the underlying TCP connection, making the script run faster.

You can also use BeautifulSoup's SoupStrainer to only parse the listing tag. This way, your crawler won't have to go through each and every line of the HTML document.

Additionally on perfomance, you can use the lxml parser which happens to be faster than html.parser.

You seem to be using the base link quite often, move it into a constant and add href tags to it as needed.

As an example, the way you are filling up your finlist can be written as such.

import requests
from bs4 import BeautifulSoup, SoupStrainer

URL = 'https://www.sccci.org.sg'
session = requests.Session()

response = session.get(URL + '/en/directory/corporate/members?ind=150')
strainer = SoupStrainer(class_='listing')
soup = BeautifulSoup(response.content, 'lxml', parse_only=strainer)
listing_links = [URL + link['href'] for link in soup.select('ol[start] a[href]')]

Note that I have used all of the above and CSS selectors resulting in reducing the amount of for loops to just one. Populating finlist takes about 2 seconds on my machine.

Staying on finlist, it's not a particularly descriptive variable name. Perhaps something like listing_links would be better?

I can't go through the rest of the crawler as I am short on time, but for file operations, use the with statement. It will ensure the file is closed, even if an error occurs.
Example usage:

foo = '1234'
with open('bar.txt', 'w') as f:
    f.write(foo)


Access resolve function outside of a JavaScript Promise

If I understand your question correctly, your question runs on these assumptions:

You want to hook up multiple listeners to a single Promise.
The promise is triggered arbitrarily, not necessarily on promise creation.
You want to use native promises.
You run on an engine that has Promises.

The second bullet point, where the operation is triggered arbitrarily, is the tricky part because native promises are read-only. You'll need to catch resolve and reject from the constructor every time.

So while your implementation is correct, you'll find yourself repeating the pattern. jQuery Deferreds are better in this case, but we don't want to lug around jQuery, or any library for that matter.

What you could do is create your own little Deferred constructor. It just wraps around the existing native Promise API, essentially just forwarding arguments. The only difference is that it's exposing resolve and reject.

function Deferred(callback){
  var instance = this;

  // Catch the resolve and reject
  this._resolver = null;
  this._rejector = null;
  this._promise = new Promise(function(resolve, reject){
    instance._resolver = resolve;
    instance._rejector = reject;
  });

  // Deferred has { resolve, reject }. But personally, I like the Promise
  // version of resolve and reject as separate args.
  if(typeof callback === 'function')
    callback.call(this, this._resolver, this._rejector);
}

Deferred.prototype.then = function(resolve, reject){
  return this._promise.then(resolve, reject);
};

// resolve, reject etc.

// For other APIs, refer to jQuery for Deferred and MDN for Promises:
// https://api.jquery.com/category/deferred-object/
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Now with Deferred out of the way, let's go back to your jQuery version and improve it. Since we created Deferred as a constructor, we can subclass from it. This means we can have Foo become a Deferred and have the luxury of the Deferred API.

// Setup Foo as a Deferred in as little as 2 lines.
function Foo(){ Deferred.apply(this, arguments); }
Foo.prototype = Object.create(Deferred.prototype);

// Your Foo API
Foo.prototype.init = function(){
  var instance = this;
  setTimeout(function(){
    instance.resolve();
  }, 2000);
};

In the end, foo will have Deferred powers, care of an extended Promise API.

var foo = new Foo();

// We can now use `then`.
foo.then(function(){
  alert('foo.ready!');
});

//
foo.init();

Now if I wrote the code properly, this should work:

function Deferred(callback) {
  var instance = this;
  this._resolver = null;
  this._rejector = null;
  this._promise = new Promise(function(resolve, reject) {
    instance._resolver = resolve;
    instance._rejector = reject;
  });
  if (typeof callback === 'function')
    callback.call(this, this._resolver, this._rejector);
}

Deferred.prototype.then = function(resolve, reject) { return this._promise.then(resolve, reject); };
Deferred.prototype.resolve = function(resolution) { this._resolver.call(null, resolution); return this; };
Deferred.prototype.reject = function(rejection) { this._rejector.call(null, rejection); return this; };

// The setup code:

function Foo() { Deferred.apply(this, arguments); }
Foo.prototype = Object.create(Deferred.prototype);

Foo.prototype.init = function() {
  var instance = this;
  setTimeout(function() {
    instance.resolve('YAY!');
  }, 2000);
};

// Phew! Now your Foo is a "native" Deferred.

var foo = new Foo();

foo.then(function(value) {
  alert('foo.ready! ' + value);
});

foo.init();


Databinding entire objects between child Vue components and the root Vue instance

General feedback

The use of the

Borrower:
 in parent:{{ form.borrower }}
  <applicant v-model="form.borrower"></applicant>

Co-borrower:
 in parent:{{ form.coborrower }}
  <applicant v-model="form.coborrower"></applicant>


I think B is the best of the three, but here's another alternative using a simple lookup:

middleware.customer = function(req, res, next){
  var methods = {POST: req.body, GET: req.query};
  req.customer = methods[req.method] || false;
  return next();
}


Underscore and general app design review

Since you asked to review only the underscore part,

Just had one remark that I would suggest to move the templates to a script tag "text/template" rather than defining them as a variable.

eg:

Compile and use the same like below,

var msg_container = _.template($('#msg_container').html());
var msg_reply = _.template($('#msg_reply').html());

Though you asked to review only the '_' part but couldn't resist asking this question, From your example snippet I see 6 potential AJAX calls based on the loops. Wouldn't there be a performance problem since it completely relies on the number of messages and replies and what if the messages and replies are more or I could be missing the overall picture :)


Using R to transform Excel files to be combined

I have not figured out all processing you need to do, so my solution will not give you the exact same data.frame, but it should be close enough for you to get by with minimal post-processing.

General consideration

You are using nested for loops to fill a data.frame. This is usually a bad idea, there are almost always better ways to go about it. If you really need to use loops, read about preallocation first (for example in this question on stackoverflow question)
Think about the structure of your data. Do you really need one row for each single individual, or is a count variable enough? (see below)
Your task can be split up into two distinct steps: Reshaping the input, and replicating the rows. A function should always do one thing and not several (though in this case I agree that it is not obvious that you are actually doing two things)

Reshaping the input

The first function restructures your data so that it is easier to deal with. We use the reshape2 package for that:

parse_chiro <- function(x){
  taxa <- names(x)[[1]]
  reshape2::melt(
    Chiro.1,
    id.vars = c("Habitat", taxa),
    variable.name = "Size",
    value.name = "count"
  )
}

res <- parse_chiro(Chiro.1)

This gives you a data.frame with all the columns you want, + a count variable that contains how often you want the row to be replicated. The syntax for reshape is a bit hard to explain and I refer you to the package documentation for that. You can achieve something similar with the newer tidyr package, but I personally prefer reshape.

Expanding the data

The next part is expanding the data.frame with the count variable.
This is where most if not all of the speed improvement to your original function comes from. I cannot think of an application where you would want your data like that, but if you still need to do it, go about it like this:

expand_chiro <- function(x){
  # Removes all rows with NA count. I am not sure if you really want that?
  x <- x[!is.na(x$count), ]
  x$rowid <- seq_len(nrow(x))
  rep_rowid <- rep(x$rowid, round(x$count))
  x[rep_rowid, ]
}

Using the vectorized function rep() and data.frame row indexing will yield a significant speed increases to your nested loops. There were also a few things wrong with your loop that could have improved the performance, but the way I propose is much cleaner, so I am not going into that.

Remarks

rbind all your parsed data.frames before you do the expanding (so that you only need to expand once)
I would recommend to stick to the tidyverse style guide for naming your functions and variables. It is currently the most popular style guide for R, and you are already using tidyverse packages (readxl, dplyr)
2M rows are no problem in R, the limit is your RAM. You can use format(object.size(x), "auto") to display the size of your object in human readable form. In theory, you can work with objects about 1/3 - 1/2 the size of your available RAM, but if you are not super careful and know what you are doing you might crash R. Your data.frame should be only a few hundred MB so no need to worry.


Converting Between Clojure Maps and Lists

Here's a few other ways you can go about it:

(defn map-vals [f a-map]
  (zipmap (keys a-map) (map f (vals a-map))))

(defn map-vals [f a-map]
  (reduce-kv #(assoc %1 %2 (f %3)) {} a-map))

or if you're set on transients/into

(defn map-vals [f a-map]
  (persistent! (reduce-kv #(assoc! %1 %2 (f %3)) (transient {}) a-map)))

This is a use case that could maybe stand to have a more elegant core tool, though. Or at least, I'm not the only one to miss it.
For what it's worth, the zipmap approach actually appears to perform best in my cursory testing and is pretty clear in its intent to change the values while keeping the keys as they were. If you're using a function literal it also means that fn doesn't have to take keys it's not going to do anything interesting with, which could make it a little clearer.


Filtering undefined elements out of an array

To be using strict null checks, you must be on "typescript": "^2.0.0". Thus, my example will be using this version of typescript with "compilerOptions":{"strictNullChecks": true}.

It does seem that the filter solution is the most elegant solution to the titular question. Sadly, it seems that the typescript static analysis is unable to track this behavior:

const source: (string|undefined)[] = ["one", "two", "three", undefined, "five"]
const filtered: string[] = source.filter(element => element !== undefined)
//  [ts]
//    Type '(string | undefined)[]' is not assignable to type 'string[]'.
//      Type 'string | undefined' is not assignable to type 'string'.
//        Type 'undefined' is not assignable to type 'string'.

This seems to be the case because of the declaration of the filter method:

/** Returns the elements of an array that meet the condition specified in a callback function. */
(method) Array<string | undefined>.filter(callbackfn: (value: string | undefined, index: number, array: (string | undefined)[]) => any, thisArg?: any): (string | undefined)[]

In this case, our own type logic beats out the compiler's. It's these cases that is the reason that Type Assertion is part of the language spec. Thus:

const source: (string|undefined)[] = ["one", "two", "three", undefined, "five"]
const filtered: string[] = source.filter(element => element !== undefined) as string[]

This transpiles exactly as you would expect -- in this case, transpiling is as simple as just removing the type information. If you need to convince the language to convert two unrelated types, you need to step through any to tell the compiler to back off: object as any as string.

Now, looking at the rest of the code:

shortFlagWithArgument and shortFlagWithoutArgument can be consts, as you do not mutate their values.

Personally, I would add an explicit final return to the flagDescriptions.map operation. This makes explicit why the undefined needs to be in the results array in the first place.

The regex patterns seem good candidates for refactoring into a reusable constant. Depending on your project ecosystem, however, it may be better just to leave them inlined.


Caching is definitely appropriate here as well. You can carry a cache through the calculations using an Erlang map.

I took your original code and made the following modifications:

Grouped the values into a tuple to make it easy to use them together as a cache key.
Changed the paths/4 function to paths/3, which takes as its arguments a list of value tuples, an accumulated sum, and a map for caching.
Made paths/3 recursively walk the list of value tuples passed to it. For each value tuple (the head of the list), it checks the cache and if the value tuple is present, it uses the cached sum, but if not found, it calculates the sum for that value tuple and caches it. When the list of value tuples is empty, the accumulated sum is returned.

Here's the revised code:

-module(pathing).
-export([paths/1]).

paths(N) ->
    {Result, _} = paths([{N, 0, 0, 0}], 0, #{}),
    Result.

paths([], Sum, C) ->
    {Sum, C};
paths([{0, 0, 0, 0}|T], Sum, C) ->
    paths(T, Sum+1, C);
paths([{0, _, _, _}|T], Sum, C) ->
    paths(T, Sum, C);
paths([{N, X, Y, Z}=Key|T], Sum, C) ->
    {NewSum,NC} = case maps:get(Key,C,undefined) of
                      undefined ->
                          {NS,NC0} = paths([{N-1, X, Y+1, Z-1},
                                            {N-1, X, Y-1, Z+1},
                                            {N-1, X+1, Y, Z-1},
                                            {N-1, X-1, Y, Z+1},
                                            {N-1, X+1, Y-1, Z},
                                            {N-1, X-1, Y+1, Z}],0,C),
                          {NS,maps:put(Key,NS,NC0)};
                      S ->
                          {S,C}
                  end,
    paths(T,Sum+NewSum,NC).

The final paths/3 clause is where all the interesting work occurs. It first calls maps:get/3 with a default value of undefined to check if the value tuple is present. If it's not, the default value of undefined is returned, and the case clause for undefined creates a new list of value tuples based on the incoming values of N, X, Y, and Z and passes it to a new paths/3 call, setting the initial sum value to 0 and passing the current cache. This call returns a 2-tuple comprising the sum for that value tuple and a new cache. The final line in this case clause inserts the sum for the value tuple into the cache.

The case clause for when maps:get/3 finds the value tuple just returns the cached sum and the current cache.

The result of the case expression is stored into {NewSum,NC}, and then paths/3 is called recursively with T, which is the tail of the value tuple list, a new sum which is Sum+NewSum, and the new cache NC.

We can run the code in a list comprehension to calculate the running times for N values from 1 to 12 using timer:tc/3 like this:

[begin pathing:paths(V), {V,timer:tc(pathing,paths,[V])} end || V <- lists:seq(1,12)].

We execute the pathing:paths/1 function twice for each value and time only the second call — this is a non-rigorous attempt to prime caches and such to get a more accurate measurement.

Some results for your original code are:

[{1,{3,0}},
 {2,{4,6}},
 {3,{16,12}},
 {4,{86,90}},
 {5,{522,360}},
 {6,{2320,2040}},
 {7,{10364,10080}},
 {8,{55940,54810}},
 {9,{339876,290640}},
 {10,{2099300,1588356}},
 {11,{12857019,8676360}},
 {12,{75383602,47977776}}]

The first value is N, the second value the execution time in microseconds, and the third value the result of the pathing:paths/1 function for that N value.

For N values greater than 2, there is roughly a 6x increase in run time at each step. For N of 12, the execution time is just over 75 seconds.

Here are the results for the revised code:

[{1,{4,0}},
 {2,{8,6}},
 {3,{43,12}},
 {4,{139,90}},
 {5,{229,360}},
 {6,{383,2040}},
 {7,{485,10080}},
 {8,{744,54810}},
 {9,{987,290640}},
 {10,{1351,1588356}},
 {11,{1549,8676360}},
 {12,{2683,47977776}}]

First, we can see that the third numbers, the function results, are identical to those for the original code. This means that either the new code is also correct, or both versions are incorrect.

As you can see the execution times are greatly reduced from the original code for all values of N greater than 4. For the smaller values, the original code is faster because it doesn't have any caching overhead. But for the larger values, each increment in N results in only a small increase in execution time. For N of 12, the run time is only 2.68ms, which is roughly 28000 times faster than the original code. With the revised code, calculating N=100 takes only 2.8 seconds:

{100,{2792880,1791977497884763591097926128926348807126038292969051375074848031878536740320}}


Base service for two different implementations

App settings

When dealing with something like ConfigurationManager, Session, some state bag, etc., it's common to want to just inject the whole thing. The problem with that is that not only do you jump through some hoops to wrap the thing so it can be injected, but also the provider-specific means of interacting with it comes along. So you tie yourself to always having a keyed dictionary of sorts to pass in. You might be better served injecting the one setting instead of putting AppSettings access in your method. I'm not sure how this is accomplished in Unity, but you can inject .FromAppSettings(...) in Castle Windsor and even more.

File System

Kind of the same thing. I understand why you are doing this, but there's a difference between really isolating code and turning procedural code inside-out by calling the same instructions through multiple methods. It will probably help to simplify things by fetching your files a layer up and passing them to your class method(s). If you're like "Yeah, but how do I know my file access works?" I would respond with, "Are you trying to test your code in isolation, or trying to make your code runnable in unit tests?" With the former approach, you may get less test coverage, but you can get extremely granular tests around what it is you're doing. The latter approach results in integration tests that require considerable setup and probably end up testing the .NET Framework (i.e. this file would always be able to be accessed unless there was a bug in the framework).

Not sure how flexible your options are with file types, but the level of granularity you probably want to pursue is being able to pass in mock files and overriding the OpenText() method to ensure your mocked content is returned from files that pass validation. But keep it simple--don't go overboard with trying to inject file objects or wrapping them in interfaces either just so you can write tests.

Inheritance

You probably don't need to have a base class and an interface for that base class. Just register the base class in your container (why not make it abstract?) and use that in your signatures. Is that interface used for anything but making a mock? Plus, a 1:1 interface to class ratio or close to it usually means "too many interfaces" or "I'm worrying too hard about breaking the rules of making code testable."

Don't worry about specifying type associations in IoC configuration

I can't think of a more appropriate place to define any rules around typing than the container. As long as the abstract class is necessary, this is fine. This is fairly common when you have multiple classes that implement the same interface (a good thing, it means you are using an interface for its intended use and not just as a slick means to mock something).

But...

The only thing that is different between your classes is a suffix string. You don't need an inheritance structure to accomplish this--just make the suffix a parameter in your constructor! Then you can associate each different type of template generator with a specific named instance, or you can use a factory method that is run when resolving generators, where each generator registration provides a different string.

Some Philosophy

Instead of trying to get all code under test, try to completely isolate logic starting from the inside and working outwards, redrawing the boundaries between objects as you go. Chances are this C# code is not in an ASP.NET MVC app that was designed for DI. If you have to move code up a layer or completely out of the DI paradigm to get rid of awkward dependencies, it's not the end of the world, especially if you can still test it in isolation.  After all, you could still make a static method in your page or form-level layer that can be tested by a test class directly accessing it. Otherwise you may end up causing yourself a lot of pain trying to split a (rather simple) process up in steps across multiple objects.

Could the same means of simplification by parameterizing the suffix also be applied to the generators for additional reduction in complexity and number of objects? I haven't seen the code, but I'm thinking probably.

In closing

Prioritize simplicity and elegance over a focus on separation of concerns.


Use Promise to wait until DOM element exists

One idea would be to put the script tags at the end of the document's body - not in the head at all. It's a common trick in itself, often used to speed up load time, because it means no time is spent parsing scripts before moving on to the page's actual content. It also means that the scripts will have everything that's "before" them in the DOM ready for use.

Alternatively: If you're unwilling to move all the scripts, but still willing to simply wait for the document to report ready, there's no need for polling. See MDN's documentation for more. You may want to check document.readyState first, since attaching an event listener too late (after the document has loaded), is pointless: The event only fires once.

But wait! It appears you're already using jQuery, in which case all you have to do is:

$(function () {
  // code to run on document ready
});

That code can resolve a promise, but usually you'd just put that in your various scripts to make sure they only run once the document's ready (e.g. $(initWidget); where initWidget is whatever function kicks something off). It's how most jQuery scripts are written.


Some improvement (DRY - Don't Repeat Yourself):

import glob
import os
import os.path                    # another import
from datetime import datetime

monitor_files = []

# Instead of your 5-time repetition then use this part:

PREFIX = "/home/skeer/Documents/Projects/Python_temp/home"
subdirs = ["chpt", "adr01", "emb01", "exp01", "iix01"]       # We will loop over these
UP = "upload"
PATTERN = "*.pgp"

for sd in subdirs:
    full_path = os.path.join(PREFIX, sd, UP)        # Inteligent joining of path's parts
    os.chdir(full_path)
    for file in glob.glob(PATTERN):
        if os.path.isfile(file):
            last_modified_date = datetime.fromtimestamp(os.path.getmtime(file))
        else:
            last_modified_date = datetime.fromtimestamp(0)
        monitor_files.append(sd + " | " + file + (" | ") + str(last_modified_date) + "\n")

print("\n".join(monitor_files))   # Your code after repetitions is OK


Elixir / Phoenix login controller, allowing multiple attempts

Personally I would do the inc and count of the attempts in one place,
You can still split it, but you actually need this every time an attempt is going to happen.

You could also replace the if with a case. You don't have to, but I think it looks nicer :)

The next thing is, remove the when password == @password_login and just use @password_login in the function definition

  def login(conn, %{"login" => %{"password" => password}}) do
    case inc_and_get_login_attempts(conn) <= 10 do
      true ->  conn |> try_to_login(password)
      _ ->     conn |> redirect(to: "/")
    end
  end

  defp inc_and_get_login_attempts(conn) do
    attempts = (conn |> get_session(:count_attempt_login)) || 0
    put_session(conn, :count_attempt_login, attempts + 1)
    attempts + 1
  end

  defp try_to_login(conn, @password_login) do
    conn
      |> put_session(:is_admin, true)
      |> delete_session(:count_attempt_login)
      |> redirect(to: "/dashboard")
  end

  defp try_to_login(conn, _) do
    conn
      |> put_flash(:error, "Impossible to connect with this password")
      |> redirect(to: "/dashboard/auth")
  end


I am not familiar with the Firebase or DKImagePickerController framework, so I cannot say anything
about that. But there are some things that I noticed:

There is no need in Swift to reference properties via self
(unless there is an ambiguity with a local variable, e.g. in an init
method). And you are not consistent here, e.g. both self.selectedItems
and selectedItems is used.

This

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if imageDatas.count == 0 {
        return 0
    } else {
        return imageDatas.count
    }
}

can be simplified to

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return imageDatas.count
}

And in

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell

there is no need to check for imageDatas.count == 0 (and return a dummy cell in that case). If the array
is empty then numberOfItemsInSection returns zero, i.e. the
collection view displays no item at all and cellForItemAtIndexPath
will not be called.

If the order of the selected items is not relevant then you can
use a set instead of an array:

var selectedItems = Set<NSIndexPath>()

Adding or removing an index path then simplifies slightly to

if selectedItems.contains(indexPath) {
    cell.backgroundColor = UIColor.clearColor()
    selectedItems.remove(indexPath)
} else {
    cell.backgroundColor = UIColor.redColor()
    selectedItems.insert(indexPath)
}

A loop like

self.imageDatas = []
for key in self.keys {
    self.imageDatas.append(...)
}

can be replaced by a mapping:

self.imageDatas = self.keys.map { key in ... }


There is no need for this

DateTime aDate = DateTime.Now;

int currentYearMeetingCount = Meeting.Where(x => x.Year == aDate.Year).Count();

if (currentYearMeetingCount == 0)
{
    aDate = DateTime.Now.AddYears(-1);

}

if the collection has no data for the current year, it'll only get the past 3 years if any.  so, you can do this directly :

var totalYearCount = 3;
var maxYear = DateTime.Now.Year;
var minYear = maxYear - totalYearCount;

var result = Meeting.Where(x=> x.Year >= minYear && x.Year <= maxYear).ToList();

if(result.Count == 0)
{
    // no data, do something
}

foreach(var meeting in result)
{
    Console.WriteLine($"{meeting.Name}-{meeting.Year}");
}

this will output 2017-2019 records. However, if your logic has a special case, let's say if there is no records for current year, then start with the last year instead so the output will be from 2016 to 2019. If this is the case, then instead of depending on DateTime.Now.Year you can get the max year from the collection, and subtract the past x years from it. Something like this :

var totalYearCount = 3;
var maxYear = Meeting.Max(x=> x.Year);
var minYear = maxYear - totalYearCount;
var result = Meeting.Where(x=> x.Year >= minYear && x.Year <= maxYear).ToList();

if(result.Count == 0)
{
    // no data, do something
}

foreach(var meeting in result)
{
    Console.WriteLine($"{meeting.Name}-{meeting.Year}");
}

this will output 2016-2019 records, and if there is any records for the current year (say 2020), then it'll output 2017-2020.


Unit test for a maximum-finding function

I'm not a C++ developer, and can't comment on the details of the code. But I can comment on the test cases and the general style of the code.
A good test should be enough to recreate the code from reading just the test cases. Especially when you get the task to make sure the code works under any circumstance.
Successful test cases
Let's have a look at your first test case:
std::vector<int> vec = { 7, 50, 16, 8, 25, 9, 12,112 };
test (vec, 112);

You have a vector with a max number 112, and you test for that. If I were to implement the most simple way of accepting your test I would do this (using pseudocode):
return 112;

Let's change add another test to avoid that implementation:
std::vector<int> vec = { 7, 50, 16, 8, 25, 9, 12,113 };
test (vec, 113);

Now I can't just return 112, I have to actually do something else. I would use either of these as my implementation:
return vec.lastElement();
return vec[7];

More test cases needed to fix those problems. I could go on, but I think you understand. I think the following test cases could be a good base:
{ 111 }
{ 7, 50, 16, 8, 25, 9, 12, 112 }
{ 7, 50, 16, 8, 113, 25, 9, 12 }
{ 114, 7, 50, 16, 8, 25, 9, 12 }
{ -1, -2, -3 }
{ -1, 0, 1 }
{ -333, 0 }
{ 0, 123456 }

That's a good start, now we have a lot of test cases with numbers. But we're still missing one important test:
std::vector<int> vec = { };

I have no idea what you want to be returned in this case, but it is a valid case that needs to be handled.
Naming tests
Now we have 10 tests for that simple function. But we need to look at the code to see what the test is testing, and it might not be obvious in all cases. It would be better to have a name for each test that explains what the test is testing in plain English. This is easier with testing frameworks, but a comment would also make the intention clear.
Indent
Looking at your code I struggle to see where the functions begin and end. Make sure to indent properly.
Is this a failing test?
Your second test is:
std::vector<int> vec = { 7, 50, 16, 8, 25, 9, 12,112 };
test (vec, 7);

What is this testing? My understanding is that 7 shouldn't be returned, failing this test. I don't understand why this is added, please explain in a comment.


Let's see the code:

Your Session class does too many things:

Session management
Login
Data validation
Logout
Authentication
Inclusion management

Your class has no clean way to destroy a session.
You don't verify if a session is active.
Your constructor seems a little off. Sessions are a singleton. Use a single static final class.
You don't need to repeat public on every method;
You are storing a class on a $_SESSION. I would avoid that like plague. You should start and end the session. And you should have a method to save the session (that runs session_write_close() on shutdown or at any given time).
There's no way to check if a session was opened before or not, or if it was saved already or not.

Fixing these points and splitting your code into classes that do each thing in separate will make your code better in every conceivable way.
A while ago I've used JSON to store the session data. It generates files a bit longer, but it is faster to save. Consider making your own session management system, based out on PHP's way.
Since HDD is cheaper than CPU cycles, I would consider using such way to load/save your sessions.
Completely outside the scope of this review, you could use a RAMdisk with the /tmp partition to squeeze every tiny piece of performance you get. Use only 10% of your RAM for such purpose.

Before doing anything to store your password, I recommend a good read:
How to securely hash passwords?

One of the points is that you shouldn't use SHA1, but instead use bcrypt or password_verify (PHP5.6 and up) in the future.

Also, you should be extremely careful with SQL injection and other possible attacks, especially evolving different encodings.
I sound paranoid, and I know that. But I just want a safe code.


In this case you could push the isSplit method to the Player class and implement it with return false;. Then the need to instanceof disappears.

I wouldn't say that it is bad to use instanceof but often there are other options that are better.


Overall it looks fine for a newcomer, you've made proper use of const for variables and methods, which is something beginners tend to overlook.

A few points you can still work on:

For such a tiny class like Tone, I would not bother separating declaration from implementation and would have declared it inline in the header file only. That would be less boilerplate and easier to maintain. A word of caution though: Inline code can be better optimized by the compiler and is recommend for small methods (like get/set accessors), but don't overuse it. Too much inlining will increase compile-times and generate bloated executables. I don't recommend it as an optimization either, the gain is in reducing redundant/boilerplate code implicit in the prototype/implementation setup.
Prefixing in-class member access with this-> is very rare in C++. You should only be doing that when, for instance, you need to disambiguate some shadowed member access (but even that is discouraged because shadowing members is a bit of a design flaw; better to uniquely identify your variables).
This is a personal preference, I find it better to declare public members of a class first, followed by protected and then private. My rationale is that the public section should have more emphasis, since it is what readers and users of my code will be interested on most of the time. Private/protected details are of interest for the implementer/maintainer, so they don't need to be visible right at the top of the file.
When using <cmath>, the correct way of referencing its functions, like sin/pow, is thru the std:: namespace. They happen to visible at the global level because on most compilers math.h (the C header) and cmath are implemented as wrappers to the same file. There is no requirement from the C++ Standard that this be implemented is such way, so a C++ compiler is not required to provide sin() outside the std namespace when including cmath.
Avoid using C-style casts. To cast numerical values, C++ provides static_cast. To cast pointers, reinterpret_cast is usually the operator to use. A quick overview on C++ cast operators.
Yes, size_t and int16_t are part of the Standard and are declared in <cstddef> and <cstdint> respectively. For ultimate correctness, they should be accessed from the std namespace, (e.g.: std::size_t, std:int16_t) for the same reasons cited on §4.
Your main() function is too long and doing too much. You should probably have another class, Sample perhaps, that holds the array of Tones. That class should provide methods for processing and have write_sample() as a member.
There is a much simpler way of initializing the tones vector. You can fill it with defaults on declaration using a parameterized constructor and eliminate the loop:

std::vector<Tone> tones(count, Tone(SAMPLE_RATE));

If you use an std::array you gain the size() method that knows the array length, which would remove the need for the sizeof() calculation, which is not the clearest thing you can do. Another way I tend to use for inferring the length of statically allocated arrays, without compromising readability, is by declaring a helper template function:

// Length in elements of type 'T' of statically allocated C++ arrays.
template<class T, std::size_t N>
constexpr std::size_t arrayLength(const T (&)[N])
{
    return N;
}

...

const double octaves[] = { -2, 0, 4./12, 7./12, 1, 16./12, 19./12 };
const auto count = arrayLength(octaves);

constexpr will force the function to be evaluated at compile time, thus making it suitable for use in places a compile-time constant would be required.


You can speed up your code by changing changing strategy. The overall goal is to determine the occurrence counts (frequencies) of all possible 'normalised' substrings of the given input, and then to use these counts for computing the number of pairings.

'Normalised' means processed in a way that gives all anagrams the same physical representation, either by sorting the substrings on character code (which is \$\mathcal{O}(N log N)\$ where \$N\$ is the length of the string to be normalised) or by frequency counting (which is \$\mathcal{O}(N)\$).

Byte-sized variables are sufficient for frequency counting since inputs are no longer than 100 characters, which means the normalised form of any string will by an array of 26 bytes. Which version is better depends on the (unknown) input distribution, but normalisation by sorting is simpler to arrange in Java than frequency counting and hence preferrable.

The number of possible substrings of a string of length \$K\$ is \$K * \frac{(K + 1)}{2}\$, normalisation was discussed above, and dictionary lookups are amortised \$O(M)\$ where \$M\$ is the length of what's being looked up. Hence overall complexity of this simple approach is quadratic, modulo a logarithmic component if normalisation is done by sorting instead of frequency counting (but that doesn't change the overall picture much), and modulo an additional linear factor if you look up variable-length substrings instead of fixed-length frequency count arrays.

Given the shortness of the inputs, this simple solution should be fast enough to be accepted. If the envelope needs to be pushed then there is no ready-made recipe. The only thing safe to say is that enumerating substrings one by one will invariably add a quadratic component to the complexity.

Also, the constant factor dropped by the asymptotic can be several orders of magnitude depending on how smart you go about enumerating the normalised forms of all substrings. For example, you could enumerate all substrings starting at a given position by starting with the character at that position, adding it to the map, inserting the next character in sorted order, adding that to the map, and so on. That would make the cost of a single normalisation \$\mathcal{O}(log N)\$ instead of the \$\mathcal{O}(N log N)\$ for taking a substring and sorting it, or \$\mathcal{O}(1)\$ if frequency counting is used. A similar strategy can be used with frequency counts. This incremental approach is what makes the overall complexity quadratic instead of cubic (but beware of var-length strings as discussed above).

Also, the are data structures like tries that can handle operations on substrings in linear time instead of quadratic, but the algorithms get really involved. You really need to know your basic data structures and algorithms inside out in order to see whether they can help you with a given problem. I'm not certain whether Sherlock and Anagrams can be solved with less than quadratic complexity without resorting to tries.

However, as a general strategy you should take the problem and look for ways of not doing work, to strip the problem down to its irreducible core of work that cannot possibly be avoided. And remember that counting things can be easier computationally speaking than enumerating them and incrementing a count. E.g. if you know that there are \$K\$ somethings then you can compute the number of their possible pairings in \$\mathcal{O}(1)\$ with a bit of combinatorics, instead of enumerating and counting at a cost of \$\mathcal{O}(K^2)\$. Another classic example is the length of the longest common subsequence of two strings which can be computed in \$\mathcal{O}(N^2)\$ even though the number of possible common subsequences is exponential.


Simply modifying this algorithm will not solve the problem in the required time. When n=10, this code is going through every permutation of an array of 30 integers. That is 30! (about 2^107) permutations. Going faster through the loop in paths() will not be enough.

I would suggest a backtracking solution, which cuts down the search space enormously. I think the answer when n=10 should be around 125,000,000. I'd also claim the code should run in under 30 seconds.

Obligatory code review comment. In the loop in main(), there is an out of bounds bug when evaluating buff[j+1] when j == e-1;

Here is the code that I wrote using a backtracking approach.

#include<iostream>
#include <utility>
#include <vector>
#include <map>
using namespace std;

class TripCounter {
public:
    TripCounter(int cities, int visits) : length(cities*visits) {
        for (auto i = 1; i <= cities; i++)
            pool[i] = visits;
    }

    long Count() {
        count = 0;
        BackTracker(0);
        return count;
    }

private:
    void BackTracker(int level) {
        if (level == length) {
            count++;
            return;
        }
        for (auto& bucket : pool) {
            if (IsValidAtLevel(bucket, level)) {
                trip.push_back(bucket.first);
                bucket.second--;
                BackTracker(level + 1);
                bucket.second++;
                trip.erase(trip.end() - 1);
            }
        }
    }

    bool IsValidAtLevel(pair<int, int> bucket, int level) {
        if (bucket.second == 0)
            return false;
        if (level == 0)
            return true;
        if (bucket.first == trip[level - 1])
            return false;
        return true;
    }

private:
    map<int, int> pool;
    int const length = 0;
    vector<int> trip;
    int count = 0;
};

int main() {
    int n;
    cin >> n;

    auto counter = TripCounter(3, n);
    cout << "Backtracking: " << counter.Count() << endl;
}


If I understand correctly, your frustration is with the necessary computation for knowing whether to print Result or Result: temp - childname. That's because you're doing more steps than necessary.

Instead of:

Calculating the (ChildName - Name) string
Trimming any whitespaces in the resulting string
And then checking if this string is empty

You could just check if both the Name and ChildName are equal. If they are, your variable temp isn't used. Also, since result is written independently of such calculation, you could always print it.

So, I would suggest exchanging

foreach (var item in items) {
    string temp = item.ChildName.Replace(item.Name, "").Trim();
    if (temp.Length == 0) {
        Console.WriteLine(string.Format("{0}","Result"));
    } else {
        Console.WriteLine(string.Format("{0}: {1} - {2}", "Result", temp, item.Name));
    }
}

for

foreach (var item in items) {
    Console.Write("Result");

    if (item.Name != item.ChildName) {
        string childNameWithoutName = item.ChildName.Replace(item.Name, "").Trim();
        Console.Write(string.Format(": {1} - {2}", childNameWithoutName, item.Name));
    }

    Console.WriteLine();
}


Given an element, returning the inorder rank of it an in a binary search tree with only two parameters

I'd recommend the following approach. Split up Rank into a public-facing member function and a private-facing member function. The private one's signature is:

template <typename Value>
std::pair<bool, int> RankImpl(BinaryNode* tree, const Value& value);

The public one is:

template <typename Value>
boost::optional<int> Rank(BinaryNode* tree, const Value& value);

(Secondarily, I flipped the order of your arguments, provided better names for them, and am not limiting the value we're looking for to be a Comparable. Rather, anything that is equality-comparable to Comparable should suffice).

The idea of using boost::optional is that it, as a return type, already encompasses what you want in a single type - it tells you if there is or isn't a value (i.e. was value found or not) and if there is a value, what it is (i.e. its rank). We however privately still need a value even in the false case, hence the pair helper function.

Altogether:

template <typename Value>
boost::optional<int> Rank(BinaryNode* tree, const Value& value)
{
    auto pr = RankImpl(tree, value);
    if (pr.first) {
        return pr.second;
    }
    else {
        return boost::none;
    }
}

template <typename Value>
std::pair<bool, int> RankImpl(BinaryNode* tree, const Value& value)
{
    if (!tree) {
        return {false, 0};
    }

    auto left = RankImpl(tree->left, value);
    if (left.first) {
        return left;
    }
    else if (tree->m_element == value) {
        return {true, left.second + 1};
    }
    else {
        auto right = RankImpl(tree->right, value);
        return {right.first, left.second + 1 + right.second};
    }
}


The ugly

  Not sure about this code but it feels ugly to me...

I agree :-)

The WalkTest function and other code that uses it is not pretty.
This is not part of the exercise,
not really well done, so practically it's just noise.
It's not well done, because all it does is put values from the tree into a slice, return it, and then main checks that the length is 10.
What does that mean? It's not a useful test.

I'm not a fan of variables for one-time use without justification.
For example these:

testTree1 := tree.New(1)
testTree2 := tree.New(1)
sameTest := Same(testTree1, testTree2)
if !sameTest {
  panic("same test failed")
}

I would find the above easier to read without the one-time variables:

if !Same(tree.New(1), tree.New(1)) {
    panic("got false; expected true (same trees)")
}

Magic

In this code, why should the length of walkTest be 10?

walkTestCh := make(chan int, 10)
walkTest := WalkTest(walkTestTree, walkTestCh)
if len(walkTest) != 10 {
  panic("Walk test failed")
}

You create a buffered channel with size 10.
But why buffered, and why 10?
Then WalkTest does something,
but just be reading this code,
we have no clue that 10 has any special significance.
Yet we expect the returned walkTest slice to have length of 10.

This could would have made a lot more sense if WalkTest took a count parameter. Then it would be reasonable to expect that a slice returned by WalkTest(tree, ch, 123) should have length = 123.

Variable declarations

In this code, t1Slice and t2Slice are declared at the top,
but only used much later.

var t1Slice []int
var t2Slice []int
ch1 := make(chan int, 10)
ch2 := make(chan int, 10)
go Walk(t1, ch1)
go Walk(t2, ch2)
for i := 0; i < 10; i++ {
  t1Slice = append(t1Slice, <-ch1)
  t2Slice = append(t2Slice, <-ch2)
}

It would be better to declare them right before you need them:

ch1 := make(chan int, 10)
ch2 := make(chan int, 10)
go Walk(t1, ch1)
go Walk(t2, ch2)

var t1Slice []int
var t2Slice []int
for i := 0; i < 10; i++ {
    t1Slice = append(t1Slice, <-ch1)
    t2Slice = append(t2Slice, <-ch2)
}

Performance

The exercise includes a link to the documentation of Tree,
from where you can find the source code too.
As it turns out,
the random binary tree is actually built as a binary search tree.
The consequence of that is in this case if you traverse the nodes in in-order, you will get sorted values:

func Walk(t *tree.Tree, ch chan int) {
    if t == nil {
        return
    }
    Walk(t.Left, ch)
    ch <- t.Value
    Walk(t.Right, ch)
}

With that, testing the equivalence becomes simpler and more efficient,
without needing intermediary slices, and sort.Ints and reflect.DeepEqual:

func Same(t1, t2 *tree.Tree) bool {
    ch1 := make(chan int)
    ch2 := make(chan int)
    go Walk(t1, ch1)
    go Walk(t2, ch2)

    // as per the spec, a tree.Tree has 10 elements
    size := 10
    for i := 0; i < size; i++ {
        if <-ch1 != <-ch2 {
            return false
        }
    }
    return true
}

The "specs" I'm referring to is this btw:

  The function tree.New(k) constructs a randomly-structured binary tree holding the values k, 2k, 3k, ..., 10k.

Formatting

There is a standard formatting in Go,
enforceable by the go fmt command.
Simply run this command on your code,
or use the Format button on the playground or on the tour.


Calculate percentage based on dummy variable in Pandas

I think the better way is to use groupby. It looks more logical and "natural":

df = pd.DataFrame({
    'Product': ['A', 'B', 'B', 'C', 'D', 'D'],
    'Qty': [10, 15, 5, 5, 5, 20],
    'Dummy': [0, 0, 1, 0, 0, 1]
})

# Create new column = Dummy*Qty
df['DQty'] = df['Dummy'] * df['Qty']

# Groupby df by 'Product' and summarize columns
df2 = df.groupby('Product').sum()

# Create new column equal to percentage of the total quantities
df2['Q'] = df2['DQty'] / df2['Qty']

# Drop unnecessary columns
df2 = df2.drop(columns=['Dummy', 'Qty', 'DQty'])

# Drop rows equal to zero
df2 = df2.loc[df2['Q'] != 0]
df2

The result is:

        Q
Product
B       0.25
D       0.80


Creating links using DOMDocument makes no sense to me.

I have created a simple benchmark for both methods.

Simple string concatenation is around 7 times faster on my computer:

Method Name          Iterations    Average Time      Ops/second
------------------  ------------  --------------    -------------
simpleLink        : [10,000    ] [0.0000013786793] [725,331.85764]
linkUseDomDocument: [10,000    ] [0.0000098103762] [101,932.89054]

You could reuse objects in (for example) static variables like this:

public function linkWrap2($string, $route, array $route_params = [], $prefilter = null)
{
    static $dom = null, $new_hyper = null;

    if(strlen($string) > 0)
    {
        if ($dom === null) {
            $dom = new \DOMDocument();
            $new_hyper = $dom->createElement('a');
        }

        $new_hyper->setAttribute('href', $this->generateUrl($route, $route_params).(isset($prefilter) ? '?'.htmlspecialchars($prefilter) : ''));
        $new_hyper->nodeValue = $string;

        return $dom->saveHTML($new_hyper);
    }

    return $string;
}

but it's only 30% faster.

My observations

Don't use htmlspecialchars in setAttribute value, because it will be encoded twice:

$new_hyper->setAttribute('href', $this->generateUrl($route, $route_params).(isset($prefilter) ? '?'.($prefilter) : ''));

However, you must use htmlspecialchars in simple concatenated strings:

$link = "generateUrl('a_route', array('id' => 23)) . '?'.htmlspecialchars($prefilter).'">some text';

Try to avoid custom query strings after a generated route URL. Instead of place value of $prefilter after the URL, you could place additional route params:

$this->generateUrl($route, array_merge($route_params, [ 'prefilter' => $prefilter ]));


Reversing a string in place without using iteration in C

There is a bug. Some teststring contains an odd number of characters, therefore a left == right condition is eventually hit. For an even-length string, it would never be satisfied. You should test for left < right instead.
There is absolutely no need to reassign left, right to ll, rr. revert(++left, --right) works as good.

To clear the possible confusion (see comments) this is what I meant:

if (left < right) {
    swap_values(left, right);
    revert(++left, --right);
}


Using JavaScript callback to conditionally send email

Your implementation will work but in my opinion you have made your code complicated for no reason. You are violating the "Single Responsibility" principle here by making your "checkMilestones" method do two things

Check if milestone is reached
Send email

You could have simplified this as follows:

(req.body.sessionThreeMileStones.length <=3) ? sendMail() : doNothing();

This way your code is more readable and also easy to debug.


Method that compares the scores of two players

As Timothy mentioned, your naming of the variables are not so good. I would recommend you have a look at Java Naming Conventions. It will be helpful for writing easily readable codes.

Secondly, try using private for your method. I know it is not a big program, but you will get used to it.

Thirdly, the beauty of the code is in shortness and effectiveness. And here I took Timothy's code and wrote it with for loop:

int[] scoresOfPlayerA = new int[]{a0,a1,a2};
int[] scoresOfPlayerB = new int[]{b0,b1,b2};

for (int i = 0; i < scoresOfPlayerA.length; i++){
    if (scoresOfPlayerA[i] > scoresOfPlayerB[i]){
        finalScoreOfA++;
    } else if (scoresOfPlayerA[i] < scoresOfPlayerB[i]) {
        finalScoreOfB++;
    }
}

return new int[]{finalScoreOfA, finalScoreOfB};

Good luck with your future codes.


Extract last record inserted for each key identifier

Using a CTE (Supported by SQL Server) would help separate the logic of the query better than the sub-select in the from clause. Using the auto-increment ID is also something that can simplify the query.

Consider the following:

with MostRecent as (
    select max(ID) as ID
    from ArchiveData
    group by PathKey
)
select *
from ArchiveData inner join MostRecent on MostRecent.ID = ArchiveData.ID
order by PathKey

The above should reduce the number of joins a lot, and use a better key for the joins that are done.


I guess your question is essentially:
why do you need getters for final fields,
rather than accessing them directly by name.

One reason is that you won't be able to create custom subclasses that extend the functionality of those fields,
because variables cannot be overridden,
only methods.

This may seem a moot point with an enum as in your question,
because enums cannot be extended anyway.
The most extensible setup is when you work with interfaces.
You could have a Country interface that includes those getters,
and an enum that implements that interface and those getters.
Then you could have a CustomCountry that implements the same interface.
Of course this extensible setup requires methods instead of variables.

Another reason to use getters instead of variables is that the member variables are too intimate implementation details.
In the future you might want to derive these values from multiple other variables,
but you won't be able to without disrupting your users,
since the original variable names are now part of the public API of your class/enum.
By exposing getters instead of the variables directly,
you are free to refactor your internal implementation without disrupting your users.


Perfect Hash Family Non-Distinct t Columns Calculator

For a start, use iterators. Don't convert to lists constantly:

get_column can be simplified to (use generator rather than list):

def get_column(phf, c):
    return (x[c] for x in phf)

combine_columns_into_array to:

def combine_columns_into_array(phf, cs):
    return zip(*[get_column(phf, c) for c in cs])

In count_non_distinct_combinations:

for c in combinations(range(k), t):

Rather than:

for c in combinations([i for i in range(k)], t):

To further simplify, combine_columns_into_array can be merged with get_column:

def combine_columns_into_array(phf, cs):
    return zip(*[[x[c] for x in phf] for c in cs])

Combining combine_columns_into_array into count_non_distinct_combinations:

def count_non_distinct_combinations(phf, t):
    k = len(phf[0])
    true_count = 0
    # get all combinations
    for c in combinations(range(k), t):
        b = False
        for row in zip(*[[x[i] for x in phf] for i in c]):
            # if the row is completely distinct
            if len(row) == len(set(row)):
                b = True
        # if all rows are non-distinct:
        if not b:
            true_count += 1
    return true_count

The zip(*[[x[i] for x in phf] for i in c]) can be simplified to ([x[i] for i in c] for x in phf)

The whole

k = len(phf[0])
true_count = 0
# get all combinations
for c in combinations([i for i in range(k)], t):
    b = False
    choices = combine_columns_into_array(phf, list(c))
    for row in choices:
        # if the row is completely distinct
        if len(row) == len(set(row)):
            b = True
    # if all rows are non-distinct:
    if not b:
        true_count += 1
return true_count

section can be simplified (I think) to:

true_count = 0
# get all combinations
for c in combinations(range(len(phf[0])), t):
    s = [[x[i] for i in c] for x in phf]
    # if all rows are non-distinct:
    if not [len(i) for i in s] == [len(set(i)) for i in s]:
        true_count += 1
return true_count

And so to:

def count_non_distinct_combinations(phf, t):
    true_count = 0
    for c in combinations(range(len(phf[0])), t):
        if not any(len(set(i)) == len(i) for i in ([x[i] for i in c] for x in phf)):
            true_count += 1
    return true_count

I admit I lost readability somewhere along the line, but this new 6 line version takes 55.3% of the time needed to complete the phf2 case, so its almost twice as fast as your version. There may be improvements that can be done to the algorithm, but I'll stop here.


I would recommend a process like this:

Code: (Demo)

$string1 = "abacadeee";
$string2 = "aabbccddee";

$counts2 = count_chars($string2, 1);

$tally = 0;
foreach (array_intersect_key(count_chars($string1, 1), $counts2) as $charcode1 => $count1) {
    $tally += min($counts2[$charcode1], $count1);
}
echo $tally;

count_chars() lends itself beautifully to this task, so using array functions onward is a sensible choice.

It is important to try to minimize iterations and not perform any useless iterations.  By calling array_intersect_key() on the two count_chars() results, the foreach() loop is only going to iterate elements with keys which are shared between the two arrays.  In doing this, you don't need to check which array is smaller (which is otherwise how you would choose which array to iterate).

$tally is incremented by the lesser of the two counts for each char.

p.s. calling chr() is irrelevant to your objective.


Your code doesn't handle names with spaces within, nor names with characters that are illegal for URL's. To accomodate these two issues, you could use something like:

$item->casting = 'André, Ann Charlotte, Bob, Kåre Ronny';

$actors = array();

foreach (explode(',', $item->casting) as $actor) {
    $actor = trim($actor);
    $actors[] = ''. $actor .'';
}

echo implode(', \n', $actors);

Which would produce the following output:

André,
Ann Charlotte,
Bob,
Kåre Ronny

I kind of prefer building the $actors array, as that allows me easily to change output variants. But you could also opt for using echo directly, which would eliminate the need for the entire $actors table. I did however removing the original $actors and included that directly in the foreach, as I try to keep intermediary variables to a minimum.

PS! Depending on font settings and encoding elsewhere, you could consider calling htmlspecialchars() in addition before using in the URL.


I see a number of things that you could use to improve your code.

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.  Know when to use it and when not to (as when writing include headers).

Avoid introducing unneeded variables

The helper string is not necessary.  Instead, you could rework your addition routine so that it calculates first+=second and then swaps first and second.  In that way, second would always contain the final value.  This would also help with the next suggestion.

Avoid introducing unneeded tests

With a little judicious rewrite, your main function can eliminate the special case testing to see if the terms value is 1 or 2.  I'd rewrite it like this:

int main()
{
    unsigned int maxterm;
    std::cin >> maxterm;
    std::string first="1";
    std::string second="1";

    for(unsigned i=2; i < maxterm; ++i) {
        fibnext(first,second);
    }
    std::cout << second << std::endl;
}

Note that I've also renamed a variable from value (which is not very descriptive) to maxterm and the routine from addition (which is descriptive but very general) to fibnext which more accurately suggests that it's calculating the next Fibonacci term.

Simplify your addition

There are a few ways to simplify the addition, but this is perhaps the most straightforward:

std::string &fibnext(std::string &first, std::string &second)
{
    char carry = 0;

    // make strings the same length by 0-padding first
    first.insert(0, second.length() - first.length(), '0');
    for(int i=first.length()-1; i >= 0; --i)
    {
        first[i] += second[i] - '0' + carry;
        if (first[i] > '9') {
            first[i] -= 10;
            carry = 1;
        } else {
            carry = 0;
        }
    }
    if (carry)
        first.insert(0, 1, '1');

    std::swap(first,second);
    return second;
}

Results

The effects of these changes are to reduce the number of times that strings are copied and constructed.  In fact, only two std::string objects are created and then expanded as needed.  Each time a digit is inserted at the beginning of a string, it (conceptually, anyway) needs to allocate a new space that's large enough, copy the string into that new memory, and then free the old space.  However, std::string implementations are often smart enough to allocate larger-than-immediately-needed chunks to help with exactly this type of operation.

I measure it as being almost 30x faster than the original code (0.10 seconds vs 2.88 seconds on my 64-bit Linux box) when calculating the 10,000th Fibonacci number.