Get list of new questions from Stack Overflow

This is nice code for someone just learning Clojure. You haven't made any of the common pitfalls like trying to use def to create local variables. I'm going to just jump around and mention things as I see them.

Your parse-int function is much slower (and arguably more manual) than it needs to be.

If you run lein check on your project, you'll see the following warning:

call to java.lang.Integer ctor can't be resolved.

It's also highlighted in yellow in IntelliJ for the same reason. It can't tell what overload of Integer. to use since it doesn't know with certainty what type re-find returns. This is forcing it to use reflection at runtime to do lookups, which can be very slow. Add a type hint to tell it exactly what re-find returns:

(defn parse-int [s]
  "convert string to int"
  (Integer. ^String (re-find  #"\d+" s)))

Here's some timings using Criterium, a great benchmarking library. Below, cc is an alias for criterium.core:

; Without type hints

(cc/bench
  (parse-int "1234567890"))

Evaluation count : 38179800 in 60 samples of 636330 calls.
             Execution time mean : 1.636166 µs  ; <-----------------------
    Execution time std-deviation : 226.156823 ns
   Execution time lower quantile : 1.459082 µs ( 2.5%)
   Execution time upper quantile : 2.309723 µs (97.5%)
                   Overhead used : 4.213229 ns

Found 5 outliers in 60 samples (8.3333 %)
    low-severe   5 (8.3333 %)
 Variance from outliers : 82.3868 % Variance is severely inflated by outliers

; With type hints

(cc/bench
  (parse-int "1234567890"))

Evaluation count : 187133520 in 60 samples of 3118892 calls.
             Execution time mean : 318.835981 ns  ; <-----------------------
    Execution time std-deviation : 3.399965 ns
   Execution time lower quantile : 314.452726 ns ( 2.5%)
   Execution time upper quantile : 326.997655 ns (97.5%)
                   Overhead used : 4.213229 ns

Found 4 outliers in 60 samples (6.6667 %)
    low-severe   2 (3.3333 %)
    low-mild     2 (3.3333 %)
 Variance from outliers : 1.6389 % Variance is slightly inflated by outliers

That's over 5x faster just from adding type-hints.

Here's a personal favorite of mine though that's much faster, and just falls back onto Java's parseInt implementation:

(defn my-parse-int [^String str-num]
  (try
    (Integer/parseInt str-num)  ; Fall back onto Java

    (catch NumberFormatException _
      nil)))  ; Return nil on a bad parse

(cc/bench
  (my-parse-int "1234567890"))
Evaluation count : 1531312920 in 60 samples of 25521882 calls.
             Execution time mean : 35.208889 ns  ; <-----------------------
    Execution time std-deviation : 1.018581 ns
   Execution time lower quantile : 34.554978 ns ( 2.5%)
   Execution time upper quantile : 38.078887 ns (97.5%)
                   Overhead used : 4.213229 ns

Found 7 outliers in 60 samples (11.6667 %)
    low-severe   4 (6.6667 %)
    low-mild     3 (5.0000 %)
 Variance from outliers : 15.8023 % Variance is moderately inflated by outliers

35 ns!

Note how I'm wrapping the parsing call in a try and returning nil in the event of an exception. In Clojure, it's common for nil to represent the absence of a valid value; like after a bad parse. It's similar to other language's notion of an Optional type. This concept allows you to do all sorts of nice things. Like, say you have a list of possible String numbers and you want to grab the first valid number:

(some my-parse-int ["bad" "also bad" "123" "another bad"])
=> 123

some ignores all the nils because they're falsey.

(cond
  (= has_more true) (fetch-question (+ page 1) from site (concat accum questions))
  :else (concat accum questions))
))

Isn't written ideally.

A cond with only one condition should just be an if unless you have a strong suspicion that you'll need to add more cases later
(= ... true) is redundant. if is already checking if the condition evaluates to a truthy value.
(+ page 1) can be simply (inc page)
Trailing closing braces like that aren't generally considered to be idiomatic style. Ideally you're using a good IDE that uses par(enthesis)-infer. That lets you write Clojure code using indentation to indicate nesting like it's Python. I never worry about braces when writing Clojure, and never manually type closing braces.

If you have a decent computer, I recommend the Community version of IntelliJ, paired with the Cursive plugin that allows for writing Clojure (both are free for personal use). I've been using this setup for three years now, and it's excellent (heavy, but excellent).

Anyways, I'd write that chunk just as

(if has-more
  (fetch-question (inc page) from site (concat accum questions))
  (concat accum questions))

That reads nicer anyways. You write (concat accum questions) twice though. I'd probably bind that to a name to reduce redundancy:

(let [...
      more-questions (concat accum questions)]
  ...

  (if has-more
    (fetch-question (inc page) from site more-questions)
    more-questions))

With

(defn print-questions [questions]
    (doseq [q questions] (println (get q "title"))))

I wouldn't shove everything onto one line like that. I would spread that out:

(defn print-questions [questions]
  (doseq [q questions]
    (println (get q "title"))))

I'm not sure if you know about Clojure's doc-strings, but you have yours in the wrong place. The doc-string comes before the argument list. defn actually expects a String to internalize to act as a doc-string (see the docs of defn). Just move it up:

(defn save-time
  "save value to configuration file; file will be overwritten"
  [value]
  (spit config-file-name value))

Now good IDE's can show that documentation when requested.

Also, most of your casing is correct, but remember Clojure using dash-casing like I changed it to, not camelCasing, or snake_casing like you're using elsewhere. Consistency is key for readability.


why does this programs speed not increase?

Contrary to your belief, running a program with more threads than the number of processors (Runtime.getRuntime().availableProcessors()) will not increase the performance of your program, in fact it will decrease performance. The decrease in performance occurs because your processor has to jump from thread to thread. That is not a time-free operation.

The exception to this rule being if you have a lot of blocking I/O operations in your threads, in that case, more threads than the number of processors may be appropriate for your use.

I suggest you use an ExecutorService which runs with the correct number of threads (possibly obtained through one of the factory methods in Executors) and submit tasks for it to complete.


Booleans are normal values:

lessThan n (a, b)
  | a <= n = True
  | otherwise = False

Simply write:

lessThan n (a, _) = a <= n

Use pattern matching:

toRoman' :: Integer -> String
toRoman' x
  | x == 0 = ""
  | x > 0 = (snd . numToSubtract $ x) ++ toRoman'(nextNum)
      where nextNum = x - (fst. numToSubtract $ x)

If you want to take fst and snd of the same tuple, think about pattern matching.
Minor point: brackets in toRoman'(nextNum) are redundant, simply write toRoman' nextNum.

toRoman' :: Integer -> String
toRoman' x
  | x == 0 = ""
  | x > 0 = b ++ toRoman' (x - a)
      where (a, b) = numToSubtract x

Remove duplication:

toRoman and toRoman' contain duplicate code. In fact toRoman is only used to treat specially 0, so can be changed:

toRoman :: Integer -> String
toRoman 0 = "N"
toRoman x = toRoman' x

Move or remove utility functions:

lessThan and numToSubtract are used only once and don't seem to be generally useful, maybe inline them:

toRoman' :: Integer -> String
toRoman' x
  | x == 0 = ""
  | x > 0 = b ++ toRoman' (x - a)
      where (a, b) = head $ filter (\(a,_) -> a <= x) convMap

As Dan Burton commented, you can write also:

      where (a, b) = head $ filter ((<= x) . fst) convMap

Final code

convMap = [(1000,"M"), (900,"CM"), (500,"D"), (400,"CD"), (100,"C"),
           (90,"XC"), (50,"L"), (40,"XL"), (10,"X"), (9,"IX"), (5,"V"),
           (4,"IV"), (1,"I")]

-- Auxiliary function just so we treat 0 differently
-- (avoids 3 == "IIIN" if not used)
toRoman :: Integer -> String
toRoman 0 = "N"
toRoman x = toRoman' x

toRoman' :: Integer -> String
toRoman' x
  | x == 0 = ""
  | x > 0 = b ++ toRoman' (x - a)
      where (a, b) = head $ filter ((<= x) . fst) convMap

Fold

If you stare a little at the code, it turns out you each entry from convMap only once. First you check how many M's you need. Then CM's. Then D's. And so on. Using "filter" function always restarts search from beginning. In fact, toRoman can be written as a fold!

import Data.List (genericReplicate)

convMap = [(1000,"M"), (900,"CM"), (500,"D"), (400,"CD"), (100,"C"),
           (90,"XC"), (50,"L"), (40,"XL"), (10,"X"), (9,"IX"), (5,"V"),
           (4,"IV"), (1,"I")]

toRoman :: Integer -> String
toRoman 0 = "N"
toRoman x | x > 0 = snd $ foldl f (x,[]) convMap
  where f (n,s) (rn, rs) = (l, s ++ concat (genericReplicate k rs))
              where (k,l) = divMod n rn

Going crazy with abstractions

Erik Hilton's nice answer gives a solution using unfoldr. So you can write the code using fold and unfold, and these are two ways of looking at it. I believe that combination of fold and unfold is called "paramorphism" or "apomorphism" or something like that...


typedef struct weapons {
    int dagger = 2, sword = 3, axe = 4, mace = 5, bow = 3, arrows = 2;
} weapons;

The typedef struct X { ... } X; pattern is a C-ism; in C++ you don't need the typedef and can just write struct X { ... };.

You're creating a struct type named weapons with a bunch of per-instance member variables. This is almost certainly not what you meant to do. Probably what you meant was

enum class Weapon {
    dagger = 2,
    sword = 3,
    axe = 4,
    mace = 5,
};

so that you could later write

Weapon w = Weapon::sword;
if (w == Weapon::axe) { ... }

What you actually wrote, unfortunately, is simply nonsense.

character characterCreation(string name);

Look up the C++ notion of "constructors" (and also destructors). What you have here would normally be spelled something like

Character::Character(const std::string& name) {
    this->name = name;
    this->strength = rand() % 5 + 5;
}

and so on.

Also consider writing yourself a helper function

int randint(int lo, int hi) {
    return rand() % (hi - lo) + lo;
}

so that you can write simply

    this->strength = randint(5, 10);

Ninety percent of what we call "programming" is just finding sources of repetition and eliminating them.


The reason that you are getting so many more entries is because of this list comprehension:

 students_plus_codes = [x + str(" - " + y) for y in students for x in code_list]

It's a nested for loop. If we expand it we can see what is happening:

students_plus_codes = []
for y in students:  # students has 24 items
    for x in code_list:  # code_list has 24 items
        students_plus_codes.append(x + str(" - " + y))

So for every iteration of students you do 24 iterations of code_list.

Fortunately, python has a builtin function called zip that will merge lists for us. So we can replace the nested list comprehension with this line:

students_plus_codes = list(zip(students, code_list))

Which results in a list of tuples:

[('Aljoša', '256D2B'), ('Blažka', 'OEGJL9'), ('Nana', 'GB1PJL'), ('Kaja', 'F0P0F2'),
 ('Alja', '62KU94'), ... ('Matic', 'E7CJIP'), ('Marija', '1D2UCL'), ('Žiga T.', '6X1DD5')]

Generating the codes:

First, I would replace for i in range(24): with for i in range(len(students)): as this allows you to change the number of students without having to change other aspects of your code. In this instance 24 is a magic number that could cause issues down the line.

You could even create a function that generates each code, then you can use an easy to read list comprehension.

# <=python3.5
def generate_code(n, characters):
    return ''.join([random.choice(characters) for _ in range(n)])

# >=python3.6
def create_code(n, characters):
    return ''.join(random.choices(characters, k=n))

Printing the codes:

It isn't ideal to join the names and codes as a single string as this makes it hard to use them separately later. For this reason, I used a list of tuples to match them as pairs. To print them the for loop has two variables, student and code that takes advantage of unpacking and then prints them using the format function.

for student, code in students_plus_codes:
    print('{} - {}'.format(code, student))

Altogether:

import random
import string

def create_code(n, characters):
    return ''.join(random.choices(characters, k=n))

students = ["Aljoša", "Blažka", "Nana", "Kaja", "Alja", "Tjaša", "Ana",
           "Gal", "Danijela", "Alma", "Neja", "Žiga K.", "Patricija", "Aja",
           "Kristjan",  "Urban",  "Janja", "Lea", "Žana", "Aljaž", "Tilen",
           "Matic", "Marija", "Žiga T."]

# It generates the code and puts it in a list
key_size = 6
chars = string.ascii_uppercase + string.digits
code_list = [create_code(key_size, chars) for _ in range(len(students))]

# Combines the two lists (students and codes) into a list of tuples
students_plus_codes = list(zip(students, code_list))

for student, code in students_plus_codes:
    print('{} - {}'.format(code, student))


Make a given number by adding given numbers

Avoid repeated values

In your testing code, the values 4, 6, 9, 20 appear in multiple places. You could re-write your code to generate a formatted answer from the list:

num_list = [4, 6, 9, 20]
for num in range(100):
    answer = sumFinder(num_list, num)
    if answer:
        answer = " + ".join("{} * {}".format(a, b) for a, b in zip(num_list, answer))
    print(num, "=", answer)

Document your function and use the correct type

Your function returns both lists and boolean. Maybe it's be clearer to make it return a list (when a list is found) and None otherwise. This can be documented accordingly in a docstring.

def sumFinder(quantities, final_num):
    """Return a list such that dot-product(list, quantities) == final_num. Return None when no list is found."""
    if len(quantities) == 1:
        for i in range(final_num//quantities[0]+1):
            num = quantities[0] * i
            if num == final_num:
                return [i]
        return None
    for i in range(final_num//quantities[0]+1):
        num = quantities[0]*i
        found_nums = sumFinder(quantities[1:], final_num-num)
        if found_nums:
            return [i] + found_nums
    return None

Handle empty input

You access the first element of the input without checking the length first. Maybe it'd be clearer to document this as an invalid input or you could handle it properly by returning [] if final_sum == 0 else None.

Removing duplicated logic

When the empty case is handled, the case with 1 element doesn't need to be handled in a special way.

With a few minor changes, you can write:

def sumFinder(quantities, final_num):
    """Return a list such that dot-product(list, quantities) == final_num. Return None when no list is found."""
    if not quantities:
        return [] if final_num == 0 else None
    first, remain = quantities[0], quantities[1:]
    for i in range(final_num//first+1):
        found_nums = sumFinder(remain, final_num - first * i)
        if found_nums is not None:
            return [i] + found_nums
    return None

Names

Python names are usually snake_cased. Also, find_sum would be a better name that sum_finder which sounds like a class name.

final_num could be renamed target, n, etc.

quantities could be renamed lst


The first thing we can do to improve the efficiency of this code is to remember to check for an error and make sure that the returned objects array returns anything before we do anything.  Generally, code from Apple libraries would guarantee our objects array to be empty if there were any sort of error, but some libraries don't make that guarantee.

We can also store our allAchievements locally as an NSDictionary rather than an array.  If allAchievements is an NSDictionary, our code looks something more like this:

[earnedQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    for (PFObject *earnedAchievement in objects) {
        Achievement *achievement = allAchievements[earnedAchievement[@"achievmentId"]];
        if (achievement) {
            achievement.earned = @YES;
            achievement.earnedDate = earnedAchievement[@"earnedOn"];
        }
    }
    [context save:&error];
}];

Now we eliminate the nested loop.  And we only run through the outer loop once per earnedAchievement (which may be zero times).

Also, keep in mind that everything within the findObjectsInBackgroundWithBlock: is executing in the background.

Some other comments...

I would eliminate the use of magic strings.  Define all of your keys as constants somewhere.  This serves multiple purposes.

If we ever decide to actually change the key, it's changed everywhere all at once.
Typing magic strings is prone to typos, where as using a variable won't compile if we've made a typo (unless we typo into another variable name).
Typing magic strings won't auto-complete (which makes typos more likely, see point 2), but constant variables will.


I see three problems with this function:

Why calculate the values up to len(p), when you are actually interested in p[n] (which may be larger or smaller than len(p))? In the case of n > len(p) your code actually raises an exception (and it seems not to be excluded by the rules, but also not to be checked by the online judge).
This is not really using memoization, since you calculate everything again whenever the function is called.
You mutate p, which might lead to unexpected results (in general), although here it happens to work out fine.

The second (and third) problem are not so easy to fix (probably only by memoizing all different p ever seen and for each of them the maximum n used). Also the online judge may or may not use the same p again.

The first one however is an easy fix:

def cut_log(p, n):
    for i in range(2, n + 1):
        p[i] = max(p[i-k] + p[k] for k in range((i//2)+1))
    return p[n]


I currently create a new derived collection each time Volatilities changes

This was a good idea, but in this case I'd just recreate the brokers list (since it's not a straight volatilities.Select(x => ...), it's a SelectMany. One thing that's important though, is whether you mutate (i.e. add and remove) items from Volatilities, or you only replace the list (i.e. via an API call, set this.Volatilities to a new collection).

Pick one or the other, don't mix them or else your code will be complicated. Let's assume you're using ReactiveCollection and you're adding/removing to Volatilities.

Volatilities.CollectionCountChanged.StartWith(Volatilities.Count)
    .Select(_ => Volatilities.SelectMany(x => x.BrokerList))
    .ToProperty(this, x => x.Brokers);

Then, we can watch when someone changes Brokers - we'll do this in the constructor (along with everything else). Generally, if you're not calling RxUI methods in the constructor, you're Doing Something Wrong. You're wiring up on startup what will happen when various parts of your ViewModel change, those wires typically are constant:

this.WhenAny(x => x.Brokers, x => x.Value)
    .Subscribe(_ => SelectedBroker = Brokers.FirstOrDefault());

Now let's set up the IsMarket:

this.WhenAny(x => x.Brokers, x => x.Value)
    .Select(x => x.Count > 0)
    .ToProperty(this, x => x.IsMarket);

What We Can Learn™

The key point here though, is that IsMarket is directly related to Brokers and nothing else - we should describe that relationship without mentioning Volatilities, then separately describe the relationship between Volatilities and Brokers. We don't want to mix the two.


Looking through your whole module it's apparent you've only had experience with imperative programming (it's full of side-effects, variable re-bounds, in-place updates, ...). I've already written on the topic (see this and this) so I won't expand here about the goodness of functional programming.

I'd write:

def initialize(response_string)
  @code = parse_code(response_string)
  raw_headers, @body = parse_data(response_string)
  @headers = parse_headers(raw_headers)
end

You get the idea, create parsing methods (or class methods, actually they won't need instance variables, they are pure functions) with inputs (arguments) and outputs that get assigned/bound to instance variables just once (not incidentally, that makes those methods easier to test).

On the other hand, there are already good network libraries for Ruby, what's the point of re-implementing them?

[EDIT] You asked for further advice. Ok, let's get a couple of methods of Response and refactor them:

def parse_data(raw_data)
  all_headers, body = raw_data.split("\r\n\r\n", 2)
  raise InvalidHttpResponse unless body && raw_data.start_with?("HTTP")
  raw_headers = all_headers.split("\r").drop(1)
  [raw_headers, body]
end

def decode_data(body)
  # You can use condition ? value1 : value2 for compactness
  data = if headers["Transfer-Encoding"] == "chunked"
    decode_chunked(body)
  else
    body
  end

  if headers["Content-Encoding"] == "gzip" && body.length > 0
    Zlib::GzipReader.new(StringIO.new(data)).read
  else
    data
  end
end

Ideas behind the refactor:

Put a space after a comma (more on style).
Don't reuse variables names (different values must have different names).
Don't update variables in-place.
Don't write explicit return.
Use if conditionals as expressions.
Use || && for boolean logic.
Put parentheses on calls (except on DSL code).


Searching text files for string patterns that are each defined in their own classes

It's very easy: you shouldn't. An interface is used to indicate that a subset of classes present common behaviour or should be considered similar in some way.
In your situation there simply is no reason to make this change because all you do is change a text value in a property, which could just as easily be done by taking an argument in your constructor and keeping a private backing fields which should then be used to populate the property's regex.
This will result in several code optimizations:

No heavy duplication of code in StringType1 and StringType2 (this should have been a red flag)

No reflection necessary to get the different types. Just keep a collection of the different regexes and return a collection of StringType objects, constructed with your regexes.

Additionally, this code will also be obsolete:
public IStringType getNewInstance(string msg)
{
    return (IStringType)(new stringType2(msg));
}

since you should just overwrite that variable with new Stringtype(thisVariable.StringPattern, message).
Ultimately, your code would look something like this:
public class StringType
{
    private IPatternProcessor _processor;
    private string _pattern;
    private string _message { get; set; }

    public StringType(string str, IPatternProcessor processor)
    {
        _message = str;
        _processor = processor;
    }

    public string StringPattern {
        get { return pattern; }
        set { pattern = value; }
    }

    public void Process() {
        _processor.Process(_message);
    }
}

public static class PatternFactory
{
    private static List<String> _patterns = new List<String>();

    static PatternFactory() {
         _patterns.Add("(?m)^TEST1.+[\r\n]";);
         _patterns.Add("(?m)^BLAH2.+[\r\n]";);
    }

    public static List<StringType> GetTypeList()
    {
        return _patterns.Select(x => new StringType(x));
    }
}

public interface IPatternProcessor {
    void Process(string input);
}

public class ProcessMethod1 : IPatternProcessor { }
public class ProcessMethod2 : IPatternProcessor { }

If you want to make it easy for your user, you can hardcode these different methods into properties:
public class PatternProcessor {
    public IPatternProcessor ProcessMethod1 { get { return new ProcessMethod1(); } private set; };
    public IPatternProcessor ProcessMethod2 { get { return new ProcessMethod2(); } private set; };
}

Now you can simply call this with
new StringType(input, PatternProcessor.ProcessMethod1).Process();

If you were really into it, you could just cache the IProcessMethod objects in a collection in your PatternProcessor class (provided each method is stateless), but that might be going a little too far out of the scope of this review.
Style notes

Classes are UpperCamelCase (StringType)
Private fields are less standardized but they are often written as _field
Methods and constructors are always capitalized (StringPattern, StringType), just like the class

Conclusion
This code does not benefit from interfaces at all and as such it is impossible to review it since interfaces are the main problem with the code.
Post-edit
So, with the additional requirement of pattern-specific behaviour the introduction of interfaces and separate types now makes a lot more sense. I see two architecture options off the bat:

Separate StringType classes for each situation (if you name them StringType1, StringType2 etc, I'll chase you with a bat)

Separate strategies (strategy pattern) for each type of processing with a sauce of factory pattern

I will go with the second option because it would require less rewriting. Someone else can write the less complex first option but the second option is more flexible in terms of allowing two different patterns to use the same processing option.
I will change the earlier block of code with some additions to keep everything in one place.


Unless you're overwriting properties set elsewhere, there's no reason for this line because this is the default for all flex containers:

flex-flow: row nowrap;

If your goal is to make this work on browsers with either of the old Flexbox implementations, there are 2 things to be aware of:

The March 2012 draft (IE10) does not have individual properties for flex-grow, flex-shrink, or flex-basis.  The only way to control them is via the flex shorthand.
The original draft does not allow you to have differing flex-shrink and flex-grow values.  It would be ok to translate flex: 1 1 auto to box-flex: 1, but you can't translate something like flex: 1 0 (with prefixes).  For your purpose, box-flex: 0 should work (though you might have problems with buttons in old Webkit browsers, see: https://stackoverflow.com/questions/16961192/flexbox-doesnt-work-with-buttons).


An explicit cast for narrowing numeric conversions

The first thing I noticed: you only support basic arithmetic types (integral and floating point).  This isn't apparent from the name narrow_cast.  Either enforce this with a static assert, or provide a mechanism to provide extensions for user defined types.

Here's what you write:

template <typename T, typename U>
constexpr bool can_fully_represent =
    std::is_same<T, U>::value ||
    ( std::is_integral<T>::value && std::is_integral<U>::value &&
        ( ( std::is_signed<T>::value && sizeof(T) >  sizeof(U) ) ||
          ( is_same_signedness<T, U> && sizeof(T) >= sizeof(U) ) ) ) ||
    ( std::is_floating_point<T>::value && std::is_floating_point<U>::value && sizeof(T) >= sizeof(U) );

Here's what I think should be sufficient:

template <typename T, typename U>
constexpr bool can_fully_represent =
       std::numeric_limits<T>::min() <= std::numeric_limits<U>::min()
    && std::numeric_limits<T>::max() >= std::numeric_limits<U>::max();

OK, maybe I overlooked some edge cases, but that's the idea.

The unchecked version uses a forwarding reference, whereas the check version does not.  Try to keep the interface consistent.

std::is_same<T, U>::value can be simplified to std::is_same_v<T, U>.


Checking if a number fits in a primitive type

String input;
for(int times = 0; times < t; times++) {
    // Ask for the number
    input = in.next();

There's no need to declare input outside of the loop. It has no advantage at all as you don't need to keep it between iterations. Always minimize the scope.

       // If the longValueExact() returns a greater number than the long max value, then it throws an ArithmeticException

As pointed in a comment, I misread longValueExact as longValue. Updated the answer, so that both are covered.

For longValue, this isn't true and the Javadoc says it pretty clearly:

  if this BigInteger is too big to fit in a long, only the low-order 64 bits are returned

For longValueExact, the following is said

  If the value of this BigInteger is out of the range of the long type, then an ArithmeticException is thrown.

So checking for exception is correct. If it gets thrown, the number doesn't fit in long and obviously in no smaller type either.

        if(number.longValueExact() < Long.MAX_VALUE && number.longValue() > Long.MIN_VALUE)
        {
            System.out.println("* long");
        }

By definition, there's no long bigger than the biggest long, is it?

So this test is a tautology.

Using longValueExact makes the program correct. With longValue, it wouldn't work and instead of testing if a number fits in a type, you test if its lowest 64 bits do.

Still, letting an exception be thrown for a normal program flow is extremely inefficient as the JIT assumes that exceptions are well... exceptional. Moreover, filling their stacktrace is pretty complicated and slow, as they actually don't exists in an optimized code.

In order to get a faster code, you need to do it the other way round: Convert to BigInteger and then compare. As a bonus to speed, you get compatibility with Java 7.

You should also fix your spacing and braces. Let your IDE do it, it's free.


Both are fine, and it's a matter of choice.

The first definition, being a composition of functions, treats snd . head . filter (\(k, v) -> key == k) as one big function.  It can therefore be transformed more easily into point-free style, if you like that kind of thing.

findKey'' :: (Eq k) => k -> ([(k, v)] -> v)
findKey'' key = snd . head . filter (\(k,v) -> key == k)


Basic playing card generation and shuffle

First off I want to say that your decision to make an array that represents the ordering permutation is a really good idea. Many people would have passed in the array to be shuffled and had it mutated. Returning a permutation and applying that to an ordered array is a conceptually much nicer way to go.

Your shuffle algorithm has an interesting and common bug. Your shuffle algorithm is "generate the vector {0, 1, 2, 3, 4, ..., 51}. For each position 0 through 51, swap the current contents with a randomly-generated position".

Let's do a little math. Suppose we have only three cards, to make the math easier. How many decks are there? Six:

0, 1, 2
0, 2, 1
1, 0, 2
1, 2, 0
2, 0, 1
2, 1, 0

Each deck should be as likely as any other.

How many paths through the algorithm are there? Twenty-seven, each equally likely:

Swap 0 with 0, swap 1 with 0, swap 2 with 0
Swap 0 with 1, swap 1 with 0, swap 2 with 0
Swap 0 with 2, swap 1 with 0, swap 2 with 0
Swap 0 with 0, swap 1 with 1, swap 2 with 0
Swap 0 with 1, swap 1 with 1, swap 2 with 0
Swap 0 with 2, swap 1 with 1, swap 2 with 0
Swap 0 with 0, swap 1 with 2, swap 2 with 0
Swap 0 with 1, swap 1 with 2, swap 2 with 0
Swap 0 with 2, swap 1 with 2, swap 2 with 0

... I won't list all of them.

Now we have 6 possible outcomes and 27 paths through the algorithm, so plainly some of the outcomes must be produced more often than the others. There is no way to divide 27 paths into 6 sets such that each set has the same number of elements.

The same is true with your shuffle; there are \$52!\$ possible decks and \$52^{52}\$ paths through the code, and those don't divide evenly into each other.

What you've done is the most common incorrect implementation of the Knuth Shuffle.  Now go do some research and figure out how to fix your bug; it's an easy fix.

Once you've done that, you've still got a problem. There are 52! possible decks but only \$2^{32}\$ possible seeds to Random, so you are still not sampling the space of all possible decks fairly.  If you care about this, you should probably use a crypto-strength randomness generator.

You might be interested in my articles on these subjects.

http://ericlippert.com/2013/04/15/producing-permutations-part-one/
http://ericlippert.com/2014/10/13/producing-combinations-part-one/

Other problems with your code:

int[][] deck;

What the heck?  A deck of cards is an array of arrays of integers?  That's craziness.  I want to see

Deck deck = new Deck();

Programming computers is the art of creating meaningful abstractions.  A deck is not an array of arrays of integers.  A deck is a deck. Make a class that represents the concept of deck that abstracts away this mechanism.

String clabel;

We pronounce that "klabel" of course.

Seriously, typing out the remaining letters of a word will not cause you to die younger.

Later...

  String c_label, s_name = "", v_name = "";

Oh, it's c_label now when it was clabel before. Now would be a good time to get into good habits. I don't care what your naming strategy is, so long as it is (1) comprehensible, and (2) consistent.  Your strategy is neither.  My preference as a C# programmer is

cardLabel

but

card_label

is idiomatic in Java.  Better entirely though would be to make a Card type that has a label getter.

        order = new int[decksize];
        order = shuffle(decksize);

If you saw

x = 1;
x = 2;

you would immediately note that the first line is pointless. But your code is equally pointless for exactly the same reason.

Something made you think that you needed to initialize order to a new array immediately before throwing it away, just like the contents of x are thrown away. What incorrect process of thought led you to this conclusion?  Can you examine that process?

These are not rhetorical questions. I analyze these sorts of programming errors for a living and I am very interested in the beginner-mind psychology that leads to them. Any insights would be appreciated.

WHY IS "ACE" IN ALL CAPS? It seems weird.


Strongly-connected component for a graph

Firstly, I think you class name can be improved somewhat. Sure, it tells you the underlying data structure that the graph will use (sort of, anyway), but it doesn't tell you anything about what kind of graph it is. Unless you read the source, you won't know that this is supposed to represent a directed graph - so why not put that in the name: directed_matrix_graph.

Speaking of underlying data structure, simply taking an int** that you don't copy, but simply use as-is, is generally not good practice. Most users of a class like this will assume that it manages its own memory. This puts the onus on the user to make sure everything used in your class remains within scope. I'd recommend replacing this with a std::vector<std::vector<int>> which manages its own memory. This should probably have a constructor which it initializes from a template; something like:

class matrix_graph
{
private:
    std::vector<std::vector<int>> vertexes;

public:
    template <typename Iterator>
    matrix_graph(Iterator begin, Iterator end)
    {
        std::vector<int> v(begin, end);
        for(std::size_t i = 0; i < v.size(); ++i) {
            vertexes.push_back(v);
        }
    }

...
};

Destructors shouldn't take parameters (even void), and you shouldn't declare one if it isn't going to do anything: the compiler generated one will suffice in this case.

Both  int get_max_vertexes() and bool is_connected(int i,int j) should be const methods, as these don't change the underlying matrix_graph:

int get-max_vertexes() const;
bool is_connected(int i, int j) const;

On to the main code: your dfs has a memory leak: you declare new Color[N] but never delete[] it. Again, using a std::vector will make these sorts of problems go away. It will also simplify the code:

void dfs(matrix_graph m, std::list<int>& visited_vertexes_in_order )
{
    std::vector<Color> c(m.get_max_vertexes(), WHITE);
    for(int i = 0;i < N; i++)
        if(c[i] == WHITE)
            matrix_dfs_visit(m, i, visited_vertexes_in_order, c);
}

In matrix_dfs_visit and dfs, you pass your matrix_graph by value and call it recursively. If you were actually storing graph vertexes in your class, this would get very slow very quickly. You aren't modifying the underlying matrix_graph here, so you should pass it by const-reference instead: const matrix_graph& m.

You have another memory leak in dfs_transpose, same solution applies as above. You pass your matrix_graph here by reference, but it is never changed. Since bool is_connected(int i, int j) should be const (if you change it per the advice given above), you can now pass by const matrix_graph&.

Similar complaint for void print_scc(list<int> & l), should be const list<int>& l. Anything that doesn't change should always be passed by const, this will make sure that the underlying object isn't changed (well, as long as people don't start const_casting things, but you have bigger problems in that case).

The algorithms themselves look like they come straight from CLRS so I won't bother going over them.

Some other general comments:

Use whitespace in loops: for(int i=0;i<vertexes;i++) is so much harder to read than for(int i = 0; i < vertexes; i++).
Avoid using namespace std as much as possible, even in .cpp files. In fact, you don't even use any standard library components in your matrix_graph.cpp file, so it doesn't even need to be there in the first place. Even if you did, the absolutely tiny time savings you get by not having to type out std:: in a few places is not worth the potential name clashes.
Put your code in a namespace, it's generally good practice.
In general, be careful of memory leaks. Use new as little as possible. Prefer std::vector to manually dealing with arrays: they stop memory leaks and offer much better exception safety.


This isn't "optimized", I just tried to make it more readable.
As I cant test it (really wish people would make jsbin examples to test with, buggered if Im going to do it) I have no idea if it works ;)

function onAccrualEndDateChange(current) {
  var endDate = $(current).val();

  if (endDate === "") {
    $(current).closest("td").removeClass("cell-error");
    return;
  }
  if (endDate === null) {
    $(current).closest("td").addClass("cell-error");
    return;
  }

  var actualEndDate = {
    month: endDate.getMonth(),
    date: endDate.getDate(),
    fullYear: endDate.getFullYear()
  };

  var tempEndDate = parseInt(actualEndDate.month + 1, 10) + "/" + actualEndDate.date + "/" + actualEndDate.fullYear;

  if (!ValidateDate(tempEndDate)) {
    $(current).closest("td").addClass("cell-error");
    return;
  }

  var startDate = $(current).closest("tr").find("input[id$='StartDate']").val();

  if (startDate === "") {
    $(current).closest("tr").find("input[id$='StartDate']").closest("td").addClass("cell-error");
    return;
  }
  if (startDate === null) {
    $(current).closest("td").addClass("cell-error");
    return;
  }

  var actualStartDate = {
    month: startDate.getMonth(),
    date: startDate.getDate(),
    fullYear: startDate.getFullYear()
  };

  var tempStartDate = parseInt(actualStartDate.month + 1, 10) + "/" + actualStartDate.date + "/" + actualStartDate.fullYear;

  if (!ValidateDate(tempStartDate)) {
    $(current).closest("td").addClass("cell-error");
    return;
  }

  if (actualStartDate.date > actualEndDate.date || actualStartDate.month > actualEndDate.month || actualStartDate.fullYear > actualEndDate.fullYear) {
    $(current).closest("td").addClass("cell-error");
  } else {
    $(current).closest("td").removeClass("cell-error");
  }
}


A Merge Sort implementation for efficiency

Some comments:

Include a convenience function that takes only a list, i.e., where you don't need to provide the bounds.
Don't fight Python's inclusive-start exclusive-stop paradigm and naming.
Write docstrings to explain what the parameters mean, especially if you use unusual stuff.
Don't compute mid when you don't have to anyway.
Compute mid with integer division and from the sum (Python's ints don't overflow).
Don't reimplement slicing.
You can easily do it with copying out just the left part.
For benchmarking, I'd suggest to randomly shuffle the list instead of using a reverse-sorted list. I suspect you did the latter because you thought it's a worst case, but for example for Python's built-in sorting algorithm Timsort, it's a "best case", taking only linear time. And other algorithms might also be unrealistically affected (either faster or slower than for the typical case).
Don't write an unstable merge sort, that's a sin :-P
4444444444444444444444 is unsafe. What if the list has items larger than that?

Here's my version of it, it's about three times as fast as yours both on reverse-sorted and on shuffled lists (tested with 100,000 items).
def merge(items, start, mid, stop):
    """Merge sorted items[start:mid] and items[mid:stop] into items[start:stop]."""
    for left in items[start:mid]:
        while mid < stop and items[mid] < left:
            items[start] = items[mid]
            start += 1
            mid += 1
        items[start] = left
        start += 1

def mergesort_slice(items, start, stop):
    """Sort items[start:stop]."""
    if stop - start > 1:
        mid = (start + stop) // 2
        mergesort_slice(items, start, mid)
        mergesort_slice(items, mid, stop)
        merge(items, start, mid, stop)

def mergesort(items):
    mergesort_slice(items, 0, len(items))


I assume the $items array is indexed by numbers, otherwise you have to change the code below to include a counter.

foreach ($items as $i => $item) {
    if ($i % 3 == 0) {
        // Do something for 0, 3, 6, 9, ...
    } elseif ($i % 3 == 1) {
        // Do something for 1, 4, 7, 10, ...
    } elseif ($i % 3 == 2) {
        // Do something for 2, 5, 8, 11, ...
    }
}

This code uses the modulo operator %.

After your edit
The following code is a more clear solution to your problem:

foreach (array_chunk($items, 3) as $chunk):
    echo '

';
    foreach ($chunk as $item):
        echo '' . $item . '	';
    endforeach;
    echo '

';
endforeach;


Password Generator with injected password model

Is there a cleaner way to "include" symbols and digits, I just appended them to a list.

Cast (rather than wrap) ascii_letters etc. to a set.

Is there anything built-in to exclude one list from another?

Yes - don't use lists; use sets and apply set subtraction.
Otherwise: if you perform a cursory scan of this site for Python-based password generators you will hear some of these same points, but -

Do not use random; use the secrets module to generate secure random numbers
PasswordGenerator being its own separate class does not make sense; it doesn't offer anything over generate so generate can be a free function or more likely a method on PasswordModel
charset would be better to return a set than a str
Maybe exclusion_list is being accepted as a string due to the valid concern that mutables (lists, etc.) should not be made parameter defaults. That's fine, though a type hint exclusion_list: Iterable[str] = "" should make it clear that other iterables are acceptable, such as a set or tuple.


Your first F# code isn't too bad. I've made some small simplifications to streamline your code a bit and take advantage of some built-in F# functions:

type internal CsvReader(source : Stream) =

    // input stream
    let stream = source

    // reader
    let mutable reader : StreamReader = new StreamReader(source)

    [<Literal>]
    let bufferSize = 1000

    // currently processed line
    let mutable buffer : char[] = Array.zeroCreate bufferSize

    // current position
    let mutable currentPosition = bufferSize

    // end of file
    let mutable EndOfFile = false

    // loads new chunk of data from file to buffer
    let UpdateBuffer() : bool =
        reader.ReadBlock(buffer, 0, buffer.Length) <> 0

    // initialization method
    let Initialize() =
        let pos = source.Seek(0L, SeekOrigin.Begin)
        if not (pos = 0L) then
            invalidOp "sdf"

    // read one char from stream
    let rec GetChar(eat : bool) : (bool * char) =
        let position = currentPosition
        match position with
        | 1000 ->
            match UpdateBuffer() with
            | false ->
                EndOfFile <- true
                false, Char.MinValue
            | true ->
                currentPosition <- 0
                GetChar eat
        | _ ->
            match int buffer.[position] with
            | 0 ->
                false, Char.MinValue
            | _ ->
                match eat with
                | true ->
                    currentPosition <- currentPosition + 1
                    true, buffer.[position]
                | false ->
                    true, buffer.[position]

    // default constructor logic
    do
        if Utils.IsNull source then
            nullArg "source"
        if not source.CanRead then
            invalidArg "source" "The source stream cannot be read from."
        if not source.CanSeek then
            invalidArg "source" "The source stream does not support seeking."

        Initialize()

    // parameterless constructor
    // always throws ArgumentNullException
    private new() = CsvReader(null)

    // just for testing
    member x.PublicGetChar = GetChar

One thing you'd definitely want to add (if this were production code) -- this class would ideally implement the IDisposable interface so you can properly close and release the resources associated with the StreamReader you use internally.


Nice:

using bytes = std::vector<std::byte>;

I would call it Bytes to make it clear it is a type rather than an object.

This is not a good idea:

using namespace std;

See: Why is “using namespace std;” considered bad practice?

This is technically not valid C++.

  byte data[length];

Variable sized arrays (VSA) are an extension to the language supported by several compilers but not actually part of the C++ standard. Though it is part of the more recent versions C standard.

Also creating a local array means that the data is being created on the local stack frame (here I assuming a Von-Neumann like architecture). This means for the data to exist after the function completes means you will need to copy it out of the function. So an alternative data object is probably a good idea.

Also there is a limitation on the size of array allowed on the stack (there are hardware limitations on the size of stack frames on lots of architecture).

So a god idea would be to use the same data structure that you return.

  Bytes data(length);   // This is basically std::vector

Now in older versions of C++ there are some nice optimizations that can be applied to std::vector when it is returned from a function that allow the compiler to build the std::vector at the final destination so that it is not actually copied on return.

In modern versions of the compiler the language has the concept of move semantics built into the language. So returning a std::vector is not an expensive operation as the internal buffer is moved (just the pointer is copied) from the function to the destination result.

Also the compiler is now required to perform copy elision of objects when it can.

Error checking

This code does zero error checking. There are several things that can go wrong and you don't check for any of them. But you said you removed this (you should have left it in).

So a better version:

#include <vector>
#include <string>
#include <fstream>
#include <cstdint>

using Bytes = std::vector<std::byte>;

Bytes read_block(std::uint32_t      offset,
                 std::uint32_t      length,
                 std::string const& filename)
{
  // Not going to explicitly check these.
  // The use of gcount() below will compensate for a failure here.
  std::ifstream is(filename, std::ios::binary);
  is.seekg(offset);

  Bytes data(length);
  is.read(reinterpret_cast<char*>(data.data()), length);

  // We have to check that reading from the stream actually worked.
  // If any of the stream operation above failed then `gcount()`
  // will return zero indicating that zero data was read from the
  // stream.
  data.resize(is.gcount());

  // Simply return the vector to allow move semantics take over.
  return data;
}


Given a list of numbers and a number k, return whether any two numbers from the list add up to k

Boolean -vs- boolean

Java provides both a Boolean and a boolean type; the difference being the first type is an Object where as the second is just a value.  Wherever possible, you should use a value type, for efficiency.  Since you return a simple true or false result, boolean is the correct return type to use:

...
    boolean ans = solution(arr, k);
...
private static boolean solution(int[] arr, int k) {
...

Autoboxing

The java Collections need Objects as keys and values.  The Java language will automatically "box" and "unbox" values as required.  You take advantage of autoboxing in map.put(k-v,true) ... The value k-v is autoboxed as an Integer and true is autoboxed as Boolean.TRUE.

Yet, when you retrieve the value from map, you explicitly do the autoboxing yourself: map.get(Integer.valueOf(x)).  You could simply write map.get(x).

Map -vs- Set

When you have a Map<K,V>, it is expected that different values will be stored in the map (under one or more keys).

In this case, you are only ever storing Boolean.TRUE (autoboxed from true).  Your map.get() either returns Boolean.TRUE, or it returns null if no value was stored under that key.  You explicitly test if it is equal to the former value, but you could have tested the value was not null instead.  Or more directly, you could test whether a value was stored under that key, and replace the complicated statement with simply:

if (map.containsKey(x)) { ... }

At this point, it should be clear we don't need a HashMap.  Simply a Set of Integer values.

final Set<Integer> set = new HashSet<>();
...
   set.add(k-x);
...
   if (set.contains(x)) {
...

Algorithm

As mentioned by hodisr, you need to take into account that the list of numbers may contain only one copy of the value x which is exactly half of the target value (k/2).  With your code, you add k-x to your container, and later successfully pull out the flag corresponding to x, and declare true.

Then, hodisr proceeds to demonstrate how to do it in one pass, and goes ahead and repeats the same error, by adding k-x to the container before testing whether x can be pulled out.  To obtain the correct result, the check for x must be made before putting k-x into the container.

private static Boolean solution(int[] arr, int k) {
    Set<Integer> set = new HashSet<>();

    for (int x : arr) {
        if (set.contains(x))
            return true;
        set.add(k-x);
    }
    return false;
}


CodedUi method which checks all cells in certain column

Disclaimer: Never done this UITestControl stuff

Edge case

If the searched columnName isn't contained in the header of the table I would expect the returned columnIndex to be -1 and therefor the check for IsNullOrWhiteSpace() will throw an exception.

Instead of using row.GetChildren() and then access the needed cell by index, you should better use the right tool for the job and call the GetCell(int) method.

Because an extension method can be also called directly like AllCellsInColumnHaveValue(aHtmlTable, aColumnName); you should ensure that the passed in HtmlTable tableis not null.


Checking if a directory exists in FTP without relying on exception handling

don't omit braces {} for single if statements. Using braces in this case will make your code less errorprone.
you want to return a state, which represents a specific states which shouldn't be restricted to only two states. This just calls for an enum.

public enum FtpResponse
{
    DirectoryExists, DirectoryNotFound, DirectoryNotSpecified
}

public FtpResponse DirectoryExists(string directory)
{
    if (String.IsNullOrEmpty(directory))
    {
         return FtpResponse.DirectoryNotSpecified;
    }
    // the rest of the code

}


Basic User Interaction in Python - syntax, docstrings, performance

Snippet 1.

The way yinyang is organized is quite unconventional. I presume that

tries += 1

is a typo (tries -= 1 would make much more sense). Even than I don't see a need for a recursion. A simple loop will do.

assert(input) also misses the point. If raw_input() succeeds, an assertion cannot possibly trigger; if not, EOFError will be raised. For the same reason, there's no need to

input = None

Passing yes and no arguments to yinyang need some serious justification. Returning True/False would be as good.

Snippet 2.

PUNCTUATION doesn't feel right: string.punctuation is there for a reason.

word.strip(p) is palliative. What if a punctuation mark is in the middle of the word?

A try/except flow is supposed to deal with problems beyond your control. It is not an if substitute. Besides,

    lc.word = word.lower()
    word_type = type_words.get(lc_word, None)

may not possibly raise AssertionError. Thus they do not belong to the try clause.

Also I guess you are trying too hard with affirmatives. y/n is just than enough.

Snippet 3.

I don't see a reason for class Sentence to exist. BTW it is not documented at all.


MessageFormat.format() with named parameters

Performing string substitutions using multiple passes is almost always the wrong approach, and leads to bugs.  If one of the values happens to be a string that looks like a %(key), then all sorts of unpredictable things could happen, including various uncontrolled format string attacks!

Therefore, the string replacements must be done in a single pass of the format string.  I recommend doing it using a regular expression.

Furthermore, your method provides no escape mechanism, in case you need to specify a literal %(blah) in the format string.  In Java, it would be customary to use backslash as an escape character.

Suggested solution

This solution uses Matcher.replaceAll(Function<MatchResult,String> replacer), which was introduced in Java 9, to provide each substitution text via a callback.

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NamedFormatter {
    private static final Pattern RE = Pattern.compile(
        "\\\\(.)" +         // Treat any character after a backslash literally
        "|" +
        "(%\\(([^)]+)\\))"  // Look for %(keys) to replace
    );

    private NamedFormatter() {}

    /**
     * Expands format strings containing %(keys).
     *
     *
Examples:

     *
     *

     *
NamedFormatter.format("Hello, %(name)!", Map.of("name", "200_success")) → "Hello, 200_success!"

     *
NamedFormatter.format("Hello, \%(name)!", Map.of("name", "200_success")) → "Hello, %(name)!"

     *
NamedFormatter.format("Hello, %(name)!", Map.of("foo", "bar")) → "Hello, %(name)!"

     *

     *
     * @param fmt The format string.  Any character in the format string that
     *            follows a backslash is treated literally.  Any
     *            %(key) is replaced by its corresponding value
     *            in the values map.  If the key does not exist
     *            in the values map, then it is left unsubstituted.
     *
     * @param values Key-value pairs to be used in the substitutions.
     *
     * @return The formatted string.
     */
    public static String format(String fmt, Map<String, Object> values) {
        return RE.matcher(fmt).replaceAll(match ->
            match.group(1) != null ?
                match.group(1) :
                values.getOrDefault(match.group(3), match.group(2)).toString()
        );
    }
}


Project Euler # 52 Permuted multiples in Python

For the umpteenth time, do not write

if not digits1 == digits2:
    return False
return True

Do write

return digits1 == digits2

The magic number 125000 must be explained. Preferably in the code, not in comments.
Seven levels of indentation should be immediately seen as a big bright red flag, style wise. At least fold it into the loop.
Seven levels of indentation should be immediately seen as a big bright red flag, algorithm wise. How would you approach a question asking for 16, rather than 6, multiples? As a side note, if you continue with PE, you have a chance to encounter it.
Expanding on the bullet above, please take my advice and study some math. This problem does have a nice solution. Ponder on the fact that \$142857 * 7 = 1000000 - 1\$. An Euler's generalization of Fermat's Little theorem is a must. PE is very fond of it.

And stop brute forcing.


I don't think that this data structure has any special name(vector of pointers sounds reasonable).

Now about the code itself:

I do not see any reason to use void* pointers here and cast them explicitly every time you access an element. You can just use vector<T*> addresses and get rid of all casts. You can also use smart pointers(unique_ptr looks like a good choice here). Here is my version of this class:

template<class T>
class PointerArray {
public:
    PointerArray(size_t initialSize = 100): array(initialSize) {}

    T& operator[](size_t pos) {
        if (pos >= array.size()) {
            size_t newSize = std::max(pos + 1, 2 * pos);
            array.resize(newSize);
        }
        if (!array[pos]) {
            array[pos] = std::unique_ptr<T>(new T()); // or std::make_unique in C++14
        }
        return *array[pos];
    }

private:
    std::vector<std::unique_ptr<T>> array;
};

There no need for a custom destructor anymore(unique_ptr handles it).
Note that I have added this line: int newSize = std::max(pos + 1, 2 * pos);. Why is it necessary? We need it when the initialSize is 0 and so is pos.
In this line: if(pos >= addresses.capacity()), you should be comparing pos to the vector's size, not capacity(because it is an undefined behavior to access elements of the vector beyond size).
More general notes:

using namespace std; is a bad practice. There is no need to pollute global namespace.
Binary operators are usually surrounded with whitespaces. It is also conventional to have an empty line between different functions to improve readability.

And the last one: do have good reasons to use this data structure? In my opinion, as long as a simple std::vector<T> works fine, there is no need to invent any new data structures.


Prolog predicate for adjacency of integers with all signatures and no spurious choice points

The best way to reason about integers is to use your Prolog system's CLP(FD) constraints.

For example, in SICStus Prolog and SWI-Prolog:

:- use_module(library(clpfd)).

nearby(X, Y) :- abs(X - Y) #= 1.

This works in all directions out of the box.

For example, with both arguments integers:

?- nearby(1, 2).
true.

Second, with only one argument known:

?- nearby(X, 3).
X in 2\/4,
_G1047+3#=X,
_G1047 in -1\/1.

Third, with both arguments variables:

?- nearby(X, Y).
_G1085+Y#=X,
_G1085 in -1\/1.

etc.

All serious Prolog systems ship with CLP(FD) constraints, and I recommend you use them when describing relations over integers. Just state the constraints and let Prolog do the reasoning for you.

Note that the predicate is semideterministic: It either fails or succeeds precisely once. You can use labeling/2 to enumerate solutions if the domains are finite.


Reading file and print it in hex format really slow

Writing to the console is incredibly slow.... it also bit me in the past :)

Console is not really meant to print such big data anyway. What's your use case ?

Performance tuning

To reduce the impact on performance, you should try to reduce the number of call to System.out.print(set) to only one, at the end of the run....

You may end with a very big String however, so you should use a StringBuilder instead.

Combining both those things should reduce the time taken by your application by a very noticeable amount and you should end up with something looking like this :

StringBuilder sb = new StringBuilder();
// some more code
try (RandomAccessFile aFile = new RandomAccessFile("filePath", "r")) {
        FileChannel inChannel = aFile.getChannel();
        MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
        for (int i = 0; i < buffer.limit(); i++) {
            final byte read = buffer.get();
            sb.append((String.format("%02X ", read)));
            sb.append("\n");
        }
}

To ((very) slighlty) improve performance you may give your StringBuilder a big starting size like this :

StringBuilder sb = new StringBuilder(1_000_000);

Of course, you should prefer a well named constant over this ugly 1000000.

Other things in the code

Now that we are done with the performance aspect :
1. the name aFile is not really good looking IMO.
2. there is two nested try clause within each other but it's useless here.
3. please never user empty catch block :'(

After all those tweaks : it takes my computer 1 minute and a half to read a 28.5 mb file.


Control DataTable to CSV toString() formatting

What's the point of dataTable = newMyDataTable;? Why not simply work with newMyDataTable directly? Note that newMyDataTable is a bad variable name anyway.

Ditto fileId: this is only used to pass to PathMaker, so why then not simply use newMyDataTable.TableName?

Ditto dataLine: why not work with dr.ItemArray directly?

writtingLock has a spelling error.

What is dc? Ditto dr? Use descriptive names; using abbreviations isn't making your code faster.

Why assign dateTime and otherData when you could easily make this one line? Even better: why not move this code -- including the string.Join -- to separate methods?

Example:

string.Join(",", dr.ItemArray
     .Where(o => o.GetType() == typeof(DateTime))
     .Select(x => ((DateTime)x).ToString(dateTimeFormat)));

Why assign lineToWrite when you could simply write swr.WriteLine(dateTimeToWrite + "," + otherDataToWrite);?

filePath is a property, so it should be PascalCase.


Correct way to assign variables before a try/catch/finally

Two main issue I can see with your code:

app and book can potentially remain null and therefore your finally code has the potential to throw a NullReferenceException. You need to check for null first before calling methods on these objects.
The way you re-throw the exception will destroy its stacktrace. Instead of this:

catch (Exception ex)
{
    throw ex;
    //To Do...
}

you should do this:

catch (Exception ex)
{
    //To Do...
    throw;
}

As to your question where to declare books - it best practice to limit the scope of variables and declare them as close to their use point as possible.

As mentioned in the comments if you want to pass a custom error message via the exception then the best way forward it to create a custom exception which accepts the original exception as a parameter. If you derive from Exception one of the constructors accepts an inner exception parameter. So something along these lines:

public class DocumentProcessingException : Exception
{
    public DocumentProcessingException(string message, Exception innerException) :
            base(message, innerException)
    { }
}


The first thing to look at is: what is the same for each if statement and what is different. The key differences are:
message.content.toLowerCase().includes("this string here is what's different")

and
message.channel.send("links are different")

To clean it up, we can get rid of the if statements all together and create an object that contains key:value pairs with key message.content you want to check against with and value the associated media link. That would look like this:
const gifs = {
  "coffee": "https://cdn.glitch.com/1f3ad41e-6c0c-4160-902b-a50330e419bd%2FCoffee%20cropped.gif?v=1613444146008",
  "latte": "https://cdn.glitch.com/1f3ad41e-6c0c-4160-902b-a50330e419bd%2FLatte.gif?v=1613444145762",
  "muffin": "https://cdn.glitch.com/1f3ad41e-6c0c-4160-902b-a50330e419bd%2FMuffin.gif?v=1613444146225",
  "strawberry cake roll": "https://cdn.glitch.com/1f3ad41e-6c0c-4160-902b-a50330e419bd%2FStrawberry%20cake%20roll.gif?v=1613444145762",
};

We can take out the string "order" because that is also common to all of the keys. If the data you are getting back requires you to check on "order coffee" then change it back.
Now you can map through the keys of the gifs object to see if that key is included in the message content. If it is, return the value associated with that key.
Object.keys(gifs).forEach(key => {
  if(message.content.toLowerCase().includes(key)) {
    return gifs[key]; // get the value at key in the gifs object
  }
}

Object.keys() takes an object and returns an array of the keys in that object. _.forEach is a method on an Array that loops through an array just like a for loop. It takes a callback function as a param.
Putting that all together we get:
// can define this in a helper / util file or at the top of this file since it is a constant list
const REPLIES_LIST = [
    "Here's your order!",
    "Enjoy!",
    "Here you go!",
    "Let me know if you need anything else!",
    "You've been served.",
    "That'll be $3.50.",
    "That'll be $5.50",
];

bot.on("message", message => {
  const { channel, content, reply: messageReply} = message; // destructure variables off of message, reply: messageReply renames reply to messageReply
  const response = REPLIES_LIST[Math.floor(Math.random() * REPLIES_LIST.length)];

  Object.keys(gifs).map(key => {
   if(content.toLowerCase().includes(key)) {
    channel.send("Coming right up!").then(msg => {
      msg.delete({ timeout: 5000 })
    }).catch(console.error);

     setTimeout(() => {
      messageReply(response);
      channel.send(gifs[key]); // get the value at key in the gifs object
    }, 5000);
   }
  });
});

Code Walkthrough

The bot gets a message "message" we declare temporary variables equal to message.content, message.channel, and message.reply by destructuring
Create another variable equal to a random response from the reply list or array
Traverse through the keys in the gifs object using forEach
For each item in the gifs object we check to see if the message.content.toLowerCase() includes that key, if it does we send a message "Coming right up!" to the channel
Handle some logic and a catch after sending
Create a setTimeout that waits 5 seconds before replying with the response and channel.sending the gif url

Updated: 02/17/21
There were comments questioning the use of _.map over _.forEach or _.some. We should be using _.forEach in this case and I updated the original answer to reflect that. Below I highlighted the differences between the three and ultimately what works best for this scenario.
Array.prototype.map((item) => // do something)
A method that iterates through every element of an array and returns a new array resulting from the callback function you passed.
Example:
 const list = [1, 2, 3, 4, 5];
 const newList = list.map((item) => item + 2); // [1+2, 2+2, 3+2, 4+2, 5+2]

 console.log(list); // [1, 2, 3, 4, 5]
 console.log(newList); // [3, 4, 5, 6, 7]

We only use map if we are using the array that the map returns (in this example newList. In the original answer, we were using map without returning anything or using the returned array which is an anit-pattern.
Array.prototype.forEach((item) => // do something)
A method that iterates through an array and uses a callback to mutate the array, returning undefined.
Example:
 const list = [1, 2, 3, 4, 5];
 list.forEach((item, index, arr) => arr[index] = item + 2);

 console.log(list); //[3, 4, 5, 6, 7]

The forEach provides you with the current item (item), index of the current item in the array (index), and the original array (arr).
We use forEach when we want to use the callback passed to mutate the array without returning a new array. Key thing to note, you cannot exit a forEach without raising an exception.
Array.prototype.some((item) => // do something)
A method that checks if at least one element in the array "passes" the callback you provide, returning a boolean.
Example:
 const list = [1, 2, 3, 4, 5];
 list.some((item) => item === 2); // true, stops when it reads 2 in the array because it matches

 console.log(list); //[1, 2, 3, 4, 5]

For the question that was asked, forEach is most appropriate. You then have to contemplate, will my data have duplicates or not have anything at all and handle those conditions. If you will have duplicates, you may want to you the find method approach Daniël van den Berg suggests. find is similar to forEach and some. It looks for the first item that matches the condition and returns that item.


Returning a list of divisors for a number

Don't reset num to orig_num (to fasten division/modulo)
Think functionnaly :

From your prime factors, if you generate a new collection with all possible combinations, no need to check your products.
It makes harder to introduce bugs. Your code is indeed broken and won't output 20 or 25 (...) as divisors of 100.
You can re-use existing (iter)tools.

Avoid unnecessary convertions (sorted can take any iterable)
Compute primes as you need them (eg, for 10**6, only 2 and 5 will suffice). Ie, use a generator.

This leads to :

from prime_sieve import gen_primes
from itertools import combinations,  chain
import operator

def prod(l):
   return reduce(operator.mul, l, 1)

def powerset(lst):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    return chain.from_iterable(combinations(lst, r) for r in range(len(lst)+1))

def list_divisors(num):
    ''' Creates a list of all divisors of num
    '''
    primes = gen_primes()
    prime_divisors = []
    while num>1:
       p = primes.next()
       while not num % p:
          prime_divisors.append(p)
          num = int(num / p)

    return sorted(set(prod(fs) for fs in powerset(prime_divisors)))

Now, the "factor & multiplicity" approach like in suggested link is really more efficient.
Here is my take on it :

from prime_sieve import gen_primes
from itertools import product
from collections import Counter
import operator

def prime_factors(num):
   """Get prime divisors with multiplicity"""

   pf = Counter()
   primes = gen_primes()
   while num>1:
      p = primes.next()
      m = 0
      while m == 0 :
         d,m = divmod(num,p)
         if m == 0 :
            pf[p] += 1
            num = d
   return pf

def prod(l):
   return reduce(operator.mul, l, 1)

def powered(factors, powers):
   return prod(f**p for (f,p) in zip(factors, powers))

def divisors(num) :

   pf = prime_factors(num)
   primes = pf.keys()
   #For each prime, possible exponents
   exponents = [range(i+1) for i in pf.values()]
   return sorted([powered(primes,es) for es in product(*exponents)])


Making a simple session class more secured

You don't post the code that interacts with database, there is the main security concern. I hope you use PDO prepared statements, which will keep you safe from SQL Injections.

As for non-security-related problems, there are quite some of them.

Consider creating multiple functions for form submit processing, for example:

function process_form_submit($_POST)
{
    $input = $this->validate_user_input($_POST);
    if ($this->user->authenticate($input['email'], $input['password'])) {
        $this->log_user_in($this->user->getId());
    }
}

Then your functions

do one thing per function
are testable
are able to throw exceptions properly

As for exceptions, you don't just echo problems, do things like

throw new FormSubmitException('Email format is invalid');

and call process_form_submit like this:

try {
    $session->process_form_submit($_POST);
} catch (Exception $e) {
    echo $e->getMessage(); // or any other error handling
}

Why? I suppose your code is in the middle of the page (since you just echo all the errors), what if you want to move it to the top in order to change page title if login fails. Then your echo will show the error above page design and you will have to look for every single echo in all of classes used in order to fix this. Code like I provided will let you move it up and replace a single echo with $error = and the task will be done painlessly. Not even mentioning test-ability improvement.

Don't use global $var;, use Dependency injection instead in constructor or factory:

$session = new Session($user, $misc);

If you don't do that than your session class keeps depending on them implicitly and it makes you unable to just copy it into some other project. If you try - you will get errors here and there saying it is missing something that is not clear from it's initialization. Would not it be better to write a good class once in such a way that you can then use it in other projects?

As a last hint, start documenting your code with phpDocumentor standards in mind. It is a good habit and the sooner you start doing it, the easier it will be for yourself to work with code you write today in a few years, when you won't remember a thing about how it works.


__missing__
I would have started to propose a simpler design using the __missing__ dunder so that, each time a user tries to access a command that has not been populated, the __missing__ method would be called and you could fetch the informations:
def Foo(dict):
    def __missing__(self, key):
        self[key] = item = fetch_item(key)
        return item

And voilà. I wouldn't try to enforce barriers to avoid users behaviour. After all, we're all consenting adults here.
Playing it nice with the interactive shell
This behaviour, however let the user clueless about all the possible commands available at the tap of the TAB key. They are still able to call get_item_names if need be. But you could automatically build them using some metaclass logic.
The class you want in the end could be:
def Foo:
    _<some_name> = None

    @property
    def <some_name>(self):
        if self._<some_name> is None:
            self._<some_name> = fetch_item(<some_name>)
        return self._<some_name>

    def __getitem__(self, key):
        return getattr(self, key)

with every <some_name> being returned by get_item_names. Read-only of the attributes are ensured by the property.
So you need to define your base class being:
class Foo(metaclass=CommandBuilder):
    def __getitem__(self, key):
        return getattr(self, key)

And build your metaclass like
class CommandBuilder(type):
    def __new__(cls, name, bases, dct):
        for command_name in get_item_names():
            _command_name = '_{}'.format(command_name)
            dct[_command_name] = None

            def getter(self):
                command_value = getattr(self, _command_name)
                if command_value is None:
                    command_value = fetch_item(command_name)
                    setattr(self, _command_name, command_value)
                return command_value

            dct[command_name] = property(getter)

        return super(CommandBuilder, cls).__new__(cls, name, bases, dct)

If you trully need to use a subclass of dict here, it wouldn't be much more difficult:
def Foo(dict, metaclass=CommandBuilder):
    def __missing__(self, key):
        item = getattr(self, key)  # will call the property
        super(Foo, self).__setitem__(key, item)
        return item

    def __setitem__(self, key, value):
         pass  # or raise an exception of your own

    def __delitem__(self, key):
        pass  # or raise an exception of your own

Immutability of the attributes is still guarantied by property.


Now that's some coincidence! No later than this week I wrote an ADODB "wrapper" for some vb6 legacy code (here). This looks very much similar, only for ADO.NET.

I don't like the name. DB is not respecting the PascalCase naming convention for VB.NET classes (same in C#) - I realize it's a short handy name, but it looks like a variable's name. I'd rename the class to, say, AdoCommandBuilder; the name of the object should say what the object's role is. In this case, building an ADO.NET command.

I might be completely wrong here, but it seems to me that a thread entering BuildCommand from ExecuteReader would open up a connection, and then when the function returns, the connection would be disposed before the client code can start iterating the reader. Thus I wouldn't wrap an IDisposable in a Using block if I'm going to be returning it.

Anyway your command is being disposed twice. Once in BuildCommand:

        Using cmd As SqlCommand = con.CreateCommand()
            cmd.CommandType = CommandType.StoredProcedure
            cmd.CommandText = cmdTxt
            AddParameters(cmd, params)
            con.Open()
            Return cmd
        End Using '<<<<<< here

...and once more in the ExecuteXxxxx methods:

    Using cmd As SqlCommand = BuildCommand(cmdTxt, params)
        Return cmd.ExecuteReader()
    End Using ' <<<<<< here too!

I'd remove the Using cmd As SqlCommand from the CreateCommand method.

I agree with @Malachi, that BuildCommand shouldn't be opening the connection - its concern is building a command, so it should be taking a connection as a parameter; by doing that you enable extending your class with methods that take a connection, which enables running your commands in a transaction.

Hence, I think I would drop the parameterized constructor, add a Connect(connectionString As String) method instead, encapsulate the connection (, implement IDisposable) and give each ExecuteXxxxxx method an overload that takes an IDbConnection parameter; if you're not going to be taking in a connection, then you should own the whole process and return the data, not the reader itself - the idea is that you generally want the object that creates an IDisposable to be the one calling Dispose on it, so I'd only return a SqlDataReader when the client code owns the connection.


Storing realm objects using Kotlin extensions

Please correct me if I got you wrong, but we're talking here about simple inheritance:

open class RealmObject {

    fun store() { /*RealmObject impl*/ }

}

open class Player : RealmObject() {

    override fun store() {
     /*Player impl*/
     super.store() /*RealmObject impl*/

   }
    ...
}

Your wanted behaviour fits:

Player().store() // executes override function - Player impl, then RealmObject impl
RealmObject().store() // executes RealmObject implementation

If you want to keep it as extension functions, your code is valid, but isn't really an eye-candy.

Both classes Player and RealmObject would have the same function store(), but they are 'unrelated' - thats why we don't see any override. Extension functions extend statically and they can shadow your implementation, which makes your code very hard to read and the behaviour becomes at some point not understandable.

Please use extension functions wisely and try to never use it for inheritance.


Given N, generate sequence of random numbers from 0 to N - 1 with no repetitions

You can use the inside out version of the Fisher-Yates shuffle

In C# it would look like:

private static int[] Shuffle(int n)
{
    var random = new Random();
    var result = new int[n];
    for (var i = 0; i < n; i ++)
    {
        var j = random.Next(0, i + 1);
        if (i != j)
        {
            result[i] = result[j];
        }
        result[j] = i;
    }
    return result;
}

It's good because you create and shuffle your array at the same time using a well known shuffle.

You'd want to reuse the same Random instance though.


You should have to split your function absolutely.
You should have to group commons conditions statements and instructions.

However, I think there are deeper problem in your architecture which cause this piece of code. You have to rethink your problem at higher level.

For the three top conditions you can do this, for example :

    public static void Test(int? inventoryCheck, int? POCheck, int? PromotionCheck)
    {
        bool bInventoryCheck = (inventoryCheck == null);
        bool bPOCheck = (POCheck == null);
        bool bPromotionCheck = (PromotionCheck == null);

        ValidInventory (!bInventoryCheck && bPOCheck && bPromotionCheck, inventoryCheck);
        ValidInventory (bInventoryCheck && !bPOCheck && bPromotionCheck, PromotionCheck);
        ValidInventory (bInventoryCheck && bPOCheck && !bPromotionCheck, POCheck);

    }

    public static void ValidInventory(bool validate, int? toValidate)
    {
        if (validate)
            //db.ValidInventory(toValidate);
    }

But I don't think it's a good solution because as you mention here, you have a lot of other cases. We can reduce your code by many way but it's bury the real problem.

In order to reduce we have to understand the concept behind the Process.

PS : Here the "else if" statement seems to be unnecessary, because you are testing every parameters in each case.


Retrieving a user's password for verification

What I would correct in the code:

if anything goes wrong it's best to just display "Login incorrect", instead of specialized messages ('user not found' / 'incorrect passsword'). Giving too many details may lead to information leakage
searchUser is not a very good variable name. It in fact represents the result of a search, so I'd name it matchedUser. searchUser would be a good name for a query.
the encryptedPassword variable is assigned but never used. You could use it to compare against the password hash in the database

In the end, my code would look like this:

private void userVerification()
{
    var myDbContext = new DataClasses1DataContext(dbPath);

    var hasher = new Hasher { SaltSize = 16 };
    var encryptedPassword = hasher.Encrypt(txtPassword.Text);

    var matchedUser = myDbContext.Accounts
        .Where( user =>
                user.accnt_User == txtUser.Text &&
                user.accnt_Pass == encryptedPassword)
        .FirstOrDefault();

    if(matchedUser != null)
        MessageBox.Show("CORRECT!");
    else
        MessageBox.Show("Invalid user or password.");
}


Generic NSMapTable replacement written in Swift

(Not a full review, but some remarks and suggestions.)

Generally, your code looks correct to me, I could not see obvious
errors or problems – for the single-threaded usage.

You cannot
assume that it will work correctly when used from multiple threads
simultaneously.
Cocoa mutable collection types are not thread-safe (see Thread Safety Summary),
and – as far as I know – the same applies to Swift collections
(references: Swift: process Array in parallel using GCD, Swift mutable array thread safety, Swift Arrays are not Threadsafe).

In

let watcher = DeallocWatcher { [weak self] in
    if let v = self?.dict[hashableBox] { self?.block(v) }
    self?.dict[hashableBox] = nil
}

self is (conditionally) unwrapped three times. I would use
optional binding instead so that it is unwrapped only once.
You could also take advantage of the fact that removeValueForKey()
returns the old value (or nil):

let watcher = DeallocWatcher { [weak self] in
    if let s = self {
        if let v = s.dict.removeValueForKey(hashableBox) {
            s.block(v)
        }
    }
}

When a value for key is removed in

    else {
        objc_setAssociatedObject(key, unsafeAddressOf(self), nil, 0)
        dict[hashableBox] = nil // <-- not needed!
    }

then the first line already causes the value to be removed from dict,
because disassociating the associated object fires the DeallocWatcher
callback. So the second line is not needed.

The keys and keyValues properties can be simplified using map():

public var keyValues: [(K, V)] {
    return map(dict) { (k, v) -> (K, V) in (k.value!, v) }
}

public var keys: [K] {
    return Array(dict.keys.map { $0.value! })
}

You can also easily add conformance to additional protocols to make
your WeakKeyDictionary more look and feel like a real dictionary.

If you add the Printable protocol

public class WeakKeyDictionary<K: AnyObject, V where K: Hashable> : Printable {

    // ...
    public var description: String  {
        return "[ " + ", ".join(map(dict) { (k, v) in "\(k.value!) : \(v) " }) + "]"
    }
}

then println(wkdict) produces an output similar to a dictionary.

And with SequenceType

public class WeakKeyDictionary<K: AnyObject, V where K: Hashable> : Printable, SequenceType {

    // ...
    public func generate() -> GeneratorOf<(K, V)> {
        var gen = dict.generate()
        return GeneratorOf {
            if let (k, v) = gen.next() {
                return (k.value!, v)
            }
            return nil
        }
    }
}

you can enumerate keys and values like

for (k, v) in wkdict {
    println((k, v))
}


While it's great to see someone actually take the trouble to refactor code, to move away from the depreacted mysql_* extension, it's not so great to see that, like most, you're actually trying to use the replacement (mysqli_*) as a 1-on-1 copy of the old extension.
On a personal note, though I've restricted myself to only dealing with the mysqli_* extension, I couldn't help noticing you're using the OO API it offers. Personally, I find the mysqli_* API, both procedural and OO a tad, erm, ... messy. If you're collaborating with others, there's nothing to stop them from switching/inserting procedural-style code, and mixing it in with your OO code. That's just nasty. PDO is another, valid alternative. It's API is OO-only, a lot cleaner and waaaay more easy to use. It's said to be slower, but in reality, the differences are so minute, they don't outweight the upsides in terms of code maintainability. Look into PDO, too, is what I'm trying to say... :)

Some history:
The old extension was created back in the days of MySQL version 3. Today, MySQL is already at version 5.6. Most hosts, if not all, offer mysql 5.x as standard DB. The list of features that weren't around back in the MySQL 3 era, but that are in common use now is rather impressive, and long:

New and better storage engines
Cursors
Stored procedures, functions, views and triggers
Foreign Key Contraints
Cluster support (Though I'm no big fan of MySQL clusters)
transactions (Commit, rollBack)
Prepared statements!
Start here, browse back and forth between releases, and compare for even more differences

Of course, there were other reasons why the mysql_* extension was deprecated. Its source wasn't very maintainable, for example. It's been around longer than the ZendEngine2, too. In short: it'd become sort of historic ballast, that wouldn't have worked, considering the direction PHP is going in (compiled language, OOP supprt, namespaces...)

Applied to your code:
All in all, there's a lot of changes, and some of them are quite useful when it comes to security. Take prepared statements for example (Note: here's some info on what they are, what they do). Rather than calling $mysqli->escape_string(), which as it happens requires you to set the charset!, you can easily use a prepared statement, much to the same effect:

$emailStmt = $mysqli->prepare('SELECT email FROM user WHERE email= ?');
$emailStmt->bindParam('s', $_POST['email');
$emailStmt->bind_result($dbEmail);//fetches result into this variable
if (!$emailStmt->execute() || $emailStmt->num_rows === 0)
{
    header('Location: '.basename($_SERVER['PHP_SELF']));//302 redirect is fine here
    $emailStmt->close();
    $mysqli->close();//be tidy!
    exit();// I hate die statements
}
$emailStmt->close();

So, no tedious escaping of all params all the time anylonger, you don't even have to worry about the types anymore. Mysql is, after all, fairly picky when it comes to data-types. Sure it can handle an_int_field >= '123', but really, it's best to avoid forcing the DB server having to cast the data to the right type. That's not what it's for.
As I said in the comments, mysqli->escape_string is considered as safe as prepared statements, But:

When working on your code, it's easy to forget that call to the escape_string method. Once you've forgotten that, your code is vulnerable to attacks.
If you forget to set the correct char-set, your queries are no longer as safe as prepared statements would be
getting into the habbit of using prepared statements is a good thing. You can prepare a single statement once, then use it to query your DB as much as you want. I've explained this here, with an example of how to do this.
Preparing a statement for a simple query might seem like a bit much, and in some ways it is. That's why the PDO extension emulates the prepare calls. That's one of the benefits of PDO: the statements are prepared, without any intervention of the DB server, so there's very little overhead when using prepared stmts. Honestly, there's no reason not to use them.

Anyway, I'm drifting off, slightly. What I'm actually trying to say is this:

Since you're refactoring anyway, why not look into what sort of new goodies mysqli_* brings to the party? the i is for improved after all. Don't use it as a 1-on-1 copy of the old extension. Time has, as it tends to do, moved on. There are new features. Learn about them, and use them. You're code will be more reliable, more maintainable, more future proof and 9/10 more safe, too, because of it.
Begin with using prepared statements, then move along to transactions. That's just a tip.

Some other thoughts
I see (or rather don't see) a worrying lack of data validation in your code. You just assume $_POST['email'] is going to be set, and that its value is going to be an email address. At no point in time, do I see you use something like this:

if (isset($_POST['email'])) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
    //query DB
}
else
{
    exit('no valid email address provided');
}

The only time your code reflects any form of awareness that, perhaps, some POST data might not be set is here:

 @$referrer = $_POST['referrer'];

But the way it's dealt with just gets to me. As I've said before, and as I will keep on saying until either the supressor of death (@, that is) or I am no more:

  Argh... the @ suppressor of death! I hate that, don't use it... save for those few rare use-cases where you can't help a notice from being issued (seen this only 2 or 3 times in 10 years). If there's a notice, there's an issue, if there's an issue: don't ignore it fix it!

In this case, there isn't even an issue that needs fixing, except for the @ itself. Why not simply write:

$referrer = null;//declare var and assign null value
if (isset($_POST['referrer']))
{
    $referrer = $_POST['referrer'];
}

isset is a language construct, and therefore it's fast. supressing a notice isn't fast, it's slow, and completely pointless in most (if not all) cases. Don't.
If you don't want your code to be too long, because of all the if(isset branches, you can easily replace them with something like this:

if (isset($_POST))
{
    $email = $password= $password1 = $referrer = false;//all default value
    foreach($_POST as $key => $value)
    {
        if (isset($$key) && $$key === false)
        {//variable variable, check if it exists, and if its value is false
            $$key = trim($value);//if it is, assign POST val... perhaps trim while you're at it?
        }
    }
}

With this code, though not very maintainable, you save a lot of space, and you know that if any of the variable's used holds false as a value, it wasn't posted. All other variables (the ones that aren't false) have been reassigned the posted data.


How can I optimise a foreach calling an API? The code calls an API and returns the first string reponse

one way of solving this would be using Task.WhenAll the idea is to add all tasks into a list of tasks then we call Task.WhenAll and await the final results.
Here is an example of it :
private async Task<ProductItem> SetSiteLink(ProductItem item)
{
    item.site = await _testRepo.GetSiteLink(item.Id, item.baseLink);

    return Task.FromResult(item);
}

then call it like this :
var tasks = new List<Task<ProductItem>>();

foreach (var item in products)
{
    tasks.Add(SetSiteLink(item));
}

var results = await Task.WhenAll(tasks);


Calculator that works by compiling and running a .java file

Let me answer your questions first:

Yes, there is a better way of doing this, and you already know it as you have suggested it yourself.
Yes, it would be more efficient to do it manually by analyzing the String and evaluating it part-by-part, like an interpreter would.
This is most definitely the wrong way of doing Java (not mincing my words here, you know that you're doing it wrong, otherwise that question wouldn't have occurred to you).
Yes, you have to improve your style. See below.

My Views:

Your approach to a calculator is certainly novel, for Java. This is highly  inefficient (you have to spawn new processes, which is always slow), as you have suspected. What you do is basically emulating eval of Python. Bad idea, but you've done it. Now how to go forward? (Yes, doing this the "classic" way is the way to do it in Java. Doing it this way feels like you are forcing Java to be more Python-ish.)

Style:

Space around operators, please! Whitespace is free and makes the code that much more readable.
Magic numbers. Instead of 5 everywhere, put

private static String prefix = "Math.";
private static int prefixLength = prefix.length();

at the top of the Calculator class, and use those instead of their values. More self-explanatory and much easier to read and maintain. This prefix business is voided by another suggestion below, though.
Weird variable names. Nested loop indices are usually named i,j,k, etc., like in mathematics. What do adds and add even mean? p1 and p2 are as good as foo and bar in telling what they contain, which is no good.

Code:

Why do you wrap a String literal into a String object using a String(String) constructor? (If that sounded weird to you, better drop the new String("...") for just "..." everywhere.
Where you are creating your Term.java, you don't need the import java.lang.Math, it's imported by default as it is part of the java.lang package.
What you might want to do is have import static java.lang.Math.*, which is a better idea as it allows you to skip all the weird string processing going on in the loop where you prepend "Math." wherever there is a function call in the term.
Why an empty else? If you don't need it, skip it.
Comparing boolean values against boolean literals is not required. For <x> == true, use just <x>, and for <x> == false, use just !<x>
Wrap the possible IOException in a RuntimeException and rethrow it. This prevents the caller from having to rethrow the exception or gobble it (like you do) compulsorily.
Try FileReader and FileWriter, especially wrapped up in a BufferedReader and BufferedWriter, respectively, instead of using FileInputStream and FileOutputStream raw - the former ones will allow you to
read and write whole Strings at a time, getting rid of all the getBytes() calls you have on Strings (horrible idea especially if you don't specify your file encodings)
String.format(String, Object...) is a good idea if you have to create a String with variables interpolated into it.


Adding to Bobby's very good answer, you could also explore alternative ways for checking the winning game.
You can think of noughts and crosses as 1s and 0s (true and false):
boolean[][] board = new boolean[][]{
     {false, false, false},
     {false, true, false},
     {false, false, true}
};

and therefore transform the board to an integer number:
int intboard = 0;
int exponent = 0;
for (int i = 0; i < board.length; i++) {
    for (int j = 0; j < board[0].length; j++) {
        intboard += board[i][j] ? Math.pow(2, exponent) : 0;
        exponent++;
    }
}

Then you can simply check intboard against a set of pre-calculated integers for all winning boards:
List<Integer> winningBoards = List.of(
        7, // Horizontal, row-0 --> 000000111
        56, // Horizontal, row-1 --> 7 << 3
        448, // Horizontal, row-2 --> 7 << 6
        73, // Vertical, column-0 --> 001001001
        146, // Vertical, column-1 --> 73 << 1
        292, // Vertical, column-2 --> 73 << 2
        273, // Diagonal-0 --> 100010001
        84 // Diagonal-1 --> (273 >> 2) | 16
);

Note that you can calculate some of these winning boards using bitwise operations too!

Finally checking for the winning cases is a matter of applying the winningBoards masks on intboard:
final int boardToCheck = intboard;
boolean youHaveWon = winningBoards.stream()
        .anyMatch(winningboard -> (boardToCheck & winningboard) == winningboard);

System.out.println("Nought has won: " + youHaveWon);

If you want to check for crosses you simply need to flip the bits of the winning boards using the complement operator ~:
youHaveWon = winningBoards.stream()
        .anyMatch(winningboard -> (~boardToCheck & winningboard) == winningboard);

System.out.println("Cross has won: " + youHaveWon);

The advantage of this technique is not clear for a game as simple as noughts and crosses, but if you are working on more complex games and need to check many many boards (even millions or billions!) when performing Minimax or equivalent, you can get a very nice speed up by changing the representation of your game from using objects to bits.


Javascript module for sorting and searching

arrays in js already have a sort method, all it needs is a compare function. I made a similar api for a general binary search. It takes an array as its first arg and the compare func as the second. The binary search function could be bound to the Array prototype too. But people complain too much about extending the native prototypes, so we'll just pass the array in.

The style here is consistent. The indentation is the same and the variable names are short yet descriptive enough. Each function does 1 thing and nothing more.

var FIND = 100;
var arr = [ 9, 8, 10, 100, 60, 1 ];

var sorted = arr.sort((a, b) => a - b);
console.log(sorted);

var i = binary_search(sorted, n => FIND - n);
console.log('FOUND AT', i);

//https://github.com/MrOutput/learning/blob/master/js/binary_search.js
function binary_search(array, fn) {
    var low, mid, high;
    low ^= low;
    high = array.length - 1;
    while (low <= high) {
        mid = (low + high) >> 1;
        var cmp = fn(array[mid]);
        if (cmp < 0) {
            high = mid - 1;
        } else if (cmp > 0) {
            low = mid + 1;
        } else {
            return mid;
        }
    }
    return -1;
}

Binding it to the array prototype has its benefits though. Consider....

//https://github.com/MrOutput/learning/blob/master/js/binary_search.js
Array.prototype.bsearch = function (fn) {
    var low, mid, high;
    low ^= low;
    high = this.length - 1;
    while (low <= high) {
        mid = (low + high) >> 1;
        var cmp = fn(this[mid]);
        if (cmp < 0) {
            high = mid - 1;
        } else if (cmp > 0) {
            low = mid + 1;
        } else {
            return mid;
        }
    }
    return -1;
};

var FIND = 100;
var arr = [ 9, 8, 10, 100, 60, 1 ];
var i = arr .sort((a, b) => a - b).bsearch(n => FIND - n);

console.log('FOUND AT', i);


If you try to get an IteratorForContainerOfContainer for an empty container, your constructor will run into Undefined Behavior when it tries to get the inner iterators because the outer container is empty, outerLoop will be the end iterator, and you can't dereference the end iterator.

You're using a default constructed object to double as an end iterator.  Consider adding in a static method to return one, end(C &c), with appropriate changes to nextValidPos.

If you need to work with a const object, you won't be able to get one of these flattened iterators for it.

You don't define operator++(int), so using it++ won't compile.