Fibonacci sequence and nth number with reduce()

A short review;

I prefer fat arrow syntax => for inline functions
Its a good exercise to code this with reduce but it is definitely not the best option for production code. (That would be a non-recursive old skool loop)
The modern approach to Fibonacci numbers has them start with [0,1,1] not [1,1]
If you have control over what the function returns, then I would just return the sequence. It is trivial for the caller to get the last value in the array

Please find below a counter proposal, I like that it support both the old and new style sequence.

function buildFibonnaciSequence(n){
  const start = [0,1];
  //Recursion exit lane
  if(n <= 1){
    return [start.slice(0,n+1), start[n]];
  }
  //Recurse
  const priorSequence = buildFibonnaciSequence(n-1);
  //Build return value
  const nValue = priorSequence[0][n-2] + priorSequence[0][n-1];
  return [[...priorSequence[0], nValue], nValue];
}

console.log(buildFibonnaciSequence(0));
console.log(buildFibonnaciSequence(1));
console.log(buildFibonnaciSequence(5));
console.log(buildFibonnaciSequence(45));


Java 8 functions to avoid try-catch repetition

First of all, Function<Void, Void> is not an appropriate choice of functional interface for this purpose.

Function<T,R> implementation should receive an instance of T and return an instance of R (although T and R still can be of same type).

If there is no incoming type, this looks like a Supplier.

If there is no returned type, it resembles a Consumer.

If there are no types to specify, Runnable can be used, but it'd better be kept for its initial concurrent usage.

So a dedicated functional interface can be created to solve the problem:

@FunctionalInterface
interface ExecutedWithFacesLogger {

  void executeWithFacesLogger();

}

Now, the execute method changes to the following:

protected void execute(ExecutedWithFacesLogger function) {
  try {
    function.executeWithFacesLogger();
    facesUtils.addInfoMessage("PROPERLY_SAVED");
  } catch (Exception ex) {
    facesUtils.addErrorMessage("ERROR");
    throw ex;
  }
}

And the caller is reduced to:

public void assignWorker() {
  execute(() -> {
      assignWorker(selectedEquipment);
      reloadEquipmentById(selectedEquipment.get_Id());
  });
}


One major concern is that you define the array of account names and their associated hashed passwords in the file that, presumably, is publicly accessible through a web server.

You might be tempted to think this is not a concern, because users will not be able to see the source code, right? Generally speaking, that's correct. However, if the web server somehow becomes misconfigured at some point, where .php files are not executed by the PHP engine, but in stead are served as plain text, you have a big security issue: any visitor will now be able to view the account info.

To deal with this, you should keep this sensitive information outside of the server's public directory.

So, let's imagine this is your web server's directory structure:

 - etc/
 - private/ <-- A hidden private directory, outside of the public directory
 - public/ <-- The public root directory from which your .php pages are served
   - img/
   - js/
   - authentication.php
   - protected.php

...then you should, for instance, put your account info in private:

 - etc/
 - private/
   - accounts.php
 - public/
   - img/
   - js/
   - authentication.php
   - protected.php

accounts.php would then look like this:

<?php
return array (
    'sebas' => '$2y$10$96Yi1ezzoS6xZYjPhbvYTeCha.YypKF.7MSYwfruXtKaFyeGRLeMK',
    'bert' => '$3g$10$96Yi1ezzoS6xZYjPhbvYTeCha.YypKF.7MSYwfruXtKaFyeGRLeMK',
);

authentication.php would then do something like this:

<?php
session_start();

if($_SERVER['REQUEST_METHOD'] == 'POST'){
    // I personally prefer to name this variable as plural
    $accounts = include '../private/accounts.php';

    // if include has failed, it will return false
    if(is_array($accounts)) {
       // continue your authentication procedure
    }

... etc.


main

It is not considered good practice to just catch every possible exception like this. You should always specify which exceptions are possible and should be catched. In this specific case, the try-catch-statement is not necessary at all, because you are catching all possible exceptions in demoLoop already:

public static void main(String[] args) {
    demoLoop();
}

demoLoop

Are you trusting the user with making correct inputs? If the user does enter a String instead of a number, your program will crash. You can solve this problem by using the following snippet:

private static void demoLoop() {
    Scanner scanner = new Scanner(System.in);
    showOptions();
    int option;
    while(true) {
        try {
            option = scanner.nextInt();
            if(option > 2 || option < 0) {
                throw new InputMismatchException();
            }
            break;
        }
        catch(InputMismatchException e) {
            System.out.println("Enter 0, 1 or 2!");
            scanner.nextLine();
        }
    }
}

(don't forget to import java.util.InputMismatchException;)

I also don't like the way how you use the switch-case-statement, but this is probably just a matter of taste. I prefer the standard way:

switch (option) {
    case 0 :
        System.exit(0);
        break;
    case 1 :
        showDesignPrinciples();
        break;
    case 2 :
        runDuckSimulator();
        break;
    default :
        System.err.println("Please select a valid option.");
}


Measuring typing speed in terminal without a mistake

I think this is very nice, clean code. Let's make it better!

Consistency

Consistency helps a lot, making the code easier to understand.

Some functions are named camelCase, others snake_case. Stick to one pattern.
Some variables are named SHOUT_CASE, others snake_case. Stick to one pattern. The latter is recommended, because upper case variable names are commonly used for system variables like PATH and others.
The indentation is mostly 8 spaces, with few exceptions. Use the same everywhere.

Variable declaration

It's good to declare global constants at the top of the file where they are easy to see.
The same is not true for state variables that are implementation details,
such as current_lesson.
That variable would have been better to initialize right before you need it.

Iterating over arrays

Instead of a counting loop over the lesson array,
there is a more idiomatic approach:

for value in "${lesson[@]}"; do ...; done

I would also rename the array to plural lessons.

The return value of functions

There are some subtle points I don't like in this code:

function check_correct() {
        if [ "$user_input" == "$string_to_type" ]; then
                return;
        else
                echo "too many mistakes, try again!"
                false;
        fi
}

A return command without parameter will use the exit code of the last statement. In this case it's success. I would find it clearer if you used an explicit return 0 there.

The else branch ends with a false statement.
If this is the last statement in the function,
then the exit code of the function will be 1, as intended.
But this is not explicit enough.
The function doesn't return immediately on the false statement.
An explicit return 1 would be much better.

Like this:

function check_correct() {
        if [ "$user_input" == "$string_to_type" ]; then
                return 0
        else
                echo "too many mistakes, try again!"
                return 1
        fi
}

With my other suggestions further down, I recommend to write this function like this:

check_correct() {
        if ! [ "$user_input" = "$string_to_type" ]; then
                echo "too many mistakes, try again!" >&2
                return 1
        fi
}

Undocumented features

The == operator is not documented in man [.
For that reason I recommend using = instead of == in [ ... ].

Style

The recommended function declaration style is without the function keyword:

start() {

There are a bunch of redundant semicolons at end of lines that can be safely removed.

Instead of this:

wpm=$((sec / time_it_took))

You can write slightly simpler like this:

((wpm = sec / time_it_took))

This works too:

((wpm *= length_of_string / 5))

I don't remember the explanation, but instead of let count+=1, ((count+=1)) is recommended. An even better way to write is ((count++)).

Sharpening the saw

  I've been programming slightly better every year, but this year it has hardly changed.

Just keep doing it!


Exercism: determine if a word or phrase is an isogram

You can iterate once over text and short-circuit right away if any character is not unique.
import string

def is_isogram(text):
    seen = set()
    for char in text:
        if (lower := char.lower()) in string.ascii_lowercase:
            if lower in seen:
                return False
            else:
                seen.add(lower)
    return True


Both _tmain() and _TCHAR are Microsoft-specific and are non-portable. Just make them main() and char respectively.

The name T is commonly used in template statements.  Even with the given explanation, it may still confuse others, especially if you end up adding templates somewhere.  You could just rename this to testCases or something similar.

It's good to have more whitespace between operands for readability.
For instance, this:

for(int k=0;k<T;k++)

can look like this:
  for (int k = 0; k < T; k++)

You have some not-so-useful comments:

//  Take the test cases as input

This is already obvious based on what it's doing.

// the main loop that runs T times

This is also already obvious, based on the loop statement.

int result=2*N-1;   //  the numerator of the result

int square=N*N;   //  the denominator of the result

Although not necessarily useless comments, they are an indication that those variables can be given more accurate names.  It'll also help give more meaning to the very last cout statement that uses those variables.


AlwaysUpdate attribute for Entity Framework Code First POCO

Instead of checking .Count() > 0 which needs to iterate over the IEnumerable you can just use .Any() which only checks if at least one item is contained in the IEnumerable
you should extract the result of typeof(AlwaysUpdateAttribute) to a variable.

Type desiredType = typeof(AlwaysUpdateAttribute);

you can restrict the outer loop by adding the "continue condition" to the Where() method. For readability we will do this outside of the loop

changeSet = changeSet.Where( c=>
            c.State == System.Data.EntityState.Modified
              && !(entry.State == System.Data.EntityState.Added
              || entry.State == System.Data.EntityState.Unchanged)
             );

you shouldn't shorten any variable names -> prop should be propertyName

Refactoring

Implementing all above will lead to

public override int SaveChanges()
{
    var changeSet = ChangeTracker.Entries();
    if (changeSet != null)
    {
        changeSet = changeSet.Where( c=>
                 c.State == System.Data.EntityState.Modified
                  && !(entry.State == System.Data.EntityState.Added
                  || entry.State == System.Data.EntityState.Unchanged)
                  );

        Type desiredType = typeof(AlwaysUpdateAttribute);

        foreach (var entry in changeSet)
        {
            foreach (var propertyName in entry.Entity.GetType().GetProperties().Where(p => p.GetCustomAttributes(desiredType , true).Any()).Select( p => p.Name ))
            {
                // Try catch removes the errors for detached and unchanged items
                try
                {
                    entry.Property(propertyName).IsModified = true;
                }
                catch { }
            }
        }
    }
    return base.SaveChanges();
}

    foreach (var entry in changeSet)
    {
        foreach (var prop in entry.Entity.GetType().GetProperties().Where(p => p.GetCustomAttributes(desiredType , true).Any()).Select( p => p.Name ))
        {
            // Try catch removes the errors for detached and unchanged items
            try
            {
                entry.Property(prop).IsModified = true;
            }
            catch { }
        }


Decoding indeterminate types using JSON Decoder

I've finally end up splitting the two use cases. This in order to make the code readable and more maintainable.
PayloadError is mapped to a ServiceError: Error in order to align the output.
Use case 1
guard let data = response.data else {
    completion(.failure(.invalidData))
    return
}

let jsonDecoder = JSONDecoder()
if let payloadError = try? jsonDecoder.decode(PayloadError.self, from: data) {
    completion(.failure(ServiceError.from(payloadError)))
} else if let token = String(data: data, encoding: .utf8) {
    completion(.success(token))
} else {
    completion(.failure(.decodingError))
}

Use case 2
guard let data = response.data else {
    completion(.failure(.invalidData))
    return
}
let decoder = JSONDecoder()
guard let either = try? decoder.decode(Either<T, PayloadError>.self, from: data) else {
    completion(.failure(.decodingError))
    return
}
switch either {
case .left(let value):
    completion(.success(value))
case .right(let payloadError):
    completion(.failure(ServiceError.from(payloadError)))
}


Two sum problem implementation with Hashtable

Interesting solution for the problem. My first question as interviewer to you would be: are you sure it's O(n) time complexity? The worst case for hash lookup is O(n) so doesn't that make your total time complexity O(n²)?

Hint to answer this: when does that worst case occur, and why is this no problem for you? (Given how you initialised the map in your code you probably don't even need this hint to answer it correctly though).

You don't check your input values. What happens if nums is null?
I'm not saying your solution is wrong, but this should usually be a consious decission.
Your current choice is that the user of this method is responsible for passing non-null arguments or that we should start the fun journey of debugging where that NPE comes from.

The same reasoning goes for the target value. What if it's an impossible sum? Take for example the input nums = [2,3] and target=4. I partially like that you return an int[] result with negative indices instead of throwing an error. But the comment documenting it feels wrong.

I would have prefered that you would have handled it like an actual valid case and added a javadoc on top of the method that states that passing an impossible target results in [-1,-1].

Since you handle an impossible target that way, you could also choose to handle a null input for nums the same way. Add it to the javadoc and start your method with this simple check

if(nums == null){
    return new int[]{-1, -1};
}

Alternatively you can also throw explicit errors to force users to handle edge cases correctly.

It's generally better during an interview if you make those choices explicit. There's no real wrong choice, as long as you can tell why you picked a specific one. (A possible answer is: it's the easiest to implement, which to chooce often depends on what the method is for and how the company usually handles edge cases).

Why do you want an O(n) space and time complexity?
Wouldn't it be better to use O(1) space at the cost of O(n²) time if the implementation is easier?

For example:

private int[] twoSum(int[] nums, int target){
    if(nums == null) {
        return new int[]{-1, -1};
    }
    for (int i = 0; i < nums.length - 2; i++) {
        for (int j = i + 1; j < nums.length; j++) {
            if(nums[i]+nums[j]==target){
                return new int[]{i,j};
            }
        }
    }
    return new int[]{-1, -1};
}

Using this approach, you could ask the interviewer if the array is sorted. If it is you can replace the inner for loop with a search of the target in the remaining array. This turns the total time complexity into O(n*log(n)) instead.

Note that I wouldn't immediatly implement this for the interview. I would mention that these kind of optimisations are useful and possible, but that I would only do them after profiling shows these are the methods that take most time.

If it's a method that is only used a couple times per hour and on relatively small inputs then it's not worth putting in effort to optimise the implementation.
If it's a major function that runs millions of times per hour then it's worth optimising the hell out of it, even going as far as bit-trickery if wanted.

parter isn't the right word in this context. I'm assuming you meant partNer. Typos happen and not being native english myself I too make spelling mistakes. But this one is repeated too often to ignore in your piece of code.

You mention that you would have prefered to return a Pair. What would you do if we also wanted the methods threeSum fourSum or a general nSum?

In this example it doesn't matter too much, but it's best practice if you code against the interface, not the implementation. More specifically this line of code:

Hashtable<Integer, Integer> parterIdxHash = new Hashtable<Integer, Integer>(loadFactor*nums.length);

should have been:

Map<Integer, Integer> partnerIndices = new Hashtable<>(loadFactor*nums.lenth);

Since you didn't do this in your little example solution, the interviewer might conclude that you never do this. For local variables it doesn't change that much, but if you also use concrete classes as return types or as parameter inputs you violate the encapsulation principle.

It's also good practice to always put curly braces after each for/if/while/... statement. With maybe an exception when putting the entire statement on the same line for reasons explained here

As a final note I would like to emphasize that with interview solutions it's more important that you can tell what your solution is good at, what can still be improved and that your coding style is consistent. With this in mind you can always implement the easiest solution and tell the interviewer what the alternatives are without actually having to write them correctly.


Starting with Python 3.3, there is a standard ipaddress module.  Avoid reinventing-the-wheel.

Your IpAddr class is cumbersome because you store the four dotted-quad components separately.  It would be easier to represent it internally as a 32-bit integer, and convert it from/to dotted-quad notation in the constructor and the __str__ method.  For those conversions, you may find struct.pack() and struct.unpack() useful.

I would expect IpAddr objects to be immutable; the .next() method should return a new object instead of mutating the original one.

When scanning a range of IP addresses, watch out for network and broadcast addresses.  Opening a connection on a broadcast address would be inappropriate.

The find function is poorly named, and its parameters z and i are cryptic.  In fact, your variable names are generally horrible — what do p, q, n, and d mean?

Using a global cnt variable is inappropriate — especially since you access it in threads without any mutex.  But why even bother, if it's just a write-only variable whose value never matters?


Optimization over 7 constants, running a function 10,000,000 times

You have several loops that are completely unnecessary. Remove them and you will see dramatic speedups. Take voltoalph and voltoenen for example:

voltoalph2 <- function(v,c) {
  # v: a data vector
  # c: a scalar constant
  c(0, c[1L] * (v / max(v, na.rm=TRUE)))
}
voltoenen2 <- function(v,c) {
  # v: a data vector
  # c: a scalar constant
  enhelp <- 1 / c(1, abs(v / max(v, na.rm=TRUE)))
  c[1L] * (enhelp / max(enhelp))
}
require(microbenchmark)
v <- 1:10000
microbenchmark(voltoalph(v, 2), voltoalph2(v, 2))
# Unit: microseconds
#              expr        min          lq        mean     median          uq        max neval cld
#   voltoalph(v, 2) 105004.652 106038.7245 108767.0230 106725.827 108326.7975 151482.035   100   b
#  voltoalph2(v, 2)     81.925     83.5825    141.3382     89.794     91.6065   5350.052   100  a
identical(voltoalph(v, 2), voltoalph2(v, 2))
# [1] TRUE
microbenchmark(voltoenen(v, 2), voltoenen2(v, 2))
# Unit: microseconds
#              expr        min         lq        mean     median        uq        max neval cld
#   voltoenen(v, 2) 103595.526 105433.803 108797.6308 106882.274 110160.65 148550.397   100   b
#  voltoenen2(v, 2)    200.275    203.182    227.6582    207.932    220.57   1007.375   100  a
identical(voltoenen(v, 2), voltoenen2(v, 2))
# [1] TRUE

The vectorized (non-loop) versions are over 1000, and 500 times faster (for voltoalph and voltoenen, respectively), and provide identical output. percentcorrect calls each of those functions two times, which makes the speed improvement have twice the impact.


Dictionary foreach loop with multiple occurences

Don't write dead code - it rots like a corpse and makes it hard to maintain your code:

else if (counter >= 27)
{
    //Do nothing
}

Just delete this.

You can use the ++ increment operator here:

counter = counter + 1;

Like this:

++counter;

There is a += operator you can use here:

counter = counter + 2;

Like this:

counter += 2;

There is a Math.Pow() method you can use:

temp2 = temp * temp;

Like this:

temp2 = Math.Pow(temp, 2);


Checking errors from a series of function calls

Do your early returns properly, and there will be no more to tweak:

int Foo()
{
    int result;
    if((result = Init()))
        return result;
    if((result = SetTemperature( 30 )))
        return result;
    return SetVoltage( 5 );
}

Using the extra parentheses () around the assignment to suppress a compiler warning.

I don't check for expr != ERROR_SUCCESS because that's equivalent to expr in a boolean context.

If there are really a lot of those calls, consider investing in a preprocessor macro.
Don't forget to undefine it after use if the compilation unit is not at an end.
Also, many really don't like those.

#define OkOrReturn(a) do{int result = a; if(result) return result;}while(0)
#undef OkOrReturn


Installing charts in parallel using go routines

The code is ignoring the return values from the go routine
The WorkGroup isn't used to block until completion

// 1. Perhaps you'd want to have a separate channel to communicate the errors.
var errCh := make(chan error, len(charts))
for _, chartInstallation := range charts {
    wg.Add(1)
    go func(errCh chan error){
       installed, err := installChart(&wg,chartInstallation, releaseName, actionConfig, clientGetter, settings, log)
       if err != nil {
           errCh <- err
       }
    }(errCh)
}
// 2. Wait for the wait group to complete
wg.Wait()
// 1. Collect the errors
for err := range errCh {
    fmt.Println("Error: ", err)
}


Handling objects and arrays simply in this tagging library

The solution is to have contents always be a list. If we don't want to impose this onto the caller of the constructor, we have to use a variable number of arguments:

def __init__(self, name, *contents, **attrs):
   ...

Now the functions can be called as table(tr(td('d1'), td('d2')), tr()) or more generally:

foo("name", child1, child2, ... attr1=value, attr2=value, ...)

Then inside the function, contents will be a tuple and attrs a dictionary.

Otherwise, I find your inappropriate usage of OOP unnecessary. For example, the class n does not really add value, and violates the Liskov Substitution Principle – the constructor signature is incompatible with the parent class. Instead, use closures to provide a default argument:

def namedtag(name):
    return lambda *contents, **kws: tag(name, *contents, **kws)


Fast insert, fast removal and fast access object pool C++ container

Define exactly what properties you want your container to have

You say:

  As you can see, with usual STL containers, you can't have O(1) performance and low memory footprint everywhere.

That's not so much a property of STL, but of container structures in general. You only get O(1) performance if you don't have to search and don't have to shuffle memory around, and if you can't shuffle memory around you can't have a low memory footprint. So you have to make some compromises.

You don't mention what you want to optimize for, or what kind of usage patterns you are expecting. It would be good if you could write down (for yourself) what exact properties you want your container to have, and then verify whether your implementation actually has those properties.

Your metadata uses storage as well

Your container has a vector<T> with the actual data, which is quite efficient. However, there is also metadata. In particular, there is vector<int> index, which you never shrink. So this means that if you have an access pattern where there is a short spike where a lot of data is stored in the container, then after the spike the data itself doesn't use a lot of space, but the vector of indices is now very large. Especially if T is small, then the overhead of the indices and availability queue might be very significant.

Note that you also never shrink index, even if it is possible to do so (whenever tail indices are unused).

Adding to a vector<> is amortized O(1)

Adding items to a vector<> might cause memory allocations and moves, so the time used for an addition is variable, and does not have an upper bound. Whenever the STL has to reallocate memory for a vector<>, it basically doubles the size, so with a constant rate of addition, it needs less and less reallocations. The result is that the amortized cost is O(1). However, be aware that this container might not be suitable for a real-time system.


Do you really want to go recursive on this? Binary trees in the worst case may be a linear list. A better idea is to do some thing like this:

getNodesPerDepth(rootNode) {
    list.add(rootNode); // Start with the root node,
    dlst = new List() // depth lit
    while(list.size() != 0) {
        nextlst = new List(); // make a list of children to iterate next phase.
        for(e : list) {
          for (c : e.children())
             nextlst.add(c);
        }
        dlst.add(list);
        list = nextlst;
    }
    return dlst;
}


I think this would be more useful if  the user could specify an interval and how many times he wants to retry like:

public static Try Repeat(int dalay, int count)
    => new Repeat(Enumerable.Repeat(delay, count));

or if he could specify a count and the increment function:

public static Try Repeat(int count, Func<int, int> increment)
    => new Repeat(Enumerable.Range(1, count + 1).Select(x => increment(x));

where the increment could be:

x => x * 20

I wouldn't provide such members as Fast or Slow because they are very subjective and what for you currently is slow might be in my application still too fast.

Never does not make any sense ;-) Why should I want to never try to execute something? I might as well not write the code at all if it shouldn't run :-P

One more thoght. How about specifying the retry strategy via a generic argument:

class SlowTry : Repeat
{
    public SlowTry() : base(0, 500, 1500, 4500, 12000) { }
}

the  Try becomes this:

public abstract class Try
{
    ... stays the same

    public static void Execute<TStrategy>(Action action) where TStrategy : Try, new()
    {
        new TStrategy().Execute(action);
    }
}

use:

Try.Execute<SlowTry>(() => File.Copy(@"c\a.txt", @"c:\b.txt"));

This way the user can easier specify his strategy.


Building a string representing 50+ ActiveDirectory options

You can put the switch-cases into a dictionary to reduce the boilerplate case and break. The foreach and the string concatenation part can also be reduced with string.Concat(...) or string.Join(delimiter, ...):

public string GetUserAttributes(UserPrincipal user, ActiveDirectoryUserAttribute[] attributes)
{
    var userAsDirectoryEntry = (DirectoryEntry)user.GetUnderlyingObject();

    var getters = new Dictionary<ActiveDirectoryUserAttribute, Func<object>>();
    getters[ActiveDirectoryUserAttribute.AccountExpirationDate] = () => user.AccountExpirationDate;
    getters[ActiveDirectoryUserAttribute.AccountLockoutTime] = () => user.AccountLockoutTime;
    getters[ActiveDirectoryUserAttribute.Assistant] = () => userAsDirectoryEntry.Properties[AttributeAssistant].Value;
    getters[ActiveDirectoryUserAttribute.BadLogonCount] = () => user.BadLogonCount;
    // ...

    // just concat them directly, like you are doing now
    return string.Concat(attributes.Select(attr => getters[attr]()));

    // or, you can separate them with a comma, or anything :
    return string.Join(", ", attributes
        .Select(attr => getters[attr]()));
}

You can also use the collection initializer for dictionary to cut down some letters :

var getters = new Dictionary<ActiveDirectoryUserAttribute, Func<object>>
{
    // C# 6
    [ActiveDirectoryUserAttribute.AccountExpirationDate] = () => user.AccountExpirationDate,
    [ActiveDirectoryUserAttribute.AccountLockoutTime] = () => user.AccountLockoutTime,

    // older version
    { ActiveDirectoryUserAttribute.Assistant, () => userAsDirectoryEntry.Properties[AttributeAssistant].Value },
    { ActiveDirectoryUserAttribute.BadLogonCount, () => user.BadLogonCount },

    // ...
};

Personally I prefer the C# 6 collection initializer the most, second by the method shown in first snippet, and lastly the older initializer.


One thing that immediately pops out (and happens a lot with beginner Haskell programmers, IME):

s2 = sum $ map sumDigits $ map (*2) es

This means (reads as for me) "map (*2) on es, then map sumDigits on it, then sum the numbers."

What you typically want to do is to stay on the "function side" on things as long as possible:

s2 = sum . map sumDigits . map (*2) $ es

Meaning you compose as much as you can, and put only one application at the end. That makes it easier to eta-reduce and in general is considered more idiomatic.

You could also compose the mapped operation, bringing it down to classic "map-reduce" scenario (where "map" part is sumDigits . (*2), and "reduce" part is the sum).

s2 = sum . map (sumDigits . (*2)) $ es

I'd also flip the order of Valid and Invalid:

data Validity = Invalid | Valid deriving Eq

This way, when you derive Ord, Valid > Invalid, which is sometimes helpful and in general you'll see that it holds "intuitively", for Maybe (Just _ > Nothing), Either (Right _ > Left _) and similar values.


Project Euler 22: Names scores by Loki 2

std::accumulate with a lambda is quite a bit more complicated than writing out the range-for-loop manually, and it isn't even more concise:

long result = 0;
for(char c : name)
    result += c - 'A' + 1;
return result;

Using a std::set instead of a std::vector and sorting it once manually after reading everything in is possibly a bit less efficient. The really interesting part though is that duplicates are silently discarded, and the problem-statement doesn't seem to allow that.
Your range-for-loop in main needlessly copies every string. Better go for references even though that's slightly longer:

for(const auto& name: names)

Inserting a single char instead of a length-1 string is probably slightly more efficient.


Showing/hiding deletion buttons in a grid view

Use a single selector instead of "find" and "not." Leave the find, this is faster in every browser except opera (see comments).

For the 2nd part of the selector, you can use the "sibling" combinator ~ to grab everthing except its first operand, and the :first-child pseudoclass selector to get the first child, giving you the same set of elements without using several jQuery methods. This is faster than using not(':first') in all browsers, and faster than a single selector (e.g. not using find either) in all browsers except Opera (which maintains its native-selector edge). See this test.

Note: #someTable tr will also return tr elements from a nested table. You really want to target the direct row descendants of the table. But don't forget about tbody, which is a required element. So this probably should be "#divTab2GridInquiries > tbody > tr:first-child ~ tr". But that is a mouthful... and it's really slow. If you have no nested tables it will work fine as coded below.

$.each($("#divTab2GridInquiries").find("tr:first-child ~ tr"), function () {
    var tr = $(this);

Not sure what  you're doing here - the selector is using a wildcard match, but val only operates against the first element in a selection set. Can you target this element more specifically? In any event, instead of wildcard matching the id, add a class and select on that. Classes are much faster than substring matching attributes.

        //var val = tr.find("input[id*='hdnLineStatus']").val();
        var val = tr.find(".hdnLineStatus").val();

IDs are supposed to be unique. I'm not sure why you would have to target it this way. But using an attribute selector like this will definitely be slower than a regular ID or class selector. If these ids are really unique then just use #divBtnDelete. I suspect that they aren't and you're creating invalid html. Get rid of the ID an add a class.

        // var btnDelete = tr.find("div[id='divBtnDelete']");
        var btnDelete = tr.find(".divBtnDelete");

        //var btnTobeDeleted = tr.find("div[id='divBtnTobeDeleted']");
        var btnTobeDeleted = tr.find(".divBtnTobeDeleted");

This set of ifs should be a switch, but that's probably not slowing you down nearly as much as the selectors.

        if (val == "N") {
            btnDelete.hide();
            btnTobeDeleted.hide();
        }
        if (val == "S") {
            tr.css("background-color", "#99FF99");h
            tr.find("input").css("background-color", "#99FF99");
            btnDelete.show();
            btnTobeDeleted.hide();
        }

        if (val == "D") {
            tr.css("background-color", "#FFFF99");
            tr.find("input").css("background-color", "#FFFF99");
            btnDelete.show();
            btnTobeDeleted.hide();
        }

Use a class again.

        //From user rights
        //if ($("input[id*='hdnTab2ShowDelete']").val() != "Y") {
        if ($(".hdnTab2ShowDelete").val() != "Y") {

            btnTobeDeleted.hide();
            //btnDelete.show();
        }
    });


Recursive function to find the number of ways a number can be generated out of a set of numbers

I'm assuming in this answer that you have infinite quantities of the designated numbers at your disposal, since that appears to be the way your code works. With that condition, this problem is the coin sums problem on Project Euler: given a set of coin denominations, how many ways can change be made for a number?

Looking at your code in terms of efficiency, the top-down recursive function is doing a lot of repeated work because of overlapping subproblems, similar to the recursive Fibonacci problem and is the hallmark of dynamic programming.

The biggest improvement available to you is using a memo or cache in the form of an associative array. Memoization makes it possible to keep track of what's already been computed for a given recursive call and avoid recomputations, pruning off huge chunks of the call tree. This effectively turns the exponential O(nk) problem into O(nk) [source] where k is the number of coins.

There's also a bottom-up iterative version which is an improvement still over the "recursion with cache" version. I recommend adding a cache to your algorithm as above, solving the Project Euler problem and spending some time perusing the solution thread that you'll gain access to which contains many imaginative and efficient solutions including these bottom-up versions.

In terms of coding style, there are variables and loops that can be removed. Moving "set up" code out of the recursive call and into a wrapper can save a few conditional checks and eliminate the level variable. Doing an array_search through your coins array and setting used elements to 0 is a bit awkward and can be handled easily by passing an index variable to determine which coins have been used already. The full function header I used has 4 parameters (including the index and a reference to the memo), which makes it nice to wrap.

Lastly, your base case checks need only happen for being out of money. When that happens, either you've made change successfully, or the change you tried to make wasn't valid (you went into negative numbers). No need to test anything else. All told, the whole program can be 30 lines or less.

I'd like to post my PHP code here, but in the spirit of Project Euler, you'll have the most fun if you solve it yourself instead of reading a spoiler! We can compare notes afterwards if you want (although the solutions you'll see in the forum will be far superior).


Validate your text argument. This causes an ArgumentNullException in Regex.Matches:

((string)null).ParseCommandLine();

It would be better to check the argument before passing it on:

if (text == null)
{
    throw new ArgumentNullException(nameof(text), "Command line arguments cannot be null");
}

Why is this better? The stack trace is more meaningful because the error is thrown closer to where the problem call is and you can supply your own context specific error message. Either that, or you can return an empty array for null.

Properties should be PascalCase - including anonymous types. lastChar should be LastChar and the same for the rest.

result should be plural as it is a collection: Results.

Use default() to get the default value, it signals intent better than a literal ('\0' == default(char)).

Name your constants! E.g. the double quote and the space. A single space is the most difficult thing to read in source code (in my experience).

I think this is good code (all the above is pretty minor). I'd never thought of using Aggregate over a string for simple parsing before :)


The main issue I can see, is the excessive use of generic data types like tuples and dictionaries instead of domain classes. That may be a matter of taste, but I prefer meaningful named domain classes like your Account class.
In the Account class, the dictionary is exposed as public member. IMHO internal data structures should be encapsulated. The class should be extended by appropriated methods to manipulate that data structures. That would automatically move code like

if (debtors.ContainsKey(transaction.Item1))
{
    debtors[transaction.Item1] += transaction.Item2;
}
else
{
    debtors.Add(transaction.Item1, transaction.Item2);
}

into the domain class. Imagine use have to add items somewhere else, that kind of code must be duplicated each time.

Instead of

if (!beneficiary.Equals(transaction.Item1))
{
    ...
}

You could use

 if (beneficiary.Equals(transaction.Item1))
 {
     continue;
 }

 ....

to reduce nesting.

The instance variable debtors should be read-only.
Another small point: I would use strings to store the users because you can store names and you do not run into problems if the group becomes greater than 26 persons :P - of course, that is not relevant for the algorithm.

Generall Approach

Your approach is, to build up two dictionaries (the ledger and the debtors within the account class). The data structure of nested dictionaries matches the requirements exactly. If the requirements change, you have to restructure your whole code.

It is better to transform the data in a simple generally usable data structure and implement your algorithm for that data structure.

Such a simple data structure may be a list of Transactions:

public class Transaction
{
    public Transaction(string payer, string payee, int amount)
    {
        Payer = payer;
        Amount = amount;
        Payee = payee;
    }

    public string Payer { get; }
    public int Amount { get; }
    public string Payee { get; }
}

The algorithms could be implemented in a class like Bank:

public class Bank
{
    private readonly List<Transaction> myTransactions = new List<Transaction>();
    private readonly HashSet<string> myPayers = new HashSet<string>();
    private readonly HashSet<string> myPayees = new HashSet<string>();

    public void AddTransaction(string payer, string payee, int amount)
    {
        myTransactions.Add(new Transaction(payer, payee, amount));
        myPayers.Add(payer);
        myPayees.Add(payee);
    }

    public void PrintPayees()
    {
        foreach (var payee in myPayees)
        {
            var trans = myTransactions.Where(t => t.Payee == payee);
            Console.WriteLine($"User {payee} owes ${trans.Sum(t => t.Amount)} total:");
            foreach (var groupedTransaction in trans.GroupBy(t => t.Payer))
                Console.WriteLine($"- ${groupedTransaction.Sum(t => t.Amount)} from {groupedTransaction.Key}");
        }
    }

    public void PrintPayer()
    {
        foreach (var payer in myPayers)
        {
            var trans = myTransactions.Where(t => t.Payer == payer);
            Console.WriteLine($"User {payer} gets ${trans.Sum(t => t.Amount)} total:");
            foreach (var groupedTransaction in trans.GroupBy(t => t.Payee))
                Console.WriteLine($"- ${groupedTransaction.Sum(t => t.Amount)} to {groupedTransaction.Key}");
        }
    }
}

Usage base on the list of tuples:

void Main()
{
    var bank = new Bank();

    foreach (var transaction in new[] { Tuple.Create("A", 100, new [] { "A", "B", "C", "D" }),
                                        Tuple.Create("D", 500, new [] { "B", "C" }),
                                        Tuple.Create("B", 300, new [] { "A", "B", "C" }) })
    {
        var payer = transaction.Item1;
        var amount = transaction.Item2;
        foreach (var payee in transaction.Item3)
            if (payee != payer)
                bank.AddTransaction(payer, payee, amount);
    }

    bank.PrintPayees();
    bank.PrintPayer();
}


I would advise not to use a different CustomerSearch per search criteria.
As your functionality will evolve you could need a CustomerSearch that is using the country the Customer is from.
But what if you want to search on the Country in combination with part of the name?
Soon you will be combining different search criteria together which will require one smart CustomerSearch bean.


I would probably combine these two if clauses:

elif userInput>100:
    print("Our guess range is between 0 and 100, please try a bit lower")
elif userInput<0:
    print("Our guess range is between 0 and 100, please try a bit higher")

To:

elif user_input > 100 or user_input < 0:
    print("Our guess range is between 0 and 100, please try again")

Trusting that the user is clever enough to realise that if he entered 1000 (which is still visible in the line just above this output), that he is too high for range(1,101).

Incidentally, there may be a small bug in your program:

random.randrange(1,100)

will never generate 100, just like range(1,100) will only give you the numbers from 1 to 99, inclusive. But you also allow the user to guess 0 or 100.

Use either of these two:

random.randrange(0,101)
random.randint(0,100)

The latter actually does return an integer N, such that a <= N <= b

Your program will crash if the user enters any non-number. Better use something like:

while True:
    try:
        user_input = int(input("Your guess please: "))
    except ValueError:
        print("Please enter a number")
        continue
    if user_input == random_number:
        print("You win")
        break
    elif user_input < 0 or user_input > 100:
        print("Our guess range is between 0 and 100, please try again")
    elif user_input < random_number:
        # Notify user
    elif user_input > random_number:
        # Notify user

Which will ask the user until a valid number is supplied. You can also put all the other checking code in there as well.


follow-up review of a custom Undo Manager

I think you should not clear _redoCommands stack when you are re-doing command. Actually you should be able to continue re-doing command until you will restore state when you called first undo command. You should clear redo-commands when completely new command arrives:

public void ChangeState(Command command)
{
    command.Execute();
    _undoCommands.Push(command);
    _redoCommands.Clear(); // new command arrived, you cannot redo anymore
}

public void RestorePreviousState()
{
    if (!_undoCommands.Any())
        return;

    var command = _undoCommands.Pop();
    command.Undo();
    _redoCommands.Push(command);
}

public void RedoPreviousState()
{
    if (!_redoCommands.Any())
       return;

    var command = _redoCommands.Pop(); // commandPop a little strange name :)
    command.Execute();
    _undoCommands.Push(command);
}

Also I'm thinking on improving naming... because RestorePreviousState() looks like restoring state which was before last state change - i.e. two call of this method should leave object in initial state.

UPDATE: I'd go with UndoStateChange and RedoStateChange without word previous - I find such terms less confusing. Also I'd think about making public properties for checking available state changes. Because currently it's not clear whether state changed or not. You call UndoStateChange and nothing is returned whether state changed or there is nothing to undo.


LRU cache implementation in C++ using unordered_map and doubly linked list

Code simplification

You don't need to use a custom linked list here. std::list will do fine, too.

You can keep the pairs (key, value) in an std::list and store a mapping from keys to iterators in this list in an std::unordered_map.

Passing by const reference

Passing keys and values by value creates an extra copy, which may be expensive. You can pass them by a const reference to avoid it.

Comments

Redundant comments clutter the code and hurt its readability, for instance:

// move the page to front
m_pageList->Move_Page_To_Front(m_pageMap[key]);

Delete this kind of comments.

API design

if (m_pageMap.find(key) == m_pageMap.end()) {
    return -1;
}

Returning -1 is a terrible idea. Firstly, -1 can be a valid value. Secondly, it won't compile for an arbitrary type of values, so it makes the use of your cache extremely limited.

Here're several ways to fix it:

Change the return type to std::optional<Value>. It works with C++17 only, but you can use boost::optional<Value> with earlier version of the standard.
If neither C++ 17 nor boost is available, you can return something that can either contain a value or be empty (like a smart pointer to a Value).
You can throw an exception if the key is missing.
You can insert a default value for the key and return it.

I prefer the first option as the optional type accurately reflects what may happen: there's either a value or nothing.


Is this method a good candidate for a service layer?

As @Vogel612 hinted, a class shouldn't expose its fields publicly - this:

public class Car
{
    public int Id { get; set; }

    // ...
}

Is equivalent to this:

public class Car
{
    private int _id;
    public int Id
    {
        get { return _id; }
        set { _id = value; }
    }

    // ...
}

As you can see, encapsulation is easily achieved with auto-properties - don't expose your fields!

Method GetPhysicalFileLocation has dependencies on the file system and on an HttpContext, so you definitely want that to be abstracted away, so you can write a test that uses that code and doesn't actually hit the file system.

I'd move it to some IFileSystemService implementation:

public interface IFileSystemService
{
    string GetPhysicalFileLocation(int carId);

    // ...
}

And then make a class that implements it:

public class FileSystemService : IFileSystemService
{
    // load this value from application settings?
    private readonly string _localDirectory = "~\\CarFiles\\";

    public string GetPhysicalFileLocation(int carId)
    {
        var diPath = new DirectoryInfo(HttpContext.Current
                                                  .Server.MapPath(_localDirectory + carId);
    }
}

And now you can have client code like this:

public class MyClass
{
    private readonly IFileSystemService _service;

    public MyClass(IFileSystemService service)
    {
        _service = service;
    }

    public void DoSomething(int carId)
    {
        var fileName = _service.GetPhysicalFileLocation(carId);
        // ...
    }
}

This way you can inject a "fake"/"mock" implementation for IFileSystemService and test DoSomething without hitting the file system or depending on an HttpContext; the key being that depending on the file system and on an HttpContext, is an implementation detail that the client code doesn't need to know about.


Use PreparedStatement to insert into H2 database

There are some things to improve in this code. Especially when it's underlined that "if it can be maintained later on".

SQL query

The columns where the data will be inserted should always be defined, for example: INSERT INTO TASK(id_task, title, creation_time... etc) VALUES(... . It's the same problem as for SELECT *, that should never be used in serious queries. That's because the table definition evolves over time; tomorrow there may be new columns added, other removed or reordered. There is absolutely no warranty that the meaning of what is behind the question marks in the example will be valid after the next feature implemented into the software.
Another reason to define them is just to help yourself: it's very difficult to remember which is the natural order of columns in the table for the thirteen question marks.

PreparedStatement

There is no need to recreate the PreparedStatement instance on each loop. Indeed, one of the reasons they are made for is the possibility to be reused. And their creation is sometimes quite costly.
The third line should come just before the for loop.

Parameter Indices

From the point of view of maintenability, calculating/incrementing the parameter index (j variable) is not safe. It's just almost like the columns ordering issue above. If j is incremented, the order of the lines with parameters setting is crucial and prone to errors. To solve, some readable (local) constants may be introduced, for example:

final int COLUMN_ID = 1;
final int COLUMN_TITLE = 2;

...
sqlState.setInt(COLUMN_ID, id);

Parameters Mapping

There is absolutely no way to know the meaning of the values that are retrieved from the table. Since it looks like a JTable object, here is a way how an explicit mapping can be created.

Define a TableModel by extending, for example, the javax.swing.table.DefaultTableModel and map the values you need with their respective getters:

class TaskTableModel extends DefaultTableModel {
    ...
    public String getTitle(int rowIndex) {
        return getValueAt(rowIndex, 2);
    }
}

When the JTable object is created, set a TaskTableModel instance on it:

JTable table = new JTable(...);
table.setModel(new TaskTableModel());

When setting the parameter values of the PreparedStatement, use the TaskTableModel instance:

TaskTableModel tableModel = (TaskTableModel) table.getModel();
...
sqlState.setInt(COLUMN_TITLE, tableModel.getTitle(i));


HttpClient wrapper for simple calls with optional cert

As is this does not work because multiple requests will concurrently operate on the same variables (instance variables and HttpClient internal state as it is being configured).

This is fairly easy to solve because there's a nice pattern for this. Your core problem is that you need to initialize one expensive object for each instance of a certain kind of key (here: HttpClient and certificate path).

I'm modifying some existing code to ensure that only one HttpClient per key is ever created:

public static class HttpClientManager
{
    private static ConcurrentDictionary<string, Lazy<HttpClient>> _clients =
        new ConcurrentDictionary<string, Lazy<HttpClient>>();

    public static HttpClient Get(string certificatePath)
    {
        return _clients.GetOrAdd(certificatePath, _ =>
            new Lazy<HttpClient>(CreateClient(certificatePath));
    }

    static HttpClient CreateClient(string certificatePath)
    {
        //TODO
    }
}

You only need to fill in the TODO.

This code is thread safe because the infrastructure takes care of only invoking your factory method once per unique certificatePath. The factory will only use local state so that it is totally unconcerned with thread safety.

I'd avoid methods such as void SetUpXxx(...). These messods make use of side-effects for no reason. In particular, _clientHandler seems to be used only as a way to thread this value through the various methods being called. It is often better to avoid passing data in such covert ways. Convert that field to a method parameter and explicitly pass that value around. I'd do the same thing for _client itself. Then, you can keep the SetUpXxx methods but they become static. It will be explicit what data they consume and what they output.

This might seems like a subtle point but I found this kind of change helpful over and over again.


using namespace std is not preferred, although not that bad for small programs.
Each variable should be declared/initialized on separate lines.  This improves readability and also makes it easier to add any necessary comments.

unsigned i;
unsigned k = 0;
unsigned n;

Same with this:

cout << "n= ";
cin >> n;

Prefer "\n" to std::endl here (the latter flushes the buffer, which takes longer).  It's still okay to use the latter where both flushing and newlining are needed.
Always use descriptive names for variables.  Single-characters are best for loop counters (such as i).  This will vastly improve readability as you won't need comments to describe them.
It looks like you could use recursion instead of all these loops.  It may take longer (if you input a large number), but it should at least simplify the logic.


Calculate the crc32 of the contents of a file using boost

You seem to be missing a seek to the end.

This will always be zero.

    std::ifstream is{fp, std::ios::in | std::ios::binary};
    size_t file_size = is.tellg();

You need to add a seek to end:

    std::ifstream is{fp, std::ios::in | std::ios::binary};
    is.seekg(0, std::ios::end);
    size_t file_size = is.tellg();

There are other functions that query the file system to get the size. But You should note this does NOT do a scan of the file it just moves the descriptor to the end. So its not like reading the file.

You could just wrap it.

std::size_t fileSize(std::ifstream& file)
{
    std::streampos current = file.tellg();
    file.seek(0, std::ios::end);
    std::size_t result = file.tellg();
    file.seek(current, std::ios::beg);
    return result;
}

Now your function becomes:

std::uint32_t crc32(const std::string &fp)
{
    std::ifstream is{fp, std::ios::in | std::ios::binary};
    std::size_t file_size = fileSize(is);

    std::vector<char> buf(file_size);
    is.read(&buf[0], file_size);

    boost::crc_32_type result;
    result.process_bytes(&buf[0], file_size);

    return result.checksum();
}

The problem with this is that some files are huge. You don't want to read the whole thing into memory like that. So you could define a reasonable size buffer and read chunks at a time.

 std::vector<char>   buffer(4096);

 while(is.read(&buffer[0], buffer.size()))
 {
     std::size_t count = is.gcount();
     result.process_bytes(&buffer[0], count);
 }

Or you could use a memory mapped file:

Its been a while since I did this. Here are some instructions.

https://www.safaribooksonline.com/library/view/linux-system-programming/0596009585/ch04s03.html


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

Make sure to #include all required headers

This program refers to std::vector and std::thread but does not include the corresponding headers.  Fix that by adding these lines:

#include <thread>
#include <vector>

Check return values

The function rdx.connect() can fail.  Your program should check the return value and handle the case in which it does.

Understand your data structures

The std::vector is used appropriately except for the peculiar call to pool.empty() at the end of the code.  The purpose for empty() is to check to see if the vector is empty, not to empty the vector.  In any case, it's not necessary to empty it since it will automatically be destroyed when it goes out of scope at the end of main().

Understand the thread pool pattern

The question describes this as a "thread pool" but that's not what I see here.  It's not a finite set of threads doing some other number of tasks; rather it's one function being called once for each thread.  While this is multithreading, it's not a thread pool.  To keep from confusing yourself or others, it's useful to use common terms in the usual way.

Avoid concurrency problems

Any time multiple tasks run in parallel, we have to take extra care to assure that things work correctly.  In particular, my_cool_function() claims to "do stuff with rdx", but rdx is a single global variable.  The code for that function isn't shown, but it's highly likely that some form of locking will be required to avoid problems with concurrent access to the single global object.

Omit return 0 at the end of main

The compiler will automatically generate a return 0; at the end of main so it is not necessary to supply your own.


I don't like how you have all your logic in the header file.  You should declare your methods and fields in the header and use the .cpp file for logic.

On the other hand, C++ is not strictly object oriented, the way C# and Java are.  You didn't need a class for this solution, you could just have called fibHelper() from main().

Third point is your naming.  fibHelper() actually isn't a helper function, it is the function that actually calculates the Fibonacci sequence.  fibR() actually isn't recursive, like your comment says, it calls the recursive function.  int x1 doesn't say what it actually does, although it is easy to guess because the program is only a couple lines long - in a large project, this could (and probably would) cause many weeks of time wasted catching bugs.

Fourth is consistency:

static int fibR(int limit = 1000)
static int fibSumEven(int limit=1000)

For the most part, you are consistent, and I like how you use spaces around your operators and braces on your one-line ifs.


Compound assignment operators in Python's NumPy library

Ben,

The following modification to your code is a more accurate reflection of my larger problem:

    from timeit import timeit
    import numpy

    # Dimensions
    ROWS = 10000000
    SAMPLES = 10000
    COLS = 4

    # Number of times to run timeit
    TEST_COUNT = 100

    # Matrices
    a = numpy.zeros((ROWS, COLS), dtype='uint32')
    b = numpy.zeros((ROWS, COLS), dtype='uint32')
    c = numpy.zeros((ROWS, COLS), dtype='uint32')

    # Indices
    i = numpy.random.random_integers(0, ROWS - 1, SAMPLES)
    j = numpy.random.random_integers(0, COLS - 1, SAMPLES)

    # Fancy
    def fancy():
        a[i,j] += 1
    print "Fancy:", timeit("fancy()", setup="from __main__ import fancy", number=TEST_COUNT)

    # Loop
    def loop():
        for k in xrange(SAMPLES):
            b[i[k],j[k]] += 1
    print "Loop:", timeit("loop()", setup="from __main__ import loop", number=TEST_COUNT)

    # Flat
    def flat():
        flatIndices = i*COLS + j
        sums = numpy.bincount(flatIndices)
        c.flat[:len(sums)] += sums

    print "Flat:", timeit("flat()", setup="from __main__ import flat", number=TEST_COUNT)

    # Check that for_loop and custom are equivalent
    print "Equivalent:", (c == b).all()

With the exception that there are probably few samples that are actually repeated in this version. Let's ignore that difference for now. On my machine, your code gave the following timings:

    Fancy: 0.109203100204
    Loop: 7.37937998772
    Flat: 126.571173906
    Equivalent: True

This slowdown is largely attributable to the large sparse array output by bincount().


I think, you don't need tables client_reservation and reservation_rooms. You have tables clients and rooms, and then, to make a reservation, you need only one table - reservation (I prefer to give table names in singular form). This table will reference to a client and to a room, and the reservation period (start date/end date). Also, you forgot about the actual state of the room - it could be just booked or busy. I would propose to create a new table - status, and reference it from reservation. The table status could contain the following values:

booked - when a client booked the room
busy - when a client came to the hotel
canceled - when a client didn't come at time and room became available for other guests
unavailable - for example, when a room needs a renovation and/or repair of equipment
etc.

Also, a billing is mentioned in the task. It is a very wide area, to fully support it, you may need a lot of tables to store the data about billing plans (a room can have different prices depending on a season, a category, available equipment, a client type, a view from the window, the number of the floor, etc.).


Finding numbers whose product of the digits are perfect squares

Compile time really shouldn't be an issue. Right now, I would focus on readability, and then maybe runtime performance.

Variable names

Normally, I really dislike short variable names. In this case it's ok for A, B, and K, because they are part of the question. But if you do use the same variable names as in the question, you should probably do it consistently: cases should be T.

For the other variable names, you have no excuses: temp isn't a good name, and caseNum vs cases is also somewhat confusing. The worst is probably k, as you already have K.

Perform Action on Number

Instead of num = num/10; you can write num /= 10, instead of product=-1; you could write product--, and instead of product = product*temp.get(j); it could be product *= temp.get(j);. Your way isn't necessarily bad, but the alternatives are more common and easier to read.

Declare variables where they are used

You are declaring double sqrt; a lot earlier than you need sqrt, which makes your code harder to read. Same for product.

For loop with two indices

This for loop: for(long i=A,k=0;i<=B && k<(B-A+1);i++,k++) is extremely hard to understand.

Luckily, you can just remove k. The stop condition is already covered by i.

Enhanced for loops

If you use for (Long currentTemp : temp) { you can get rid of the j variable.

Functions and Tests

main really should only be responsible for starting your program, nothing else. Extract the code to a separate function, that way, you can also easily test it. To use unit tests, it would also be useful if you returned a result from a function instead of printing it directly.

You should also extract other functionality to its own function. For example, everything inside the while loop could go in its own function.

Different Approach

When getting a question like this, I wouldn't put everything in one big method. If you read the question, it becomes obvious that you need something to create the product of digits. So create a product method. You also need something to check if a number is a perfect square, so create that method as well (isPerfectSquare). Lastly, create a method to check if a number contains zero (containsZero).

Then, just create the main method and combine everything:

public static long run(long A, long B, long K) {
    int satisfiedConditionCount = 0;
    for (long i = A; i <= B; i++) {
        if (!containsZero(i) && isPerfectSquare(product(i))) {
            satisfiedConditionCount++;
            if (satisfiedConditionCount == K) {
                return i;
            }
        }
    }
    return -1;
}

public static long product(long number) {
    long product = 1;
    while (number != 0) {
        number /= 10;
        product *= number % 10;
    }
    return product;
}

public static boolean isPerfectSquare(long number) {
    int sqrt = (int) Math.sqrt(number);
    return sqrt * sqrt == number;
}

public static boolean containsZero(long number) {
    return String.valueOf(number).contains("0");
}

Now the code is a lot more readable, and because it is in separate functions, you could profile it to find bottle necks, and then improve on those.

Another added benefit of separate functions (apart from the readability, reusability, and profiling) is that you can test them separately.


Priority checker for infix-to-postfix converter

There is duplicated code that can be removed.

static int precedence(char operator) {
    switch (operator) {
      case '*': case '/':
        return 2;
      case '+': case '-':
        return 1;
      default:
        return 0;
    }
}

int hasLowerPriority(char operator, char otherOperator) {
    return precedence(operator) < precedence(otherOperator);
}

At that point, you might as well get rid of the hasLowerPriority() function altogether, since precedence(operator) < precedence(otherOperator) is clearer and more readable.

(Note that operator is a reserved keyword in C++, but not in C.  You might want to rename it to op or something.)


DAO for fetching organizations and departments through a REST API

On the advise of a person from reddit here : Java code refactoring, in order to get rid of code duplication

I tried something like this :

private <T0, T1 extends ResourceSupport<T0>> List<T0> getResources(Class<T0> clazz1, Class<T1> clazz2, String path, GenericType<Resources<T1>> genericInstance ) {
    List<T0> results = new ArrayList();
    Client client = ClientHelper.createClient();
    Resources<T1> response = client
            .target(restApiRoot + path)
            .request(MediaType.APPLICATION_JSON)
            .get(genericInstance);
    List<T1> resources = response.getContent();
    for (T1 resource : resources) {
        results.add(resource.getEntity());
    }
    return results;
}

@XmlRootElement
@Getter
@Setter
public class OrganizationResource extends ResourceSupport<Organization> {

    @XmlElement(name="organization")
    private Organization entity;

    @Override
    public Organization getEntity() {
        return entity;
    }
}

@XmlRootElement
@Getter
@Setter
public abstract class ResourceSupport<T>  {
    @XmlElement(name="link")
    private List<Link> links;

    public abstract T getEntity();
}

Called like this :

GenericType<Resources<OrganizationResource>> genericInstance = new GenericType<Resources<OrganizationResource>>(){};
List<Organization> list = getResources(Organization.class, OrganizationResource.class, "organizations", genericInstance);

For information, the rest api response is :

{
  "links": [],
    "content": [
        {
            "organization": {
                "id": "GES",
                "code": "GES",
                "name": "GES XX1",
                "legalNumber": "654654654"
            },
            "links": [
              {
                  "rel": "self",
                  "href": "https://server:8443/api/organizations/GES"
              },
              {
                  "rel": "organizations",
                  "href": "https://server:8443/api/organizations"
              },
            ]
        },
        {
            "organization": {
                "id": "PRO",
                "code": "PRO",
                "name": "PRO XX1",
                "legalNumber": "54545646"
            },
            "links": [ ... ]
        ...
    ]
}


Effective way to remove white spaces from string

General Comment
Stop trying to re-invent the wheel.
Or at least go look at a more interesting wheel that has not been optimized to the point were you can't do better.
Code Review
You are calling std::end() every iteration of the loop. Its not a very ineffecient call. But its still doing work they you probably don't need to in most containers.
    while (it != std::end(c))

The standard erase-remove idiom does not need to do this because it works out what it needs to remove first. Thus saving this cost (even if it is very small).
This does not work on all container types (in pre C++11):
             it = c.erase(it);

On containers like std::vector the erase(it) is very expensive. As you have to move all the elements down by one place each time you call erase. This is why the erase-remove idiom does it the other way. It moves elements down as many places as they need to go in a single shot without having to do multiple copies (one move per element).


Calculate different speeds between min and max speed with a stepsize

First off, you should capture this functionality in a dedicated method, rather than in the class' main method.

Secondly, I'm not sure why you want an array of String. I don't know the context, but as you're already calculating with speeds, it seems likely you'll calculate more with them further on, and you'll want them to be numbers again.

Next, your method of doing this is appending everything in one giant String, and then splitting it again, after dealing with an unnecessary separator at the end. Looks like a lot of work for nothing. You can just add everything to an array directly (you'll have to precalculate its size beforehand though)

Java 8 has IntStream, which is ideal for this task. It enables the one-liner you're looking for.

private int[] allSpeeds(int lower, int upper, int step) {
    return IntStream.iterate(lower, i -> i + step)
            .limit(Math.max(0, ((upper - lower) / step) + 1)) // limit to the needed size, ensure this value cannot be negative
            .toArray();
}


PHP function to check if something valid or return error message

Simply , the method isTodayWithinDateRange can throw the exception in this case since the responsability of the method is to check the constraint .
So , i think that you can try it as :

function isTodayWithinDateRange(\DateTime $start, \DateTime $end) {
  $now = new \DateTime();
  if($now < $start) throw new Excception('Today is before the start date') ;
  if($now > $end) throw new Exception('Today is later than the end date');
  return true;

}

First , start with case where you are looking to throw exception , in this case , it's not clearly , but think about a case where you have a lot of logic , here you should start with cases where you don't need to manipulate your logic (like if the argument is null , or missing ...) .

Call you  method as :

$myStart = new Datetime('01-06-2012');
$myEnd = new Datetime('01-06-2020');

// loop

try{

if(isTodayWithinDateRange($myStart, $myEnd)) {
 echo 'contraint validated';

}
}catch(Exception $e){

    echo $e->getMessage();
}
//end loop

I hope this help you .


Check if path exists directed graph, without using collection

Performance

HelperClass used a fix amount memory, due to the predetermined array size. This looks like a waste.

Single responsibility principle

HelperClass is used in 2 different ways:

As a queue, that can grow at its end and shrink at its beginning
As an array to store the neighbors of each vertex

I suspect this dual use has lead to the terrible meaningless name of this class.

Instead of doing different things, it's recommended to design classes that do one thing and do it well. This is called the single responsibility principle, one of the first crucial considerations when creating a new class.

If you want to write your own queue, that's fine, but focus on its most important responsibility, which is efficient push, poll, isEmpty operations.

When your class has a single responsibility, naming becomes easier too, often obvious.

For the storage of neighbors, it's unclear what you really need. You haven't shared how they are initialized, so it's impossible to comment on that. A fixed array might be good enough, who knows.

Pointless Graph constructor

The constructor initializes the vertices empty, with no neighbors. That seems rather useless. Perhaps you want to move the functionality of the setAdjacencyList method inside the constructor.


Read output from a subprocess executed by Python

First of all, you have a bug.  You gave stderr=subprocess.STDOUT.  That means exactly what it says: stderr will be redirected to stdout.  Because of that, stderr will always be None and stdout will be assigned to whatever the errors are.  Test it yourself with something like ls --qaz.  What you should have said is stderr=subprocess.PIPE.

It is difficult to do a comparative review because the two functions do not do quite the same thing.  I will, however, do a review of the second function.

I don't see a need to create a temporary return_code variable.  Just check if proc.returncode: instead.

You don't account for the cases when there is an error.  What you used in the first function looks pretty good.  I would use a different exception class so that functions that call this function can handle the different types of exceptions in different ways.

File objects are iterable.  That means that your last loop can be shortened to this:

for line in proc.stdout:
    yield line.strip()

That prevents reading all of the lines into memory.  You could also use map(), though it wouldn't be very efficient in Python 2 (because it creates a complete list instead of a generator):

return map(str.strip, proc.stdout)

Another option is a generator expression:

return (line.strip() for line in proc.stdout)


Current year

If you don't want the current year to be hardcoded, you could use the method today() from datetime.date.

from datetime import date
current_year = date.today().year

User input

You should always put your user input request in a try/except block, because you never knows what the user will think and do. I'd go with:

def ask_for_birth_year():
    while True:
        try:
            return int(raw_input('Enter Year Of Birth: '))
        except ValueError:
            print('This is not a number, try again.')

This way it will keep asking until the user enters a proper number.

UPDATE (following comment) :

If you need some restriction on the input number, you could try this kind of structure :

def ask_for_birth_year():
    while True:
        try:
            nb = int(raw_input('Enter Year Of Birth: '))
            if nb < 0:  # can be any condition you want, to say 'nb' is invalid
                print('Invalid year')
            else:  # if we arrive here, 'nb' is a positive number, we can stop asking
                break
        except ValueError:
            print('This is not a number, try again.')
    return nb

Other remarks

Since age is an integer, you'll prefer using %d instead of %s (strings) in your print call.

mytext = 'You are %d years old.'

It is also recommended that you put all level-0 code under a __name__ == '__main__' condition, to avoid having it launched later when you import this module. This is a good habit to take, you can read about it in the brand new StackOverflow Documentation here.

if __name__ == '__main__':
    # do stuff

Finally, the limit age (18), is what we call a magic number. It should be avoided, if you plan on making your code grow, and replaced by a meaningful constant.

#at the beginning
LIMIT_AGE = 18

#your 'if' statement
if age < LIMIT_AGE:
    ...

Altogether

from datetime import date

LIMIT_AGE = 18

def ask_for_birth_year():
    while True:
        try:
            nb = int(raw_input('Enter Year Of Birth: '))
            if nb < 0:
                print('Invalid year')
            else:
                break
        except ValueError:
            print('This is not a number, try again.')
    return nb

def print_message(age):
    mytext = 'You are %d years old.'
    print(mytext % age)
    if age < LIMIT_AGE:
        print('YOU SHALL NOT PASS!')
    else:
        print('Welcome To The Portal.')

if __name__ == '__main__':
    year_of_birth = ask_for_birth_year()
    current_year = date.today().year
    age = current_year - year_of_birth
    print_message(age)


using namespace std; // TESTING

Judging by your comment, I'm guessing you're aware about the problems of exposing namespace members in the global scope. But did you know that you can using namespace inside scopes other than the global? It is fine if in your unit tests you want to expose the std stuff to make the code less verbose, but do that in the shortest possible scope then, in this case, inside main():
int main()
{
    // Make an exception since this is a unit test and expose
    // the whole Standard Library inside main(), so we don't have
    // to std:: qualify everything.
    using namespace std;

    // same as before ...
}

 cout << "Destroyed" << endl;  myStack.~Stack();

Very unusual for you to be calling the destructor for myStack. A destructor is called automatically when an object goes out of scope or is deleteed. There are very few cases where a programmer would manually call a destructor, those are not present here. If you just wan't to ensure the object is destroyed before the end of main(), to log some stuff, wrap its declaration inside a new scope. E.g.:
int main()
{
    {
        Stack<char> myStack(3);
        ...
    } // <== ~myStack() called here
}

This way you won't risk ending with a half destroyed object in your hands.

template <typename T>
T Stack<T>::top() const
{
    if (head != nullptr)
    {
        return head->data;
    }
    else return NULL;
    //          ^^^^ problem here!
}

That will not work for a T type that is not a pointer or integer. NULL can be assigned to integers because it is usually implemented as #define for 0. That's one of the reasons why you should use nullptr whenever possible (C++11). If you had used nullptr, your test with T=char would have failed and you would have noticed this problem.
The usual convention for a generic stack is to throw an exception if you try to access the top for an empty stack. Returning a "default" value is less generic and also makes it harder for the caller to detect errors. Returning a default also requires the type T to be default constructible, so don't do it.
Same goes for popping on an empty stack. Right now you are not generating any errors. You should consider throwing and exception. Deriving a StackUnderflow exception type from std::runtime_error might be a good idea. Then you can extend the concept to a StackOverflow error when trying to push to the bounded stack. Granted that you can do with a simple std::runtime_error, but defining custom exception classes is a nice exercise if that's your point for writing this implementation.

cout << "push: "; myStack.push('H'); cout << myStack.top() << endl;

Don't pack that many statements in a single line. People read shorter columns of text much faster. But not just that, mixing several statements together makes it a lot easier for a quick read to miss some important part of it. Put each statement in its own line.
cout << "push: ";
myStack.push('H');
cout << myStack.top() << endl;

Not a huge thing, but usually this kind of data structures uses std::size_t for things like size and capacity. That's an unsigned integer, which makes sense since the stack size is not meant to be negative, however, there is some discussion about avoiding unsigned integers, so that's up to you to decide if it is worth it.

Last thing is a bit of a big subject, which was introduced with C++11, called move semantics. Your code does some unnecessary copying of data on push and StackNode's constructor, which might affect performance when T is something other that a native type or pointer. I'll leave you with a couple references you can read to further learn about this:

SO: What are move semantics?

cppreference.com: Move constructors.


colorprint - An ANSI Escape sequence console writer mini-library

Architecture: IMO, the time for trusting that char * buffers will not overflow is past.  Pass in a size_t size and check for valid sizes in function calls.
static const char *numch = "0123456789"; serves little value and its application can cause UB on unruly input.  Rather than use it convert to digit character, just add '0', offset as needed.  numch[fx - 1] --> fx - 1 + '0'
Global functions that being with _ are reserve for the implementation. Use a different name.

// void _cprint(struct cpoptions *cpo)
void cp_print(struct cpoptions *cpo)

\e is a non-standard escape sequence.  Use \033 or ...

// printf("\e[%s%s\e[0m"
#define ESC 27
printf("%c[%s%s\e[0m", ESC

colorprint.h should have a protective #ifndef  to cope with re-entrantcy.

#ifndef colorprint_h
#define colorprint_h
   ... // existing content
#endif

I found useful enumerating the Nth item

enum color {
    color_invalid,
    color_white,
    color_N  // add
};

if (value >= color_N) Handle_InvalidValue(value);

Nice to have example usage in .h file.  Suggest #if 0 bracketing instead as it does not stop syntax highlighting.
Pedantic: size_t is the type to use for array indexing rather than int.  Code accordingly, remember that size_t is some unsigned type.
Namespace colorprint.h abuses namespace with color_..., fx_..., cp....  Suggest a more uniform prefix.  cp... is not too bad, but then use cp.h.
Avoid magic number - why 30?  Numbers other than -1,0,1,2 and maybe 42 deserve a macro or const object.

char options[30] = "";

Do not include files before "colorprint.h". "colorprint.c" should do this to insure "colorprint.h" is not dependant on some <*.h> file
tidy up, remove /*{{{*/, etc.
Good use of static functions.
Print-like functions should return int.

/// void _cprint(
int  _cprint(
  ...
  int i = printf("\e[%s%s\e[0m", options, cpo->string);
  return i;
}

func is much too common to use as a macro name

// #define func(name, type, ...) \
#define cp_func(name, type, ...) \


Merge Sort implementation with generators and recursion

You don't actually get benefits from using generators in this particular implementation since you are still slicing actual lists having the slices created in memory. And, you also collect the results into a new_l list being created in memory and returned all at once.

You should use iterative islice() like demonstrated in this example. Also, check out this generator-based merge sort implementation - note how the results are yielded from the "merge sort" function.

Some code style related notes:

since you return from the function when len(lis) <= 1, you can omit the else: part and decrease the indentation level of the case when len(lis) is more than 1
improve your variable naming - lis is not a good way to workaround not naming a variable list, over should probably be middle, cRL and cLL should probably become left and right etc.
documentation strings should start with a capital letter and end with a dot, according to PEP8 style guide (reference)
watch for other PEP8 code style violations - specifically, watch for spaces around operators (reference)


Parse a search condition into an expression tree

You don't show how this is being called. So we have to make some assumptions:

I assume that the search conditions have been parsed into tokens as one-token-per-string in the vector? That is, for search conditions like "a + b < 10 OR c = 1" (your example), the tokens vector looks like { "a", "+", "b", "<", "10", "OR", "c", "=", "1" }.
I assume that the node type contains a vector<node *> called subTree.
You also don't specify if you expect the resulting tree to be a binary tree or not. Your code is written that way, but it doesn't seem to be a requirement. Other than the relational operators, the rest of your operators could easily handle more than two operands: a OR b OR c, 1 + 2 + 3, etc. I assume that the tree must be binary, since you coded it that way.

With those assumptions, I observe:

You are not handling the case of a zero-length tokens vector. This would be an empty input, or an error of some kind.
You are not handling syntax errors at all, really. What should your code be returning for something like a + * b?
You are using recursion when it is not necessary. Specifically, your switchDelimiter function is really just a way to hide iteration. It would be better, IMO, to write your code to loop over the delimiters instead of calling a function and then recursing with the same tokens and a new delimiter.
You are using recursion when it is not necessary. Specifically, your "right subtree" case recurses with the same delimiter, and it + 1. That's a sign that you can just continue your existing loop, after updating the parent node to a new value. (You will have to move your "new node" code inside the loop, though.)
 3.


There are 4 foreach loops for the same files, going for a little more complex but more
organaized nested loop would be better, like this

foreach ($_FILES['event-images']['tmp_name'] as $tmp_name) {
    if (!empty($tmp_name)){
        $image = $_FILES["event-images"]["name"];
        $path_info = pathinfo($image);
        if ($path_info['extension'] == 'jpg' || $path_info['extension'] == 'jpeg' || $path_info['extension'] == 'png' || $path_info['extension'] == 'gif'){
            if ($_FILES["image"]["size"] <= $maxFileSize){
                $image_d = getimagesize($image);
                if(($image_d[0] >= $minWidth) && ($image_d[1] >= $minHeight)){
                    $errors[]="valid image";
                }else{
                    $errors[]="invalid dimension";
                }
            }else{
                $errors[]="invalid file size";
            }
        }else{
            $errors[]="format not supported";
        }

    }else{
        $errors[] = 'Please select at least one image.';
    }
}


You don't need to make an initWithType: method. Just override the buttonWithType: factory method.


Can be done in \$O(n)\$ time

You can do better than \$O(n^3)\$ if you think about what kinds of triplets give nonzero contributions.  First of all, any triplet that does not contain a 1 will contribute zero to the final answer.  Next, if you examine all the triplets that contain 1, there are 5 types of triplets that contribute nonzero amounts to the answer:

1 1 1 contributes 3
1 1 2 contributes 2
1 1 X contributes 1, where X > 2
1 2 2 contributes 1
1 2 3 contributes 1

So you can get an \$O(n)\$ solution by counting all the 1s 2s and 3s in the input.  Then you can compute the number of each of the 5 types of triplets above by using simple combinatorics.

Sample \$O(n)\$ solution

Here is a sample solution based on the above.  Notice I removed the entire input array because all that is needed is the counts:

#include <iostream>

int main()
{
    long n   = 0;
    long c1  = 0;
    long c2  = 0;
    long c3  = 0;
    long res = 0;

    std::cin >> n;
    for(long i=0;i<n;i++) {
        long num;
        std::cin >> num;
        if (num == 1)
            c1++;
        else if (num == 2)
            c2++;
        else if (num == 3)
            c3++;
    }

    // Count all the {1, 1, 1} triplets.  There are (c1 choose 3),
    // each contributing 3:
    res += ((c1 * (c1-1) * (c1-2)) / 6) * 3;

    // Count all the {1, 1, 2} triplets.  There are (c1 choose 2) * c2
    // combinations, each contributing 2:
    res += ((c1 * (c1-1)) / 2) * c2 * 2;

    // Count all the {1, 1, X} triplets, where X > 2.  There are
    // (c1 choose 2) * (n - c1 - c2) combinations, each contributing 1:
    res += ((c1 * (c1-1)) / 2) * (n - c1 - c2);

    // Count all the {1, 2, 2} triplets.  There are c1 * (c2 choose 2)
    // combinations, each contributing 1:
    res += c1 * ((c2 * (c2-1)) / 2);

    // Count all the {1, 2, 3} triplets.  There are c1 * c2 * c3
    // combinations, each contributing 1:
    res += c1 * c2 * c3;

    std::cout << res << std::endl;
    return 0;
}

Of course, this program can be optimized even further by combining some of the expressions, but I wrote it in the way that most clearly demonstrates where each part of the answer came from.


TabController for handling opening and closing of tabs

public TabsOpen(ViewModel vm)
    : base(vm)
{
    this.vm = vm;
}

There's no reason to set this.vm = vm here. You're already doing that by passing the argument to your base class' constructor. Both of your subclass ctors could look like this.

public TabsOpen(ViewModel viewModel)
  : base (viewModel) { }

I changed the parameter name to make it a bit clearer. Speaking of naming, it's a convention in C# to PascalCase method names. You've camel cased yours. It's consistent though, so I can't gripe too much about it.

To address your actual question though, typically yes, you will pass your view model to the controller as you've done here. However, that's because the controller is typically updating the view. That doesn't seem to be the case here, so the thought comes to mind that it is better to only inject what you actually need.

I like that you've used polymorphism to simulate the state of an object, but it makes me wonder if what you have here is really a view model and not some other concept.


Unfortunately, it's not safe. That's due to the records. If I know any Prime, I can construct a new Prime:

import Data.Numbers.Primes.Type

example :: Prime -> Prime
example p = p {getIndex = 0, getValue = 0} -- whoops

So you want to get rid of the records in your type and write the getters by hand:

data Prime int = Prime int Int

getValue :: Prime int -> int
getValue (Prime v _) = v

getIndex :: Prime int -> Int
getIndex (Prime _ idx) = idx

Alternatively rename them, rebind them and don't export the record selectors:

data Prime int = Prime { _getIndex :: Int, _getValue int }

getValue :: Prime n -> n
getValue = _getValue

getIndex :: Prime n -> Int
getIndex = _getIndex

Also, you can improve maybePrime:

maybePrime :: Integral n => n -> Maybe (Prime n)
maybePrime x = Prime x <$> primeIndex x

Either x is prime and primeIndex returns Just idx, or it isn't. There is no need to check x twice. maybePrime is usually called a "smart constructor", by the way.

  Am I dealing with index type the right way?

That depends on your use-case. If you need the index of the Prime often, it makes sense to cache it. If you don't need the index often, don't. You could provide an IndexedPrime that always contains the Index, though:

type Index = Int
data IndexedPrime int = IndexedPrime Index int

newtype Prime int     = Prime int

You could split those into separate modules, but that's a matter of personal preference.

  Is an Int the right type for storing indices of primes, in the light of the facts that no prime has a negative index and there is a type Word for bounded unsigned integer values?

That's a good question. The answer is: yes, Int is a right type, but it's not the right type. Most of the time, you want to use the result of getIndex in some operation that wants an Int, not a Word, just like you want to use take (a - b). Note that I said that Int is a correct type. You can of course use Word.

  Is it good to use fromIntegral everywhere to make the types of the functions that deal with indices more general?

It can lead to interesting behaviour. For example, I can use

exampleInput :: Int
exampleInput = 13^9 + 33 + 13 -- yes, that's a prime. found by lucky guess :)

exampleOutput :: Maybe (Prime Word8)
exampleOutput = maybePrime exampleInput

-- exampleOutput = Just (Prime {getValue = 195, getIndex = 333})

That's why I changed maybePrime's type, to ensure that the conversion has to be explicit by the user before they apply maybePrime.

Overall, good ideas and implementation, but try to keep the fromIntegral parts in your own code to a minimum. By the way, if you're interested in predicative types, have a look at Liquid Haskell.


Using Python to tokenize a string in a stack-based programming language

It would be good practice to use r'raw strings' for regexes, especially since this one contains a backslash.  Instead of [^\d], you could use \D, or better yet, just ., since any digits would have been slurped up by the \d+ already.

Testing .isdigit() feels redundant to me, since the regex was already detecting digits.  If you use capturing parentheses, then you could immediately tell which portion of the regex matched, and avoid having to make a second pass to convert the integers.

If, as you say, this Script is meant to be interpreted, consider making _tokens an iterator rather than a list, which saves you from having to parse the entire string at once.  To that end, I recommend re.finditer() rather than re.findall().

I don't see any need to define a public method for tokenizing.  The generator expression could be written directly within the constructor:

import re

class Script:
    def __init__(self, text):
        self._tokens = (
            match.group(1) or int(match.group(0))
            for match in re.finditer(r'\d+|(.)', text)
        )


You should not use single letter variables.
Rather than a lambda you can create an actual function and pass its name.
There are still several magic numbers. What is 8, 20, etc.?
maxVol should also be uppercase, and should probably be named MAXIMUM_AMPLITUDE to avoid the need for the comment.
Rather than duplicating result.append you can use a separate function with a counter for how many times you want to repeat it.
Encapsulate functionality in functions or objects. Initialising noise_output (or the output as an object), the for loop and outputting/closing the stream are candidates.
Check whether it's possible to use with wave.open('noise2.wav', 'w') as noise_output: or similar.
Rather than reading the whole file into memory you can read a chunk at a time to speed up the program.
Some variable names are difficult to understand. values is almost meaningless (all it tells me is that it's an array-like structure), results likewise (how about something like audio_bytes?).


Function for most frequent level of string or factor categorical variable in R

Your function isn't very complicated so I don't know how much more efficient you can get.  However, maybe removing the if and else states may help.  How about something like this?

Code

# Sample Data
dat <- c("a", "a", "b", "c", "d","a", "a", "b", "c", "d","a", "a", "b", "c", "d","a", "a", "b", "c", "d","a", "a", "b", "c", "d")

# Mode function
MaxTable <- function(x){
     dd <- unique(x)
     dd[which.max(tabulate(match(x,dd)))]
}

Output

> MaxTable(dat)

[1] "a"

How many variables are you trying to process? You may want to think about writing a function that splits up the number of obs. for parallel processing, tabulate the mode for each section, merge each section, and then do which.max() .  Although, I'm not sure if you are reaching the limits of R.  Also, maybe a database such as mysql would be another option.