Count number of gemstones in a set of minerals

You need to stop iterating over indexes and loop like a native. A first rewrite with that in mind would yield:

def gemstones(collection):
    collection = [''.join(set(rock)) for rock in collection]
    biggest_rock = max(collection, key=len)

    count = 0
    for mineral in biggest_rock:
        for rock in collection:
            if mineral not in rock:
                break
        else:
            count += 1
    return count

This version make use for the for...else construct. But the all() builtin would be more expressive:

def gemstones(collection):
    collection = [''.join(set(rock)) for rock in collection]
    biggest_rock = max(collection, key=len)

    count = 0
    for mineral in biggest_rock:
        if all(mineral in rock for rock in collection):
            count += 1

    return count

And counting a condition in a for-loop can be more efficient using sum():

def gemstones(collection):
    collection = [''.join(set(rock)) for rock in collection]
    biggest_rock = max(collection, key=len)

    return sum(
        all(mineral in rock for rock in collection)
        for mineral in biggest_rock
    )

Other than that, you won't have more gemstones than the amount of minerals in the smallest rock, so why doing extra work by using the biggest one to start with?

But you are going back and forth between strings and sets when the problem clearly calls for set intersection repeated on several elements of an array. Luckily, the set.intersection method accept a variable number of arguments. Just make sure to catch any error thrown in case the original collection is empty:

def gemstone(collection):
    rocks = map(set, collection)
    try:
        minerals = next(rocks)
    except StopIteration:
        return 0  # If the collection is empty, there is no gemstones
    return len(minerals.intersection(*rocks))


Custom exception handling function or logging library?

The Python community favors having just one way to do something. As the Zen of Python puts it:

  There should be one-- and preferably only one --obvious way to do it.

Other people and packages will be using the logging module, in general. That makes it much easier for your code to interoperate with other packages, use consistent configuration, avoid non-obvious mistakes (like writing error messages to stdout), etc. As such, it's probably to your (and your code's) long-term advantage to use the logging module.

I'll say, one handy tip for logging in this particular case is the exc_info argument to .error, which makes it easy to log exceptions and stack traces while also printing your own messages.

@Peilonrayz responded first with a couple points that I planned to mention, so I'll just re-affirm those points:

You should use exceptions with messages properly; don't just log something and move on as if nothing happened. Whoever called your code (I don't care if you're the only one calling your functions) deserves to know that what they asked for didn't happen, and you're begging for bugs if you don't throw an exception to tell them.
Don't use a pile of if/else statements just to convert an integer into a string for an error message. Use named strings or a dictionary to store this data somewhere else in your code. (Once you do that, it'll make a whole lot more sense to just pass the error message to any handler function rather than have a custom function to look up error codes. This feels very much like an old habit from C/C++; welcome to Python, please don't use error codes that people need to look up, use one of the many excellent error types initialized with useful messages to communicate errors.)


A few things:

IData is not a particularly good name for the interface as it represents a source of data rather than the data itself. Therefor IDataSource seems more appropriate.

The interface is a bit ambiguous - which method am I supposed to use GetDataStream or GetDataString? Why use one or the other? Could I call both multiple times and interchangeably?
As of now it doesn't really provide enough value to warrant it's existence. You'd be better of having XmlValidator accept a TextReader and let the calling code deal with how to wrap it around the source.

Consider passing the ValidationSchema as part of the constructor for the XmlValidator - it's an integral part of its validation logic.

In the validator when the reader throws an exception because there was a problem reading from the stream for example then you catch those as validation errors which I'd consider technically wrong. Your validator should catch validation errors - i.e. anything that has to do with invalid XML. Everything else should not be of its concern. So don't catch Exception - be more specific.


Consider tightening up the long if statement using || which should be equivalent to your current logic.  I can't test this for you, but see if this works:

var test = function($f, $c, declarations) {
  var split = declarations.split(":"), key, value, cIsFProp;

  if (split.length < 2)
    throw new Error("Declaration is in an invalid format");

  cIsFProp = $f[$c] !== undefined && $f[$c][split[1]];

  value = cIsFProp ? $f[$c][split[1]] : null;
  value = value || $c[split[1]]) || $f[split[1]]) || "" + split[1];
  key = split[0];
  return {[key]: value};
};


Is it thread-safe? Yes
Is it going to do what you expect? Probably not
Is there a better way? Yes.
Safe
Your code will correctly lock, and access the mData value each time, and this makes it thread safe.... but, you will not get the results you expect.
Expectations
I suspect that your plan is to start, say, 10 threads, each of them incrementing from 0 through 9, adding 1 each time. You would expect the end result for the value to be 100.
It may not be. This is because, while your code is thread-safe, it is not atomic.
Atomic means that an operation starts and completes as a single logical step. You have the code:

mData.setValue(mData.getValue(id) + 1, id);

The apparent expectation is that you get the value, add one, and then set the new value. You would expect the value to increment from 0 through 10.
But, in a multi-threaded system, it may not. This is because two threads may each call mData.getValue(...) before the other has then reset the value... For example, consider the following:
Time      mData value  Thread 1  Thread 2
========  ===========  ========  ========

Initial             0

t1 get              0         0
t1 add              0         1
t1 set              1         1

t1 get              1         1
t1 add              1         2
*t2* get            1                   1
t1 set              2         2
t2 add              2                   2
t2 set              2                   2

Notice how the thread-2 can get in after the thread-1 has got the value, and before it has set the value?
What you need is an atomic operation, one which gets, adds, and sets the values all in one locked process. You can do it with your code using:
  for (int a = 1; a <= 10; a++) {
      synchronized(mData) {
          mData.setValue(mData.getValue(id) + 1, id);
      }
  }

That way all the get, add, and set operations are in a single synchronized block.
Better way
Note, in the above code, that we are synchronizing the block on the mData:

synchronized(mData) {
    ....

This illustrates a potential bug in your usage.... anyone can synchronize on your class. This may, or may not be a good thing. Your get and set methods are already synchronized on the mData instance, so now you have multiple classes all using the same synchronization point ("monitor").
The bottom line is that Java already identifies atomic operations to be a problem, and there is a subset of the standard library dedicated to ensuring that Atomic operations are safe. In your case, use AtomicInteger


Cracking the Coding Interview — 1.5 One Away

Generally nice code: easy to read, good use of const char* for the string arguments.

It's great that we have unit tests; we can improve them by making them self-checking:
/* return number of test failures (0 or 1) */
int test_one_away(const char *str1, const char *str2, int expected)
{
    const int actual = one_way(str1, str2);
    if (actual == expected)
        return 0;
    fprintf(stderr, "one_way \"%s\", \"%s\" expected %d but got %d\n",
            str1, str2, expected, actual);
    return 1;
}

int main(void)
{
    return
        + test_one_away("pale", "ple", 1)
        + test_one_away("pales", "pale", 1)
        + test_one_away("pale", "bale", 1)
        + test_one_away("pale", "bake", 0);
}

We should add some more tests.  When I start writing tests (usually before the production code) I usually write the very simplest tests first, probably passing NULL to exercise the error recovery.  I'm going to assume that the code won't be testing for null pointers, but would certainly start with the next simplest case: are two empty strings within one change:
        + test_one_away("" "", 1)

Then compare one- and two-character strings against the empty string, and for strings that differ by one or two deletions at the beginning, middle and end.  A good guideline for testing functions that return a boolean value is to identify the boundaries where the result should change between false and true (e.g. remove one character from the front ⇒ true; remove two characters from front ⇒ false) and write one test for each side of that transition.
Here's a test that exposes a bug in the code:
        + test_one_away("pale", "ale", 1)

This is because we don't accept deletion of the first character:

        if (flag && i) --i;

The fix is to remove the second part of the condition (remember, unsigned overflow is well-defined, and will exactly match the ++i in the loop increment):
        if (flag) --i;

I'm not sure why flag needs to be a size_t;  a simple int should be sufficient.  If/when we have access to a C99 compiler (which should be soon; it's around 20 years old now), we could include <stdbool.h> and make it a bool.  It also needs a better name; I had to look to the call site to understand what it's for (it seems that a true value means that we're looking for a deletion rather than a replacement).

The conditions in the wrapper function could be expressed more clearly with a single switch on the difference in length:
/* check if str1 can be obtained from string2 adding, deleting, removing
 * at last one char */
bool one_way(const char *str1, const char *str2)
{

    size_t len1 = strlen(str1);
    size_t len2 = strlen(str2);

    switch (len2 - len1) {
    case (size_t)-1: return helper_one_way(str2, str1, len2, true);
    case 0:          return helper_one_way(str1, str2, len1, false);
    case 1:          return helper_one_way(str1, str2, len2, true);
    default:         return false;
    }
}

We don't need to pass the length to helper_one_way, because it can simply stop when it reaches the terminating null char:
    for (i = 0, j = 0;  str1[i];  ++i, ++j) {

Given that we're iterating over strings, it's more idiomatic to use a char pointer than to repeatedly index into the string (though a good compiler ought to generate the same code):
static bool helper_one_way(const char *a, const char *b,
                           bool allow_deletion)
{
    size_t nchars = 0;
    while (*a) {
        if (*a++ != *b++) {
            if (++nchars > 1) return false;
            if (allow_deletion) --b;
        }
    }
    return true;
}

Finally: the name - should one_way be spelt one_away?

Modified code
Applying the above suggestions, we get:
#include <stdbool.h>
#include <string.h>

static bool helper_one_away(const char *a, const char *b,
                           bool allow_deletion)
{
    size_t nchars = 0;
    while (*a) {
        if (*a++ != *b++) {
            if (++nchars > 1) return false;
            if (allow_deletion) --b;
        }
    }
    return true;
}

/* Return true if a can be obtained from string2 by adding,
   deleting, or removing at most one character */
bool one_away(const char *a, const char *b)
{
    switch (strlen(a) - strlen(b)) {
    case (size_t)-1: return helper_one_away(b, a, true);
    case 0:          return helper_one_away(a, b, false);
    case 1:          return helper_one_away(a, b, true);
    default:         return false;
    }
}

/* Test code */

#include <stdio.h>

/* return number of test failures (0 or 1) */
static int test_one_away(const char *a, const char *b,
                         bool expected)
{
    const int actual = one_away(a, b);
    if (actual == expected)
        return 0;
    fprintf(stderr, "one_away \"%s\", \"%s\" expected %d but got %d\n",
            a, b, expected, actual);
    return 1;
}

int main(void)
{
    return
        + test_one_away("", "", true)
        + test_one_away("", "a", true)
        + test_one_away("pale", "", false)
        + test_one_away("pale", "le", false)
        + test_one_away("pale", "ale", true)
        + test_one_away("pale", "pale", true)
        + test_one_away("pale", "pal", true)
        + test_one_away("pale", "pa", false)
        + test_one_away("pale", "ple", true)
        + test_one_away("ple", "pale", true)
        + test_one_away("pales", "pale", true)
        + test_one_away("pale", "bale", true)
        + test_one_away("pale", "bake", false);
}


Rails API for communication between two Rails app where the former app posts data to the latter and the latter return a response

I will try to approach this from top to bottom, and mention things as I notice them.

(1) First obvious one is indentation, as mentioned in the other answer. The standard is 2 spaces. Nested modules and classes should be indented:

module Api
  module V1
    class OrderApiController < ApiController
    end
  end
end

(2) Extract logic into object(s) or other methods. You have started what is and will increasingly be a difficult piece of code to maintain. If you find yourself dumping everything into a single method, and that method grows beyond 4 or 5 lines, you could probably clean it up by using multiple methods and/or objects.

That's all well and good, but what does this look like? This means your send_invoice_data should look something like this:

def send_invoice_data
  render json: generate_invoice
end

def generate_invoice
  @generate_invoice ||= Api::GenerateInvoice.post(order)
end

module Api
  class GenerateInvoice
    def initialize(order)
      @order = order
    end

    def self.post(order)
      new(order).post
    end

    def post
      HTTPParty.post(url, body: data)
    end

    private

    def url
      'http://localhost:3001/api/v0/generate_invoice?key=docket'
    end

    def data
      {
        id: @order.id,
        txnid: 'etc'
      }
    end
  end
end

It is important you understand what we have done above, and the benefits that gives you. For one, it has instantly cleaned up the controller method and now you can solely worry about dealing with the response for the action.

The GenerateInvoice object has allowed us to not just extract all of that messy logic, but given us the ability to further break it down into small, descriptive methods. This will greatly improve the readability and maintainability of it. You also have the added benefit of being able to use this class elsewhere, should you need to.

Let's delve into the actual method now.

The first thing you are doing is initializing a couple of variables. response is either being assigned later (response = HTTParty) or you are using merge (response.merge! etc). You can remove this variable initialization and simply assign it later. Remove your merge and use response = ApiStatusList::INVALID_REQUEST.

You should remove debugger before you commit the code.

The Order.includes part should be extracted into a method:

def order
  @order ||= Order.includes(:status, :user, payment: [:status])
                  .find_by(txnid: params[:txnid])
end

You can also extract the scope into Order itself:

class Order < ActiveRecord::Base
  scope :eager, -> { includes(:status, :user, payment: [:status]) }
end

..and use..

def order
  @order ||= Order.eager.find_by(txnid: params[:txnid])
end

Now this might appear to be a bit extreme or contrived, but it is important to notice what I'm doing as I refactor this code. What is informing my main design decisions is the idea of extracting things into smaller, descriptive pieces. Just following that path alone is vastly improving the design of the code. Keep that in mind as you write and refactor code.

Another great place for extraction is checking whether and order is of a certain service type. You could extract this directly into your Order class again under what we call a predicate method:

class Order
  def service_i_want?
    services.include?(service.name)
  end

  def services
    %w(Notary Attestation Franking)
  end
end

This means your send_invoice_data will now look like:

def send_invoice_data
  if order
    if order.services_i_want?
      no_of_copies = # etc
    else
      no_of_copies = # etc
    end

    # HTTParty.post etc
  else
    ..
  end
end

Again, lots of extraction going on. Either into methods, or other classes.

Looking at the above we can see yet another opportunity for extraction - the no_of_copies. Instead of initializing a variable, extract it into it's own method..

def no_of_copies
  if order.services_i_want?
    ((order.answers.where(question_id:
             [37,15]).length > 0) ? order.answers.where(question_id:
             [37,15]).first.body : 0).to_i
  else
    ((order.answers.where(question_id:
             [37,15]).length > 0) ? order.answers.where(question_id:
             [37,15]).first.body : 0).to_i + 1
  end
end

I think you know where I'm going next ;) Extracting this into its own method has clearly shown us these two branches have essentially the same code. In the effort to DRY things up we should extract further.

First, let's breakdown what you are doing here.

If you have answers that have the question id of 37 or 15, then fetch body of the first answer. If no answers, return 0. Convert result to_i.

To better express this, you should, guess.. extract it into smaller parts! The logic itself probably belongs in the Order class. So first thing would be to extract it there:

class Order
  def number_of_copies
    # etc
  end
end

Because you are now in the Order context, you can better extract the other parts. We want answers with question id of 37 or 15 first..

def copied_answers
  answers.where(question_id: [37, 15])
end

We can now reduce our number_of_copies method to this:

def number_of_copies
  ((copied_answers.length > 0) ? copied_answers.first.body : 0).to_i
end

MUCH easier to think about! Looking at your logic from this viewpoint, we can now easily rewrite it to give us what we want in a much more elegant way:

def number_of_copies
  if copied_answers.any?
    copied_answers.first.body.to_i
  else
    0
  end
end

Or if you like your ternaries:

def number_of_copies
  copied_answers.any? ? copied_answers.first.body.to_i : 0
end

Let's go back to our copied_answers method for a second.

def copied_answers
  answers.where(question_id: [37, 15])
end

As the other answer mentioned, you should refrain from using 'magic numbers'. 37 and 15 above are magic because they give me no idea of what they represent. Extract them into methods or constants or whatever. Just hide them behind something descriptive so I can use this:

def copied_answers
  answers.where(question_id: [MY_QUESTION, ANOTHER_QUESTION])
  # or
  answers.where(question_id: question_ids)
end

Describe what the questions are so somebody can understand why these question ids are connected to 'copied' answers.

We also have another piece of logic to address. If the order service name is not in that services list above (services_i_want), then we increment the number of copies. I'm open to suggestions, but my first attempt at that would be:

def number_of_copies
  copies = 0

  if copied_answers.any?
    copies = copied.answers.first.body.to_i
  end

  copies += 1 if services_i_want?

  copies
end

That can no doubt be improved, but I'm writing that just as a way to match the current logic. It is, regardless, a vast improvement of what we had previously.

Let's return to your send_invoice_data method.

Because we have extracted the logic that determines the number of copies into number_of_copies on the Order itself, our send_invoice_data now looks like:

def send_invoice_data
  if order
    response = HTTParty.post('http://localhost:3001/api/v0/generate_invoice?key=docket',
      :body => {
        "order" => {
        "id" => order.id,
        "txnid" => order.txnid,
        "service_name" => order.service.name,
        "payment_date" => order.payment ?
          order.payment.created_at.strftime('%d/%m/%Y') :
          order.created_at.strftime('%d/%m/%Y'),
        "delivery_amount" => order.delivery_amount || '',
        "no_of_copies" => order.number_of_copies}}.to_json,
        :headers => { 'Content-Type' => 'application/json' }
      }
    )
  else
    response = ApiStatusList::INVALID_REQUEST
  end

  render json: response
end

Again, much easier to see what the hell is going on here now. If we have an order, we send that order to generate invoice endpoint and return the response. If no order found, we return INVALID_REQUEST.

Let's first extract the post into it's own method..

def generate_invoice
  # HTTParty.post(etc)
  # etc
  # etc
end

Notice this method from before? The natural progression would be to first extract into a method, then as that requires further breaking down, extract into other methods. If those methods begin to pollute the class we are in, extract it into its own object.

The end result is this:

module Api
  module V1
    class OrderApiController < ApiController
      def send_invoice_data
        if order
          render json: generate_invoice
        else
          render json: ApiStatus::INVALID_REQUEST
        end
      end

      def generate_invoice
        @generate_invoice ||= GenerateInvoice.post(order)
      end

      def order
        @order ||= Order.eager.find_by(txnid: params[:txnid])
      end
    end
  end
end

I will stop extracting things at this point and allow you to work through the rest by yourself. First place to start would be to create your GenerateInvoice class and throw all your logic into there. After that, just continue to extract things into small, descriptive methods, and, if necessary, other objects.

Use the advice in these answers and apply what you've learned to your second file. It's the same principles and if you follow them will lead to cleaner code.

A starting point might be the payment_date value on your post request body. Extract into Order and simply call order.payment_date.

I hope this has helped you somewhat. If you want more help, please follow the advice above and refactor your code, then post another question and I will give feedback there (do not update this question as will render my answer useless to other people).


Reduce Duplication

There appears to be some significant code duplication between the encrypt and decrypt methods.

Method Overloads

The first and most obvious spots we can refactor are the overloads for your decrypt and encrypt functions:

public static byte[] EncryptStringToByteArray( string data , string password )
{
    byte[] bytes = Encoding.ASCII.GetBytes( data );
    byte[] passwordBytes = Encoding.ASCII.GetBytes( password );
    int passwordShiftIndex = 0;
    for( int i = 0; i < bytes.Length; i++ )
    {
        bytes[ i ] = ( byte )( bytes[ i ] + passwordBytes[ passwordShiftIndex ] );
        passwordShiftIndex = ( passwordShiftIndex + 1 ) % passwordBytes.Length;
    }
    return bytes;
}

public static byte[] EncryptStringToByteArray( string data , string password , uint seed)
{
    byte[] bytes = Encoding.ASCII.GetBytes( data );
    byte[] passwordBytes = Encoding.ASCII.GetBytes( password );
    int passwordShiftIndex = 0;
    for( int i = 0; i < bytes.Length; i++ )
    {
        bytes[ i ] = ( byte )( bytes[ i ] + passwordBytes[ passwordShiftIndex ] + seed );
        passwordShiftIndex = ( passwordShiftIndex + 1 ) % passwordBytes.Length;
    }
    return bytes;
}

The only difference between these two is that one takes in a seed and adds it to the bytes within the loop.  The overload without a seed can be rewritten as follows:

public static byte[] EncryptStringToByteArray(string data, string password)
{
    return EncryptStringToByteArray(data, password, 0);
}

A similar refactor can be done with the two decrypt overloads.  I will leave that step as an exercise for the reader.

Symmetric Encryption

With what's left, I cannot help but notice that this appears to be a symmetric encryption algorithm.  As a result, the encrypt and decrypt steps are nearly identical to one another:

public static byte[] EncryptStringToByteArray( string data , string password , uint seed)
{
    byte[] bytes = Encoding.ASCII.GetBytes( data );
    byte[] passwordBytes = Encoding.ASCII.GetBytes( password );
    int passwordShiftIndex = 0;
    for( int i = 0; i < bytes.Length; i++ )
    {
        bytes[ i ] = ( byte )( bytes[ i ] + passwordBytes[ passwordShiftIndex ] + seed );
        passwordShiftIndex = ( passwordShiftIndex + 1 ) % passwordBytes.Length;
    }
    return bytes;
}

public static string DecryptByteArrayToString( byte[] data , string password , uint seed)
{
    byte[] bytes = data;
    byte[] passwordBytes = Encoding.ASCII.GetBytes( password );
    int passwordShiftIndex = 0;
    for( int i = 0; i < bytes.Length; i++ )
    {
        bytes[ i ] = ( byte )( bytes[ i ] - passwordBytes[ passwordShiftIndex ] - seed );
        passwordShiftIndex = ( passwordShiftIndex + 1 ) % passwordBytes.Length;
    }
    return Encoding.ASCII.GetString( bytes );
}

They do, however, have some subtle differences:

Encrypt adds the seed, while Decrypt subtracts it
Encrypt takes in string and returns byte[], while Decrypt takes in byte[] and returns string.

However, neither are particularly large differences.  We can refactor further if we extract the following method:

private static byte[] Encrypt(byte[] bytes, string password, uint seed, int factor)
{
    var passwordBytes = Encoding.ASCII.GetBytes(password);
    var passwordShiftIndex = 0;
    for(int i = 0; i < bytes.Length; i++)
    {
        bytes[i] = (byte) (bytes[i] + factor * (passwordBytes[passwordShiftIndex] + seed));
        passwordShiftIndex = (passwordShiftIndex + 1) % passwordBytes.Length;
    }
    return bytes;
}

Note the following changes:

It takes in and returns byte[]
I added an integer factor variable which is used to control whether passwordBytes[passwordShiftIndex] and seed are added or subtracted

With those changes, we can refactor our seeded encrypt and decrypt methods to call the above method, changing the class as follows:

public static class SimpleByteCipher
{
    public static byte[] EncryptStringToByteArray(string data, string password)
    {
        return EncryptStringToByteArray(data, password, 0);
    }

    public static byte[] EncryptStringToByteArray(string data, string password, uint seed)
    {
        var bytes = Encoding.ASCII.GetBytes(data);
        return Encrypt(bytes, password, seed, 1);
    }

    private static byte[] Encrypt(byte[] bytes, string password, uint seed, int factor)
    {
        var passwordBytes = Encoding.ASCII.GetBytes(password);
        var passwordShiftIndex = 0;
        for(int i = 0; i < bytes.Length; i++)
        {
            bytes[i] = (byte) (bytes[i] + factor * (passwordBytes[passwordShiftIndex] + seed));
            passwordShiftIndex = (passwordShiftIndex + 1) % passwordBytes.Length;
        }
        return bytes;
    }

    public static string DecryptByteArrayToString(byte[] data, string password)
    {
        return DecryptByteArrayToString(data, password, 0);
    }

    public static string DecryptByteArrayToString(byte[] data, string password, uint seed)
    {
        var bytes = Encrypt(data, password, seed, -1);
        return Encoding.ASCII.GetString(bytes);
    }
}


For the most part, this looks good. However, there are a few things I'd recommend changing.

Don't use module. namespace should be used instead. From the Typescript Handbook:

  A note about terminology: It’s important to note that in TypeScript 1.5, the nomenclature has changed. “Internal modules” are now “namespaces”. “External modules” are now simply “modules”, as to align with ECMAScript 2015’s terminology, (namely that module X { is equivalent to the now-preferred namespace X {).

You do not properly escape special characters. If a double quote appears anywhere in the URL, the form will break. Try the url https://example.com/?a=" >Broke to see an example.
Related to the above, building HTML with strings is an incredibly error prone process. If at all possible, avoid it. It is a better idea to use the <template> tag.
You don't need omnibox browsers have a built in URL api which covers everything that omnibox does and more. If you need to support IE, you can use the url-polyfill package - and gain the advantage that newer browsers don't need to load it.
Consider using Object.entries instead of Object.keys as it can slightly simplify some of your code.

const querystrings = Object.entries(o.query)
    .map(([key, value]) => `${key}=${value}`)
    .join('&')

For your specific questions:

A module namespace is a reasonable choice for the app. I personally never use them, preferring to use ES Modules. A larger concern is that you export the module to the global scope unnecessarily. Instead of using onclick="parse()" in your HTML, it would be better to add the event handler in your index.ts file and have this module in it's own file.
I don't believe you even need the map function, it wouldn't be that big of a deal to check for pathname instead of pathnames in the switch statement and split the string there. If you do keep the map function, it should be renamed to something more descriptive. When I saw map I expected it to be roughly equivalent to Array.prototype.map.
For tests, it depends on who you ask. Since you aren't parsing the URL yourself (good!) there isn't really too much that can go wrong here. I'd probably only write a few integration tests for this app as a whole.


Constant members
n and k can be constant, so long as

you remove them from being parameters to crackSafe
you add them as parameters to a constructor
the constructor uses inline initialization syntax, i.e. n(n)

Basically, your two member functions should - in their current form - be bare functions outside of a class, since the class member variables only really have transient meaning. For this to make sense as a class, n and k would only make sense as "permanent" attributes per instance.


The end of your code...

bool isIn = true;
if (criteria.Count() == 0)
    return isIn;
isIn = criteria.Any(x => x(job));
return isIn;

Looks really weird to me

Get rid of the boolean variable, you don't need it to return a true or false value from expressions that return a boolean.

Also, make this an if/else statement.

if (criteria.Count() == 0)
{
    return true;
}
else
{
    return criteria.Any(x => x(job));
}

You could also condense this to a single return statement using a ternary statement

return criteria.Count() == 0 ? true : criteria.Any(x => x(job));

or even a simple or conditional

return criteria.Count() == 0 || criteria.Any(x => x(job));

some would say that having the ==0 isn't very clean when you could instead write it like this

return !criteria.Any() || critera.Any(x =>  x(job));

On the other hand, in your FilterByJobsSearchBox method I would un-nest the if statement, it is indented in a way that isn't necessary and looks messy.

Something else that you should do to make this more dry, is to apply the ToLower method to the variable assignment instead of when you compare to see if the jobs contain the search text, I will show you what I mean

    var searchText = CharactersOnly(jobsSearchBox.Text);
    var job = o as JobModel;
    if (searchText == string.Empty)
    {
        return true;
    }
    else
    {
        if (CompanyContains(job.JobReference, searchText.ToLower()) ||
            CompanyContains(job.CaseClient, searchText.ToLower()) ||
            CompanyContains(job.JobDescription, searchText.ToLower()) ||
            CompanyContains(job.JobNotes, searchText.ToLower()) ||
            CompanyContains(job.JobID.ToString(), searchText.ToLower()))
        {
            return true;
        }
    }
    return false;

Here is what it looks like when you do everything I mentioned above

var searchText = CharactersOnly(jobsSearchBox.Text).ToLower();
var job = o as JobModel;
if (searchText == string.Empty)
{
    return true;
}

if (CompanyContains(job.JobReference, searchText) ||
    CompanyContains(job.CaseClient, searchText) ||
    CompanyContains(job.JobDescription, searchText) ||
    CompanyContains(job.JobNotes, searchText) ||
    CompanyContains(job.JobID.ToString(), searchText))
{
    return true;
}

return false;

we could go a little further and make this one return statement as well, it will be a very long return statement....

var searchText = CharactersOnly(jobsSearchBox.Text).ToLower();
var job = o as JobModel;
return searchText == string.Empty
    || CompanyContains(job.JobReference, searchText)
    || CompanyContains(job.CaseClient, searchText)
    || CompanyContains(job.JobDescription, searchText)
    || CompanyContains(job.JobNotes, searchText)
    || CompanyContains(job.JobID.ToString(), searchText);


This is a non standard header.

#include<bits/stdc++.h>

The "bits" directory is an implementation detail of your compiler. You should NEVER use it in your code.

Your headers should be:

#include <vector>
#include <iostream>

You should not do this:

using namespace std;

Read the details about the issues here: Why is “using namespace std” considered bad practice?

You should avoid using global variables.

vector<pair<string, string>> v;

Here you are locking your check() function to searching only one list. It should search any list for the key.

This global variable does not seem to be used anywhere:

int awal1 = 1;

Bounds checking:

string check(string s, int awal, int akhir){

If awal and akhir are equal there is nothing to check. You have gone beyond the range. So You need to do a test here. If these two are equal then you failed to find the data.

Note: That akhir is one beyond the end of the range you are checking. For the very right hand end of the vector this means beyond the end of the v which means that accessing it is undefined behavior and likely to cause a crash.

This value is always false.

    bool temukan = false;

Because this statement is never executed.

    if(v[tengah].first == s){
        return v[tengah].second;

        // The line above is a return.
        // So the next line is never reached.
        // So we never execute this.
        temukan = true;
    }

    // So in this line  `temukan` is always false.
    // So this `if` test is always true
    // So this would always return 'NIHIL'
    if(temukan == false) return "NIHIL";

BUT. In the same function you also have another set of if else statements. That always result in a return. So the code never falls through to the last 'NIHL' statement.

if(v[tengah].first == s){              // Equal
    return v[tengah].second;
}
else if(v[tengah].first > s){          // Greater
    return check(s, awal, tengah-1);
}
else if(v[tengah].first < s){          // Less
    return check(s, tengah+1, akhir);
}

One of those branches must be true (unless you were comparing floats). So the code will never go past these set of tests.

So there are some massive bugs in the function check(). You definitely need to fix these. I am not going to fix them because I think it would do you good to try and work out what the correct solution is. But as it stands this would fail any unit tests you should have written.

This is C code.

    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);

What you probably want is the C++ std::fstream class.

One variable per line please:

     string s, s1, s2; vector<string> h;
    int n, p;

As containers like arrays/vectors are 0 based. We usually loop from 0 to 1 less than the number.

    for(int i=1;i<=n;i++){

    // Most C/C++/Java/C# etc programmer would write that loop as:
    for(int i = 0; i < n; ++i) {

Yes this works.

        v.push_back(make_pair(s, s1));

But you can use the emplace_back() method which makes it easier to read and removes an unneeded copy.

        v.emplace_back(s, s1);

As I mentioned above containers are indexed from 0.

        cout << check(h[i], 1, v.size()) << "\n";

So passing a 1 here is wrong. As you will never find the first element. You should have noticed there was not check for "agung". You can't find this person if you search from 1 as they are in position 0. Unfortunately your check loop also started at 1 so your code missed it.


Variant of 2-SUM Problem using Hashtable with multi-threading

functions

split the work you want to do in logical functions. I try to limit the work that is done in the general script (and thus the global namespace) as much as possible. Lookups of local variable are supposed to be faster, but it make the code easier to read and test as well, so win-win.

hashing

Why device your own hashing? just dumping all the numbers in a set will eliminate all the duplicates, and 1M integers is a limited amount of memory. Certainly a lot less that the defaultdict you use

global variable ans

Instead of passing the global variable ans, the easiest way would be to use the fact that in a numeric context (like sum), True equals 1 and False equals 0, so you can just return True or False in two_sum_present

my take on this:

read the file

Using the fact that a file is an iterator, I would do something like this

def read_file(filename):
    with open(filename, 'r') as file:
        return set(map(int, file))

find the target

About the same as your two_sum_present with my remarks incorporated

def find_target(numbers, target):
    for i in numbers:
        if target - i in numbers and 2 * i != target:
            return True
    return False

iterate over the interval

def find_sums(numbers, start=-10000, end=10000):
    for target in range(start, end + 1):
#         print(target)
        yield find_target(numbers, target)

putting it together

def main(filename, start=-10000, end=10000):
    numbers = read_file(filename)
#     print(f'numbers found: {len(numbers)}')
    return sum(find_sums(numbers, start, end))

if __name__ == '__main__':
    filename = 'data/_6ec67df2804ff4b58ab21c12edcb21f8_algo1-programming_prob-2sum.txt'
    print(main(filename, -100, 100))

All in all, it took 43 seconds to scan those 201 numbers on my system, to find 5 matches. Reading the file took about .6s of that time

This solution is essentially the same as sum(any(n-x in numbers and 2*x != n for x in numbers) for n in range(-100, 101)), but that one took 59s

Multithreading

If you want to, you can divide out all the call to find_target to different workers/cores/... In this case, a frozenset instead of a set might be more appropriate since it's immutable, and will give less problems with concurrency

distinct

As noted by Gareth Rees, the original question is ambiguous on what is mean with distinct numbers x,y. To cover the second interpretation, You can change the set to a collections.Counter, and change the test criterium slightly

from collections import Counter

def read_file_distinct(filename):
    with open(filename, 'r') as file:
        return Counter(map(int, file))

def find_sums_distinct(numbers, start=-10000, end=10000):
    for target in range(start, end + 1):
#         print(target)
        yield find_target_distinct(numbers, target)

def find_target_distinct(numbers, target):
    for i in numbers:
        if target - i in numbers and (2 * i != target or numbers[i] > 1):
            return True
    return False

def main_distinct(filename, start=-10000, end=10000):
    numbers = read_file_distinct(filename)
#     print(f'numbers found: {len(numbers)}')
    return sum(find_sums_distinct(numbers, start, end))

This has an effect on speed, though

%timeit main(filename, -10, 10)

4.51 s ± 32.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit main_distinct(filename, -10, 10)

6.42 s ± 48.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

distinct 2

A slightly different, faster approach can be used to tackle the 2nd interpretation

def find_sums_distinct2(numbers, repetitions,start=-10000, end=10000):
    for target in range(start, end + 1):
#         print(target)
        yield find_target_distinct2(numbers, repetitions, target)

def find_target_distinct2(numbers, repetitions, target):
    for i in numbers:
        if target - i in numbers and (2 * i != target or i in repetitions):
            return True
    return False

def main_distinct2(filename, start=-10000, end=10000):
    numbers = read_file_distinct(filename)
    repetitions = {k for k, v in numbers.items() if ((v > 1) and (start < k < end))}
#     print(repetitions)
    numbers = set(numbers)
#     print(f'{len(numbers)} numbers found, {len(repetitions)} repetitions')
    return sum(find_sums_distinct2(numbers, repetitions, start, end))

%timeit main_distinct2(filename, -10, 10)

4.92 s ± 160 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)


Fetching daylerees colour schemes for PHPStorm from Github

Instead of os.path.exists you may want to specifically use os.path.isdir and isfile. isdir checks if the path matches an existing folder, and isfile checks for files. It is possible for the path you pass to be valid but not of the correct type for your purposes, which would be a significant error for your folders as you then have invalid paths that you'd attempt to download to.

Also to make it easier on your user, I would wrap the main code in a while loop so that if they enter an invalid path the program doesn't exist the program still doesn't exit:

while True:
    download_location = raw_input(
        "Where would you like me to save the files? (e.g. ./ or ../ or ./themes/ or /path/to/folder): ")
    if download_location and re.match(r'.+/$', download_location):
        if not os.path.isdir(download_location):
            os.mkdir(download_location)
        crawler = Crawler('https://api.github.com/repos/daylerees/colour-schemes/contents/jetbrains',
                          download_location)
        crawler.crawl()
        print('\n\nAll done. Themes have been saved into ' + download_location +
              '. Thank you for your cooperation. Have a nice day.')
        break
    else:
        print('The path must end with a forward slash.')

Putting break after your print call will end the infinite loop once the code has  successfully run but otherwise it will keep asking for input.

Also no need for regex. Python has a str.endswith function that detects if a string ends with a certain string. So you could just use:

    if download_location.endswith('/'):

raw_input will at least return a string, so you can just call this function on download_location. If it's an empty string it will return False since an empty string doesn't end with '/'.


Traversing through single large array to convert single array into array of arrays as per condition

Observations and Remarks

Your code is pretty complex and hard to read, as it involves a
callback with a complex outside state encoded within the global
revious_sub, capture and file_no variables. Each time your
callback is executed, it modifies some of those state variables =
there are many side-effects, which makes things confusing.
The variable capture is unused.
Not all variables are declared and thus become global.
Your sample input seems to be a list of strings, but within your
callback you access the path via testfile = file.relativePath;
indicating that you deal with objects.
It doesn't seem necessary to me to perform a basic array operation
without IO delays asynchronously. So I recommend a simpler
synchronous function.
Your resulting grouped file list is not very useful, as its groups
are unnamed. If we want to know the 'sub-*' prefix of a group, we
would have to manually inspect a random group element. An explicit
mapping from prefix or name to file would allow us to query e.g.
groups.get('sub-03') in constant time.
Your current implementation requires a sorted input file list. By
using a Map, you can guarantee the same runtime complexity without
having to rely on sorted input.

Suggested Implementation
Write a general purpose groupBy helper function or use a library which already includes one. Such a function would group array elements by their label or name. The user supplies a callback which returns the label or name for each array element:
function groupBy(array, cp) {
    return array.reduce((groups, next) => {
        const name = cp(next);
        if (name !== undefined) {
            const group = groups.get(name);
            if (group) group.push(next);
            else groups.set(name, [next]);
        }
        return groups;
    }, new Map());
}

For a given list of file paths, you could then simply write:
const files = [
    '/sub-09/func/sub-09_task-genInstrAv_run-05_physio.tsv.gz',
    '/sub-10/anat/sub-10_T1w.json',
    '/sub-10/anat/sub-10_T1w.nii.gz',
    '/sub-10/fmap/sub-10_magnitude1.nii.gz',
    '/sub-10/fmap/sub-10_magnitude2.nii.gz',
    '/sub-10/fmap/sub-10_phasediff.json',
    '/sub-10/fmap/sub-10_phasediff.nii.gz',
    '/sub-11/anat/sub-11_T1w.nii.gz'
];

const groups = groupBy(files, path => {
    const match = path.match(/^\/(sub-\w+)\//);
    if (match) return match[1];
});

If your file list is made up of objects instead of strings, you could write:
const groups = groupBy(files, file => {
    const match = file.relativePath.match(/^\/(sub-\w+)\//);
    if (match) return match[1];
});

The result is a Map { "sub-09" → […], "sub-10" → […], "sub-11" → […] } which we can query via e.g. groups.get('sub-09') or transform into your array of arrays via e.g. [...groups.values()].


Finding columns of a matrix that are the same for combinations of events

There's quite a few things that you can do to reduce computation time.

First of all, if you know that an outcome has to be the combination of seven events, you can throw out whatever has fewer of them.

Then, you can preassign the output array (growing in a loop is usually not very fast).

Finally, you want to generate all possible subsets if there are, say, 9 events from which you can choose 7.

So you'd start

%# throw out useless stuff
tooFewIdx = repeat_counts < 7;

b(tooFewIdx,:) = [];
U(tooFewIdx) = [];
repeat_counts(tooFewIdx) = [];

%# estimate how many combinations you will get
nPerms = arrayfun(@(x)nchoosek(x,7),repeat_counts);

intIdx = [0;cumsum(nPerms(:))];

%# pre-assign output
%# If this runs out of memory, try using integer formats
%# instead, e.g. zeros(...,'uint8') if no value is above 255
intersection = zeros(intIdx(end),11);

%# loop to fill intersection
for i=1:length(U)

%# fill in the experiment information
intersection((intIdx(i)+1):intIdx(i+1),1:4) = repmat(b(i,:),nPerms(i),1);

%# add all combinations of events
intersection((intIdx(i)+1):intIdx(i+1),5:11) = combnk(U{i},7);

end


Memoized solution to Count number of ways to climb n steps

First impressions:

The dynamic approach is a good idea, but it can be improved
When a Map<Integer, T> is used, see if a T[] can be used instead
When doing a dynamic solution, see if you can remove the need for recursion

By applying these tricks, my suggested solution is this:

public static int numberOfWaysFast(int n) {
    if (n < 2) {
        return n >= 0 ? 1 : 0;
    }
    int[] cache = new int[n+1];
    cache[0] = 1;
    cache[1] = 1;
    cache[2] = 2;
    for (int i = 3; i <= n; i++) {
        cache[i] = cache[i-1] + cache[i-2] + cache[i-3];
    }
    return cache[n];
}

This solution is about 50-100 times faster on my computer, and doesn't run into StackOverflowErrors for large inputs.

If you want to improve even further, you can reuse the cache array for subsequent calls, and only calculate new values when you have to. This could be applicable if you knew the maximum bound for values to be calculated, and had to rerun the function multiple times. Otherwise you could use an ArrayList<Integer>, but that's a tiny bit slower.

EDIT: forgot to handle input <2, added some code for it.


Sierpinski’s Gasket Triangle in JavaScript

Performance

For positive numbers < 2 ^ 31 use num | 0 (bitwise or zero) to floor
You are drawing an arc that is 1 pixel in radius, with the stroke width of 1 the diameter is 3 pixels. This covers an area much greater than the point you sample. Use fillRect to draw a single pixel as its much quicker. Better yet as they are all the same color create a single path and use ctx.rect to add to it. Render all rect in one pass at the end of begin function.
Avoid creating objects needlessly. Create a working object and use that to hold intermediate values. This can greatly reduce memory allocation and GC overheads. Eg the object you return in updateDot is a waste of memory and time.
If you test two numbers to find the max or min, knowing either means you also know the other and thus do not need to test for it. The long lines Math.min(p.y, p1.y) + (Math.max(p.y, p1.y) - Math.min(p.y, p1.y)) / 2 can be reduced by a single test and give significant performance improvement.

Style

Use const for constants. Eg canvas and ctx should be const.
Capitals only for names of objects that are instantiated with the new token. Eg GenerateRand should be generateRand
Avoid repeated code by using functions. Eg you create many instances of an object {x,y}, would be better as a function.
Spaces between operators, commas, etc.
Use === rather than ==
else on the same line as the closing }
The final statement in function begin does not need the test (randN == 5 || randN == 6) (assuming you want a new point each iteration)

Code
The random number generated is from 0 to 6 and you ignore 0, redrawing the same point 1 in 7 times. You can reduce the random to give 3 values 0,1,2 and perform the correct calculation on that or use a counter and cycle the points.
You could also put the points pA, pB, pC in an array and index them directly via the random number.
Rather than use setInterval, use setTimeout. That way you don't need to clear the timer each time.
Put magic numbers in one place and name them as constants.
You reset the start point each time delay is called (first two lines). Better to just let it keep going. It may also pay to stop the rendering after a fixed amount of points have been rendered.
The rewrite.
This is just an example of the various points outlined above.
Also a few modifications

Automatically adjust number of points rendered to keep the GPU load steady.
Stop rendering after a fixed number of points rendered.
The starting points pA,pB,pC are in an array.
Magic numbers as constants.
Using a single render path to draw all points per render cycle.
Using a working point wPoint to hold coordinates rather than create a new point for each point rendered.

const ctx = canvas.getContext('2d');

const padding = 5;
const renderDelay = 200;
const maxTime = 2;  // time in ms allowed to render points.
const maxPointsToDraw = canvas.width * canvas.height * (1 / 3);

var pointsPerRender = 500; // points to render per render pass
var totalPoints = 0; // count of total points drawn
ctx.fillStyle = '#fc3';

const generateRand = () => Math.random() * 3 | 0;
const point = (x, y) => ({x, y});
const drawDot = p => ctx.rect(p.x, p.y, 1, 1);

const updateDot = (p, p1) => {
    p.x = p.x < p1.x ? p.x + (p1.x - p.x) / 2 : p1.x + (p.x - p1.x) / 2;
    p.y = p.y < p1.y ? p.y + (p1.y - p.y) / 2 : p1.y + (p.y - p1.y) / 2;
    return p;
}

const points = [
    point(canvas.width / 2, padding),
    point(padding, canvas.height - padding),
    point(canvas.width - padding, canvas.height - padding)
];
const wPoint = point(canvas.width / 4, canvas.height / 2); // working point

const renderPoints = iterations => {
    totalPoints += iterations;

    const now = performance.now();
    ctx.beginPath();
    while (iterations --) { drawDot(updateDot(wPoint, points[generateRand()])) }
    ctx.fill();
    const time = performance.now() - now;

    // use render time to tune number points to draw
    // Calculates approx time per point and then calcs number of points
    // to render next time based on that speed.
    // Note that security issues mean time is rounded to much higher
    // value than 0.001 ms so must test for 0 incase time is zero
    pointsPerRender = maxTime / ((time ? time : 0.1)/ pointsPerRender);

    if (totalPoints < maxPointsToDraw) {
        setTimeout(renderPoints, renderDelay, pointsPerRender | 0);
    }
}
renderPoints(pointsPerRender);
<canvas id="canvas" width="500" height="500"></canvas>


Setting every element in an array to a given value

You can also use the static Array.Fill to quickly initialize an array to a given value:

bool[] isPrime = new bool[500];
Array.Fill(isPrime, true);

This will set all items in the array to true.

As mentioned in the comments by Pieter Witvoet, this feature is available in .NET Core only.


Excel VBA Filtering: AODB vs Autofilter vs SQLite

For anyone reading, I ended up moving my spreadsheets to Microsoft Access, and used ADODB/SQL Queries from Excel to retrieve values from the Access database. This helped speed up my code by approx 10x, so definitely worth the move.


Create several homogeneous arrays from a larger heterogenous array efficiently

Ideally, you would want a groupBy function, such as the _.groupBy() function offered by lodash.  If you don't want to load a library, it's not too hard to reimplement groupBy.

This solution also has the advantage of returning the result as one associative array rather than mutating four global variables as a side-effect.

let aircraft = [
    {
        tail: "9736968",
        status: "DRAFT"
    },
    {
        tail: "5114419",
        status: "SERVICEABLE"
    },
    {
        tail: "8395671",
        status: "OUTOFSERVICE"
    },
    {
        tail: "332273",
        status: "SERVICEABLE"
    },
    {
        tail: "6123961",
        status: "UNSERVICEABLE"
    },
];

// http://stackoverflow.com/a/34890276
function groupBy(collection, attr) {
    return collection.reduce(function(result, item) {
        (result[item[attr]] = result[item[attr]] || []).push(item);
        return result;
    }, {});
}

let aircraftByStatus = groupBy(aircraft, 'status');
console.log(aircraftByStatus);


The way to do this in C is to define an array, and use designated array initializers to ensure the correct mapping between number and string, like so:
static const char *signames[] = {
    [SIGKILL] = "SIGKILL",
    [SIGSTOP] = "SIGSTOP",
    ...
    [0] = "[NO SIGNAL TO DELIVER]",
};

const char *getsig(int sig) {
    if (sig < 0 || sig >= sizeof(signames) / sizeof(*signames) || !signames[sig])
        return "UNKN";

    return signames[sig];
}

Note that it is hard to make this portable; the list of available signals varies by operating system, and some don't even have the concept of signals. Some operating systems and/or standard libraries might already have some function to convert signal numbers to strings, if you target a specific platform and don't care about compatibility, you might consider using that.
Note that strsignal() should be available on any POSIX platform, although it gives you a more human readable string like "Killed" instead of "SIGKILL".


You're adding a click handler to all your inputs, and then implementing the click handler such that each click processes all the labels.  This is probably not what you want.

I'd suggest the following:

$('label input[type=checkbox]').click(function() {
    $(this.parentNode).toggleClass('active', this.checked);
});

$('label input[type=radio]').click(function() {
    $('input[name="' + this.name + '"]').each(function(){
        $(this.parentNode).toggleClass('active', this.checked);
    });
});

Happily enough, that approach is also more efficient, as it's processing 1 element per click for checkboxes instead of n elements per click.  For radio buttons it still has to process multiple elements, but the number processed is still less than the total number of elements on the page (assuming the page contains more than a single group of radio buttons).

Here's a live example:  http://jsfiddle.net/DfU3R/3/

As nickles80 rightly notes, however, the performance difference between the two approaches will likely be negligible, and premature optimization is the root of all evil.


There are three validation failures (ignoring case sensitivity) that Double.parseDouble() would have accepted otherwise:

A starting positive sign (+1.23).
A starting decimal point (.123).
The E notation aka scientific notation (1.23E4).

As for your comments... they should explain the why, not the how. The comments you have now are only explaining the how, so you should consider removing them when you get the chance to write code outside of academic exercises in the future...

Variable names... it depends. i is quite well-understood, but some may frown upon a single c to represent a character, or even str for your method argument... I'm not suggesting to be overly descriptive (currentCharacterOfMethodArgument is an example), but maybe an actual English word (current?) might be slightly more readable for your marker.

And just for completeness, remember to do a null check at the start too, before str.isEmpty(). :)

edit And since you asked about it, the implementation of charAt(int) is just:

public char charAt(int index) {
    if ((index < 0) || (index >= value.length)) {
        throw new StringIndexOutOfBoundsException(index);
    }
    return value[index];
}

The only 'evaluation' here is the if statement for out-of-bounds check, which I don't think is that significant/performance-hurting (if you're alluding to this indirectly as well). It's fine both ways whether you want to 'cache' it first.


my two cents : use duck-typing.

@efficiency = efficiency.to_f

... if it quacks like a float, then it is a float. This allows to leverage ruby's awesomeness with things like :

class EfficiencyProfile
  def initialize(some_data, value)
    @data = some_data
    @efficiency_value = some_value
  end

  def to_f
    @efficiency_value.to_f
  end
end

e = EfficiencyProfile.new(some_big_chunk_of_data_about_engine_performance, 42)
ElectricalEngine.new(1,2,e) # would work without a complain

Dynamic typing sure is dangerous, but you have to embrace it if you want to benefit from it.

Checking the type explicitly is an half-arsed solution, because :

it is cumbersome, and you will never be as good at it than, say, a C compiler is
it will completely remove the sole benefit from dynamic typing : flexibility.


Separating data from string representation of objects, with added extras

Type hinting
Instead of having helpdocs declare the types of function parameters, why not go with type hinting?
Complexity
Your code currently has too many moving parts. You define 2 different functions to parse the data, and they both need to be called in chain. This should be done by a single parsing function.
Let the parser get data text, then the parser should be handling first parsing using pipe and later using the numerical ranges.
Selection from a list
Your randomize_by_pipe shuffles the list, and selects the 0th value. You can instead let random.choice do the job.
range parsing
I think range parsing can be improved a little. How about the following flow:

Remove [ and ] from the given text.
Split from ,.
For each section of the split, try parsing as float (or int, depending on your dataset)
In case of float conversion error, let the rand_no_from_string get a value.

regex
You have a regex, but you're not making full/elegant use of it. Instead of matches, you can group the results, and operate on those groups. The pattern itself can also be a little optimised:
\d+(?:\.\d+)?-\d+(?:\.\d+)?

A rewrite, for eg:
from re import sub, Match
from random import choice, randint

def randomise_range(match: Match):
    given_range = match.group(0).split("-")
    low, high = map(float, given_range)
    if low > high:
        low, high = high, low
    if low.is_integer():
        return str(randint(int(low), int(high)))
    multiplier = 10 ** len(given_range[0].split(".")[-1])
    low = int(low * multiplier)
    high = int(high * multiplier)
    return str(randint(low, high) / multiplier)

def extract_range(text: str = None):
    if not text:
        return text
    return sub(r"\d+(?:\.\d+)?-\d+(?:\.\d+)?", randomise_range, text)

def parse(text: str = None):
    if not text:
        return text
    selection = choice(text.split("|"))
    if selection[0] in ('[', '('):
        return extract_range(selection)
    return selection

if __name__ == "__main__":
    examples = (
        "(1-3,1,1)",
        "(0.2-0.4,1,1)",
        "foo|bar|foobar",
        "(108-100,0.25-0.75,100)|Foo|Bar|[123,234,234-250]",
        "[1-2,1,2]|foo|bar|[1,8-10,99]",
    )
    for text in examples:
        print(parse(text))


I think this is a matter of taste, I don't see any major disadvantages but no major advantages either. In these cases I would err on the side of simplicity and go with querying localStorage directly.

Now to fully whet my morning CR.SE appetite let's get really nitpicky:

Pros

It will make it marginally easier to change your code if you some day decide to use a different storage mechanism (for example a fallback mechanism if localStorage doesn't exist). This is only marginally easier unless your code is partitioned in such a way that a global search for LOCAL_STORAGE.USERNAME won't work
From the standpoint of coding practice, it IS generally considered better to hide all your external dependencies, and a good argument can be made that localStorage is one
Gets rid of your LOCAL_STORAGE keys object
Getters and setters are familiar to people coming from a java background

Cons

You actually have more global objects now, as window.namespace.username and all it's children are now effectively global (though namespaced)
If someone picks up your code they might not see the localStorage references and assume that you don't depend on it. They might therefore make decisions (for example to deploy to an old IE) that might damage stability. (this is the counterpoint to abstracting away external dependencies).
Getters and setters are icky and anti-intuitive for someone not coming from the java world
Someone has to learn your api to use it the way you want it to be used. While your code makes the assumption that they are accessing username through your object, someone could very reasonably pick up the code, open up devtools, see that there is a Username key in localStorage, and start querying it directly thereby breaking your expectation. In short, it's so easy to access localstorage, there's no reason for them to expect that you abstracted it.
Are you going to follow the same pattern for other objects too? You really should pick one pattern and stick to it and only make exceptions when there is a good reason to.
Because you're using this someone can use new, or call, or apply and break your username functions

General Notes

localStorage.getItem('Username') is in no way worse than localStorage.getItem(LOCAL_STORAGE.USERNAME). I would wager it's better because it is less typing and more obvious. Butbutbut it's a magic string! This is javascript, not java, it's all magic strings. Note that my own personal preference is to use ' to differentiate a token (similar to ruby's :token) from text for which I use ".
LOCAL_STORAGE - I really dislike that naming convention. Whatever works for you I guess, but what is the semantic meaning of all-caps? How is it semantically different than namespace.localStorageKeys?
Do you really need a setter? I image that you're only going to be setting Username in one place - why make a global method then?
So you still want to abstract away localStorage? How about a more javascript-y approach?

myNamespace.storage = function(key, val) {
  return val === undefined ?
  localStorage.getItem(key) : localStorage.setItem(key, val);
}

then:

myNamespace.storage('Username', "George");
myNamespace.storage('Username') == "George";

This is of course a very naive implementation, you could probably add some more logic handling serializing/deserializing objects from json and fallback mechanisms.


Stack trace

I think you shouldn't work with the stack string but retrieve the stack and go through each frame yourself. I find it would make the analysis more reliable and you could get the information you need without extracting it from the string because you would have direct access to each part.

private static IEnumerable<dynamic> GetStackTrace(this Exception exception)
{
    var stackTrace = new StackTrace(exception, true);
    var stackFrames = stackTrace.GetFrames();
    var result = stackFrames?.Select(sf => new
    {
        Caller = (sf.GetMethod() as MethodInfo)?.ToShortString() ?? string.Empty,
        FileName = Path.GetFileName(sf.GetFileName()),
        LineNumber = sf.GetFileLineNumber(),
    });
}

This snippet comes from my Exception prettyfier.

Other suggestions

It would be a good idea to split this method into three or four methods.

the first one gets you the information you need from the stack - you could implement it either based on the string or on the raw stack trace
the second one would encode the data as Base64String
the third and last one would clean-up or encode the string generated by the second one
the fourth could be a helper encapsulating the three other methods

Example:

var ex.ToExceptionId()

where

public static string ToExceptionId(this Exception ex)
{
    return ex.GetStackTrace().ToBase64String().EncodeBase64String();
}

Now you can test and maintain each part of the exception id creation separately.


Given 4 vertices representing a quadrilateral, divide it into N parts

First, there is no need for this to be a class at all. Your class has only two static methods, so they might as well be stand-alone functions. In this regard Python is different from e.g. Java, where everything is supposed to be a class.

Your get_factors function can be sped-up significantly by recognizing that if k is a factor of n, then so is l = n / k. This also means you can stop looking for factors once you reach \$\sqrt{n}\$, because if it is a square number, this will be the largest factor not yet checked (and otherwise it is an upper bound). I also used a set instead of a list here so adding a factor multiple times does not matter (only relevant for square numbers, again).

from math import sqrt

def get_factors(n):
    '''
    Takes a number and returns a list of factors
    :param number: The number for which to find the factors
    :return: a list of factors for the given number
    '''
    factors = set()
    for i in range(1, int(sqrt(n)) + 1):
        if n % i == 0:
            factors.add(i)
            factors.add(n // i)
    return list(sorted(factors))  # sorted might be unnecessary

As said, this is significantly faster than your implementation, although this only starts to be relevant for about \$n > 10\$.

(Note the log scale on both axis.)

As for your main function:

First figure out how many rows and columns you will have. For this I would choose the factor that is closest to \$\sqrt{n}\$:

k = min(factors, key=lambda x: abs(sqrt(n) - x))
rows, cols = sorted([k, n //k])   # have more columns than rows

Then you can use numpy.arange to get the x- and y-coordinates of the grid:

x = np.arange(0, quad_width + 1, quad_width / cols)
y = np.arange(0, quad_height + 1, quad_height / rows)

From this you now just have to construct the cells:

def get_cells(x, y):
    for x1, x2 in zip(x, x[1:]):
        for y1, y2 in zip(y, y[1:]):
            yield [x1, x2, x2, x1, x1], [y1, y1, y2, y2, y1]

Putting all of this together:

import numpy as np

def get_partitions(n, width, height):
    factors = get_factors(n)
    k = min(factors, key=lambda x: abs(sqrt(n) - x))
    rows, cols = sorted([k, n //k])   # have more columns than rows

    x = np.arange(0, width + 1, width / cols)
    y = np.arange(0, height + 1, height / rows)

    yield from get_cells(x, y)

if __name__ == "__main__":
    for cell in get_partitions(56, 1980, 1080):
        plt.plot(*cell, marker='o')
    plt.show()


Program to calculate a student's test average

Here are some comments regarding how I would approach this:

Coding Style

Avoid using comments to document things that are evident: For example, "Getter for average" is not needed when the method is a very standard getAverage method, which most people will know what is and what to expect from it. You will find many different positions on this topic, but I try to add comments just for situations where the purpose of the code is not evident, or something is used/done in a not very standard way.
Code separators: I wouldn't recommend using separators like the one you ask about for separating portions of code. IT is not very standard, and the code separation should come from good class and method definitions, and not from artificial elements.

Main Programing Considerations

Requirements and Objective: always start with clear objectives and requirements. In your case, I would say (from your comments) that it is to calculate the average score for your students. This is important because it allows you to focus on what's required, and avoid what's not needed.
Constructor: as you ask in your comments, probably the best way to create a Student is not doing it with a "blank" object, which is what you do when you don't use a constructor to set its initial state. Passing the student name to the constructor would be a better way to initialize this type of object, because there's no point (in this particular case) to create an instance of Student that has no name and belongs to nobody.
Extensibility: the way things are now, adding a new test would require more code than I would like. Adding 10 tests would require a lot of code. I would approach this using a collection of Tests, and would decide which methods I really need to supply the required functionality.
Decomposition: as your comments suggest, each Test can have it's own score and weight. I would create a Test class to keep those attributes (I would also consider adding a Name property to identify each test easily (in case I decide to print or produce the full Test summary for the Student).
Getters and setters: it is ok to have getter and setters for your class properties, but just because you have properties doesn't mean you need to provide setters and/or getters for them. I would choose for which properties I really need to have getters and setters, according to your objectives and requirements. Some properties can be modified and consumed internally (only from within the class), and that's fine. By choosing wisely the public methods each class provides (the class API), you simplify the class API, which IMHO is always desirable.

With this comments in mind, this is the code I produced to solve your problem:

Application.java

public class TestCases {
    public static void main(String[] args) {
        Student student1 = new Student("Bob");
        student1.addTestScore(new Test("test1", 80, 0.25));
        student1.addTestScore(new Test("test2", 60, 0.25));
        student1.addTestScore(new Test("final", 90, 0.5));

        student1.printStudentTestSummary();
        student1.printStudentTestAverage();
    }
}

Student.java

public class Student{

    private String name;
    private ArrayList<Test> tests = new ArrayList<>();

    public Student(String name) {
        this.name = name;
    }

    public void addTestScore(Test test) {
        tests.add(test);
    }

    public void printStudentTestAverage() {
        float average = 0;
        for (Test test: tests) {
            average += test.getWeightedScore();
        }
        System.out.println("Test average for student: " + average);
    }

    public void printStudentTestSummary() {
        System.out.println("Test scores for student: " + name);
        for (Test test: tests) {
            System.out.println(test.toString());
        }
    }
}

Test.java

public class Test {

    private String name;
    private int score;
    private double weight;

    public Test(String name, int score, double weight) {
        this.name = name;
        this.score = score < 0 ? 0 : score; // basic check for valid score
        this.weight = weight < 0 ? 0 : weight; // basic check for valid weight
    }

    public double getWeightedScore() {
        return score * weight;
    }

    public String toString() {
        return "Test: " + name + ". Score: " + score + " (w " + weight * 100 + "%).";
    }
}

Finally, see that you can now add more complex validations to scores and weights, if needed. You can easily extend this code now to support additional use cases also.

Hope this helps!


C++ return the sum of the 2 smallest elements in a vector

Missing headers

This code needs to include <vector> (for std::vector<int>) and <cstdint> (for std::uint64_t).

Don't pass collections by value

The function signature int smallest(std::vector<int> numbers) makes a copy of the input vector.  If we follow the hint that we shouldn't modify it, we can pass by reference:

int smallest(const std::vector<int>& numbers);

Even better would be to act like the standard algorithms, and not depend on the type of container at all:

template <typename Iter>
typename std::iterator_traits<Iter>::value_type
smallest(Iter first, Iter last);

Use the correct type for indexing

When indexing an collection, int isn't necessarily adequate.  Instead you should be using std::vector<int>::size_type (which is the same as std::size_t on many implementations):

using index_t = std::vector<int>::size_type;
for (index_t i = 0;  i < numbers.size();  ++i)

Use the standard algorithms

#include <algorithm>

That gives you std::partial_sort_copy().  You can fill a two-element array with the lowest two elements:

using std::begin;
using std::end;
int first_two[2];

std::partial_sort_copy(begin(nums), end(nums),
                       begin(first_two), end(first_two));

return std::accumulate(begin(first_two), end(first_two), 0);

(Yes, std::accumulate() is overkill, but it does show how to generalize this).


Synchronization algorithm for deterministic context switching between threads

Threading

Trying to use time.sleep with threading.Locks usually means you’d be better of using a threading.Condition instead. It lets you wait passively instead of using an active while True: ... time.sleep(0.001).

However, in your case, you could simplify further using a threading.Event:

class Synchronizer:
    def __init__(self, num_instances):
        ...
        self._lock = threading.Event()

    def lock(self, idx):
        while self._current != idx:
            self._lock.wait()
            if self._want_abort:
                raise SynchronizerAbort()
        self._lock.clear()

    def die(self):
        self._want_abort = True
        self._lock.set()

    def yield_to(self, idx=None):
        ...
        self._current = idx
        self._lock.set()

Every thread, except the 0\$^{th}\$ one, will enter the while self._current != idx loop and wait for the Event to become available. Once available after thread 0 exits yield_to, only the one with the right ID will exit the loop and all the others will wait on the Event to be set again.

Now what have we here? Every thread needing to wait at a synchronization point, loop until a condition becomes available, and check for a flag that indicates if an other thread went through an error… Time to change for a threading.Barrier (Python 3.2 and up).

There is a drawback to using barriers, in that they must be reached by all threads before they are all released at once. Meaning we can't let DeterministicRunner.run exit before all threads are done. So we must have Synchronizer.lock return a boolean value indicating if we are running out of instances or not.

class Synchronizer:
    def __init__(self, num_instances):
        ...
        self._barrier = threading.Barrier(num_instances)

    def lock(self, idx):
        while True: # Force any thread to enter, independently of its idx
            self._barrier.wait()
            if not self._instances:
                # All threads exit at once when everything is done
                return False
            if self._current == idx:
                # Only the active thread can exit otherwise
                return True

    # No need of `die` anymore
    def yield_to(self, idx=None):
        if idx is None:
            idx = self._get_next_instance()

        if idx not in self._instances:
            self._barrier.abort() # Make all other thread abort with BrokenBarrierError
            raise Exception('Can not yield to non-existent instance "%s"' % idx)

        self._current = idx

Coding Style

It is recommended that

import threading, time, types

is written

import threading
import time
import types

However, since you’re making very little use of time and types I’d rather recommend the from .. import .. form.

Other than that, there is little to talk about. It is mostly a matter of taste:

converting the generator parameter of _run_threads into a list could be done using the variable-length argument syntax:

def _run_threads(*threads):
    for thread in threads:
        thread.start()

    for thread in threads:
        thread.join()

and call it with _run_threads(*(<generator_expression>)).
DeterministicRunner.run might be better written with the try within the while to reduce the amount of protected code:

def run(self):
    while True:
        self._syncer.lock(self.idx)
        try:
            n = next(self._g)
        except StopIteration:
            self._syncer.remove(self.idx)
            break
        else:
            self._syncer.yield_to(n)

note that when using barriers, you have to while self._syncer.lock(self.idx): and not break.
Synchronizer._get_next_instance might be more readable using plain list iteration:

def _get_next_instance(self):
    for n in self._instances:
        if n > self._current:
            return n
    return self._instances[0]

I'd check that the methods returns an object that has a __next__ method rather than being of type GeneratorType. It allows for more flexibility for anyone using your API and wanting to provide a custom class rather than generator functions.

You are also using a custom made exception for cleanup purposes but you use generic Exceptions for errors in using your API. I'd go the other way around and use custom exceptions that are easier to handle for real errors and generic ones for cleanup.

Proposed Improvements

import threading

class SynchronizeError(Exception):
    """Abort execution because a thread does not respect the API"""

class Synchronizer:
    def __init__(self, num_instances):
        self._instances = list(range(num_instances))
        self._current = 0

        self._barrier = threading.Barrier(num_instances)

    def lock(self, idx):
        while True:
            self._barrier.wait()
            if not self._instances:
                return False
            if self._current == idx:
                return True

    def yield_to(self, idx=None):
        if idx is None:
            idx = self._get_next_instance()

        if idx not in self._instances:
            self._barrier.abort() # All other threads get BrokenBarrierError
            raise SynchronizeError(
                'Can not yield to non-existent instance "{}"'.format(idx))

        self._current = idx

    def _get_next_instance(self):
        if self._current >= self._instances[-1]:
            return self._instances[0]
        for n in self._instances:
            if n > self._current:
                return n

    def remove(self, idx):
        self._instances.remove(idx)
        if self._instances:
            self.yield_to()

class DeterministicRunner:
    def __init__(self, syncer, idx, method):
        self._syncer = syncer
        self._idx = idx

        self._g = method()
        if not hasattr(self._g, '__next__'):
            raise SynchronizeError('Not a generator')

    def run(self):
        while self._syncer.lock(self._idx):
            try:
                n = next(self._g)
            except StopIteration:
                self._syncer.remove(self._idx)
            else:
                self._syncer.yield_to(n)

def _run_threads(*threads):
    for t in threads:
        t.start()

    for t in threads:
        t.join()

def run(*consumers):
    sync = Synchronizer(len(consumers))
    _run_threads(*(
        threading.Thread(target=DeterministicRunner(sync, i, c).run)
        for i, c in enumerate(consumers)
    ))


On my windows 10 laptop, I ran your program on a dummy log file under the python
profiler using the command line:

python -m cProfile -s cumulative loggrep.py "speech" \data\test.log

The dummy log file has about 4.3 Mbytes of text spread across about 100k lines
comprising 32772 log entries.  The search pattern was "speech", which occured
444 times.

This is the ouput of the profiler:

     1322924 function calls (1322872 primitive calls) in 2.006 seconds

Ordered by: cumulative time

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
   7/1    0.000    0.000    2.006    2.006 {built-in method builtins.exec}
     1    0.000    0.000    2.006    2.006 loggrep.py:3(<module>)
     1    0.077    0.077    1.997    1.997 loggrep.py:38(process)
100003    0.136    0.000    1.788    0.000 loggrep.py:42(processLine)
 32772    0.013    0.000    1.369    0.000 loggrep.py:60(flush)              <-----
   444    0.014    0.000    1.355    0.003 loggrep.py:67(printBuffer)        <-----
  9722    1.341    0.000    1.341    0.000 {built-in method builtins.print}  <-----
100003    0.061    0.000    0.132    0.000 loggrep.py:71(addToBuffer)
100004    0.042    0.000    0.116    0.000 fileinput.py:248(__next__)
100003    0.028    0.000    0.075    0.000 loggrep.py:80(isEntryHead)
100004    0.060    0.000    0.071    0.000 {method 'readline' of '_io.TextIOWrapper' objects}
195293    0.068    0.000    0.068    0.000 {method 'search' of '_sre.SRE_Pattern' objects}
100003    0.027    0.000    0.062    0.000 loggrep.py:83(isEntryTail)
 95290    0.027    0.000    0.060    0.000 loggrep.py:86(lineMatches)
100010    0.047    0.000    0.047    0.000 {method 'match' of '_sre.SRE_Pattern' objects}

The header shows the program took 2.006 seconds to run. Looking at the
lines marked with "<-----", we see that flush() was called 32772 times
and took about 1.369 seconds.  From the code, we know flush() calls
printbuffer(), which calls print().  The profile says print() was
called 9722 times taking 1.341 seconds, or about 65% of the total run time.

I changed entryTailPattern to "\|!\s*$".  This let me get rid of the
.rstrip() on each line so that the lines would keep the '\n' at the end.
This let me change the print() for loop in printBuffer() to a call to
sys.stdout.writelines().  This saved about 0.5 seconds over the print()
for loop.

All the other function calls seem to be in the noise, so i don't see any other
promising things to try.


Output CSS class based on day-of-the-week match

I would suggest you familiarize yourself with the DateTime class and it's related classes including DateInterval and DatePeriod as these are your most powerful tools for working with date/times, intervals of time, and iterating over intervals of time.

You should have no reason to build an array for days for the week or anything like that.

Let me give an example for how you might approach this problem using these classes.

// current DateTime
$now = new DateTime();
// create a DateTime representing the beginning of the week
$monday = clone $now;
$monday->setTime(0,0,0)
       ->modify('Monday this week');
// create a DateInterval to represent a one day interval
$dayInterval = new DateInterval('P1D');
// create a DatePeriod to represent a full week
$weekPeriod = new DatePeriod($monday, $dayInterval, 7);
// iterate the DatePeriod
foreach($weekPeriod as $day) {
    if($day->format('D') === $now->format('D')) {
        // today matches this day of week
    }
}

Beyond that, I would suggest being cognizant of your styling.  Right now:
- your indentations are inconsistent
- your variable naming style in inconsistent between using snake_case, camelCase (like in $dataarray keys), and no way to differentiate words in your variable name at all (i.e.$dayofweek, $dataarray).  You should pick either snake_case or camelCase to make your code more readable and stick with whichever style you choose.  I would actually recommend camelCase as PHP, as a language, is moving more in that direction with regard to industry styling standards.


I would probably create a separate validateConfig() method on the class, such that your code might look like:

public function __construct(
    array $config,
    EntityManager $em,
    EventDispatcherInterface $dispatcher
) {
    $this->validateConfig($config);
    $this->em = $em;
    $this->dispatcher = $dispatcher;
    $this->endpoint = $config['endPoint'];
    // set other config-driven properties here
    $this->apiClient = $this->createApiClient();
}

protected function validateConfig($config) {
    if (!isset($config['endPoint'])) {
        throw new ConfigurationException();
    }
    if (!isset(
        $config['partnerLogin'],
        $config['partnerPass'],
        $config['account_id'],
        $config['user_id']
    ) {
        throw new MissingCredentialsException();
    }
}

However, that might not be getting you where you ultimately would like to go.  I would suggest that with a config with as many "properties" (your array keys) as you have, that you might consider creating an actual config class to be passed to constructor. This would allow you to type hint against the object type and place logic for validating the config into its own class.  This class would then be 100% assured the dependencies it needs in its constructor are met.

This approach could easily be achieved without much change to the calling code.  Instead of something like:

$object = new YourClass($config, $em, $dispatcher);

You could simply do:

$object = new YourClass(
    new YourClassConfig($array),
    $em,
    $dispatcher
);

Also, if you are going through the trouble of validating dependencies in this manner, is only looking for presence of an array value being set going far enough to make sure your object is set up in proper state? What if these values are set to empty strings or other non-sensical values for your context?


I don't know the other conditions but I would do it like this:

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    var memberNames = new List<string>();

    bool isValidDateOfBirth = DateOfBirth > DateTime.MinValue && DateOfBirth < DateTime.MaxValue && Age.HasValue;
    if (!isValidDateOfBirth)
    {
        memberNames.Add("DateOfBirth");
        yield return new ValidationResult("Invalid date, please enter your date of birth", memberNames);
    }

    bool isValidAge = Age.HasValue && Age.Value >= 18 && Age <= 75;
    if (!isValidAge)
    {
        memberNames.Add("DateOfBirth");
        yield return new ValidationResult("Age must be between 18 and 75 years", memberNames);
    }

    bool isValidGender = Gender.HasValue;
    if (!isValidGender)
    {
        memberNames.Add("Gender");
        yield return new ValidationResult("This field is required", memberNames);
    }
}


Specific feedback on performance would be appreciated.

There are some things to improve performance-wise:

on every single iteration, you are calculating all the 3 remainders, even though you need a single one (in the best case)
the 0 in fizzBuzzValues check is not really needed (and the "in list" is O(n) in general, even though n=3 in this case, but you are doing that in a loop) - you can compare each of the remainders one by one
if you can calculate something before the loop - always do it - the fizzNumber * buzzNumber can be defined before the loop

Modified code:

def fizz_buzz_new(fizz_number, buzz_number):
    fizz_buzz_number = fizz_number * buzz_number
    for i in range(1, 101):
        if i % fizz_buzz_number == 0:
            print("Fizzbuzz")
        elif i % fizz_number == 0:
            print("Fizz")
        elif i % buzz_number == 0:
            print("Buzz")
        else:
            print(i)

Some timeit tests (replaced print() with yield to avoid seeing impact of printing to stdout):

$ ipython3 -i test.py

In [1]: %timeit for x in range(100): list(fizzBuzz(3, 5))
100 loops, best of 3: 3.52 ms per loop

In [2]: %timeit for x in range(100): list(fizz_buzz_new(3, 5))
100 loops, best of 3: 1.98 ms per loop


Should I be using Regex to uppercase uncommon characters?

One-to-one substitution is precisely what tr is for.

def norwegian_upcase(string)
  string.upcase.tr('æ-ý','Æ-Ý')
end

That being said, the unicode_utils gem provides a method for this:

def norwegian_upcase(string)
  UnicodeUtils.upcase(string, :no)
end

I don't know Norwegian, but you can supply language subtags :nb (Norwegian Bokmal) or :nn (Norwegian Nynorsk) if they would behave differently than general :no (Norwegian).


Binding touch events and moving an element

Could you write something like this?

var limited = function( value, limit ){
    if (value >= limit) {
        return limit;
    } else if (value <= 0) {
        return 0;
    } else {
        return value;
    }
}

then, when you need to work out move, just write move = limited( difference, limit );


Static class for constants with reference to java resources

well as pointed out using singletons is considered bad practice and using global constants in an object-orientatd world is bad practice as well...

So, what is your suggestion?

Consider the purpose of the attribute

you want to define a app-specific attribute (color), an attribute you want to configure - this is the very reason why you use ressources, right. Or do you want to define a constant?

 1. it's a constant

if you don't want to specify a configurable attribute you should define a constant in your app

private static final int COLOR_ONE = 0x123456;

 2. it's an attribute

but if you want to specify a configurable attribute you simply define it as such in your app:

int colorOne = MainActivity.getContext().getResources().getColor(R.color.colorOne);

you are right, this might be a bit intricately so it would be just as simple to wrap this call in a method

private int getColorFromRessource(int colorId){
    return MainActivity.getContext().getResources().getColor(colorId);
}

this would be applied in your setup of the Paint in an quite easy way:

public ScreenArea(Rect area) {
    this.area = area;
    paint = new Paint();
    paint.setColor(getColorFromRessource(R.color.colorOne)); //obvious
  //paint.setColor(Attributes.COLOR_ONE);  far less obvious
}


Two ways to remove duplicates from a list

The teacher is obviously using a better way. Check/read more about time complexity for lists in python here (python wiki).
In your case, you are going for a time complexity:

\$ O(n) \$ for iteration
\$ O(n) \$ for .count()
\$ O(n) \$ for intermediate pop
\$ O(n) \$ for .index

for a final (worst case) time: \$ O(n^2) \$ (see explanation in comments from superb rain).
In case of the tutorial:

\$ O(n) \$ for iteration
\$ O(k) \$ for not in check (using \$ k \$ since the list is different now.
\$ O(1) \$ for append

generating a worst case performance of \$ O(n \cdot k) \$.

A more efficient solution, disregarding the order of elements would be the call:
uniques = list(set(numbers))

as suggested in comments. This would have \$ O(n) \$ time.


Add elements to collection conditionally

You could do a loop over the elements that you are always adding:

for (var info in ["basket", "account", "delivery", "payment", "placeorder"] {
    this.state_collection.add (new OrderWizardState ({ state: info, phase: this.phase_collection.findWhere ({ phase: info }) }));
}

And to add the special one, you use your if statement and insert it at a specific index:

if ( _.has (this.regions, "lp")) {
    var state = new OrderWizardState({ state: 'loyaltypoints', phase: this.phase_collection.findWhere({ phase: 'account' }) })
    this.state_collection.insert (2, state);
}


How about

if BlackOrWhite == 1:
  if oldtrial == high:
    newtrial = oldtrial+factorIncrease*(high-low)+1
    high = newtrial
    low = oldtrial
  elif high-oldtrial==1:
    finished = 1
    newtrial = oldtrial
  else:
    newtrial = oldtrial+(high-oldtrial)/2
    low = oldtrial

For simplifying your ifs?


Did you ever test it with buffers which are multiples of 8 long?
Because the last block won't get the nice printable display.
Are you sure the newline at the beginning of the output should be there?
Should the test-output really contain the implicit 0-terminator?
return 0; is implicit for main().

Modified test-function:

int main()
{
    const char test[] = "abcdef123456\0zyxwvu987654";
    std::string s(test, sizeof(test) - 1);

    std::cout << "---\n";
    hex_dump(std::cout, s);
    std::cout << "---\n";
    hex_dump(std::cout, "");
    std::cout << "---\n";
    hex_dump(std::cout, "12345678");
    std::cout << "---\n";
    hex_dump(std::cout, "1234567812345678");
    std::cout << "---\n";
}

Do you have the opening brace for functions on its own line or not? Seems 2+1 for, 1 against...
If you only want to output a single character, using a character is potentially more efficient than a string.
The conditional operator is excellent for choosing between two values.
Beware of the implementation-defined signedness of plain char. The character-classification-functions inherited from C expect the value of an unsigned char or EOF.
See std::isprint.
Consider marking internal functions static to avoid externally visible symbols and promote inlining.
If you don't actually ever use a return-value, why provide one?

static void render_printable_chars(std::ostream& os, const char* buffer, size_t bufsize)
{
    os << " | ";
    for (size_t i = 0; i < bufsize; ++i)
        os << (std::isprint((unsigned char)buffer[i]) ? buffer[i] : '.');
}

Don't play around with a useless flag just because. Tracing data-flow is quite a lot more involved than following the program-flow.
Testing whether a variable already has a value before setting it to the same is rarely anything but obfuscation and pessimisation.
Don't use std::endl unless you really want to flush. And if that's your intention, consider being more explicit by using std::flush.
If you use C++17, you might want to accept a std::string_view by value instead of a std::string by constant reference. It's generally more efficient.


Interesting question,

The most striking thing is your repeated use of this pattern:

connection.sanitizeId(response['xxx']);

I dont believe sanitizeId should be a function of connection. Also, response is not a good name because it often is part of a response from the query and not the actual response. And, it is suggested that response.xxx makes more sense than response['xxx']. To that end, I feel that sanitizeId should be part of the response or data. Also, I would be tempted to call it simply sanitize.

function addSanitizer( data , server){
  data.sanitize = function( propertyName ){
    return this[propertyName].replace( server , "" );
  }
  return data;
}

Then you could do

function Node(response) {
    this.id   = response.sanitize( 'self' );
    this.data = response.data;
}

Or, if you agree that response might be misleading

function Node(node) {
    this.id   = node.sanitize( 'self' );
    this.data = node.data;
}

Node with be called like this:

getNode: function (id, callback) {
    var connection = this;
    get(this.server + id + "/properties", function (data) {
        if (data == null) data = {data: {}};
        else data = {data: data};
        data['self'] = id;
        callback(new Node(this.addSanitizer( data, this.server ), data));
    });
},

From a style point:

You are skipping new lines on your if statements: if (data == null) data = {data: {}};, dont do that
Your code stretches quite a bit horizontally, but not too bad, feel free to to split up some of your longer lines into something more readable, this :

createRelation: function (start, target, type, callback) {
    var connection = this;
    post(this.server + start + '/relationships', {to: this.server + target, type: type}, function (data) {
        callback(new Relation(connection, data));
    });
}

could be

createRelation: function (start, target, type, callback) {
    var connection = this,
        data = {to: this.server + target, type: type};
    post(this.server + start + '/relationships', data , function (data){
        callback(new Relation(connection, data));
    });
}

The code looks all in all fine to me. For a Java developer you did good :P


Retrieving lists of consecutive capitalised words from a list

A trivial optimisation that iterates on the tokens instead of by index (remember that in Python lists are iterables, it's unPythonic to iterate a list by index):

def retrieve(tokens):
    results = []
    group = []
    for token in tokens:
        if token[0].isupper():
            group.append(token)
        else:
            if group:  # group is not empty
                results.append(group)
            group = []  # reset group
    return results

A solution like @JeremyK's with a list comprehension and regular expressions is always going to be more compact. I am only giving this answer to point out how lists should be iterated.


The implementation isn't correct, because it doesn't traverse sub-trees. Consider

Node 1 [Node 2 [Node 3 []]]

Then your folding function will only fold over 1 and 2, but not over 3.

If you have a recursive structure like this, a folding function over it must also be recursive. Otherwise it won't be able to traverse arbitrarily large recursive structure.

For the other question: If you specialize the folding function as

treeFold :: ([Char] -> [[Char]] -> [Char]) -> (Char -> [Char])
         -> Tree Char -> [Char]

by setting b = [Char], you get what you're looking for - converting a Tree Char to String. You just need to supply the two function for folding, for example

treeFold (\x ys -> x ++ concat ys) (: [])

Update: The signature also isn't correct. The general rule is that the folding function should have one additional argument for each constructor of the data type where recursive types (here Tree a) are replaced by the result of the fold:

treeFold :: (a -> [b] -> b) -> Tree a -> b

For example for a list you have 2 constructors: (:) :: a -> [a] -> [a] and [] :: [a], so its folding function is

foldr :: (a -> b -> b) -> b -> [a] -> b