Simple addition calculator accepting addition expressions

Instance method vs. class method vs. function:
You declared a constructor function Calculator whose instances all come with their own individual calculate method. Since the calculate method doesn't rely on other instance properties, it should probably be a class method instead.
In JavaScript, a class method is simply a property of the constructor function:
function Calculator() { ... }

Calculator.calculate = function(sum) { ... };

Using class syntax, this is equivalent to:
class Calculator {
  ...
  static calculate(sum) { ... }
}

However, unless your Calculator will have additional properties later on, a simple function calculate(sum) { ... } instead of a class will do the job just fine.
Instance properties and side effects:
Within your calculate method, you create new instance properties such as this.sumArr, this.newSum and this.summ holding the result of the calculation. This is called a side effect. Pure functions without such side effects are easier to understand and debug.
Also, those property names are not very descriptive.
Consistency:
For different inputs, the values of this.summ and the return values of calculate(sum) are inconsistent:
sum         calculate(sum)  this.summ
-------------------------------------
undefined   TypeError       0
""          undefined       0
"1 x 1"     undefined       0
"1 + x"     NaN             NaN

Filtering your operands with number > 0 leads to strange effects such as returning NaN for inputs with a zero such as 0 + 1 and returning 1 for input bla - bla + 3 + 2.
Parsing:
Instead of parseInt(str) I recommend using the unary plus operator +str which is "the fastest and preferred way of converting something into a number" according to MDN.
To split an expression into operands and operator, I recommend using robust regular expressions. A regular expression makes it much easier to understand which input strings will be accepted as valid and which input strings will be rejected.
Implementation:
First, the available operations are declared. Then, the input is parsed. For valid input, the result of the operation is returned. For invalid (non-matching) input, undefined is returned:

function calculate(expression) {
  const operations = {
    '+': (left, right) => left + right,
    '-': (left, right) => left - right,
  };
  const [match, left, op, right] = expression.match(/^(\d+) (\+|\-) (\d+)$/) || [];
  return match ? operations[op](+left, +right) : undefined;
}

// Example:
console.log(calculate("3 + 7")); // 10
console.log(calculate("3 - 7")); // -4

Replacing above regular expression with e.g. a much more refined ^\s*([\+\-]?(?:\d*[.])?\d+)\s*(\+|\-)\s*([\+\-]?(?:\d*[.])?\d+)\s*$/ allows you to capture floating point numbers, negative numbers and whitespace. To support more operations, simply append them to the operations object literal, e.g. '*': (left, right) => left * right and add \* to the operator capture group within the regular expression.


Cryptographic range based random number generator class

When dealing with fair randomness and bit manipulation code, you have to be a lot more careful than you currently are.

Your random number generator is not fair, i.e. not all numbers have exactly the same possibility of being returned. Have a look at Java's implementation of java.util.Random or the Python standard library, which are all open source and good learning resources.

When you do integer calculations, don't use floating point calculations internally. They are very tricky to do correctly. Think about rounding for every arithmetic operation.

Shuffling is not the same as sorting. Read the Wikipedia article on shuffling (or any other article) to get this right.

Your Next() function is documented to return a 32-bit integer, but that integer has a little less than 31 bits of randomness. Therefore the documentation is misleading. To properly implement this method, you should get 32 bits of randomness from the underlying random generator, and if you only want positive numbers, return rnd & Integer.MaxValue. This gives you exactly 31 bits of randomness, and this is also what the documentation should say.

In the Next(min, max) function, you must throw an exception if min == max. Your current code returns max in that case, but the documentation says that max is exclusive.

And finally, remove redundant documentation comments. Having an empty <param name=min></param> comment is worthless, since it doesn't add any information. The code already says clearly that there is a parameter called min, and the comment should not repeat this. If you had written some additional information in that comment (like you did in the summary), it would be ok.


Challenge: solution for this deep-iteration JavaScript function dilemma?

Let me start by asking how would you like to iterate over your object? Because what you are doing is not the same as calling a function for every property of an object.

function iter(obj,fn,iter_pos){
    var ret, iter_pos = iter_pos || [];
    for (var i=0; i<obj.length; ++i)

The above for loop may access elements in the array that are not even defined. For example, take this array:

var a = [0, 1];
a[9] = 9;
console.log(a.length);  // -> 10
console.log(a.hasOwnProperty(0)); // -> true
console.log(a.hasOwnProperty(1)); // -> true
console.log(a.hasOwnProperty(2)); // -> false !!
console.log(a.hasOwnProperty(9)); // -> true

The above array has a length of 10, but it only has three properties (it has 10 elements, but not all are defined). If you do an a.forEach(), you'll iterate over the array's properties, only those that are defined.

If you do a for (i=0; i<a.length; i++) loop over the array, you'll get properties that are not defined. To avoid those, you should check a.hasOwnProperty(). Or just use the native forEach, if you can, that will iterate over the array correctly.

Note that checking against undefined would not be sufficient either, array elements can be present but undefined:

a[5] = undefined;
console.log(a.hasOwnProperty(5)); // -> true !!

        if (ret = typeof(obj[i]) == "object" ? iter(obj[i],fn,iter_pos.concat(i)) : fn(iter_pos.concat(i),obj[i]))
            return ret;
    for (var key in obj)
        if (isNaN(Number(key)))

Here you're trying to do the opposite of forEach: enumerating properties that are not elements of the array.

But this code will miss properties that still evaluate as numbers! Have a look at the following array:

var a = [0, 1, 2, 3, 4];
a[100] = 99;
a[1.5] = 'this is not an array element';
a[-1] = 'this one is not an array element either';
a['20'] = 'this one *is* an array element!';

Also, watch out for rounding:

a[30.00000000000001] = 'this is *not* an array element';
a[30.000000000000001] = 'this *is*, however, because it rounds to 30'

But also for the string representations:

a[30.000000000000001] = 'array element';
a['30.000000000000001'] = 'not array element';

Especially the ones that evaluate the same:

a[1e1] = 'element number ten';
a['1e1'] = 'a completely different element';

'-1', '1.5', '1e1', '30.000000000000001', etc. can all be properties of an array, but they will all evaluate false for isNaN(Number(key)).

            if (ret = typeof(obj[key]) == "object" ? iter(obj[key],fn,iter_pos.concat(key)) : fn(iter_pos.concat(key),obj[key]))
                return ret;
};

You can easily fix your script by changing the line

        if (isNaN(Number(key)))

to

        if (!key.match(/^\d+$/))

, but unfortunately that makes your code about 18% slower.

TL; DR

I've removed the double loop from your code:

function iter(obj, fn, iter_pos){
    var ret, iter_pos = iter_pos || [];
    for (var key in obj)
        if (ret = typeof(obj[key]) == "object" ? iter(obj[key], fn, iter_pos.concat(key)) : fn(iter_pos.concat(key), obj[key]))
            return ret;
};

and it does not seem to be any slower, or at least not according to jsperf.com/iter.

I tried it in a number of browsers I could find.

UPDATE 1:

Here is a version that uses two loops, but is much faster. It will fix the ordering, but only in cases where the array indexes come before other array properties.

__toString = Object.prototype.toString;

function iter(obj, fn, iter_pos) {
    var ret, i = 0,
        iter_pos = iter_pos || [];
    if (__toString.call(obj) === '[object Array]') {
        obj.forEach(function (item) {
            if (!ret) {
                ret = typeof (obj[i]) === "object" ? iter(obj[i], fn, iter_pos.concat(i)) : fn(iter_pos.concat(i), obj[i]);
                i++;
            }
        });
        if (ret)
            return ret;
    }
    for (var key in obj)
        if (--i < 0)
            if (ret = typeof (obj[key]) === "object" ? iter(obj[key], fn, iter_pos.concat(key)) : fn(iter_pos.concat(key), obj[key])) return ret;
};

UPDATE 2:

This is your original version, with two loops, but using forEach and Object.prototype.toString. It seems to output the same result, but is about 2000× faster.

__toString = Object.prototype.toString;

function iter(obj, fn, iter_pos) {
    var ret, iter_pos = iter_pos || [];
    if (__toString.call(obj) === '[object Array]') {
        obj.forEach(function (item) {
            if (!ret)
                ret = typeof (obj[i]) === "object" ? iter(obj[i], fn, iter_pos.concat(i)) : fn(iter_pos.concat(i), obj[i]);
        });
        if (ret)
            return ret;
    }
    for (var key in obj)
        if (!("" + key).match(/^\d+$/))
            if (ret = typeof (obj[key]) === "object" ? iter(obj[key], fn, iter_pos.concat(key)) : fn(iter_pos.concat(key), obj[key]))
                return ret;
};

UPDATE 3:

This version is about as fast as the other one, but uses only Object.prototype.toString and does not use typeof.

__toString = Object.prototype.toString;

function iter(obj, fn, iter_pos) {
    var ret, obj_type, iter_pos = iter_pos || [];
    if (__toString.call(obj) === '[object Array]') {
        obj.forEach(function (item) {
            if (!ret)
                ret = ((obj_type = __toString.call(item)) === "[object Object]") || (obj_type === "[object Array]") ? iter(item, fn, iter_pos.concat(i)) : fn(iter_pos.concat(i), item);
        });
        if (ret)
            return ret;
    }
    for (var key in obj)
        if (!("" + key).match(/^\d+$/))
            if (ret = ((obj_type = __toString.call(item)) === "[object Object]") || (obj_type === "[object Array]") ? iter(obj[key], fn, iter_pos.concat(i)) : fn(iter_pos.concat(i), obj[key]));
                return ret
};


Given Sum of sub sums of an integer find the original integer

It seems to me that you could find an approximate solution easily.
Maybe you could then use this knowledge to iterate through less numbers.

When checking your number, you do this operation for D = 4: a + truncate(a/10) + truncate(a/100) + truncate(a/1000), which can be quite close to the float a + a/10 + a/100 + a/1000, but not exactly the same value as any of the terms might not be an integer value.

Basically, the float computation is a * 1.111, and the result is probably not too far from your number N.

If you take N / 1.111, that should bring you pretty close to your desired number. In your example, 2148 / 1.111 = 1933.39.

You also know that the float value that you find with this division is lower than the one you want, because of truncations.

A naive way would be to start from this value, and iterate until you find a solution. I am not sure how well this would be compared to your binary search, but this could already be something worth trying.

EDIT

Just another thought: you can also take into account that the sum of digits must match the last digit of N during your iteration (1 + 9 + 3 + 5) % 10 = 8 = 2148 % 10, this will help iterate only 9 by 9 instead of 1 by 1.


PHP - How can I refactor this store function (which handles different database operation for user types) in order to reduce duplication?

I think it's a very good case to employ OOP, namely polymorphism and inheritance.

First, we've got to create a dedicated class to handle the user preferences.

A common ancestor to hold all the common code

abstract class UserPreferences
{
    protected $userId;
    protected $db;

    public function __construct($userId, $db) {
        $this->userId = $userId;
        $this->db = $db;
    }
    protected function addGeneric($preferences) {
        $sql = "INSERT INTO preferences (...) VALUES (?,?,?)";
        $this->db->prepare($sql)->execute($preferences);
    }

    abstract protected function addSpecific($preferences);

    public function add($preferences)
    {
        $this->db->beginTransaction();

        try {
            $this->addGeneric($preferences);
            $this->addSpecific($preferences);
            $this->db->commit();
        } catch(Throwable $e){
            $this->db->rollBack();
            throw $e;
        }
    }
}

and then implementations for different types

class AdminPreferences extends UserPreferences
{
    protected function addSpecific($preferences) {
        $sql = "INSERT INTO admin_preferences (...) VALUES (?,?,?)";
        $this->db->prepare($sql)->execute($preferences);
    }
}

class SalesPreferences extends UserPreferences
{
    protected function addSpecific($preferences) {
        $sql = "INSERT INTO sales_preferences (...) VALUES (?,?,?)";
        $this->db->prepare($sql)->execute($preferences);
    }
}

...and so on.

Then in the User class create an instance of the Preferences class

class User
{
    public $preferences;
    public function __construct($db, $type) {
        $this->userId = $userId;
        $this->db = $db;
        $this->preferences = $this->setPreferences($db, $type);
    }
    protected function setPreferences($db, $type) {
        switch($type) {
            case 'Admin':
                $this->preferences = new AdminPreferences($db);
                break;
            case 'Sales':
                $this->preferences = new SalesPreferences($db);
                break;
        }
    }
}

the same goes for the statistics

and finally in your controller simply

$preferences = $parsedBody['preferences'];
$this->User->preferences->add($preferences);
$this->User->preferencesStatistics->add($preferences);

return $response->withJSON([
    "error" => false,
    "message" => "operation completed successfully"
    "data" => null
]);

Note that checking $preferenceAdded manually is not the way to go. There should be a dedicated error handler to do the job.


OnKeyPress event do same stuff on multiple inputs

There are in fact different ways to handle your request. Here's one I'd like to show as it is:

re-useable (As you can use it on any element everywhere on the page multiple times.)
decoupled from the HTML markup and from CSS classes

HTML

Add a data-*-attribute to the fields where the magic should happen:

<input type="text" name="a" value="a" data-log>

JavaScript

query those specific elements
attach the event handler to each element
run your code

The ES5 way:

var logMe = document.querySelectorAll('[data-log]');

for (var i = 0, max = logMe.length; i < max; i++) {
    logMe[i].addEventListener('keypress', function(event) {
        if (13 == event.which) {
            console.log(this.value);
        }
    }, false);
}

Try it online.

The ES6 way:

let logMe = document.querySelectorAll('[data-log]');

for (let item of logMe) {
    item.addEventListener('keypress', function(event) {
        if (13 == event.which) {
            console.log(this.value);
        }
    }, false);
}

Try it online.

That being said, you can alternatively use CSS classes as well to identify the elements:

<input class="log" type="text" name="a" value="a">

And select the elements using:

let logMe = document.getElementsByClassName('log');


Avoiding an if statement is not a useful goal. Occasionally it is the correct means towards a goal, such as making code easier to write or to understand. Thus I think your question is too narrowly focused, or oversimplified. The problem here is that the wrapper function _create_object is too simple to merit being its own function, and the complexity outside of it matches that inside.

Let's consider some small transformations of this. First we'll take the if data outside of _create_object. I do this because I find the current implementation is close to do-what-I-mean. This may have been less true if the conditions were more intricate.

def _create_object(data):
    return Object(data)

if data:
    mylist.append(_create_object(data))

From there it's pretty obvious that _create_object is another spelling of Object, and the final transformation is to just remove the wrapper:

if data:
    mylist.append(Object(data))

Let's take a step further back and assume you're pulling subsequent values of data from a list that I'll call data_source. You can avoid the kind of if statement you had before by writing either a list comprehension (with embedded if), or using filter:

mylist += [Object(data) for data in data_source if data]
# or
mylist += [Object(data) for data in filter(None, data_source)]
# or, if _create_object's conditions are too complex for this transformation
mylist += [_create_object(data) for data in data_source if _create_object(data)]
# or, two-layers
mylist += filter(None, [_create_object(data) for data in data_source])

Note that I don't particularly like the third as it calls _create_object twice per item, but the fourth one requires your second wrapper - the one that returns None.

As for whether you should be using exceptions, the answer is two-fold. If you're dealing with a large number of false values in data, and this is in an inner loop, performance could be a problem. In cases like that, it can make sense to implement the look-before-you-leap semantics of your other examples. However, if Object cannot reasonably construct itself from a false data parameter, it should itself raise an exception. That way if a given caller doesn't check first, it will result in a clear fixable error.


Merge Sort Implementation and Optimization

pop(0) has a linear time complexity, which makes the entire time complexity quadratic.

The single most important advantage of merge sort is stability: the elements compare equal retain their original order. In your code, if two elements are equal the one from the right is merged first, and stability is lost.


It could be shortened to:

function setAlphaNumeric() {
  $(".numeric, .alpha, .alphanumeric").each(function() {
    $(this)[this.className]({
      allow: $(this).attr("char-allow")
    });
  });
}

$(setAlphaNumeric);


Python script to identify regex matches in all subdirs and write dict of matches to MongoDB

f.readlines() is redundant. Just iterate over the file: for i, line in enumerate(f):, or, as you are not using i at all: for line in f:
d.setdefault becomes redundant if you use d = collections.defaultdict(list)


One way to simplify the problem is a shift of datastructure to hold your islands. By converting the grid to a set containing only the "land" parts, you can speed up the computation by entirely removing the check for "does it fit into the map". The idea here is to pick a land in your set — doing so you'll know that you have discovered a new island — and remove all land connected to it in your set. Luckily set.remove is easy to use and let us know if the element was present or not so we can stop the recursion.

I would also advise against using explict len to iterate over the grid. enumerate should give you anything you need in a more cleaner way.

Lastly, in the testing code, grid is

[['1', '1', '0', '0', '0'],
 [' ', ' ', ' ', ' ', '1', '1', '0', '0', '0'],
 [' ', ' ', ' ', ' ', '0', '0', '1', '0', '0'],
 [' ', ' ', ' ', ' ', '0', '0', '0', '1', '1']]

So you might have some inexpected results. I suggest the use of the textwrap module like so:

if __name__ == '__main__':
    from textwrap import dedent
    grid = dedent("""\
        11000
        11000
        00100
        000111""")
    ...

Revised algorithm would look like:

class Solution(object):
    def numIslands(self, grid):
        """
        :type grid: List[List[str]]
        :rtype: int
        """

        # Convert the grid to a bag of land
        self.lands = {
            (row, col)
            for row, line in enumerate(grid)
            for col, land in enumerate(line)
            if land == '1'
        }

        island_counter = 0
        # Remove islands from the bag one by one
        while self.lands:
            island_seed = next(iter(self.lands))  # pick a random land
            island_counter += 1
            self.remove_island(island_seed)

        return island_counter

    def remove_island(self, coordinates):
        try:
            self.lands.remove(coordinates)
        except KeyError:
            return

        x, y = coordinates
        self.remove_island((x - 1, y))
        self.remove_island((x + 1, y))
        self.remove_island((x, y - 1))
        self.remove_island((x, y + 1))

If you don't like remove_island being recursive, you can still write it as a BFS as you did in your solution. But since you’re not poping from the left, there is no need of a deque:

    def remove_island(self, coordinates):
        queue = [coordinates]
        while queue:
            x, y = queue.pop()
            try:
                self.lands.remove((x, y))
            except KeyError:
                pass
            else:
                queue += [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]


A third option is to use continuations:

public void DeleteAccount(string accountId, Action<string> OnAccountInUse, Func<string,bool> OnConfirmation)
{
    var bookingsUsingAccount = GetBookingsUsingAccount(accountId);
    if (bookingsUsingAccount.Count > 0)
    {
        OnAccountInUse("msg");
        return;
    }
    BankAccount account = GetAccount(accountId);
    if (OnConfirmation("confirm"))
    {
        account.Delete(false);
    }
}

edit: adding the usage, similar to the cases in the question

private void cmdDelete_enterClick(object sender, EventArgs e)
{
    var accountManager = new BLAccountManager();

    Func<string,bool> OnConfirmation = (msg) =>
    {
        var dialogResult = MessageBox.Show(msg);
        return (dialogResult == DialogResult.OK);
    };

    accountManager.DeleteAccount(selectedAccountId,
                                 (msg) => MessageBox.Show(msg),
                                 OnConfirmation);
}


Project Euler 4: Largest palindrome product in Functional Programming

For the cross product I used this code snippet:
https://stackoverflow.com/a/36234242

Slow as hell but seems to be fp with vanilla JS only:

/*jshint esversion: 6 */
(function () {
  'use strict';
  const isSymmetric = n => {
    const asString = n.toString();
    return asString === asString.split("")
      .reverse()
      .join("");
  };
  const range = num => Array.from(new Array(num), (_, i) => num - i);
  const from999To100 = range(999)
    .filter(x => x >= 100);

  //https://stackoverflow.com/questions/12303989/cartesian-product-of-multiple-arrays-in-javascript/36234242#36234242
  const cartesianProduct = arr => arr.reduce(
    (a, b) => a.map(
      x => b.map(
        y => x.concat(y)))
    .reduce((a, b) => a.concat(b), []), [
      []
    ]);

  const combinations = cartesianProduct([
    from999To100, from999To100
  ]);
  const solution = combinations.map(x => x[0] * x[1])
    .filter(isSymmetric)
    .reduce((acc, x) => acc < x ? x : acc, 0);
  console.log("solution ", solution);
})();


Car store implementation using abstract factory

use protected instead of private

by making $sports and $family protected you could just override them within the child classes without having to use parrent::__construct.

interface vs abstract

why Interface for Car? It is not wrong or something but since you are asking for feedback i would recommend to use an abstract class for Car and extend it for implementations of car like Galaxy. You should ask yourself "what other object than specific cars would implement the interface "car" afaik no one.

But if you would have an Interface like ABS you could ask questions like "does instance of car implement ABS" which sounds more like the real world you are trying to model

separation of sport && family cars

i dont know why you separate them like this, it looks like you could simplify the code a lot without this kind of separation.

my simplified take:

    <?php
namespace Car {

    abstract class Car
    {
    }

    class Shop
    {
        private $factory;

        public function __construct(\Car\Factory\Factory $factory)
        {
            $this->factory = $factory;
        }

        public function orderCar($name)
        {
            return $this->factory->makeCar($name);
        }
    }

abstract class Ford extends Car {}
class Mustang extends Ford {}

}
namespace Car\Factory{
abstract class Factory {

    protected $cars = array();
    abstract public function makeCar($name);
}

class Ford extends \Car\Factory\Factory {

    protected $cars = array("Mustang" => '\Car\Mustang');
    public function makeCar($name) {
        if (!isset($this->cars[$name])) {
            throw new \InvalidArgumentException(sprintf("%s %s \n", "invalid car name", $name));
        }

        return new $this->cars[$name];
    }

}
}
namespace App {

use Car\Factory\Ford as FordFactory;
use Car\Shop;

try {
    $fac = new FordFactory();
    $shop = new Shop($fac);
    $car = $shop->orderCar('Mustang');
    var_dump($car);

    if ($car instanceof \Car\Ford) {
        echo "real deal \n";
    }
} catch (\Exception $e) {
    print_r($e->getMessage());
}
}


function access variable in module.exports file in nodeJs

Since getfirst() and getsecond() are called only within parsefile.js, you can just define an object inside this file (something like this const local = {} at the top of your file) and use it instead of global.


Avoid mutable state

Mutable state, in this example the modifying of the x and y positions to draw,
causes all kinds of troubles.

For example, if you call the draw method a second time,
it will paint another board right after the first one.
This might be surprising to users.
Normally we expect that calling a method multiple times has the same effect,
which is often not the case with methods that mutate state.

Another common problem with mutable state is that it breaks thread-safety.
If draw gets called from multiple threads in parallel, it will most certainly paint rubbish.

Granted, you probably don't plan to call this method multiple times and from multiple threads.
But as a general good practice,
it's good to avoid mutable state when possible.

Using constants

Avoid hard-coded (magic) numbers. The number 8 is the SIZE of the board,
the number 64 is SIZE * SIZE. If you refer to them that way, the intention of the code becomes all the more clear. And if you decide to paint a larger (or smaller) board, you can change one value in one place.

Formatting

Instead of this:

private void updateTileColor(int tileNumber)
{
    if((tileNumber % 8) != 0)
    {
        tileColor = (tileColor == Color.WHITE) ? Color.BLACK : Color.WHITE;
    }
}

The convention is Java is this:

private void updateTileColor(int tileNumber) {
    if ((tileNumber % 8) != 0) {
        tileColor = (tileColor == Color.WHITE) ? Color.BLACK : Color.WHITE;
    }
}

If you use an IDE like IntelliJ or Eclipse,
the auto-reformat feature will format the code for you as per the convention.

Alternative implementation

Others have given you various alternatives,
here's mine, without mutating state,
and applying the suggestions above:

public class Checkerboard {

    private static final int SIZE = 8;

    private final int squareSize = 50;

    public void draw(Graphics2D g2) {
        for (int pos = 0; pos < SIZE * SIZE; pos++) {
            int x = calculateX(pos);
            int y = calculateY(pos);
            Color color = calculateColor(pos);

            Rectangle tile = new Rectangle(x, y, squareSize, squareSize);

            g2.setColor(color);
            g2.fill(tile);
        }
    }

    private int calculateX(int pos) {
        return (pos % 8) * squareSize;
    }

    private int calculateY(int pos) {
        return (pos / 8) * squareSize;
    }

    private Color calculateColor(int pos) {
        int offset = (pos % 16) < 8 ? 0 : 1;
        return (pos + offset) % 2 == 0 ? Color.WHITE : Color.BLACK;
    }
}


Test for an array being subset of another master array

So the key here is that I value code that's obvious to others.

Someone else is likely to try to stuff duplicate elements in unless it requires a type refactor; making const masterSet: Set<number> and using that throughout the code is a Good Idea. That "someone else" can often be you two months down the line, too.

In this case I would not say that the point of this length comparison is obvious; it will work but it takes some thinking -- that is why it has bugs with duplicate elements. In this case I would write something  which I find more straightforward like,

function isSubsetOf<x>(sub: Iterable<x>, sup: Set<x>): boolean {
  for (const x of sub) {
    if (!sup.has(x)) {
      return false;
    }
  }
  return true;
}

I am also hinting through the type system how this function works by insisting that the subset is any iterable -- so I must be iterating through it.

With a restriction to an array and a set, one can get a little swankier by using the reduce function,

function isSubsetOf<x>(sub: Array<x>, sup: Set<x>): boolean {
  return sub.reduce((acc, x) => acc && sup.has(x), true);
}

but probably not all other readers will find that as intuitive as I do, and the former has slightly better runtime characteristics on very large lists that are obviously not subsets.


Check if given number can be expressed as sum of 2 prime numbers

Some general remarks:

Use more horizontal space, for(i=0;i<t;i++) is difficult to read.
Use true and false from <stdbool.h> for boolean values, not
the integers 1 and 0.
Declare variables at the nearest scope where they are used, e.g.
in loops:

for (long long i = 2; i * i <= n; i++) { ... }

Always use braces { } in if-statements, even if there is only a
single statement to be executed in the if- or else-case.
Adding the braces easily forgotten if you add more statements later.
long long int is identical to long long. I prefer the latter,
but that is a matter of taste (or your coding style guidelines).

Now to your code:

The isPrime() functions treats n = 1 as a prime number, which
it isn't.
Separate the computation from the I/O. That makes the code more
organized and allows you to add test cases easily.

So the program should look like this:

#include <stdio.h>
#include <stdbool.h>

bool isPrime(long long n) {
    if (n < 2) {
        return false;
    }
    for (long long i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}

bool isSumOfTwoPrimes(long long n) {
    // ... check if `n` is the sum of two prime numbers ...
}

int main(void) {
    int t;
    scanf("%d", &t);
    for (int i = 0; i < t; i++) {
        long long n;
        scanf("%lld", &n);
        if (isSumOfTwoPrimes(n)) {
            printf("Yes\n");
        } else {
            printf("No\n");
        }
    }
    return 0;
}

Printing the result can also be done with a single statement:

        puts(isSumOfTwoPrimes(n) ? "Yes" : "No");

You  return true for all even numbers, which is correct because
 Goldbach's conjecture has already been proven for all even numbers in your range 1<=n<=1000000.

For odd numbers, the calculation can be simplified considerably.
If n = p + q is odd then p is even and q is odd, or vice versa.
Since 2 is the only even prime number, this reduces to check
if n - 2 is prime:

bool isSumOfTwoPrimes(long long n) {
    if (n < 4) {
        return false;
    }
    if (n % 2 == 0) {
        return true;
    }
    return isPrime(n - 2);
}

Note another advantage of the separate function: You can "early-return",
and that makes the "state variable" int prime from your code obsolete.

If the program is run with a large number of test cases, then a further improvement would be to pre-compute all prime numbers in the given range,
for example with the Sieve of Eratosthenes.


A few points to make about this:

(function () {
//    timedRefresh(10); //3600000
    delayedAlert();

    var timeoutID;

    function delayedAlert() {
        clearAlert();
      timeoutID = window.setTimeout(slowAlert, 10000);
    }

    function slowAlert() {
      alert("You may have been logged out due to inactivity. Click OK to refresh the page.");
    }

    function clearAlert() {
      window.clearTimeout(timeoutID);
    }
})();

slowAlert/delayedAlert can be improved by moving slowAlert into delayedAlert as follows:

function delayedAlert() {
    clearAlert();
    timeoutID = window.setTimeout(function(){
        alert("You may have been logged out due to inactivity. Click OK to refresh the page.");
    }, 10000);
}

I can't see why the clearTimeout call deserves its own function, when it only gets called from delayedAlert; You could just put it in delayedAlert:

function delayedAlert() {
    window.clearTimeout(timeoutID);
    timeoutID = window.setTimeout(function(){
        alert("You may have been logged out due to inactivity. Click OK to refresh the page.");
    }, 10000);
}

You can make delayedAlert an anonymous function, so that it cannot be called other than inside that block by changing function delayedAlert() into var delayedAlert = function()
You call delayedAlert before timeoutID is defined:

delayedAlert();

var timeoutID;

If you're going to use globals (which are recommended against), declare them first, at the top.

(function(){
    var timeoutID;
    // functions and whatnot
    delayedAlert();

All resulting in:

(function(){
    var timeoutID;
    var delayedAlert = function() {
        window.clearTimeout(timeoutID);
        timeoutID = window.setTimeout(function(){
            alert("You may have been logged out due to inactivity. Click OK to refresh the page.");
        }, 10000);
    }
    delayedAlert();
})();


Removing a specific character and its neighbors from a string

Generalise

Having a method RemoveAsterix isn't a scaleable approach to solving the general case.  A better method might be:

static string RemoveLettersSurroundingCharacter(string sourceString, char charToRemove)

Passing in the character to remove also helps you to remove a lot of the hard coded * references in your code.

Variable names

Avoid names that start with 'my'.  It reads very much like example code that isn't meant for production, although some people also use it as a naming convention when referring to member variables of a class (which you aren't).

Algorithm

As has already been said in the comments, your algorithm is quite naive.  It works for simple cases, but doesn't seem to have been tested for many edge cases that you might expect to encounter.

**1         => 1
***         => Crash
1234***567  => 123*567
1234**      => 1234
ab*cd*ef    => ad*ef

Your algorithm will remove any leading *, any trailing * and the first instance of * outside of these positions.  This leaves its processing in a bit of a weird state of completeness.  If you only want to process a single *, then you should check to ensure that the string only contains a single * and error if it doesn't.  If you want to support removal of any number of *, then you need to think about what to do when you encounter two * next to each other.  Does the second one get ignored (because it has been removed when the first is encountered) or does it extend the removal.  This is the difference between: 12**34 turning into 134 or 14.

Use specific exceptions where available

You want to throw the most specific exception that you can.  Generally speaking, you should avoid throwing and catching base exceptions.  So, rather than:

throw new Exception("You need an asterix!");

It would be better to:

throw new ArgumentException("You need an asterix!", "myString");


Powershell Script for setting DHCP reservation description & host value

Very impressed with your formatting and spacing. Top notch to see that in practice. I see a couple areas that could be improved and I see at least 2 problems.
Variable Expansion in Strings
Variables will expand in double quotes easy. However you need to be using subexpressions in order to get the property portion to work correctly. You can also use the format operator -f but that is better used for more complicated string.
... -Description "$($PrinterObjects.Name) & $($PrinterObjects.Location)"

If this code is in use already check existing descriptions for dependencies.
Efficient and Reliable conditions

Where-Object { ($_.Name -match "^.{6}$") -and ($_.PortName -match "IP*" -or $_.PortName -match '^10*') -and ($_.Shared -EQ $True)}

The first clause looks like you are just trying to find Name's that are exactly 6 characters long? Just use the length property all strings have instead. No need for regex: $_.Name.Length -eq 6).
In the second clause you are using regex as well and while I doubt it will cause conflicts you need to be aware you would match IP as well as IPPPPPPPPPPP. -like "IP*" or the string method .StartsWith("IP") would work just as well. Note that StartsWith() is case sensitive.
Similarily with $_.PortName -match '^10*' if you are just trying to find ones where the first octet is 10 you will also match ones that are 100 or 1000000 since the greedy quantifier is in use here. Solution is the same as the last one. -like "10.*" or the string method .StartsWith("10."). Notice I added periods. That may or not be an issue for you in production.
Possible trade off of readabilty but for the last clause here (($_.Shared -EQ $True)) you don't need to use -eq. PowerShell will evaluate $_.Shared as its own expression. If it is a non-zero length string or non-zero integer it will evaluate to true.
Curly Braces
You are slightly inconsistent in your foreach blocks. Some have the opening brace after the block and some have it on the following line. I would pick on standard and stick with it. I personally favour the former.
foreach ($DHCPSvrReservation in $DHCPSvrReservations){
    # Do stuff
}

Same goes for your if and other similar blocks and constructs.
Your Set-DhcpServerv4Reservation and Set-DhcpServerv4OptionValue dont need to be surrounded by curly braces. They should function the same without them.
Using if when Where would do
You act on all $printerobject's that have a matching reservation. You loop though is still running through the $printerobject's that don't match. True, you don't do anything with them but you could move that condition into your loop then you can drop the if
foreach ($DHCPSvrReservation in $DHCPSvrReservations){
    foreach ($PrinterObject in ($PrinterObjects | Where-Object{$DHCPSvrReservation.IPAddress -eq $_.PortName})){
            Set-DhcpServerv4Reservation -ComputerName $DHCPSvr -IPAddress $PrinterObjects.PortName -Description "$($PrinterObjects.Name) & $($PrinterObjects.Location)"
            Set-DhcpServerv4OptionValue -ScopeId $DHCPSvrScope -OptionId 12 $PrinterObjects.Name
    }
}

That should work but you should test first.


Solution overall seems nice, although:

casting to list in list comprehension is not needed
product returns iterator, so you also may want to generate iterator if you mainly plan to iterate over possibilities
I'd strongly advice using better names. Characters in source code costs nothing and maintaining code afterwards is much easier

My attempt would be:

import itertools

letters_map = {'2':'ABC', '3':'DEF', '4':'GHI', '5':'JKL',
               '6':'MNO', '7':'PQRS', '8':'TUV', '9':'WXYZ'}

def possible_words(phone_number):
    letters_to_combine = (letters_map[digit] for digit in phone_number)
    for letters_group in itertools.product(*letters_to_combine):
        yield ''.join(letters_group)

print list(possible_words("23567"))


'Genetic algorithm' implementation for constructing a battle mech

Here's a summary of my comments in the answer format:

Instead of coded return values, I'd consider using an enumeration for clarity: http://en.cppreference.com/w/cpp/language/enum
// A good rule of thumb is that if you have to document a special meaning of (implicit) enumerators, like "0 = draw, 1 = mech #1 wins, 2 = mech #2 wins", then it's probably better to use an explicit enumeration.
I would also suggest using a namespace non-member function instead of a static member function whenever possible: https://stackoverflow.com/a/1435105/859774
Further, unless you're supporting negative turns count turnLimit or want turn to go backward (would that even make sense in your context? BTW, turn++ looks awkward, change it to ++turn), I would use size_t instead of int for turn and turnLimit: http://en.cppreference.com/w/cpp/types/size_t
// NOTE: in fact, the cases where int is the right type to choose are significantly rarer than most beginning developers seem to assume -- as a good rule of thumb, whenever you think you should use an int, you should always stop and think whether it's actually a good idea -- e.g., are you sure you really want negative values?
I also wouldn't use mech1Alive or mech2Alive but rather their opposites (e.g., mech1Dead or mech2Dead) -- note that you're always negating them in your if statements, so it would improve code clarity to do so straight away, at the outset.
I've just looked at the online version, BTW. Your next step should be to remove all uses of new (and, consequently, all manual invocations of delete) and all of the resource-owning raw pointers: preferably change them to (stack-allocated) automatic variables (using references, preferably to const, when avoiding copies is necessary), then only for the ones for which you can't possibly do that (if there are any, don't just assume this, but carefully verify that free-store/heap dynamic allocation is in fact absolutely required!) use std::unique_ptr, and finally, as a last resort, use std::shared_ptr (and, as a last resort after this last resort ;], in the extremely rare case you have need to break a cycle, consider std::weak_ptr).
See: https://codereview.stackexchange.com/a/25721/24670


Nesting BsonDocuments in MongoDB queries

I found one way to simplify this which helps break up the number of rows required.

Following this StackOverflow question about converting a JSON string to Bson, I wrote part of my query as it would be in a console. I could only figure out how to do this for the match and group part:

var matchJSON = "{ project_id : '1234' }";
var groupJSON = "{ " +
    "_id : { project_id : '$project_id', date : '$VehicleEntry.@Date' }, " +
    "passed : { $sum : { $cond : [ { $eq : [ '$VehicleEntry.VehicleStatus', 'PASSED' ] }, 1, 0 ] } }, " +
    "failed : { $sum : { $cond : [ { $eq : [ '$VehicleEntry.VehicleStatus', 'FAILED' ] }, 1, 0 ] } } }";

Then I converted it to BsonDocuments:

var matchBson = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(matchJSON);
var groupBson = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(groupJSON);

and then ran my aggregate query just like it was previously:

var aggregate = collection.Aggregate()
    .Match(matchBson)
    .Unwind(i => i["VehicleEntry"])
    .Group(groupBson);


Notes

Currently I'm aware that each node is created on the Heap.

No such thing as heap in C++ (or stack technically).
You mean dynamically allocated memory in the situation.
Note: Though the language does not specify the need for a stack most implementations will use one. But the concept itself is not useful for thinking about C++ objects. You should look up "Automatic/Static/Dynamic" storage duration.

I have no idea how to delete the nodes in a LinkedList once the LinkedList itself is deleted.

If you create something with new ou delete it with delete. I'll cover that below. When an object is destroyed (either manually or by going out of scope) its destructor will always be called.

I'm also not sure how to create a linkedlist without pointers.

I don't think I could do that either.

Also, should I potentially add an abstract class/or a c++ version of an interface for my LinkedList to follow.

In C++ we use this thing called "Concepts". A linked list is an implementation of the "Concept: Container" there is no interface for a concept but rather a standard set of things that it should implement. https://en.wikipedia.org/wiki/Concepts_(C%2B%2B)
Thus allows for template to do "Duck" typing.
If it quacks like a duck then it can be used as a duck.
Basically templates allow you to use any type as long as the function you use are available for that type and it compiles it is said to follow the duck typing interface of the template.

and then I could use this same abstraction for, say, a stack?

Now there is already a type std::stack that underneath uses an object that implements the Concept of a SequenceContainer.
And defines these functions (As defined for a Sequenced Container).

back()
push_back()
pop_back()

See: https://en.cppreference.com/w/cpp/named_req/SequenceContainer
Code Review
Don't need to mention the template type inside the templates object.
template <typename T>
struct Node {
    Node(T value);
    T data;
    Node<T> *next;  // That <T> is not needed here.
                    // The compiler assumes its a T unless you
                    // manually specify otherwise.
};

The * and & and && are part of the type infomration. So in C++ (unlike C) they are usually placed next to the type information not the member.
    Node*   next;   // Next has a type Node* (or Node Pointer).

Don't use this->
template <typename T>
Node<T>::Node(T value){
    this->data = value;
    this->next = nullptr;
}

The only time you need to use this-> is when you have a local variable that shadows a member variable. If you have a shadowing problem them the compiler can not tell when you accidently leave off the this-> and thus shadowing leads to hard to detect bugs.
So it is better to use unique names and get the compiler to warn you when you have a shodowed variable. Then your naming of variables becomes better and you don't accidently use the wrong variable.

For short function put them in the class definition.
template <typename T>
Node<T>::Node(T value){
    this->data = value;
    this->next = nullptr;
}

Thats short and because you don't need the template <typename T> in the class it becomes even shorter.

Prefer to use the initializer list over constructor code.
When an object is created all its members are initialized in the order declared in the class. If there are no members initialized in the initializer list they are zero or default initialized depending on the exact declaration.
But if you are setting the values in the constructor code this means you are re-setting them in the code. For complex objects this means you are calling the operator= to redo work that was done in the initializer list.
template <typename T>
Node<T>::Node(T value)
    : data()            // You have an implicit initialization here
    , next()            // even if you don't do it yourself.
{
    data = value;       // If the above initialization did work
    next = nullptr;     // Then these two assignments become extra work.
}

Your copy constructor passes the data by value:
Node<T>::Node(T value)     // Pass by value causes a copy of value here.
    : data()               // Data is default constructed here.
                           // See above.
{
    this->data = value;    // Copy assignment causes another copy to be
                           // made here.

If you are keeping the data you need to copy it at some point but you don't need to copy it twice. So pass by const reference to avoid a copy.
Node<T>::Node(T const & value)  // Pass by reference to avoid copy.
    : data(value)               // Construct data using the copy constructor.
{

In modern C++ we have the concept of move semantics. This allows an object to move expensive parts to another object if it is not going to be used again. Think of passing a huge array into an object. You may not want to copy it (as above). If you are not going to use the data again you want to move the object.
Node<T>::Node(T&& value)        // The double && indicates it will bind
                                // To an r-value reference (something that can be moved)
    : data(std::move(value))    // You pass the T object to the move
                                // constructor of the type T to allow it to
                                // move itself.
{

Better declaration for Node:
template <typename T>
struct Node
{
    Node(T const& value)
        : data(value)
        , next(nullptr)
    {}
    Node(T&& value)
        : data(std::move(value))
        , next(nullptr)
    {}
    T        data;
    Node*    next;
};

But even better news. Since the above is such a common pattern (Adding constructors and assignment operators like this). That this is done automatically for all types (unless you start manually defining them). So the above type can be defined simply by doing:
template <typename T>
struct Node
{
    T        data;
    Node*    next;
};

Note: Normally this is a bad thing if your object contains a pointer. BUT if we consider the Node as a non owning of the pointer it works. But you have to move the responsibility for owning onto the LinkedList class. So we will cover that below.

LinkedList is a class that contains an "OWNED" pointer (unlike Node). So this class you do need to specify a couple of methods or things go wrong.
Look up the rule of three.
If you don't specify them the compiler will automatically generate:

CopyConstructor LinkedList(LinkedList const&);
CopyAssignment  LinkedList& operator=(LinkedList const&);
Destructor      ~LinkedList()

The constructors do a shallow copy and the destructor simply makes sure that all members are correctly destroyed. So in this case they do:
 LinkedList(LinkedList const& copy)
     : head(copy.head)
 {}
 LinkedList& operator=(LinkedList const& copy)
 {
     head = copy.head;
     return *this;
 }
 ~LinkedList()
 {
     /* Nothing is done for pointers */
 }

So what you say. This does not affect me. This is true because currently you have not defined the destructor. But if you correctly define the destructor the constructors will cause problems.
 ~LinkedList()
 {
     deleteTheListPointedAtBy(head);  // This is what you should do.
 }

This causes problems because the above 2 constructors allow:
 {
      LinkedList<int>  a;
      a.push_back(1);
      LinkedList<int>  b(a);   // We are allowed to copy a like this.
                               // But both a and b have a head that points
                               // at the same value.

 } // At this point both a and b are destroyed.
   // Thus there destructors are called.
   // Thus they both try and delete all the same nodes.
   // which will cause problems.

As above in Node. You should think about move semantics. There are two methods added in C++11 that change the rule of three into the rule of 5.

MoveConstructor LinkedList(LinkedList&&);
MoveAssignment  LinkedList& operator=(LinkedList&&);

As above use the initializer list:
template <typename T>
LinkedList<T>::LinkedList(){
    this->head = nullptr;
}

As above pass by const reference to avoid a copy.
template <typename T>
void LinkedList<T>::push_back(T data){

Same again pass by const reference:
template <typename T>
void LinkedList<T>::push_back(int index, T data){

This is good and looks correct.
    Node<T> *cursor = this->head;
    unsigned const position = index - 1;
    int i = 0;
    while (i < position && cursor->next != nullptr){
        cursor = cursor->next;
        i++;
    }
    Node<T> *nodeToInsert = new Node<T>(data);
    Node<T> *temp = cursor->next;
    cursor->next = nodeToInsert;
    nodeToInsert->next = temp;

But we could simplify it a bit:
    Node* cursor = head;
    for(int loop = 0;loop < position && cursor->next !- nullptr;++loop,cursor = cursor->next)
    {}

    cursor->next = new Node<T>(data, cursor->next);

This also works well.
template <typename T>
void LinkedList<T>::print(){
    Node<T> *cursor = this->head;
    while(cursor != nullptr){
        std::cout << cursor->data << '\n';
        cursor = cursor->next;
    }
}

But you assume the output is std::cout. I would pass the output stream as a parameter (it can default to std::cout`). This makes the print much more flexable.
The print() method does not change the state of the object so it should be marked const.
In C++ we normally use operator<< to output stuff. So you may want to write that function so it looks more natural. It can simply call the print method.
template <typename T>
void LinkedList<T>::print(std::ostream& str) const
{
    Node<T> *cursor = this->head;
    while(cursor != nullptr){
        str << cursor->data << '\n';
        cursor = cursor->next;
    }
}
template<typename T>
std::ostream& operator<<(std::ostream& str, LinkedList<T> const& list)
{
    list.print(str);
    return str;
}

Your missing destructor:
template<typename T>
~LinkedList()
{
    Node<T>*   old;
    while (head) {
        old = head;
        head = head->next;
        delete old;
    }
 }

Alternative Implementation:
template <typename T>
class LinkedList
{
    // Make Node a private member of the Linked List.
    struct Node
    {
        T      data;
        Node*  next;
    };
    Node*      head;
    Node*      tail;

    public:
        ~LinkedList() {deleteList();}

        LinkedList()
            : head(nullptr)
            , tail(nullptr)
        {}

        LinkedList(LinkedList const& copy)
            : LinkedList()
        {
            for(Node* other = copy->head; head; head = head->next) {
                push_back(other->data);
            }
        }
        LinkedList operator=(LinkedList const& copy)
        {
            LinkedList   tmp(copy);  // See Copy and Swap Idiom
            swap(tmp);
            return *this;
        }

        LinkedList(LinkedList&& move) noexcept
            : LinkedList()
        {
            swap(move);
        }
        LinkedList operator=(LinkedList&& move) noexcept
        {
            swap(move);
            return *this;
        }

        void swap(LinkedList& other) noexcept
        {
            using std::swap;
            swap(head, other.head);
            swap(tail, other.tail);
        }
        friend void swap(LinkedList& lhs, LinkedList& rhs) noexcept
        {
            lhs.swap(rhs);
        }

        void push_back(T const& data)
        {
            pushbackNode(new Node{data, nullptr});
        }
        void push_back(T&& data)
        {
            pushbackNode(new Node{std::move(data), nullptr});
        }

        void push_back(int index, T const& data);
        void push_back(int index, T&& data);

        void print() const;
        friend std::ostream& operator<<(std::ostream& str, LinkedList const& data) {
            data.print(str);
            return str;
        }
    private:
        void deleteList()
        {
            Node*  old;
            while (head) {
                old  = head;
                head = head->next;
                delete old;
            }
        }
        void pushbackNode(Node* node)
        {
            if (tail) {
                tail->next = node;
                tail = tail->next;
            }
            else {
                head = tail = node;
            }
        }
};


Escaping the RegExp

You should never do manual escaping, if an appropriate function exists. For RegExp, this is preg_quote. Another risk is that you'r escaping before splitting, so you might destroy an escaping sequence. Better do

function substitute($template, $values, $delimiter = '{??}')
{
    $half    = (int) ( (strlen($delimiter) / 2) );
    $begin   = preg_quote(substr($delimiter, 0, $half), '/');
    $end     = preg_quote(substr($delimiter, $half), '/');
    $pattern = '/' . $begin . '(\w+)' . $end . '/';

Escaping the Values

The user provided values maust be escaped according to the context, where they are used. In this case it is HTML, so you must suppress unwanted tags, especially scripting tags. You can use strip_tags() or htmlspecialchars() for that purpose. I prefer the latter, because the user's value is not changed.

    return preg_replace_callback(
        $pattern,
        function ($matches) use ($values) {
            if (isset($values[$matches[1]])) {
                return htmlspecialchars($values[$matches[1]]);
            }
            return $matches[0];
        },
        $template);
    }
}

Conclusion

With these two small changes you have done everything to make that function save.


I did not check the acm package but my 2 cents:

No need to instantate a PythagoreanTheorem each time

public void run() {
    PythagoreanTheorem myCalculator = new PythagoreanTheorem();

run is not static, so there already is an instance of PythagoreanTheorem availiable in the method, referencable by this.

So instead of:

if(myCalculator.formula(a,b) ==

You can use

if(this.formula(a,b) ==

Reuse results

You have a few calls to myCalculator.formula(a,b). While a and b do not change. You can store the result in a variable.

double c = myCalculator.formula(a,b)
if(c == Math.floor(c))
....


Create and open a file to take lecture notes depending on day and time

killall Terminal is very harsh!  Maybe you aren't a serious Terminal user now, but someday, you might be doing something important in another Terminal window.  And, due to the way macOS works, multiple windows all run under a single Terminal process, so you would be killing all of your Terminal windows.  At most, do

osascript -e 'tell application "Terminal" to close the front window'

… which sends a message to just one window using AppleScript.  But I would consider even that to be too violent for my taste.

I find those cases too cumbersome to read as conditions.  I would write out all of the combinations, using pattern matching, and in particular, extended pattern matching enabled by shopt -s extglob.

#!/bin/bash

shopt -s extglob

read date hour day month <<< $(date +"%-d %-H %a %B")

case $day.$hour in
    @(Tue|Thu).@(8|9|10|11))
        dir="/path/to/first"
        ;;
    @(Tue|Thu).@(13|14))
        dir="/path/to/second"
        ;;
    Wed.16)
        dir="/path/to/third"
        ;;
    *)
        echo "I am of no use to you right now"
        exit 1
esac
…


Inizialize an Jarray wih n JObject that contain an progressive index

Instead of creating JObject after JObject you should create it once without the areaNum property. Then in a loop you should DeepClone() it and use AddFirst(), if positions matter, to add the areNum property like so

    Dim original As JObject = New JObject(
    New JProperty("numbers", New JArray({New JArray({}), New JArray({}), New JArray({})})),
    New JProperty("systems", New JArray({""})),
    New JProperty("multiplier", New JArray({""})),
    New JProperty("qp", False),
    New JProperty("series", False),
    New JProperty("noseries", False),
    New JProperty("twodigit", False),
    New JProperty("onedigit", False),
    New JProperty("void", False))

    For i As Integer = 1 To 5
        Dim panel As JObject = original.DeepClone
        panel.AddFirst(New JProperty("areaNum", i))
        panelsArray.Add(panel)
    Next i


Binary tree implemented using references

What's wrong with using references for binary tree (other than that you can't insert or delete elements)?

Well, it does work, as you've shown. But in order to use references instead of pointers, you had to make two awkward changes to the "natural" pointer-based code:

(1) You had to invent a null_node object, which is a global variable, and suffers all the problems of global variables (for example, it won't play well with dynamic libraries, a.k.a. shared objects, a.k.a. DLLs, because you might end up with a program containing two null_node variables — one from the main program and one from the DLL).

(2) You had to prefix all your accesses with an extra & character.

Compare your way (slightly reformatted for style and const-correctness):

void post_order(const Node& node) {
    if (&node.left_child != &null_node) {
        post_order(node.left_child);
    }
    if (&node.right_child != &null_node) {
        post_order(node.right_child);
    }
    std::cout << node.value;
}

to the "natural" approach:

void post_order(const Node *node) {
    if (node->left_child) {
        post_order(node->left_child);
    }
    if (node->right_child) {
        post_order(node->right_child);
    }
    std::cout << node->value;
}

Which one is easier to read (and incidentally to write)?

Notice that C++'s syntax for pointers dates back all the way to C, i.e., the mid-1970s. It's had a long time to polish and refine and streamline that syntax. You're trying to invent something "better", without the benefit of controlling the language definition. You shouldn't be surprised that the built-in, ~40-year-old syntax is really suitable for the exact job it was designed for. :)

By the way, if you want to deal with empty trees in the "natural" way, consider the following refactoring:

void post_order(const Node *node) {
    if (node != nullptr) {
        post_order(node->left_child);
        post_order(node->right_child);
        std::cout << node->value;
    }
}

Straight-line code is best code!


Handling two buttons that submit a form using AJAX

If it's the exact same call you could abstract the Ajax call into its own function and pass the url. For example:

const doAjax = (url) => {
    $.ajax({
        type: 'POST',
        url: url,
        dataType: 'json',
        data: $(this).serialize(),
        success: function (data) {},
        error: function (data) {}
    });
}

doAjax('add');
doAjax('edit');

This is an ES6 function expression but would also work with ES5 function(){} syntax.

function doAjax(url) {
    $.ajax({
        type: 'POST',
        url: url,
        dataType: 'json',
        data: $(this).serialize(),
        success: function (data) {},
        error: function (data) {}
    });
}


Bug
Unfortunately both your functions return bad results for many input arguments. You don't carry.
Both should return [0,1] however they return [0]
addTwoNumbers([1], [9]); // >> [0] wrong
addTwoNumbers2([1], [9]);  // >> [0] wrong

And the return for the following should be [6,0,1] but they return [6,6]
addTwoNumbers([9], [7, 9]);  // >> [6, 6] wrong
addTwoNumbers2([9], [7, 9]);  // >> [6, 6] wrong

The reason is that you forget to deal with the carry.
To number?
Konijn's answer is a tempting solution but will also fail as it is limited by JS Number.
addTwoNumbers([1,1,9,9,0,4,7,4,5,2,9,9,1,7,0,0,9], [1,9,9,0,4,7,4,5,2,9,9,1,7,0,0,9])

The correct answer is
[2,0,9,0,5,1,2,0,8,1,9,1,9,7,0,9,9]
However Konijn's solution incorrectly returns.
[0,0,9,0,5,1,2,0,8,1,9,1,9,7,0,9,9]
This is because the second number is Number.MAX_SAFE_INTEGER above which you can not get a reliable result.
BigInt
You could use a BigInt as its size is not limited.
Big ints can be written with the suffix n
 const big = 9907919180215090099079191802150900n;  // Note the suffix n

To convert the reversed number to a big int
 const a = [0,0,9,0,5,1,2,0,8,1,9,1,9,7,0,9,9,0,0,9,0,5,1,2,0,8,1,9,1,9,7,0,9,9];
 const big = BigInt(a.reverse().join(""));

Thus your function would be
 const addTwoNumbers = (a, b) => (
          BigInt(a.reverse().join("")) +
          BigInt(b.reverse().join(""))
      ).toString().split("").reverse();

But that takes the puz out of puzzle me thinks.
Carry
The aim is to carry the remainder of each addition onto the next digit. This is fundamental to all ALU (Arithmetic Logic Units) that are part of almost every modern CPU. (In the case of binary the carry is 1 or 0)
So when you add two values 9 + 9 the result is 8 and carry 1. You then add the 1 to the next digit. If no digit add it to zero. The result is 18.
The function is thus
Example A
function addNumbers(a, b) {
    const sum = [];
    var i = 0, carry = 0;
    while (i < a.length || i < b.length || carry > 0) {
        carry += (a[i] ? a[i] : 0) + (b[i] ? b[i] : 0);
        sum.push(carry % 10);
        carry = carry / 10 | 0;
        i++;
    }
    return sum;
}

Note That it continues adding digits until the carry is zero.
Performance
I am not surprised that the big int solution is nearly 7 times slower than carry method (example A) above, but this is due to the reverses, joins, and split
Big int are not fast (Very slow compared to standard JS numbers), doing the same sum on big int literals is only 5 times faster than the carry method (example A)
NOTES
BigInt is very new and you should check the browser for support before using it.
Big int also sees the arrival of 64bit int arrays (YAY YAY YAY) BigUint64Array, BigInt64Array (sorry MDN has empty pages on these references)


Sending a HttpRequest Message, and retrying in case of unauthorised

How unpleasant is my use of delegates and what lengths should I go to change this code, if any?

If you want the caller to provide some small piece of code, then a delegate is exactly the right way to do it, it's not unpleasant at all.

But looking at your two usage samples, it looks like they have some code in common (calling InitialiseHttpClient and InitialiseRequest), so it might make sense to change the signature to something like:

private async Task<HttpResponseMessage> SendToFooAsync(
    HttpMethod method, string uri,
    Action<HttpClient> clientAction = null,
    Action<HttpRequestMessage> requestMessageAction = null)

The two usage samples would then look like this:

SendToFooAsync(HttpMethod.Post, path);

SendToFooAsync(
    HttpMethod.Post, path,
    client => client.DefaultRequestHeaders.Accept.Add("some json stuff"),
    message => message.Content = new StringContent("some json stuff"));

Also, I don't like the way you're naming your delegates. Func<HttpClient> is not HttpClient, so it shouldn't be called just client. Something like clientFunc would be more accurate.


public class GL

Your class name should really be a more descriptive noun.

private static class MethodSignature

You actually have no need for this private static class since Reflection gives you direct access to methods and method signatures, as you'll see in my modified version of your code below.

String name;
Class<?>[] parameters;

When you create a class, you should always explicitly declare whether a field is public, protected, or private.

private final static MethodSignature[] METHOD_SIGNATURES = new MethodSignature[] { //...
private final static String[] CONSTANT_NAMES = new String[] { //...

Again, you don't need either of these since you have Reflection, which gives you access to methods and fields.

public static int GL_ARRAY_BUFFER;
public static int GL_ELEMENT_ARRAY_BUFFER;
public static int GL_STATIC_DRAW;

public static Method _glGenBuffers;
public static Method _glDeleteBuffers;
public static Method _glBindBuffer;
public static Method _glBufferData;
public static Method _glGetBufferSubData;

These are all very odd variable names.  In general, NAMES_IN_CAPS are constants (private static final).  The beginning underscore is also a paradigm that isn't really Java-esque (and to my knowledge in other languages it is generally used for private-like fields).

public static int glGenBuffers() {

Your method names are also oddly named for Java.  In general, Java method names should be actions and verb phrases.  (For example, getGLGenBuffers())

catch(IllegalAccessException | IllegalArgumentException | InvocationTargetException e)

No need for these lengthy catch declarations since they all do the same thing and all you're doing is printing the stack trace.  catch(Exception e) will do and make your code more sensible.

public static void useClass(Class<?> glClass)

This entire method will be refactored below.  But basically you don't need two for() loops, since you're just looping through the class's fields.  This also eliminates the need for the overarching constants for the field names and the method signatures, as you'll see.

I cut your code length by about half by doing all of the above, and I think it's generally more readable and understandable this way as well.

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.FloatBuffer;

public class OpenGLInterceptor {

    public static int GL_ARRAY_BUFFER;
    public static int GL_ELEMENT_ARRAY_BUFFER;
    public static int GL_STATIC_DRAW;
    //...

    public static Method _glGenBuffers;
    public static Method _glDeleteBuffers;
    public static Method _glBindBuffer;
    public static Method _glBufferData;
    public static Method _glGetBufferSubData;
    //...

    public static int invokeGenBuffers() {
        try {
            return (Integer)_glGenBuffers.invoke(null);
        }
        catch(Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public static void invokeDeleteBuffers(int buffer) {
        try {
            _glDeleteBuffers.invoke(null, buffer);
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void invokeBindBuffer(int target, int buffer) {
        try {
          _glBindBuffer.invoke( null, target, buffer );
        }
        catch(Exception e) {
          e.printStackTrace();
        }
    }

    public static void invokeBufferData(int target, FloatBuffer data, int usage) {
        try {
            _glBufferData.invoke(null, target, data, usage);
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void invokeGetBufferSubData(int target, long offset, FloatBuffer data) {
        try {
            _glGetBufferSubData.invoke( null, target, offset, data );
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void useClass(Class<?> glClass) {
        for(Field field : GL.class.getDeclaredFields()) {
            try {
                if(field.getName().contains("_")) {
                    field.set(null, glClass.getDeclaredMethod(field.getName(), ((Method)field.get(null)).getParameterTypes()));
                }
                else {
                    field.set(null, glClass.getField(field.getName()).get(null));
                }
            }
            catch(Exception e) {
                e.printStackTrace();
            }
        }
    }

}


This answer assumes there's no way the different "groups" would actually belong in different enum types. Otherwise the only sensible answer is "if you have different groups of related values, put them in different enum types". Status is a fairly broad name (enum types shouldn't have "Enum" in their names) that doesn't really says anything - if you have an Availability group with NotAvailable and Available possible values, then have an Availability enum with these values.

That's [very] little more than a hard-coded Enum.GetValues helper...

Define your enum vertically:

public enum Status
{
    Unknown,
    Known,
    NotAvailable,
    Available,
}

Then it's much easier to add attributes, e.g. a [Description]:

public enum Status
{
    [Description("Device is unknown.")]
    Unknown,
    [Description("Device is known.")]
    Known,
    [Description("Device is not available.")]
    NotAvailable,
    [Description("Device is available.")]
    Available,
}

Or whatever. If you have enum values that semantically related and need to regroup them, you can use flags for that. Use powers of 2 to specify explicit underlying values for each enum; you can use bit-shifting to simplify that:

[Flags]
public enum Status
{
    Unknown = 1 << 0,
    Known = 1 << 1,
    NotAvailable = 1 << 2,
    Available = 1 << 3,
}

And then you can define the "groupings" as you please:

[Flags]
public enum Status
{
    Unknown = 1 << 0 | Knowledge | Negative,
    Known = 1 << 1 | Knowledge | Positive,
    NotAvailable = 1 << 2 | Availability | Negative,
    Available = 1 << 3 | Availability | Positive,
    Knowledge = 1 << 20,
    Availability = 1 << 21,
    Positive = 1 << 22,
    Negative = 1 << 23,
}

And now when you're faced with a Status value, you can do this:

var isPositive = value.HasFlag(Status.Positive);

And you can get all Positive enum values rather easily:

var positiveStatusCodes = Enum.GetValues(typeof(Status))
                              .Cast<Status>()
                              .Where(status => status.HasFlag(Status.Positive))
                              .ToArray();

That way when you need to add enum values, just give them the proper flags and your "get all positive status codes" code doesn't need to change at all.


Actually, your code is efficient - it does exactly what it is supposed to do, and does not take any extra steps.
There are a few other issues, of the kind that are expected from a new coder in the process of learning, so here are some tips:
Global row variable
In Python, if you declare a variable outside of a function and then one with the same name inside a function (by assigning it value, as you do with row), you create a new variable, that "overshadows" the global one.
Basically, the top row in you code is never used, instead, main has its own local copy.
But that is ok, because you don't need a global row variable any way.
As a general practice it is best to avoid global variables completely.
There are very few cases where they are needed, especially in object oriented languages like Python.
String formatting
When you want to compose a string from multiple parts, including values in variables you should use formatting instead of string concatenation with '+'.
It is a more robust method allowing for prettier output, and makes your code more readable and more convenient to modify should the need arise.
Also, if you are putting together a lot of parts, this will be more efficient.
If you are using Python 3.6 or newer, you can do this:
print(f"What is {num_1} + {num_2} ?")
...
print(f"Correct!  You've gotten {row} correct in a row.")

If you are on an older version of Python, you can do this:
print("What is {} + {} ?".format(num_1, num_2))
...
print(f"Correct!  You've gotten {} correct in a row.".format(row))

As you can see, you no longer have to convert numbers to strings manually, the formatting function will do it for you!
Pay attention to hints in questions
You have used constants for range of random numbers, but not for the maximum number of correct answers in a row.
The question almost requires you use a constant by saying:

(Note: the number of problems the user needs to get correctly in a row to complete the program is just one example of a good place to specify a constant in your program)

In general, numbers that have meaning but are written as is directly in the code (like the number of correct answers) are called "magic numbers" and are considered bad practice.
Just add at the top:
MAX_IN_ROW = 3

And use MAX_IN_ROW everywhere else in the code you need to check this value.
Input validation
This may be an advanced topic you have not covered yet, but as a rule of thumb all programs must guard against bad or invalid user input.
Some questions, especially on time constrained exams tell you to omit such checks, but if not explicitly instructed to do so, and if you can, you should check all input before using it.
For this question, exception handling would be appropriate:
try:
    user_input = int(input("Your answer: "))
except ValueError:
    print("Invalid answer! You must type a positive decimal number.")
    continue


How do I clean up these Python decorators?

I agree with @minitech that accepts shouldn't be a class. It can be written much more compactly using a nested decorator (like returns, in fact):

def accepts(*artypes, **kwtypes):
    """
    Pass it a list consisting of types or tuples of types.
    in other words, pass it things that will be valid second
    arguments to the isinstance(arg, type) method.
    """
    def outer(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            type_zip = zip(args, artypes)
            for arg, type_ in type_zip:
                if not isinstance(arg, type_):
                    raise ValueError()

            for key, value in kwargs.items():
                if not isinstance(value, kwtypes[key]):
                    raise ValueError()
            return func(*args, **kwargs)
        return wrapper
    return accepts_wrapper

This then works equivalently to returns, and is much shorter (as you need less variable-passing code).


This might seem a bit much, but I'm reviewing this as if it were intended for production code:

black and isort can reformat this code to be more idiomatic without changing the functionality.

pylint, flake8 or both can tell you of some issues with this code:
$ pylint --disable=missing-function-docstring,missing-module-docstring q.py
************* Module q
q.py:3:0: C0303: Trailing whitespace (trailing-whitespace)
q.py:14:0: C0303: Trailing whitespace (trailing-whitespace)
q.py:6:8: R1723: Unnecessary "elif" after "break" (no-else-break)
q.py:23:0: C0413: Import "import random" should be placed at the top of the module (wrong-import-position)

------------------------------------------------------------------
Your code has been rated at 8.26/10

The plural of "try" is "tries".

trys += 1 is syntactic sugar for trys = trys + 1.

The code mixes I/O (input/print) and logic, which generally makes the code harder to maintain. It might be better to split this into two functions, one to check the answer against the right answer, and one to receive input and print output.

To enable reuse of the code I would add a main function and the idiomatic
if __name__ == "__main__":
    main()

lines at the bottom of the script to actually run it. Basically, if you just import your file into another nothing should print when importing it. Right now it's impossible to import cleanly from the script:
$ python
Python 3.9.1 (default, Dec 13 2020, 11:55:53)
[GCC 10.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import q
Welcome to guess the number!!
You have 5 trys to guess the number
Good Luck!!
I'm thiking in a number from 0 to 100

Your guessing is?


A simple rule I (and other) try to apply is : define things in the smallest possible scope.

For instance, int UserNumber = 0; can be moved inside the loop.

Similarly, k can be moved once you've made your loop a for loop : for(int k = 1; k < 11; k++).

Then, computer people love counting from 0. If you write : for(int k = 0; k < 10; k++), I am used to this and I know straight-away that there will be 10 iterations. If you re-index your loop, you'll need to convert else if (k == 10) into a else if (k == 9).

Then, you'll realise that there is no need for this check, you can just move this out of the loop.


Determining the number of days in a month

Well havent tried either Excel or VBA , but the logic will go like this ,

Loop through the table
Say the date is day/month/year , where day,month and year are variables
lets have an array of months which is [31,28,31,30,31,30,31,31,30,31,30,31]
if year is divisible by 4 or 400 , then months[1]= months[1] + 1
now just display months[month]

Here months is the array and month is the number of month present in the date , for more info in arrays for VBA you can look here .


Return value when the requested variable returns null

You're right, this is not the best thing to do. The correct way would be to return an empty list.

private List<HtmlNodes> GetNodes(HtmlDocument aHtmlDoc, string aID)
{
    List<HtmlNode> nodes = new List<HtmlNode>();

    HtmlNode currentDiv = aHtmlDoc.GetElementbyId(aID);
    if (currentDiv != null)
    {
            //Do stuff - fill the nodes list...
    }

    return nodes;
}

Now why is that better than returning null? Simple, it allows to remove checking from the client code. Imagine your function would return null if there are no nodes, clients always need to write the following code when interacting with it:

List<HtmlNode> nodes = GetNodes(htmlDoc, id);
if (nodes != null)
{
    foreach (HtmlNode node in nodes)
    {
        // Super secret business code
    }
}

Always. Now if you'd return an empty list, the checking becomes optional on the client side:

foreach (HtmlNode node in GetNodes(htmlDoc, id))
{
    // Still secret...
}

Or with checking:

List<HtmlNode> nodes = GetNodes(htmlDoc, id);
if (nodes.Length > 0)
{
    foreach (HtmlNode node in nodes)
    {
        // Super secret business code
    }
}

You should always write XML Documentation.

private List<HtmlNodes> GetNodes(HtmlDocument aHtmlDoc, string aID)

There's a typo, it should be HtmlNode.

Also your variables are named not optimal. Drop that a prefix, nobody cares if it is an argument or not, it's a variable you have to work with.

The name of the function is also not good, it's called GetNodes yet from what I see (and interpret into it) it does not fetch the nodes with the given ID, it fetches the children of the first node with the given ID. So it should actually be called GetChildren.


Add a value to each of the array element between two given indices successively

Some general remarks:

System.out.println(queryLength);

The function should only return the result, but not print anything.

int a = 0 , b = 0 , k = 0;

The initial values are not used, and variables should be declared at the narrowest scope, in this case, inside the loop:

for(int i = 0 ; i < queryLength ; i++ )
{
    int a = queries[i][0];
    int b = queries[i][1];
    int k = queries[i][2];
    // ...
}

Iterating over all queries can also be done with an “enhanced for loop”:

for (int[] query: queries)
{
    int a = query[0];
    int b = query[1];
    int k = query[2];
    // ...
}

Here

for(int j = (a-1) ; j <= (b-1) ; j++)

the parentheses are not needed, and this

 p[j] = p[j] + k ;

can be shortened to

p[j] += k ;

The initialization

// initialize p
for(int i = 0 ; i < n ; i++)
{
    p[i] = 0 ;
}

is not needed because all elements are initialised to 0 by default.

It might be a matter of personal preference, but I would always put horizontal space around operators and keywords, e.g. in

if(p[i]>max)

There are also some unneeded import statements, but those are given by the submission template.

But your real problem is that the algorithm is too slow. The inner loop runs up to \$ 10^{7} \$ times, for each of the up to \$ 2 \cdot 10^{5} \$ queries.

The main idea to improve the performance is to represent the data differently. Instead of storing and updating the array with the actual numbers, one can store and update an array which holds the differences between successive numbers.

Initially, all differences are zero.

Then for each query \$ (a, b, k) \$ you only have to update two entries in the differences array: One difference increases by \$ k\$, and one difference decreases by \$ k \$.

Finally you compute the actual numbers by accumulating the differences, and determine the maximum value.

This should be much faster, because the inner loop has been eliminated.

Let's take the given example with \$n = 10\$ and the queries

a b k
1 5 3
4 8 7
6 9 1

Instead of maintaining an array of the \$ n \$ numbers

index:             1  2  3  4  5  6  7  8  9 10
initial array:    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
after (1, 5, 3):  [3, 3, 3, 3, 3, 0, 0, 0, 0, 0]
after (4, 8, 7):  [3, 3, 3,10,10, 7, 7, 7, 0, 0]
after (6, 9, 1):  [3, 3, 3,10,10, 8, 8, 8, 1, 0]

we maintain an array of \$ n+1 \$ differences, where each entry \$ d[i] \$  holds the difference \$a[i+1] - a[i] \$:

index:             0, 1  2  3  4  5  6  7  8  9 10
initial diffs:    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
after (1, 5, 3):  [3, 0, 0, 0, 0,-3, 0, 0, 0, 0, 0]
after (4, 8, 7):  [3, 0, 0, 7, 0,-3, 0, 0,-7, 0, 0]
after (6, 9, 1):  [3, 0, 0, 7, 0,-2, 0, 0,-7,-1, 0]
final array:         [3, 3, 3,10,10, 8, 8, 8, 1, 0]

Do you see that only two entries are updated for each query? Can you figure out the pattern?

The final array is reconstructed by accumulating the final entries in the differences array.


Calculating and displaying number statistics

Please tell me this is for your personal benefit and that you aren't asking me to do your homework!

average = total / count;

total and count are both integers, so / performs integer division.  The result is then converted to a double.  This should fix your problem:

average = ((double) total) / ((double) count);

  Is there any way to dynamically assign the size of the array? so i
  could if i wish enter more than 10 values?

Use a java.util.ArrayList:

// old:
// int[] input = new int[10];
// new:
List<Integer> input = new ArrayList<Integer>();

  I'd also like to format this to always display 2 decimal places

Look at java.text.DecimalFormat.

General Advice

You do an awful lot of typing and a lot of dereferencing (and typing!).  Declare a local inVal parameter:

int inVal = 0;
...

inVal = Input.readInt();
if (inVal < 0) {
    ...
}
// Finally, after all your checks and calculations, add inVal to your array (or List):
input[count] = inVal;

The point of most loop syntax is to make the exit conditions for the loop obvious.  Instead of while (true) I'd like to see something like:

do {
    ...
} while (inVal >= 0)

I like that you calculate your max and min in the input loop.  You could count your total in that loop as well  instead of taking a second loop through your data.  Hmm...  If you do that, you don't need to use an array or a List, just inVal.

You have "magic numbers" 0 and 100.  Years from now when three other programmers have worked on this code, they may add a percentage calculation as x / 100 so that when you decide to increase your number of inputs to 200, you search-and-replace 100 with 200 you have broken your percentage calculation.  You should factor these out of your code:

public final int MAX_NUM_INPUTS = 100;
public final int INPUT_TOO_LOW_VALUE = 0;

This clarifies what you are comparing in a way that Magic Numbers could not:

if (count > MAX_NUM_INPUTS) ...

if (inVal <= INPUT_TOO_LOW_VALUE) ...

Hopefully no-one would ever calculate percent as x / MAX_NUM_INPUTS.  Now you can change these limits in one place without doing any search-and-replace.

UPDATE:

System.out.println...

Yeah, Java is funny about string concatenation.  If you have a non-final variable as part of a String, it can cause a bunch of nasty overhead.  For a little program like yours, it really doesn't matter what you do.  If it were going to print out a String in a loop, then I'd suggest the following change.  Note that System.err.println() uses an OS-specific line separator - not necessarily \n.

// This is fine for your program..
System.err.println("Error: " + input[count]
                        + " is not valid, exiting.\n");

// Option 1: Use multiple print stmts to avoid String concatenation:
System.err.print("Error: ");
System.err.print(inVal);
System.err.println(" is not valid; exiting.");
System.err.println();

// Option 2: Use a StringBuilder (also uses "method chaining" idiom):
System.err.println(new StringBuilder().append("Error: ")
                                      .append(inVal)
                                      .append(" is not valid; exiting.")
                                      .toString());
System.err.println();

This really isn't important in your specific example because it's so small.  In a bigger program or a production situation String concatenation can be a real performance problem.  People often make mistakes in logging code that really slows a system down.  I think later versions of Java have tamed this issue.  I know IntelliJ IDEA reports various times when it's better to use the + signs vs. a StringBuilder.  I've checked the compiled code a few times when I thought it was wrong, and it turned out to be right, so now I just trust it to tell me.


Tiny function to ensure a node of a BST has a valid relationship with its children

Which of my two versions is more pleasant and readable?

The second is just bad as said in the comment by JK01.

It should be just

return !(hasLeft() && left.compareTo(this) > 0 ||
    hasRight() && right.compareTo(this) < 0);

and then you could use De-Morgan rule to get rid of the outer negation. However, something like

return (!hasLeft() || left.compareTo(this) <= 0) &&
    (!hasRight() || right.compareTo(this) >= 0);

has nothing to do with the idea it represents. Sticking with the original and adding braces is best:

private boolean nodeIsValid() {
    if (hasLeft() && left.compareTo(this) > 0) {
        return false;
    }
    if (hasRight() && right.compareTo(this) < 0) {
        return false;
    }
    return true;
}

It's easily extensible: Just add another condition.
It's structured: 2 simple expressions instead of a multiline monster.
It corresponds exactly with what could go wrong.


Is this the most efficient way of doing it?

Sometimes the simplest solution is also the most efficient solution.  I'm not sure why you decided to use Math.pow and PHI to compute something that can be easily (and more quickly) be computed with simple addition:

public class EvenFibonacciFinder {
    private static final int MAX_NUM = 4_000_000;

    public static void main(String[] args)
    {
        long time = System.nanoTime();
        int  f1   = 1;
        int  f2   = 2;
        long sum  = 0;

        while (f2 <= MAX_NUM) {
            int f3;
            sum += f2;
            // This skips three ahead in the sequence.
            f3 = f1 + f2;
            f1 = f2 + f3;
            f2 = f1 + f3;
        }
        long end = System.nanoTime();
        System.out.println("Result: " + sum +
                "\nTime used for calculation in nanoseconds: " +
                (end - time));
    }
}

Output:

  Original code using pow:
  Result: 4613732
  Time used for calculation in nanoseconds: 9952

  Using addition instead of pow:
  Result: 4613732
  Time used for calculation in nanoseconds: 934

(Note: both programs were modified to measure the end time before the println(), otherwise some of the string concatentation time was being counted).


Some tips:

You could replace the innermost if with return
Adding doctests would be nice
Note that abs(a - b) is the same as abs(b - a). To avoid repeated calculation of abs values, it would be more optimal to cache in local variables

Like this:

def close_far(a, b, c):
    """
    >>> close_far(1, 2, 10)
    True
    >>> close_far(1, 2, 3)
    False
    >>> close_far(4, 1, 3)
    True
    """
    diff_ab = abs(a - b)
    diff_ac = abs(a - c)
    if diff_ab <= 1 or diff_ac <= 1:
        diff_bc = abs(c - b)
        return diff_ac >= 2 <= diff_bc or diff_ab >= 2 <= diff_bc
    return False


Calculating Earnings from attendance details

General point
Is there a strong reason for going with MVP?  One of the downsides of an MVP approach is that a lot of the nice data-binding facilities within the architecture get bypassed.  A Presentation Model / Model-View-ViewModel (MVVM) approach is pushed for WPF and can be used with Winforms.

There is a nice write-up on MVP to be found at MVC vs. MVP.

Form / Presenter
Whichever flavour of MVx one goes with, a basic idea is that the View doesn't need to know about the Presenter (and vice versa).  You mentioned excluding the interfaces and DI but in the Form code, it still needs to know about the Presenter class - its method signatures et al - and the Presenter knows about each of the controls on the Form.

Another way of structuring this is to create an interface

interface ISalaryFormView {
    event EventHandler<EventArgs> RequestProcessEarnings;
    void SetSalaryDetails(IEnumerable<SalaryDetails> salaryDetailsList);
    DateTime StartDateTime { get; set; }
    DateTime EndDateTime { get; set; }
}

(The SetSalaryDetail() method and StartDateTime, EndDateTime properties are part of the reason why MVVM is being pushed. A lot less plumbing code)

and have the Presenter take an ISalaryFormView as an argument

class SalariesPresenter {

    private readonly ISalaryForm _form;
    private readonly SalariesService _service;

    public SalariesPresenter(ISalaryForm form, SalariesService service) {
        _form = form;
        _service = service;
        _form.ProcessEarningsRequested += HandleProcessEarningsRequested;
    }

    private void HandleProcessEarningsRequested(object sender, EventArgs e) {
        _form.SetSalaryDetails(_service.GetSalaries(_form.StartDateTime, _form.EndDateTime));
    }
}

In the form, we now implement the interface and rout the click to raising the event

public partial class MainWnd : Form, ISalaryForm  {

    public MainWnd() {
       InitializeComponent();
    }

    private void btnProcess_Click(object sender, EventArgs e) {
        RaiseProcessEarningsRequested();
    }

    #region ISalaryForm

    public void SetSalaryDetails(IEnumerable<SalaryDetails> salaryDetailsList) {
        dgvSalaries.DataSource = salaryDetailsList;
        dgvSalaries.Refresh();
    }

    public DateTime StartDateTime {
        get { return dtpStartDate.Value; }
        set { dtpStartDate.Value = value; }
    }

    public DateTime EndDateTime {
        get { return dtpEndDate.Value; }
        set { dtpEndDate.Value = value; }
    }

    #region ProcessEarningsRequested

    public event EventHandler<EventArgs> ProcessEarningsRequested;

    protected void RaiseProcessEarningsRequested() {
        OnRaiseProcessEarningsRequested(EventArgs.Empty);
    }

    protected virtual void OnRaiseProcessEarningsRequested(EventArgs e) {
        var handler = ProcessEarningsRequested;
        if (handler != null) {
            handler(this, e);
        }
    }

    #endregion

    #endregion

}

We do this to help the testing in the Presenter

It doesn't need to know the concrete class of the Form - it is working against an interface.
It doesn't need to know the final screen format - swap out a listview for the datagrid and it doesn't impact.
We can unit test by having a Mock raise and event and verifying that the Setter is called.

DataService
It is a personal preference but I have a dislike of passing around data in DataTables, especially untyped datatables.  A quick web search will give lots of reasons against doing so. Adding data containers and reading into them doesn't add that much work.  That said, it is a personal preference.  The datatable is a lot faster and doesn't impact the MVx shape at all.

Passing the DataGrid in as a parameter though is a bad idea. We have now a linkage to System.Windows.Controls that is totally unnecessary and impacts portability (say we want to use this on the server side of a Web app or migrate to WPF). Even changing the screen layout - changing to a DataGridView instead of a DataGrid is impacted. Passing in a IEnumerable<> of some Data Transfer Object (DTO) (or even a datatable) is a better idea. No layer behind the view should know about or be concerned with the screen controls.

EDIT
Generally I would return an IEnumerable<T> rather than an IList<T> but in the example I am working on this is giving strange results => the DataGridView is not refreshing correctly for IEnumerable<T> but works fine for IList<T>.

For the minimal example I have two columns, Name and Value,

I have a SalaryDetails class

public class SalaryDetails {
    public string Name { get; set; }
    public decimal Value { get; set; }
}

and the SalariesService class

public class SalariesService {

    public IList<SalaryDetails> GetSalaries(DateTime start, DateTime end) {
        return ReadTable(start, end).Rows.OfType<DataRow>().Select(CreateSalaryDetails).ToList();
    }

    private static DataTable ReadTable(DateTime start, DateTime end) {
        var ret = new DataTable();
        ret.Columns.Add("Name", typeof (string));
        ret.Columns.Add("Value", typeof(decimal));

        ret.Rows.Add(new object[] { "January", 1.1m});
        ret.Rows.Add(new object[] { "February", 1.21m });
        ret.Rows.Add(new object[] { "March", 1.331m });
        ret.Rows.Add(new object[] { "April", 1.4641m });
        ret.Rows.Add(new object[] { "May", 1.651051m });

        return ret;
    }

    private static SalaryDetails CreateSalaryDetails(DataRow row) {
        return new SalaryDetails() {Name = (string) row["Name"], Value = (decimal) row["Value"]};
    }

}

The ReadTable() is a placeholder for your current Calculate() call and the Select() call is a quick way to create the SalaryDetails entries from the datarows.

Notes
I hadn't looked over your Calculate code in detail (I felt that wasn't really part of the MVP question) but looking at it now I have a few comments.
1) AFAIK, you shouldn't need a DataSet. You should be able to create and fill the table without one - not worth it to me to set up a DB to try it out but you might.
2) The using block on the datatable looks a bit strange.  On leaving the using block (i.e. when returning), Dispose() is called on the DataTable.  This doesn't appear to do anything (the data is still in the DataTable) so it is probably worth leaving out. (A quick wander down through the DataTable code shows no specific implementation for Dispose, it uses the base MarshalByValueComponent version)

EDIT
There is an IsNull() method on the DataRow.  One can use an extension to check for nulls and return default values

public static class DataRowExtensions {
    public static T GetValue<T>(this DataRow row, string name) {
        return row.IsNull(name)
                ? default(T)
                : row.Field<T>(name);
    }
}


This is a very instructive example of wrong judgement. I understand (correct me if I am wrong) that you went for a low-level write to avoid seemingly unnecessary overhead of FILE * functions offered by a stdio library. Not only it made your code less portable, it in fact made id slower!

The net effect is that your code invokes a system call for each 10 characters.

System call is an extremely expensive operation. It involves switching memory maps from a user to a kernel space, and on top of that it faces who knows how many cache misses. This is exactly the problem stdio solves by internal buffering.

This is how your original code behaves:

~/projects/play/cr/pedro $ time ./original

real    0m7.929s
user    0m0.484s
sys     0m7.432s

I changed opening a file to

FILE * file = fopen(fi, "w");

and writing to it to

    fputs(cad, file);

and the new timigs are

~/projects/play/cr/pedro $ time ./with-stdio

real    0m0.908s
user    0m0.276s
sys     0m0.584s

PS To make it a code review:

You shall #include at least <sys/types.h>, <sys/stat.h>, <fcntl.h> and <time.h>.