Recording a customer's shopping cart as an order 2.0

Maps

(copying my answer from another question):

A HashMap or ConcurrentHashMap (if you require the thread-safety) is preferred over the legacy Hashtable, as mentioned in the Javadoc:

  As of the Java 2 platform v1.2, this class was retrofitted to implement the Map interface, making it a member of the Java Collections Framework. Unlike the new collection implementations, Hashtable is synchronized. If a thread-safe implementation is not needed, it is recommended to use HashMap in place of Hashtable. If a thread-safe highly-concurrent implementation is desired, then it is recommended to use ConcurrentHashMap in place of Hashtable.

Typo?

OrderDetailsPeer.insertOrderDetails(statement, orderId, customer);

Compared to your first version, it seems that shoppingCart should be inserted here instead of customer, unless you have changed your APIs. If so, then shoppingCart is unused in this method...


Finding the number of boxes that fit into a truck using JavaScript (Followup Q)

This is an interesting pattern:

var heightA = boxHeight > 0 ? ((truckHeight / boxHeight) | 0) : 0;

I assume you intend to be using integer division here? Ie, 5/2 | 0 = 2?

Also.. why are you repeatedly declaring different variables with the same values?

var heightA = boxHeight > 0 ? ((truckHeight / boxHeight) | 0) : 0;
var heightB = boxHeight > 0 ? ((truckHeight / boxHeight) | 0) : 0;
var heightC = boxHeight > 0 ? ((truckWidth / boxHeight) | 0) : 0;

Here you are comparing two fundamentally different types:

if (multiplesA > arrayA)
{
boxCount = multiplesA;
}

Comparing different data types in Javascript involves the type coercion system, which in javascript is a Bad Thing -- you're basically putting yourself at the mercy of an extremely unpredictable system. But, beyond that, it's not even clear what your intention with this line is -- how does it make sense to compare a float to an array?


Find out whether number is of Power of Two

I mean, I would use a library to do this. Namely, Math.log2

function isPowerOfTwo(n) {
  return Math.log2(n) % 1 === 0;
}

console.log(isPowerOfTwo(3)); //false
console.log(isPowerOfTwo(4)); //true
console.log(isPowerOfTwo(7)); //false
console.log(isPowerOfTwo(8)); //true
console.log(isPowerOfTwo(-1));//false


Thread safety
std::malloc and std::free are thread-safe by themselves... But Freelist and Cache aren't, unless exclusively accessed through allocate or deallocate.
In all other cases some synchronization is needed in FreeList::push and FreeList::pop (or alternatively, Cache::allocate and Cache::deallocate).

There are some options to make those two classes thread-safe for all access paths:

Move get, get_cache, Cache and FreeList into a class as private nested classes / member functions (so they aren't publicly accessible anymore) and make allocate and deallocate a friend of that class. (private/anonymous namespace won't work since that one has to ve just as accessible as allocate/deallocate because it has to reside in a header.)
Why move get and get_cache? Because references and pointers to thread_local objects can be shared with other threads - so a threads might get access to another threads thread_local Cache inside get.
thread_local objects are only thread-safe if no reference or pointer to them gets shared with other threads (which might happen accidentally, e.g. by a mismanaged lambda capture).
This means allocate and deallocate are not thread-safe as long as references to the underlying Cache (via get or get_cache) could be shared by someone else. And since allocate and deallocate have exactly the same level of access as get or get_cache the posted implementation is not thread-safe in the general case.

Add some locking inside FreeList, or make FreeList lock-free by making this_head a std::atomic<Node*>.
This would make the critical section inside Cache::allocate and Cache::deallocate thread-safe as well.

Memory management

Cache::allocate won't provide correctly aligned memory for alignments greater than std::max_align_t (std::malloc is only specified to support alignments to this value). This might cause problems if higher alignments are needed, e.g. for SSE or AVX instructions.
std::aligned_alloc could be used as a replacement. (Beware: std::aligned_alloc isn't available for MSVC yet.)

It isn't possible to create objects whose size is less than sizeof(void*) - so exchanging int64_t for int32_t inside main will fail to compile on 64-bit systems. This could be fixed by always allocating chunks of memory that are at least sizeof(void*) (or FreeList::NODE_SIZE, if you prefer).

Naming

Cache doesn't actually cache objects - only chunks of memory. FreeListAllocator might be a better name.

get is a very generic name. (get_)thread_local_instance or singleton might be more descriptive.

Similar, get_cache might better be get_allocator or get_thread_local_allocator.

General stuff

With some slight modifications Cache could be changed into a standard library compatible std::pmr::memory_resource - which would allow it to be used with standard containers.

If I had to design this, I'd likely make FreeList an adaptor over another allocator (taken as template parameter) who would be asked for memory if the list was empty. This design would allow easy composition of different allocation strategies. There's an excellent talk by Andrei Alexandrescu about this topic.


Using a bool is_valid results in a deeply nested code. You have 5 levels of nesting, with the core of algorithm being hidden at the deepest one. I recommend an early return: as soon as you determine that the string doesn't pass a criteria, return false; immediately.
Testing for length_s == 0 is redundant. In this case s[0] is '\0', which is neither a digit nor a sign.
Passing std::string as an argument makes a copy. Prefer passing a (constant) reference.
Leaving the point of the exercise aside, the best way to validate a number is to just go ahead and directly call std:stoi with the second parameter, e.g.:

    size_t end;
    int number = std::stoi(s, &end);
    if (s[end] != '\0') {
        // The string was not parsed completely. It is not a number.
    }


Check robustness of function to add an interval to a date

static long secondsSpecial=0;

Static variables that get modified? Rethink your approach.

If you have static variables, there's a good chance that either your design is wrong, or it should be an instance class. Always limit the scope of variables, methods and classes to the smallest one possible. A variable that is not used outside of the class should not be public, a function that only concerns the class it is defined in should not be public, a variable that is only used inside one function should not be declared in the class but in the function itself and so on.

public static void secondsToNotify(long seconds, String d){

What does d do? What is it for? Rename it according to what it role is, or provide thorough documentation on why it only is one letter.

System.out.println(""+dt);

Are you coming from a VB6 background? I wish I could say that the last time I saw someone using the "empty-string-concatenate-cast" was somewhere in the nineties...unfortunately I did not code back then and I work with a VB6 coder...so...

Why is that bad? It's some sort of, well, implicit type casting in the hope that it might work. That the Java compiler allows such thing is still a mystery to me.

Easier readable alternatives:

System.out.println(dt.toString()); // Turns out this does the same in a better way.
System.out.println(dt); // Calls the objects toString() method.

secondsSpecial = secondsInterval*(1+(seconds/secondsInterval));

By now I know that those variables do not have the ideal names they could have.

System.out.println(""+(secondsSpecial));

Same here...are you aware that System.out has an overload of println that accepts long?

System.out.println(secondsSpecial);

long hour = (secondsSpecial /60)/60;

I here for inform you that this static method is not threadsafe...well, that felt funny.

If this static helper method is called from two different threads, it's possible that the first thread will set secondsSpecial, print something and while the first thread prints something the second will come along and also set secondsSpecial.

...
Thread1: Set secondsSpecial to 3
Thread2: Set the time of the calendar
Thread1: Print the value of secondsSpecial
Thread2: Set secondsSpecial to 25634
Thread1: Use secondsSpecial

And that's why static variables that get modified are bad. No one would expect a static helper method to be not threadsafe if not explicitly told about. Or would you think that Arrays.asList() is not threadsafe?

if(hour >= Integer.MAX_VALUE){

}else{

Silently failing is not acceptable, this would be a good moment to throw a IllegalArgumentException with a descriptive message.

intValue =  (int) (long)hour;

hour is already a long.

System.out.println(""+dateSecondsReg);
System.out.println(""+secondsSpecial);

While we're at it, your function should not directly print to stdout. If you want to log something within a function, a Logger would be appropriate.

secondsSpecial = secondsInterval*(1+(seconds/secondsInterval));

  is important for me to get an integer division to drop off the residue.

Please correct me, but isn't that what seconds / 60 does?

Java automatically performs an integer division if it is handed two integers/long. Anyway, this solution would be hacky at best, (int)Math.floor(value) would be better.

All in all, it sounds more like you want to rewrite the function completely and instead only accept a calendar instance which you then add the long seconds to. Like this (pseudo code):

function addSecondsToCalendar(Calendar cal, long seconds) {
    long hours = seconds / 60
    if hours >= Integer.MAX_VALUE throw IllegalArgumentException

    cal.add(hours)
}

Which raises the question what you're doing that you need this functionality. Short comparison:

Integer.MAX_VALUE:  2147483647
In minutes:         35791394.116667
In hours:           596523.23527778
In days:            24855.134803241
In years:           68.096259734906

So if you only use int seconds, you can already schedule notifications (that's what your function does, right?) for the next ~68 years.

If, on the other hand, you use "historic" dates as starting point, then it is understandable that you need a bigger range than ~68 years. Should be mentioned in the JavaDoc of the method, though.


Knowing which way to iterate the for loop C

You have a really complicated example with variables, and a simpler one with literals. The literal one is only going to use one branch. So let's do a simple one with variables. Let's say you want to iterate from a to b, but you don't know which is larger. Well, first of all, unless I'm missing something, if a>b, then you'll want integer -= increment in the second branch, while your code has integer += increment in both. So before your for-loop, define a variable direction equal to the sign of b-a (that is, if b-a >0 then direction = 1, if b-a<0 then direction = -1). Then do:

for(integer = a; (b-integer)*direction > 0; integer += direction*increment)


Pattern for writing a generic string transformation function

Look at Boost.Range.  Your first point drives most of the rest of the concerns.

Write your template function to take a Range.  You can pass it a C string literal, a std::string, an array, vector, or anything —— even a pair of iterators if that’s what you need after all.

Not limited to char?  No problem: make it a Range of T, with a default of char.

This takes the place of your initial idiomatic approach.  Use ranges rather than iterators, and you don’t need to wrap it for convenience.  Boost.Range does all that for you.

The output can remain an output iterator, but I like to make it a range adaptor.

With that, you can do things like:

for (auto c : mystring|escaped) { ⋯


Read contents of file with appropriate error handling (Rust)

Your code gives a warning:

warning: variable does not need to be mutable
  --> src/main.rs:15:12
   |
15 |         Ok(mut f) => f,
   |            ^^^^^
   |

When you move a value from one binding to another, the two bindings don't have to agree on mutability. It may sound strange, but it's valid to move from an immutable binding to a mutable binding. It's perfectly safe because in order to be able to move a value, there must not be any pointers to it, which ensures that you have exclusive access to the value. Therefore, you could write Ok(f) here instead of Ok(mut f).
The match / return Err pattern is so frequent that Rust has a shorthand for it: the ? operator (and its predecessor, the try! macro). We could rewrite your program using the ? operator like this:

use std::fs::File;
use std::io::Read;

fn main() {
    let path = "bar/foo.txt";

    match read(path) {
        Ok(contents) => println!("{}", contents),
        Err(err) => println!("Unable to read '{}': {}", path, err),
    }
}

fn read(file: &str) -> Result<String, std::io::Error> {
    let mut file = File::open(file)?;

    let mut data = String::new();
    file.read_to_string(&mut data)?;
    Ok(data)
}

The second match in read ends the function, so we don't need the ? operator. Instead, we could use map to replace the data in the Ok variant while keeping the Err the same, and then just return the result of map.

fn read(file: &str) -> Result<String, std::io::Error> {
    let mut file = File::open(file)?;

    let mut data = String::new();
    file.read_to_string(&mut data).map(|_| data)
}

Which one you use is up to you. :)
File::open accepts more than just &str. Its signature is:

fn open<P: AsRef<Path>>(path: P) -> Result<File>

You could make your own read function more generic by introducing a type parameter.

use std::path::Path;

fn read<P: AsRef<Path>>(file: P) -> Result<String, std::io::Error> {
    let mut file = File::open(file)?;

    let mut data = String::new();
    file.read_to_string(&mut data)?;
    Ok(data)
}

Look at the list of implementations for AsRef<Path> to see what types you can now pass to your function.


scan activedirectory for all users and their groups in domain with c#

I suspect you'd better off using a DirectorySearcher, but I don't know Active Directory services are supported by .NET Core.

Here is how I did it in .NET Framework (4.7.2).

Classes to hold the data I needed:

public class Account
{
    private Account(string name)
    {
        Name = name;
    }

    public Account(string name, List<DataCombination> groupData)
        : this(name)
    {
        GroupData = groupData;
    }

    public string Name { get; }

    public List<DataCombination> GroupData { get; }
}

public class DataCombination
{
    public string GroupName { get; set; }

    public string Account { get; set; }
}

The code that queries AD:

        var searchResults = new List<SearchResult>();

        using (var directoryEntry = new DirectoryEntry(directoryEntryPath))
        {
            directoryEntry.RefreshCache();

            using (var directorySearcher = new DirectorySearcher(directoryEntry))
            {
                directorySearcher.SearchRoot = directoryEntry;
                directorySearcher.SearchScope = SearchScope.Subtree;
                directorySearcher.PageSize = 1000;
                directorySearcher.Filter = filter;

                directorySearcher.PropertiesToLoad.Clear();
                directorySearcher.PropertiesToLoad.Add(PropertyName.Name);
                directorySearcher.PropertiesToLoad.Add(PropertyName.MemberOf);

                searchResults.AddRange(directorySearcher.FindAll().Cast<SearchResult>());
            }
        }

        var accounts = searchResults
            .Select(searchResult => _accountFactory.Execute(searchResult.Properties))
            .OrderBy(x => x.Name)
            .ToList();

        return accounts;

directoryEntryPath is an LDAP URI, starts with "LDAP://".
filter is used to filter using a list of user names and is filled by this method:

public static string Execute(IEnumerable<string> userNames)
{
    var filter = new StringBuilder();
    filter.Append("(&(objectClass=user)(|");

    foreach (var userName in userNames)
    {
        filter.Append($"(sAMAccountName={userName})");
    }

    filter.Append("))");

    return filter.ToString();
}

PropertyName is a class containing const strings:

internal static class PropertyName
{
    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms675090.aspx
    public const string Name = "name";
    public const string LockoutTime = "lockoutTime";
    public const string UserAccountControl = "userAccountControl";
    public const string MemberOf = "memberOf";
    public const string DisplayName = "displayName";
}

This is the _accountFactory which converts the data returned by the DirectorySearcher into my classes:

internal class GroupAccountFactory : BaseDirectorySearcher, IAccountFactory
{
    public Account Execute(ResultPropertyCollection properties)
    {
        var accountName = GetValue<string>(properties, PropertyName.Name);

        var groupData = GetGroupData(properties, accountName);

        return new Account(accountName, groupData);
    }

    private List<DataCombination> GetGroupData(ResultPropertyCollection properties, string accountName)
    {
        var groupNames = new List<string>();

        foreach (var propertyValue in properties[PropertyName.MemberOf].Cast<string>())
        {
            groupNames.AddRange(propertyValue
                .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(part => part.Split('='))
                .Select(x => new
                {
                    Key = x[0],
                    Value = x[1],
                })
                .Where(x => x.Key == LdapDirectory.CommonName)
                .Select(x => x.Value));
        }

        return DataCombinationCollectionCreator.Execute(new HashSet<string>(groupNames), accountName);
    }
}

Its base class:

internal abstract class BaseDirectorySearcher
{
    protected T GetValue<T>(ResultPropertyCollection properties, string propertyName)
    {
        var value = PropertyValueRetriever.GetObject(properties, propertyName);
        if (value == null)
        {
            return default(T);
        }

        return (T)value;
    }
}

And that one uses:

internal class PropertyValueRetriever
{
    public static string GetString(ResultPropertyCollection properties, string propertyName)
    {
        var value = GetObject(properties, propertyName);

        return (string)value;
    }

    public static object GetObject(ResultPropertyCollection properties, string propertyName)
    {
        if (properties.Contains(propertyName)
            && properties[propertyName].Count > 0)
        {
            return properties[propertyName][0];
        }

        return null;
    }
}

You might have noticed this class:

internal class LdapDirectory
{
    public const string CommonName = "CN";
    public const string OrganizationalUnit = "OU";
    public const string DomainComponent = "DC";
}

And finally:

internal class DataCombinationCollectionCreator
{
    public static List<DataCombination> Execute(ICollection<string> groupNames, string accountName)
    {
        var groupData = new List<DataCombination>();

        foreach (var groupName in groupNames)
        {
            groupData.Add(CreateDataCombination(groupName, accountName));
        }

        return groupData;
    }

    private static DataCombination CreateDataCombination(string groupName, string accountName)
    {
        return new DataCombination
        {
            GroupName = groupName,
            Account = accountName
        };
    }
}

(Note that I have stripped away some of the extra logic that is present in my code which only applies for my purposes; thus the whole use of DataCombinationCollectionCreator might be overkill for you.)

It's all fairly self-explanatory. Whether it performs better than your code, I don't know: AD operations can be notoriously slow.


Detecting arithmetic overflow in C with NASM

Wrong flag
I believe you should be looking at the overflow flag instead of the carry flag, since all of your operands are signed values.  On x86, the overflow flag is set if signed addition overflows.  The carry flag is set if unsigned addition overflows.
Not reliable
As @Edward pointed out, it doesn't seem reliable to use this kind of function because you never know how the compiler is going to rearrange your code.  Even without the compiler rearranging your code, the results could be confusing.  From your own example:
ret = a + a + b;
overflow = read_overflow_flag();

Here, you are only detecting overflow over the second of the two additions.  If the first addition overflowed but the second didn't, you wouldn't catch it.  In other words, the assembly might look like this:
add %ecx, %edx, %edx  // ret = a + a  <- overflow not detected here
add %ecx, %ecx, %ebx  // ret = ret + b
seto %al              // overflow = overflow flag

To do it correctly, I would suggest you use a function that adds two numbers together and updates a cumulative overflow:
// If the add overflows, 1 will be added to *pOverflow.
int32_t add32_with_overflow(int32_t x, int32_t y, int *pOverflow);

int32_t ret      = 0;
int     overflow = 0;

ret = add32_with_overflow(a,   a, &overflow);
ret = add32_with_overflow(ret, b, &overflow);
printf("Overflow = %d\n", overflow);


Eliminating some unnecessary code

Some programmers find break statements to be problematic. If you'd like to know more, here is a programmers stack exchange question about breaks and continues.

You could easily eliminate your use of break by just changing the inner loop to the following:

for (var j = i - 1; j >= 0 && array[j] > currentItem; j--) {
  array[j + 1] = array[j];
}

This shortens your code a bit and condenses all the control flow logic of you loop into one spot.

You could shorten your code even further by eliminating the conditional j >= 0:

for (var j = i - 1; array[j] > currentItem; j--) {
  array[j + 1] = array[j];
}

However, this might obfuscate the code a bit.

Note: This works because array[-1] will return undefined and undefined > myVar will always evaluate to false - ECMAScript Standard


Word break problem with recursion and memorization

bug

def wordBreak(self, s, wordDict):
    wordDict = set(wordDict)
    str_map = dict()
    if not s or not wordDict: return False

    def check(s):
        if s in str_map: return str_map[s]
        if s in wordDict:
            str_map[s] = True
            return True
        for i, c in enumerate(s[1:], 1):
            if s[:i] in set(wordDict) and check(s[i:]):
                str_map[s[:i]] = True
                return True  # <== you forgot this one
        str_map[s] = False
        return False

    return check(s)

passes all cases in 48ms

set(wordDict)

No need to do this in each iteration if you do that at the start of the algorithm

c

this variable is not used. Python convention uses _ for variables that are not used

reinventing the wheel (cache)

Python is batteries included

so you can as easily use functools.lru_cache instead of implementing your own cache:

from functools import lru_cache

def wordBreak(self, s, wordDict):
    wordDict = set(wordDict)
    if not s or not wordDict: return False
    @lru_cache(None)
    def check(s):
        if s in wordDict:
            return True
        for i, _ in enumerate(s[1:], 1):
            if s[:i] in wordDict and check(s[i:]):
                return True
        return False
    return check(s)

passes in 36ms

alternative version

instead of running over the string, you can also try to build a graph of all occurrences of the words in wordDict, and then look if you can find a path from 0 to len(s)

all chars in wordDict

you can check whether all chars in s appear in a word in wordDict

def validate_all_chars(text, words):
    all_chars = set()
    for word in words:
        all_chars.update(word)
    return all_chars.issuperset(text)

or with itertools.chain:

from itertools import chain
def validate_all_chars(text, words):
    all_chars = set(chain.from_iterable(words))
    return all_chars.issuperset(text)

occurrences:

Unfortunately, re.finditer and re.findall only give non-overlapping occurrences, so we can't use them here. So we'll have to build our own finder:

def find_occurrences(pattern: str, text: str):
    idx = 0
    while True:
        idx = text.find(pattern, idx)
        if idx == -1:
            return
        yield idx, idx + len(pattern)
        idx += 1

build a graph

from collections import defaultdict
def build_span_graph(text, words):
    all_spans = defaultdict(set)
    spans = (find_occurrences(word, text) for word in words)
    for span in spans:
        for begin, end in span:
            all_spans[begin].add(end)
    return all_spans

walk the graph:

def find_path(spans, length, begin=0, visited=None):
    visited = set() if visited is None else visited
    visited.add(begin)
    ends = spans[begin]
    return length in ends or any(
        find_path(spans, length=length, begin=new_begin, visited=visited)
        for new_begin in ends
        if new_begin not in visited and new_begin in spans
    )

Here you can try to optimize a bit by first visiting the furthest ends, but that is only marginally useful

main:

def wordBreak(s: "str", wordDict: "List[str]") -> "bool":
    if not validate_all_chars(s, wordDict):
        return False

    spans = build_span_graph(s, wordDict)

    return find_path(s, wordDict)


Style

There is an official standard Python style guide called PEP 8. This is highly recommended reading. It gives guidelines to help writing code that is both readable and consistent. The Python community tries to follow these guidelines, more or less strictly (a key aspect of PEP 8 is that it provides guidelines and not strict rules to follow blindly).

It deals with various aspects of the code style: naming conventions, indentation convention, etc.

You'll find various tools to try to check whether your code is PEP 8 compliant and if is it not, to try and fix this:

pycodestyle package (formerly known as pep8) to check you code
pep8online to check your code with an online tool
autopep8 package to fix your code automatically
Also, this is also checked by various linters: pylint, pyflakes, flake8, etc.

In your case, the major point is that indentation should be 4 space. Also, you should not have trailing whitespaces.

Modules

Splitting the code into small modules can be a good idea. However, I find page_01 to be a pretty weird name. Also, the way the code is splitted in different modules does not seem to be perfect to me. The way you use storage suggests that is should probably be a data structure (a class?).

For the time being, let's move everything back to a single file:

health = 100
wealth = 10

def instructions():
    print("You can move N, S, E or W.")

def ask_player_for_move():
    react = input("\nWhat is your next move?")
    player_move(react)

def player_update():
    print("\nYour health is now: " + str(health))
    print("You now have " + str(wealth) + " coins.\n")

def player_move(action):
    if action == "N":
        print("You stepped on a bear trap.")
        health -= 10
        player_update()
        ask_player_for_move()
    elif action == "S":
        print("You tripped over a pengiun!")
        print("But, you found a small bag of 15 coins.")
        health -= 3
        wealth += 15
        player_update()
        ask_player_for_move()
    elif action == "E":
        print("Err...I wouldn't go that way if I were you!")
        ask_player_for_move()
    elif action == "W":
        print("You ride off into the sunset")
        player_update()
    else:
        print("That is not a valid entry.")
        ask_player_for_move()

instructions()
print("You have " + str(health) + " health points and " + str(wealth) + " coins.")

action = input("What do you want to do now?")
player_move(action)

Functions

player_update does not update the player, maybe print_player would be more relevant.

Similarly, I'd expect ask_player_for_move to be a function returning the move asked to the user.

In both cases, it seems like the functions could be used in the "main" part instead of duplicating the code.

health = 100
wealth = 10

def show_intructions():
    print("You can move N, S, E or W.")

def ask_player_for_move():
    react = input("\nWhat is your next move?")
    player_move(react)

def print_player():
    print("\nYour health is now: " + str(health))
    print("You now have " + str(wealth) + " coins.\n")

def player_move(action):
    global health
    global wealth
    if action == "N":
        print("You stepped on a bear trap.")
        health -= 10
        print_player()
        ask_player_for_move()
    elif action == "S":
        print("You tripped over a pengiun!")
        print("But, you found a small bag of 15 coins.")
        health -= 3
        wealth += 15
        print_player()
        ask_player_for_move()
    elif action == "E":
        print("Err...I wouldn't go that way if I were you!")
        ask_player_for_move()
    elif action == "W":
        print("You ride off into the sunset")
        print_player()
    else:
        print("That is not a valid entry.")
        ask_player_for_move()

show_intructions()
print_player()
ask_player_for_move()

Hidden recursion

Your game loop relies on a hidden recursion: player_move calls ask_player_for_move which calls player_move. This makes things heard to follow but also will add another level of function calls in the stack. This can be an issue if you need a backtrace because you'll get something like:

  File "new_main.py", line 37, in player_move
    ask_player_for_move()
  File "new_main.py", line 12, in ask_player_for_move
    player_move(react)
  File "new_main.py", line 37, in player_move
    ask_player_for_move()
  File "new_main.py", line 12, in ask_player_for_move
    player_move(react)
  File "new_main.py", line 37, in player_move
    ask_player_for_move()
  File "new_main.py", line 12, in ask_player_for_move
    player_move(react)
  File "new_main.py", line 37, in player_move
    ask_player_for_move()
  File "new_main.py", line 12, in ask_player_for_move
    player_move(react)
  File "new_main.py", line 37, in player_move
    ask_player_for_move()
  File "new_main.py", line 12, in ask_player_for_move
    player_move(react)
  File "new_main.py", line 37, in player_move
    ask_player_for_move()
  File "new_main.py", line 12, in ask_player_for_move
    player_move(react)
  File "new_main.py", line 43, in player_move
    ask_player_for_move()
  File "new_main.py", line 12, in ask_player_for_move
    player_move(react)
  File "new_main.py", line 43, in player_move
    ask_player_for_move()
  File "new_main.py", line 11, in ask_player_for_move
    react = input("\nWhat is your next move?")
KeyboardInterrupt

but the other issue is that you could end up reaching the recursion limit.

You could write something like:

health = 100
wealth = 10
finished = False

def show_intructions():
    print("You can move N, S, E or W.")

def ask_player_for_move():
    return input("\nWhat is your next move?")

def print_player():
    print("\nYour health is now: " + str(health))
    print("You now have " + str(wealth) + " coins.\n")

def player_move(action):
    global health
    global wealth
    global finished
    if action == "N":
        print("You stepped on a bear trap.")
        health -= 10
        print_player()
    elif action == "S":
        print("You tripped over a pengiun!")
        print("But, you found a small bag of 15 coins.")
        health -= 3
        wealth += 15
        print_player()
    elif action == "E":
        print("Err...I wouldn't go that way if I were you!")
    elif action == "W":
        print("You ride off into the sunset")
        print_player()
        finished = True
    else:
        print("That is not a valid entry.")

def game():
    global finished
    show_intructions()
    print_player()
    while not finished:
        action = ask_player_for_move()
        player_move(action)

game()

Then you could move the call of game() behind an if __name__ == "__main__": guard.


Get the difference between two dates, in the most convenient unit

Use getTime instead of the UTC transformation it'll return the timeStamp.

So your diff would be:

b.getTime() - a.getTime()

This will give you the milliseconds if you want the seconds you would divide it by 1000 so you would get:

var secondsDiff = (b.getTIme() - a.getTime())/1000

Then for the return

if (secondsDiff > 86400)  {
 return Math.floor(secondsDiff/86400) + ' D'
}
if (secondsDiff > 3600)  {
 return Math.floor(secondsDiff/3600) + ' h'
}
if (secondsDiff > 60)  {
 return Math.floor(secondsDiff/60) + ' min'
}
if (secondsDiff > 0) {
 return secondsDiff + ' sec'
}


Is there a better way to update fields in an web app?

How about _.pick()?

Posts.update = function(req, res){
    _.extend(req.post, _.pick(req.body, 'title', 'author', 'body'));
    post.save();
};


Functionally retrieving rows from a database in Scala

Of course this is not purely functional, although it represents an improvement. What would a purely functional solution look like?

trait Sql[A] { self =>
  def unsafePerformIO(ds: javax.sql.DataSource): A = unsafePerformIO(ds.createConnection)

  def unsafePerformIO(conn: java.sql.Connection): A //abstract

  def map(f: A => B): Sql[B] = new Sql[B] {
    def unsafePerformIO(conn: Connection) = f(self.unsafePerformIO(conn))
  }
  def flatMap(f: A => Sql[B]): Sql[B] = new Sql[B] {
    def unsafePerformIO(conn: Connection)
      = f(self.unsafePerformIO(conn)).unsafePerformIO(conn)
  }

}

I imagine you might say "huh?" at this point. Let me introduce the companion:

object Sql {
  def apply[A](comp: Connection => A) = new Sql[A] {
    def unsafePerformIO(conn: Connection) = comp(conn)
  }
}

The idea (of course) is that you delay side-effects until the end of the world, encapsulating the values returned by the database in a type that represents value returned from DB call, in the same way Option represents value which may not exist.

The usage becomes something like this:

Sql { conn => process( conn.prepareStatement.executeQuery ) }

Where the process method might look like your code (above) perhaps.

I imagine this may raise a few questions:

What the? Huh? I mean, what the?

Well, it allows you to do something like this:

def getStuff1: Sql[Int]
def getStuff2: Sql[Int]
def useStuff(i: Int): Sql[String]

Then you can compose using for-comprehensions

val result =
  for {
    i <- getStuff1
    j <- getStuff2
    s <- useStuff(i + j)
  }
  yield s

What is the type of this expression? Well, it's an Sql[String] of course! To get hold of the String:

result.unsafePerformIO(myDataSource)

This creates a single connection which is then threaded through the computation.

What is missing? Well, resource management (i.e. cleaning up the connections of course). I understand this will all be available in scalaz7


So I recast your code to make it a bit more pythonic. For reference, all of the code is at the bottom of this post. I played around a bit looking for some performance improvements, but found nothing significant.

Some notes:

Pep8:

First thing to do is get a style/lint checker.  I use the pycharm ide which will show you style and compile issues right in the editor.  When you get a chance you should also read through pep8 which is the official python style guide.

Native Types:

I changed all of the +/-1 to True/False

Bug at a boundary:

The sieve_list list was one element too short.  I discovered this with a quick sanity test of:

print atkin_sieve(28)
print atkin_sieve(29)
print atkin_sieve(30)

Use python iterators:

This:

i = r*r
while i < limit:
    sieve_list[i] = -1
    i += r*r

became:

for n in range(r_squared, len(sieve_list), r_squared):
    sieve_list[n] = False

And this:

results = []
x = 0
for p in sieve_list:
    if p > 0:
        results.append(x)
    x += 1
return results

became:

return [x for x, p in enumerate(sieve_list) if p]

Code:

def atkin_sieve(limit):
    assert limit > 3
    sieve_list = [False] * (limit + 1)
    sieve_list[2:4] = (True, True)

    # Part I: preliminary work
    x = x_squared = 1
    while x_squared < limit:
        y = y_squared = 1
        while y_squared < limit:
            n = 4 * x_squared + y_squared
            if n <= limit and n % 12 in (1, 5):
                sieve_list[n] = not sieve_list[n]

            n = 3 * x_squared + y_squared
            if n <= limit and n % 12 == 7:
                sieve_list[n] = not sieve_list[n]

            if x > y:
                n = 3 * x_squared - y_squared
                if n <= limit and n % 12 == 11:
                    sieve_list[n] = not sieve_list[n]
            y += 1
            y_squared = y * y
        x += 1
        x_squared = x * x

    # Part II: Remove the squares of primes (and their multiples)
    r = 5
    r_squared = r * r
    while r_squared < limit:
        if sieve_list[r]:
            for n in range(r_squared, len(sieve_list), r_squared):
                sieve_list[n] = False
        r += 1
        r_squared = r * r

    # Part III: Append everything into a list
    return [x for x, p in enumerate(sieve_list) if p]


I reduced the script in this way:

The script length (in lines): was 49, now 27
The jQuery lookups: was 18, now 7
The sub-function amount: was 2, now 0

There is still 2 change handlers.

The main changes:

I used classes... You were using any, except for custom-select that was not used here, in fact.
And I used CSS for the onload hiding of countries sub-division selects.

The lookups are made onload, in the const declarations, for all needed elements. Why only store the selector's string when the jQuery object can be stored?

You had the named function hideCountryOptions() to call 3 times the .hide() method on "similar" elements... I gave them the same countryPossible class to hide them in one shot.

The selectSPR(country) named function was replaced by spr.val(this.value); on change of countrySubDiv, which is the lookup made to target all the country sub-division's user inputs. No need for a switch()! Clearly, only the select that is visible can change, so this.value is the one to put into #spr.

const country = $("#country");
const countryPossibilities = $(".countryPossible");
const countrySubDiv = $(".countryPossible select, .countryPossible input");
const usa = $("#usa");
const canada = $("#canada");
const otherCountry = $("#otherCountry");
const spr = $("#spr");

country.on("change", function() {
  countryPossibilities.hide();
  switch (this.value) {
    case "UNITED STATES":
      usa.show();
      break;
    case "CANADA":
      canada.show();
      break;
    default:
      otherCountry.show();
  }
  countrySubDiv.val("");
  spr.val("");
});

countrySubDiv.on("change",function(){
  spr.val(this.value);
});
.countryPossible{
  display: none;
}

  *Country
  <select name="country" id="country" required>
    <option value="">CHOOSE…</option>
    <option value="UNITED STATES">UNITED STATES</option>
    <option value="CANADA">CANADA</option>
    <option value="AFGHANISTAN">AFGHANISTAN</option>
  </select>

  *State
  <select name="state">
    <option value="">CHOOSE...</option>
    <option value="ALABAMA">ALABAMA</option>
    <option value="ALASKA">ALASKA</option>
  </select>

  *Province
  <select name="province">
    <option value="">CHOOSE...</option>
    <option value="ALBERTA">ALBERTA</option>
    <option value="BRITISH COLUMBIA">BRITISH COLUMBIA</option>
  </select>

  *Region
  <input type="text" name="region" placeholder="Region">

  <input type="text" name="spr" id="spr">


There are some big holes in your security

Authenticate the data source. (Is it a legitimate source, username/password/etc)
Sanitize the user data.

Check $trackCols against a list of valid column names you are expecting, to stop me doing things like I have below.

$valid_cols = array('id', 'user', 'name');
foreach ($trackCols as $col) {
    if (!in_array($col, $valid_cols)) {
        die("Alert! Unexpected Column $col");
    }
}

PDO allows you to bind variables to the statement, and it will escape any dangerous data.
This will help stop people from creating attacks as I have below.

$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();

I have included a test script below (DO NOT RUN AGAINST YOUR LIVE DATABASE)

I have manufactured some bad json data so that it will execute a delete statement on the tracker table in your database.

Obviously it won't work unless I get the table and column names correct, but as your code is now, if I try a dummy column name it will give me back an sql error message, which can help me to narrow it down.

Log the error message instead of returning them. This is an API, all the client end needs to know is that it failed. Don't give the attacker any more information then necessary.

<?php

// WARNING MAKE SURE YOU ONLY RUN THIS AGAINST A TEST DATABASE

$bad_sql = 'id) VALUES (1); DELETE FROM tracker; INSERT INTO tracker(id';
$json = json_encode(array(array($bad_sql => '99999')));

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,            "http://yourdomain/api.php" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST,           1 );
curl_setopt($ch, CURLOPT_POSTFIELDS,     $json);
curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: application/json'));

$result=curl_exec ($ch);

var_dump($result);


Listing sessions within folders in API results

There's no reason to check if there are any items in a collection before iterating over it.  If there are no items, iterating over it won't do anything.  So that alone removes half of the indentation, which makes the code fairly manageable.

parentFolderResponse = GetFolders(parentFolder, sessionMgr, SessionManagementAuth, pagination);

foreach (Folder folder in parentFolderResponse.Results)
{
    Console.WriteLine("\n + Class Of =  " + folder.Name);

    ListFoldersResponse childFolderResponse = GetFolders(folder.Id, sessionMgr, SessionManagementAuth, pagination);
    foreach (Folder childFolder in childFolderResponse.Results)
    {
        Console.WriteLine("\n \t Course Name =  " + childFolder.Name);
        ListSessionsResponse courseSessionResponse = GetPresentations(sessionMgr, SessionManagementAuth, pagination, childFolder.Id);

        foreach (Session session in courseSessionResponse.Results)
        {
            Console.WriteLine("n \t \t Session Name = " + session.Name);
        }
        if (courseSessionResponse.Results.Length == 0)
        {
            Console.WriteLine("\n No sessions found!");
        }
    }
    if (childFolderResponse.Results.Length == 0)
    {
        Console.WriteLine("\n No course folder(s) found!");
    }
}
if (parentFolderResponse.Results.Length == 0)
{
    Console.WriteLine("\n No class of folder(s) found!");
}

You could also consider breaking the code up into several methods, to cover each of the logical objects being printed, rather than doing the whole thing all together.  This is more useful if you're doing more stuff at each level, rather than just a conditional and unconditional console write at each tier, but it helps remove indenting, and is more useful the more tiers there are:

parentFolderResponse = GetFolders(parentFolder, sessionMgr, SessionManagementAuth, pagination);

foreach (Folder folder in parentFolderResponse.Results)
{
    PrintClass(folder);
}
if (parentFolderResponse.Results.Length == 0)
{
    Console.WriteLine("\n No class of folder(s) found!");
}

void PrintClass(Folder folder)
{
    Console.WriteLine("\n + Class Of =  " + folder.Name);

    ListFoldersResponse childFolderResponse = GetFolders(folder.Id, sessionMgr, SessionManagementAuth, pagination);
    foreach (Folder childFolder in childFolderResponse.Results)
    {
        PrintCourse(childFolder);
    }
    if (childFolderResponse.Results.Length == 0)
    {
        Console.WriteLine("\n No course folder(s) found!");
    }
}

void PrintCourse(Folder childFolder)
{
    Console.WriteLine("\n \t Course Name =  " + childFolder.Name);
    ListSessionsResponse courseSessionResponse = GetPresentations(sessionMgr, SessionManagementAuth, pagination, childFolder.Id);

    foreach (Session session in courseSessionResponse.Results)
    {
        Console.WriteLine("n \t \t Session Name = " + session.Name);
    }
    if (courseSessionResponse.Results.Length == 0)
    {
        Console.WriteLine("\n No sessions found!");
    }
}

Pulling out the printing of sessions seemed...not useful.


Grouping counts from tables by account ID

I took the liberty of throwing this in to an SQLFiddle here

If I play with the query, and run the screened and approved queries on the data that I chose, I see you have a condition which may or may not be a bug. If you consider my data, where I have multiple accountId values per application, then, your subquery:

SELECT      application.accountId, 0, COUNT(*), 0
FROM        application
JOIN        termsofapproval ON application.accountId = termsofapproval.accountId
JOIN        approvaluserjoin ON termsofapproval.id = approvaluserjoin.termsofapprovalId
[accountIdCondition]
GROUP BY    application.accountId

That query will duplicate the count of approved users if there are multiple applications for the same accountId. In the SQLFiddle I have, it returns a count of 4 for only 2 distinct approvaluserjoin records.

It is likely that in your data it is not possible to get that condition though... right?

Regardless. I believe the more logical representation of your query is as follows (which I have in this SQLFiddle here

SELECT application.accountId ,
       count(distinct application.id) as ApplicantsCount,
       count(distinct approvaluserjoin.id) as ApprovedCount,
       count(distinct screened.id) as ScreenedCount
FROM application
left join termsofapproval on application.accountId = termsofapproval.accountId
left join approvaluserjoin on approvaluserjoin.termsofapprovalId = termsofapproval.id
left join screened on screened.applicationId = application.id
where application.accountId <= 2
group by application.accountId

Note how there is only one join, using left outer joins. Also note that a count of a null value is 0, so the null values in the outer-join results do not contribute to the sum. The coutn(distinct ...) construct allows you to count the things you are interested in, even if the query returns them in multiple contexts.

You will need to carefully understand the query, the implications are different to yours, and it may be more accurate than what you have (or less accurate).


Create an Array of Objects for Patch Notes in React

You got the first step right by removing every white space and line breaks from your string. Next you will have to remove the first occurence of ### by splitting your string and then slicing out the first element.

When done, you will have to map the result of your split. Map will create a new array the exact same size of your input and apply the same function on every attribute of it.

You will then have to split each update by the *. When done, you can get the first value of your array with shift. This function will give out the first element of your array and delete it from the array, only leaving the notes that are going to be put in the notes variable :

const data = '### 0.1.2\n* Patch notes now implemented when the modal starts.\n* Added top lists for organizations\n### 0.0.1\n* Patch Notes Added\n* Modal to include Patch Notes'

const updates = data.replace(/(\r\n|\n|\r)/g, '').split('### ').slice(1).map(update => {
 updateData = update.split('* ')
 return {
  version: updateData.shift(),
  notes: updateData
 }
})

console.log(updates)

You can then put this function in the .then of your axios call


Two methods for finding a sprite in sprite sheet C++, which is better?

I prefer the first one, because having the named variable numRows:

Certainly makes the code more "self-documenting": it's easier for me (the programmer) to understand what the algorithm is doing
May make the code faster: because you only do the floor(imageWidth / SpriteAverageSize) calculation once instead of three times (although it's possible that an optimizing compiler might be able to make that optimization itself, even without your 'hint' that it's a reused sub-expression)


Thanks. I have been trying to learn about bloom filters. Had to do some research before the review :-)

Code Review

Hash Function

This is an old C style typedef.

typedef unsigned int (*HashFunction)(std::string);

Though not wrong I prefer the C++ style as they are easier to read.

typedef std::function<unsigned int(std::string)>   HashFunction;

Or using the newer C++11 using directive (I am beginning to use more of this myself).

using HashFunction = std::function<unsigned int(std::string)>;

While we are on the hash function. I note that you are passing std::string as a value and thus inducing a copy of the string. To avoid the copy pass by const reference.

using HashFunction = std::function<unsigned int(std::string const&)>;

Members

Looking at the data members of BloomFilter.

    // This member is not used anywhere.
    // but should also be the same value as hashFunctions.size()
    // So I think we can remove this.
    unsigned int numberOfFunctions;

    // Here we have a pointer data member. This is usually a bad
    // idea. We want to encourage the rule of zero. So we want to
    // use classes that do their own memory management.
    bool* cell;
    // More about this in notes on the destructor.

So I would use:

    std::vector<bool>   cell;

Constructor

Just like normal variable declarations, prefer to initialize members one per line. There are no prizes for using the least number of rows possible.

Also like the hash function you are passing the parameters by value (and thus inducing a copy). Here we can pass funcs by const reference.

    BloomFilter(unsigned int numbCells, std::vector<HashFunction> funcs) : numberOfCells(numbCells), hashFunctions(funcs) {
        cell = (bool*)calloc(numbCells, sizeof(bool));
    }

    // Can be

    BloomFilter(unsigned int numbCells, std::vector<HashFunction> const& funcs)
        : numberOfCells(numbCells)
        , hashFunctions(funcs)
        , cell(numbCells)          // assuming we change cell to vector
    {}

As a side note:

        // Please don't use C-Casts.
        // These are completely unchecked. You are basically
        // telling the compiler to ignore all errors.
        cell = (bool*)calloc(numbCells, sizeof(bool));
        // Also there is no check to see if calloc() failed.

It should look more like this:

        cell = static_cast<bool*>(calloc(number, sizeof(bool));
        if (cell == null) {
            throw bad_alloc;  // maybe another exception.
        }

        // or better yet use new/delete
        cell = new bool[number]();      // need a call to delete [] cell; in destructor: The braces force value initialization that is false.

        // or better yet use a type like vector that does memory management correctly.
           // No action needed as you did it all in the initializer list.

addElement

Passing parameter by value again. Prefer to pass by const reference.

    void addElement(std::string str) {
    // So prefer
    void addElement(std::string const& str) {

When using iterators prefer to use the pre-increment ++iter rather than the post increment iter++. There is slight performance environment.

So you use the standard for loop from C++03

        for (std::vector<HashFunction>::iterator iter = hashFunctions.begin(); iter != hashFunctions.end(); iter++) {
            cell[(*iter)(str) % numberOfCells] = true;
        }

We can improve this in C++11 using auto.

        for (auto iter = hashFunctions.begin(); iter != hashFunctions.end(); ++iter) {
            cell[(*iter)(str) % numberOfCells] = true;
        }

In C++14 we now have the range based for loop.

        for (auto const& item: hashFunctions) {
            cell[item(str) % numberOfCells] = true;
        }

searchElement

Passing parameter by value again. Prefer to pass by const reference.

    bool searchElement(std::string str) {
    // should be
    bool searchElement(std::string const & str) {

The first note I want to make is the name. A searchX() function usually return a reference to something. I would name it checkX().

In this case rather than using a for loop you can use one of the standard function. In this case we can use find(). You are looking for a failure (but that's a thing).

    auto f = std::find(std::begin(hashFunctions), std::end(hashFunctions),
                       [&cell, &str](HashFunction hash){
                           return !cell[hash(str)];
                       });
    return f != std::end(hashFunctions);

Destructor

We should note that in C++11 we moved to using nullptr rather than NULL.  It is type safe.

    ~BloomFilter() {
        free(cell);
        cell = NULL;  // This is actually a bad idea.
                      // It hides errors that can be detected by the
                      // debug system.
    }

One of the issues you can get into with doing your own memory management is called the double free. Usually debug version of the standard library detects double free so you can catch it during testing. But by setting the value to nullptr in the destructor prevents that check.

The other thing you need to note is that by default the compiler will generate four methods for a class if you don't define them.

  BloomFilter();                             // Constructor.
  BloomFilter(BloomFilter const&);           // Copy constructor.
  BloomFilter& operator=(BloomFilter const&);// Assignment operator
  ~BloomFilter();                            // Destrutor.

You define the Constructor and Destructor but the other two you don't define. So the compiler will generate the other two for you. Usually these work fine. BUT if your class contains an owned RAW pointer then the default compiler generated versions don't work as you would expect.

So you should look up the rule of three.
If you have to define one of Copy Constructor/Copy Assignment or destructor you probably need to do all three. If your class only uses objects that obey the rule of three already then your class will obey the rule of zero automatically (look them up).

Design Review

Asking user to provide a large set of hash functions is unreasonable. Hash functions are hard to define in the first place and even harder to get a good distribution with over a set of them. You need to define some way that in most cases the hash is provided (though being able to provide your own is a nice touch).


Titleize words in a sentence but with some conditions

Rather than split and join the string, it'd be simpler to

Always capitalize the sentence itself, so it always starts with an uppercase letter
Pass a block to gsub, letting it do the filtering.

Also: a minor thing but unlike Java, Ruby favors snake_case rather than camelCase for names. So conventionally, it'd be little_words, not littleWords.

Here's a simplistic implementation:

def titleize(sentence)
  little_words = %w(end over and the)
  sentence.capitalize.gsub(/(\w+)/) do |word|
    little_words.include?(word) ? word : word.capitalize
  end
end

Of course, capitalize doesn't just make the leading letter uppercase, it also foribly downcases the rest of the string. So writing, say, "DNA and RNA" will incorrectly give you "Dna and Rna". It isn't fond of unicode characters either, so caveat emptor.

Basically, that "titleizing" a string is bit of hornet's nest. There are multiple schools of thought on how it should be done, some depending on context. And right when you think you have it, someone writes a URL or a name like "iPhone" in a sentence, and it comes out wrong anyway.

A slightly more clever - but still brittle! - solution might be:

def titleize(sentence)
  little_words = %w(end over and the)
  sentence.gsub(/\b(\p{Ll}+)\b/) do |word|
    # The following breaks codereview's syntax highlighting, but it's valid Ruby code.
    # I used a "full" if-else rather than a ternary just to keep the lines shorter.
    if $`.empty? || !little_words.include?(word)
      word.capitalize
    else
      word
    end
  end
end

The regex only matches words that are all-lowercase meaning "DNA" and "iPhone" will pass though undisturbed. But we can't capitalize the string in its entirety because it'd just make everything except the first word an all-lowercase word. So instead, we have the $` "magic" variable, which contains the string before the current match. If it's empty, we're at the start, and should capitalize the word even if it's on the small_words list.

But again, this isn't a great solution at all. It's just here to illustrate some regex voodoo.

And in any event this isn't a new problem. Here's a gem that sounds like it's a port of this Perl script, which, if nothing else, comes with an explanation of its working.

Edit: As tokland points out in the comments, using a Set instead of an array for litte_words would make for faster lookups; no searching necessary. It'd also be nicer to define the list of little words as a constant, rather than declare it as a local variable when the method's run:

LITTLE_WORDS = %w{ end over and the }
  #=> ["end", "over", "and", "the"]


Conversion from decimal to negabinary and vice versa in Haskell

A couple of things I noticed:

xrem and xdiv are exactly the same except they use a different division function. You could therefore replace them with a single function that takes the type of division as a parameter:

dec2negbin :: Int -> NegaBinary
dec2negbin = reverse .
             map intToDigit .
                 unfoldr (\x -> if x==0 then Nothing else Just(abs(doDiv rem x (-2)), doDiv div x (-2)))
    where
      doDiv division a b = if b > 0 then division a b else (-(division a (-b)))

In your second function you could use zipWith which applies a given function whilst zipping instead of doing a zip then a map:

negbin2dec :: NegaBinary -> Int
negbin2dec = sum . zipWith raise [0..] . reverse . map digitToInt
    where
        raise e x = x * (-2) ^ e


Cloning Windows Forms controls from a template

I think you should remove Clone method from your builder. So you essentially would have:

interface ITemplateBuilder<TSource>
{
     ITemplateBuilder<TSource> WithArgument(...);
     ITemplate<TSource> Build();
}

where:

interface ITemplate<TSource>
{
     TSource Clone();
}

while it is similar to what you have, it conveys your intention in clearer way.

But overall I have to agree with Adriano, I think you are over-engineering. A simple factory will do the job and will probably take less code to write. However you can improve your implementation so it works more like a simplified version of WPF style, so that those actions you were saving up can be applied to any instance of Control. That, I think, would be much more useful. That you can't do with a factory.

 var style = new ControlStyle<Label>()
        .Setter(label => label.TextAlign = ContentAlignment.MiddleLeft)
        .......;
 style.Apply(_myLabel);
 style.Apply(_myCustomClassThatInheritsLabel);


Poker Game: Unit testing different poker hands without violating DRY principles

One thing that would help with reducing duplication is to use parameterized tests.

Additionally, you might want to have a enum with the different hand types instead of - or in addition to - having one method for each hand type, such as your current PokerHandEvaluator.OnePair.


Apache POI and cyclomatic complexity of code

If you want to create an object from Excel row you can change the method's signature to accept an array of values:

private WHTApps createModelFromValues(Object[] values) {
    WHTApps whtApp = new WHTApps();
    whtApp.setVendorCode((int) values[0]);
    whtApp.setVendorName((String) values[1]);
    ....
    whtApp.setCategory((String) values[17]);
    return whtApp;
}

This method is not as complex as the first one and is easier to test. Client code will have to populate an array of values to pass.

You should consider adding some kind of error checking: validate values array before processing it. Check for length and data type errors. You can create a custom exception class that will clearly show where the problem is.

Probably, you can make this code more flexible by adding a separate mapper class that will set properties using reflection. I'm not sure if it's worth the effort in this particular case, though.


good

yay for specifying bash in your #! line.
nice indentation of loops and conditionals
good variables names
Thanks for splitting long commands onto multiple lines, which are also nicely indented.  (Another way to to do this is to built up the command options in a variable and then pass that as the command argument.)

suggestions

I'm a big fan of https://www.shellcheck.net/ which is basically a linter for shell scripts.  Don't worry about fixing all of its suggestions, but most of them are worth considering.  My next few suggestions are based on its output.
Using backticks (`) for command substitution is not the current best practice.  Using $() for command substitution is nicer since it matches the () used for subshells and it stands out a bit more.  Lots of folks were confused by quotes being used for non-quoting things.  SC2006 mentions a few other reasons.
When you do mkdir -p ${backup_dest[$i]}/$today/db on line 46, if one of the backup_dest had spaces in it you'd end up making two directories instead of one.  It is best when doing variable substitutions in the shell to enclose them in double quotes.  mkdir -p "${backup_dest[$i]}/$today/db" is safer.  SC2086 explains more.
Are you expecting more db_creds in the future?  The for loop at line 35 seems superfluous.  Even if you had 99 entries in db_creds it is only going to set the db_* variables for the last one.  If you want to do something for each one you'd have to put more of the work inside the loop.  Or am I missing some intent here?
checking to make sure you got a db_host in line 43 is a good idea, but should there be an else do this that warns about it being missing?
does it matter if any of the stuff before the rsync fails?  Do you want to exit with FAILED for anything before the rsync?
putting a bit more documentation in the code would be better, but the comments that are there are good.

Overall, an excellent job for someone new to shell scripting.


Finding out players gender and name in text based adventure game

I see a number of things that may help you improve your code.

Use objects

The code has two things that look like a menu.  It also collects two pieces of data about a single player.  Those things, menu and player could and probably should be objects.  Perhaps you're a beginning programmer, and haven't learned about objects yet, but this kind of repeated task with associated data is really well-suited to object-oriented programming and that's something that C++ is very good at expressing.  For an example of a usable menu object, see this answer.

Prefer const variables to #define

Instead of using the old C-style #define as in this line:

#define NL "\n"

It's generally better and more type-safe to use a const variable like this:

static const std::string NL{"\n"};

However, I'd probably not define this particular one in either case and simply type \n where it's needed.

Use constant string concatenation

The code currently contains this:

std::cout << "Are you a boy or a girl?" << NL << "1. Boy | 2. Girl"
<< NL << "Choices are selected by typing in a single number" << NL;

But you don't really need to do it that way which potentially calls the << operator six times.  Instead, you could express the same thing as this:

std::cout << "Are you a boy or a girl?\n"
    "1. Boy | 2. Girl\n"
    "Choices are selected by typing in a single number\n";

Which is both more readable and only calls << once.  The compiler automatically concatenates the string literals together.

Use consistent formatting

The code as posted has inconsistent indentation which makes it hard to read and understand. Pick a style and apply it consistently.

Sanitize user input better

The code doesn't quite work as posted.  If I enter a string such as "Edward" to answer a question, the program stays in an endless loop.  It would be better to read a (text) line in and then convert it to a number.  Users can do funny things and you want your program to be robust.

Omit return 0

When a C or C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no need to put return 0; explicitly at the end of main.

Note: when I make this suggestion, it's almost invariably followed by one of two kinds of comments:  "I didn't know that." or "That's bad advice!"  My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard.  For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:

  [...] a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0.

For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:

  If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;

All versions of both standards since then (C99 and C++98) have maintained the same idea.  We rely on automatically generated member functions in C++, and few people write explicit return; statements at the end of a void function.  Reasons against omitting seem to boil down to "it looks weird".  If, like me, you're curious about the rationale for the change to the C standard read this question.  Also note that in the early 1990s this was considered "sloppy practice" because it was undefined behavior (although widely supported) at the time.

So I advocate omitting it; others disagree (often vehemently!)  In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means.


clean approach to decorator that takes optional keyword arguments

Nice little snippet! A couple of minor points:

It's usually better to put the shorter block first in an if else. This stops the else statement being far from the if, making it clearer how the logic flows.
When comparing to None, check if func is None or similar, rather than comparing to True/False.
Although this is just a toy example, docstrings should always be used to show what the code does and returns.
PEP8 spacing between imports, functions and code.
Argument names could be better but without knowing the application it's hard to say what they should be.

from functools import partial, wraps

def decorator(func=None, **kwargs):
    """
    Decorator which optionally takes an argument sayhi (True or False).
    prints 'hi' if True, function is then returned as normal
    """
    if func is None:
        return partial(decorator, **kwargs)
    else:
        @wraps(func)
        def decorated(*func_args, **func_kwargs):
            if kwargs.get('sayhi'):
                print('hi')
            return func(*func_args, **func_kwargs)
        return decorated


Create an array with the highest values from each array

The challenge says that you will be given exactly four subarrays, but it doesn't specify the length of each subarray.  You've assumed a square matrix, which is not stated in the problem.

To find the maximum of 4, 5, 1, and 3, you could write Math.max(4, 5, 1, 3).  If those numbers are given to you as an array, you could use Math.max.apply(null, array).

To transform each element of the outer array, use arr.map().

function largestOfFour(arr) {
  return arr.map(function(subArr) {
    return Math.max.apply(null, subArr);
  });
}

console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]));


Bash Script for file auditing, push information to server and be able to view in a web page

Performance pitfalls

Running ssh in a loop tends to be slow. Running it twice for every file in a list is probably extremely slow. There's no easy fix for this. You need to rethink how to solve the problem of matching paths between two systems.

Off the top of my head:

Get the list of paths from both systems, and then try to match those locally. This can be done with one ssh call per system: a major improvement.
For the list of matched paths, get the md5 sums. Again this can be done with one ssh call per system.
Compare the hashes, and build a new list of mismatched files.
For the final comparison of files, you could fetch them one by one to conserve disk space. If the number of remaining files is expected to be small, then one scp call per file might be acceptable. Or if disk space is not an issue, then you could transfer all the files with one call.

A much smaller performance issue is running sed ... | column ... for each file type for each base directory. You could instead make the loop body output only the output of the multiple find calls, and run the sed ... pipeline on the entire loop (writing as done | sed ...).

Looping over arrays

Instead of this:

for((i=0; i<${#DIR[@]}; i++))
do
  echo "CHECKING: ${DIR[$i]}"

When you don't need the array indexes, just the elements, you can iterate like this:

for dir in "${DIR[@]}"
do
  echo "CHECKING: $dir"

Most of the loops in the posted script can be replaced with this simpler, more intuitive style.

Simple mistakes

Use . instead of $PWD
Double-quote variables used in command arguments: instead of find $var, write find "$var"
Don't export if you don't need to
Don't create arrays if you need a simple variable: instead of tmpdir=("$_TMPDIR$path") write tmpdir="$_TMPDIR$path"
Strive for simple writing style: instead of env2file=(/"$ScriptsDir"/tmp"$x"), write env2file="$ScriptsDir/tmp$x"


Batch bash installer script for clean Ubuntu GNOME installation

Wall of code

The script looks like a wall of code.
It would be a lot more pleasant to read if related groups of commands were separated from each other by blank lines, for example:

# install steam
wget https://steamcdn-a.akamaihd.net/client/installer/steam.deb
sudo dpkg -i steam.deb
sudo apt-get install -f

# install atom
wget https://atom.io/download/deb
sudo dpkg -i atom*
sudo apt-get install -f

Displaying info

This is not a very user-friendly (or pretty) way to show a message to the user before opening gnome-tweak-tool:

xterm -e "echo Make sure you select Bridge as the cursor, Papirus as the icon theme, and Numix as the GTK+ theme && gnome-tweak-tool"

Since you are on a Gnome Desktop, you can benefit from zenity,
a scriptable tool to display dialogs, for example like this:

zenity --info --text="Make sure you select Bridge as the cursor, Papirus as the icon theme, and Numix as the GTK+ theme" && gnome-tweak-tool

Pointless command

This command will have no useful effect:

sudo cd /usr/share/icons

In fact, instead of this:

sudo cd /usr/share/icons
wget https://dl.opendesktop.org/api/files/download/id/1464728434/164587-bridge.tar.gz
tar -xvzf 164587-bridge.tar.gz

You probably want to do something like this:

wget -O /tmp/bridge.tar.gz https://dl.opendesktop.org/api/files/download/id/1464728434/164587-bridge.tar.gz
sudo tar -xvzf /tmp/bridge.tar.gz -C /usr/share/icons

That is, download the tarball to a temporary folder,
and extract the content with root into /usr/share/icons.


Overriding operator delete/new to check correct pairs of (non-)array variants

#include <cstring>

Also include <cstdlib> (for std::malloc), and I'd include <new> out of paranoia anytime I'm messing with operator new, even if it might be unnecessary in this case.

constexpr char PREFIX_ARRAY [] = "STR2MED";
constexpr char PREFIX_OBJECT[] = "str1med";
constexpr auto OFFSET_ARRAY  = std::size(PREFIX_ARRAY);
constexpr auto OFFSET_OBJECT = std::size(PREFIX_OBJECT);

This strikes me as needlessly complicated. Also, such similar names invite accidental typo-bugs (e.g. mistyping OFFSET_ARRAY as OFFSET_OBJECT). Also, the use of the C++14 library algorithm std::size is unnecessary — (sizeof will do exactly what you want); and the use of auto is obfuscatory (the type of sizeof x is invariably size_t).

If you really wanted to use std::size, you should have included at least one of <array>, <deque>, <forward_list>, <iterator>, <list>, <map>, <regex>, <set>, <string>, <unordered_map>, <unordered_set>, <vector>.

Also, if you need these variables at all, you might consider putting them in a namespace, so that they don't conflict with the user's own global variable or function names.

using OFFSET_TYPE = decltype(OFFSET_ARRAY + OFFSET_OBJECT);

This is super duper confusing, or else it's one of those typo-bugs I was warning you about. Here you're adding together OFFSET_ARRAY (i.e. size_t(8)) and OFFSET_OBJECT (i.e. size_t(8)), taking the decltype of that (i.e. size_t), and declaring a typedef named OFFSET_TYPE. If you really wanted this typedef, you should write it as

using OFFSET_TYPE = size_t;  // or std::size_t if you enjoy typing

Related: I never write std:: for the stuff that I know is coming from libc anyway. That's a personal quirk, though. I get the impression that a lot of people do write std:: everywhere, even where it's not technically needed.

template<OFFSET_TYPE OFFSET>
inline void * guardDelete(void * pointer, const char PREFIX[OFFSET])

Here I would worry that the programmer didn't know that arrays in C and C++ are passed "by decay to pointer". I would prefer to write this as

template<size_t Offset>
inline void *guardDelete(void *ptr, const char *prefix)

so that it is obvious that Offset is not deducible. Notice also that I'm consistently using snake_case for local variable names, and CamelCase for template parameter names (such as Offset); I find that this makes code easier to decipher than using a mix of lower and UPPER case.

void __cdecl operator delete  (void * pointer)

If I cared about portability to non-MSVC targets, I'd preemptively factor out this __cdecl into a macro that I could easily turn off. However, it occurs to me that __cdecl itself is an identifier that could be defined away on non-MSVC platforms; so sure, let's leave it alone.

So putting it all together, I'd have:

#include <string.h>
#include <stdlib.h>
#include <new> // maybe

template<size_t N>
inline void *guardNew(void *pointer, const char (&guard)[N])
{
    ASSERT(pointer != nullptr); // Out of virtual memory?
    memcpy(ptr, guard, N);
    return reinterpret_cast<char*>(ptr) + N;
}

template<size_t N>
inline void *guardDelete(void *ptr, const char (&guard)[N])
{
    if (ptr == nullptr) {
        return ptr;
    } else {
        char *prefix = reinterpret_cast<char*>(ptr) - N;
        ASSERT(memcmp(prefix, guard, N) == 0);
        return prefix;
    }
}

void * __cdecl operator new(size_t size) {
    return guardNew(malloc(size + 8), "str1med");
}
void * __cdecl operator new[](size_t size) {
    return guardNew(malloc(size + 8),  "STR2MED");
}
void __cdecl operator delete(void *ptr) {
    free(guardDelete(ptr, "str1med"));
}
void __cdecl operator delete[](void *ptr) {
    free(guardDelete(ptr, "STR2MED"));
}

However, then I start worrying... is this code even doing a sensible thing? Notice that if I try to new an object of some type T where alignof(T) > 8, then the pointer returned from our operator new will not be properly aligned for that T. And the fact that it's properly aligned for alignments <= 8 feels like an accident. If we changed our guard strings from str1med and STR2MED (not obvious why we picked those strings, by the way — and again the unfortunate mix of lowercase and UPPERCASE) to, let's say, hello and world, this code would break in several different ways. So maybe we want to force the compiler to diagnose that breakage for us:

inline void *guardNew(void *pointer, const char (&guard)[8])
{
    ASSERT(pointer != nullptr); // Out of virtual memory?
    memcpy(ptr, guard, 8);
    return reinterpret_cast<char*>(ptr) + 8;
}

Now if we change the string in operator new from str1med to hello, we'll get a compiler error.

But we've still got two instances of the magic number 8 separated by a fair number of lines of code. Let's inline this guardNew helper so that we're malloc'ing and memcpy'ing in the same place:

#include <stdlib.h>
#include <string.h>

void * __cdecl operator new(size_t size) {
    void *p = malloc(size + 8);
    ASSERT(p != nullptr);  // Out of memory?
    memcpy(p, "str1med", 8);
    return (char *)p + 8;
}
void * __cdecl operator new[](size_t size) {
    void *p = malloc(size + 8);
    ASSERT(p != nullptr);  // Out of memory?
    memcpy(p, "STR2MED", 8);
    return (char *)p + 8;
}
void __cdecl operator delete(void *ptr) {
    if (ptr == nullptr) return;
    char *p = (char*)ptr - 8;
    ASSERT(memcmp(p, "str1med", 8) == 0);
    free(p);
}
void __cdecl operator delete[](void *ptr) {
    if (ptr == nullptr) return;
    char *p = (char*)ptr - 8;
    ASSERT(memcmp(p, "STR2MED", 8) == 0);
    free(p);
}

From 36 lines down to 27 — and with no pollution of the global namespace, no templates, and — mainly as a result of flattening and inlining things with complicated dependencies on each other — it's just a little bit harder to break accidentally.


Moving average function in C++ for use with R

Overall your code is not bad, but we can do better. Let's start with the coding style.
Your variables are clearly named and your code is easy to follow, however the use of & is not necessary.
const NumericVector &x

R objects are always passed by reference in Rcpp even without the &. Dirk has some slides (see 29,30) with more information about this topic here. It is also in the Rcpp FAQ. The point is, is that we can safely drop these ampersands.
Now, let's talk about how we can improve the performance of your code. We first note that there are many unnecessary checks in the inner for loop.
if((ind_x >= 0) & (ind_x < n))

This can be avoided outside of the loop like so :
// [[Rcpp::export]]
NumericVector roll_meanReduceChecks(const NumericVector x,
                                    const NumericVector w) {

    int n = x.size();
    int w_size = w.size();
    int size = (w_size - 1) / 2;

    NumericVector res(n);
    int i, ind_x, ind_w, strt, endx;

    double tmp_wsum, tmp_xwsum, tmp_w;

    for (i = 0; i < n; i++) {
        tmp_xwsum = 0;
        tmp_wsum = 0;

        if ((i - size) <= 0) {
            strt = 0;
            ind_w = size - i;
        } else {
            strt = i - size;
            ind_w = 0;
        }

        endx = ((i + size) >= n) ? n : (i + size);

        for (ind_x = strt; ind_x < endx; ind_x++, ind_w++) {
            // This check is no longer necessary
            // if((ind_x >= 0) & (ind_x < n)){
            tmp_w = w(ind_w);
            tmp_xwsum += x(ind_x) * tmp_w;
            tmp_wsum += tmp_w;
        }

        res[i] = tmp_xwsum / tmp_wsum;
    }

    return res;
}

With this modification, we get about 10% faster timings:
set.seed(42)
x <- sample(10^3, 10^4, TRUE)
w <- sample(100, 10^3 , TRUE) / 100

## Gives the same result
all.equal(roll_mean(x, w), roll_meanReduceChecks(x, w))
[1] TRUE

library(microbenchmark)
microbenchmark(roll_mean(x, w), roll_meanReduceChecks(x, w),
               times = 50, unit = "relative")
    Unit: relative
                       expr      min       lq     mean   median       uq      max neval
            roll_mean(x, w) 1.138508 1.135057 1.119695 1.132882 1.123308 1.149893    50
roll_meanReduceChecks(x, w) 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000    50

We can still do better. The real savings comes into play with the use of iterators. There is a lot of good information out there regarding this topic and here is just one resource written by Hadley Wickham that is a good starting place.
Putting it all together we have:
// [[Rcpp::export]]
NumericVector roll_meanIterator(const NumericVector x,
                                const NumericVector w) {

    int n = x.size();
    int w_size = w.size();
    int size = (w_size - 1) / 2;

    NumericVector res(n);
    NumericVector::const_iterator itw, itx, itEnd;
    double tmp_wsum, tmp_xwsum;

    for (int i = 0; i < n; i++) {
        tmp_xwsum = 0;
        tmp_wsum = 0;

        if ((i - size) <= 0) {
            itx = x.begin();
            itw = w.begin() + size - i;
        } else {
            itx = x.begin() + i - size;
            itw = w.begin();
        }

        itEnd = ((i + size) >= n) ? x.end() : x.begin() + i + size;

        for (; itx < itEnd; itx++, itw++) {
            tmp_xwsum += (*itx) * (*itw);
            tmp_wsum += (*itw);
        }

        res[i] = tmp_xwsum / tmp_wsum;
    }

    return res;
}

Here is a sanity check:
all.equal(roll_mean(x, w), roll_meanIterator(x, w))
[1] TRUE

And here are the benchmarks:
microbenchmark(roll_mean(x, w), roll_meanIterator(x, w),
                          times = 50, unit = "relative")
Unit: relative
                   expr      min       lq     mean   median       uq      max neval
        roll_mean(x, w) 8.480686 8.458674 8.493975 8.894612 8.548443 8.453865    50
roll_meanIterator(x, w) 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000    50

That is nearly 9x faster. Not bad, considering we didn't have to change the code that much.
Update
Below is an example of over optimizing and a lesson on "when to stop" as the code appears to be more efficient but is much messier than the code above with little to no trade-off in efficiency.
If we examine tmp_wsum more closely, we will find that on every iteration, it is only changing at the endpoints. In roll_meanReduceChecks above, if we insert std::cout << ind_w << ' '; just before the inner for loop and std::cout << ind_w << std::endl; just after it, here is the output for the first 5 iterations:
499 998
498 998
497 998
496 998
495 998

And the last 5 iterations:
0 504
0 503
0 502
0 501
0 500

This seems like an opportunity for even further optimizing our code as we can alter our code such that we won't have to reconstruct tmp_wsum from scratch every time. However, in order to implement this, we must add two extra variable, and two extra checks to every iteration. Observe:
NumericVector roll_meanOverOptimized(const NumericVector x,
                                     const NumericVector w) {

    int n = x.size();
    int w_size = w.size();
    int size = (w_size - 1) / 2;

    NumericVector res(n);    // must add variables for checks below
    NumericVector::const_iterator itw, itwBeg, itwEnd, itx, itxEnd;
    double tmp_wsum = 0, tmp_xwsum = 0;

    // We must first initialize tmp_wsum, itwBeg,
    // itwEnd, as well as populate res[0]
    itx = x.begin();
    itwBeg = itw = w.begin() + size;
    itxEnd = (size >= n) ? x.end() : x.begin() + size;

    for (; itx < itxEnd; itx++, itw++) {
        tmp_xwsum += (*itx) * (*itw);
        tmp_wsum += (*itw);
    }

    res[0] = tmp_xwsum / tmp_wsum;
    itwEnd = itw;

    // Start i @ 1 instead of 0 as the first
    // iteration was taken care of above
    for (int i = 1; i < n; i++) {
        tmp_xwsum = 0;

        if ((i - size) < 0) {
            itx = x.begin();
            itw = w.begin() + size - i;
        } else {
            itx = x.begin() + i - size;
            itw = w.begin();
        }

        // first check
        if (itw != itwBeg)
            tmp_wsum += (*itw);
        itwBeg = itw;

        itxEnd = ((i + size) > n) ? x.end() : x.begin() + i + size;

        // N.B. only one variable is being updated now
        for (; itx < itxEnd; itx++, itw++)
            tmp_xwsum += (*itx) * (*itw);

        // second check
        if (itw != itwEnd)
            tmp_wsum -= (*itw);
        itwEnd = itw;

        res[i] = tmp_xwsum / tmp_wsum;
    }

    return res;
}

Let's see if this extra optimization paid off:
## Gives the same results
all.equal(roll_meanIterator(x, w), roll_meanOverOptimized(x, w))
[1] TRUE

microbenchmark(roll_mean(x, w),
               roll_meanIterator(x, w),
               roll_meanOverOptimized(x, w),
               times = 50, unit = "relative")
               Unit: relative
                        expr      min       lq     mean   median       uq      max neval
             roll_mean(x, w) 8.679318 8.751559 8.605352 8.796965 8.509649 7.683454    50
     roll_meanIterator(x, w) 1.015420 1.028507 1.041876 1.019177 1.017208 1.133470    50
roll_meanOverOptimized(x, w) 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000    50

Virtually identical results as roll_meanIterator. IMO, the ~2% efficiency gain is not worth it as we have made our code more difficult to read.
Update 2 (Many thanks to @HongOoi)
In the comments @HongOoi states, "the speedup isn't because of iterators per se, but because OP is using bounds-checked array access via the operator (). Switching to the regular [] should give you the same result as iterators. Let us test!!!
// [[Rcpp::export]]
NumericVector roll_meanBrackets(const NumericVector x,
                                const NumericVector w) {

    int n = x.size();
    int w_size = w.size();
    int size = (w_size - 1) / 2;

    NumericVector res(n);
    double tmp_wsum, tmp_xwsum;
    unsigned long int ind_x, ind_w, xEnd;

    for (int i = 0; i < n; i++) {
        tmp_xwsum = 0;
        tmp_wsum = 0;

        if ((i - size) < 0) {
            ind_x = 0;
            ind_w = size - i;
        } else {
            ind_x = i - size;
            ind_w = 0;
        }

        xEnd = ((i + size) > n) ? x.size() : i + size;

        for (; ind_x < xEnd; ind_x++, ind_w++) {
            tmp_xwsum += x[ind_x] * w[ind_w];
            tmp_wsum += w[ind_w];
        }

        res[i] = tmp_xwsum / tmp_wsum;
    }

    return res;
}

And here are the benchmarks:
microbenchmark(roll_mean(x, w),
               roll_meanIterator(x, w),
               roll_meanBrackets(x, w),
               times = 50, unit = "relative")
Unit: relative
                   expr      min       lq     mean   median        uq      max neval
        roll_mean(x, w) 8.596342 8.425527 8.374452 8.414136 8.3626927 7.479161    50
roll_meanIterator(x, w) 1.012213 1.007219 1.007606 1.000564 0.9973372 1.177148    50
roll_meanBrackets(x, w) 1.000000 1.000000 1.000000 1.000000 1.0000000 1.000000    50

As predicted by @HongOoi, the efficiency is nearly identical. This begs the question

Which method should you use? Iterators or C-style indexing?

Fortunately for us, there is some great information out there addressing this very topic. In fact, I found the answer to the stackoverflow question Iterator Loop vs Index Loop extremely helpful. Here is the summary by @TemplateRex:

"if you really need the index (e.g. access the previous or next element, printing/logging the index inside the loop etc.) or you need a stride different than 1, then I would go for the explicitly indexed-loop, otherwise I'd go for the range-for loop.
For generic algorithms on generic containers I'd go for the explicit iterator loop unless the code contained no flow control inside the loop and needed stride 1, in which case I'd go for the STL for_each + a lambda."


Best solution: Create a single section class and add it to all sections.

Second best solution: Write a specific section class and @extend on other sections (in case you do not have control of HTML)

Worst solution: Writing a mixin (duplicates styles)


Transform snake_case to camelCase with sed

Why try to match for (^|_)? You are anyway modifying it at the end, so just skip the first character entirely:

echo "my_long_variable" | sed -r 's/_([a-z])/\U\1/gi' | sed -r 's/^([A-Z])/\l\1/'

The above pattern will take care of cases where you start with:

Some_var_Iable


Check if three arrays contains the same element

Your code assumes that each of the 3 arrays is sorted. Otherwise the < operator would not work. It's ok to assume this. You should have mentioned this in your question.

You use the == operator for comparing the numbers and the lengths. You should better use the === since the == operator considers 0 and "0" equal, which is not good in most cases.

It does not matter which of the 3 arrays comes first. The result will always be the same. Therefore it would be nice if the code looked the same for each of the 3 arrays. Your current code looks different for arr3.

I would write the code differently:

function smallestCommonElement(a, b, c) {
    let i = 0, j = 0, k = 0;

    while (i < a.length && j < b.length && k < c.length) {
        const max = Math.max(a[i], b[j], c[k]);

        let same = true;
        while (i < a.length && a[i] < max) i++, same = false;
        while (j < b.length && b[j] < max) j++, same = false;
        while (k < c.length && c[k] < max) k++, same = false;

        if (same)
            return a[i];
    }
    return null;
}

The idea is to start at the beginning of the arrays. In each step, look at the current values and find the maximum number. Advance each array to this maximum number. If none of the 3 arrays has been advanced, this means that the current values from all the arrays must be the same. In that case, return this value. Otherwise the values must be different, so try again. Do all this until one of the arrays is at the end, in which case there is no common element.

Looking again at your code, there is a bug. Given the arrays [2, 3], [2, 3], [3], your code will return 'No equal number' even though the 3 appears in each array. Using a debugger (or pen and paper), you should step through your code to see where the bug is.

It's an edge case, and it happens in the part of the code that differs from the other parts. That's why I suggested that the code for all 3 arrays should look the same. It's one less chance of introducing bugs.


Project Euler #10 (sum of primes less than two million) in Clojure

I won't comment on the Java bit because I don't write Java very often. I agree with the other answer though that sqrt should only be called once. Computing the sqrt of a number is relatively expensive.

First, for Clojure, a baseline on my computer:

(defn sieve [size]
    (-> (reduce (fn [prev i]
                  (if (prev i)
                    (vec (reduce #(assoc %1 %2 false)
                                 prev
                                 (range (+ i i) size i)))
                    prev))
                (vec (repeat size true))
                (range 2 (-> size Math/sqrt int inc)))
        vec
        (assoc 0 false)
        (assoc 1 false)))

(defn main []
  (time
    (let [limit 2000000
          s (sieve limit)]
      (reduce #(+ %1 (if (s %2) %2 0))
              0 (range limit)))))

; From REPL
(main)
"Elapsed time: 2274.584779 msecs"
=> 142913828922

I should note that I'm on a crappy M3 Surface Pro 4; not a power machine by a stretch of any definition. If this is taking 14 seconds, you must have something else going on. That's far too long.

I actually prefer wrapping threading calls in parenthesis, even if they aren't required. I'd write lines such as (-> size Math/sqrt int inc) as (-> size (Math/sqrt) (int) (inc)). I find it helps differentiating between the form being a plain function call, and the threading of a value. The only time I omit them is when I'm golfing.

Your nested reduction is a lot going on in only a few lines. I would definitely break the inner reduction off into its own function, give it a descriptive name, and call it in the outer reduction.

(defn calc [size i prev] ; Although give it a better name
  (vec (reduce #(assoc %1 %2 false)
               prev
               (range (+ i i) size i))))

(defn sieve [size]
    (-> (reduce (fn [prev i]
                  (if (prev i)
                    (calc size i prev)
                    prev))
                (vec (repeat size true))
                (range 2 (-> size Math/sqrt int inc)))
        vec
        (assoc 0 false)
        (assoc 1 false)))

I like breaking functions up. Having giant functions forces you to consider a large amount of data and interactions at once. If you split a part off into its own function and ensure that it's pure, you know that no code in that function can manipulate any data that you haven't explicitly given it as a parameter. That's one less bit of the code to need to look at when debugging.

For your second bit, interestingly, it performed the same for me:

(main) ; Using your arrays version
"Elapsed time: 2106.530431 msecs"
=> 142913828922

You're making a critical error though when dealing with arrays in Clojure: don't use aset unless you have to. aset works on Objects, not primitives, as its documentation notes:

  Sets the value at the index/indices. Works on Java arrays of
    reference types. Returns val.

Using aset forces your bools to be boxed into a Boolean, which is pricey when done over and over. aset has multiple overloads for primitive types that should be used instead. I'd switch to aset-boolean, and create the array using boolean-array instead:

(defn sieve2 [size]
  (-> (let [ar (boolean-array (repeat size true))]
        (dorun (map (fn [i]
                      (when (aget ar i)
                        (dorun (map (fn [j] (aset-boolean ar j false))
                                    (range (+ i i) size i)))))
                    (range 2 (-> size Math/sqrt int inc))))
        ar)
      vec
      (assoc 0 false)
      (assoc 1 false)))

(defn main []
  (time
    (let [limit 2000000
          s (sieve2 limit)]
      (reduce #(+ %1 (if (s %2) %2 0))
              0 (range limit)))))

(main)
"Elapsed time: 759.412393 msecs"
=> 142913828922

A little better. I'll also note though that use of (dorun (map is usually a code smell. You're better off just using mapv which is strict. Using laziness when you don't need it can be costly. maping isn't the right tool here for the job anyways. Use map when you want to transform a list. Use doseq when you want to carry out side effects over a list. Think of it as Java's enhanced for-loop. I'm also using doseq's :when clause to replace the use of the when macro:

(defn sieve2 [size]
  (let [ar (boolean-array (repeat size true))]
    (doseq [i (range 2 (-> size (Math/sqrt) (int) (inc)))
            :when (aget ar i)] ; Replacing the call to when
      (doseq [j (range (+ i i) size i)]
        (aset-boolean ar j false)))

    (-> ar
        (vec)
        (assoc 0 false)
        (assoc 1 false))))

(main)
"Elapsed time: 577.607879 msecs"
=> 142913828922

Still not great, but better.

Just for a laugh comparison, here's a implementation of Eratosthenes' Sieve I wrote back in April:

(defn sieve-primes [n]
  (loop [p 2 ; First prime
         marked #{} ; Found composites
         primes []]
    (let [mults (->> n
                     (range p)
                     (map #(* p %))
                     (take-while #(< % n)))

          next-p (->> p
                      (inc)
                      (iterate inc)
                      (remove marked)
                      (first))

          new-primes (conj primes p)]

      (if (>= next-p n)
        new-primes
        (recur next-p (into marked mults) new-primes)))))

(time
  (apply + (sieve-primes 2000000)))
"Elapsed time: 8719.010487 msecs"
=> 142913828922

Ouch! I don't think I tried very hard to get it lower though. That was the first time I had ever written the sieve in any language, and was happy with just having a working implementation at the time. It is pretty though, even if it's slow.

Clojure is really not a performance-oriented language though. Yes, you can add all sorts of optimizations to make good use of all cores and limit intermediate lists when doing transformations, but it generally won't perform as well as other languages. It's generally even slower than Java of all languages in my experience. I write Clojure because it's fun to write and produces nice looking code, not because it produces fast code.


Regex for a string with at least a letter and no repeating dash

The lookahead (?=[a-z0-9-]*[a-z][a-z0-9-]*) can be reduce to:

(?=.*[a-z])

because the allowed characters are defined after in the non capturing group.

The dash [-] doesn't need to be inside a character class, - is enough

Then, the whole regex becomes:

^(?=.*[a-z])(?:[a-z0-9]|-(?!-)){1,10}$