R Container for Multiple data.frame with a Brief Description of the Content of the data.frame

One approach
If the description is to serve only as a metadata, R allows you to add any number of metadata to objects with attributes feature. you can add it as an attribute for the data.frame object.
attr(sub_data, "Description") <- "Contains all sumscales + sociodemographics, names abbreviated"

# Description now shows in the data frame structure
str(sub_data)
# 'data.frame': 5 obs. of  2 variables:
#  $ x: num  2 3 5 1 6
# $ y: num  20 30 10 302 5
# - attr(*, "Description")= chr "Contains all sumscales + sociodemographics, names # abbreviated"

#You can access the Description only
attributes(sub_data)$Description
# [1] "Contains all sumscales + sociodemographics, names abbreviated"

However, custom attributes come with limitations.They are not persistent when you perform certain operations on objects such as subsetting. Here is an example using same object with the new Description attribute we just added. If we subset the data, the custom attribute will be lost.
sub2_data <- sub_data[,"x", drop = FALSE]

attributes(sub2_data)$Description
# NULL

Alternative approach
You can use the same idea of creating a container within container. However, instead of creating a list that contains data frames, you can create a data.frame within a data.frame. This makes it easier to access and manipulate. You can access the inner data frame by adding second $
# Assigning new column `data` to hold data frames
index_df$data <- index_list

# We can access Description
index_df$Description
# [1] "Contains all sumscales + sociodemographics, names abbreviated"
# [2] "Only sum scores for the UV Scale"

# Accessing Data
index_df$data$sub_data
#  x   y
#1 2  20
#2 3  30
#3 5  10
#4 1 302
#5 6   5

str(index_df)
# 'data.frame': 2 obs. of  3 variables:
#  $ Data.Frame : chr  "sub_data" "uv_newScale"
# $ Description: chr  "Contains all sumscales + sociodemographics, names abbreviated" "Only sum scores for the UV Scale"
# $ data       :List of 2
#  ..$ sub_data   :'data.frame':    5 obs. of  2 variables:
#  .. ..$ x: num  2 3 5 1 6
#  .. ..$ y: num  20 30 10 302 5
#  ..$ uv_newScale:'data.frame':    5 obs. of  2 variables:
#  .. ..$ item1: num  2 3 5 1 6
#  .. ..$ item2: num  3 5 1 3 2

Efficiency
The first approach is more efficient than the second in terms of memory footprint. Here is a comparison between objects sizes in bytes.
# Creating one data frame within one data frame for comparison
list_df <- list(sub_data=sub_data)
dfs <- data.frame("Data.Frame"="sub_data",
             "Description"="Contains all sumscales + sociodemographics, names abbreviated")

dfs$data <- list_df

# Adding attributes
attr(sub_data, "Description") <- "Contains all sumscales + sociodemographics, names abbreviated"

# Memory Size in bytes
object.size(dfs)
# 2376 bytes
object.size(sub_data)
# 1224 bytes


Password-Lock a Single Page with PHP - How did I do?

A few things, mostly around logged_in:

private function check_login() {
    if (isset($_SESSION['logged_in'])) {
        // If logged in, take this action
        $this->logged_in = true;
    } else {
        // If not logged in, take this action
        $this->logged_in = false;
    }
}

Simply:

$this->logged_in = isset( $_SESSION['logged_in'] );

Also, the accessor method is_logged_in is being used quite well, yet there is a lack of a  corresponding set_logged_in. Add a set accessor, even if private, and use it exclusively.

Directly assigning the value of an instance variable in more than one place violates the DRY principle. That is, the assignment of $this->logged_in = <<value>> should exist only once: within the accessor. For example:

private function set_logged_in( $logged_in ) {
  $this->logged_in = $logged_in;
}

Once the accessor is in place, use it:

private function check_login() {
  $this->set_logged_in( isset($_SESSION['logged_in']) );
}

After the logged in status is using accessors exclusively, you can remove the logged_in variable completely and rely only on the $_SESSION['logged_in'] value. Think about what this implies for the check_login() method.

Next:

if ($pass !== 'TheChosenPassword') return false;

return true;

Simply:

return $pass === 'TheChosenPassword';


Sometimes (actually, normally), simpler is better.

I'm going to present a different way of doing this that's really simple, if you understand the tricks, then I'm going to explain what makes it better. One of the reasons I am doing it this way is because your code is hard to follow.... simply because there's so much. I suspect that when you see a different way of doing things a penny will "drop".

Here's the alternative:

private static final int[] findMissing(int[] data) {
    if (data == null || data.length <= 1) {
        // nothing missing.
        return new int[0];
    }
    int first = data[0];
    int last = data[data.length - 1];
    int[] missing = new int[last - first - data.length + 1];
    int missingCursor = 0;
    int expect = first;
    for (int value : data) {
        while (expect < value) {
            missing[missingCursor] = expect;
            missingCursor++;
            expect++;
        }
        expect++;
    }
    return missing;
}

Is that it? Yes, and it is probably still too much. But, let's consider the problem...

for too-small inputs, we know that there's nothing missing.
for larger inputs, we know exactly how much is missing - the difference between the first and last data values, less the number of values we actually have, and, add 1 because the last-minus-first is actually 1 too small.
then, all we have to do is 'expect' certain values, and fill in the gaps until we get the values we expect.

So, that is what the code does, but, note the following:

there is no need for object-oriented programming - there is no object here to represent. A single static method works fine.
there is no need for an adjustable-size ArrayList<Integer>() because we know how much is missing. Also, that's converting int values to Integer members in a List, which is more work than needed.
the method assumes the inputs are valid - no error-handling or validation

Now, that's the way I would write that method, and why I think it is an improvement.

Having said that, I want to point out some other issues in the code:

When creating a collection like an ArrayList, you need to use the diamond operator <> on the right-hand side. The code:

private List<Integer> missing = new ArrayList();

should be:

private List<Integer> missing = new ArrayList<>();

On the other hand, I really like that you have made the left-side List, this shows an understanding of the Collections API
When I run your code, the order of the missing values in the first array is suspect. I get: 2 3 7 8 11 16 17 18 13 14 (yes, the 13 and 14 are at the end for some reason). There's a bug in there somewhere I can't find.
Your code should print a new line after each output. Currently it is all on one line. System.out.println() to do that.

See this running in Ideone


cont is continuing the computation process.

The printListRevTR function, in the process of execution, builds up a "chain" of cont functions. The very first (or last, depending on how you count) such function is the one that prints "Done!". After that, each next cont prints the current number and then calls the previous cont.

As printListRevTR goes through the list, it builds up a chain of conts, by creating each next function that calls the previous one. This chain could be visualized like this:

After the list has been exhausted, the very last iteration calls the very last (or first, depending on how you count) function in that chain, which calls the next one, which calls the next one, and so on, until the final "Done!" function is called.

As for loop - that's not a keyword, just a name that Juliet has chosen for her function.


jsanc623 had some good points, but I think he missed a lot too.  In particular, I think you have a fairly major design problem.  Without seeing all of the related classes, my comments are a bit limited, but there's a few things below.

There's a few different 'concerns' your code is handling here:

Authenticating (is the username/password pair x, y valid?)
Persisting an identity (remembering that the user is logged in under username x)
Checking permissions

These concerns should be separated.

The logic of "is [x, y] a valid authentication pair?" and the logic of "can this person do z?" have no need to be coupled.

Additionally, there's no reason to hard code all of the session stuff.  (The class should definitely not be responsible for starting the session.)

Based on the API seen, I have a suspicion that your controller and model classes have convoluted functionality and APIs.

You might want to consider looking into how a few different frameworks have handled authentication.  Zend Framework is the only one I have experience with the authentication components.  It has a few quirks, but overall, it has a good API.


A few improvements:

Assignment operator (=) should return a reference to short_int32_t, returning *this in the implementation.
Operator < or any other comparison/arithmetical operator for that matter, should be const, since they only read the object's state. E.g.: bool operator < (short_int32_t x) const.
Where are the other comparison operators, BTW? I would expect at least ==,!=,<,>,<=,>=.
get/set are good enough names, but wouldn't maybe set32 and get32 be more idiomatic in this case? Or perhaps even more explicit, such as fromInt32 and toInt32.
Consider making those global inline functions member of the class, if they are never used elsewhere.


I think this is a good approach.

Stylistically I think you've done a good job as well; you've use a descriptive variable name (line), good indentation (4 spaces is standard for Julia), and have made use of a function that returns an iterator, which will be more efficient for this purpose than, say, one that returns an array.

The only thing I would do differently is to replace write with print. I tend to reserve the former for writing to a file and use the latter for writing to STDOUT.

There are two alternative ways to do this that I can think of. I'll provide them for completeness.

Read the entire input stream as a single string and print it to STDOUT. Note that this is quite impractical for large input streams.

print(readall(STDIN))

Read and print each character from the stream one at a time.

while !eof(STDIN)
    print(read(STDIN, Char))
end

This may provide some benefit in efficiency over your approach if the input is very large and contains few to no newlines, since eachline returns an iterator over the lines of the input, where lines are delimited by newlines. If I'm not mistaken, all lines are read before the loop body executes.

Overall though, for practical purposes I think this is a fine approach. Nice job.


Your implementation fails if there are duplicates values in the stack:

def main():
    stack = SmartStack()
    stack.stack_push(1)
    stack.stack_push(1)
    stack.stack_push(3)
    stack.stack_pop()
    stack.stack_pop()
    print(stack.stack_min())

$ ./smartstack
Traceback (most recent call last):
  File "./smartstack", line 35, in <module>
    main()
  File "./smartstack", line 32, in main
    print(stack.stack_min())
  File "./smartstack", line 23, in stack_min
    return self.min[-1]
IndexError: list index out of range

Suggested fix:

def stack_push(self,x):
    self.stack.append(x)
    if not self.min or x <= self.stack_min():
        self.min.append(x)

The naming is redundant: methods of the SmartStack class shouldn't need to have "stack_" in their names.

If you are targeting Python 2, be sure to use new-style classes (i.e., SmartStack should have object as a superclass).


It looks fine, but there are a few issues with it:

When we check if a number is a prime, we need to test all possible divisors up its root inclusively. If you print the primes list, you'll see that 9 is there, which is obviously a bug. untilRoot n = takeWhile (\x -> x*x < n) should be untilRoot n = takeWhile (\x -> x*x <= n). However, this bug does not affect the correctness of your factorization algorithm.
It does not scale well. In the firstPrimeDivisor function, all primess up to x are checked in the worst case. That's why it works slowly even for moderately large prime numbers(for instance, 10^9 + 7).

Here a more efficient solution which checks only O(sqrt(n)) divisors in the worst case:

factorize :: Integer -> Integer -> [Integer]
factorize _ 1 = []
factorize d n
    | d * d > n = [n]
    | n `mod` d == 0 = d : factorize d (n `div` d)
    | otherwise = factorize (d + 1) n

primeFactors :: Integer -> [Integer]
primeFactors = factorize 2

It is also much more concise. The idea behind it is to prove two statements first and then write a very simple code based on them:

The smallest divisor of any natural number greater than two is a prime. Let's assume that it is not the case and d = p * q (p, q > 1), where d is the smallest divisor of n. But then p < d and p is a divisor of n. Thus, d is not the smallest one. This statement also shows why your original solution is correct, even though the primes list is contains some composite numbers.
Any composite number has a divisor that does not exceed its square root. The proof by contradiction is very straightforward so I will omit it.


An online store, being converted from procedural to OOP

At first I'm not mysqli guy and maybe somewhere I have mistake but the important part here Is the idea.

My advice to you is to throw exception instead of die or exit because you can catch them a lot easier. In your case you can put instantiation of MySQLDatabase in try/catch and if exception is occurred to show static page or whatever you wish.

class MySQLDatabase {

    private $connection;

    function __construct() {
        $this->open_connection();
    }

    public function open_connection() {
        $this->connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
        if(!$this->connection) {
            throw new \Exception("Database connection failed: " .mysqli_connect_errno());
        }
    }
    /*
     * This function (mysqli_select_db) should only be used to change the default
     * database for the connection. You can select the default database with 4th
     * parameter in mysqli_connect().
     */
    public function select_db($db_name){
        mysqli_select_db($this->connection, $db_name);
        if(!$this->connection){
            throw new \Exception(" meaningfull message");
        }
        return $this;
    }

    public function close_connection() {
        mysqli_close($this->connection);
        unset($this->connection);
    }

    public function query($sql) {
        $result = mysqli_query($this->connection, $sql);
        return $this->confirm_query($result);
    }

    public function fetch_assoc($result_set) {
        return mysqli_fetch_assoc($result_set);
    }

    private function confirm_query($result) {
        if(!$result) {
            throw new \Exception("Database query failed: " . mysqli_error($this->connection));
        }
        return $result;
    }

    public function free_result($result) {
        if($result) {
            return mysqli_free_result($result);
        }
    }
}

I will make separate class for every table or group of futures(e.g. some kind of statistics) in separate class and all SQL queries are there. Important part of this is to not make validation in this class. You must consider that every parameter of method Is validated and correct.

class UserDomain
{
    protected $conn;

    public function __construct(MySQLDatabase $conn){
      $this->conn = $conn;
    }

    public function getUser($id){
        $sql = "SELECT * FROM users WHERE u.id = ?";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $tmp = array();
        while($res = $stmt->fetch()){
            $tmp[] = $res;
        }

        return $tmp;
    }

    public function setName($name, $user_id){}
    public function loginBy($user_id, $password){}
    public function changePassword($new_paswwrod, $user_id){}
    public function deleteUser($user_id){}
}

Here we have our class User. It can be tested very easy because your sql queries are now separated

// This class represents single user
class User {
    protected $id;

    protected $db;

    public function __construct($id, UserDomain $conn){
        $this->id = $id;
        $this->conn = $conn;
    }

    function getUserId(){
        return $this->id;
    }

    function changePassword($old_password, $new_password){

        if($this->conn->loginBy($this->id, $password)){
            // here you must validate new password against your business logic and if its true or pass try/catch you will update
            $this->changePassword($new_password, $this->id);
        }
    }

    function getUserInfo(){
        return $this->conn->getUserInfo($this->id);
    }
}

Finally I recommend you to watch this speak from Adam Culp he also have and book I think you will like it. And will give you nice ideas about refactoring legacy code and not write it


Bug

This:

knight_moves([2,5],[2,5])

prints:

Your path is:
[2, 5]
[4, 6]
[2, 5]

Not the shortest path. In knight_moves, simply call bfs with [first_child] as the children argument. There's no need to call create_children in knight_moves; bfs can compute the first level of the search tree the same way it computes all other levels.

Global variable

In create_children, you're setting @children which acts like a global variable as this method isn't inside a class. Simply return valid_children without setting any variables.

(You're not setting Square#children because the method isn't inside Square. You actually never use Square#children. Remove this field from Square).

Naming

Rename:

Square -> Node (The class represents a node in the search tree. A true Square class would only have x and y fields).
create_children -> child_nodes
first_children -> root
board argument -> node (or parent)
display_path -> print_path

Missing Square class

The code sometimes uses an [x, y] array for squares, and sometimes the x and y fields of Node. This makes the code full of wrapping of unwrapping:

# lines that unwrap an [x, y] array:
Node.new(space[0], space[1], board)
first_child = Node.new(first_square[0],first_square[1])

# lines that create an [x, y] array:
if [current.x,current.y] == search_value
array << [current.x,current.y]

You can eliminate this by creating a Square class and use it for representing squares everywhere in the code (including in Node):

class Square
  attr_reader :x, :y

  def initialize(x, y)
    @x = x
    @y = y
  end

  def ==(other)
    [self.x, self. y] == [other.x, other.y]
  end

  def to_s
    [self.x, self.y].to_s
  end
end

I already implemented equality (for the comparison in bfs) and to_s (for printing in print_path). Then change Node to use a Square: (also, use attr_reader)

class Node
  attr_reader :square, :parent
  def initialize(square, parent=nil)
    @square = square
    @parent = parent
  end
end

Now replace any [x, y] array in the code with a Square:

# in child_nodes:
square = node.square
...
Square.new(square.x + 2, square.y + 1),
...
space.x.between(0, 8) &&
...
Node.new(space, node)

# in knight_moves:
Node.new(first_square)

# in bfs:
if current.square == search_value

# in print_path:
array << parent.square
array << current.square
puts i # instead of "p i", so to_s is used

# calling knight_moves:
knight_moves(Square.new(2, 5), Square.new(4, 7))

Missing Square methods

Most of child_nodes deals with squares, so most of its functionality should be inside Square methods. The only thing it does that doesn't involve only squares is creating nodes, so it should do just that:

def child_nodes(node)
  node.square.knight_moves.map do |square|
    Node.new(square, node)
  end
end

Square#knight_moves is a new method that returns an array of the squares that can be reached from the current one. It should look something like this:

def knight_moves
  [
    Square.new(self.x + 2, self.y + 1),
    ...
  ].select { |square| square.valid? }
end

This requires adding a Square#valid? to check if a square's coordinates are legal.

Revisiting knight_moves

knights_moves does too little now, it only creates a root node and put it in a one-element array. I would remove it and move its functionality to bfs (Make bfs accept first_square and final_square as arguments, and call it directly).

Seperating logic and printing

Don't print the path in bfs, just return it (the array of squares) and let the main code print it. You can simplify the code for getting the path:

def path_from_root(current)
  array = []
  loop do
    array << current.square
    current = current.parent
    break if current.nil?
  end
  array.reverse
end


Your code looks good, but can be improved.

/**
 * Resizes the array when capacity reaches 100% or 25%
 *
 * @param capacity New capacity for the array
 */
private void resize(int capacity) {
    Item[] copy = (Item[]) new Object[capacity];
    for (int i = 0; i < size; i++) {
        copy[i] = queue[i + index];
    }
    queue = copy;
}

The javadoc states that this method would resize the array when the capacity reaches a specific value which isn't correct. This method resizes the underlaying buffer no matter what capacity it has.

This javadoc is lying. After removing the lying part only Resizes the array is left as description which basically doesn't add any value because it is obvious.

I would remove that javadoc completely and rename the method to resizeInternalBuffer.

enqueue()

/**
 * Adds an item onto the end of the queue. If the size of the queue reaches
 * the length of the array, the length of the array is doubled.
 *
 * @param item Item to be added. Must not be null
 * @throws NullPointerException if the parameter item is null
 */

Without reading the code I see that this method (and the dequeue() method as well) is doing too much. I would extract the checking for the size to separate methods like so

private void ensureCapacityMax() {
    if (size == queue.length) {
        resize(2 * queue.length);
    }
}

private void ensureCapacityMin() {
    if (size < queue.length / 4) {
        resize(queue.length / 2);
    }
}

which are then called like

public void enqueue(Item item) {
    if (item == null) {
        throw new NullPointerException("Item must not be null");
    }

    ensureCapacityMax();

    queue[size + index] = item;
    size++;
}

By using lambda expressions you could simplify this to one method.

I don't really like the usage of index for enqueue() and dequeue(). A much cleaner way would be to use head and tail like so

private int head = 0;
private int tail = 0;

public void enqueue(Item item) {
    if (item == null) {
        throw new NullPointerException("Item must not be null");
    }

    ensureCapacityMax()

    queue[tail] = item;
    tail = (tail + 1) % queue.length;
    size++;
}

public Item dequeue() {
    if (isEmpty()) {
        throw new NoSuchElementException("There is nothing in the queue");
    }

    ensureCapacityMin()

    Item item = queue[head];
    queue[head] = null;
    head = (head + 1) % queue.length;
    size--;
    return item;
}

now we need to adjust the resize() method like so by the usage of System.arraycopy()

private void resize(int capacity) {
    Item[] copy = (Item[]) new Object[capacity];

    if (size > 0) {
        if (head < tail) {
            System.arraycopy(queue, head, copy, 0, size);
        } else {
            System.arraycopy(queue, head, copy, 0, queue.length - head);
            System.arraycopy(queue, 0, copy, queue.length - head, tail);
        }
    }

    queue = copy;
    head = 0;
    tail = (size == capacity) ? 0 : size;
}

I didn't test this implementation but it should work well.


This:

private static class IntegerObj {
    Integer obj = null;
}

really made me wonder. You're threading this object through recursive calls to hold the answer.

Instead you can remove this class and change your methods to return an int:

public int ceiling(int val) {
  return recurseCeiling(root, null, val);
}

public int floor(int val) {
  return recurseFloor(root, null, val);
}

private int recurseCeiling(TreeNode node, Integer ceil, int value) {
  if (node == null) {
    return ceil;
  }
  if (value <= node.item) {
    return recurseCeiling(node.left, node.item, value);
  }
  return recurseCeiling(node.right, ceil, value);
}

private int recurseFloor(TreeNode node, Integer floor, int value) {
  if (node == null) {
    return floor;
  }
  if (value < node.item) {
    return recurseFloor(node.left, floor, value);
  }
  return recurseFloor(node.right, node.item, value);
}

We can now see that these methods can be written iteratively

private int recurseCeiling(TreeNode node, Integer ceil, int value) {
  while (node != null) {
    if (value <= node.item) {
      ceil = node.item;
      node = node.left;
    } else {
      node = node.right;
    }
  }
  return ceil;
}

private int recurseFloor(TreeNode node, Integer floor, int value) {
  while (node != null) {
    if (value < node.item) {
      node = node.left;
    } else {
      floor = node.item;
      node = node.right;
    }
  }
  return floor;
}


ValidateString is strange name for a class. StringValidator would be more apt.
Don't make your constructor print anything. Your class exists to validate a string, not print things to stdout. Leave that to some other piece of code.
valid should be named valid? and return a boolean. And you can omit the return keyword.
Add attr_reader :string, and replace your @string with just string
8 is a magic number, and should be replaced with constant (e.g. MIN_STRING_LENGTH)
Presumably, this exists to check for simple passwords. However, you're not checking that the string contains both upper- and lowercase letters. An all-uppercase string with a number would pass validation. For passwords, you'd want to enforce that it's mixed casing.

I'd just write a method:

def valid_string?(string)
  return false unless string.length >= 8
  return false unless string =~ /[0-9]/
  return false unless string =~ /[[:upper:]]/ # allows non-Latin letters
  return false unless string =~ /[[:lower:]]/ # ditto
  true
end

Of course, you'd be better off using something like zxcvbn to check password entropy. Your rules allow for the good ol' Password1 string just fine.


Saving settings to Windows registry as a tuple

you need save winpos_t as single value with REG_BINARY instead 3 different values. possible implementation:

class CConfig
{
    HKEY _hKey;
public:

    ~CConfig()
    {
        if (_hKey)
        {
            RegCloseKey(_hKey);
        }
    }

    CConfig() : _hKey (0)
    {
    }

    LSTATUS Save(
        PCWSTR lpValueName,
        DWORD dwType,
        const void* lpData,
        DWORD cbData)
    {
        return RegSetValueExW(_hKey, lpValueName, 0, dwType, (BYTE*)lpData, cbData);
    }

    LSTATUS Load(
        PCWSTR lpValueName,
        PDWORD lpType,
        void* lpData,
        PDWORD lpcbData)
    {
        return RegQueryValueExW(_hKey, lpValueName, 0, lpType, (BYTE*)lpData, lpcbData);
    }

    LSTATUS Init(HKEY hKey, PCWSTR lpSubKey)
    {
        return RegCreateKeyExW(hKey, lpSubKey, 0, 0, 0, KEY_ALL_ACCESS, 0, &_hKey, 0);
    }
};

void test_cfg()
{
    CConfig cfg;
    if (!cfg.Init(HKEY_CURRENT_USER, L"Software\\MyKey"))
    {
        struct winpos_t
        {
            DWORD dwWindowStyle;
            int iWindowX;
            int iWindowY;
        };

        winpos_t test_pos = { 1, 2, 3};

        static const PCWSTR szwinpos_t = L"winpos_t";

        if (!cfg.Save(szwinpos_t, REG_BINARY, &test_pos, sizeof(test_pos)))
        {
            ULONG type, cb = sizeof(test_pos);
            RtlZeroMemory(&test_pos, sizeof(test_pos));
            if (!cfg.Load(szwinpos_t, &type, &test_pos, &cb) && type == REG_BINARY && cb == sizeof(test_pos))
            {
                DbgPrint("{%x, %x, %x}\n", test_pos.dwWindowStyle, test_pos.iWindowX, test_pos.iWindowY);
            }
        }
    }
}


Searching through a huge set with threads

There are definitely some problems if you want to make this threaded. Firstly, access to m_searches is not protected in any way. Since this is a shared bit of memory, it would need to be protected by something (say a mutex) before you modify it.

Generally in situations like these, it's far better to let std::async do a lot of the hard work for you. Also, try and eliminate shared mutable state as much as possible, because it makes life a lot harder. Firstly, let's write a simple search function that'll return an index if we find a match:

const std::size_t not_found = -1;

template <typename Iterator, typename T>
std::size_t find_index(Iterator begin, Iterator end,
                       const T& value, std::size_t start)
{
    std::size_t s = start;
    Iterator it = begin;

    while(it != end) {
        if(*it == value) {
            return s;
        }
        ++s;
        ++it;
    }

    return not_found;
}

Ok, this is just our normal linear search, but it allows us to start from anywhere in our search range since we're only passing in a few iterators.

Next, we define a vector to search over:

std::vector<int> v { 4, 5, 1, 3, 9, 8, 7, 6, 11, 42, 13 };
typedef typename std::vector<int>::iterator iter_t;

Create our vector of future to hold results:

std::vector<std::future<std::size_t>> futures;

And then populate it:

futures.emplace_back(
    std::async(std::launch::async, find_index<iter_t, int>,
               v.begin(), v.begin() + 6, 8, 0));
futures.emplace_back(
    std::async(std::launch::async, find_index<iter_t, int>,
               v.begin() + 6, v.end(), 8, 6));

Note the std::launch::async flag specifies we want to create a new thread to run our function in. I've hardcoded the search start and end places here, but you can obviously add some logic to split things up evenly if you'd like. Also, note that we need to explicitly define the template types here, since they won't be deduced.

Now we'll set up a vector to store our results in, and get the results back:

std::vector<std::size_t> results;
for(auto& future : futures) {
    results.emplace_back(future.get());
}

Finally, print out anything that was found:

std::for_each(results.begin(), results.end(),
              [](std::size_t index)
              { if(index != not_found) std::cout << index << "\n"; });
}

The whole thing can be found here.

Hopefully this gives you an idea of a different way of approaching your problem.


How to optimize a nested foreach loop which is creating same data object (with different values)

when ever you want to solve violations of the DRY principle you have to convert similar code into equal code.

If you look at the two inner loops: make the most inner loop using new local variables to replace the differeing parts

       {
            var circuitsCount = routes.Circuits.Count;
            Row routesRow = null;

            if (routes.Name != segReq.Name)
            {
                 routesRow = new Row
                {
                    c = new RootObject[] { new RootObject { v = routes.Name }, new RootObject { v = segReq.Name }, new RootObject { v = circuitsCount }, new RootObject { v = 16 } }

                };
            }
            else
            {
                throw new NotSupportedException("segReq name and  routes name can not be same !!");
            }

            rows.Add(routesRow);
        }

becomes

       { // may be no valid syntax since I'm not a C# guy...
            var count = routes.Circuits.Count;
            Row routesRow = null;
            var master = "routes"
            var masterName = routes.Name;
            var detail = "segReq"
            var detailName = segReq.Name;
            var magicNumber =  16;

            if (masterName != detailName )
            {
                 routesRow = new Row
                {
                    c = new RootObject[] { new RootObject { v = masterName }, new RootObject { v = detailName }, new RootObject { v = count }, new RootObject { v =  magicNumber } }

                };
            }
            else
            {
                throw new NotSupportedException(detail+" name and "+master+" name can not be same !!");
            }

            rows.Add(routesRow);
        }

now you extract the "future common" part to a new method:

       {
            var count = routes.Circuits.Count;
            var master = "routes"
            var masterName = routes.Name;
            var detail = "segReq"
            var detailName = segReq.Name;
            var = magicNumber  16;

            Row routesRow = CreateMasterDetailRow(master, masterName, detail, detailName, count, magicNumber);
            rows.Add(routesRow);
        }
//...

func Row CreateMasterDetailRow(var master, var masterName, var detail, var detailName, var count, var magicNumber)
{

            if (masterName != detailName )
            {
                 return new Row
                {
                    c = new RootObject[] { new RootObject { v = masterName }, new RootObject { v = detailName }, new RootObject { v = circuitsCount }, new RootObject { v =  magicNumber } }

                };
            }
            else
            {
                throw new NotSupportedException(detail+" name and "+master+" name can not be same !!");
            }
}

inline the extracted variables into the function call:

       {
            Row routesRow = CreateMasterDetailRow("routes", routes.Name, "segReq", segReq.Name, routes.Circuits.Count, 16);
            rows.Add(routesRow);
        }

then use the call in the middle loop:

   {  // maybe I got the order of "master" and "detail" wrong...
        Row segReqRow= CreateMasterDetailRow("MastrSegment ", MastrSegment.Name, "segReq", segReq.Name, segReq.routess.Count, -26);
        foreach (var routes in segReq.routess)
        {
            Row routesRow = CreateMasterDetailRow("routes", routes.Name, "segReq", segReq.Name, routes.Circuits.Count, 16);
            rows.Add(routesRow);
        }
        rows.Add(segReqRow);

You can even replace the similar code in the outer loop if you provide some "fake data" for the (not failing) consistency check to satify the new methods parameter list...


Here are some things that may help you further improve your code.

Clearly separate interface and implementation

The Ticker.hpp includes two headers, ipc/Client.hpp and ipc/Message.hpp which are not actually part of the interface.  They're part of the implementation and so those #includes should be moved to the .cpp file instead.

Don't throw an exception from a destructor

A destructor really really shouldn't throw an exception, but yours might.  Consider this simple main():

int main() {
    sdp::Ticker t(1);
    t.stop();
}

This will throw an error because stop attempts to set the done_promise value and then the destructor calls stop and attempts to set it again.  That second attempt is guaranteed to throw an error.

Set an exception in the promise

It seems likely that your code for constructing and sending a message could throw an exception.  If they do, the program will seem to silently fail.  Consider using std::promise::set_exception to propagate the error out to the caller so that it could be handled.

In particular, the code for tickfunction might include something like this:

    try {
        throw runtime_error("aaaah!");
    } catch (...) {
        valuePosted = true;
        throw;
    }

The calling function could then include something like this:

try {
    t.get();
} catch (std::exception &err) {
    std::cout << err.what() << '\n';
}

This allows you to catch an exception that might have been thrown within the spawned thread.

Consider making the class generic

One can easily imagine that doing something on a regular basis (i.e. every x seconds) might be useful beyond this singular usage.  For that reason, it might be useful to think about either passing a void function into the constructor or creating a template that uses a Callable type for later invocation.


Trim string of words based on character count

Yes, it's extremely inefficient, because in every iteration you count the number of words twice: once in count_words, and then wp_trim_words internally has to count the words again.

Another problem is that the method won't work for content that is many words larger than the target limit length. For example with a content of 4000 chars and a limit of 100, due to the if ($count > 10) break check in the middle, the method will basically cut off the last 10 words and return a still very large content. Not sure if that was part of your plan.

I don't really know PHP. But here's a naive implementation that should be more efficient and work with long content too:

function is_letter($char) {
    return ctype_alpha($char) || in_array($char, ['-']);
}

function custom_length_excerpt_max_char($content, $max_chars_limit) {
    if (strlen($content) < $max_chars_limit) {
        return $content;
    }
    $cut_at = $max_chars_limit;
    for (; $cut_at >= 0 && is_letter($content{$cut_at}); --$cut_at);
    return substr($content, 0, $cut_at);
}

function test_custom_length_excerpt_max_char() {
    $sample = 'some sample-text some sample-text';
    for ($i = 5; $i < strlen($sample) + 10; ++$i) {
        echo custom_length_excerpt_max_char($sample, $i)."\n";
    }
}

Here's the logic behind the main function:

If the content is shorter than the limit, return it
Iterate backward from the target limit position, until you find something that's NOT a letter, and break the content there.

If you run the test function, the output is something like:

...
some
some
some sample-text
some sample-text
some sample-text
some sample-text
some sample-text
some sample-text some
some sample-text some
some sample-text some
...


Do I need still to be concerned about favouring str_replace over preg_replace in PHP 7?

Most of such advises are crystal clear bullshit, on so many levels. You need to understand that such recommendations are never a result of some quality research, but just a rephrase of some vague rumor. The internet is full of chimpanzees.

This particular advise didn't make any sense even for PHP5.

That said, a set of consequent function calls apparently should be less efficient than a single call (but again if only it made any real life difference whatsoever).

That said, str_replace accepts array arguments, so it can be

$Page = str_replace(['-&-','-&amp;-','&amp;','-and-','-et-','-und-','-y-'], '-[+]-', $Page);

But you can use whatever version you like, as any difference is unnoticeable. Personally I find preg_replace() approach the cleanest and would prefer that.

As a rule of thumb, do not trust some random pieces of advise from Internet, especially performance-related. It's always just random rubbish. Bother with any optimizations only if your code actually has performance issues. And even in this case do not optimize random irrelevant parts but find the actual bottleneck and optimize it.


How about don't go to the next element before the loop, just check for the counter to reach zero, get the next element first in the loop, and the use a conditional operator to determine how to change the counter:

skipElement : function() {
  if (this.eventType !== Jsonix.XML.Input.START_ELEMENT) {
    throw new Error("Parser must be on START_ELEMENT to skip element.");
  }
  var numberOfOpenTags = 1;
  var et;
  while (numberOfOpenTags > 0) {
    et = this.nextTag();
    numberOfOpenTags += et === Jsonix.XML.Input.START_ELEMENT ? 1 : -1;
  }
  return et;
}


Firstly, I don't see any "real" issues with this - you mostly have done an awesome job! I have a few recommendations though that might help this be a little more performant, readable, and refined:

Do you really need all of these to be instance/public variables? Later on when you instantiate an ImageSlider, are you going to need an external module to know about these properties? Most of them could probably be private with var
lastImage and currImage are improperly/confusingly named - really they should be lastIndex and currIndex, because they are storing the index of an image, not a reference to the image itself.
It is a common convention to store a reference to the current scope at the top of a constrctor function.
The prefix "_" (underscore) is usually used to mark a function as private (using var _animate, for example). The airbnb style guide shows a usage similar to yours here, but, it is a very bad idea and I can't imagine why they would spread it. If a variable is attached to this, i.e. this.anything/this['anything'], it is, in JavaScript, not private. Putting this _ prefix is incredibly unintuitive and many people have told them so. At first glance, I thought maybe you were using it to indicate that the property was a method (i.e., this.elem and this.images are properties, but this._animate and this._init are functions), but I see you have other methods that do not use this prefix. If you are going to use this prefix to denote that it is a function, definitely be consistent with it.
You can remove the typeof check by reversing your logic a bit.
Did you mean to use "this" here, or "self"? Be sure to be consistent.
Use jQuery chaining to reduce scope resolution - you were calling this.bottom twice but you only needed to resolve that variable once, since jQuery will return the element for chainability. You can break it onto two lines if you prefer as well.
Pass animate by reference to setInterval instead of creating an anonymous scope to wrap the item.
minusTwo and plusOne are, at least for me, difficult to understand. I have read the function a few times and still do not quite understand why these variables have this name.
Cache this.bottom and this.top in order to reduce scope resolution in this function, since you are using them both quite a bit.

Here is the code, slightly modified and rewritten with specific numeric callouts:

function ImageSlider(wrapper, images){

    // 3
    var self = this;

    // 1
    this.elem = wrapper;
    this.images = images;
    this.top = this.elem.find('#topImage');
    this.bottom = this.elem.find('#bottomImage');
    this.next = this.elem.find('#nextBtn');
    this.prev = this.elem.find('#prevBtn');

    // 2
    this.lastIndex = images.length - 1;
    this.currIndex = 1; // This is 1 as the first iteration is rendered in the HTML.
    this.interval;
    this.fadeTime = 400;
    this.sliderDelay = 4000 + this.fadeTime;

    // 4
    this._init = function(){

        $(window).on('load', function(){
            self.elem.css('height', self.top.height());
            self.next.show();
            self.prev.show();
            self._animate();
            self._startInterval();
            self.next.click(function(){
                clearInterval(self.interval);
                self._animate(true);
                self._startInterval();
            });

            self.prev.click(function(){
                clearInterval(self.interval);
                self._animate(false);
                self._startInterval();
            });
        });
    }

    /**
     * @param next boolean. True next, false prev
     */
    // 4, 5
    this._animate = function(next){
       if(!next){
         self.prevImage();
        } else {
          self.nextImage();
        }
    }

    this.nextImage = function(){
        self.currIndex++;

        // 6
        this.top.fadeOut(self.fadeTime, function(){
            self.bottom.addClass('active');
            self.top.attr('src', self.images[self.currIndex - 1]).show();

            if (self.currIndex > self.lastIndex) {
                self.currIndex = 0;
            }

            // 7
            self.bottom.removeClass('active').attr('src', self.images[self.currIndex]);
        });
    }

    this.prevImage = function(){

        // 9
        var minusTwo = self.currIndex - 2;

        switch (minusTwo){
            case -1:
                minusTwo = self.lastIndex;
                break;
            case -2:
                minusTwo = self.lastIndex - 1;
                break;
        }

        // 10
        var bottom = self.bottom,
            top    = self.top;

        bottom.attr('src', self.images[minusTwo]);
        top.fadeOut(self.fadeTime, function(){
            bottom.addClass('active');

            // 9
            var plusOne = minusTwo + 1;
            if (plusOne > self.lastIndex){
                plusOne = 0;
            }

            top.attr('src', self.images[minusTwo]).show();
            bottom.attr('src', self.images[plusOne]);
            bottom.removeClass('active');
            self.currIndex--;
            if(self.currIndex < 0){
                self.currIndex = self.lastIndex;
            }
        });
    }

    // 4
    this._startInterval = function(){
        // 8
        self.interval = setInterval(self._animate, self.sliderDelay);
    }

    // 4
    this._init();
}


First question: How do I make these type of links good for SEO

I can't confidently say that it's bad in its current state as I'm not too clued up on SEO, see this link for some more info https://webmasters.stackexchange.com/questions/15393/is-a-url-with-a-query-string-better-or-worse-for-seo-then-one-without-one

I'm guessing if you wanted to make it somewhat more human and or seo friendly you can set your route up as so:

Route::get('{search}/{color}/{etc}', [
  'uses' => 'SearchController@postSearchResults'
]);

Then you'd need to add some parameters to the controller:

public function postSearchResults($search, $color, $etc) {

        $query = DB::connection('mysql')->table('cards')
            ->where('name', 'LIKE', '%'.$search.'%')
            ->where('color', 'LIKE', '%'.$color.'%')
            ->where('etc', 'LIKE', '%'.$etc.'%')
            ->get();

        return parent::ajaxView('results', compact('query'));
}

Note: you may want to change your method name to getSearchResults() instead of postSearchResults(), as you are using the GET ajax method when calling the route, right?

and is this secure? It seems like it would be easy to inject code?

From the Laravel Documentation: http://laravel.com/docs/5.0/queries#introduction

  Note: The Laravel query builder uses PDO parameter binding throughout
  to protect your application against SQL injection attacks. There is no
  need to clean strings being passed as bindings.

Second question: After getting the corresponding input from the user, I have the following in my SearchController to deal with the input:

... your code

Is the above secure or is there something I should do in addition to make it secure?

I'd like to think it's pretty secure based on what is aforementioned regarding how the query builder works.

Finally, don't consider this a complete answer. I'd definitely do some more digging around or maybe someone with more knowledge will come and post another answer! All the best!


This looks good to me. A nice use of space, Everything is very clear and easy to read, just a couple of problems:

Magic Numbers / Strings

You have a few of these dotted about, a couple of examples:

ctor.Body.Instructions[1].Operand = context.Request["A"];

I have no idea what A signifies here, nor why it should be the first instruction's operand. Swap A with a const that gives that string a name describing its purpose. You can probably do the same for 1 in this scenario too, unless A's purpose is only FirstInstructionOperandCode or something similar.

Commenting

Your comments don't add anything to your code. A lot of them just describe what you're doing, which any maintenance programmer can work out by reading the actual code. Instead you should use your comments to describe why you're doing something, particularly if it breaks from the expected norms.

The most egregious example is this:

// Clear existing response.
context.Response.Clear();

Structure

The Write New Response section could be refactored out into a separate method, but unless you're writing these responses elsewhere, it's probably not going to give you any significant gains.


Cleaner way for coding a repetitive application of a function

What's wrong with straight recursion?

def ntimes[A](n:Int, f:A=>A, a:A):A = if (n==0) a else ntimes(n-1, f, f(a))

Another clean option is

Iterator.iterate(a)(f).drop(n).next


Data validation for preventing blank entries

Extract the input code into a method:

String getNonBlankInput(String prompt) {
   String input = JOptionPane.showInputDialog(prompt);

   while (input.equals("")) {
      JOptionPane.showMessageDialog(null, "Cannot accept blank entries!");
      input = JOptionPane.showInputDialog(prompt);
   }

   return input;
}

Usage:

String name = getNonBlankInput("Enter name: ");


You should exploit the structure of the password, if it has any. Here you have a 20 character password separated into four blocks of five characters each, joined with a -. So don't go on generating all combinations of length 23, only to throw most of them away.

You also str.join the guess, then convert it to a list, then replace the values and str.join it again. You could have saved yourself the first str.join entirely by directly converting to list.

You know the length of the password, so no need to hardcode it. Just get it from the real password (or, in a more realistic cracker, pass the length as a parameter).

With these small changes your code would become:

def guess_password(real):
    chars = string.ascii_uppercase + string.digits
    password_format = "-".join(["{}"*5] * 4)
    password_length = len(real) - 3
    for guess in itertools.product(chars, repeat=password_length):
        guess = password_format.format(*guess)
        if guess == real:
            return guess

Here I used some string formatting to get the right format.

Note also that the timing and output string are not in there. Instead make the former a decorator and the latter part of the calling code, which should be protected by a if __name__ == "__main__": guard to allow you to import from this script without running the brute force cracker:

from time import perf_counter
from functools import wraps

def timeit(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = perf_counter()
        ret = func(*args, **kwargs)
        print(f"Time elapsed: {perf_counter() - start}")
        return ret
    return wrapper

@timeit
def guess_password(real):
    ...

if __name__ == "__main__":
    real_password = 'E45E7-BYXJM-7STEY-K5H7L'
    if guess_password(real_password):
        print(f"Scan completed: {real_password}")

On my machine this takes 9.96 s ± 250 ms, whereas your code takes 12.3 s ± 2.87 s for the input string "AAAAA-AAAAA-AAAAA-FORTN".

But in the end you will always be limited by the fact that there are a lot of twenty character strings consisting of upper case letters and digits. Namely, there are \$36^{20} = 13,367,494,538,843,734,067,838,845,976,576\$ different passwords that need to be checked (well, statistically you only need to check half of them, on average, until you find your real password, but you might get unlucky). Not even writing your loop in Assembler is this going to run in less than days.


Menu Model class using Model-View-Presenter

I would separate the responsibility to load the file from this class.I think this class have more responsibilities of a Presenter than a model class. A good indicator of that is the method display and the method clear and seems to me that you are using the Observer pattern to inform the view that the model has changed, and this seems to be the work of a middle-man class (Presenter).

So the only 2 thing I would change is to create a class to make the load of the file, and I would use for-each instead iterator, seems to me that iterator is something used much more in C++ than in Java.

I hope this can help :)


Task Scheduler for small interval and one number of start

Good work. A few comments and questions.

In SchduleJob class, I think that DateTrigger and TaskId need to be defined as internal and the SchduleManager only need to set them. If they will be public, the concrete class may set them to some value and the manager will override it in the Schedule method.
I think you need to constraint the TaskId to be unique and the manager only set it with a unique validation. For user define name\id you the TaskName property.
According to section 2, in the Remove method, replace RemoveAll by Remove.
Consider to change the type to long\int instead string, I don't talk about performance but about meaning although string is also make sense.
If you prefer to use string for the id, use string.CompareOrdinal() for the comprasion.
I think all the logging (add, remove, start, stop, error) need to be in the manager. The ScheduleJob need to be dedicated to the job. It can handle exception if you want, but the manager need to log it also.
Make the ScheduleManager IDisposable is dangerhere. Its a singleton and no body going to use it with using statement, but if somebody will do it, it make a problem because your timer will be disposable...


Overall, I like this. It is concise, and neat, and all. My only beef is the nested ternaries.
In general, ternary operator precedence is complicated by the lack of blocks.... The need for the parenthesis on the modulo precedence makes the conditions clear ( (n % 15 == 0) ) and the actual indenting you have, makes the logic a little clearer, but precedence is not that simple, and I have seen bugs where subtle precedence problems have caused the wrong execution-path through the nested ternaries....
.... bottom line, is for simple statements, ternaries are great, but the readability is compromised when there are multi-levels of ternaries. Nice for small things, ugly for big.
I would have preferred if you made the coditionals more obvious ... by extracting to a function maybe... but that would ruin your 1-liner.....
How about ... (Shown in this ideone here):
Enumerable.Range(1,100).Select(
                    n =>
                    (n % 15 == 0) ? "FizzBuzz" :
                    (
                        (n % 3 == 0) ? "Fizz" :
                        (
                            (n % 5 == 0) ? "Buzz" :  n.ToString())
                        )
                    )
                    .ToList()
                    .ForEach(Console.WriteLine);

EDIT: The above answer is not as good as I wanted it to be.....
The exact problem with ternary precedence is that it is right-associative. This makes the logic potentially buggy, and hard to understand.....
Consider the ternaries:
expa = boola ? expc : expd;
expb = boolb ? expe : expf;

result = boolc ? expa : expb;

You can modify this to be:
expa = boola ? expc : expd;

result = boolc ? expa : boolb ? expe : expf;

Or, rewriting it in 'your' style, as:
expa = boola ? expc : expd;

result = boolc ? expa :
         boolb ? expe :
         expf;

But, you cannot 'inline' expa in the above as easily:
expb = boolb ? expe : expf;

result = boolc ? (boola ? expc : expd) : expb;

You need the parenthesis.
Inlining ternaries is just plain ugly.

Better solution
I regret suggesting to use the parenthesis to block the code in a more readable format. There is no more readable format, other than to extract the function, which is the 'right' thing to do:
    static private string FizzBuzz(int value)
    {
        if (value % 15 == 0)
        {
            return "FizzBuzz";
        }
        if (value % 3 == 0)
        {
            return "Fizz";
        }
        if (value % 5 == 0)
        {
            return "Buzz";
        }
        return value.ToString();
    }

    public static void Main()
    {
        foreach(var val in Enumerable.Range(1, 100).Select(n => FizzBuzz(n)))
            Console.WriteLine(val);
    }

Note, I have also undone the slow, and unnecessary conversion of the Enumerable to the ToList().ForEach() operation. Converting it to the list before re-converting it to an Enumeration is a waste of effort.
Bottom line, is that the 1-liner is not the best, or most readable format.
I have put this in an ideone, to show it working.


Convert JSON to a different format (nested json)

var found = false;

Using flag is not good practice.

This is better solution:

var movies = [
  {"name":"Ice Age 3", "language":"English", "year":"2012"},
  {"name":"Ice Age 3", "language":"French", "year":"2011"},
  {"name":"Ice Age 3", "language":"German", "year":"2013"},
  {"name":"Ice Age 4", "language":"German", "year":"2013"}
];

function convert(arr) {
    return $.map(unique(arr), function(name){
        return {
            name: name,
            details: $.grep(arr, function(item){
                return item.name == name
            })
        }
    });
}

function unique(arr) {
    var result = [];
    $.map(arr, function(item){
        if ($.inArray(item.name, result))
            result.push(item.name);
    })
    return result;
}

console.log(convert(movies));


Mostly just style
Why add the variable len inside the for loop. It is a constant so put it outside the loop as one.
The variable result is in function scope. Use var rather than let.
The variable rand does not change inside the loop so it should be a const.
The expression to get the random number does not need the (...) as operator precedence ensures that the | is applied correctly.
Add some spaces between operators for readability. eg (Math.random()*str.length)|0; is better as (Math.random() * str.length) | 0
One issue
The only problem is that you have one to many iterations. The last random value will always be to select from a 1 character string, so it is not needed. You need only iterate the string length minus one.
The rewrite
How I would rewrite your code. I personally don't like putting the let inside the for loop, so I put the declaration in the scope above. This is because for loops can have a lot of noise (clutter) and that reduces it a bit. Also the function is so short and simple variable names can be shortened without problem, I would make rand just the r.
function fisherYates(str) {
  var i, result = '';
  const len = str.length - 1;
  for (i = 0; i < len; i ++) {
    const r = Math.random() * str.length | 0;
    result += str[r];
    str = str.slice(0, r) + str.slice(r + 1);
  }
  return result + str;
}


Nicely written. The space saving trick you did with min stack is especially nice.

When you push, the conditions can be a bit simpler:

push(data) {
  if (this.minStack.isEmpty() && this.stack.isEmpty()) {
    this.minStack.push(data);
  } else if (data <= this.minStack.peek()) {
    this.minStack.push(data);
  }
  this.stack.push(data);
}

The min stack will only be empty when the stack is empty, so you can drop the second condition in the first if statement. And since the else if branch does the same thing as the if branch, you can combine them:

push(data) {
  if (this.minStack.isEmpty() || data <= this.minStack.peek()) {
    this.minStack.push(data);
  }
  this.stack.push(data);
}


String.IndexOfAny(string, string[]) (lowest position for group of needles in haystack)

It seems that you've managed to fix the algorithm, so it does what it's supposed to do. But the concept is the same and performance isn't improved.

Still you could use some more descriptive names, and i instead of j1 (why 1?).

You could use foreach (string target in targets) { ... } instead of for (int j1;...) because you don't use the index to anything and the performance for an array is about the same for the two for-concepts.

You ask for other algorithm types that improves performance.

One concept for the algorithm - that seems to improve the performance significantly - could be the following:

public static int IndexOfAny(this string text, params string[] targets)
{
  if (string.IsNullOrEmpty(text)) return -1;
  if (targets == null || targets.Length == 0) return -1;

  for (int i = 0; i < text.Length; i++)
  {
    foreach (string target in targets)
    {
      if (i + target.Length <= text.Length && target == text.Substring(i, target.Length))
        return i;
    }
  }

  return -1;
}

Another that can improve performance even more is the following written in pseudo code - leaving it as a challenge for you to implement it in C#:

IndexOfAny text targets:
    for i = 0 to len(text)-1:
        skip = len(text)
        foreach target in targets:
            target_can_skip = 0
            for k = 0 to len(target)-1:
                if target[k] <> text[i+k]:
                    target_can_skip = count how many chars that can be skipped in text before target can be a candidate again
                    break
            if k == len(target):
                return i

            skip = min(skip, target_can_skip)

        if skip > 0:
            i = i + skip - 1

    return -1 // No match found

Besides that you may find inspiration here

Update according to VisualMelons comments:

The above implemented with string.IndexOf():

public static int IndexOfAny1(this string text, params string[] targets)
{
  if (string.IsNullOrEmpty(text)) return -1;
  if (targets == null || targets.Length == 0) return -1;

  for (int i = 0; i < text.Length; i++)
  {
    foreach (string target in targets)
    {
      if (i + target.Length <= text.Length && text.IndexOf(target, i, target.Length) == i)
        return i;
    }
  }

  return -1;
}

Notice that the count parameter must be at minimum the length of target or else it will not be found.

Test case:

  Stopwatch watch = Stopwatch.StartNew();
  IndexOfAnyDelegate[] funcs = new IndexOfAnyDelegate[]
  {
    Extensions.IndexOfAny,
    //Extensions.IndexOfAny1,
  };

    int sum = 0;

    for (int i = 0; i < 10000; i++)
    {
      foreach (var func in funcs)
      {
        sum += func("foo bar baz", "foo", "barz", "baz", " ");
        sum += func("aabbccddeeffgghh", "bbb", "hh", "aaa", "fg");
        sum += func("abcabc", "c", "abc");
        sum += func("abcabc", "x", "wer");
        sum += func("adfaææwjerqijaæsdklfjaeoirweqærqkljadfaewrwexwer", "xxxxx", "yyyyy", "zzzzz", "Aaaaaa", "x", "wer");

        //Console.WriteLine($"IndexOfAny should be 8: {func("foo bar baz", "barz", "baz", " ", "foo")}");
        //Console.WriteLine($"IndexOfAny should be 0: {func("aabbccddeeffgghh", "bbb", "hh", "aaa", "fg")}");
        //Console.WriteLine($"IndexOfAny should be 0: {func("abcabc", "c", "abc")}");
        //Console.WriteLine($"IndexOfAny should be 0: {func("abcabc", "x", "wer")}");
        //Console.WriteLine(func("adfaææwjerqijaæsdklfjaeoirweqærqkljadfaewrwexwer", "xxxxx", "yyyyy", "zzzzz", "Aaaaaa", "x", "wer"));
        //Console.WriteLine();
      }
    }
    watch.Stop();
    Console.WriteLine(sum);
    Console.WriteLine(watch.ElapsedMilliseconds);

You'll have to comment in/out as needed.

Update 2

The performance of the above pseudo code decreases (obviously) when the number of targets increases. So my analysis wasn't quite good enough. To optimize on that problem the below variant maintains an array of the next valid index per target, which minimize the number of targets that should be examined per char in the text string:

public static int IndexOfAny(this string text, params string[] targets)
{
  if (string.IsNullOrEmpty(text)) return -1;
  if (targets == null || targets.Length == 0) return -1;

  // Holds the next valid index in text per parget.
  int[] targetNextIndex = new int[targets.Length];

  for (int i = 0; i < text.Length; i++)
  {
    for (int j = 0; j < targets.Length; j++)
    {
      // If the targets next index isn't i then continue to next target
      if (targetNextIndex[j] > i)
        continue;

      string target = targets[j];
      int k = 0;

      for (; k < target.Length && i + k < text.Length; k++)
      {
        if (target[k] != text[i + k])
        {
          int nextIndex = i + 1;
          // Tries to find the next index in text where the char equals the first char in target.
          while (nextIndex < text.Length && target[0] != text[nextIndex])
          {
            nextIndex++;
          }
          // The next valid index for the target is found, so save it
          targetNextIndex[j] = nextIndex;
          break;
        }
      }

      if (k == target.Length)
      {
        return i;
      }
    }
  }

  return -1;
}


Create objects corresponding to whichever field has value from among a list of fields

This

const int STATUS_BASE = 1;
const int STATUS_FIN = 2;
const int STATUS_FINI = 3;
const int STATUS_WAST = 4;
const int STATUS_PRGR = 5;

screams for an enum like

public enum StockState
{
    Base = 1, Fin, Fini, Wast, Prgr
}

but you should rename the enumvalues in a way that you or Sam the maintainer doesn't has to guess about the meaning. If you or Sam have to fix a bug in 6 months it will be easier if your code can be graps at first glance. Just don't use abbreviations for naming things.

bool moveStock()

Based on the .NET Naming Guidlines methods should be named using PascalCase casing hence moveStock() should read MoveStock(). While we are at naming things I would name the method parameter sourceStockState which is IMO more clear.

stockStatus.date again properties should be named using PascalCase casing.

Because moveStock can't return false it should be void.

Let's get the meat. If you would change the createStockStatus() method in a way that it takes 2 additional parameters your moveStock() would get more readable because it would get shorter.

Assume the createStockStatus() would look like so

private void createStockStatus(StockStatus newObj, int quantityUOM, StockState state)
{
    if (!newObj.isValid()) { return; }

    newObj.quantityUOM = quantityUOM;
    newObj.state = (int)state;
    newObj.deleted = false;
    newObj.submittedId = null;
    UserPersonal user = context.UserPersonal.FirstOrDefault(u => u.email == currentUserEmail);
    newObj.setCreatedTimeStamp(user); //sets fields CreatedBy, ModifiedBy with value of user
    context.StockStatus.Add(newObj);
    context.SaveChanges();
}

then the former moveStock() could look like so

public void moveStock(WStockStatus fromStockStatus)
{
    StockStatus stockStatus = new StockStatus();
    stockStatus.date = fromStockStatus.date;
    stockStatus.location = fromStockStatus.location;

    if(fromStockStatus.qtyBase > 0)
    {
        createStockStatus(stockStatus, fromStockStatus.qtyBase, StockState.Base);
    }
    if(fromStockStatus.qtyFin > 0)
    {
        createStockStatus(stockStatus, fromStockStatus.qtyFin, StockState.Fin);
    }
    if(fromStockStatus.qtyFini > 0)
    {
        createStockStatus(stockStatus, fromStockStatus.qtyFini, StockState.Fini);
    }
    if(fromStockStatus.qtyWast > 0)
    {
        createStockStatus(stockStatus, fromStockStatus.qtyWast, StockState.Wast);
    }
    if(fromStockStatus.qtyPrgr > 0)
    {
        createStockStatus(stockStatus, fromStockStatus.qtyPrgr, StockState.Prgr);
    }
}

Edit

  But my main intention was to see if there is a better way by which I can avoid using these multiple if statements, like using a different data structure or use a different format of capturing the data.

By moving the if condition into createStockStatus() like so

private void createStockStatus(StockStatus newObj, int quantityUOM, StockState state)
{
    if (quantityUOM <= 0 || !newObj.isValid()) { return; }

    newObj.quantityUOM = quantityUOM;
    newObj.state = (int)state;
    newObj.deleted = false;
    newObj.submittedId = null;
    UserPersonal user = context.UserPersonal.FirstOrDefault(u => u.email == currentUserEmail);
    newObj.setCreatedTimeStamp(user); //sets fields CreatedBy, ModifiedBy with value of user
    context.StockStatus.Add(newObj);
    context.SaveChanges();
}

the moveStock() could look like so

public void moveStock(WStockStatus fromStockStatus)
{
    StockStatus stockStatus = new StockStatus();
    stockStatus.date = fromStockStatus.date;
    stockStatus.location = fromStockStatus.location;

    createStockStatus(stockStatus, fromStockStatus.qtyBase, StockState.Base);
    createStockStatus(stockStatus, fromStockStatus.qtyFin, StockState.Fin);
    createStockStatus(stockStatus, fromStockStatus.qtyFini, StockState.Fini);
    createStockStatus(stockStatus, fromStockStatus.qtyWast, StockState.Wast);
    createStockStatus(stockStatus, fromStockStatus.qtyPrgr, StockState.Prgr);

}


In programming there is the general principle Don't Repeat Yourself (DRY). Your code is a lot of repetition of exactly the same pattern, with only the string changing.

So, just put those strings into a dictionary, with the final variable name as keys:

RECEIPT_ITEMS = {"cp_poi": "POI", "cp_terminal": "Terminal",
                 "cp_merchant": "Merchant", "cp_period": "Periode",
                 "cp_transaction": "Transactie", "cp_card": "Kaart",
                 "cp_card_serial_number": "Kaartserienummer", "cp_date": "Datum",
                 "cp_authorisation_code": "Autorisatiecode",
                 "cp_total": "Totaal", "cp_card_type_id": "CardTypeId",
                 "cp_card_type_text": "CardTypeText",
                 "cp_drawer_amount": "DrawerAmount", "cp_drawer_id": "DrawerId",
                 "cp_cancelable": "Cancelable", "cp_card_type": "Leesmethode"}

def parse_card_payment(product):
    cp = dict.fromkeys(RECEIPT_ITEMS.keys())
    for line in product.splitlines():
        for key, value in RECEIPT_ITEMS.items():
            if value in line:
                cp[key] = line.split(":")[1].strip()
                break
    return cp

This has the advantage that if you ever have receipts in another language than Dutch (but with the same structure), you only need to localize the values of this dictionary and not change your whole code.

Note that I used str.splitlines, which automatically ignores trailing newlines.

A different approach might be to use a multi-line RegEx to perform the search directly, but that will probably be more complicated.


Let me focus on the Filter method.

There are a lot of repetitions in that method, which makes your code

harder to maintain

for example: replacing IndexOf to Equals
or by changing the StringComparison option to another

and more error-prone

for example: it is easy to misspell the All at one of the occurrences.

There are a couple of useful techniques that can make your code less error-prone and easier to change:

Using constants, like: const string all = "All";
Using single return, like: return concessionList.Where(predicate).ToList();
Extracting common logic, like:

static bool IsPresent(string source, string target)
   => source.IndexOf(target, StringComparison.InvariantCultureIgnoreCase) >= 0;

Using default values instead of fallback,

like: predicate can have default value instead of relying on a
final else block.

With these in our hand the Filter method could be rewritten like this:
private List<ConcessionModel> Filter(string product, string category, string status)
{
    const string all = "All";

    static bool IsPresent(string source, string target)
        => source.IndexOf(target, StringComparison.InvariantCultureIgnoreCase) >= 0;

    Func<ConcessionModel, bool> predicate = model =>
        IsPresent(model.Product, product) &&
        IsPresent(model.Category, category) &&
        IsPresent(model.Status, status);

    if (category == all && status != all)
    {
        predicate = model =>
            IsPresent(model.Product, product) &&
            IsPresent(model.Status, status);
    }
    else if (category != all && status == all)
    {
        predicate = model =>
            IsPresent(model.Product, product) &&
            IsPresent(model.Category, category);
    }
    else if (category == all && status == all)
    {
        predicate = model =>
            IsPresent(model.Product, product);
    }

    return concessionList.Where(predicate).ToList();
}

predicate: I've defined a function variable (Func<TInput, TOutput>)

It receives a ConcessionModel (as TInput)
and will return with a bool (as TOutput).

So, I have defined a function which implementation varies based on the input parameters.
We use this function as a filter condition (Where) against the data source (concessionList)

Here I have used the short form, but could be written like this:

return concessionList.Where(model => predicate(model)).ToList();


Perhaps something can be done shorter

A trick that I often use to avoid creating "filled" objects is simply matching on Just:

isIdentical:: Variable -> String -> String -> Bool
isIdentical (Variable (Just n) (Just u)) n' u' = n == n' && u == u'
isIdentical _ _ _ = False

You can even do the actual check inside the pattern guard:

(Variable (Just n) (Just u)) n' u' | n == n' && u == u' = True

But that seems like an overkill.

Not saying that this change is particularly warranted in this specific case, but it's a nice tool to have, I think.


Just put all those conditions into single IF using AND/OR. return limited queryset in ELSE branch.


It can be shortened and "beautified" by refactoring the bounds cyhecking and mine checking into internal method:
private boolean isWithinBounds(int x, int y) {
    return x >= 0 && y >= 0 && x < width && y < height;
}

private boolean isMine(int x, int y) {
    return field[x][y] == MINE;
}

Then the mine count becomes trivial (we can assume that the center of the 3x3 square does not have a mine, otherwise the player would have exploded and ended the game):
for (int x1 = x - 1; x1 <= x + 1; x1++) {
    for (int y1 = y - 1; y1 <= y + 1; y1++) {
        if (isWithinBounds(x1, y1) && isMine(x1, y1) {
            mineCount++;
        }
    }
}

What we have done is breaking code into methods, each of which implement a small and well defined function. Because each method does exactly one thing, they become easier to understand, maintain and test.
You should check Java naming conventions. Variable names should be in camelCase, startingWithSmallLetter.
Variable and method names should describe the reason why the code exists. E.g. mineSearch is confusing as the variable does not search mines, it just keeps count of them. Thus mineCount is a better alternative.
Counts is also confusing as it contains a value named MINE which obviously is a marker for a cell containing mine but it also contains the surrounding mine counts. I did a minesweeper clone (or actually a minesweeper solver) once and I used an array containing Cell-objects. The Cell object provided methods for querying the status of the cell (stepped on, flagged, unknown) and the number of surrounding mines if it had been stepped on.


Performance

Regex

regex.MustCompile() is very expensive! Do not use this method inside a loop !

instead, define your regex as global variables only once:

var (
    boldItalicReg = regexp.MustCompile(`\*\*\*(.*?)\*\*\*`)
    boldReg       = regexp.MustCompile(`\*\*(.*?)\*\*`)
    ...
)

Headers

If a line is a header, it will start by a #. We can check for this before calling ReplaceAllString() 6 times ! All we need
 to do is to trim the line, and then check if it starts with #:

line = strings.TrimSpace(line)
if strings.HasPrefix(line, "#") {
    // convert headings
    ...
}

We could go further and unrolling the loop to avoid unecessary allocations:

count := strings.Count(line, "#")
switch count {
case 1:
    line = h1Reg.ReplaceAllString(line, `<h1>$2</h1>`)
case 2:
    ...
}

Use a scanner

The idiomatic way to read a file line by line in go is to use a scanner. It takes an io.Reader as parameters, so you can directly pass
your mardown file instead of converting it into a string first:

func NewMarkdown(input io.Reader) string {

    scanner := bufio.NewScanner(input)
    for scanner.Scan() {

        line := scanner.Text()
        ...
    }
}

Use []byte instead of string

In go, a string is a read-only slice of bytes. Working with strings is usually more expensive than working with slice of bytes,
so use []byte instead of strings when you can:

line := scanner.Bytes()
line = boldItalicReg.ReplaceAll(line, []byte(`<b><i>$1</i></b>`))

Write result to a bytes.Buffer

Instead of string.Join(), we can use a buffer to write each line in order to further reduce the number of allocations:

buf := bytes.NewBuffer(nil)
scanner := bufio.NewScanner(input)
for scanner.Scan() {

    line := scanner.Bytes()
    ...
    buf.Write(line)
    buf.WriteByte('\n')
}

return buf.String()

final code:

package parse

import (
    "bufio"
    "bytes"
    "io"
    "regexp"
)

var (
    boldItalicReg = regexp.MustCompile(`\*\*\*(.*?)\*\*\*`)
    boldReg       = regexp.MustCompile(`\*\*(.*?)\*\*`)
    italicReg     = regexp.MustCompile(`\*(.*?)\*`)
    strikeReg     = regexp.MustCompile(`\~\~(.*?)\~\~`)
    underscoreReg = regexp.MustCompile(`__(.*?)__`)
    anchorReg     = regexp.MustCompile(`\[(.*?)\]\((.*?)\)[^\)]`)
    escapeReg     = regexp.MustCompile(`^\>(\s|)`)
    blockquoteReg = regexp.MustCompile(`\&gt\;(.*?)$`)
    backtipReg    = regexp.MustCompile("`(.*?)`")

    h1Reg = regexp.MustCompile(`^#(\s|)(.*?)$`)
    h2Reg = regexp.MustCompile(`^##(\s|)(.*?)$`)
    h3Reg = regexp.MustCompile(`^###(\s|)(.*?)$`)
    h4Reg = regexp.MustCompile(`^####(\s|)(.*?)$`)
    h5Reg = regexp.MustCompile(`^#####(\s|)(.*?)$`)
    h6Reg = regexp.MustCompile(`^######(\s|)(.*?)$`)
)

func NewMarkdown(input io.Reader) string {

    buf := bytes.NewBuffer(nil)

    scanner := bufio.NewScanner(input)
    for scanner.Scan() {

        line := bytes.TrimSpace(scanner.Bytes())
        if len(line) == 0 {
            buf.WriteByte('\n')
            continue
        }

        // wrap bold and italic text in "<b>" and "<i>" elements
        line = boldItalicReg.ReplaceAll(line, []byte(`<b><i>$1</i></b>`))
        line = boldReg.ReplaceAll(line, []byte(`<b>$1</b>`))
        line = italicReg.ReplaceAll(line, []byte(`<i>$1</i>`))
        // wrap strikethrough text in "<s>" tags
        line = strikeReg.ReplaceAll(line, []byte(`<s>$1</s>`))
        // wrap underscored text in "<u>" tags
        line = underscoreReg.ReplaceAll(line, []byte(`<u>$1</u>`))
        // convert links to anchor tags
        line = anchorReg.ReplaceAll(line, []byte(`<a href="$2">$1</a>`))
        // escape and wrap blockquotes in "<blockquote>" tags
        line = escapeReg.ReplaceAll(line, []byte(`&gt;`))
        line = blockquoteReg.ReplaceAll(line, []byte(`<blockquote>$1</blockquote>`))
        // wrap the content of backticks inside of "<code>" tags
        line = backtipReg.ReplaceAll(line, []byte(`<code>$1</code>`))
        // convert headings
        if line[0] == '#' {

            count := bytes.Count(line, []byte(`#`))
            switch count {
            case 1:
                line = h1Reg.ReplaceAll(line, []byte(`<h1>$2</h1>`))
            case 2:
                line = h2Reg.ReplaceAll(line, []byte(`<h2>$2</h2>`))
            case 3:
                line = h3Reg.ReplaceAll(line, []byte(`<h3>$2</h3>`))
            case 4:
                line = h4Reg.ReplaceAll(line, []byte(`<h4>$2</h4>`))
            case 5:
                line = h5Reg.ReplaceAll(line, []byte(`<h5>$2</h5>`))
            case 6:
                line = h6Reg.ReplaceAll(line, []byte(`<h6>$2</h6>`))
            }
        }
        buf.Write(line)
        buf.WriteByte('\n')
    }
    return buf.String()
}

Benchmarks

I used the folowing code for benchmarks, on a 20kB md file:

func BenchmarkMarkdown(b *testing.B) {

    md, err := ioutil.ReadFile("README.md")
    if err != nil {
        b.Fail()
    }
    raw := string(md)
    b.ResetTimer()

    for n := 0; n < b.N; n++ {
        _ = Markdown(raw)
    }
}

func BenchmarkMarkdownNew(b *testing.B) {

    for n := 0; n < b.N; n++ {
        file, err := os.Open("README.md")
        if err != nil {
            b.Fail()
        }
        _ = NewMarkdown(file)
        file.Close()
    }
}

Results:

> go test -bench=. -benchmem

goos: linux
goarch: amd64
BenchmarkMarkdown-4               10     104990431 ns/op    364617427 B/op    493813 allocs/op
BenchmarkMarkdownNew-4          1000       1464745 ns/op      379376 B/op      11085 allocs/op

benchstat diff:

name        old time/op    new time/op    delta
Markdown-4     105ms ± 0%       1ms ± 0%   ~     (p=1.000 n=1+1)

name        old alloc/op   new alloc/op   delta
Markdown-4     365MB ± 0%       0MB ± 0%   ~     (p=1.000 n=1+1)

name        old allocs/op  new allocs/op  delta
Markdown-4      494k ± 0%       11k ± 0%   ~     (p=1.000 n=1+1)


Your choice of data structures is unnecessarily heavy. You're interested only in the first and last index of a number, so store only those in a lightweight data structure of two integers (an array):

for (int i = 0; i < nums.length; i++) {
    final int num = nums[i];
    int[] span = spans.get(num);
    if (span == null) {
        span = new int[] { i, i };
        spans.put(num, span);
    } else {
        span[1] = i;
    }
}

Java comes with built in functions for selecting larger or smaller number from two, so use them instead of if-statements or ternary operations. It makes code easier to read.

// Empty set has maxSpan = 0
int maxSpan = 0;
for (int[] span: spans.values()) {
    maxSpan = Math.max(maxSpan, span[1] - span[0] + 1);
}
return maxSpan;

Avoid end-of-line comments. They make the code messy and are a pain in the ass to maintain. Avoid unnecessary comments that describe what code does. The reader can already see that the code iterates over values. Instead document why the code does what it does.

Use variable names that describe what the variable is used for. Value does not give any new information to the reader about what it contains.

Position as a name for a list is deceptive. It's singular form suggests that it contains one value when it instead contains all positions of a certain number.

Edit: You don't actually even need to store the last occurrence of a number. Just store the first one and calculate the maxSpan as you traverse the array the first time.

int maxSpan = 0;
for (int i = 0; i < nums.length; i++) {
    final int num = nums[i];
    Integer firstIndex = firstIndexes.get(num);
    if (firstIndex == null) {
        firstIndex = i;
        firstIndexes.put(num, firstIndex);
    }
    maxSpan = Math.max(maxSpan, i - firstIndex + 1);
}
return maxSpan;


C++ wrapper class for array of OpenGL buffer objects -- just the constructors

Some specific questions I have about this code/approach are, if applicable,

OK.

Error handling design decision: should the constructors throw, or should I leave error checking, if desired, to the caller?

Either the object is correctly initialized and ready to use or it should throw. Two stage initialization (construct then check) is a bad idea as it leaves it open to the user to do the correct thing. You should make sure your object can not be abused not relie on the user to not abuse you.

Design decision: is it a good idea to use templates here?

If you are going to use std::array you don't really have a choice.

Will this lead to problematic code bloat if I'm using a lot of different-sized buffer_objects, or is it efficient? Can I evaluate this through profiling?

Potentially this will lead to methods be compiled for different types. But this is compiler dependent and some modern compiler can optimize this out. But what are you comparing it too?

Are the memcpys worth it to put the rvalues in a valid non-owning state, or can I treat the rvalues as non-owning leftovers?

I think you need to null out the src values. Otherwise the destructor is going to release the names. Alternatively you can store more state about if the object is valid and make the call to glDeleteBuffers() conditional on the object being in a valid state.
But I also think there is a bug here. You have just copied over the values. But you did not release the values on the dst side before the copy so you have lost the names stored there.
Remember that a std::array does not have its own move (as the data is local to the object not dynamically allocated). It moves the underlying objects between containers.

Am I properly using the base class's move constructor?

Yes it seems ligit.
Suggestions.
I would make the std::array a member rather inherit from it.
I would do:
#ifndef THORSANVIL_GL_WRAPPER_H
#define THORSANVIL_GL_WRAPPER_H

#include <GL/gl.h>
#include <array>
#include <algorithm>
#include <cstring>

namespace ThorsAnvil::GL {

template<size_t N>
class BufferObjects
{
    std::array<GLuint, N>  buffer;
    bool                   valid;
    public:
        BufferObjects() noexcept;
       ~BufferObjects();

        // Note: These are non copyable objects.
        //       Deleting the copy operations.
        BufferObjects(BufferObjects const&)           = delete;
        BufferObjects operator=(BufferObjects const&) = delete;

        // Note: The move is as expensive as a copy operation.
        //       But we are doing a logical move as you
        //       can not have two objects with the same resource.
        BufferObjects(BufferObjects&& from)            noexcept;
        BufferObjects& operator=(BufferObjects&& from) noexcept;

        // Reset an invalid object.
        // Note: If object is valid no action.
        void reset();

};

template<size_t N>
BufferObjects<N>::BufferObjects() noexcept
    : valid(false)
{
    reset();
}

template<size_t N>
BufferObjects<N>::~BufferObjects()
{
    if (valid) {
        glDeleteBuffers(N, buffer.data());
    }
}

template<size_t N>
BufferObjects<N>::BufferObjects(BufferObjects<N>&& from) noexcept
{
    // Move the resources from the other object.
    std::move(std::begin(from.buffer), std::end(from.buffer), std::begin(buffer));

    // Maintain the correct valid states
    // The rhs is no longer in a valid state and has no resources.
    valid = from.valid;
    from.valid = false;
}

template<size_t N>
BufferObjects<N>& BufferObjects<N>::operator=(BufferObjects<N>&& from)
    noexcept
{
    // The standard copy and swap not efficient.
    // So we should do a test for self assignment
    if (this != &from)
    {
        // Destroy then re-create this object.
        // Call destructor and then placement new to use
        // the move copy constructor code to set this value.
        ~BufferObjects();
        new (this) BufferObjects(std::move(from));
    }
    return *this;
}

template<size_t N>
void BufferObjects::reset()
{
    if (!valid) {
        glGenBuffers(N, buffer.data());
        valid = true;
    }
}


Your current implementation is quite nice.

The only way you are going to avoid using the while loop to find the right-most node is if you have each individual branch maintain its branch's tail Node. This is a [sort of] good approach to the problem. However, once you reach this point, a Node really starts becoming more than just a Node: it now has information about the entire structure instead of what is directly around it.

So instead of modifying the Node class, you could create a Tree class.

This change makes sense:

Right now you manually create your 'tree'. This approach is not very portable. A Tree class can handle its own creation.
You need to store information about the entire branch structure somewhere. Inside a Node doesn't feel right.
You don't really flatten a Node, you flatten a tree of nodes. Thus, it again makes sense to move the flatten function inside a Tree class (or at least take a Tree parameter).

Here is a skeleton version of my Tree class. I have stubbed out all my methods except flatten as that is the function in question:

class Tree(object):
    def __init__(self, root=None):
        self.root = root
        self.tail = root
        self.length = 1 if root else 0

    def __iter__(self):
        ''' Allows iteration through the tree using `for node in tree`. '''
        pass

    def __getitem__(self, index):
        ''' Fetches the `Node` at the passed index. '''
        pass

    def grow(self, nodes):
        ''' Appends node/nodes/Tree onto itself. Be careful when adding `Node`
            we need to append a *copy* of a `Node`, not the reference. '''
        pass

    def graft(self, tree, node_pos=0):
        ''' Grafts in another tree to this one. By default the new tree
            is grafted to the root of the tree. '''
        pass

    def flatten(self):
        ''' Returns the flattened version of itself. '''
        flat = Tree()
        for next in self:
            flat.grow(next)
            if next.child:
                flat.grow(next.child.flatten())
        return flat

In this version of flatten, we keep the recursive feel as we call a method with the same method declaration. However, we are not doing true recursion because the methods are bound to different objects, and thus are different methods.

In any case, the flatten function is really quite simple:

Create the new Tree we are going to modify and return.
Loop through the Nodes of the current tree.
Append the current Node.

3.1. If that Node has a child Tree, append the flattened version of that Tree.
Return the final flattened Tree.

Here is my Tree class plus your Node class in action:

one, two, three, four, five, six, seven, eight, nine = [Node(num) for num in xrange(1,10)]

tree = Tree(one)
tree.grow([two, three, five])

# Graft the new `Tree` to the 3rd `Node`.
tree.graft(Tree(eight), 3)

branch = Tree(six)
branch.grow(seven)

# Graft the new `Tree` to the 1st `Node`.
branch.graft(Tree(nine), 1)

tree.graft(branch, 1)

def flatten(tree):
    ''' A non-class version of the `flatten` function. '''
    flat = Tree()
    for next in tree:
        flat.grow(next)
        if next.child:
            flat.grow(flatten(next.child))
    return flat

print ' - '.join([str(node.value) for node in flatten(tree)])
print ' - '.join([str(node.value) for node in tree.flatten()])


Check whether string of braces, brackets, and parentheses is balanced

Your solution is complicated due to the use of three separate stacks:

For each closing character, you have to cross-validate the two other types of delimiters.  (If you had to handle a fourth type of matching characters, such as < and >, it would be even messier.)
At the end, you need to write !Object.values(brace).flat().length to verify that all of the stacks have been cleared.

I also think that the use of Object.freeze() is overkill.

Your removeBrace() helper can use Array.prototype.pop() instead.

Suggested solution

Keep all of the state in one combined stack.

const areBracesBalanced = brs => {
  let expectCloseStack = [];
  return [...brs].every(b => {
    switch (b) {
      case "(": return expectCloseStack.push(")");
      case "[": return expectCloseStack.push("]");
      case "{": return expectCloseStack.push("}");

      case ")":
      case "]":
      case "}":
        return expectCloseStack.pop() === b;
    }
  }) && !expectCloseStack.length;
};

console.log(areBracesBalanced("[({})](]"));


print array of previous smaller elements

This can be done in a single pass over input list with a stack to keep track of previous smaller elements. Note that the stack will have a sub-sequence that is sorted at any given point.

def FastSolve(v):
  res = []
  s = [-1]
  for x in v:
    while s[-1] >= x:
      s.pop()
    res.append(s[-1])
    s.append(x)
  return res

Note that this exact question has been asked before here and a very similar variation (next smaller instead of last) here - the latter question has an excellent detailed explanation of the O(n) solution and code examples.


Recursively generating flat XML elements from hierarchical data structure

I think the code could be made better by keeping all of the XML tree-building code together.  The recursive traversal of .sub_scores could be done using a generator function.

Additionally, you might want to reduce the punctuation noise by setting XML attributes using keyword arguments.

class Scorer:
    def generate_report(self, score):
        r = etree.Element('report', user=getpass.getuser(), time=timestamp())
        etree.SubElement(r, 'summary', tests=score.total(), …)
        etree.SubElement(r, 'results', file=self.results_path)
        samples = etree.SubElement(r, 'samples')
        for sample in self._samples(score):
            etree.SubElement(samples, 'sample', sample.report_attr())
        return r

    def _samples(data):
        # Some scores are wrappers that should not be included in output
        if not data.wrapper:
            yield data
        yield from _samples(data.sub_scores)

Alternatively, you could write _samples as a nested function.

class Scorer:
    def generate_report(self, score):
        def extract_samples(data):
            # Some scores are wrappers that should not be included in output
            if not data.wrapper:
                yield data
            yield from extract_samples(data.sub_scores)

        r = etree.Element('report', user=getpass.getuser(), time=timestamp())
        etree.SubElement(r, 'summary', tests=score.total(), …)
        etree.SubElement(r, 'results', file=self.results_path)
        samples = etree.SubElement(r, 'samples')
        for sample in extract_samples(score):
            etree.SubElement(samples, 'sample', sample.report_attr())
        return r


Counting and scoring two- and three-word phrases

So I redid your main loop to make it more pythonic.  The completed inner loop is below.  But first let us discuss some of the changes.

If space allows, build intermediate data structure to ease later processing

So this bit of code recasts the word list into a single list that is more readily processed in the main loop.

words_x = [re.sub('[^0-9a-zA-Z]+', '', w) for w in words] + ['', '']

It does:

Add some padding at the end for end of list processing.  I wasn't sure that this was actually accurate to the described algorithm, but it does emulate the existing behavior.
Perform the regex substitution only once.

If space does not allow building another data structure, the itertools module has various tools that may allow efficient iterating over a data structures, and is often worth investigating.

zip() allows processing more than one list at a time

So I restructured the loop to look like:

for w, w1, w2 in zip(words_x, words_x[1:], words_x[2:]):

This iterates through without the need for a list index and gets three adjacent words each iteration.

zip() works by iterating through each of its arguments, and presenting the first element of each list the first time it is called, and then the second element of each list, and then...  And by calling it with the same list but starting at the 1st, 2nd and 3rd elements respectively, we can get three adjacent elements each iteration.

Use collections.Counter

So python has a nifty data structure that acts a lot like a dictionary but is used for counting.  It is oddly enough called Counter.

Counter allows replacing:

try:
    phrases[p] = phrases[p] + 1
except:
    phrases[p] = 1

with:

phrases[w] += 1

Code:

from collections import Counter

words = ("lorem", "ipsum", "lorem", "ipsum", "quick", "brown", "fox")
words_x = [re.sub('[^0-9a-zA-Z]+', '', w) for w in words] + ['', '']

phrases = Counter()
for w, w1, w2 in zip(words_x, words_x[1:], words_x[2:]):

    if len(w) > 1 and not w.isdigit():
        if w1:
            w += ' ' + w1
        phrases[w] += 1
        if w2:
            w += ' ' + w2
        phrases[w] += 1

Bugs?:

Code walks off the end of the list:

The current code walks off the end of the list.  The effect of this can be seen by the fact that the single word 'fox' ends up in the phrases list.  The current code looks for any phrase that exists more than once, so this word is eventually dropped, but...

At the end of the list the last two word phrase double counted as a three word phrase

In the current code, brown fox is counted twice.

The code below fixes both terminal condition problems.

Revised Code:

from collections import Counter

words = ("lorem", "ipsum", "lorem", "ipsum", "quick", "brown", "fox")
REMOVE_EXTRA = re.compile(r'[^0-9a-zA-Z]+')
words_x = [REMOVE_EXTRA.sub('', w) for w in words] + ['']

phrases = Counter()
for w, w1, w2 in zip(words_x, words_x[1:], words_x[2:]):

    if len(w) > 1 and not w.isdigit():
        if w1:
            w += ' ' + w1
        phrases[w] += 1
        if w2:
            # only count as three word phrase if w2 is not blank
            phrases[w + ' ' + w2] += 1