Fast Prime Sieve (Python Implementation)

Since this is tagged beginner, you should know that speed isn't everything. First of all you should care about making your code readable as ultimately that is more important.

You should always put new statements on new lines. At first I ignored your first guard statement, due to this. I only caught on that you'd done this when I saw the second from last line was huge.
Your comments aren't great. Yes [True]*(n + 1) initializes a list, we can read the code to understand that.
Your variable names don't really help reading the code.

def sieve(limit):
    if limit < 2:
        return []

    limit += 1  # Preincrement `limit` so `sieve` is inclusive, unlike `range`.
    primes = [True]*limit
    for base in range(2, int(limit**0.5 + 1)):
        if primes[base]:
            for composite in range(base*2, limit, base):
                primes[composite] = False
    return [num for num, is_prime in enumerate(primes) if is_prime][2:]

I'd like to point out that your memory usage can be improved. How many \$O(n)\$ lists do you have?

primes to perform the sieve.
Your list comprehension, that gets all the indexes.
Your duplication of the list comprehension to remove two values.

You can remove the second by returning an iterator. As for the third, you can instead perform an islice, or setting 0 and 1 to false. Yes this is now 10% slower.

However if you change the second for loop to run in C land rather than Python land you net a 40% speed-up from the original.

from math import ceil

def sieve(limit):
    if limit < 2:
        return []

    limit += 1  # Preincrement `limit` so sieve is inclusive, unlike `range`.
    primes = [True]*limit
    for base in range(2, int(limit**0.5 + 1)):
        if primes[base]:
            primes[base*2:limit:base] = [False]*(ceil(limit / base) - 2)

    primes[0] = primes[1] = False
    return (num for num, is_prime in enumerate(primes) if is_prime)

From this changing the last line to use itertools.compress rather than an iterator comprehension reduces time an additional 40% (nearly 70% from the original).

from math import ceil
from itertools import compress

def sieve(limit):
    if limit < 2:
        return []

    limit += 1  # Preincrement `limit` so sieve is inclusive, unlike `range`.
    primes = [True]*limit
    for base in range(2, int(limit**0.5 + 1)):
        if primes[base]:
            primes[base*2:limit:base] = [False]*(ceil(limit / base) - 2)

    primes[0] = primes[1] = False
    return compress(range(limit), primes)


Ways of forming multiple elements in a list comprehension without duplicates (Euler #109)

Your threeshots line

Since using the operator !! is not very Haskelly, let's get rid of that and think of a way to get your b and c using typical list operations. Since you want a list of all pairs, let's create a new function called pairs.

pairs :: [a] -> [(a,a)]
pairs [] = []
pairs (x:xs) = map (\y -> (x, y)) (x:xs) ++ pairs xs

Your new threeshots would thus be:

threeshots = [a + b + c | a <- doubles, (b, c) <- pairs alls]

In a nutshell, pairs takes the first element of the given list, forms tuples with every element of that list and continues with the rest of the list until it's empty.

If you prefer, you could write pairs (x:xs) as map ((,) x) (x:xs) ++ pairs xs. I find that one to be less clear, though.

Other Nitpicks

As a rule of thumb, every top level declaration should have a type annotation.

You've declared your main in a do-block, which is not necessary since you're not using any monadic stuff. The (++oneshots) $ (++twoshots) threeshots part looks unusual, too.

main = print . length . filter (< 100) $ threeshots ++ twoshots ++ oneshots

You can keep the $ in your main if you prefer; in this scenario, it's probably just a matter of taste. Using . is less noise though - to me at least.

Putting it all together

singles, doubles, triples, alls :: [Int]
singles = [1..20] ++ [25]
doubles = map (*2) singles
triples = map (*3) [1..20]
alls    = singles ++ doubles ++ triples

pairs :: [a] -> [(a, a)]
pairs []     = []
pairs (x:xs) = map (\y -> (x, y)) (x:xs) ++ pairs xs

oneshots, twoshots, threeshots :: [Int]
oneshots   = doubles
twoshots   = [a + b | a <- doubles, b <- alls]
threeshots = [a + b + c | a <- doubles, (b, c) <- pairs alls]

main :: IO ()
main = print . length . filter (< 100) $ threeshots ++ twoshots ++ oneshots


Cracking the coding interview 1.7 - Rotate matrix by 90 degrees

Most of your code looks good. I have a few remarks, though.

The name of your function rotate_m1 is misleading. What does the m1 mean at all? Additionally, your function prints the result. It should not do that. Instead, it should either rotate the matrix in-place, or alternatively return the rotated matrix. That way, you can use the result further:

print(rotate(rotate(matrix)))

With your current code, thisis not possible.

The docstring of your function is very long. This docstring should be written for a specific target audience, which is the users of the function. The users only need to know:

"""Returns a copy of the given matrix, rotated clockwise by 90 degrees.

Example: [[1, 2, 3], [4, 5, 6]] is rotated to [[4, 1], [5, 2], [6, 3]]
"""

The implementation details do not belong in the behavioral description of the function.

Note that I chose a non-square example on purpose. If you rotate the matrix in-place, the matrix has to be square, but when you create a copy, you can also handle arbitrary rectangular matrices. Your code currently doesn't do this, but it should.

My standard disclaimer about CtCI: Don't trust that book. It contains many typos and inefficient, English-America-centric code. The "solution" code is often not indented properly, variables are not named carefully, edge cases are forgotten, and so on. I would not hire someone who learned from that book alone.


Rather than use narrow types, use fastest ones

// uint8_t first = (uint8_t)(*txt);
unsigned first = (uint8_t)(*txt);
// or
uint_fast8_t first = (uint8_t)(*txt);

Rather than lookup a value to shift, look up the shifted value.

// static uint8_t MSK[] = {0,0,3,4,5,0,0,0};
//  val = first & (0xFF >> MSK[len]);

static const uint8_t FF_MSK[] = {0xFF >>0, 0xFF >>0, 0xFF >>3,
    0xFF >>4, 0xFF >>5, 0xFF >>0, 0xFF >>0, 0xFF >>0};
val = first & FF_MSK[len];

Some modern compilers can make additional optimizations if the pointers are known to not overlap - use restrict and const where applicable.

// int utf8_cp(char *txt, int32_t *ch)
int utf8_cp(const char * restrict txt, int32_t *restrict ch)

Coding the companion function would aid in testing for both functions.

int utf8_cp_encode(int32_t *ch, char *txt);

As code does not detect invalid encoding like surrogates, redundant patterns and values above max_Unicode, I see little value in handling only a subset of invalid sequences.  Either detect them all (maybe in debug mode)  or skip detection.

Suggest doing a 32-byte (or 256-byte) lookup for performance.  Profile to find optimal.

// len = (first > 0) * (1 + ((first & 0xC0) == 0xC0) * LEN[(first >> 3) & 7]);
len = (first > 0) * LEN_32[first >> 3];
// or
len = LEN_256[first];

Could extend the above to do one lookup for both the len and val.


Evaluate/Refactor my ASP.NET XSS Security Helper Class

Some general idea:

Use guard statements instead of big if blocks.
Extract the !string.IsNullOrEmpty(query) && PotentialXssAttackRegex.IsMatch(query) condition to a method.
Extract individual checks to distinct methods. The IsPotentialXssAttack will be quite easy to read and the code of different validations will not be mixed in one big method.
I'd create an expireAllCookies helper method too.

The final code of the first method would look like this (I haven't tested nor compiled):

public static bool IsPotentialXssAttack(this HttpRequest request) {
    if (request == null) {
        return false;
    }
    if (isPotentialXssAttackQuery(request)) {
        return true;
    }
    if (isPotentialXssAttackFormOrAnything(request)) {
        return true;
    }
    if (isPotentialXssAttackCookie(request)) {
        return true;
    }

    return false;
}

public static bool isPotentialXssAttackQuery(this HttpRequest request) {
    string query = request.QueryString.ToString();
    if (isMatch(query)) {
        return true;
    }
    return false;
}

public static bool isMatch(string input) {
    if (string.IsNullOrEmpty(query)) {
        return false;
    }
    return PotentialXssAttackRegex.IsMatch(query);
}

// TODO: rename it
public static bool isPotentialXssAttackFormOrAnything(this HttpRequest request) {
    if (!request.HttpMethod.Equals("post",
            StringComparison.InvariantCultureIgnoreCase)) {
        return false;
    }

    string form = request.Form.ToString();
    if (isMatch(form)) {
        return true;
    }
    return false;
}

public static bool isPotentialXssAttackCookie(this HttpRequest request) {
    if (request.Cookies.Count <= 0) {
        return false;
    }

    foreach (HttpCookie cookie in request.Cookies){
        if (isMatch(cookie.Value)) {
            return true;
        }
    }
    return false;
}


Show a ProgressDialog and send an SMS in the background

What you are trying to achieve is such a common pattern (run some command in separate thread and then modify the UI with the result) that Android has a class just for that: AsyncTask.  There is also a small example in the dev guide and I'm sure all Android books must have a full section, if not a full chapter, about AsyncTask.

Be very careful about Java conventions.  When you don't respect them, the code is quite confusing for Java developers.

Class names always start a capital letter, so CommandXDev instead of commandXDev.
commandXDev.Get.  I'm not quite sure what that is.  In Java, if you write a getter method, you always call it get followed by what you are getting, i.e. getName(), getId(), getSharedPreferences(), etc.  Your commandXDev.Get seems to be a static getter, which is best avoided.  I'm not sure what you are trying to do.  Maybe look into the singleton pattern.

Minor point: in English it is "sent" instead of "sended".  It does not make sense, but it is how it is.


You are not performing any percent encoding of parameter names or values, which would likely lead to breakage or even a security vulnerability if the you are given parameters that contain a special character.

A std::map might not be the right type; a std::multimap may be more appropriate.


OOP doesn't mean to "split up" code into random classes.

The ultimate goal of OOP is to reduce code duplication, improve readability and support reuse as well as extending the code.

Doing OOP means that you follow certain principles which are (among others):

information hiding / encapsulation
single responsibility
separation of concerns
KISS (Keep it simple (and) stupid.)
DRY (Don't repeat yourself.)
"Tell! Don't ask."
Law of demeter ("Don't talk to strangers!")
replace branching with polymorphism

You example suffers multiple violations of this OO principles.

e.g:

Single Responsibility / Separation of concerns.

The (only) method in you class does nothing but delegates the call to one of it's parameters while passing the other parameter. This is the reverse version of feature envy. This method has no reason to exist here.

And since this is the only method in this class (you showed) the whole class has no reason to exist.

interface segregation

Your constructor has 3 parameters but  there is only one member variable initialized.

The complete content should be outside the constructor and only the Player instance should be passed in to be assigned to the member variable.


UNUSED() with teeth in C++11 debug builds

Missing headers

This code needs

#include <type_traits>
#include <cstring>

Use sizeof operator on a value

While we can write sizeof (type), in this case we have a value, and we can use it here - sizeof will read through the reference, saving us some work:

std::memset(&v, 0xBD, sizeof v);

Reduce repetition

There are two expressions that need to be maintained in parallel in the std::enable_if template.  We can refactor these into a single trait template:

template<typename T>
struct is_mutable_pod_lvalue
    : std::integral_constant<bool,
                             std::is_lvalue_reference<T&&>::value
                             && !std::is_const<typename std::remove_reference<T>::type>::value
                             && std::is_pod<typename std::remove_reference<T>::type>::value>
{};

Then the functions reduce to

template<typename T>
typename std::enable_if<!is_mutable_pod_lvalue<T>::value>::type
UNUSED(T && v) {
    static_cast<void>(v);
}

template<typename T>
typename std::enable_if<is_mutable_pod_lvalue<T>::value>::type
UNUSED(T && v) {
    std::memset(&v, 0xBD, sizeof v);
}

In C++14, we could use the _t and _v forms to avoid typing ::type and ::value respectively, and in C++17, we could use std::bool_constant instead of std::integral_constant.

If we were using C++17, we could further reduce to a single function, by moving the test within the function body:

template<typename T>
UNUSED(T&& v) {
    if constexpr (is_mutable_pod_lvalue<T>::value)
        std::memset(&v, 0xBD, sizeof v);
}

Now we're no longer using is_mutable_pod_value more than once, we can just inline it back again:

template<typename T>
void UNUSED(T&& v) {
    static const bool is_mutable_pod_lvalue =
        std::is_lvalue_reference<T&&>::value
        && !std::is_const<typename std::remove_reference<T>::type>::value
        && std::is_pod<typename std::remove_reference<T>::type>::value;

    if constexpr ((is_mutable_pod_lvalue)
        std::memset(&v, 0xBD, sizeof v);
}

Enhancement: accept multiple arguments

Here's a varargs template that makes it easier to use:

template<typename T, typename... U>
void UNUSED(T&& v, U&&... u)
{
    UNUSED(v);
    UNUSED(u...);
}

Again, C++17 makes this simpler, with fold expressions:

template<typename... T>
void UNUSED(T&&... v)
{
    (UNUSED(v) , ...);
}

A definition is required when NDEBUG is set

Probably just an oversight, but the code is missing an #else block.  It's probably worth reordering so that the positive branch comes first (confusing because NDEBUG is itself a negative...).  Further, since the only difference between the debug and non-debug cases it the use of std::memset() in one of the implementations, we can reduce the scope of #ifdef to just that (at a small cost to non-debug compilation times):

template<typename T>
typename std::enable_if<is_mutable_pod_lvalue<T>::value>::type
UNUSED(T&& v)
{
    static_cast<void>(v);
#ifndef NDEBUG
    std::memset(&v, 0xBD, sizeof v);
#endif
}

Revised code

#include <type_traits>
#include <cstring>
template<typename T>
struct is_mutable_pod_lvalue
    : std::integral_constant<bool,
                             std::is_lvalue_reference<T&&>::value
                             && !std::is_const<typename std::remove_reference<T>::type>::value
                             && std::is_pod<typename std::remove_reference<T>::type>::value>
{};

template<typename T>
typename std::enable_if<!is_mutable_pod_lvalue<T>::value>::type
UNUSED(T&& v)
{
    static_cast<void>(v);
}

template<typename T>
typename std::enable_if<is_mutable_pod_lvalue<T>::value>::type
UNUSED(T&& v)
{
    static_cast<void>(v);
#ifndef NDEBUG
    std::memset(&v, 0xBD, sizeof v);
#endif
}

template<typename T, typename... U>
void UNUSED(T&& v, U&&... u)
{
    UNUSED(v);
    UNUSED(u...);
}

#include <memory>
void f(int i, const int ci, int& ri, const int& cri, int *pi,
       std::unique_ptr<int> ui, std::unique_ptr<int>&& rrui)
{
#ifdef TEST_UNUSED
    UNUSED(i, ci, ri, cri, pi, ui, rrui);
#endif
}

Four compilations are required to test this fully for all combinations of TEST_UNUSED and NDEBUG.


These four functions are doing different things:

The 1st and 4th set up immediately and down when the user scrolls.

The 2nd and 3rd set both up and down when the user scrolls. (The 2nd seems unlikely to work properly because triga is not defined in the 1st function, so the line triga.css("display", "none"); will result in an error. Only in the 1st will the triga element be initially hidden.)

So they will behave differently if the element #horiz_line changes position between the function being set and the user scrolling.

I'm guessing what you want is to check the position of the horizontal line and the scroll top when the user scrolls. In this case something like the 2nd and 3rd function should work, but it is needlessly complicated to pass the values as parameters and call a function from within a function. Instead you can do either:

$(function() {
  var triga = $('.trigger');
  triga.css("display", "none");
  $(window).scroll(function() {
    var down = $(this).scrollTop(),
        up = $('#horiz_line').offset().top + $('#horiz_line').height() + 25;
    triga[down > up ? 'fadeIn' : 'fadeOut']('fast');
  });
});

or

$(function() {
  var triga = $('.trigger');
  triga.css("display", "none");
  $(window).scroll(scrollMenu);
  function scrollMenu() {
    var down = $(window).scrollTop(),
        up = $('#horiz_line').offset().top + $('#horiz_line').height() + 25;
    triga[down > up ? 'fadeIn' : 'fadeOut']('fast');
  }
});

If, on the other hand, up never changes, then there will be a performance advantage to either defining up as a global variable or passing it as a parameter to the scrolling function (because accessing the DOM is usually costly in terms of performance.)

I think the other aspect of your question is whether there is a performance difference in passing a value as a parameter to a function vs. having it in the scope of an outer function; I don't know but suspect it makes a negligible difference, especially if the parameter is first defined as a variable in the outer function anyway.

More generally: focus on understanding how the code works before worrying about performance optimisation!


Welcome to Code Review :)
Here are some nits and tips to get you on your way.

It is much more Pythonic to define your functions outside the user flow and put the user flow inside of a main() function. The flow should look like this:

def bodmas():
    ...

def sqrt_n():
    ...

def main():
    print("""Choose from
        ...
    """)
    choose = input("enter required number \n")
    if choose == '1':
        ...
        bodmas()
        ...
    elif choose == '2':
        ...

Use an if __name__ == '__main__': guard to invoke your main() function.

if __name__ == '__main__':
    main()

Do you want to handle and catch errors?

A = int(input("Enter coefficient A: "))
...
sol1 = (-B-cmath.sqrt(D))/(2*A)

What if the user enters a non-numeric coefficient? Or what if the user enters 0? This is also applicable if the user tries to divide by zero in the bodmas() function.
Consider following a style guide like PEP8 to make your code more readable and consistent.

Happy coding!


Better way to count the number of occurrences of a maximum number in the array in Ruby

Your method shouldn't call the given array my_array. It's not the method's array, it's the caller's array. Just call it array, which is also shorter, so less clutter.
And you're making it very complicated. The array already offers all you need:
def max_number_count(array)
  array.count(array.max)
end

That's also much faster:
            user     system      total        real
yours   1.696091   0.034977   1.731068 (  3.476805)
mine    0.074057   0.000000   0.074057 (  0.131310)

Benchmark code:
require 'benchmark'

def max_number_count1(my_array)
    max_num, max_num_count = my_array.inject([0, 0]) {
                               |arr, age| age > arr[0] ?
                               [arr[0] = age, arr[1] = 1] : age == arr[0] ?
                               arr[1] += 1 : arr[1] = arr[1];
                               arr
                             }
    max_num_count
end

def max_number_count2(array)
  array.count(array.max)
end

n = 5
array = (1..1000).to_a * 1000
Benchmark.bmbm do |x|
  x.report("yours") { n.times { max_number_count1(array) } }
  x.report("mine")  { n.times { max_number_count2(array) } }
end


I would suggest changing your html and giving all the tags some class like 'tag', then you'll be able to do something like:

<button id="tab1" class="tab" onClick="changeColor(this.id)">B1</button>
<button id="tab2" class="tab" onClick="changeColor(this.id)">B2</button>
<button id="tab3" class="tab" onClick="changeColor(this.id)">B3</button>
<script type="text/javascript">
    function changeColor(id) {
        var tabs = document.getElementsByClassName('tab')
        for (var i = 0; i < tabs.length; ++i) {
            var item = tabs[i];
            item.style.backgroundColor = (item.id == id) ? "white" : "silver";
        }
    }
</script>

see fiddle - http://fiddle.jshell.net/vP7ku/

must shorter, Hua?


I like that you are trying to not use explicit recursions everywhere. That being said, there are a few standard functions that we could use to get a code similar to the following.

import Data.List(intercalate)

grid :: Int -> [String]
grid n = [intercalate " --- " . take n . drop (n-k) $ osxs | k <- [1..n]]
    where osxs = replicate n "O" ++ replicate n "X"

printGrid :: Int -> IO ()
printGrid = putStr . unlines . grid

Most notably, Data.List.intercalate can be used to generalize your linePrinter, and unlines helps us avoid mapM_.

If you are writing a game, then a Data.Map.Strict.Map could be useful for storing the board's current values.


Does this image-processing library break the Single Responsibility Principle?

Private Fields

I prefer to prefix my private fields with an underscore, and as readonly as possible. If you don't like the underscore, fine - but then be consistent with this, and don't use it only in your constructor - use this whenever you're referring to a private field. It greatly helps telling private fields from parameters.

Personally I don't like sprinkling this everywhere in my code, so I prefer the underscore; I also like my access modifiers explicit:

public class FilteredImageProvider : IDisposable
{
    private readonly SharpDXRenderer _renderer;
    private readonly FilterContainer _filterContainer;
    private readonly ImageGPULoaderFactory _loaderFactory;

    private GPUImage _currentImage;

    //...

Constructor

The readonly fields are still assigned in the constructor:

public FilteredImageProvider()
{
    _renderer = new SharpDXRenderer();
    _filterContainer = new FilterContainer();
    _loaderFactory = new ImageGPULoaderFactory();
}

These three should be injected as constructor arguments - creating these instances within the constructor breaks SRP, at least if you're applying DI principles. SRP is only the S of SOLID. By taking these instances in as constructor arguments, you greatly facilitate the rest of SOLID.

You're mostly exposing cherry-picked encapsulated methods, that works for me. However I find that you shouldn't be newing up the FilterCompilator like you're doing. It should be constructor-injected, and perhaps made a dependency of FilterContainer, or of another type that would deal with everything that can be done with a Filter.

Note: If _renderer is injected in the constructor, then you shouldn't call _renderer.Dispose() since you've put that burden onto the caller (ideally your favorite IoC container).


At first I tried to make it completely lock-less, but it turned out to be impossible. This implementation contains a lock however the lock isn't an instance wide.

It may shock you to hear that lock-free code may be slower than code using locking.

Lock-free code is usually longer and is definitely much more complex. You should not attempt to write lock-free code until you fully understand the .NET memory model. Joe Duffy's book would be a good starting point after reading those articles. I would say you are ready to write lock-free code when you can describe why double-checked locking is broken in Java and correctly answer this question: is it also broken in C#?

But back to the point: lock-free code is easily slower than regular locking in this instance because lock-free code is only faster when there's a lot of contention. When you're writing async-compatible primitives, any locks you take are only going to last for the synchronous portion of that method call - an extremely short time. So, unless you have literally hundreds of different threads all calling Set or WaitAsync on the same instance at the same time, you won't have a problem. In other words, async primitives kind of "lift" you to a higher level of scheduling - you actually build your own queue of waiters. And any lock you have isn't going to affect the real contention, which will be represented by that queue.

So, on with the actual code review...

As @svick correctly pointed out, you have a (benign) race condition in your code that may cause starvation, when your Set chooses to re-enqueue a TCS. You are also holding onto resources longer than necessary by keeping "dead" TCS instances in your queue. Remember that each TCS has a Task along with all its continuations, and any local variables captured by their lambdas, etc.

But that's not a deal-breaker, it's just somewhat unfair (starvation) and inefficient (holding references). There's a more sinister and subtle problem with this implementation.

You are calling back to end-user code while holding a lock. This is violating one of the central laws of multithreaded programming. Whenever you do this, there is a possibility of deadlock.

It's very subtle because the callback is not obvious, but it's there in both Set and Reset: SetResult and SetCanceled both (synchronously) invoke any task continuations that were scheduled with the ExecuteSynchronously flag.


Convert a password to a phonetic string for end users

Your code looks pretty good to me. I applaud your using datastructures to hold the mappings. A lot of developers would have used a humongous switch statement there, but I think as a general rule, datastructures are to be preferred over code as they makes things clearer and more flexible.

It's a good programming principle to break things down into smaller functions. That makes the code easier to read and maintain. It makes your code self-documenting, which means you don't need to rely on comments so much.

We can put the inner logic of your blob of code into its own function:

function wordFromChar($char)
{
    switch -Regex -CaseSensitive ($char){
        "[a-z]"{$phoneticAlphabet."$char"}
        "[A-Z]"{($phoneticAlphabet."$char").ToUpper()}
        "\d"{$numberAsString."$char"}
        "\s"{$char}# Return whitespace unaltered
        default{ $symbolAsString."$char"}
    }
}

And then call it like this:

$words = $StringToExplode.ToCharArray() |  ForEach-Object {
    wordFromChar $_
}

$words -join $Delimiter

We can improve the code in the wordFromChar function. The regular expressions such as [a-z] are repeating the information that is already contained in the hash table. That violates the DRY Principle. ("Don't repeat yourself.") This is an important principle which you can look up.

I'd be inclined to put all the hash tables into a single hash table. I don't see why there should be separate tables. Having separate tables just means we have more stuff to deal with but without any real benefits. Assuming that we make a single hash table called $charMap, we could rewrite the function like this:

function wordFromChar($char)
{
    if ($charMap.Contains($char))
    {
        $result = $charMap[$char]
    }
    else
    {
        throw "Can't handle '$char'"
    }

    if (isUppercase $char)
    {
        $result = $result.ToUpper()
    }

    $result
}

(If there was a good reason to keep the separate hash tables, we could certainly do that. We could just put them all in an array. That is, we would have an array of hash tables. That would make the lookup logic a little more complicated, but only by a little.)

isUppercase is a new function that could look like this:

function isUppercaseChar($char)
{
    $char -cmatch "^[A-Z]$"
}

-cmatch is a case-sensitive regular expression match.

I haven't tested any of the code above, by the way.


Handling null arguments in a factory class

It seems to me that you are not quite making good use of exceptions and as long as I believe it is possible that you are disrespecting some principles. First things first, you really should be using IllegalArgumentException because that is the java standard exception class for invalid arguments. You shouldn't also throw a exception and then catch it so your throw statement should be outside the try block. Why should you ever raise a error to treat it imeadiatly? You should avoid it instead!

public static Response initResponse(final Destination destination, final Source1 source1, final Source2 source2, final Source3 source3, final Source4 source4) {
    if(source1 == null && source2 == null && source3 == null && source4 == null) {
        throw new IllegalArgumentException ("Atleast one source has to be not null");
    }
    try {
        return ResponseImplManager.getInstance(destination, source1, source2, source3, source4);
    } catch (Exception e) {//if possible catch the specific type of the exception that is thrown by getInstance thought I don't see it as a huge issue as you don't have any other method calls
        throw new ABODataException("Unable to instantiate Response:"+e.getMessage());
    }
}


dead code should be removed
the indention is horrible

    byte[] StreamMessage = new byte[9632*2];
    try
    {
    socket = peerListener.AcceptSocket();

    Thread.Sleep(500);

        MessageLength = socket.Receive(StreamMessage, 0, StreamMessage.Length, SocketFlags.None);
    }

should be look like

    byte[] StreamMessage = new byte[9632*2];
    try
    {
        socket = peerListener.AcceptSocket();

        Thread.Sleep(500);

        MessageLength = socket.Receive(StreamMessage, 0, StreamMessage.Length, SocketFlags.None);
    }

you should enclose IDisposable's like Stream, StreamWriter in using blocks.

internal void SendMessageViaStreamWriter(object message)
{
    string messageOut = (string)message + "\n";
    using (StreamWriter sw = new StreamWriter(peerClient.GetStream()))
    {
        sw.Write(messageOut);
        sw.Flush();
    }
}

The use of the using statement ensures that the Dispose() method is called in any case (like an exception has happened) this also ensures that the stream is closed.
methods should be named using PascalCase casing and should be made out of verbs or verb phrases. See: Naming Guidelines
local variables should be named using camelCase casing.
the Thread.Sleep(500); does make no sense after accepting the socket. Why do you want the thread to sleep ?
SendMessageViaStreamWriter is badly named. SendMessage would be much better. What would happen if you decide to change the implementation of the method but forget to change the name, ? Mr.Maintainer would be confused.


Class that calls initiates the validation of itself and then initiates the assignment of offers

Is it bad practice to throw an exception if validation fails? Is there a better way to notify the user if validation fails?

It depends but usually validations return some kind of a validation result.

  Does this class have too many responsibilities i.e. validate and assign offers.

Actually not. They are not the responsibilities of this class. Validation is injected and provided via a service so it's fine.

I would worry more about its design.

The constructor requries two parameters but their corresponding properties are not readonly so you could just use them. More appropriate would to use fields or make the properties get only and private.

public void AssignOffers()
{
    ValidationResult results = _validator.Validate(this);
    if (results.IsValid)
    {
        _assignedOffers = _rulesOfferCalculator.CalculateOffers(this);
    }
    else
    {
        _validator.ValidateAndThrow(this);
    }
}

It's a weird process. It first validates the object and then calculate the offer. The Offer property should be a getter-only property and use the calculator to get the value and the validation should take place where the other properties necessary for the calculation are set because they need to be validated as apparently they can be invalid.


Your program looks nice and is easy to understand. I only could find a single thing that you should change.

The variable counter is wrong, since it doesn't count anything. You should remove that variable completely. Instead, write while (true), and check the return value of the "again" dialog whether it is something else than JOptionPane.YES. If so, break out of the loop.


Assuming that you will want to do more interesting things with these images later, you should probably come up with a better OOP design.  I suggest:

public interface ImageTransformation {
    public Pixel[][] transform(Pixel[][] image);
}

public class Clockwise90Rotation implements ImageTransformation {
    ...
}

public class AntiClockwise90Rotation implements ImageTransformation {
    ...
}

It's practically no work to rearrange the code that way.  In return, you gain the flexibility to do things like:

ImageTransformation[] pipeline = new ImageTransformation[] {
    new Clockwise90Rotation(),
    new ContrastEnhancer(),
    new GaussianBlur(/* radius= */ 5)
};
for (ImageTransformation t : pipeline) {
    image = t.transform(image);
}


1. The purpose of comments

Comments are a tool that you use in order to make code easier to understand and easier to maintain. But they are not the best tool to achieve that aim. Comments increase the amount of text that has to be read (you have to read the comment as well as the code) and there is a risk that when code is changed, a programmer will forget to change the nearby comments, leading to nonsense like the comments in this question.

So comments are a last resort when you can't make the code clear enough by other means. Before writing a comment you should ask these questions:

Do functions have documentation explaining their arguments and results? (In Python, do they have docstrings?)
Are there test cases (or documentation examples) demonstrating the correct behaviour of the code?
Do function names clearly describe what they do? And do variable names clearly indicate the meaning of their values?
Is the code written in the simplest, clearest way?

Only when the answers are all "yes", and the code is still not clear, should you consider writing a comment.

2. Worked example

Let's take the numberToBase function and ask these questions:

# converts number N base 10 to a list of digits base b
def numberToBase(n, b):
    digits = []
    while n: # takes n and the finds the modulus, the remainder of n % b
        digits.append(int(n % b)) # then it will append that to a list
        n //= b # following on it will then divide n into b
    return digits[::-1] #returns those digits into reverse order from -1, the end to the beginning

There's no documentation. Let's turn the first comment into a docstring:

def numberToBase(n, b):
    """Convert the number n to base b and return a list of digits."""
    digits = []
    while n:
        digits.append(int(n % b))
        n //= b
    return digits[::-1]

There are no examples. Let's add some:

def numberToBase(n, b):
    """Convert the number n to base b and return a list of digits.

        >>> numberToBase(1234, 10)
        [1, 2, 3, 4]
        >>> numberToBase(1023, 2)
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

    """
    digits = []
    while n:
        digits.append(int(n % b))
        n //= b
    return digits[::-1]

These are in the form of doctests so that they can be automatically checked using the doctest module.
There are bunch of improvements we can make to the names. (i) Something like number_to_digits would be clearer than numberToBase since the result is a list of digits. (ii) base would be clearer than b. (iii) The built-in function divmod would make it clear that we are computing the division and modulus. (iv) The name digit for the modulus would make its meaning clear. (v) Using the built-in functions list and reversed would make it clear that we are computing a list in reverse order.

def number_to_digits(n, base):
    """Convert the number n to a list of digits in the given base.

        >>> number_to_digits(1234, 10)
        [1, 2, 3, 4]
        >>> number_to_digits(1023, 2)
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

    """
    digits = []
    while n:
        n, digit = divmod(n, base)
        digits.append(digit)
    return list(reversed(digits))

The code seems clear and simple now: there is no need to add any comments.

3. Other review points

When n is 0, the result is an empty list. It might be better to return the list [0].
When b is 1, the function goes into an infinite loop. It might be better to raise an exception in this case.


Coding style

There's a limit to how much untidiness a reviewer is willing to tolerate.
This code is right on the border.
Please read PEP8 and follow the recommendations carefully.
There is also a command line utility called pep8 that can check your program and tell you what to fix.
There are also editors like PyCharm that warn you about violations of coding conventions,
and help you fix them.

In my review below, I will try to not repeat what PEP8 can already tell about your code.

Return values

Many of the functions don't have an explicit return value.
Take for example this:

def checkVertical(table,token):
        # VERTICAL
        for column in zip(*table):
            check_col = []
            for item in column:
                if item == token:
                    check_col.append(token)
                if len(check_col) == len(table[0]):
                    return True

The nested loop might be exited with a return True.
If that doesn't happen,
there's no other return statement,
so the method will exit with None.
This may work OK,
as None is a falsy value in Python,
but it would be cleaner to add a return False at the end to make this a proper boolean function.

Strange logic

What is going on in this function?

def whoWon(who, table, token):
    if who == 'x':
        if(checkHorizontal(table,token)): return True
        elif(checkVertical(table,token)): return True
        elif(checkDiagonal(table,token)): return True
    else:
        if(checkHorizontal(table,token)): return True
        elif(checkVertical(table,token)): return True
        elif(checkDiagonal(table,token)): return True

Regardless of the value of who,
the same code gets executed.
And again, there's no explicit return statement in case none of the conditions match.
As it is, the function could be replaced with:

def whoWon(who, table, token):
    return checkHorizontal(table, token) or checkVertical(table, token) or checkDiagonal(table, token)

Separation of concerns

The board() function reads the board size and initializes a board.
That's two distinct responsibilities.
It would be better to split these to different functions.

Simplifications

The initialization of the board in the board() function can be simplified:

return [[0] * board_size for _ in range(board_size)]

checkHorizontal() can be similarly simplified:

def checkHorizontal(table, token):
    for row in table:
        if all(column == token for column in row):
            return True
    return False


Determine whether there is a winner in tic-tac-toe game

Your code is WET.

var[0] != 0 and len(set(var)) == 1

Is repeated four times.
field[len(field)-i-1] can be simplified to field[~i].
I'd personally just use a couple of any and a couple of ors.

def is_unique_player(values):
    return values[0] != 0 and len(set(values)) == 1

def is_win(field):
    N = len(field)
    return (
        any(is_unique_player(row) for row in field)
        or any(is_unique_player(column) for column in zip(*field))
        or is_unique_player([field[i][i] for i in range(N)])
        or is_unique_player([field[~i][i] for i in range(N)])
    )


At first glance, a couple of things I'd change about your code are:

Follow coding standards, PSR being the most commonly adopted standard out there. Class definitions and method definitions have the opening { on a separate line.
Specify the visibility of properties (as you do) and methods. Relying on the implied public will work for now (might change in the future), but it's best to be explicit: self-documenting code is what you should be aiming for
use type-hints as much as you can. In particular your ArtikelRepository class: the constructor takes a $database argument, but what is it supposed to be? You're not performing any checks to see whether or not the value that was passed was indeed the expected one. I could've passed a string, null or anything in between. Same goes for the addArtikels method, and the ArtikelMapper class.
Method names should make sense. addArtikels is plural, so going by the name, I expect to pass an array of Artikel instances, but you're using array_push on a property that is a 1-dimensional array of Artikel instances. The correct name for that method would be addArtikel.
The ArtikelMapper class should not depend on the DB. It doesn't even look like a mapper. A mapper maps a set of data in a particular format (arrays, class instances, ...) onto another format (eg query results returned as arrays can be mapped onto Artikel instances). That's its job, exposing the DB to this class does not make sense.
This suggests the mapper class you have is violating the Single Responsibility Principle (SRP).
The use of require_once all over the place seems to suggest you're not using an autoloader, which is fine for quick, small tests or proof-of-concept type work, but for actual applications, use namespaces and a PSR compliant autoloader.
Personal preference perhaps: but entity setters are, IMHO, best fluent (return $this;) so they can be used in a single statement without having to repeat the variable to which you've assigned the instance.

Basically, here's how I'd write the Artikel entity:

class Artikel
{//new line
    /**
     * @var int
     */
    private $id;

    /**
     * @var string
     */
    private $naam;

    /**
     * @param int $id
     * @param string $naam
     */
    public function __construct($id, $naam)
    {//new line
        $this->id = $id;
        $this->naam = $naam;
    }

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return string
     */
    public function getNaam()
    {
        return $this->naam;
    }

    /**
     * @param int $id
     * @return $this
     */
    public function setId($id)
    {
        $this->id = $id;
        return $this;
    }

    /**
     * @param string $naam
     * @return $this
     */
    public function setNaam($naam)
    {
        $this->naam = $naam;
        return $this;
    }
}

The setters could perform some basic validation on the arguments passed (eg make sure $id is an integer), in which case, the constructor should not assign the properties directly, but rather call the setters, too.

Along with the (mainly style) changes to the entity class, I'd refactor the repository class, too:

class ArtikelRepository
{
    /**
     * @var ArtikelMapper
     */
    private $artikelMapper;

    /**
     * @var Database <-- what class is this?
     */
    private $database;

    /**
     * @var Artikel[]
     */
    private $artikelArray = [];//initialize to array already

    /**
     * Do NOT create depenendencies in constructors, INJECT dependencies!
     * In a true Respositor, the database connection is a dependency of the Repository, not the mapper
     * @param Database $database
     * @param ArtikelMapper $mapper
     */
    function __construct(Database $database, ArtikelMapper $mapper)
    {
        $this->database = $database;
        $this->artikelMapper = new ArtikelMapper($database);
        //Don't use a constructor to query the DB, only load data if we need it
        //$this->artikelArray = $this->artikelMapper->getArtikels();
    }

    public function getArtikels()
    {
        if (!$this->artikelArray) {
            $results = $this->database->getArtikels();//load from DB
            //use mapper to convert results into Artikel instances
            $this->artikelArray = $this->artikelMapper->mapResults($results);
        }
        return $this->artikelArray;
    }

    /**
     * @param Artikel $artikel
     * @return $this <-- fluent interface
     */
    function addArtikel(Artikel $artikel)
    {
        if (!$this->artikelArray) {
            $this->getArtikels();//initialize artikels if needed
        }
        $this->artikelArray[] = $artikel;//don't use array_push
        return $this;
    }
}

I don't know what it is you're trying to do exactly, but I'm not sure why you're actually loading all existing artikel instances and assigning them to your repository property. A repository fetches data from a persistence layer in a format that the rest of the application understands. Nothing more, or less. You can add some caching mechanisms to avoid hitting the DB for data you already loaded, but in that case, it'd make more sense to use $artikelArray as an associative array (using the ID as key). To be honest, I wouldn't bother with that property at all for now, and perhaps consider adding a specialized caching layer later on.


Storing arbitrary form data in SQL as an XML blob

Well, it depends what you want to do with this data. If you ever want to query individual field names or debug an issue with a field you will have a hard time extracting this kind of information out of an XML blob.

Potential pitfall: According to the coldfusion docs, CF_SQL_VARCHAR maps to varchar columns on MSSQL. You need to make sure that the column is varchar(max) as XML can get pretty verbose and any character limit might get hit.

On how to better store the data this is hard to say. From your example it looks like a form has fields and each field could have multiple values. This looks like a classic 1:n relationship to me:

Form table:

FormID | Name | Description | ...

Field Name table:

FieldID | FormID | Name

Field Value table:

ValueID | FieldID | Value


No, that is not one of the five standard-compliant ways to generate a UUID.  What you have written is just an obfuscated concatenation of a timestamp and a random number.

The easiest way might be to use the MySQL UUID() function instead of generating the UUID in Rust.


Ohms law calculator + whitelist of user. Learning use

Don't

using namespace std;

This doesn't do what you want (only first one works):

    //Whitelist
    Whitelist = "Fred267s", "Seb4572s", "Popp4593s";

    //Check if username is on whitelist
    if (Username == Whitelist){

[It's also a VERY dodgy access control mechanism!]

I don't like asking user for a string describing the "Formula". How does the user know they should type "Wolt"? What if they type "wolt" instead? I think it would be more reasonable to show 3 choices:

1 - Wolt    2 - Amp    3 - Ohm

Please Enter (1-3):

And then clean the user input checking if it is a valid integer between 1-3 and then represent the choice internally using a Class enum in your code.

This will open up a range of oppotunities to use functions in your code.

enum class Formula ( wolt = 1, amp = 2, ohm = 3 );

...

Formula prompt_formula() {
  // code to read from std::cin clean input and cast to enum class
}

Then try to find a way to add even more structure to your program rather than one huge if/elseif/else statement. I am not going to give you the code, because that would defeat the purpose, but your main function should be more like this:

int main() {
  explain_usage();
  Formular form = prompt_formular();
  auto [label, answer] = compute(form);
  print_answer(label, answer);
}

I could go on, but that's probably plenty to get on with for now.


Combining two arrays using nested foreach loops

I have made the assumption that there is a 1:1 relationships between the $attributes and $values array elements. With that I mean the array key in the $attributes array corresponds with an entry in $values array.

If that is the case it can be reduced to one foreach loop by using the key from the attributes array:

$combined = []; // Make sure the $combined array exists.

foreach($attributes as $key => $attribute) {

    // First check if the array key exists and that the 'system_name' is the same
    if(array_key_exists($key, $values) && $attribute['system_name'] == $values[$key]['system_name']) {

        $combined[$attribute['id']] = $values[$key]['value'];

    }

}

This should produce the following array with the data you have provided:

Array(combined)
(
    [106] => 'Alfa Romeo'
)

If my assumption is incorrect, then just ignore my answer.


Ruby Rails - Snippets from a project that don't seem so eloquent

Maybe you can convert this:

scope :filter_active_cars, lambda { |options|
 filter = {}
 filter[:cars] = {:year => options[:year]} unless options[:year].empty?
 filter[:makes] = {:id => options[:make]} unless options[:make].empty?
 filter[:models] = {:id => options[:model]} unless options[:model].empty?

 joins(:car, :model, :make)
 .where(filter)
 .includes(:car, :model, :make)
 }
}

to this:

scope :filter_active_cars, lambda do |options|
 with_option(:car, 'cars.year', :year).
 with_option(:make, 'makes.id', :make).
 with_option(:model, 'models.id', :model)
end

scope :with_option, lambda do |assoc, column, option|
  (options[option].present? ?
    joins(assoc).where(column => options[option]) :
    self).
  includes(assoc)
end

You can reuse the with_option scope in other models


Instead of using a counter to count the keys for which the condition is true, you could just return false as soon as you find a key which is not an int and return true if the loop reaches its end without finding such a key:

foreach ($array as $a => $b) {
    if (!is_int($a)) {
        return false;
    }
}
return true;

This has the benefit that it short-circuits (i.e. it stops iterating once it finds a key that is not an int) and gets rid of the counter.


Checking conditions before allowing a play button to become visible

Just a few more minor things on top of jt0dd's excellent review.

Anonymous functions in JavaScript are awesome, but your program will be more readable if you give the main functions names and declare in advance. That way the main part of your program will become something like this:

if (!haveSilverlight) {
    $('.playbtn').hide();
    $('.videoposter').append('<button class="installbtn" />');
    if (isNodeWebkit) {
        $('.installbtn').on('click', openExternalSilverlightDownloader);
    } else {
        $('.installbtn').on('click', openSilverlightDownloader);
        $(window).on('focus', setupInstallBtn);
    }
} else {
    $(window).on('focus', setupPlayBtn);
}

Easier to see the overall logic, no?

Don't write if statements this way:

if (something) {
     // ...
} else if (!something) {
     // ...
}

That's what else is for:

if (something) {
     // ...
} else {
     // ...
}

You don't need to evaluate boolean variables like this:

if (isEncoding == true) {
    // ...
}

You can do simply:

if (isEncoding) {
    // ...
}

On this line, you don't need the brackets, and I think the code would be more readable with the comment on the line before the assignment.

var isNodeWebkit = (typeof process == "object"); // check if using node app

Better this way:

// check if using node app
var isNodeWebkit = typeof process == "object";

Especially with long lines like this, definitely don't put comment after the statement, as it forces me to scroll right, which is not convenient. Even better, the a comment saying // setup download URL variable for a variable assignment is pointless, so it's better to just drop it.

var downloadURL = 'https://www.microsoft.com/getsilverlight/get-started/install/'; // setup download URL variable
var isEncoding = false; // setup isEncoding variable

These lines should have been just:

var downloadURL = 'https://www.microsoft.com/getsilverlight/get-started/install/';
var isEncoding = false;

Without comments, assignments are self-explanatory.


These functions can be static, and therefore should be.  Marking them static makes it clear that this is not object-oriented code.  It also serves as a hint for the JIT to inline the helper function.

Instead of using Math.abs() and Math.max(), I suggest using Math.max() and Math.min(), which simplifies the conditionals a bit.

I would expect getHeight(null) to return 0.  As you've written it, a node with no children is at height 2, which is a weird place to start counting, even if it works.

Never omit braces like that.  You will contribute to a coding accident: [Citation 1] [Citation 2]. If you really want to omit braces, then put the entire conditional statement on the same line for safety.

private static int getHeight(Node node) {
    if (node == null) return 0;

    int leftHeight  = getHeight(node.getLeft()),
        rightHeight = getHeight(node.getRight());

    int taller  = Math.max(leftHeight, rightHeight),
        shorter = Math.min(leftHeight, rightHeight);

    if (shorter < 0 || taller - shorter > 1) {
        return -1;           // Unbalanced tree
    } else {
        return taller + 1;
    }
}


Django query filter on count in one to many relation

It's easier to answer this kind of question if you give us more code. I would have preferred the question to contain (possibly cut-down) code for your models, not just a summary description of the models.
The comment for the error field says "can be null/blank" but your code only tests for NULL, not for blank. If the comment is correct, then your code is buggy; conversely, if the code is correct, then the comment is wrong.
The question says, "I filter them afterward to check if I have more than one" but the code says, count__gt=0, so it is actually filtering for more than zero failed charges. If the text of question is right then the code is buggy.
There's no need for the count annotation — if you add a filter on a one-to-many relation then you only get results where there is at least one record that matches the filter. (In SQL terms, Django's filters on one-to-many relations are implemented as inner joins.)

So all that's needed is:

# Donations with at least one failed charge.
Donation.objects.filter(charge__error__isnull=False)

You can check this by looking at the SQL that is generated by Django's ORM:

>>> print(Donation.objects.filter(charge__error__isnull=False).query)
SELECT "myapp_donation"."id" FROM "myapp_donation"
  INNER JOIN "myapp_charge"
  ON ( "myapp_donation"."id" = "myapp_charge"."donation_id" )
  WHERE "myapp_charge"."error" IS NOT NULL

(The count annotation would, however, be necessary if the requirement were to select donations with more than one failed charge, as stated in the question.)


Simple Form Starts Long Running Task and Watches Progress

Is there any reason you're using global variables rather than passing function arguments? e.g.

exportProgress = data; progressHandler();

instead of progressHandler(data); ?

It's a much better practice to avoid globals as much as possible.
Instead of polling for progress every second, you could subscribe to SSE (Server Side Events), thus getting the latest progress updates and no unneeded traffic.

In JS this amounts to:

window.onload = function (e) {
    var source = new EventSource("get_progress");
    source.onmessage = function(event) {
        try {
            const response = JSON.parse(event.data);
            progressHandler(response)
            if (response.completed) {
                source.close();
            }
        } catch (error) {
            console.log(error);
        }
    }
}

function progressHandler(response) {
     progressBar.val(response.progress / response.total);
     if(response.completed) reset();
}


Bare bones implementation of Java HashMap

Strange constant usage
This code seems strange to me:

private int getHashCodeForKey(K key){
    int result = 7;
    return 31 * result + (key != null ? key.hashCode() : 0);
}

Why set result to 7, just to multiply it by 31?  That is, why not this:
private int getHashCodeForKey(K key){
    int result = 7 * 31;
    return result + (key != null ? key.hashCode() : 0);
}

It makes me think that you wanted to multiply the whole thing by 31 but I'm not sure of your intent.
Weakening the hash
The code that uses the hash code:

    int hashcode = getHashCodeForKey(key);
    int index = hashcode & size;
    Node head = arr[index];

weakens the hash because you are using power of 2 sized arrays (in your case a fixed size 16 array).  So in your case you are using only 4 bits of the hash.  If your array size were 17 and you used % 17, it would use all the bits of the hash.
Poor performance
With a fixed size of 16 buckets, your hash will quickly devolve into a linear search once you add a lot of entries.  A proper hash map would resize itself at appropriate intervals to maintain performance.
Correctness
This comparison is not correct:

if(head.key == key)

For example, two strings that have the same contents will not compare correctly using the above code.  You should change the comparison to:
if (head.key.equals(key))


Fast prototype code to hook up a webcam to the Azure Emotion API

Dealing with DOM

document.getElement[s]By*(...) competes with $(...). Do not mix DOM accessing styles. That hurts readability. Either use jQuery everywhere, or native API everywhere. jQuery is kind of out of fashion nowadays, mainly because major browsers got much better in exposing DOM accessing APIs.

Dealing with Http

Again, since your code already depends on jQuery, I don't see why prefer XMLHttpRequest over $.ajax(). Inconsistency of the code is one of the biggest issues when it comes to maintenance, especially in case of new hires.

Separate Data from Logic

Your mood to color scheme relationship is data that can be encapsulated in a separate place (apart from the places where it's being used). Say, you define color scheme like this:

  var schemeOfMood = {
      'Angry': { htmlBackground: '#F44336', htmlColor: '#FFFFFF', spanBackground: '#FFFFFF' },
      'Contempt': { htmlBackground: '#9C27B0', htmlColor: '#FFFFFF', spanBackground: '#FFFFFF' },
      // ...
  };

then the coloration logic becomes trivial, and no ugly switch is needed at all.

  var scheme = schemeOfMood[tempEmotion];
  htmlBody.css('background-color', scheme.htmlBackground);
  htmlBody.css('color', scheme.htmlColor);
  $('span').css('background-color', scheme.spanBackground);

The other good effect is the reduced code repetition.

Move Magic Code into Functions

When I see lines like that they look Magic to me.

let file = document.getElementById('base64image').src.substring(23).replace(' ', '+')

What is subsctring(23)? Why 23 and not 32 (I like powers of 2 more) -- "magic numbers"? Why replace ' ' with '+'?

If you extract this one-liner into a function, you can give it a good name, thus expressing your intent. At the moment, I didn't even try to understand why that manual transformation of a base64 image is needed.

Unclear Intent

When giving user a feedback, there's this if (result[0]) { ... } that makes the code look only into the first result. Why is that?

Put it into a variable, give it a name, and you will avoid the hard-to-read result[0] and explain what's going on.

var lastChronologicalResult = result[0];
if (lastChronologicalResult) {
  // work against lastChronologicalResult
}

Very similarly, the code loops through multiple results' child nodes (for (let i = 0; i < result[0].childNodes.length; i++) { ... }) and does two things:

A) populates emotionArray based on each child;

B) calculates the tempEmotion based on the last child which has .textContent.toFixed(2) > tempValue. Nobody knows what textContain holds and what's the tempValue.

So, better naming things and function extraction would clarify what is being done in that part of the code.


Code Golf Challenge: Calculate Phi (not Pi)

I would move your main outside of the golf namespace instead of glueing code together.
The not_pi name is confusing to me because I would assume its a function that checks if n is not 3.1415926..., which it clearly doesn't do.
Another suggestion is to expose most of this functionality in a golf.h header so that you can call this code from some where else. In that case move main completely outside golf.cpp and into main.cpp or similar.
Other than that you should add documentation/comments to all non-trivial functions.

Now let's talk performance.
GCD
If you have extra memory handy, then you can optimize your gcd calls through a technique known as memoization.
Basically, for small left and right (which I would rename to a and b) you would calculate the result once and then store it for future reference. This requires a minor modification to the gcd function to check if it has a pre-calculated result for that problem, and then return the result in that case. The reason this will help in the long run is that if you trace the calls to gcd you will note that it will usually end up in the smaller values and calculate these results over and over again.
I would use a 2D array or a vector of vectors for this purpose and store up to gcd(1000, 1000) or so (if you have more memory free, feel free to increase this while your code execution time increases on the desired input).
Prime
An easy optimization is checking the i = 2 case separately from the odd numbers which allows you to loop by 2's and so is roughly a 2x speedup.
There are also much faster algorithms for this than brute force division such as Miller-Rabin which can be made deterministic for a finite range of integers (a potentially very large range, much larger than 64 bit integer maximum).


alias is like root, so you need to use full server path
you can add break flag to rewrite for avoid internal redirect. added without break rewrite will make loop (internal redirect) for process all locations again; but break tell to rewrite do not loop and run current location.

I don't think here big difference in performance. Main difference is changing internal request uri. But in case of static files serve both work well.


The () is not needed in this example - the following example compiles fine.
match line {
    "" | "." => {}
    ".." => {
        str_vec.pop();
    }
    _ => str_vec.push(line),
}

This is as all arms need to return the same type, and in this case it is the type (). Luckily this type is inferred, and as such you can just make a block and (as long as it doesn't return anything), it will be inferred that the () type is being returned instead.
I would recommend making some other changes to your code though - namely changing the &String argument to &str, which can improve performance in some cases and allow more string types (such as a string literal) to be passed to the function. This type of issue can be picked up by running clippy, which also picks up a wide variety of issues - a full list can be found at https://rust-lang.github.io/rust-clippy/master/.


Make file paths relative to the configuration file path

A very raw and simple approach.
 I believe you would be loading the properties from the configuration file.

Properties prop = new Properties();
prop.load(new FileInputStream("somepath/config.properties"));

Hence I assume you know the path of your config file.

Now simple iterate over your properties and set them again.

for(String name : getProperty.getNames()) {
   String propValue = prop.getProperty(name);
   //TODO if(propValue == relative)
   setProperty(name, somepath + propValue);
}


Basically you are working with these class members inside the thread functions _temporize and _sleepThenTimeout.

timeout, _isSingleShort and _interval, these three cannot be changed after the start function is called, so it is safe to use them.
_running on the other hand can be read/write by both threads. In reality it might not cause any problem as assignment to bool is atomic (on most architectures), but to be 100% safe you can use std::atomic<bool>.

Another important thing to keep in mind is that while timer class itself is thread safe, it is responsibility of the user of this class to make sure that the timer call back function (_timeout) is thread-safe by it self, as it will be executed in a separate thread.


Binary Insert Method - handling edge cases

Here are some thoughts:

For benchmarking there are two modules folks usually use:

cProfile

bettertimeit

I put an example in a previous post located here:

Profiling

Also, can you please post the entire script? Just want to make sure I have full context. Namely mid_point.


My initial thought is to simply lose the break.  While they have their place in switch-case statements, it is generally best to avoid them in loops unless they're used at the top of a loop and truly help improve readability.  Even then, I tend to look for alternatives.

do {
    hr = pEnumMgmt->Next(1, &mgmtObjProp, &ulFetched);
    if (hr != S_FALSE) {
        llCbStorage += mgmtObjProp[0].Obj.DiffArea.m_llAllocatedDiffSpace;
    }
} while (hr != S_FALSE);

Alternatively, you could just initialize hr prior to the while loop and avoid the extra check against S_FALSE every loop.

hr = pEnumMgmt->Next(1, &mgmtObjProp, &ulFetched);
while (hr != S_FALSE) {
    llCbStorage += mgmtObjProp[0].Obj.DiffArea.m_llAllocatedDiffSpace;
    hr = pEnumMgmt->Next(1, &mgmtObjProp, &ulFetched);
}

I don't like the following style of while loop as it utilizes a side-effect.

while ((hr = pEnumMgmt->Next(1, &mgmtObjProp, &ulFetched)) != S_FALSE) {
    llCbStorage += mgmtObjProp[0].Obj.DiffArea.m_llAllocatedDiffSpace;
}

Lastly, it may be worthwhile to consider a for loop here.  I like the look of this because it cleanly separates the looping from the updates to llCbStorage.

for (hr = pEnumMgmt->Next(1, &mgmtObjProp, &ulFetched);
     hr != S_FALSE;
     hr = pEnumMgmt->Next(1, &mgmtObjProp, &ulFetched))
{
    llCbStorage += mgmtObjProp[0].Obj.DiffArea.m_llAllocatedDiffSpace;
}


Pull out text within specific divs on a webpage

First of all: how big is this document? If you're not expecting it to be big, you may want to use html.Parse instead of a tokenizer - that way, you'll get the whole document in a tree and would be able to iterate over children of your div when found, which should make the whole thing simpler.

Your current approach is streaming, which conserves memory, but you are making the assumption that the div with the class project-title will always contain just text. What if the document looks like this:

not title
title

or this

wrong title

In the first case, "not title" would be added. In the second, "wrong title" would be added.

Assuming you want to keep your logic as-is, let's move on the review!

A few general tips:

Always put string literals on top as constants (e.g. const className = "project-title").
You don't need to name your return values unless you see a need.
While Go values brevity, z is (almost) never a good variable name.
Most of the comments don't add any value (e.g. "Check if the token is an
 tag").

Some specific things:

In isImageDiv, you don't need a separate if block. You also don't need to name the return value, which actually simplifies your code in this case. Finally, you should also check if the element is a div - that way, you needn't do it in crawl:

func isImageDiv(token html.Token) bool {
    if token.Data != "div" {
        return false
    }
    for _, a := range token.Attr {
        if a.Key == "class" && a.Val == "project-title" {
            return true
        }
    }
    return false
}

getLabel seems too simple to have a need to exist.
In crawl, you shouldn't use fmt.Println. Instead, return an error, the same way http.Get returns it. Let the caller handle it.
In crawl, you can simplify the switch a lot - continue is not really needed and we made our isImageDiv function do the div check as well:

switch tt {
case html.ErrorToken:
    return
case html.StartTagToken:
    if isImageDiv(z.Token()) {
        readText = true
    }
case html.TextToken:
    if readText {
        *foundLabels = append(*foundLabels, getLabel(z))
        readText = false
    }
}

In main, you don't need to use make for a slice since the default value for a slice is an empty slice (you can just define it as var foundLabels []string and it will just work). Also, you shouldn't pass the slice as a pointer - slices are passed by reference anyway (not really, but due to the nature of how they work, they're already pointers). Make sure you change your crawl function as well after that.


If ServiceLocator.Current.GetInstance<MultiViewModel>().EightBoxesCommandIsEnabled evaluates to true you never do anything; so hoist it out of the if statements and do an early return:

public void Resize(SizeChangedEventArgs input)

    if(ServiceLocator.Current.GetInstance<MultiViewModel>().EightBoxesCommandIsEnabled)
        return;

    if (input.NewSize.Width < 450 && Crutch)
    {
        ChangeToSmall(2, 2);
    }
    //...
}

You can name crutch into something better that describes what it represents. Or keep whether ChangeToSmall or ChangeToBig was called last and replace crutch with that property.

void ChangeToBig(int, int){
    lastChangeCalledBig = true;

    //...
}

void ChangeToSmall(int, int){
    lastChangeCalledBig = false;

    //...
}


Task solution

Whole algorithm you created assumes node with label 0 is a root. It will give you false negative on other instances. This may be part of the assignment though, so will not be judge of that.

In case it is not, use method of gradual removal of leaves. First detect all leaves putting them in process queue. Then gradually remove those leaves, and if a neighbour of removed leaf becomes a leaf itself, add it to queue in the next round. If given graph is a tree, you should end up either with empty set of nodes, or root of the tree.

Data structures

In case it is sufficient, use byte instead of int arrays. As opposed to byte variable (1 cell = 4 bytes), byte array is actually spread to have 1 cell per 1 byte of memory. This will crank up your cache line hit chances, as more of the used information is in the cache at the same time. This pays both for input array (which you may not be able to change) but also for visited array.

Enum is all fine and dandy, but there is no good reason for enum that is used solely inside of a relatively small function. Especially when name of said enum is so generic as "state". At least make it private is you want to use it.

BFS vs DFS

BFS and DFS have the same complexity, and in this case, they would yield the same result. The difference is in performance though. In case of simple linked list queue, you create a lot of objects for starters, which is quite expensive operation in itself, that are all over the place in terms of memory, so two items in the queue will be rarely on the same cache line, and thus no hits.

For BFS, you could implement array rotational queue (limited size), where on poll you increment head and on add increment tail (both in modulus size Q, which should be power of 2 to have boost from masking instead of modulus itself). This will give you some hits from both sides of the queue.

As I mentioned, using DFS is also an option. But somewhat better, since you have array stack, fixed size again, but no modulus, shifting only one pointer. This will ensure that you operate only on one cache line, as opposed to two of them in case of queue.

The size in both cases does not need to be larger than N, number of nodes in the graph.

Pruning

When you expand, you always add a node in the queue, even though it may already be there. The thing is, if a node is inside of the queue, you already know you will encounter it twice, once marking it visited, second time finding out it is visited and terminating with false.

You can thus check whether an item is in queue (different flag) and save yourself all the computation that might come in between.

Next, the loop at the end where you are checking whether all nodes were visited at least once, it is connectivity checking. You can do that much faster, if you will introduce a counter, that is incremented (use pre-increment) every time you mark the node as visited. Then if you are checking at the end overall connectivity, you can just compare this counter to number of nodes, and if they do not match, a node was omitted. This way, you'll save N conditionals (that are well predicted, but still worse than addition), and pay for it with addition operation, which is not tied to anything else in the position of use, so it is well pipelined.

First loop can be removed as well, since removal of enum, and stating that 0 is unvisited, simple allocation initialized the array to correct values.

Conclusion

It is hard to optimize this, since complexity of DFS/BFS on adjacency matrix graph is O(N^2), so everything is kind of shaded by that.

I hope this "all over the place" text helped at least a bit.


I am not an expert in the zlib source tree nor am I familiar with the coding style of its authors, but I found this to be an interesting question.  I'd say it looks safe and my guess is the original authors are expecting offset to be initialized to zero. Update: OK, I misread an if statement; looking at it again it looks like it might be unsafe without a custom allocator, so we'd have to look at inflateInit et al. and the actual inflate logic to know for sure.

Explanation follows:

It looks like inflate_state is allocated with the ZALLOC macro.

That macro resolves to:

#define ZALLOC(strm, items, size) \
       (*((strm)->zalloc))((strm)->opaque, (items), (size))

According to comments in zlib.h, correct use of the library requires the caller to initialize the zalloc member being called:

The application must initialize zalloc, zfree and opaque before
   calling the init function.

If strm->zalloc is NULL, which I'd expect most callers to do, the library uses its own default implementation, zcalloc.

zcalloc, with some exceptions for ancient MS-DOS compilers and so long as sizeof(unsigned int) is greater than 1, ends up calling calloc.

calloc by definition zeroes out its data.

So, I'd say it's safe under the following conditions:

If you use a custom allocator, make sure it zeroes out the data.

2. sizeof(unsigned int) must be > 1.  (I'm guessing the standard guarantees that but I'm not certain.)

After the update: Now realizing that the allocations are not necessarily zeroed, I'd say it all depends on whether or not the local variable here can be used uninitialized, as the only assignment I see is based on that value.

Note that inflateInit, which calls inflateReset, which calls inflateResetKeep, seems to initialize the members that the assignments to here depends on, notably lenbits.  It looks like there are lots of size checks for overflow as well, eg: if ((unsigned)(here.bits) <= bits) break;.  I haven't given it a thorough audit but I'd say everything I've seen so far looks safe.


Compare two strings in extended memory - classic 8052

AT89S52 is not a classic 8052. Like all modern 8052 variants I know of, it has one feature which really shines here. Namely, it is dual data pointers. Instead of reloading DPL and DPH every time, initialize them once, and just toggle the AUXR1.DPS bit:

; setup
    clr AUXR1.DPS
    mov DPL, R2
    mov DPL, R3

    cpl AUXR1.DPS
    mov DPL, R4
    mov DPL, R5
    ....

; loop
checknexbyte:
    cpl AUXR1.DPS
    movx A, @DPTR
    mov B, A
    inc DPTR

    cpl AUXR1.DPS
    movx A, @DPTR
    inc DPTR

    cjne mismatch
    djnz R7, checknextbyte
mismatch:

You may spare a register (R6), few cycles, and some bytes by using C flag (set by CJNE) as a match/mismatch indication.
It looks like the exit logic is incorrect. On a mismatch (A != B) the jump is taken, and the loop continues. Correct me if I am wrong.


There are a couple bad things in the code

First of all, this is weird in many ways:

private Container() {
    System.out.println("Start");
}

You print out "Start" to the standard output. This basically restrict any usage of this class to have access to a console. What if it is used in a GUI application? What if this is used in a server application?

Also, "Start" what? Whoever read the console will have no clue what is started?

The object is constructed as a static field, and Java did not guarantee when these static constructor are run (they only guarantee it is run before the class methods is run, so it is basically you have a console print that is shown in non-deterministic time.

This is not great too.

public void setAppName(String appName) {
    this.appName = appName;
}

Whoever got access to the Container object instance can call this method, which means you basically have a global variable that anyone can access. That's a bad idea, because it will makes debugging really difficult.

From these classes, it appears to me that all you needed is to let the app name and app owner initialized once and get access anywhere, you can make that by simply having a Configuration class with a static property.

public class Configuration
{
    private static String appName;
    private static String appOwner;
    public static void Initialize(String appName, String appOwner)
    {
        Configuration.appName = appName;
        Configuration.appOwner = appOwner;
    }
    public static String AppName() { return Configuration.appName; }
    public static String AppOwner() { return Configuration.appOwner; }
}

That would be it, simple and clear.


Creating a dictionary of strings and list of strings

Just get rid of the outer foreach as well:

dict = objectList.SelectMany(x => x.StringList)
       .Select(x => x.Split('_'))
       .GroupBy(x => x[0])
       .ToDictionary(x => x.Key, x => x.Select(g => g[1]).Distinct().ToList());

SelectMany retrieves all the StringLists and flattens them into one single list:

"A_1", "B_1", ..., "F_1", "A_2", "B_2", ...


Splitting a string into groups of up to 3 numbers, or one letter and up to 3 numbers

right ... "tempted to solve this with a regex" doesn't quite cut it. There is a regex that kinda sorta somewhat works, but I didn't get it to do exactly what I want.
Doesn't matter though, because I can make it do what I wanted, namely spit out the results directly as separate groups. Instead I got it to match the "last result" an:

private readonly Regex someNiceName = new Regex(@"^((?:[A-Z]\d|[1-9])\d{1,2})+$", RegexOptions.Compiled);

public List<string> SpecialSplit(string input)
{
    if (input == "")
    {
       return new List<string>(); // base case for recursion
    }
    var match = someNiceName.Match(input);
    string last = match.Groups[1].Value;
    var precedessors = SpecialSplit(input.Substring(0, match.Groups[1].Index));
    precedessors.Add(last);
    return precedessors;
}

With a bit of luck we don't actually need this mess, but can rely on Captures instead:

public List<string> SpecialSplit(string input)
{
    var match = someNiceName.Match(input);
    var fullMatch = match.Groups[0];
    return fullMatch.Captures().Select(c => c.Value).ToList();
}

unfortunately I do not have C# available to check right now, but that might work better :)


ASP.NET Password Hashing reimplemented in PHP

I don't have any great concern over the implementation here when thinking of it in the context of a code port.

I do have some concern that you would be continuing with a potentially bad design.

For example:

An iteration count of 1000 for PBKDF2 seems low. Most standard implementation now use 10K+, though ultimately you would need to tune this based on the hardware on which you are running the algorithm and the desired hash computation time you are looking to achieve.  You code right now gives you no way to tune this.
Which, leads my to the concern that you are not storing any information about the key length or iteration count on the hash, meaning you will never be able to "adapt" your encryption operation to keep pace with hardware changes.  You are going to be stuck with 1000 iteration computational work factor for passwords in this application until you make code changes to increase the computation time.

If possible for your implementation, I would consider adding algorithmic information (including work factor info) to your result hash such that you can adaptively change your application configuration at some point in the future without having to change code.  Say for example you decided to increase the iterations from 1000 to 10,000.  At the point of password verification, you could catch cases with outdated encryption modes and proactively regenerate the password hash to meet your new standard (of course only for cases where the password verification is successful).

Does your getPasswordSalt() method really need to be public? Is there context in which you are expecting callers to invoke this method outside of password verification?

I don't understand the need for exception being thrown by getPasswordSalt() if you are basically just swallowing it anyway in verifyHashedPassword().  I really like the idea of logging errors on expected behavior, but I would question making whether throwing/catching here is proper pattern.

I also question having an early return upon hash string validation failure. Though early exits such as this are typically a good idea, in this specific case you are potentially leaking information about the password hash (that it is invalid) to an attack who is trying to exploit the system internally.

Consider logging the unexpected input like you are now doing, but then just creating a new hash for the input password anyway even though you are going to send a false result. This way, you ensure that you always spend hash computation time during this verification step.

It would seem that the ASP equivalent does not allow caller to pass the salt.  Do you really want to allow your caller to send in an arbitrary salt to hashPassword()? Should you move the main hash generation logic into a protected/private function that can be used from inside the class, with the public interface only allowing passing of password?

For example:

public function hashPassword(string $password) : string
{
    return $this->generateHash($password);
}

private function generateHash(string $password, string $salt = null) : string
{
    // your current hashPassword() logic here
}

Should your hash string validations around first byte and overall length live on verifyHashedPassword() method instead of getPasswordSalt()? I don't know why a potentially private method like getPasswordSalt() should have validation within it. Perhaps these could even be encapsulated into their own private validateHash() method.

This would also remove the odd exception throwing/swallowing pattern mentioned before.  So you could have something like this in the verification method:

public function verifyHashedPassword(string $hashedPassword, string $password) : bool
{
    $result = $this->validateHash($hashedPassword);
    if($result === false) {
          // let's kill some time
          $this->generateHash($password);
          return false;
    }
    $salt = $this->getPasswordSalt($hashedPassword);
    $actualHashedPassword = $this->generateHash($password, $salt);
    return ($actualHashedPassword === $hashedPassword);
}

private function validateHash(string $hash) : boolean
{
    // perform validation
    // log errors if necessary
    // return boolean result
}

Even if you choose to keep getPasswordSalt() as public method, you could still reference common validation function like:

public function getPasswordSalt(string $hashedPassword) : string
{
    $result = $this->validateHash($hashedPassword);
    // early exit for validation failure
    // rest of method logic for valid hash
}

Should this be a concrete class at all?  These seem like they should be static methods. There is nothing that you are doing here that would seem to necessitate a concrete instantiation.

If you are going to use doc blocks (a good thing) you should use them uniformly across your code, not just certain methods.


Reduce nesting

If you invert the condition if len(list) > 1: near the beginning and use an early return,
you can reduce the level of nesting, making the code slightly easier to read:

if len(list) <= 1:
    return list

middle = len(list) // 2
left_sorted = mergeSort(list[:middle])
right_sorted = mergeSort(list[middle:])
# ...

Eliminate k

The variable k is unnecessary, as it will never reach len(list). You can delete it and all its uses.

Style

The implementation doesn't follow recommended conventions of naming and formatting. I suggest to read and follow PEP8.

The good

It's really great that you included unit tests,
it made the review easier :-)


Methods for this already exist, particularly because of the weird properties of NaNs. One of them can be found in the math library, math.isnan and numpy already has a method implemented for this as well, numpy.isnan. They both deal with all three kinds of NaNs shown in your code (but the numpy version is vectorized):

import math
import numpy as np

list(map(math.isnan, [float("nan"), math.nan, np.nan]))
# [True, True, True]

np.isnan([float("nan"), math.nan, np.nan])
# array([ True,  True,  True])

If you are using pandas, pandas.isna is also interesting because it considers None and pandas.NaT (Not a Time) as missing values as well:

import pandas as pd

pd.isna([float("nan"), math.nan, np.nan, None, pd.NaT])
# array([ True,  True,  True,  True,  True])

Your code has a potential flaw, it does not return True only for NaNs (although it does return True for all NaNs), but for all objects which are not equal to themselves. In particular, it will think any instance of this class is NaN (probably true, but not necessarily):

class A:
    def __equal__(self, other):
        return False


Can my string to instance construction be improved?

I'd compact the main loop as such:

        for (var i = 0; i < tableDict.Count; i++)
        {
            var kvp = tableDict.ElementAt(i);
            var s = kvp.Key;

            // Key is "( something )" - entry is constructor
            if (brackets.IsMatch(s))
            {
                var constructor = s.WhitespaceRemoved();

                constructor = constructor.Substring(1, constructor.Length - 2); // Remove brackets

                var argsAsStrings = constructor.Split(',');
                var args = argsAsStrings.Select(num => (object)int.Parse(num)).ToArray();

                // I have only implemented this for the Color class.
                // I assume the constructor is comprised of ints.
                list.Add(new RawChanceTableEntry<T>(
                    (T)Activator.CreateInstance(typeof(T), args),
                    Convert.ToDouble(kvp.Value)));
            }
            else
            {
                // Parse string as a property of T instead
                var type = typeof(T);

                list.Add(new RawChanceTableEntry<T>(
                    (T)type.GetProperty(s).GetValue(Activator.CreateInstance(type), null),
                    Convert.ToDouble(kvp.Value)));
            }
        }

I also create a specific RegEx for the bracket matching that should be faster as it's compiled at the class level:

    private static readonly Regex brackets = new Regex(@"\(([^\)]+)\)", RegexOptions.Compiled);


Splitting C string without modifying input

token_add()

do not change the struct members before you know that your call will succeed, otherwise you'll end up with inconsistent state (e.g. you're overwriting tokens->array if realloc fails). That means keep the increment of count and the assignment of array until the end of the function.
Note that strdup is not a C standard function.

split_string()

you're creating a temporary copy in the local variables token. If you'd pass the pointer and the length to token_add and you could safe the program a string copy.
there is no need to have delimpos in string_split being const. Same goes for the parameter count and charcount. As a rule of thumb, dont use const for integer types, booleans and floating points.
Note: your comment in test.c states that values less than 0 mean unlimited matching, but your code doesn't contribute to that statement. If you have enough matches you'll eventually increment delimcount to match -1.
Separate the increment of delimcount from the comparison with count. Some will ask himself if this is correct and right now, I couldn't tell ;-)
Why don't you use tokens->count?
If a call to tokens_add failes, you're returning NULL from split_string without freeing the Tokens struct allocated before, leaking its memory.

misc

Provide more test cases. One test case for handling unlimited matching, one for restricted matching, one for empty delimiters. Best is to write down what your API supports and then add a test for every special case.

For instance, if I test the following:

    struct Tokens *tokens = string_split("Hello;world;!;", ";", 2);

    assert(tokens->count == 2);
    assert(strcmp("Hello", tokens->array[0]) == 0);
    assert(strcmp("world!", tokens->array[1]) == 0);

I receive: test: test.c:22: test_2: Assertion 'tokens->count == 2' failed.

you don't need the include in tokens.h, it's sufficient if you add it to tokens.c


C: QuickSort following the book "Schaum's Outlines"

You've implemented your own stack. C has a perfectly good stack, so don't make your own. Use recursive functions.

"Scan" means to look for something, but you modify the list while scanning. Its not a good name for the function

"GetFinalPosition" begins with Get which usually indicates the the function doesn't modify anything.


Dos and donts

Don't use using namespace std. It's fine for very small programs, but std:: immediately tells someone that you're using a standard function and not some self-written sort.

Use all #include's necessary. std::sort is defined in <algorithm>. It seems like your C++ distribution includes <algorithm> or stl_algo in one of the other headers. That's not portable.

Use proper names. anagram doesn't tell anything about the function. Does it create an anagram? Does it check whether something is an anagram of something else? are_anagrams or something similar is less ambiguous.

The issue of \$\mathcal O(1) \$

You cannot get \$\mathcal O(1)\$ for this. You have to view each letter in each word at least once, therefore ending up with \$\mathcal O(n+m)\$ if one.size() \$\mathcal O(n)\$ and two.size() is \$\mathcal O(m)\$. However, since one.size() == two.size() \$n = m\$, otherwise we can find an answer in \$\mathcal O(1) \$.

Regardless, you can solve this in \$\mathcal O(1)\$ additional memory, if you use std::array<int, 128> or another fixed/variable size \$O(1)\$ indexable container:

typedef std::array<int, 256> character_count_type;

bool is_anagram(const std::string & one, const std::string & two)
{
    if(one.size() != two.size())
    {
        return false;
    }
    character_count_type character_count_one;
    character_count_type character_count_two;

    for(std::size_t i = 0; i < one.size(); ++i){
        assert(0 <= one[i] && one[i] < 256);
        assert(0 <= two[i] && two[i] < 256);
        character_count_one[one[i]]++;
        character_count_two[two[i]]++;
    }
    return character_count_one == character_count_two;
}

This has \$\mathcal O(n)\$ worst time complexity, and due to the constant size of std::array<...> \$\mathcal O(1)\$ additional space.


Creating a custom validator class for each field in each class could potentially lead to bloated code, while you will not get much out of this.

Your model does not support user feedback. All it does is generate exceptions, and Exceptions are not suitable for representing error messages which are displayed to the user. You can catch these exceptions and display the messages to user, but you would abuse the exception mechanism that way. The rule is - never display exception content to users. It's a potential security hole.

Your model supports only a detection of the first error - an exception is thrown, and no further analysis can run. This way you can't provide a complete report of what's invalid in the model.

Initialization of static rule objects in model constructor is suboptimal - you are creating lots of these objects any time a constructor called. Simply making these static would optimize memory usage.

I would suggest returning a custom result object containing the status of the operation and a collection of rule violations from a 'Save' method, instead of throwing and catching exceptions. This way you would not abuse the exception handling mechanism with logic that is not exceptional - for example having an incorrectly entered string field is a normal situation, not an exception.

UPDATE (based on comment):
As for the displaying exception contents to UI, a better approach would be separate save and validate operation, and use validation result to change UI state, so the Save operation is not allowed in the first place when model is not valid. For example, you could disable the save button. Then you don't need to handle validation exception in Save method. I strongly encourage you to reconsider the practice of displaying exception contents to user. Let me reiterate - non-valid user input should be considered as normal program flow, not en exceptional situation.
Consider the following:
Is it a vulnerability to display exception messages in an error page?

So i would recommend the following workflow:
When initializing a form, update the ui based on validation result.
Handle every change to the model in the ui:
If model is not valid based on current user input - update UI with validation result, such as a Save button, display validation summary as text to the user, highlight form controls containing invalid values and so on.
If model is valid for particular operation - enable the UI controls which allow this operation (the 'Save' button), and clean validation summary and the highlights from user screen.
When Save button is pressed, you already sure that the model is valid, you don't need a check, because you have already sure you enabled it because of successful validation result, and it would be disabled on failed validation result.


Smoothen page transition for mobile devices

It sounds like the issue isn't really the code, just the performance of the hardware: A mobile device just can't redraw everything as fast as a desktop browser. Writing stuff in single lines does not increase performance!

However, you could try the hardware acceleration "hack" shown and explained here.

You should also consider using CSS transforms to do the actual animation, rather than jQuery's position: absolute trickery. All modern browsers (with the exception of Opera Mobile) support it, and such transforms are always hardware accelerated.

Lastly, since this is Code Review, I'd advice you to get rid of the repetition in your code:

var PAGE_SWAP_DURATION = 600; // define this once

function swapPage(outgoingPage, incomingPage, type) {
  var outDirection = type === "prev" ? "right" : "left",
      inDirection  = type === "prev" ? "left" : "right";

  outgoingPage.hide('drop', { direction: outDirection }, PAGE_SWAP_DURATION, function () {
    incomingPage.show('drop', { direction: inDirection }, PAGE_SWAP_DURATION, function () {
      // wait for the animation to finish; this is a complex selector
      // so it may cause the browser to stutter
      incomingPage.find("input:text:visible:not([readonly]):first").focus();
    });
  });
}

Apropos that selector: If possible, it would be better to find the correct input ahead of time, rather than run and re-run such a complex query on each page swap.

For instance, you could map out what inputs belong to what pages when the site first loads, and link them to their respective pages with .data(). Or you could give the inputs IDs or class names, which will make the selector much simpler.


Given an integer n, generate the nth count and say sequence

In each step of the "count-and-say sequence" (which is more usually called the "look-and-say sequence") you have to find the groups of consecutive runs of identical digits. So if you have the value 111221, these groups are 111, 22, and 1. Python has a built-in function itertools.groupby for finding groups in an iterator, and using this function, the look-and-say step becomes:

new_value = ''
for digit, group in groupby(value):
    count = sum(1 for _ in group)
    new_value += str(count) + digit
value = new_value

which can be rearranged into a single expression:

value = ''.join(str(sum(1 for _ in group)) + digit
                for digit, group in groupby(value))

and so the whole sequence can be generated like this:

from itertools import groupby

def look_and_say(value='1'):
    "Generate the look-and-say sequence starting at value."
    while True:
        yield value
        value = ''.join(str(sum(1 for _ in group)) + digit
                        for digit, group in groupby(value))

To select only the \$n\$th value of the sequence, use itertools.islice:

next(islice(look_and_say(), n - 1, None))