Notifying Students in Courses - Strategically

This smells of a message chain and violates the Law of Demeter (principle of least knowledge):

treeListViewModel.Courses[i].Students[DataNotificationList[n]].ExecuteStrategy(hasError());

Your caller very like doesn't care of the exact internal workings of a course - it should just dispatch the notifications and see if it succeeded. So a Course should probably get a method like bool NotifyStudent(int studentId, bool hasError).
When you use expressions like DataNotificationList[n] in several places then it is usually better to put it in a local variable which expresses the meaning of it and also makes the code shorter, for example like this: int studentId = DataNotificationList[n];
If you don't actually need the index then foreach will usually suffice and is shorter.

So in total your refactored code could look like this:

    foreach (int studentId in DataNotificationList)
    {
        foreach (Course course in treeListViewModel.Courses)
        {
            if (course.NotifyStudent(studentId, hasError()))
            {
                break;
            }
        }
    }

or if you want to go with a bit more LINQ:

    foreach (int studentId in DataNotificationList)
    {
        var course = treeListViewModel.Courses
                        .FirstOrDefault(c => c.NotifyStudent(studentId, hasError()));
        // could log something here and maybe raise an event handler
        // to say that a student in a course has been notified
    }

The NotifyStudent method in the course is responsible to check if the student exists in the course and return true once it has executed the strategy. It is totally encapsulated in the course and the caller doesn't have to know about any internals.


If you're looking for performance then you should, at least, provide a specialized version for the most common cases:

void big_endian_size(uint8_t to[], size_t from) {
#if UINT32_MAX == SIZE_MAX
    // Specialization for 4 bytes size_t
#elif UINT64_MAX == SIZE_MAX
    // Same as above but for 8 bytes size_t
#else
    // Your current implementation...
#endif
}

Specialized versions may simply reuse this:

to[3] = from & 0x000000FF);
to[2] = (from & 0x0000FF00) >> 8;
// And so on...

Note that you may also simply return another size_t (instead of an array) with its bytes rotated. This will be considerably faster (also if implemented with a plain for to go through all bytes).

Also note that if you extract the 32 bit swap code into a separate function then you can use it both for 32 bit and 64 bit sizes (for example see byteswap.h for an implementation).

Do you need more? Assembly. For example on X86/X64 assembly you have BSWAP that does it in one instruction (I remember also ARM has but I don't remember the mnemonic), just check for target architecture to provide more and specialized versions.

Notes: Why &? Because truncation (let's imagine uint8_t val = 0xffffffff >> 8) is platform specific.


Sorting multiple vectors based on a reference vector

For another take on the same problem (sorting parallel arrays), see Quicksort template (for sorting corresponding arrays).

Your code is strangely organized. I would expect it to have a single entry point, something like this:

template<class Vector, class... Vectors>
void parallel_sort(Vector& keyvector, Vectors&... vectors) {
    std::vector<size_t> order(keyvector.size());
    std::iota(order.begin(), order.end(), 0);
    std::sort(order.begin(), order.end(), [&](size_t a, size_t b) {
        return keyvector[a] < keyvector[b];
    });
    (reorder(keyvector, order) , ... , reorder(vectors, order));
}

(Hey, look at that! It's a complete implementation, except for the reorder function you already wrote!)

But instead you require the calling code to set up their own order vector manually, then call create_permutation, then sort_from_ref, in that order. That's a lot of steps. At the very least, you could provide a function create_order_vector to simplify that first step.

The one advantage I can see to requiring the caller to provide the order vector is that it allows your library code to do no heap allocations. Vice versa, a problem with my code above is that it requires O(n) memory to sort n elements. If I have a million-element vector, I need to heap-allocate another eight million bytes to sort it! That could be annoying or prohibitive for some callers — they might not expect a sorting function to throw std::bad_alloc. At least by making the caller allocate the eight million bytes themselves, you're putting the issue front and center where they can't miss it.

I think it's strange that you define the alias order_type to be std::vector<std::pair<size_t, iter>>. I would rather see

using order_type = std::pair<size_t, iter>;

[...] std::vector<order_type> order;

Again, I guess it comes down to my wanting to see std::vector-ness explicitly in the code. I have the same complaint about typedefs such as using Foo = foo*; that hide a type's pointer-ness.

template<typename T, typename A, typename... argtype>
void sort_from_ref(order_type order, std::vector<T,A> &vect, argtype &&...args)
{
        reorder(vect, order);
        sort_from_ref(order, std::forward<argtype>(args)...);
}

In C++17, you can use a comma-operator fold-expression to do this, as I did above. But even in C++11, you can use a pack expansion to do this without all the "recursive template" stuff. (See "Iteration is better than recursion.") You'd just do something like this:

template<class... Args>
void sort_from_ref(order_type order, Args&... args)
{
    int dummy[] = {
        [&]() { reorder(args, order); return 0; } ...
    };
}

Notice that I also changed argtype to Args. It's a pack of multiple argtypes, not just one; and the C++ convention for template parameters is to CamelCase them.

I also eliminated your perfect forwarding. We know that all our args are going to be non-const lvalue references; so we should just say so.

We also know that all our args are going to be std::vector<T> for some T, because that's the only kind of argument that will be accepted by our reorder template. Therefore, it is incorrect (but largely harmless) that you wrote

template<typename T, typename A, [...]>
void sort_from_ref([...] std::vector<T,A> &vect, [...]

because there is only one possible A that can go there and have the code still compile. You should just have said

template<typename T, typename... argtype>
void sort_from_ref(order_type order, std::vector<T>& vect, argtype&&... args)

(except that, as we've seen, you don't need this "recursive" template at all).

No comment on your reorder function; that part is all math. (Does it work? Did you test it exhaustively?)

Okay, two comments...

                    index[i].first = old_target_idx;
                    vect[i]   = old_target_v;

Your whitespace here (and other places) is wonky. It looks like maybe you were trying to align the = signs, but failed? I strongly recommend not trying to align anything, ever. It's not robust against refactoring. (For example, if you change the name of a variable, now you have to realign everything it touched.)

for (int i=0; i< vect.size(); i++)

You should be getting a stupid warning from your compiler about "comparing signed and unsigned" here. If you're not, then turn up your warning levels — you should be using -W -Wall (and maybe -Wextra) on non-MSVC compilers, and I'd say -W4 on MSVC. The traditional workaround would be to make i a size_t instead of an int.


Adapter for RecyclerView with supported onClick handling and select color text on last clicked item

I like nitwitting about kotlin, therefor only feedback about the language.
single expression functions
If your function exists out of one expression, you can write it easier.
Instead of having to write:
override fun getItemCount(): Int {
    return items.size
}

you can write:
override fun getItemCount() = items.size

code duplication
Try to remove as much duplication as possible.
if (audioRecordUI.isActive)
    itemView.name.setTextColor(itemView.context.getColor(R.color.grenadier))
else
    itemView.name.setTextColor(itemView.context.getColor(R.color.black))

In the code above, you do three things:

Choose a colorId
Get the matching color
set the itemview to the color

Actions 2 and 3 are duplicated.
With a simple variable, this code becomes much clearer.
val textColorId = if(audioRecordUi.isActive) R.color.grenadier else R.color.black
itemView.name.setTextColor(itemView.context.getColor(textColorId))

scoped functions
When you need to reuse a variable multiple times after eachother, you can use a scoped function, eg also and apply.
instead of writing:
itemView.select.isChecked = !itemView.select.isChecked

you can write:
itemView.select.also { it.isChecked = !it.isChecked }

or even:
itemView.select.apply { this.isChecked = !this.isChecked }

And as you don't have to write this:
itemView.select.apply { isChecked = !isChecked }

Personal choice
I personally don't like the three lines for a simple if:
if (!isSelectableMode) {
    clearSelect()
}

If it's this short, I would place it on one line.
If it would be a bit longer, two lines without brackets.
if (!isSelectableMode) clearSelect()


Binary Min Heap data structure implementation

You have duplicated code in your constructors, the default constructor should call the other one with capacity.
Maybe make the capacity = 100 constant and name it something like DEFAULT_INITIAL_CAPACITY.
Your tests are not named. After reading a name of a test (or anything you name in general) you should have some sort of understanding, what the test tests.
You test too many things at once. One test should test one aspect of your code. You call offer n times and assert the peek value, after that you poll and offer and assert the poll value. Better would be to split it and test the poll and offer mechanism seperately. So actually the first part could fail, while the second one would be okay, or the other way round. So you are never really sure, what really failed. You also don't have to call offer n times, it shouldn't make any difference, does it? If it would, it should be a separate test anyway.
test2() isn't meaningful, either, I mean, what's the difference between the first test, except larger numbers? I'm sure you want to test the resize of the inner array, but how does one know? I'd do something like this:

@Test
public void exceedingHeapsizeCapacityIncreaseHeapCapacity() {
    int heapCapacity = 1;
    BinaryHeap2 heap = new BinaryHeap2(1);

    heap.offer(1);
    heap.offer(1);

    // no assertion, if resize wouldn't work, 2nd call would throw Exception... maybe a method to provide the actual capacity wouldn't be _that_ bad
}

To call 'display' in a test doesn't make sense either, if you have thousands of test in an application, you just fill the console with crap and makes actual troubleshooting much harder, better to have debug or trace debugging within the class under test and activate it, when you have to troubleshoot your test or something in production.
The type has a "display" method. Usually you have an own 'View' Type. You just pass your Heap and tell the View "display your contents" (think as if you want to change the 'presentation layer', like, if you want to display it in a browser as html, the type must not write html itself)
Try to avoid naming variables like i and j. If you read the method swap by itself, you do not know, what i and j means, a method shall be as self explanatory as possible. To really understand it, you have to check, who actually calls this method.
The intention of heapifyDown is not very clear. I've read it three times and still don't understand it - goal should be, that you can read it once and understand it, shouldn't it? I think that's possible in that case. The break in the while loop hurts, can't you do that within the while condition, too?
The ordering of of public/private methods is always a discussion. It usually is public to private. But I also like to order it as how the code is called. Like you have public void offer, and you call heapifyUp, which is just under it, which I actually really like. But: The getSize() can moved beneath heapifyDown.


What changes can I make to simply this function that groups parameter key value pairs

Consistency
Sometimes you are using whitespace around operators, sometimes you don't. Sometimes you are using whitespace between the message name and the argument list of a message send, sometimes you don't.
You should choose one style and stick with it. If you are editing some existing code, you should adapt your style to be the same as the existing code. If you are part of a team, you should adapt your style to match the rest of the team.
Most communities have developed standardized community style guides. In Ruby, there are multiple such style guides. They all agree on the basics (e.g. indentation is 2 spaces), but they might disagree on more specific points (single quotes or double quotes).
In general, if you use two different ways to write the exact same thing, the reader will think that you want to convey a message with that. So, you should only use two different ways of writing the same thing IFF you actually want to convey some extra information.
For example, some people always use parentheses for defining and calling purely functional side-effect free methods, and never use parentheses for defining and calling impure methods. That is a good reason to use two different styles (parentheses and no parentheses) for doing the same thing (defining methods).
Whitespace around operators
There should be 1 space either side of an operator.
Whitespace in hash literals
In a hash literal, there should be one space after the opening curly brace and one space before the closing curly brace.
New-style hash literals
Well, they are called "new-style" or "Ruby 1.9" hash literals, but really, they were introduced in 2007, and we have Ruby 3.0 soon, so we should really simply be calling them "hash literals" at this point. They are neither new anymore nor is Ruby 1.9 still relevant.
Ruby 1.9 introduced a shortcut syntax for hash literals where keys are symbols, inspired by ECMAScript.
So, this:
{:arg => ARGV[i], :val => ARGV[i+1]}

should be this:
{ arg: ARGV[i], val: ARGV[i+1] }

Frozen string literals
Immutable data structures and purely functional code are always preferred, unless mutability and side-effects are required for clarity or performance. In Ruby, strings are always mutable, but there is a magic comment you can add to your files (also available as a command-line option for the Ruby engine), which will automatically make all literal strings immutable:
# frozen_string_literal: true

It is generally preferred to add this comment to all your files.
No space before parameter list
In a method definition, there should be no whitespace between the method name and the parameter list, e.g. this:
def self.get_params (ary)

should be
def self.get_params(ary)

Ruby allows you to specify a parameter list either in parentheses or with whitespace. If you combine the two, it could get confusing, because Ruby also allows array destructuring in parameter lists:
def foo(((first_of_first, second_of_first), second))
  second_of_first
end

foo([[23, 42], 'Hello'])
#=> 42

Array destructuring is performed by adding an additional set of parentheses. Now, if you have a method with two parameters, you can write it like this:
def foo(bar, baz)
end

or like this:
def foo bar, baz
end

If you write it like this:
def foo (bar, baz)
end

A reader might think that this is a single parameter that uses array destructuring. In fact, Ruby even prints a warning that tells you exactly that:
warning: parentheses after method name is interpreted as an argument list, not a decomposed argument

No space before argument list
In a message send, there should be no whitespace between the message and the argument list, e.g. this:
args.push ({:arg => ARGV[i], :val => ARGV[i+1]})

should be
args.push({:arg => ARGV[i], :val => ARGV[i+1]})

This will bite you as soon as you have more than one argument. Ruby allows you to write the argument list to a message send without parentheses like this:
foo.bar baz, quux

instead of
foo.bar(baz, quux)

The problem arises because the whitespace triggers the first mode, so
foo.bar (baz, quux)

is not interpreted as two arguments baz and quux but as passing arguments with whitespace instead of parentheses and thus as a single argument (baz, quux). Except (baz, quux) is not legal Ruby code, and thus you get an error.
Warnings
The Ruby developers work hard on providing helpful warning messages. You should read them and investigate them. They almost always point to problems or at least potential problems in your code.
For example, running your code generates the following warning message:
warning: parentheses after method name is interpreted as an argument list, not a decomposed argument

Unused parameter
Your get_params method is defined with one parameter ary, but you are not using this parameter anywhere. It is completely useless.
If you have a parameter or a local variable that is intentionally unused, the Ruby community standard is to name it with a leading underscore, e.g. _ary or even just _.
However, in this case, it serves absolutely no purpose and should simply be removed altogether.
Empty literals
Instead of using the new method to create instances of core classes, you should prefer to use literals. E.g. use '' or "" instead of String.new, [] instead of Array.new, and so forth.
This is especially true for empty objects.
args = Array.new

should be
args = []

Prefer each over for / in
Nobody in Ruby uses for / in. In fact, we hardly use any loops at all. I would go so far as to say, when you are using a loop, you are doing it wrong.
The idiomatic way would be to use Range#each instead. Not only is each more idiomatic, but for / in has this weird scoping rule where the loop variable escapes into the surrounding scope, which is almost always not what you want.
So, this:
for i in 0..ARGV.size-1
  if ARGV[i].start_with?('-') and i < ARGV.size + 1
    args.push ({:arg => ARGV[i], :val => ARGV[i+1]})
  end
end

should become this:
(0..ARGV.size-1).each do |i|
  if ARGV[i].start_with?('-') and i < ARGV.size + 1
    args.push ({:arg => ARGV[i], :val => ARGV[i+1]})
  end
end

Actually, there is a lot more that can be improved about that, but we will stick with the purely mechanical transformations for now, and keep our brain switched off.
Modifier if
If you have a conditional expression with only a single expression in the body and no else, it is generally preferred to use the modifier form.
if ARGV[i].start_with?('-') and i < ARGV.size + 1
  args.push ({:arg => ARGV[i], :val => ARGV[i+1]})
end

should be
args.push ({:arg => ARGV[i], :val => ARGV[i+1]}) if ARGV[i].start_with?('-') and i < ARGV.size + 1

Prefer symbolic operators ||, &&, ! over keywords and, or, not
In a boolean expression, you should prefer the symbolic operators over the keywords. The keywords have doubly-unexpected precedence: not only is the precedence of the keywords and and or much lower than the precedence of && and ||, but also and and or both have the same precedence while && has higher precedence than ||. This can be very confusing.
Idiomatic Ruby community standard is to always use the symbolic operators, except for when you actually use boolean logic for control flow, as in
do_something and exit

So,
ARGV[i].start_with?('-') and i < ARGV.size + 1

should be
ARGV[i].start_with?('-') && i < ARGV.size + 1

Redundant return
The return value of a method is the value of the last expression that was evaluated inside the method. Unless you want an early return, it is generally not necessary to use return at all.
Linting
You should run some sort of linter or static analyzer on your code. Rubocop is a popular one, but there are others.
Rubocop was able to detect all of the style violations I pointed out above (plus some more), and also was able to autocorrect all of the ones I listed.
Let me repeat that: I have just spent two pages pointing out how to correct tons of stuff that you can actually correct within milliseconds at the push of a button. I have set up my editor such that it automatically runs Rubocop with auto-fix as soon as I hit "save".
In particular, running Rubocop on your code, it detects 19 offenses, of which it can automatically correct 17. This leaves you with 2 offenses, both of which are very simple.
Here's what the result of the auto-fix looks like:
#!/usr/bin/env ruby
# frozen_string_literal: true

class Script_Helper
  def self.get_params(_ary)
    args = []
    unless ARGV.empty?
      (0..ARGV.size - 1).each do |i|
        args.push({ arg: ARGV[i], val: ARGV[i + 1] }) if ARGV[i].start_with?('-') && (i < ARGV.size + 1)
      end
    end
    args
  end
end

And here are the offenses that Rubocop could not automatically correct:
Offenses:

script_helper.rb:4:1: C: Style/Documentation: Missing top-level class documentation comment.
class Script_Helper
^^^^^

script_helper.rb:4:7: C: Naming/ClassAndModuleCamelCase: Use CamelCase for classes and modules.
class Script_Helper
      ^^^^^^^^^^^^^

1 file inspected, 2 offenses detected

Let's look at the simple one first.
Naming
Class names should be PascalCase, constants should be SCREAMING_SNAKE_CASE, everything else should be snake_case. Files should be named after the primary module or class they define, and they should be named in snake_case as well.
So, the name of your class should be ScriptHelper, not Script_Helper.
Unused parameter, take 2
As mentioned above, the parameter should be removed. Rubocop only automatically renamed it, because removing it could break code that calls this method with an argument.
But since it isn't used, it should simply be removed and all callers fixed to not pass an argument.
Vertical whitespace
Your method could use some vertical whitespace to give the code more room to breathe. I would suggest at least separating the initialization at the beginning of the method, and the return at the end:
def self.get_params(_ary)
  args = []

  unless ARGV.empty?
    (0..ARGV.size - 1).each do |i|
      args.push({ arg: ARGV[i], val: ARGV[i + 1] }) if ARGV[i].start_with?('-') && (i < ARGV.size + 1)
    end
  end

  args
end

"Reader" methods
I re-run Rubocop every time I change something in my code. In fact, I have it set up to run automatically when I save my code, when I commit my code, etc.
Since we now have removed the parameter from the method, it now tells us something new: "Reader" methods or "getter methods" that don't take any arguments and simply return a value should not be named with a get_ prefix. This is unlike Java, for example.
So, the method should simply be named params.
Redundant check
If ARGV is empty, its size will be 0, which means that the range 0..ARGV.size - 1 will be the range 0..-1, which is empty. Iterating over an empty range doesn't do anything, so we can just delete the check for ARGV.empty?
Redundant check 2
You are iterating from 0 to size-1, therefore i will never be greater than size. The check i < ARGV.size + 1 will always be true, and is thus redundant and can be deleted.
Iterators, take 2
We already converted the for loop into an each iterator. However, you are iterating over the indices of ARGV and then pull out the elements using the indices. This is a very FORTRAN way of writing that code. It is much easier to iterate over the elements directly.
Even better, since you always need the to look at the current and the next element, we can iterate over a sliding window of 2 consecutive elements. That's exactly what Enumerable#each_cons does:
ARGV.each_cons(2) do |param, arg|
  args.push({ arg: param, val: arg }) if param.start_with?('-')
end

As above, if ARGV is empty, each_cons will simply not do anything, so we don't need to check.
The "shovel" operator <<
And while we are looking at this code: Array#push is not idiomatic. More precisely, it is only idiomatic if you are using the array as a stack, then you would use Array#push and Array#pop, since those are the standard names for the stack operations.
The idiomatic way of appending something to something else is the shovel operator, in this case Array#<<, so that should be
args << { arg: param, val: arg }

Iterators, take 3
We are still doing a lot of stuff manually. Initialize the empty array, loop over ARGV, append to the array, etc.
Whenever you have the pattern of "Initialize a result, loop over a collection appending to the result, return result", that is a fold. There are two implementations of fold in the Ruby core library, inject and each_with_object. inject is the more functional one, each_with_object is the more imperative one. So, for now, we will use each_with_object here, since the code is still pretty imperative, and that makes the relationship between the old and new code more clear:
args = []

ARGV.each_cons(2) do |param, arg|
  args << { arg: param, val: arg } if param.start_with?('-')
end

args

becomes
ARGV.each_cons(2).each_with_object([]) do |(param, arg), args|
  args << { arg: param, val: arg } if param.start_with?('-')
end

Now, if we want to make it purely functional, it would look like this:
ARGV.each_cons(2).inject([]) do |args, (param, arg)|
  if param.start_with?('-') then args + [{ arg: param, val: arg }] else args end
end

Iterators, take 4
Instead of filtering inside the iteration, we could instead chain iterators and filter first. This works for both our variations:
ARGV
  .each_cons(2)
  .select { |param, _| param.start_with?('-') }
  .each_with_object([]) { |(param, arg), args| args << { arg: param, val: arg } }

ARGV
  .each_cons(2)
  .select { |param, _| param.start_with?('-') }
  .inject([]) { |args, (param, arg)| args + [{ arg: param, val: arg }] }

Excursion: Generality of fold (inject / each_with_object)
When I wrote above that you can rewrite this iteration with inject or each_with_object, that was actually a tautological statement. I didn't even have to read the code to make this statement.
It turns out that fold is "general". Every iteration over a collection can be expressed using fold. This means, if we were to delete every method from Enumerable, except inject, then we could re-implement the entire Enumerable module again, using nothing but inject. As long as we have inject, we can do anything.
Iterators, take 5
So, what we did until now was replace the loop with a low-level iterator, replace the low-level iterator with a higher-level iterator, and decompose the iteration into two chained higher-level iterators.
However, we are still not done. What we are now doing is we take each element from our filtered sliding window collection, modifying it, and putting it into a new collection. So, really, what we are doing is transforming each element, or "mapping" each element to a new element.
This is called map and is also available in Ruby as Enumerable#map.
So, finally, our code looks like this:
ARGV
  .each_cons(2)
  .select { |param, _| param.start_with?('-') }
  .map { |param, arg| { arg: param, val: arg } }
end

What we did here, was to replace the general high-level iterator fold (which can do anything) with a more restricted, more specialized high-level iterator map. By using a more specialized iterator, we are able to better convey our semantics to the reader. Instead of thinking "Okay, so here we have an accumulator, and an element, and we do something with the element, and then append it to the accumulator … ah, I see, we are transforming each element", the reader just sees map and instantly knows that map transforms the elements.
Classes and modules
In your code, you are using a class. However, your class cannot sensibly be instantiated. Therefore, it shouldn't be a class.
It makes more sense for it to be a module instead. Here's how I would write your entire file:
#!/usr/bin/env ruby
# frozen_string_literal: true

module ScriptHelper
  module_function def params
    ARGV
      .each_cons(2)
      .select { |param, _| param.start_with?('-') }
      .map { |param, arg| { arg: param, val: arg } }
  end
end

Linter, revisited
Rubocop actually complains about my inline use of Module#module_function. It wants me to write this instead:
#!/usr/bin/env ruby
# frozen_string_literal: true

module ScriptHelper
  def params
    ARGV
      .each_cons(2)
      .select { |param, _| param.start_with?('-') }
      .map { |param, arg| { arg: param, val: arg } }
  end

  module_function :params
end

I disagree. You should not be afraid to disable or re-configure rules in your linter to fit your style.
However, note that programming is a team sport. If you are modifying code, adopt the existing style. If you are part of a team, adopt the team's style. If you write open source code, adopt the project's style. If you start your own project, adopt the community's style (do not create your own style for your project, until your project is big and successful enough to have its own independent community).
Speaking of community …
Of course, the really correct solution to your problem is to use one of the many, already existing, well-maintained, well-tested, well-documented, well-known command line option parser libraries. Ruby ships with optparse in the standard library, but there are many, many others with some amazing features:

Clamp
Commander
Mixlib::CLI
Optimist
slop

Don't re-invent the wheel.
It is true that NASA has (kind-of) re-invented the wheel for the Perseverance rover, but most of us are not NASA. We don't face the unique challenge of sending a rover to Mars that needs to autonomously drive over rough, unknown terrain, and needs to be as light while at the same time as robust as possible. We just want to get from A to B on a paved road. There are plenty of wheels available off-the-shelf that do that.
Always remember: we are not NASA. It is highly unlikely that a problem we are encountering has never before been seen in the history of humankind. Parsing command line arguments is not a highly-specialized, complex, unique problem, it is a problem that has been solved with standardized libraries over 30 years ago.


First a few suggestions to your design.
You are effectively trying to represent list of small numbers as String, with no actual meaning (at least that's how I understood it).
I'd consider:

Represent it for what it is - list of small numbers could be represented as byte array. That seems a lot more natural and convenient.
Use some simpler mapping, if it doesn't matter what kind of character is the result. If numbers really are in range between 0 and 32 and not much higher, I'd go for mapping function, that for example adds 65 (and substracts 65 in reverse). That mapping function is really simple and you don't need any kind of map. Your code would be reduced only to initial tokenization basically. 00 becomes A, 30 becomes _ according to their ASCII codes (+65).

In case you wanna keep your String representation, here are my points to your code:

getValueMap

Names getValueMap name and lettersFirst don't really say what much about what do they do.
There's no point to recalculate reverse map everytime. Flag parameters with this kind of if are typical code smell and bad practice.
I suggest creating 2 module variables codesToCharacters (original map) and charactersToCodes (once pre-calculated) instead.

decode

I'd love if this function was just mapping encoded data to decoded data based on mapping function.
Not sure, why is there that if. I think you are trying to check, if current character is letter or not and if so, map it, otherwise use the character. That took me a while to understand. If there was really need, I would extract that to function with propper name (like isLetter) to increase readability.
Anyway, why even doing that? Why not instead look into the map and if map contains key, use map value, otherwise use original character.

Function would look something like (pseudocode, not tested):

function decode(encoded) {

    return encoded.split("").map(
        c => {
            charactersToCodes.hasKey(c) ? charactersToCodes[c] : c
        }).join()

}

encode would be on same principle, only difference is, that you need to tokenize it correctly first and then map :)


Series of repetitive content-loading functions

Joseph cleaned up the code a lot so let me point out a few things that you'll be able to use in your future code.

Consistent formatting greatly improves code readability and maintenance. There are many out there that are good starts, and I'm a fan of Google's language styles for the most part.
Since you're already depending on the definition of $, it's odd to mix it with jQuery in the same code. Pick one and stick with it.
To check that a value is neither null or undefined you can simply compare it to null using ==/!=. When you know the value cannot be some other falsy value (e.g. false, 0, or ''), you can simply use ! or the boolean context.

if (counterArray[1]) { ... }

DOM queries can be expensive on large pages, so it pays to save the results of a query if you're going to use it multiple times, and it cleans up the code. I like prefixing the name of a variable holding the results of a selector with a $ to make it clear that it's not a raw DOM element.

var $content = $('#content1');

Most jQuery methods return the selector itself, allowing you to chain multiple calls together.

$content.empty().html(data);

html completely replaces the contents of the element so there's no reason to call empty on it first. DOM manipulation causes a reflow; combine your manipulations when possible.


You use double values for calculations. Especially for money, I would suggest to switch to int and handle it in cents. That way you can avoid problems with floating point precision.
You don't check if cin>> fails or succeeds. If the user doesn't enter a number you may have a problem here. A possible solution might be to let the user reenter the value as long as it isn't correct.

do
{
    cout << "Enter the current balance of your loan: $";
}
while (!(cin >> balance));

You have a wrong check in the line if (interestRate = .06). You probably meant if (interestRate == .06). Additionally, this check might also be a problem as you do some calculations on interestRate that may cause inprecision (again floating point precision problem).

As you obviously await the user to input the value as int your check should be against 6 before you divide the value with 100.
You have this piece of code:

if (balance < monthlyPayment)
{
    balance = balance - balance;
}

Which is the same as:

if (balance < monthlyPayment)
{
    balance = 0;
}

I think the second version is easier to understand.

I didn't check any more of the code yet. I especially didn't prove it for correctness in you calculations.


Porting Haskell list comprehensions to Standard ML

Feedback:

The Haskell pyths is not very efficient, and it contains duplicate answers.

fun instead of val/val rec is syntactic sugar for function declarations.

Instead of generateIntsUpTo n, use List.tabulate (n, fn i => i+1).

Using rev to achieve a tail-recursive function can be a good choice. Neither SML/NJ's or Moscow ML's List.tabulate is tail-recursive, though. If you're worrying about performance here, consider the fact that you don't actually need to store these numbers in lists -- this is purely a convenience so that you can use list comprehensions to iterate their combinations.

Pythagorean triples in Standard ML

I wanted to do it using the minimum amount of custom code.

To achieve the same efficiency as the Haskell pyths and use the minimum amount of custom code, here is one version that uses List.filter, List.concat and List.tabulate:
fun isPythTriple (x, y, z) = x*x + y*y = z*z
fun tab1 n f = List.tabulate (n, fn i => f (i+1))
fun pyths n =
    List.filter isPythTriple (
      List.concat (tab1 n (fn x =>
      List.concat (tab1 n (fn y =>
                   tab1 n (fn z => (x,y,z)))))))

This takes several seconds for pyths 10; there really is not reason to generate O(n³) list elements when the solution subset is so sparse.

I have been thinking on write my own recursive functions

Writing your own helper functions is really not something that should be avoided. Generally, using library functions is good, but Standard ML's library is somewhat limited. For example, List.tabulate can't iterate a range of numbers without generating the list in memory. And as you're hinting at, the multiple nested foldrs does not make the code particularly readable.
You could for example combine List.tabulate and List.filter to reduce memory consumption:
fun tabfilter (from, to, f) =
    if from > to then [] else
      case f from of
           SOME value => value :: tabfilter (from+1, to, f)
         | NONE       =>          tabfilter (from+1, to, f)

fun isPythTriple (x, y, z) = x*x + y*y = z*z

fun pyths n =
    List.concat (tabfilter (1, n, fn x =>
      SOME (List.concat (tabfilter (1, n, fn y =>
        SOME (tabfilter (1, n, fn z => Option.filter isPythTriple (x, y, z))))))))

This runs orders of magnitude faster. Still, it is a little convoluted.
A plain recursive version:
fun isPythTriple (x, y, z) = x*x + y*y = z*z
fun pyths n =
    let fun loop (0, _, _) = []
          | loop (x, 0, _) = loop (x-1, n, n)
          | loop (x, y, 0) = loop (x, y-1, n)
          | loop (t as (x, y, z)) =
            if isPythTriple t then t :: loop (x,y,z-1) else loop (x,y,z-1)
    in rev (loop (n, n, n)) end

And a tail-recursive variant of the same:
fun isPythTriple x y z = x*x + y*y = z*z
fun pyths n =
    let fun loop 0 _ _ res = res
          | loop x 0 _ res = loop (x-1) n n res
          | loop x y 0 res = loop x (y-1) n res
          | loop x y z res =
            let val res' = if isPythTriple x y z
                           then (x,y,z) :: res
                           else res
            in loop x y (z-1) res'
            end
    in loop n n n [] end


isLessThan function for structure with 7 integers

Don't re-invent the wheel (unless of course you want practice at doing that):

Instead of naming a bunch of elements that are all the same type, use an array for your structure's elements like std::array, or use a std::tuple. Or if you really don't want to change your structure's content, use std::tie to craft a tuple of your structure's elements on demand.
If you used a regular array use std::lexicographical_compare on the iterable elements of the two structures. A std::array or std::tuple already has non-member function support for operators like <, <=, >=, etc. though.
Kick back and enjoy a brewski. ;)  (only if allowed of course and be sure to drink responsibly etc. etc.).


Summing up ints in vectors for education

Use Functions
There is a ton of repetition in your code. You could make it much better by just factoring out the common parts.
Printing
You don't like how you print your vector? There's a function for that:
template <typename T>
std::ostream& operator<<(std::ostream& os, std::vector<T> const& xs) {
    bool first = true;
    os << '{';
    for (T const& x : x) {
        if (!first) os << ", ";
        os << x;
        first = false;
    }
    return os << '}';
}

And now you can just do:
std::cout << "A = " << va << ", B = " << vb << std::endl;

Checking Summation
There is a huge amount of repetition here. Effectively, we're summing f(x) on each vector, for differing x. So we can write a function for that:
template <typename F>
int accumulate(std::vector<int> const& xs, F f) {
    int sum = 0;
    for (int x : xs) {
        sum += f(x);
    }
    return sum;

    // aka return boost::accumulate(xs | transformed(f), 0);
}

bool matches(std::vector<int> const& A, std::Vector<int> const& B, F f) {
    return accumulate(A, f) == accumulate(B, f);
}

Don't use goto
There is hardly ever a reason to use goto and this is not it. Once you refactor everything, you can just write out your test:
if (matches(va, vb, [](int x){ return x; }) &&
    matches(va, vb, [](int x){ return x*x; }) &&
    matches(va, vb, [](int x){ return x*x*x; }) &&
    matches(va, vb, [](int x){ return x*x*x*x; }))
{
    std::cout << "Found: A=" << va << ", B=" << vb << std::endl;
    break;
}

No goto needed.
Use a for loop
You are looping on split from 0 to the max uint32_t value. This isn't obvious because you're using the wrong loop:
for (uint32_t split=0; split < std::numeric_limits<uint32_t>::max(); ++split)

Returning from main
You don't have to use return EXIT_SUCCESS; or return 0;. As a special case for main, return 0 is implied.
Better algorithm
Looping over a few billion elements isn't going to be the best approach... especially when there are only ~300 million unique sets to check to begin with (those that have 16 elements on each side, ignoring mirrored duplicates for which one ends up being A).


AES encryption/decryption using pure .NET and streams

Let's talk about your code then we'll talk about that paragraph of text you have.

First off:

Using   aes As System.Security.Cryptography.Aes = System.Security.Cryptography.Aes.Create(),
        ms_unencrypted As New IO.MemoryStream(unencryptedData),
        ms_encrypted As New IO.MemoryStream()

This is largely not pleasant to read. You have ms_ hungarian (IIRC) notation, and you have everything aligned funky, and it's just visually unpleasant. Let's fix that:

Using aes As System.Security.Cryptography.Aes = System.Security.Cryptography.Aes.Create(),
    unencryptedStream As New IO.MemoryStream(unencryptedData),
    encryptedStream As New IO.MemoryStream()

Alright, that doesn't do much but it does start pushing things into motion.

You state in your question:

  I want to take advantage of streams if possible

But the API doesn't use any streams! It requires you to pass a byte[], why not allow streams to be used? Then you eliminate that unencryptedStream in Encrypt and the encryptedStream in Decrypt entirely. Let the caller deal with the stream mechanics.

Next, why not allow the caller to get a Stream back out? You still force the caller to deal with a byte[] in the end, we could eliminate that.

Public Sub Encrypt(key As Byte(), unencrypted As MemoryStream, encrypted As MemoryStream)
    Using aes As System.Security.Cryptography.Aes = System.Security.Cryptography.Aes.Create()
        Using cs As New Security.Cryptography.CryptoStream(encrypted, aes.CreateEncryptor(key, aes.IV), Security.Cryptography.CryptoStreamMode.Write)
            encrypted.Write(aes.IV, 0, aes.IV.Length)
            unencrypted.CopyTo(cs)
        End Using
    End Using
End Function

Now you have no responsibility for the streams, but once we see this we could also build a version that takes a byte[] and returns a byte[] to wrap this version. Then our API is clear, concise, and robust.

And then there's this paragraph:

  I've read that it's good practice to generate a random key. If I do that, then both the server and the client would need to know the same key. I assume this would then mean that I'd need to transmit the key in the call to the web-service from the client. Is that correct? Is that secure? I'd assume that the call to it would be done via HTTPS, but is there anything else I'd need to be aware of in that scenario?

While HTTPS is good and all, using AES to encrypt data between a server/client is not really a great idea. Encryption has the concept of a 'public key' and a 'private key', some algorithms use both, some only use one. In the case of AES, it uses one key: a private key.

The names themselves should give things away, but I'll be explicit anyway:

public key: This key can be shared with anyone, and should be available for all persons wishing to use the system.
private key: This key should be kept as secret as possible, and not shared unless absolutely required. This is the key that, without which, attackers cannot easily reverse encryption.

Now AES uses only a private key as both encryption and decryption. This is known as symmetric encryption or a symmetric encryption algorithm. What you are discussion requires something else, known as asymmetric encryption or an asymmetric encryption algorithm.

These algorithms come it two major variants: those that use the public key for encryption and the private key for decryption, and those that use the private key for encryption and the public key for decryption.

The option you pick depends on your use-case. In the case of something being shared from server -> client, you would pick an algorithm that uses the private key for encryption, since the server is entirely under your control. You can keep things on it a secret. You cannot keep things on the client a secret, so it should get a public decryption key. Then to send data back you should have a second algorithm that does the opposite, and uses the public key for encryption.

The next option is to have the client establish a connection to the server, then use a public key encryption algorithm (such as RSA - where the public key is the encryption key) to send it's AES key. Then you can use AES for the remaining communication between the server and the individual clients. This is the most common type of scenario with RSA, as it's very expensive to use for encryption and decryption.

If you're using HTTPS, however, there's no need to build a sophisticated mechanism to further encrypt your information. HTTPS already provides a secure communication session between client/server, though it doesn't hurt to add more security in general, it can have drastic performance impacts if done wrong or 'over the top'.


Python: Combining Two Rows with Pandas read_excel

Yes, there is an easier way, using pandas.Index.get_level_values.

First, I could only get your example dataframe when calling the read with df = pd.read_excel("/tmp/temp.xls", header=[0, 1]), so I get both headers correctly.

Then you can just do this:

import pandas as pd
import json

# read df
df = pd.read_excel("/tmp/temp.xls", header=[0, 1])
df.index = pd.to_datetime(df.index)

# combine multilevel columns to one level
df.columns = (pd.Series(df.columns.get_level_values(0)).apply(str)
              + pd.Series(df.columns.get_level_values(1)).apply(str))

# get Date as a column
df = df.reset_index()
df.columns = ["Date"] + list(df.columns[1:])

print(df)
#          1a   1b   2c   2d
# 2019-01-02  100  200  300  400
# 2019-01-02  101  201  301  401
# 2019-01-03  102  202  302  402

After which you can just do something similar to what you are doing, but directly getting the index of the maximum instead of comparing all values to the value of the maximum:

json_data = json.loads(df.loc[df.Date.idxmax()].to_json(date_format='iso'))
print(json.dumps(json_data, indent=4))

Which produces the desired output:

{
    "Date": "2019-01-03T00:00:00.000Z",
    "1a": 102,
    "1b": 202,
    "2c": 302,
    "2d": 402
}


Given a date and a duration, calculate the future date

This is quite tricky problem to get right. As Loki said, we need to convert it to seconds after epoch. But doing so is not trivial...
Standard approach:
Well, not really standard, but in my opinion one should use std::chrono in this case. Some stuff is done in a roundabout way, but I don't think it is a huge problem. Howard Hinnant has written a library for it, but in case the license isn't acceptable, I'll reimplement some functionality by hand.
output std::time_point:
The first issue is outputting a std::time_point. The problem with it is that it doesn't have operator<< overload for streams. The only way possible to deal with this is to implement our own:
Necessary links:

std::chrono::system_clock::to_time_t() (system clock is just example).

std::localtime()

std::put_time()

std::mktime()

The only ways to print time are either std::ctime() and std::put_time() (not counting the "implement by hand" approach). So let's follow the thread and find its end and test it:
#include <iostream>
#include <chrono>
#include <iomanip>

template <typename Clock, typename Duration>
std::ostream& operator<<(std::ostream& os, const std::chrono::time_point<Clock, Duration>& timep)
{
    auto converted_timep = Clock::to_time_t(timep);
    os << std::put_time(std::localtime(&converted_timep), "%Y %b %d %H:%M:%S");
    return os;
}

int main()
{
    auto now = std::chrono::system_clock::now();
    std::cout << now;

    return 0;
}

Output: 2017 Jun 04 12:07:48.
The only problem with implementation is that it can't be used from multiple threads, since std::localtime() returns pointer to static variable. The format could be mutable by some function, but I wouldn't care about it at this point.
Since we can manipulate std::chrono::time_point, and std::chrono::duration, let's use everything we have:
convert given date to std::chrono::time_point<system_clock>:
A good news, at last! From std::mktime():

Converts local calendar time to a time since epoch as a time_t object. time->tm_wday and time->tm_yday are ignored. The values in time are permitted to be outside their normal ranges.

Hooray! So we can just fill in the std::tm structure with year, month, and day since January 1 and we are done!
#include <iostream>
#include <chrono>
#include <iomanip>

template <typename Clock, typename Duration>
std::ostream& operator<<(std::ostream& os, const std::chrono::time_point<Clock, Duration>& timep)
{
    auto converted_timep = Clock::to_time_t(timep);
    os << std::put_time(std::localtime(&converted_timep), "%Y %b %d %H:%M:%S");
    return os;
}

auto convert_to_timepoint(int years, int months, int days)
{
    //perform checks, do division, modulus and stuff...
    years -= 1900; //epoch
    std::tm date = {};
    date.tm_year = years;
    date.tm_mon = months;
    date.tm_mday = days;

    return std::chrono::system_clock::from_time_t(std::mktime(&date));
}

int main()
{
    auto now = std::chrono::system_clock::now();
    std::cout << now << '\n';

    std::cout << "calling convert_to_timepoint:\n";
    auto date = convert_to_timepoint(1991, 0, 23);
    std::cout << date;

    return 0;
}

Output:
2017 Jun 04 13:08:49
calling convert_to_timepoint:
1991 Jan 23 00:00:00

Now the easy stuff, add the given number of days:
#include <iostream>
#include <chrono>
#include <iomanip>

template <typename Clock, typename Duration>
std::ostream& operator<<(std::ostream& os, const std::chrono::time_point<Clock, Duration>& timep)
{
    auto converted_timep = Clock::to_time_t(timep);
    os << std::put_time(std::localtime(&converted_timep), "%Y %b %d %H:%M:%S");
    return os;
}

auto convert_to_timepoint(int years, int months, int days)
{
    years -= 1900; //epoch
    std::tm date = {};
    date.tm_year = years;
    date.tm_mon = months;
    date.tm_mday = days;

    return std::chrono::system_clock::from_time_t(std::mktime(&date));
}

template <typename Clock, typename Duration>
auto add_days(const std::chrono::time_point<Clock, Duration>& timepoint, int days_to_add)
{
    constexpr std::time_t seconds_in_day = 60 * 60 * 24;
    //                                     mm   hh   dd

    std::time_t days = seconds_in_day * days_to_add;
    auto date = Clock::to_time_t(timepoint);
    return Clock::from_time_t(date + days);
}

int main()
{
    auto now = std::chrono::system_clock::now();
    std::cout << now << '\n';

    std::cout << "calling convert_to_timepoint with 1991 0 23 (1991 Jan 23):\n";
    auto date = convert_to_timepoint(1991, 0, 23);
    std::cout << date << '\n';

    std::cout << "10 day later (1991 Feb 02):\n" << add_days(date, 10);

    return 0;
}

Output:
2017 Jun 04 13:21:29
calling convert_to_timepoint with 1991 0 23 (1991 Jan 23):
1991 Jan 23 00:00:00
10 day later (1991 Feb 02):
1991 Feb 02 00:00:00

I left the convert_to_timepoint() so that it would be reusable on its own, but if needed it can be fused with add_days().
Some thoughts:

using namespace std; rarely buys anything, but opens a chance for errors.
standard library has a solution most of the time
modularity is important. Breaking functions into logical pieces makes it very easy to quickly prototype, adjust, mix'n'match.

Conclusion:
In this kind of problem, it is very dangerous try to implement by hand, since there are lots of edge cases. As a result, the problem given was rather a test of knowledge of standard library.


Changing visibility of ToolbarItem - Xamarin.Forms

Two things:

You clear ToolbarItems and CustomToolbar when page dissapearing, this causes problem: when you show next page and then go back, you won't see your items anymore, because they were cleared.
Handlers OnToolbarItemPropertyChanged will not be removed in foreach cycle, because you clear list before this cycle.


Others have given alternate solutions.  However, since this is Code Review, I'll offer a critique instead, because I think you will learn more from that than by just seeing the answer.

Interfaces

Checknumber is too vague.  I suggest DuplicateNumberDetector.
In your interfaces (class and method names), pick either English or Norwegian and stick with it.  For your comments, use whatever language works for you.
sjekk() (meaning "check") is actually responsible for receiving input rather than performing the checking.  How misleading!

Variables

b is very poorly named.  I suggest unique instead.
temp is somewhat poorly named.  I suggest num instead.
Only older dialects of C require you to declare all variables at the top.  Java lets you declare variables near the point of first use.  You should take advantage of that.  int temp should be declared inside the for (i) loop, since it is never used outside the loop.
You might try to pull the declaration of b inside the for (i) loop too.  But then you will realize that b refers to the uniqueness of the previous numbers[i].  That reveals a bug: what if the last two numbers are identical (numbers[3] == numbers[4], but numbers[2] != numbers[3])?  You haven't handled the termination case correctly.  Hint: Move your print statement.  The lesson to be learned here is that declaring temporary variables far from the point of use is almost as evil and dangerous as using global variables.

Logic

You are using -2 as a special value to indicate that an array element has already been detected as a duplicate. That's bad because your code will fail if -2 happens to be one of the inputs.
Overwriting the input array is a surprising side effect.  That's as unforgivable as sending your computer to a repair shop to install a video card and getting it back with the hard drive reformatted.  If you really need to overwrite the input, state so clearly in a comment.  You should be able to find a solution to this problem that does not require overwriting.
Your inner loop has j going from 0 to the end of the array.  That means you are handling every pair twice.  You should probably be able to start from i + 1 instead, to reduce your processing in half.  Handling each pair only once should simplify your logic as well.

Efficiency

You have two for loops, each iterating over the entire array.  If the array has n elements, then the run time for your algorithm is O(n2).  (Even with the inner-loop optimization mentioned in the previous point, it would still be O(n2).)  For a small homework problem like this, that is perfectly acceptable, because simplicity is the main goal.  If you wanted to handle very large arrays, though, it would be more efficient to sort the input first or use a HashMap.

Separation of concerns

Your input, processing, and output code are all intertwined.  Get into the habit of separating them.  Your code will be more reusable and easier to understand.

.

public class DuplicateNumberDetector {
    int[] promptInputs(int numberOfInputs) { ... }

    // If the order doesn't matter, use Set<Integer> instead
    List<Integer> findDuplicates(int[] numbers) { ... }

    void printDuplicates(List<Integer> dups) { ... }

    public static void main(String[] args) {
        printDuplicates(findDuplicates(promptInputs(5)));
    }
}


A regular expression is really all you need:

/(^| +)([a-zA-Z])/g

Then use the String#replace method and pass in a function:

function toTitleCase(s) {
    return s.toLowerCase().replace(toTitleCase.WORD_PATTERN, function(match, $1, $2) {
        return $1 + $2.toUpperCase();
    });
}

toTitleCase.WORD_PATTERN = /(^| +)([a-zA-Z])/g;

If you really feel like it, jsperf.com can give you a good idea what the performance is.


Most efficient FizzBuzz solution in Ruby

Using a destructive update like map! is weird, the user does not expect his array to be mutated. I suggest one of two possibilities:

Replace map! with each and leave the rest of the code as is.
Replace map! with map, remove puts and handle printing out of the function. Adding a join("\n") may be needed.

The first is more obvious, the second one only has one responsability.

As a minor note, it is common style to use do end for multiline blocks, not {}.


Just a review of a small portion of code:
PSet *pset = malloc(sizeof(PSet));
pset->data = malloc (sizeof(char *) * (1 << sset->size));
pset->data[pset->size] = calloc(2, 1);

pset->size is not yet assigned a value. pset->data[pset->size] is a Bug.  @1201ProgramAlarm
sizeof(char *) --> Is that the correct size?  I need to look for the declarations of pset up some lines and then the definition of PSet some 20 lines upstream.
Consider below instead - no need to check if the correct type.  The size is correct by inspection of this line alone.
pset->data = malloc(sizeof pset->data[0] * (1 << sset->size));

Later code uses int for indexing and buffer size, yet could have used unsigned and incur no additional cost in performance.  To support unsigned, add u:
pset->data = malloc(sizeof pset->data[0] * (1u << sset->size));

Redundant string length calculation
Compiler may not optimize the 2 strlen() calls into 1.  Recommend to do so by direct code.
//pset->data[pset->size] = calloc(strlen(pset->data[buffer]) + 2, sizeof(char));
//strcpy(pset->data[pset->size], pset->data[buffer]);
//pset->data[pset->size][strlen(pset->data[buffer])] = set->data[index];

size_t len = strlen(pset->data[buffer];
pset->data[pset->size] = calloc(len + 2, sizeof(char));
strcpy(pset->data[pset->size], pset->data[buffer]);  // or memcpy()
pset->data[pset->size][len] = set->data[index];  // re-use `len`

Use const for unchanged refenced data
It better conveys code's intent, allows for some optimizations and greater functionally usage.
// Set *initSet(char *str) {
Set *initSet(const char *str) {

Missing freeing of memory
For general usage of these routines, de-allocation routines are needed like uninitSet() and uninitPSet().


Obtaining project size metrics with PowerShell

My suggestions:

apply PowerShell scripting best practices; for particulars, see Concept: A list of some Best Practices for Windows PowerShell by powershell-guru;
get more knowledge from the utility (see Count and Property output properties; see also -Detailed input parameter);
allow -LiteralPath to take range operator characters in project path literally;
use Set-Alias -Name … -Value … -Force rather than New-Alias;
(not implemented yet) consider involving -Encoding parameter for Get-Content cmdlet.

The script (rewritten almost completely):

<#
 SYNOPSIS: Calculates simple size metrics about code projects.
          Combination of `Get-ChildItem`, `Get-Content` and `Measure-Object`

  Parameter         Meaning (see native cmdlet)
  ---------         ---------------------------
  -Path             obvious (Convert-Path, Get-ChildItem, Get-Item, Push-Location)
  -LiteralPath      obvious (Convert-Path, Get-ChildItem, Get-Item, Push-Location)
  -Filter           obvious (Get-ChildItem)
  -IgnoreWhiteSpace obvious (Measure-Object)
  -Detailed         returns size metrics about individual files severally
  -PushLocation     side effect: `Push-Location`

 RETURNS: Custom combination of GenericMeasureInfo and TextMeasureInfo:

  Name       Type     Meaning
  ----       ----     -------
  Count      [int]    number of files of given pattern in given (literal)path
  Lines      [int]    number of lines
  Words      [int]    number of words
  Characters [int]    number of characters
  Property   [string] tested path
#>

Set-StrictMode -Version latest

Function Measure-Project
{
    [CmdletBinding(DefaultParameterSetName='Items')]
    Param(
        [Alias('projectPath')]
        [Parameter(Mandatory=$false,
                   Position=0,
                   ParameterSetName='Items')]
        [string]$Path='.\',

        [Parameter(Mandatory=$false,
                   Position=0,
                   ParameterSetName='LiteralItems')]
        [string]$LiteralPath='.\',

        [Alias('fileFilter')]
        [Parameter(Mandatory=$false,
                   Position=1)]
        [string]$Filter='*.ps1',

        [Alias('IgnoreWS')]
        [switch]$IgnoreWhiteSpace,

        [Alias('PushD')]
        [switch]$PushLocation,

        [switch]$Detailed
    )
    Function out ($Cnt, $Prm, $Obj) {
        $auxCounter = $Obj | Measure-Object -Character -Word -Line @auxParMO
        $auxCounter | Add-Member -NotePropertyName Count -NotePropertyValue $Cnt
        $auxCounter.Property = $Prm
        return $auxCounter
    }
    if ( $PSCmdlet.ParameterSetName -eq 'LiteralItems') {
        $auxParTP = @{ LiteralPath = $LiteralPath }
    } else {
        $auxParTP = @{ Path = $Path }
    }
    if ( Test-Path @auxParTP ) {
        $auxPath = Convert-Path @auxParTP
        if ( (Get-Item @auxParTP) -is [System.IO.DirectoryInfo]) {
            $auxFiles = Get-ChildItem @auxParTP -Filter $Filter -Recurse -File
            $auxParMO = @{ IgnoreWhiteSpace = $IgnoreWhiteSpace.IsPresent }
                         # $PSBoundParameters.ContainsKey('IgnoreWhiteSpace')
            if ($Detailed.IsPresent -and $auxFiles) {
                $auxFiles | ForEach-Object {
                    out -Cnt 1 -Prm $_.FullName -Obj ($_ | Get-Content)
                }
            } else {
                $auxPar = Join-Path -Path $auxPath -ChildPath $Filter
                if ( $auxFiles ) {
                    if ( $auxFiles -is [array] ) {
                        $auxCnt = $auxFiles.Count
                    } else {
                        $auxCnt = 1
                    }
                    out -Cnt $auxCnt -Prm $auxPar -Obj ($auxFiles | Get-Content)
                } else {
                    Write-Warning "No '$Filter' inside '$Path'"
                    out -Cnt 0 -Prm $auxPar -Obj ''
                }
            }
            if ( $PushLocation.IsPresent ) {Push-Location @auxParTP}
        } else {
            $auxMsg = "'$($auxParTP.Values.GetEnumerator())' is not a directory"
            Write-Error -Message $auxMsg -Category InvalidArgument
        }
    }
    else
    {
        $auxMsg = "Cannot find path '$($auxParTP.Values.GetEnumerator())'"
        Write-Error -Message $auxMsg -Category ObjectNotFound
    }
}

Sample output demonstrates necessity of -Encoding parameter as both files contain nearly the same text so the utility should show the same count of characters. Of course, I'd expect the same encoding of source files in a particular project so sorry for the following simplified example:

  PS D:\PSh> Measure-Project -LiteralPath 'D:\bat\[source]\XX\' -filter * -Detailed | ft

Count Lines Words Characters Property
----- ----- ----- ---------- --------
    1     1     5        118 D:\bat\[source]\XX\[sourcefile].log
    1     1     5         59 D:\bat\[source]\XX\[sourcefile].txt

PS D:\PSh> type -LiteralPath 'D:\bat\[source]\XX\[sourcefile].txt'
Toto je obsah souboru `D:\bat\[source]\XX\[sourcefile].txt`

PS D:\PSh> type -LiteralPath 'D:\bat\[source]\XX\[sourcefile].log' -Encoding Unicode
Toto je obsah souboru `D:\bat\[source]\XX\[sourcefile].log`


NSManagedObject in need of smart setters

without referring to your code, I think there is one pattern, that makes core data more fun but sadly isnt supported by Xcode out-of-the-box:

Have two classes for each model: one for automatic code generation — it will be jsut changed by Xcode — and on that inherits from the first, that can be changed and will never touched again by the machine after creation.

// for the machine
@class _Event : NSManagedObject
@end

// for human beings
@class Event : _Event
// what ever you need: put it here
@end

a great tool to teach Xcode this pattern is mogenerator. mogenerator + Xcode4.x

Another similar approach would be to have categories on the Model class. But this is less powerful and needs more attention for importing.

Now to your code.

I dont see any reason to overwrite the setter. if apple says that you most likely will never be able to write as performant accessors as the provide, they probably are right. Instead you should create your own method, that will set up a object as need. you could overwrite save and similar methods, or access it via a wrapper class, that will set it up for you.

  I plan to create a service class as a factory that manages the entities and their interactions with the context.

that sounds valid and could be the wrapper class mentioned above. But make sure, you create the model objects with initWithEntity:insertIntoManagedObjectContext:, as you want them in your context.

Core Data is a great and powerful framework. but beware: if you shoot yourself in the foot, most likely both your legs will be gone.
2 Years ago I was working in a team where the Engineer responsible for persistency accidentally overwrote an internal method of NSManagedObject. It took him one week to find the cause and fix it by renaming his method. This line of code was probably the most expensive in the whole project. There-for another hint: prefix your custom methods.


Checking if a Chess space has been attacked

Switch your code up

We can make this much more readable with a switch statement.

switch(piece_abs_val) {
    case 1:
        if(piece_val != -1){ //w_pawn
            if(piece_direction == 4 || piece_direction == 6){
                is_attacked = true;
            }
        } else { //b_pawn
            if(piece_direction == 2 || piece_direction == 8){
                is_attacked = true;
            }
        }
        break;
    case 2:
        is_attacked = as_knight;
        break;
    case 3:
        is_attacked = true;
        break;
    case 4:
        is_attacked = piece_direction % 2;
        break;
    case 5:
        is_attacked = true;
        break;
    case 6:
        is_attacked = i == 0;
        break;
}

Same exact code only much cleaner. I also did some refactoring. Take 6 for example; it used to be this:

else if(piece_abs_val==6){//king
        if(i==0){
            is_attacked=true;
        }

In the switch, piece_abs_val is checked for 6. Then, is_attacked is set to whatever i==0 evaluates to. However, instead of using a conditional, I just simply wrote the statement out in the variable setting.

Magic!

Your code is littered with magic numbers. These are bad.

What you need here is a makeshift enumerated type. In case you don't know, an enumerated type is basically a type that assigns plain texts words (not strings) to integer values. I say "makeshift" because JavaScript does not have native support for these values.

Judging from your comments, I was able to make this:

var Piece = {
    KNIGHT: 2,
    KING:   6,
    ...
}

You can fill in the rest. Then, when in need of checking the value of piece, don't use the number; use this "enum". For example:

if(piece_abs_val==Piece.KNIGHT){

This also removes the need for those annoying comments.

You should also do this for your piece_directions.

This is what your code now looks like:

var Piece = {
    PAWN: {
        BLACK: -1,
        WHITE: 1
    },
    KNIGHT: 2,
    BISHOP: 3,
    ROOK:   4,
    QUEEN:  5,
    KING:   6
}

switch(piece_abs_val) {
    case Piece.PAWN:
        if(piece_val != Piece.PAWN.BLACK){
            if(piece_direction == 4 || piece_direction == 6){
                is_attacked = true;
            }
        } else {
            if(piece_direction == 2 || piece_direction == 8){
                is_attacked = true;
            }
        }
    case Piece.KNIGHT:
            is_attacked = as_knight
    case Piece.BISHOP:
            is_attacked = true;
    case Piece.ROOK:
            is_attacked = piece_direction % 2;
    case Piece.QUEEN:
            is_attacked = true;
    case Piece.KING:
            is_attacked = i == 0;
}


Code to measure the length of binary numbers in terms of English nomenclature

Just some points:

This code here:

running = True
counter = 0
while running:
    checker = check(letters(counter))
    if checker == 0:
        pass
    else:
        #Loops through over and over again until a number reaches either 13 or 18
        while checker != 0:
            checker = check(letters(checker))

    #I could have used a "for" loop but it just wasn't working with this :(
    counter += 1
    if counter > maximum:
        running = False

is a bit repetitive and could be easily simplified. First, let's remove the duplicate checker = check(letters(counter)) by using a different loop:

running = True
counter = 0
while running:
    checker = 1 # really any number can be used here
    while checker != 0
        checker = check(letters(counter))
    counter += 1
    if counter > maximum:
        running = False

and then we can change the while loop into a for loop:

running = True
counter = 0
for counter in range(0, maximum + 1):
    checker = 1 # really any number can be used here
    while checker != 0:
        checker = check(letters(counter))

Here:

for ch in binary:
    if ch == '1':
        letter += 3
    if ch == '0':
        letter += 4

Can't you use an else?

for ch in binary:
    if ch == '1':
        letter += 3
    else:
        letter += 4


Deserialize string into property array of the deserializing type using json.net

Do you have access the JsonReader and JToken classes? If so, consider the following APIs. There is a lot of logic tied into the current ReadJson method which could be (IMO) better separated out of there. You would of course have to create/implement/override
the appropriate base classes and methods: Notice how a lot of the clutter is separated and moved out to a factory with the following APIs? And the respective JTokens will know exactly what to do when you send the ToObject method to it - there is no need to check for the type, or to check if it's an array because the factory will take care of that logic. The only negative is that it might be a little annoying if you have to roll your own JsonReader implementation.

// A so-so API that is marginally better
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
    JToken token = JToken.LoadMovementConverter(reader);
    token.ToObject();
}

    // even more ideal API:
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
    JToken token = reader.GetMovementConverterJToken();
    token.ToObject();
}

    // create new JToken types:
public class JTokenNullReason : JToken
{
    public override object ToObject()
    {
        throw new NotImplementedException();
    }
}

public class JTokenArray : JToken
{
    public override object ToObject()
    {
        throw new NotImplementedException();
    }
}

public class JTokenEqualsQtyWorked : JToken
{
    public override object ToObject()
    {
        throw new NotImplementedException();
    }
}

And then the abstract class something like this:

public abstract class JToken
{
    public abstract object ToObject();

    public static JToken Load(JsonReader reader )
    {
            // not ideal because an abstract ReasonCode class instance method
            // could return the required JToken via a factory method.
            // you could certainly refactor this code, or, even better:
            // ask the reader itself to get you the correct JToken.

          string reasonCode = reader.GetReasonCode();
          switch (reasonCode)
          {
              case null:
                  return new JTokenNullReason();
                  break;
              case "Array":
                  return new JTokenArray();
                  break;
              default:
                  return new JTokenEqualsQtyWorked();
                  break;
          }
    }
}


Rendering plain text with paragraphs and line breaks as HTML

Two things that help in cases like this (IMHO):

Extract a function for more complex logic or a Array.map callback (e.g. to give a descriptive name and/or avoid nesting)
Provide descriptive names for non-obvious stuff (e.g. I'd prefer firstLine and remainingLines (or something similar) over using index)

I'd probably do something like this:

description.split('\n\n').map(renderParagraph)

// If you are in a class, this could be a method on the class
function renderParagraph(paragraph) {
  // With fancy ES6:
  const [firstLine, ...rest] = paragraph.split('\n')
  // Or ES5:
  const lines = paragraph.split('\n')
  const firstLine = lines[0]
  const rest = lines.slice(1)

  return (

      {firstLine}
      {rest.map(line => (
        // React.Fragment doesn’t create a wrapper element in the DOM.
        // If you don’t care about that, you can use div instead
        <React.Fragment>

          {line}
        </React.Fragment>
      )}

  )
}


Since you are using end-of-line commands, I will assume that you are using at least C99 in this review (it may be a compiler extension to C89 though).

main

There are too many things in your main function. It shouldn't handle the expression parsing, but delegate this task to another function. Also, if you are using C99, you don't need to return 0; at the end of main: the compiler will have your program automagically return 0 when it reaches the end of the function.

isOperator

Whenever it makes sense, try to use boolean values instead of integers. The header <stdbool.h> defines bool, true and false that you can use to make your code clearer. Using booleans instead of integers can help to clarify your intent. For example, here is your function isOperator with booleans instead of integers

bool isOperator(int c)
{
    int i;
    char legalOps[] = {'+', '-', '*', '/'};

    for (i = 0; i < 4; i++)
        if (c == legalOps[i])
            return true;
    return false;
}

By the way, there are many other way to implement this function. Your current function uses a loop and therefore performs in \$ O(n) \$ where n is the number of operators while you could rewrite it to perform in \$ O(1) \$, with a lookup table for example. That said, it shouldn't be a problem since you only have 4 operators.

Variable declarations

You seem to declare your variables at the beginning of blocks. It is not needed anymore with C99, you can declare your variable when you need it. You can also declare a variable in a for loop and therefore write things like this:

for (int i = 0; infixExpr[i] != '\0'; i++) {
    // ...
}


I would omit the StringBuilder here and would go with string.Join() by joining the processed innerLines and the processed lines like so

public string Obfuscate(string text)
{

    var lines = text.Split(new[] { "\r\n" }, StringSplitOptions.None);

    for (int i = 0; i < lines.Length; i++)
    {

        var innerLines = lines[i].Split(new[] { "\r" }, StringSplitOptions.None);
        for (int j = 0; j < innerLines.Length; j++)
        {
            innerLines[j]= string.IsNullOrEmpty(innerLines[j]) ? string.Empty : myObfuscator.Obfuscate(innerLines[j]);
        }

        lines[i] = string.Join("\r", innerLines);

    }
    return string.Join(Environment.NewLine, lines);

}

What I would add about your code would be some proper argument validation because the method is public. In addition I would move the check wether ther innerLine is NullOrEmpty inside the obfuscator.


Simple Binary Search Tree Class with Insert and Search Functions

Overall organization

Right now, you've defined a BstNode, which you use directly in main. I'd at least consider defining a Bst class, and then (probably inside that) a Node class.

class Bst {
    class Node {
        // only code to deal with individual nodes goes here
    };

    Node *root;
public:

    bool insert(int value);

    bool find(int value);
};

Then to create a Binary search tree, you'd just instantiate a Bst object, and use it:

int main() {

    Bst tree;

    // oops--this will lead to a completely imbalanced tree.
    for (int i=0; i<10; i++)
        tree.insert(i);

}

in-class initialization

Since you (almost?) always create a node with its child pointers set to nullptrs, I'd just specify that directly in the class instead of in the ctor:

// ...
class Node {
    int value;
    Node *left = nullptr;
    Node *right = nullptr;

    Node(int value) : value(value) {}
};

Insertion and Search

I'd at least consider whether you really want to use recursion to do insertion and/or search. Since you only ever descend to one child of any given node, it's pretty easy to use iteration for these tasks.

Insert return type

I'd at least consider having Insert return a bool to indicate whether it actually inserted a value in the tree or not (e.g., return false if a value is already present).

Collection type

What you've currently implemented is roughly equivalent to a std::set. That is, it stores only keys. This can certainly be useful, but there are times its also useful to have data associated with the key (i.e., roughly equivalent to std::map).

Generic Code

Right now, you've written the code so the only thing can be stored in your BST is ints. I'd at least consider making it generic so other types can be stored.

template <class T, class Cmp = std::less<T>>
class Bst {
    // ...

This increases complexity a little, but increases functionality quite a lot.


I'm thinking you named ret as in short for return.
Don't shorten variable names. Also try to give varaible names that are meaningful. Naming it return because you return it is silly.

char ret = '\0';

Same here:

std::string temp;

This line looks very odd and is a sign of poorly named variables:

ret = it->second;

r, p s these are a good example of when you should be using an ENUM.

Try to avoid 1 letter variable names.

You can use const when variables should never change. For example: rules.

I suggest putting the condition inside the while instead.
For example:

} while (std::tolower(ret[0]) != 'r' || std::tolower(ret[0]) != 'p' || std::tolower(ret[0]) != 's');

If you had an ENUM, you could check the entered value against all the values in the ENUM. This would look much better, and be easier to maintain. (E.g adding Lizard Spock)

The ENUM would also help for printing the values. (No more if r print rock etc)


A good OOP design is open for extension and closed for modification.
The single-method implementation is very far from that.

I think the purpose of the exercise is to be able to build a premium calculator from parts,
in a way that you can easily modify the parts that are likely to change.
What are the parts?

The base premium
Calculate percentage modifier based on conditions

There is a list of conditions, with associated percentage increase or decrease

A percentage modifier part is essentially a function that takes a Person and returns a percentage.
You could provide such parts to make it easy to build a calculator, for example:

interface PremiumPercentCalculator extends Function<Person, Integer> {}

PremiumPercentCalculator male(int percent) {
    return person -> person.male ? percent : 0;
}

PremiumPercentCalculator preConditions(int percent) {
    return person -> person.preConditions().size() * percent;
}

PremiumPercentCalculator goodHabits(int percent) {
    return person -> person.habits().stream().filter(Habit::isGood).mapToInt(h -> percent).sum();
}

PremiumPercentCalculator badHabits(int percent) {
    return person -> person.habits().stream().filter(h -> !h.isGood()).mapToInt(h -> percent).sum();
}

Then, using the builder pattern, you could build a calculator from parts like this:

float premium = new Calculator(person, 5000)
    .add(p -> getPremiumPercentByAge(p))
    .add(male(2))
    .add(preConditions(1))
    .add(badHabits(3))
    .add(goodHabits(-3))
    .calculate();

Imagine that there is a UI for an insurance agent,
where he can drag and drop widgets that correspond to condition types like "is male", "pre-conditions", and so on, each with an option to modify the percentage to apply.
Such a UI could be easily built from the parts we provided,
and new parts can be easily added by adding more PremiumPercentCalculator implementations.

Notice that person and the base premium 5000 are constructor parameters,
as they are absolutely essential for the calculator,
so it made sense to make them required up front,
so that the rest of the implementation can count on them to exist without further validation.

You might notice that badHabits and goodHabits iterate over the collection of habits twice.
This might very well be negligible.
But if not, it's easy enough to fix,
by adding another part:

PremiumPercentCalculator habits(int goodPercent, int badPercent) {
    return person -> person.habits().stream().mapToInt(h -> h.isGood() ? goodPercent : badPercent).sum();
}

Admittedly getPremiumPercentByAge is not so easy to make extensible,
this part can certainly be improved,
but I think that was not the most important part of the interview.

Note that although I used lambdas for compact expressions,
the concept doesn't require it,
and although the solution will be more verbose with classes fully written out,
that won't diminish its benefits.


code

Your code itself is clear, with and has only a few improvements

df

your parameter df expects actually a Series, and not a DataFrame, so I would rename this.

composition

now you first make an empty DataFrame and then change the values. More clear would be to generate it directly with the correct data:

def future_returns_2(data):
    grid = pd.DataFrame(
        index=data.index,
        columns=np.arange(len(data)),
        data=[data.shift(-i).values for i in range(len(data))],
    )
    return grid.divide(data, axis=0) - 1

Conveniently, this is also about faster

numpy

If you really want it a lot faster, you should stay in the numpy space for as long as possible, and only generate the DataFrame at the last possible time.

You can use numpy.roll

arr = data.values
result = np.array(
    [np.roll(arr, -i) for i in range(len(arr))],
    copy=False,
) / arr - 1

Since numpy.roll doesn't make the lower triangle of the result NaN, You should add this yourself:

mask = np.rot90(np.tri(l,), k=-1)
mask[np.where(1 - mask)] = np.nan
mask

array([[ 1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1., nan],
       [ 1.,  1.,  1., nan, nan],
       [ 1.,  1., nan, nan, nan],
       [ 1., nan, nan, nan, nan]])

Now you can deduct this mask instead of 1

def future_returns_numpy(data):
    arr = data.values
    l = len(arr)

    mask = np.rot90(np.tri(l), k=-1)
    mask[np.where(1 - mask)] = np.nan

    result = np.array(
        [np.roll(arr, -i) for i in range(l)],
        copy=False,
    ) / arr - mask

    return pd.DataFrame(data = result.T, index = data.index)

I find this code less clear than the pandas algorithm, but if speed is important, I would use this.

timings

For this dummy data

size=1000
np.random.seed(0)
data = pd.Series(
    np.random.random(size),
    index= pd.date_range(start='20190101', freq='1d', periods = size),
)

OP: 10.4 s ± 528 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
future_returns_2: 722 ms ± 29.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
future_returns_numpy: 79 ms ± 7.62 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)


I am just going to comment on a few things because I don't think I have a great high level understanding of your code is meant to do (not that is bad for any reason).

In general I would avoid adding scope to variables if it is not needed, for example instead of declaring _data that is available to the whole F class and reference it with a special id I would just put a new data object on each instance.  Keep in mind limiting the scope of variables would apply for _featherInstances and _eagleInstances as well but there could be some business reason for it that I don't understand.

     var F = function(data) {
                this._id = _featherInstances.length;
                _featherInstances[this._id] = this;
                this._data = data;
            }

        F.prototype.has = function(key) {
            return this._data.hasOwnProperty(key);
        }
   ...

Another note to make is has might not work as you expected it.  For example:

new F({key: undefined}).has('key') would return true


Insert node in sorted doubly linked list

Well, the problem statement is broken. Maybe this is a trick question? In the situation that the value to be inserted is at the beginning of the list (perhaps the list is empty, or the value is small), then you can't successfully control the changes needed to modify the head reference for everyone who has it.

The code you have implies that the possibly new head is always returned after each call, but you run a risk of creating multi-headed lists with multiple heads, if the code outside your function does not do the correct assignments with the head.

That sort of risk is not acceptable in a Java library/function, and thus your encapsulation is wrong, etc.

In front of an interviewer, I would recommend that you say something like: "Well, this function would not be useful in a Java context, the data should be encapsulated and the head node should not be exposed to the user. The function should have no return value, and should not take in the head node as a parameter, but instead the function should be a method on a class that encapsulates a sorted list"

Having said that, though, and looking at your code, your code does as good a job as can be done in the circumstances, and it has good style, naming, and formatting.

If I was really picky, I would suggest that you reverse the if/else condition:

if (previous == null) {
    head = node;
} else {
    previous.next = node;
}

to be:

if (previous != null) {
    previous.next = node;
} else {
    head = node;
}

because that makes it match the logic of the next condition:

if (current != null) {
    current.prev = node;
}

Otherwise, it's all good.


Taking a list of numbers and finding the two largest

You should change your function to take a list and return the two largest of it.
And so you should move the creation of numList out into it's own function.
You should also move the printing out of the function too, and instead return a list of the two largest.
This should spilt your code up to achieve:

def getNumbers():
    numList = []
    num = 'holder'
    while num != '':
        num = input('Please enter a number: ')
        if num != '':
            numList.append(float(Decimal(num)))
        else:
            break
    return numList

def twoLargest(numbers):
    x=0
    y=0
    numbers.sort(reverse=True)
    for i in range(len(numbers)):
        if numbers[i] > x:
            x = numbers[i]
        elif numbers[i] > y:
            y = numbers[i]

    if y > 0:
        return x, y
    if x > 0:
        return x,
    return (,)

if __name__ == '__main__':
    numbers = getNumbers()
    largest = twoLargest(numbers)
    print(largest)

However you can improve getNumbers, rather than checking to break from the loop twice, you can instead check once.
This removes the need for num = 'holder', and can reduce the amount of lines needed.

def getNumbers():
    numList = []
    while True:
        num = input('Please enter a number: ')
        if num == '':
            break
        numList.append(float(num))
    return numList

However it can further be simplified by making it a generator function.
To do this you can just yield the values, rather than numList.append them.

def getNumbers():
    while True:
        num = input('Please enter a number: ')
        if num == '':
            break
        yield float(num)

Moving onto twoLargest, it doesn't work with a generator, as you don't cast numList to a list.
You also use sort the list in descending order, so rather than using a loop to find the largest two, you should instead use slicing.
This can get you:

def twoLargest(numbers):
    return sorted(numbers, reverse=True)[:2]

Going forward, you can make an 'n' largest function.
But rather than using sorted you can use; heapq.nlargest, and max.
Making the interface as standard as possible you can get:

from heapq import nlargest

def nLargest(numbers, n=1, key=None, sort=False):
    kwargs = {'key': key}
    if key is None:
        del kwargs['key']
    if n == 1:
        try:
            return [max(numbers, **kwargs)]
        except ValueError: # if passed an empty iterable
            return []
    if sort:
        return sorted(numbers, reverse=True, **kwargs)[:n]
    else:
        return nlargest(n, numbers, **kwargs)

The reason for the three methods is described under nlargest:

  The latter two functions perform best for smaller values of n.
  For larger values, it is more efficient to use the sorted() function.
  Also, when n==1, it is more efficient to use the built-in min() and max() functions.
  If repeated usage of these functions is required, consider turning the iterable into an actual heap.


There is no reason to use flock and  a mutex, unless you are sharing
with another process (as opposed to thread).  I would just use the mutex and
remember to check the return values from the pthread_* and write calls.

Some other comments:

name in write_to_file should be const and the write call in that
function should use the length of the name, not an assumed 20.
you need to check the status of function calls (read, write, send
etc).
depending upon where the data being written is coming from and what it
contains, you may have byte-ordering problems that are not handled.
Since you are mixing string data and dat_com structures on the socket, you
risk getting them mixed up.  You'd be better sticking with one format, maybe
strings and have a way to check alignment and log/recover-from errors.
Your fprint calls are not synchronized across threads and may end up
interleaved.
When sending the name, there is no need to copy it into a string first.

sprintf(str_send,"%s",incm_dat->name);
send(this_fd,str_send,sizeof(incm_dat->name),MSG_NOSIGNAL);

just send it directly:

send(this_fd, incm_dat->name, strlen(incm_dat->name), MSG_NOSIGNAL);

Your variable and type names are poorly chosen.  dat_com means little,
this_fd should be just fd, incm_dat could be just data, o_fd as a
global should be longer and more descriptive of function.


Calculating the difference between 2 arrays

Regarding the way to achieve this task I couldn't find any better strategy than yours.

On the other hand your code may be made cleaner and more readable by:

first merely following best-practices (don't put several statements in the same line,
using more significant names (such as $initial and $final instead of $array1 and $array2, $final_value and $initial_value rather than only $value)
avoiding to declare useless variables (like $array1diff, used only once)
using the more direct expressions when possible (e.g. $array2[key] is already available as $value, while -1 * $array1[$key] is merely -$array1[$key])
using the ternary operator where it can simplify the code (see also the note below)

It results in a reduced code:

function stock_diff($initial, $final) {
    foreach ($final as $key => $final_value) {
        $result[$key] = $final_value - @$initial[$key] ?: 0;
    }
    foreach(array_diff_key($initial, $final) as $key => $initial_value) {
        $result[$key] = -$initial_value;
    }
    return $result;
}

NOTE: regarding the use of @ in the ternary operator, I know that many people automatically banish it as globally evil.
I don't agree with this too general point of view: sure it must be avoided in many situations where it might lead to some issues, but it's pretty legal when used carefully and with discernment.

In the case above, the only "error" it may hide is the one we know it may happen (undefined index), so it keeps sure.
And so it helps making the code more readable and reduced:
(isset($initial[$key]) ? $initial[$key] : 0)
is replaced by
@$initial[$key] ?: 0

The only con is about performance: using @ works slightly slower than isset(). So avoid it when you know that a piece of code will be executed a significantly huge number of times.


Implementation of Python's re.split in Clojure (with capturing parentheses)

You can adjust you implementation to be a lazy-seq for some added performance:

(use '[clojure.string :as string :only [blank?]])

(defn re-tokenizer [re text]
  (let [matcher (re-matcher re text)]
    ((fn step [last-index]
       (when (re-find matcher)
         (let [start-index (.start matcher)
               end-index (.end matcher)
               match (.group matcher)
               insert (subs text last-index start-index)]
           (if (string/blank? insert)
             (cons match (lazy-seq (step end-index)))
             (cons insert (cons match (lazy-seq (step end-index))))))))
     0)))

This implementation will be more efficient as the results will only be calculated as needed. For instance if you only needed the first 10 results from a really long string you can use:

(take 10 (re-tokenize #"(\W+)" really-long-string)

and only the first 10 elements will be computed.


Check if a list of ints is pairwise sorted

if (size <= 1) {
        // Pairwise sorted for lists smaller than two elements
        return true;
    }

Special cases are sometimes useful, but KISS: does this simplify the code or make it more complex for no benefit?

    boolean reIncrementSize = false;
    if (size % 2 != 0) {
        reIncrementSize = true;
        size--;
    }

  ....

    if (reIncrementSize) {
        size++;
    }

Yikes! It really shouldn't be necessary to make temporary changes to the state of the class. But if you really absolutely have to do it, you should use try ... finally to guarantee that they are undone. Here the temporary changes introduce a bug: if we hit the return false then the size is permanently decremented.

    for(int i = 0; i < size; i+=2) {
        // Pairwise sorted if elements are in increasing order
        if (elementData[i] > elementData[i + 1]) {
            return false;
        }
    }

Why was size temporarily decremented? I presume it's to avoid an out of bounds array access in elementData[i + 1]. But you can do that just as well by making that be the guard condition:

    for(int i = 0; i + 1 < size; i+=2) {


Determining whether or not a number is prime

Since this has been migrated to CodeReview, it makes sense to inspect it from a review perspective.

Others have correctly pointed out that the limit of your iteration is the root of the the number. That will impact the performance.... but what about your actual question: can the code be shorter (rather than faster)?

First, some comments....

you really should not use System.exit(...). A simple return would work better in this situation
You are not closing the Scanner when you are done with it. I know that in this case, working on System.in you don't think it's necessary, but, you should get in the habit of doing it. I have seen too many occasions where unclosed-handles create problems.
the variable names are horrible .... x, y and i? (Well, i is OK....).
in the current version of the code, you are still doing i++ and not i+=2. This is because you are starting at 2. If you start at 3 you can do a clean +=2.
Math.sqrt(...) returns a double. Doing a comparison against double for each loop is something the JIT compiler may be able to optimize, but I would err on the side of caution, and manually cast it outside the loop.

So, putting it together, I would suggest something like:

public static void main(String args[]){
    System.out.println("Enter the number:");
    try (Scanner scanner=new Scanner(System.in)) {
        final long target = scanner.nextLong();
        final long limit = (long)Math.sqrt(target);
        for(long factor = 2; factor <= limit; factor += factor == 2 ? 1 : 2){
            if(target % factor == 0) {
                System.out.printf("%d is not a prime\n%d divides by %d", target, target, factor);
                return;
            }

        }
        System.out.println(target + " is a prime number.");
    }
}

The above code is reasonably well structured, etc.

If I was aiming for raw performance though, and I threw out some of the validation rules, and allowed myself to hack it a bit, I would consider:

private static final long factor(final long target) {
    if (target <= 2) {
        return 1; // 1 and 2 are 'prime' external call will have to special-case 1 and negative numbers..
    }
    if ((target & 0x001) == 0) {
        return 2; // it's even.
    }
    final long limit = (long)Math.sqrt(target);
    for(long factor = 3; factor <= limit; factor += 2){
        if(target % factor == 0) {
            return factor;
        }
    }
    return 1;
}

public static void main(String args[]){
    System.out.println("Enter the number:");
    try (Scanner scanner=new Scanner(System.in)) {
        final long target = scanner.nextLong();
        final long fac = factor(target);
        if(fac > 1) {
            System.out.printf("%d is not a prime\n%d divides by %d", target, target, fac);
            return;
        }
        System.out.println(target + " is a prime number.");
    }
}

The reason for this is:

measuring performance with a single call is never going to do anything in Java - you need to call the code enough times to allow the JIT compiler to compile it.
It is unlikely that the JIT compiler will ever compile the main method
So I extract the 'hard' logic in to a seperate method that the JIT system can compile and isolate.
I handle the special cases seperately....
put the user-dialog outside the calculation....


Copying values from one sheet to another

Lowest Hanging VBA Fruit:

Public Sub ()
    Application.ScreenUpdating = False
    Application.EnableEvents= False
    Application.Calculation= XlManual

    ...

    Code

    ...

    Application.ScreenUpdating = True
    Application.EnableEvents= True
    Application.Calculation= XlAutomatic
End Sub

Every time you access the worksheet, events trigger, formulas recalculate and Excel re-draws the screen.
You're accessing the worksheet 4,000 times.
Turning those options off will make your code inordinately faster. Just make sure they get reset back to normal at the end.

Superfluous Logic

If rCell.Value <> "" Then
    If Len(rCell.Value) > 3 Then

If Len(value) > 0 then, by definition, value is not an empty string. So you can just drop rCell.Value <> "".

Use row/column numbers. not Strings and offsets.

This is more of a good practice thing. Get in the habit of using Cells(Row, Column) instead of Range("B" & number).

Like so:

Dim finalRow As Long
Dim iRow As Long
Const TARGET_COL As Long = 2
Dim cellText As String

For iRow = 2 To finalRow

    cellText = WSS.Cells(iRow, TARGET_COL).Text

    If Len(cellText) > 3 Then
        '/ Do Stuff
    End If

Next iRow