Your code is good, but it could be improved:

Using an enum

If you use an enum, you can avoid Magic Numbers in your switch statement:

    switch (bbFormat) {
        // Depending on which format was chosen, different regex patterns are used
        case '1':

Whereas, doing:

var BB_FORMAT_TYPES = {
    NoQuotes: 1,
    DoubleQuotes: 2,
    SingleQuotes: 3
};

with:

switch (bbFormat) {
    case BB_FORMAT_TYPES.NoQuotes:
        break;
    case BB_FORMAT_TYPES.SingleQuotes:
        break;
    case BB_FORMAT_TYPES.DoubleQuotes:
        break;
}

However, using an enum is usually suited more for when the contents of each have different execution styles. In your case, it'd be better to move the code to an object, and have a single execution path referencing said object.

    var object = {
        1: {
            regexTab: /\[tab=((\w|[ äöüÄÖÜ,.\-;:_#'+*!"§$%&/()=?ß^°])*)\]/g,
            regexSubTab: /\[subtab=((\w|[ äöüÄÖÜ,.\-;:_#'+*!"§$%&/()=?ß^°])*)\]((.|\s)+?((?=\[subtab)|(?=\[\/tabmenu)|(?=\[tab)))/g,
            titleTemplate: '###'
        },
        2: {
            regexTab: /\[tab="((.| )*)"\]/g,
            regexSubTab: /\[subtab="((.| )*)"\]((.|\s)+?((?=\[subtab)|(?=\[\/tabmenu)|(?=\[tab)))/g,
            titleTemplate: '"###"'
        },
        3: {
            regexTab: /\[tab='((.| )*)'\]/g,
            regexSubTab: /\[subtab='((.| )*)'\]((.|\s)+?((?=\[subtab)|(?=\[\/tabmenu)|(?=\[tab)))/g,
            titleTemplate: "'###'"
        }
    };

Chaining:

Instead of having the replace on each line, try using chaining:

    input = input.replace(regexSubTab, '[spoiler=' + titleTemplate.replace('###', '$1') + ']$3[/spoiler]');
                 .replace(regexTab, '[h]$1[/h]');
                 .replace('[tabmenu]', '')
                 .replace('[/tabmenu]', '');

that way you can avoid looking up and writing to the input variable each time.


Fastest way to find and replace inside a large amount of files

Building on what Heslacher and Magus have said:

You should not make publically accessible non-readonly collections. So I've converted those to readonly collections. It didn't appear to change how you were accessing them anyway.

I've also swapped your outermost for loop for a foreach, which makes the code slightly cleaner and I've swapped your while loop for a foreach, because it appears to just be iterating over the collection. However this assumes that

File.WriteAllLines(toUseData[i].applicationPath + toUseData[i].dependencyAssetPath[i], lines);

is a bug and should instead be

File.WriteAllLines(toUseData[i].applicationPath + toUseData[i].dependencyAssetPath[0], lines);

If not, then the while loop should be used.

Resulting version:

public class SendToThread
{
    private int localId = 0;
    public int LocalID
    {
        get{ return localId;}
        set{ localId = value;}
    }
    public string OldID {get; set;}
    public string NewID {get; set;}
    private readonly List<string> dependencyAssetPath = new List<string>();
    public List<string> DependencyAssetPath
    {
        get{ return dependencyAssetPath;}
    }
    public string ApplicationPath {get; set;}
}

public void ReadAssets()
{
    //toUseData is a List<SendToThread>
    foreach(var toUse in toUseData)
    {
        foreach(var assetPath in toUse.DependencyAssetPath)
        {
            string[] lines = File.ReadAllLines(toUse.ApplicationPath + assetPath);

            for (int e = 0; e < lines.Length-1; e++)
            {
                DebugVoid(lines.Length.ToString());
                lines[e].Replace(toUse.OldID, toUse.NewID);
            }

            DebugVoid(toUse.OldID + "  " + toUse.NewID);
            File.WriteAllLines(toUse.ApplicationPath + assetPath, lines);
        }
        toUse.dependencyAssetPath.Clear();
    }
}


An "Add" button that clones an item, and a "Remove" button that fades and removes an item

I would go with ChrisThompson's method of adding classes and referring to them.
But to answer your question straight and simple

the first block can look like

$.each( ['s','i','r','ieu','ied'], function(index,item){
        $('#' + item + '0 option').clone().appendTo('#' + item + obj );
    });

However, you did not specify what obj is

The second block can use the same technic to be simplified.

The entire code would look something like this

$(function() {
  $('a.add').click(function(evt) {
    //clone lists
    //is there any way to simplify this part --begin--
    $.each( ['s','i','r','ieu','ied'], function(index,item){
        $('#' + item + '0 option').clons().appendTo('#' + item + obj );
    });
    //--end--
    evt.preventDefault(); //prevents scrolling
  });

  //remove inputs/selects
  $('a.remove').click(function(evt) {
    //animation is not necessary. How can I simplify this code? --begin--
    $.each( ['comp','ppt','ct','p','ipvs'], function(index,item){ $('#' + item + x).animate({opacity:"hide"} ,"slow").remove();});
    $.each(['s','i','r','other'], function(index,item){ $('#'+item+x).remove()});
    //--end--
    evt.preventDefault();
  }
  });
});

However, it seems to me you are using too complex HTML structure.
you need to

Stop using IDs, and start using classes for elements that have things in common
For example :

Instead of cloning each item, you can wrap all of the in a DIV and simple use html() to clone the entire HTML. When you inject the HTML to some other div, give the new wrapper div an ID.

For example

$(".my-form").append($("<div/>").addClass(".object-item").attr("id","newObject" + $(".my-form .object-item").length ).html( $(".items-to-clone-wrapper").html() );

You then have a unique identifier for every element on the page. for example $("#newObject1 .s") instead of $("#s1").

Here is a fiddle I made on the assumptions I made about your code. I hope it will be of use to you. please let me know if there's something I can do.


You can simplify math whenever possible. No reason to multiply by 20 then divide by 100. Just multiply by .20. If you needed a result that was twenty percent in addition to 100 percent of what you already had you could multiply by 1.2. It saves a process making your code just a tad more efficient!


Reading new data from a constantly updating file in Java

You can use the Java WatchService as described here. You said that WatchService is too slow for you. There are other people who have had that problem and resolved it https://stackoverflow.com/questions/9588737/is-java-7-watchservice-slow-for-anyone-elsein this thread.

On a side note, consider using ScheduledThreadPoolExecutor rather than Thread.sleep. The former will recreate threads if they are killed by an exception, has the potential to reuse threads in a pool, and has other potential advantages.


There is a significant flaw in your code; this line:

pairs = [0] * 5

only occurs once, and I couldn't spot pairs being emptied anywhere.

The code to create the list of names is very inefficient, this:

name = ""
names = list()
...
for i in range(0,len(datas)):
    if (datas[i] == "\n"):
        names.append(name)
        name = ""
    else:
        name += datas[i]

Could be written as:

names = data.split("\n")

Note also that for char in data would have been a more Pythonic loop construct.

You can use itertools.combinations to get pairs of names:

for name1, name2 in combinations(names, 2):

You can use collections.Counter to simplify getting the initial numbers:

counter = Counter(name1.lower())
counter.update(name2.lower())
pairs = [sum_digits(counter[c]) for c in "pairs"]

Your compute_percent only works when exactly five letters are chosen, you can make it much more general (and shorter):

def compute_percent(pairs):
    while len(pairs) > 2:
        pairs = [sum_digits(n1+n2) for n1, n2 in zip(pairs, pairs[1:])]
    return (10 * pairs[0]) + pairs[1]

I would split the if __name__ == "__main__" section into more, smaller functions, something like:

get_names to extract the names from the file;
perfect_pairs to pair them off; and
score_pair to calculate the score.

Then all you have in the last block is:

print(len(perfect_pairs(get_names())))


// The digits of the greatest and least safe integers, 2**53 and
// -2**53 respectively.
var limDigits = [9, 0, 0, 7, 1, 9, 9, 2, 5, 4, 7, 4, 0, 9, 9, 2];

As Flambino mentioned already it's probably not a good idea to store the actual digits of 253 in the source code. At least it's confusing. It's hard to tell if there's a typo. I would use a math function like Math.pow since it's so easy to read and does exactly what the comment says:

var lim = Math.pow(2, 53);
var limDigits = String(lim);

var safeIntegerStructure = new RegExp('^[-+]?0*(\\d{1,' + limLength + '})$');

I suggest using the RegExp constructor as little as possible because it's confusing. It's only necessary if you need to use dynamic expressions. Otherwise it adds much clutter from the escape sequences and string concatenations. In fact in this case you wanted to have a dynamic expression. But it's not really necessary. You can check the length of the capture group way easier.

var safeIntegerStructure = /^[-+]+0*(\d+)$/;

// If str is not a string, it cannot be a safe integer string.
if (Object.prototype.toString.call(str) !== '[object String]') {
  return false;
}

This looks pretty good. Depending on the use of the function it might make sense. And I have too little experience to argue with it. It's not even that important since I think <input> only ever has string values. Still you might consider to accept other types and coerce them to a string. I think it's pretty easy to read and to me it seems to be the usual approach in many libraries etc. when a function expects a string.

str = String(str);

Of course if you only want to accept strings this doesn't work. And since typeof str === 'string' doesn't work with String objects your way of using Object.prototype.toString looks like the best approach.

var match = str.match(safeIntegerStructure);

I've never used String#match this way. In my opinion the real purpose of this method is to get an array of all matches with a global regexp. For obtaining a single match I use RegExp#exec. But I suppose this might be just a personal preference since both versions have the exact same results.

var match = safeIntegerStructure.exec(str);

if (match === void 0) {
  return false;
}

I think this is a bug. Both String#match and RegExp#exec should return null when there is no match. But void anything is undefined. On the other hand when there is a match they return an array. I found checking the truth value to be the easiest to write and review.

if (!match) {
  return false;
}

var numerals = match[1];
var numeralsLength = numerals.length;
if (numeralsLength < limLength) {
  return true;
}
if (numeralsLength > limLength) {
  return false;
}
for (var i = 0; i < numeralsLength; ++i) {
  var digit = parseInt(numerals.charAt(i), 10);
  var limDigit = limDigits[i];
  if (digit < limDigit) {
    return true;
  }
  if (digit > limDigit) {
    return false;
  }
}

The for-loop iterates through the individual digits to compare them and stops at the first difference. Essentially this is exactly the same thing as the built-in string comparison operators do. So after making sure the entered number and the limit have the same number of digits you can compare them lexicographically:

var digits = match[1];
if (
  limDigits.length < digits.length ||
  limDigits.length === digits.length && limDigits < digits
) {
    return false;
}

Actually though it's a matter of opinion if the range of safe integers should be defined as [-253;+253] or [-(253-1);+(253-1)]. For example the ES6 draft defines Number.MAX_SAFE_INTEGER as 253-1. This makes sense considering that 253 already is ambiguous:
Math.pow(2, 53) === Math.pow(2, 53) + 1

Using this alternative definition of "safe integer" you could safely use parseInt (or simple type coercion), removing the need for lexicographic comparison.

var lim = Math.pow(2, 53) - 1;
var value = +match[1];
if (lim < value) {
  return false;
}

So ultimately the function could become very short and therefore even easier to read in my opinion:

function isSafeInteger(str) {
  var match = /^[-+]?0*(\d+)$/.exec(String(str));
  return !!match && +match[1] < Math.pow(2, 53);
}


Currency_Names, Currency_Counts and Currency_Index all use the same range,
so it is better to declare a ranged type (or a subtype):

   type Index is range 1..10;
   Currency_Names  : array (Index) of Currency_Denomination;
   Currency_Counts : array (Index) of Integer := (others=>0);
   Currency_Index  : Index;

To loop backwards, it is better to use the reverse keyword:

   -- calculate needed currency
   for I in reverse Currency_Names'Range loop
      while Input_Amount >= Currency_Names(I).Value loop
         Input_Amount := Input_Amount - Currency_Names(I).Value;
         -- increment currency useage in array
         Currency_Counts(I) := Currency_Counts(I) + 1;
      end loop;
   end loop;

   -- display needed currency
   for I in Currency_Counts'Range loop
      -- do not display unused currency
      if Currency_Counts(I) /= 0 then
        Text_IO.Put(Currency_Names(I).Name & " ");
        Integer_Text_IO.Put(Currency_Counts(I));
        Text_IO.New_Line;
      end if;
   end loop;

A nice side-effect is that the index of Currency_Counts will now correspond to the index of Currency_Names, no need to calculate the index anymore, and the Currency_Index variable is no longer needed.


Image processing using Python OOP library

This scenario is not best case for doing an OOP conversion: In this example you're not getting real assistance from the Segmentation1 class over what you'd get by using static functions.  The code looks like it does what you need done; it's simply not a great application for OOP as written.  At some point you should check out this talk by Python core dev Jack Diederich for some perspective on when OOP helps in Python and when it doesn't. One of the main takeways there is that classes which expose just one method ususally don't need to be classes.

That said:

If you want to use this as learning case, you can refactor your arrangement so that you have two different classes for the two different strategies.  This is overkill in the code as is, but if you anticipated a much wider range of segmentation tasks with different inner workings it might make sense. It would be a good choice if the segmentation operation had multiple steps and needed to maintain state within a single run -- for example, if it had to collect data from multiple data sources and coordinate it differently for LAB colors and HSV colors.

Your existing code really has only two paths, splitting on the procedure.  So that's a good clue that you want the sibling classes to differ primarily according to the differences  -- the rule is to "encapsulate what varies" -- and, conversely, to share the parts that are the same. The file handling and so on are the same.  So first you can isolate the unchanging bits into mini-methods of their own, and then bookend them around the parts that will change:

class SegmentationType(object):
    DISPLAY_NAME = "invalid"

    def __init__(self, filename, path):
        self.filename = filename
        self.path = path
        self.input_data = None
        self.output_data = None

    def read_image(self):
        self.input_data =  cv2.imread(self.path + self.filename)[1]

    def write_image(self):
        cv2.imwrite(self.path + self.filename.split('.')[0] + '_' + self.DISPLAY_NAME + '.png', self.output_data)

    def process(self):
        # override in derived classes to perform an actual segmentation
        pass

    def start_pipeline(self):
        self.read_image()
        self.process()
        self.write_image()

Then you just need to create subclasses for your strategies:

class HSV_Segmenter(SegmentationType):
    DISPLAY_NAME = 'HSV'

    def process(self):
        source = rgb_to_hsv(self.input_data)
        self.output_data = treshold_otsu(source)

class LabSegmenter(SegmentationType):
    DISPLAY_NAME = 'LAB'

    def process(self):
        source = rgb_to_lab(self.input_data)
        self.output_data = global_threshold(source)

This should be equivalent to your earlier code -- it does have one minor advantage, which is that it will fail at compile time if you don't pick the proper subclass where the original would fail at runtime if you accidentally pass a bad value for procedure.  Then your program simply chooses the right class and calls it:

segmenter_class = {
    'hsv': HSV_Segmentation,
    'lab': LAB_Segmenter
}.get(procedure)

if not segmenter_class:
    raise ArgumentError("Invalid segmentation method '{}'".format(procedure))

for img in images:
    os.chdir(img_dir)
    processor =  = segmenter_class(img, img_dir, procedure)
    processor.start_pipeline()

Again, I personally would stick with static functions in this situation.  In Python you could achieve all the good parts of the class arrangement by just having that dictionary lookup return the right static functions instead of classes.  Lots of languages don't have that neat function and so this kind of structure is very common there.


Invert a dictionary to a dictionary of lists

You are right, you should not use a list comprehension just for its side-effects. It is not very readable and only confuses the reader of the code.

Instead, just make it for loops. And put it into a function, so it is re-usable:

from collections import defaultdict

def reverse_dict_of_lists(d):
    reversed_dict = defaultdict(list)
    for key, values in d.items():
        for value in values:
            reversed_dict[value].append(key)
    return reversed_dict

if __name__ == "__main__":
    d = {"abc": [1, 2, 3], "cde": [3, 5, 7], "efg": [4, 2, 1, 7]}
    print(reverse_dict_of_lists(d))
    # defaultdict(<type 'list'>, {1: ['abc', 'efg'], 2: ['abc', 'efg'], 3: ['cde', 'abc'], 4: ['efg'], 5: ['cde'], 7: ['cde', 'efg']})

This might take a very small performance hit (it doesn't, see below), but this should be negligible compared to actually being able to understand what the code does.

Here are some timings on my machine. First I generate a list of some randomly filled dictionaries:

import random

def generate_dicts(dict_length, step=1):
    return [{i: [random.randrange(1, 100) for _ in range(j)]
             for i, j in zip(
                 [random.randrange(1, n_keys) for _ in range(n_keys)],
                 [random.randrange(1, 100) for _ in range(n_keys)])}
            for n_keys in range(2, dict_length + 2, step)]

This will generate dictionaries of the form {i: [...]}, where there are an increasing number of keys in the dictionary and also the length of the lists increases (but is random).

Plotting the time it takes to reverse the dictionary for dict_length = 100000, step = 1000:

And, with a slightly more realistic sample dict, which does not overwrite the keys and therefore shows the quadratic behavior of the double loop:

import numpy as np

def generate_dicts(n_keys_values):
    return ({i: [random.randrange(1, 100) for _ in range(random.randrange(1, n_keys))] for i in range(n_keys)} for n_keys in n_keys_values)

n_keys_values = np.logspace(1, 4.5, num=20, dtype=int)

This is on Ubuntu 17.04, Python 3.6.3, IPython 6.2.1, Intel i7-4710MQ (8) @ 3.500GHz.

You can see that the loop based approach is actually slightly faster in both cases :). The reason being, as Eric Duminil put it succinctly in the comments:

  A list comprehension might be faster than creating a list with a for loop. In [this] case, the list comprehension creates a useless list full of Nones. And this list isn't created at all with the for loop.


Bugs

When processing an expression like 10/2 or 10*2, the 2 gets discarded from the output.

It looks like you attempted to implement a circular buffer for the output, but it actually fails miserably if the output exceeds 1000 bytes.  One problem is performance: myputchar() performs a linear scan of the buffer to find the end of the string, where it can write the next character.  A second problem is buffer overflow: myputchar() makes no attempt to ensure that the location where it stores the next character lies within the buffer.  The third problem is that when you do if (i > MAXCHAR)i = 0, you haven't made any attempt to print the buffer contents before trying to reuse the buffer.

C grammar

In C, a /* or // that appears within a "string literal" should be treated literally.  It should not be interpreted as a start-of-comment marker.

Furthermore, within a //-style comment, any /* or */ needs to be disregarded.  Similarly, within a /* */-style comment, any // should be disregarded.  That is, the correct output for the following C99 program…

#include <stdio.h>
int main() {
    puts("First " /* asdf // */ "example"
    );
    puts("Second " // /*
         "example"
         // */
    );
    puts("Third " /* "/" */ "example");
}

… should be

First example
Second example
Third example

(I also got this wrong in Rev 1 of this answer.  I've corrected the bug, but this illustrates a point that C requires a stateful parser.)

Organization

The variables c, d, newFileText, longDisable, shortDisable, and i are global; they should all be local to the main function.

It is customary to put the main function last, so that you don't need to declare the functions it uses.

Input / output

You read one character at a time with getchar(), but you attempt to print the output in chunks of up to 1000 characters.  Writing in chunks could be more efficient than writing a character at a time, but it is certainly more difficult to implement correctly.  However, after you go through the effort of accumulating the chunks, you then proceed to print the buffer one character at a time using printf("%c", theArray[i]), which negates any performance advantage you could have gained.

Therefore, you would have been better off printing the output one character at a time to begin with, without any attempt at buffering.  To do so, you could use putchar(…), which is simpler than printf("%c", …).

If you did want to efficiently write a chunk of bytes at a time, you could use the write() function instead of the loop in printArray().

Suggested solution

This solution addresses the more serious logic bugs, without attempting to handle string literals correctly.

#include <stdio.h>

int main(void) {
    int c, d;
    int longDisable = 0, shortDisable = 0;

    while ((c = getchar()) != EOF) {
        switch (c) {
          case '/':
          case '*':
            d = getchar();
            if (!longDisable && c == '/' && d == '/') {
                shortDisable = 1;
            } else if (!shortDisable && c == '/' && d == '*') {
                longDisable = 1;
            } else if (!shortDisable && c == '*' && d == '/') {
                longDisable = 0;
            } else if (!(shortDisable || longDisable)) {
                putchar(c);
                if (d != EOF) putchar(d);
            }
            break;

          case '\n':
            shortDisable = 0;
            /* fall through... */
          default:
            if (!(shortDisable || longDisable)) {
                putchar(c);
            }
        }
    }
}


Reducing the sorting time of a large number of numbers

Single Responsibility and Lying Names
The tsort method does too much. It both gets input from the user and stores that information in an array (a potentially large one at that, but more on that later). Then it prints the array. You should have three separate methods here and tsort should do one thing, sort an array. As it is, nothing actually gets sorted per se. You're just keeping the list sorted, which seems smart, but...
Performance
Think about what happens when I give gets.chomp.to_i the number 100. The number 1 gets placed into the 100th position of the array. To get it back out, we have to then iterate over 100 positions. If I give it 1000 instead, we now have to make 1000 iterations in order to find it. That's 10 times as many iterations. This method gets exponentially slower. It is no surprise that inputting 10^6 exceeds the time constraints; it takes 10^6 iterations to print the number, even if it's the only number in the array.
This can be solved by implementing any number of well studied sorting algorithms. A quick google search should get you started. I recommend learning to bubble sort first, then move on to the more efficient algorithms. This assumes you're doing this for educational purposes. Otherwise, just use Ruby's built in Array#sort method.


Simple login form with vanilla HTML markup

It's in the HTML (script tag). Link it. Keep 'em separated whenever possible.
Not a big deal but when declaring vars you can do them with one var statement, e.g. var a = 0, b = 3;
Add 'use strict;' to look super cool (but I've seen at least one thing that will break)
Fix stuff like linkLocation = 'home.html'; (no var statement - would be global - illegal in strict mode)
window is global in browsers. window.location can just be called as location
If this is to be seen by interviewers, be consistent with your style. For instance, you  mix ' and " for strings. Most prefer ' to differentiate from HTML attribute quotes which are typically double. Mixing both looks like it's not all your code or you're a little sloppy.
When it's just a JavaScript object and not JSON, it doesn't need quotes on the property names. e.g. send = { 'password':...
If it's an interview situation, don't pretend any of the regEx is yours unless you can explain it.
You're pooping all over the global namespace - quick fix would be:

(function(){

//wrap your code here

})()

Don't know what's wrong with code formatting but that puts your functions in scope with anonymous function that automatically fires so it should keep your stuff from being overwritten or overwriting other stuff in the global namespace.

Otherwise it looks like good, clean, straightforward, procedural code. Nothing wrong with that when it's all that's called for. If this were a heavy, complicated, application, I'd be wondering where the objects were at.


Bash function to generate colored output

Three things strike me immediately:

You are treating foreground and background colors equally, and giving preference to reverse video and underline(?). Why is red foreground %fRed% while reverse video is %r%? Aren't you more likely to use red,yellow,green foreground than reverse video? Aren't you more likely to use foreground colors than background colors?

I think you should give some thought to the "Huffmanization" of your color names. Maybe you need %r% %g% %y% as shortcuts for foreground red, green, and yellow. (Or, maybe not. It depends on what your use case is going to be. If you're writing a rogue-like in bash, maybe you have a different color vocabulary...)

I would suggest that foreground colors just be color names, while background colors have a bg prefix:  %cyan% versus %bgCyan% for example. This makes background colors more expensive than they currently are (1 extra character) but makes foreground colors less expensive, and I suspect they'll be more common.
Next, I think you're doing too much work inside your loop. You are actually processing the format string character-by-character! Given that the beginning delimiter and ending delimiter are the same - % - you could use IFS to split the string into an array and process the segments of the array. Given a string like "before % during % after", or even "%during%", you know that the alternate members of the array are going to be tags: even indices text, odd indices tag.

See this answer on SO for how to split a string.

This would make change your loop from processing characters into processing "strings", and should speed up your function.
Finally, there are a lot of "magic strings" in your code. Like magic numbers, you should replace these with constants (variables) and reference them just once. In particular, I'm thinking of ${pfx} ("\033[") and maybe ${reset} ("${pfx}0m").


Simple class for 2D  1D array index conversion

Use modulus

Instead if this i-x*cols_ you can use the modulus operator i % cols_.

Use a unsigned type.

If you use unsigned there is no need to check for x >= 0 && y >= 0. Also you can con throw the exception directly in check. And you just need check_xy.

    void IndexConv::check(unsigned x, unsigned y) const
    {
        if(x >= rows_ || y >= cols_)
            throw std::out_of_range("IndexConv: parameter out of bounds.");
    }

    pair<int, int> IndexConv::to_xy(unsigned i) const
    {
        int x = i / cols_;
        int y = i % cols_;
        check(x, y);
        return make_pair(x, y);
    }

    int IndexConv::to_i(unsigned x, unsigned y) const
    {
        check(x, y);
        return x * cols_ + y;
    }

EDIT: Changed the answer to keep check_xy. Keeping check_i can map (0,2) to 2 when it should throw an exception (Following your example).


I think what you are doing is crazy, but yes, you can use Python’s library functions to clean it up.

from contextlib import contextmanager

@contextmanager
def context_wrap(target):
    yield target

Again, this is busy work.

alias = thing

is clearer, shorter and faster than

with context_wrap(thing) as alias:


Avoid recomputations

You compute the energy accumulated in a sliding window. When a window slides by 1, one sample shifts out, and one sample shifts in. The accumulated energy changes by s[n]^2 - s[n-40]^2. Therefore the inner loop is superficial. This alone will give you a 40-fold improvement.
Quadratic complexity

mysignal is only getting more signals appended to it, that is its initial parts are fed to functioneg over and over again, mostly producing the same result. In fact you only need 40 last of the processed samples to ramp up the new file.
Avoid reallocations

You don't really need the o1 array. sum1 can be computed on the fly.


Populating form contents from GET - especially radio buttons

I went ahead with the one-by-one re-populating from GET (on a timeline and all that!). The form doesn't need to be highly reusable and won't be modified very frequently after roll-out, so in this particular case, it was a matter of 'getr done' rather than 'getr done the best way'.

For the radio buttons, I ended up with a series of these:

  <input id="partner_systemIntegration_1" name="partner_systemIntegration" class="element radio" type="radio" value="yes"  <?php if(($_GET['partner_systemIntegration']) && $_GET['partner_systemIntegration'] == "yes") { echo 'checked'; } ?> />
  Yes

  <input id="partner_systemIntegration_2" name="partner_systemIntegration" class="element radio" type="radio" value="no"  <?php if(($_GET['partner_systemIntegration']) && $_GET['partner_systemIntegration'] == "no") { echo 'checked'; } ?>  />
  No

It's klunky, but when I tried to break it out into a function it failed. I'm using WordPress and a plugin that allowed PHP in the post/page content itself. When trying to define and use a function, I got some sort of eval error/warning, so I'm just doing it one at a time. Not the epitome of elegance and not my ideal choice, but now I can move on.


You could clean it up a bit by using reduce and forEach instead of map (especially as you don't need map's return value, but are just using it as an iterator)

function uniqueKeys(objects) {
  var keys = objects.reduce(function (collector, obj) {
    Object.keys(obj).forEach(function (key) {
      collector[key] = true;
    });
    return collector;
  }, {});
  return Object.keys(keys);
}

Alternatively, you could combine all the objects, and then use Object.keys on the result. Just be careful, as extend-type functions usually work on the passed objects directly (as the one below does), rather than returning a new object, so pass an empty object to use as collector:

function extend(target, source) {
  var key;
  for(key in source) {
    target[key] = source[key];
  }
  return target;
}

function uniqueKeys(objects) {
  var combined = objects.reduce(function (target, obj) {
    extend(target, obj);
    return target;
  }, {});
  return Object.keys(combined);
}

If you've got an extend function that takes an arbitrary number of arguments, you could do something like

function uniqueKeys(objects) {
  var collector = {};
  extend.apply(null, [collector].concat(objects));
  return Object.keys(collector);
}

Here are demos of each one


Update the idx values if vals element match between consecutive rows

I may contribute by first eliminating the itertools and collections module.

import csv
import io

Set the data

    data = '''pos\tidx\tvals
    23\t4\tabc
    25\t7\tatg
    29\t8\tctb
    35\t1\txyz
    37\t2\tmno
    39\t3\tpqr
    41\t6\trtu
    45\t5\tlfg''';
print('INPUT:\n'+data);

Create a "set" of OrderedDictionary object based on the data, and then save it as a list. This is because data_As_dict is not subscriptable, relatively not flexible for work in iteration, and each dictionary in it will be erased after being reused.

data_As_Dict = csv.DictReader(io.StringIO(data), delimiter='\t');
list_Of_Dict = [i for i in data_As_Dict];

Now it is saved as a list, we can access each row. We can check the condition by simply checking v1+v2. For example, if v1='abc' and v2='atg', then v1+v2='abcatg'. We have a pattern, 'a' occurs twice, and the others are unique. So here is your condition : len(set(v1+v2)) != len(v1+v2)

Here is the code for creating the output,

for i in range(0, len(list_Of_Dict)-1):
    v1 = list_Of_Dict[i]['vals'];
    v2 = list_Of_Dict[i+1]['vals'];
    if len(set(v1+v2)) != len(v1+v2):
        list_Of_Dict[i+1]['idx'] = list_Of_Dict[i]['idx'];

output_data = 'pos\tidx\tvals\n';
for i in list_Of_Dict:
    output_data += i['pos']+'\t'+i['idx']+'\t'+i['vals']+'\n';
print('OUTPUT:\n'+output_data);

Full code:

import csv
import io

data = '''pos\tidx\tvals
23\t4\tabc
25\t7\tatg
29\t8\tctb
35\t1\txyz
37\t2\tmno
39\t3\tpqr
41\t6\trtu
45\t5\tlfg''';

print('INPUT:\n'+data);
data_As_Dict = csv.DictReader(io.StringIO(data), delimiter='\t');

list_Of_Dict = [i for i in data_As_Dict];

for i in range(0, len(list_Of_Dict)-1):
    v1 = list_Of_Dict[i]['vals'];
    v2 = list_Of_Dict[i+1]['vals'];
    if len(set(v1+v2)) != len(v1+v2):
        list_Of_Dict[i+1]['idx'] = list_Of_Dict[i]['idx'];

output_data = 'pos\tidx\tvals\n';
for i in list_Of_Dict:
    output_data += i['pos']+'\t'+i['idx']+'\t'+i['vals']+'\n';
print('OUTPUT:\n'+output_data);


You're doing a lot of work to parse the input. It seems like it'd be easier if you just used the Scanner class:

final Scanner sc = new Scanner(System.in);
final int numTests = sc.nextInt();

for (int i = 0; i < numTests; i++) {
    final int size = sc.nextInt();
    final int[] arr = new int[size];
    final int[] result;

    for (int j = 0; j < size; j++) {
        arr[j] = sc.nextInt();
    }
    result = calcNewArr(arr);
}

Your implementation runs at \$O(n^2)\$, however, this should be possible in \$O(n)\$ time if you just looked through the array right to left. If the question was asking for left to right on a reverse of the array, the problem would be pretty obvious since it's basically just iterate through and apply some simple rules:

The first element is -1
Copy the highest number seen so far into the position
If the value replaced is greater, set it as the largest number seen so far

So, I think something like this fulfills your calcNewArray:

int largest = -1;

for (int i = ans.length - 1; i >= 0; i--) {
    final int value = ans[i];
    ans[i] = largest;
    largest = Math.max(largest, value);
}

Obviously, comments can improve the code and there's some stylistic things that'll make most Java devs raise their eyebrows, but it's not a big deal. One thing, in particular, however, is to consistently use the following format for array types:

int[] arr = new int[size];

As opposed to int [] arr or int []arr


This 'problem' of yours can be solved using Separation of concern. Your Database class should not know about config and how it is loaded. It should simply ask for the stuff it needs. Neither should your Test class know how to connect. Your test class should test the Database class. And your database class should handle the 'connection failed' error of whatever library you are using.

For instance:

class DatabaseConnection
{
    public function __construct($host, $username, $password, $port='22'){
        if connection failed throw new ConnetionFailedException
    }
}

Your would then also have a config class that loads the correct config file. e.g.:

class Config
{
    public function __construct($enviroment)
    {
        $this->data = include __path_to_config_files_.'/'.$enviroment.'.inc';
    }
}

Your could for instance use a __get method to retrieve the data instead of having a getParameter.

your config file would look something like this:

__path_to_config_files_/development.inc

<?php

return array(
    'key' => 'value'
);

And your test class would then:

$config = new Config('development'); //or whatever enviroment you are in
try {
    $connection = new DatabaseConnection($config->db['host'], $config->db['username'], $config->db['password']);
} catch(ConnetionFailedException) {
    //connection failed
}
//connection success


Expanding upon my comment:

Here is Kadane's algorithm:

def max_subarray(arr):
    max_ending = max_current = arr[0]

    for i in arr[1:]:
        max_ending = max(i, max_ending + i)
        max_current = max(max_current, max_ending)

    return max_current

print(max_subarray([-4, -2, -3, -4, 5])) # 5

print(max_subarray([4, -5, -1, 0, -2, 20, -4, -3, -2, 8, -1, 10, -1, -1])) # 28

Like your algorithm, it is \$O(n)\$. However, it does fewer operations while looping. You could then alter it to return the array which gives that sum, which shouldn't be too hard.


Grab first successful pair from a list of maps

You can use find to avoid folding over an entire map, something like:

map1.find {
  case (k, Right(addr1)) =>
    map2.get(k) match {
      case Some(Right(addr2)) => true
      case _ => false
    }
  case _ => false
} match {
  case Some((k, Right(addr1))) =>
    map2.get(k) match {case Some(Right(addr2)) => Some(haversineDistance(addr1, addr2))}
  case _ => None
}

(I renamed first/secondAddressOption to map1/map2 to save some typing)

An alternative approach, which doesn't necessarily improve performance but does make the code shorter and more reusable, is to create a method that combines two maps by key:

def combineMaps[K, V](map1: Map[K, V], map2: Map[K, V]): Map[K, List[V]] =
  // To improve performance, compare the sizes of map1 and map2
  // and fold over the smaller map.
  map1.foldLeft(map2.mapValues(List(_))) {
    case (map2, (k, x)) => map2.updated(k, x :: map2.get(k).toList.flatten)
  }

Then use collectFirst on the combined map:

combineMaps(map1, map2).collectFirst {
  case (_, Right(addr1) :: Right(addr2) :: Nil) => haversineDistance(addr1, addr2)
}


Avoid using namespace std

This can cause name collisions because it adds every name in the std namespace to the global namespace. For a small program like this one it's unlikely that you'll run into any problems (then again, maybe not) but it's best to get into the habit of using the std:: prefix on names in the std namespace.

Alternatively, you can introduce using declarations like using std::cout; to add specific names to the global namespace.

Avoid std::endl in favor of \n

std::endl flushes the stream, which can cause an unnecessary loss in performance. In printBoard() you use std::endl three times but you can easily replace some of those uses with \n.

Use a class for the Tic Tac Toe board

Instead of using a 3x3 array it's better to create a class to hold the state of the Tic Tac Toe board, with functions to set or get the value of a place on the board, determine whether or not the board is filled, etc. This allows you to hide implementation details which may change later on -- for example, if your compiler supports C++11 or will do so in the future you may want to change your internal representation of the board to use std::array. If you have a class for the Tic Tac Toe board the external interface would not change, only the code that implements the functionality.

Here's what that class might look like:

class Board {
    int board[3][3];
public:
    typedef int value_type;

    // More modern alternative to typedef:
    //using value_type = int;

    Board() {
        for (std::size_t i = 0; i < 3; i++) {
            for (std::size_t j = 0; j < 3; j++) {
                board[i][j] = 0;
            }
        }
    }

    // Gets the value of a board place
    int place(std::size_t x, std::size_t y) const {
        // Might want to check coordinates and throw an exception (e.g. std::out_of_range) if coordinate(s) are invalid
        return board[x][y];
    }

    // Sets the value of a board place
    // It would probably be better to throw an exception (e.g. std::out_of_range) instead of printing to std::cout
    bool place(std::size_t x, std::size_t y, int value) {
        if (x > 2 || x < 0) {
            cout << "Invalid x coordinate. Try again.\n";
            return false;
        } else if (y > 2 || y < 0) {
            cout << "Invalid y coordinate. Try again.\n";
            return false;
        } else if (board[x][y] != 0) {
            cout << "Place is already filled. Try again.\n";
            return false;
        } else {
            board[x][y] = value;
            return true;
        }
    }

    bool is_filled() const {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                // Return immediately once we find a non-filled place
                if (board[i][j] == 0) return false;
            }
        }

        // All places were found to be filled
        return true;
    }
};

(Note the use of std::size_t for the coordinate type and the typedef for the int value type, which mimic practices from the standard library.)

You would no longer need initBoard() since the Board constructor performs the initialization, and some of your other functions would become member functions of the class. In some cases you can improve the performance of these functions -- e.g. you can keep a count of how many places are filled by incrementing the count each time a new place is filled by Board::place(), and then Board::is_filled() simply has to check if that count equals 9 rather than checking every place in the board (the performance gain is negligible for such a tiny board but the principle is important).

Overload operator<< for printing the board

printBoard() only prints to std::cout. You can overload operator<< in order to insert the board into any std::ostream. Using the above Board class the code would look like this:

std::ostream& operator<<(std::ostream& os, Board board) {
    os << "-----\n";

    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            os << board.place(i, j) << " ";
        }

        os << '\n';
    }

    os << "-----" << std::endl;

    return os;
}

(Note the replacement of some of the std::endl uses with '\n`.)

To print the board to std::cout you'd simply use std::cout << board;, and you can use the same function to print the board to a different std::ostream such as a std::fstream (for writing to a file).

Make your code DRYer

In some cases you can make your code DRYer. For example, the code in the if and else sections is very similar here:

if (playerOnesTurn) {
    cout << "Player 1's turn" << endl;
    do {
        cout << "Enter x coordinate: "; cin >> x;
        cout << "Enter y coordinate: "; cin >> y;
    } while (!fillPlace(board, x, y, 1));
 } else {
    cout << "Player 2's turn" << endl;
    do {
        cout << "Enter x coordinate: "; cin >> x;
        cout << "Enter y coordinate: "; cin >> y;
    } while (!fillPlace(board, x, y, 2));
 }

You can put that in a function like this:

// Capture Board by reference so we modify the original Board, not a copy
void player_move(Board& board, int player) {
    cout << "Player " << player << "'s turn" << endl;

    std::size_t x, y;

    do {
        cout << "Enter x coordinate: "; cin >> x;
        cout << "Enter y coordinate: "; cin >> y;
    } while (!board.place(x, y, player));
}

Here's a demo program with some of the changes I suggested:

#include <iostream>
#include <ostream>

using namespace std;

class Board {
    int board[3][3];
public:
    typedef int value_type;

    // More modern alternative to typedef:
    //using value_type = int;

    Board() {
        for (std::size_t i = 0; i < 3; i++) {
            for (std::size_t j = 0; j < 3; j++) {
                board[i][j] = 0;
            }
        }
    }

    // Gets the value of a board place
    int place(std::size_t x, std::size_t y) const {
        // Might want to check coordinates and throw an exception (e.g. std::out_of_range) if coordinate(s) are invalid
        return board[x][y];
    }

    // Sets the value of a board place
    // It would probably be better to throw an exception (e.g. std::out_of_range) instead of printing to std::cout
    bool place(std::size_t x, std::size_t y, int value) {
        if (x > 2 || x < 0) {
            cout << "Invalid x coordinate. Try again.\n";
            return false;
        } else if (y > 2 || y < 0) {
            cout << "Invalid y coordinate. Try again.\n";
            return false;
        } else if (board[x][y] != 0) {
            cout << "Place is already filled. Try again.\n";
            return false;
        } else {
            board[x][y] = value;
            return true;
        }
    }

    bool is_filled() const {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                // Return immediately once we find a non-filled place
                if (board[i][j] == 0) return false;
            }
        }

        // All places were found to be filled
        return true;
    }
};

bool checkWin(Board& board, int player) {
    // horizontal
    for (int i = 0; i < 3; i++) {
        if (board.place(i, 0) == player && board.place(i, 1) == player && board.place(i, 2) == player) return true;
    }

    // vertical
    for (int i = 0; i < 3; i++) {
        if (board.place(0, i) == player && board.place(1, i) == player && board.place(2, i) == player) return true;
    }

    // diagonal
    if ((board.place(0, 0) == player && board.place(1, 1) == player && board.place(2, 2) == player) ||
        (board.place(0, 2) == player && board.place(1, 1) == player && board.place(2, 0) == player))
        return true;

    return false;
}

// TODO implement function if the game is a tie before the last move

std::ostream& operator<<(std::ostream& os, Board board) {
    os << "-----\n";

    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            os << board.place(i, j) << " ";
        }

        os << '\n';
    }

    os << "-----" << std::endl;

    return os;
}

// Capture Board by reference so we modify the original Board, not a copy
void player_move(Board& board, int player) {
    cout << "Player " << player << "'s turn" << endl;

    std::size_t x, y;

    do {
        cout << "Enter x coordinate: "; cin >> x;
        cout << "Enter y coordinate: "; cin >> y;
    } while (!board.place(x, y, player));
}

int main() {
    Board board;
    std::cout << board;

    // should be a bool, not an int
    // alternatively, just use an int which is 1 when it's player 1's turn and 2 when player 2's turn
    bool playerOnesTurn = true;

    while (true) {
        player_move(board, playerOnesTurn ? 1 : 2);

        playerOnesTurn = !playerOnesTurn;

        if (board.is_filled()) {
            cout << "The game is a tie.\n";
            break;
        }

        std::cout << board;

        if (checkWin(board, 1)) {
            cout << "Player 1 has won\n";
            break;
        } else if (checkWin(board, 2)) {
            cout << "Player 2 has won\n";
            break;
        }
    }

    return 0;
}

I left a few other minor tips in the comments and I didn't make all the changes I suggested (e.g. I did not remove using namespace std).


Find path from source to destination in tilt maze

I'd still suggest using a closure, which I addressed in my last answer:

  Your code is WET. As you write pretty much the same thing four times. Instead I'd use a builder function to remove this duplicate logic. This is as you can set the special changes in the builder function, and mutate the data in the returned function.

  Take:

def _move(band, x_inc, y_inc):
    def inner(x, y):
        maze = self.maze
        while maze[y][x] & band:
            x += x_inc
            y += y_inc
        return x, y
    return inner

move_right = _move(2, 1, 0)

The name of MoveEnum could be changed to Moves, as the Enum part is useless when using it. I'd also change CAN_MOVE_* to just *, this is as it doesn't add any value. And so I'd much prefer it to be Moves.UP.

move_path is dodgy. You shouldn't have to pass a list to it, and it should really return results. Instead I would create another closure the outer function to create path, return results, and call the inner function. The inner function to perform the recursion as you currently have it.


Returning an existing data frame with four new columns

Here's a faster way:

add_2maxFaster <- function(x)
{
  imax1 <- which.max(x)
  imax2 <- which.max(x[-imax1])
  if (imax2 >= imax1) imax2 <- imax2 + 1L
  c(x, x[imax1], x[imax2], imax1, imax2)
}

set.seed(42)
m <- matrix(runif(1e6), 1e4)

# Compare speed:
system.time( a1<-apply(m, 1, add_2max) )        # 0.38 secs
system.time( a2<-apply(m, 1, add_2maxFaster) )  # 0.15 secs

# ...And compare results
all.equal(a1,a2) # TRUE


/// <summary>
/// Saves the list of data sources. This assumes that the ModelTemplateID, SetNumber and TaskNumber
/// are already properly set. Adds a new record to the DataSourceGroups table if necessary.
/// </summary>
/// <param name="dataSources">The list of data sources to save</param>
public void SaveSet(IEnumerable<DataSource> dataSources)

The method name is telling a lie. SaveSet would be appropriate if the method took an IEnumerable<Set> sets parameter. I would have called the method SaveDataSources.

Per the XML comments, the method is making assumptions, but it does nothing to verify these assumptions, and since the method has no return type, the only way you can fail is by letting it throw - throwing is good in this situation, however it's best to fail early, if possible before you even create the context instance.

This is done with a guard clause at the top of your method, that aborts the call if an argument is invalid - for example:

if (dataSources.Any(dataSource =>
       dataSource.ModelTemplateID == default(typeof(dataSource.ModelTemplateID))
    || dataSource.SetNumber == default(typeof(dataSource.ModelTemplateID))
    || dataSource.TaskNumber == default(typeof(dataSource.TaskNumber))))
{
    throw new ArgumentException("Members 'ModelTemplateID', 'SetNumber' and 'TaskNumber' not set.", "dataSources");
}

This makes your code throw a more meaningful exception, instead of adding half the items, throwing some foreign key exception and then disposing the context without persisting anything.

using (var db = _contextFactory.GetContext())

While a conveniently short identifier, db is a misleading name to use for a DbContext; it's more of a context than a database, so context would be more appropriate.

I like that the method isn't directly responsible for creating the DbContext instance, however GetContext() sounds like you're not creating anything, rather just returning an existing instance - which is counter-intuitive in the context (pun not intended) of a factory. CreateContext would be better, and since _contextFactory is already a quite descriptive name, a Create method wouldn't be any less clear:

using (var context = _contextFactory.Create())
{

foreach (var dataSource in dataSources)
{
    var dataSourceFromDb =
        db.DataSources.FirstOrDefault(x => x.DataSourceID == dataSource.DataSourceID);

Unless I look at your schema and see that DataSourceID is the entity's primary key, I have no way of being sure that you're expecting only a single record, because FirstOrDefault could just as well operate on 20 entities and only return the first that matches the criteria.

This would be less ambiguous, because if more than 1 entity is returned, SingleOrDefault would throw an exception:

foreach (var dataSource in dataSources)
{
    var dataSourceFromDb =
            context.DataSources
                   .SingleOrDefault(e => e.DataSourceID == dataSource.DataSourceID);

This part looks like it belongs in another method:

        if (dataSourceFromDb == null)
        { // not in database yet, add it
            var dataSourceGroupFromDb =
                db.DataSourceGroups.SingleOrDefault(
                    x => x.ModelTemplateID == dataSource.ModelTemplateID &&
                         x.SetNumber == dataSource.SetNumber &&
                         x.TaskNumber == dataSource.TaskNumber);
            if (dataSourceGroupFromDb == null)
            { // Add new DataSourceGroup to db
                db.DataSourceGroups.Add(new DataSourceGroup
                {
                    ModelTemplateID = dataSource.ModelTemplateID,
                    SetNumber = dataSource.SetNumber,
                    TaskNumber = dataSource.TaskNumber
                });
            }
            db.DataSources.Add(dataSource);

I don't like the comments on the same line as the scope-opening brace { //, and these comments wouldn't be needed at all if you extracted the method; the added level of abstraction would speak for itself:

if (dataSourceFromDb == null)
{
    EnsureDataSourceGroupExists(context, dataSource);
    context.DataSources.Add(dataSource)
}
else
{
    dataSourceFromDb.QueryID = dataSource.QueryID;
    dataSourceFromDb.SourceType = dataSource.SourceType;
    dataSourceFromDb.TargetFormat = dataSource.TargetFormat;
    dataSourceFromDb.SourcePath = dataSource.SourcePath;
    dataSourceFromDb.TargetPath = dataSource.TargetPath;
}

context.SaveChanges();

Notice the how the update code is simply copying the values from dataSource into the members of dataSourceFromDb - that entity is already attached and managed by the change tracker. Why complicate things? It's there, might as well use it!

One thing your code also assumes, is that SaveChanges will insert the DataSourceGroup entity before it inserts dataSource. I don't know about EF6, but in other versions one cannot make that assumption, so EnsureDataSourceGroupExists would call SaveChanges on the context if a new entity was created. Not doing this is like asking for a foreign key violation.


Shuffle the elements of the array randomly

Naming

I would write array out instead of shortening it to arr (it's just two more letters), because it's more readable (but I do like that you are very consistent with your shortening).
is there a reason that you are using ii/jj instead of the more commonly used i/j?

Spacing

You should use a lot more spaces, because they make your code easier to read.

I would at least add spaces after , and ;, before {, and around all = and <.

You should also try to be more consistent with your spacing. For example, you have spaces around some =, but not all, and sometimes you write int [], other times int[].

Randomness

It seems that you implemented a variation of the fisher yates algorithm, which is actually not truly random, but biased:

  Similarly, always selecting j [rand.nextInt(arr.length) in your code] from the entire range of valid array indices on every iteration also produces a result which is biased, albeit less obviously so.

You can go to Wikipedia to read the explanation. Implemented correctly, the swapArr method should probably look like this:

public static int[] swapArr(int[] arr) {
    Random random = new Random();
    for (int i = arr.length - 1; i >= 0; i--) {
        int j = random.nextInt(i + 1);
        arr = swap(arr, i, j);
    }
    return arr;
}

Of course, Random only uses pseudorandom numbers anyways, so the slight bias might not be all that important.

Pass by Value

Strictly speaking, Java is pass-by-value, but you could still to this for example (because references of objects are passed, and thus changes to an object affect the object outside of the scope of a method):

public static void swap(int[] arr, int ii, int jj) {
    int temp = arr[ii];
    arr[ii] = arr[jj];
    arr[jj] = temp;
}

And then just call it like this:

swap(arr, i, j);

The same is true for swapArr. I think writing it this way is clearer (and also shorter), but it's probably a matter of taste.

Misc

I would split initArr into two methods: one that gets the user input, and one that creates the array (that way, it's easier to get the input from different places, for example hardcoded for testing).


For your questions:

The usage of this : In my mind, unless you are using closures, do not use self = this, so only keep it in getMissions
Functions in prototype <- Good stuff
Function <> JSON, is an odd question. You want to use constructors, and those are functions.

Other than that,

You are using lowerCamelCase, that is good. Though firstname -> firstName
initialize: function( json ) does not really get a JSON string, instead it gets an object, so I would not name that parameter json
The function to deal with returned missions seems a bit clumsy, I would either assign each new mission to a variable and push it to both arrays:

function( data ){
    var missions = [], mission;
    $(data.missionList).each(function(){
        mission = new Mission(this)
        self.missions.push( mission );
        missions.push( mission );
    });
    callback( missions );
}

or, I would only push to missions and then concatenate missions into self.missions

function( data ){
    var missions = [];
    $(data.missionList).each(function(){
        missions.push(new Mission(this));
    });
    self.missions = self.missions.concat( missions );
    callback( missions );
}

All in all, nice code, very maintainable and self explanatory.


Instead of writing append two times, why don't append a single time with two different values depending on the length of searchBox?

Also, moving the trimmed search value into a variable simplifies the code a bit.

var text,
    trimmedSearch = searchBoxValue.trim();
if (searchBoxValue.length > numCharToDisplay) {
    text = '
Searching "' +
    trimmedSearch.substring(0, numCharToDisplay) +
    '..." Found No Results
';
} else {
    text = '
Searching "' +
    trimmedSearch + '" Found No Results
';
}
searchDropDown.append(text);

Using ternary operators, as you suggested, wouldn't be a good practice since it complicates things up, leaving maintenance really difficult.


OK, here it goes:

Currently all of your code is bunched up in a code block. It would be better to follow the single responsibility principle and have functions for every job.

Therefore, I used a main function, a parse_args function, a pop_connect function to login with the POP3 server, a smtp_connect function to do the same with the SMTP server, a get_mail function to retrieve a mail from the server and catch any exception and a send_mail function to encode the message and send it.

For the SMTP connection I used the with..as functionality of python. This makes sure that the SMTP connection is closed, regardless of any errors in between. Also, it is sufficient to connect to the SMTP server once and then re-use that connection, unless your latency is really bad (and in that case, just increase the timeout, which I mad an optional argument). Have a look at this website to read a more thorough explanation on how to use a contextmanager on a function.

I also made some formats slightly simpler. If the arguments are in order, it is not necessary, to use "{0}{1}".format(x, y), "{}{}".format(x, y) is sufficient. On the other hand, I also used the fact that format understands a few rudimentary things, namely indices and attributes:

>>> l = [1,2,3]
>>> "{0[1]}".format(l)
2
>>> from collections import namedtuple
>>> Box = namedtuple("Box", "width height")
>>> b = Box(2, 3)
>>> "{0.width}, {0.height}".format(b)
2, 3

Finally, I used the if __name__ == "__main__": idiom, to allow importing these functions from another module without running all the code.

import sys
import smtplib
import poplib
import re
import argparse

from contextlib import contextmanager

def validate_email_address(address):
    email_pattern = '^[^@]+@[^@]+\.[^@]+$'
    if not re.match(email_pattern, address):
        raise argparse.ArgumentTypeError(
            '{} is not a valid email address'.format(address))
    return address

def parse_args():
    arg_parser = argparse.ArgumentParser()
    arg_parser.add_argument(
        'popServer', help='pop server host or address of extracted account')
    arg_parser.add_argument(
        'smtpServer', help='smtp server host or address of extracted account')
    arg_parser.add_argument(
        'address', help='extract messages from this account', type=validate_email_address)
    arg_parser.add_argument('password', help='password of extracted account')
    arg_parser.add_argument(
        'target', help='redirect messages to this account', type=validate_email_address)
    arg_parser.add_argument('--useTSL', action='store_true')
    arg_parser.add_argument('--useSSL', action='store_true')
    arg_parser.add_argument('--timeout', type=int,
                            help="Timeout for the servers", default=10)
    return arg_parser.parse_args()

def pop_connect(server, user, password, timeout=10, use_SSL=False):
    pop = poplib.POP3_SSL if use_SSL else poplib.POP3
    pop_conn = pop(server, timeout=timeout)
    pop_conn.user(user)
    pop_conn.pass_(password)
    return pop_conn

@contextmanager
def smtp_connect(server, user, password, timeout=10, use_SSL=False, use_TSL=False):
    try:
        smtp = smtplib.SMTP_SSL if use_SSL else smtplib.SMTP
        smtp_conn = smtp(server, timeout=timeout)
        if use_TSL:
            smtp_conn.starttls()
        smtp_conn.login(user, password)
        yield smtp_conn
    except smtplib.SMTPException as SMTP_exception:
        print('Request of mail failed:{}'.format(SMTP_exception))
        raise
    finally:
        try:
            smtp_conn.quit()
        except UnboundLocalError:
            pass

def get_email(pop_conn, i):
    try:
        return pop_conn.retr(i)[1]
    except poplib.error_proto as pop_error:
        print('Receiving of mail failed:{0}'.format(pop_error))

def send_mail(smtp_conn, to_email, from_email, message):
    message = '\n'.join(line.decode(
        'utf-8', errors='ignore') for line in message)
    smtp_conn.sendmail(from_email, to_email, message.encode(
        encoding='ascii', errors='ignore'))

def main():
    args = parse_args()
    try:
        pop_conn = pop_connect(args.popServer, args.address,
                               args.password, args.timeout, args.useSSL)
        mail_count = len(pop_conn.list()[1])
        print('Mail count:{}'.format(mail_count))
        if mail_count:
            print('Requesting mails from {0.popServer} for {0.address}'.format(args))
            with smtp_connect(args.smtpServer, args.address, args.password, args.timeout, args.useSSL, args.useTSL) as smtp_conn:
                for i in range(1, mail_count + 1):
                    print("Receiving mail {}/{}".format(i, mail_count))
                    message = get_email(pop_conn, i)
                    pop_conn.dele(i)
                    print("Redirecting mail {}/{}".format(i, mail_count))
                    send_mail(smtp_conn, args.address, args.target, message)
    except poplib.error_proto as pop_error:
        print('Receiving of mail failed:{}'.format(pop_error))
    except OSError as os_error:
        print('Name resolution or server connection failed:{}'.format(os_error))

if __name__ == "__main__":
    main()


I have a few comments on this.
Don't attempt to nest templates with the same parameter
First, as you've already discovered, nested templates with the same parameter are a violation of the C++ language standard, whether or not your compiler complains.  (In fact, I would say it's broken if it does not complain.)
C++ standard, section 14.6.1:

A template-parameter shall not be redeclared within its scope (including nested scopes). A template-parameter shall not have the same name as the template name.

The definition of mUniformDistribution can be simpler
The code doesn't need a using statement.  The declaration can be made directly:
decltype(dist<T>()) mUniformDistribution;

(Also note that the existing code misspells "Uniform")
The use of Random does not require a scope
The code in main refers to ::Random but that's really not necessary here.  It should just be Random.
Consider repeatability
To answer the question in your code, yes,
std::default_random_engine mEngine{ std::random_device()() };

that line of code does seed mEngine however, I'd suggest rethinking that feature.  If you were using this random number generator for, say a simulation, you might want to be able to duplicate the simulation exactly and not simply always run it with new random numbers.  To get the best of both worlds, you could keep your existing code, but eliminate the initialization of mEngine and add it instead to the constructors:
Random(const T& min, const T& max)
    : mEngine{},
      mUniformDistribution(min, max)
{}
Random(const T& min, const T& max, bool )
    : mEngine{ std::random_device()() },
      mUniformDistribution(min, max)
{}
// ...
std::default_random_engine mEngine;

Now if you construct using the first version, you'll get the default seed each time.  If you use the second constructor (with a dummy bool parameter) it will use a new seed each time.


You don't want to test the network, the requests or json libraries, you want to check that your method calls requests with a certain parameter (to check if your string interpolation worked and used the correct arguments) and that you return the return value of the JSON method of the response (to check whether you actually used and passed through the object).

At least those are things worthy of testing.  You can simplify your code with mocks if you like them, otherwise I'd say move the class definitions so that you have proper MockRequests and MockResponse classes, maybe the requests with a response constructor argument or so.

And the classes should be as simple as possible, the check for "target" isn't necessary, just check whether the incoming URL has the correct (pre-set) value.  The response shouldn't call anything, it should just return the (again pre-set) JSON object instead.


Excel VBA to create a visual timeline of events using an XY scatter chart

Your variable names could use some tidying up-

Instead of c why not record as they are in the "Decision Record"

labelrotation should be labelRotation - Standard VBA naming conventions have camelCase for local variables and PascalCase for other variables and names.

Same goes for scount - sCount or even recordCount

Integers - integers are obsolete. According to msdn VBA silently converts all integers to long.

Be sure to avoid things like .Activate - it just slows the code down by needing to fiddle with the spreadsheet while doing everything else behind the scenes. There's a good question on StackOverflow addressing this - https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba-macros .

Dim timelineChart As Chart
    Set timelineChart = ActiveSheet.ChartObjects("chtDecisionTimeline")
    ...

        timelineChart.SeriesCollection.NewSeries
        With timelineChart.SeriesCollection(scount)

Speaking of structure, your spacing is a little off - your with block is the same level as your for block. Try pushing the loop back so alignment is correct -

Option Explicit

Sub UpdateDecisionTimelineChart()

    Dim sCount As Long
    Dim labelrotation As Long
    Dim record As Range

    Dim timelineChart As Chart
    Set timelineChart = ActiveSheet.ChartObjects("chtDecisionTimeline")
    sCount = 0
    For Each record In Range(Worksheets("Decision Record").Range("C7"), Worksheets("Decision Record").Range("C7").End(xlDown))
        sCount = sCount + 1
        timelineChart.SeriesCollection.NewSeries
        With timelineChart.SeriesCollection(sCount)
            .Name = "='Decision Record'!" & record.Offset(0, 1).Address
            .XValues = "='Decision Record'!" & record.Address
            .Values = "='Decision Record'!" & record.Offset(0, -1).Address
            .MarkerStyle = 8
            .MarkerSize = 7
            .MarkerBackgroundColor = RGB(228, 10, 56)
            .MarkerForegroundColor = -2
            .Format.Line.Visible = False
            .ApplyDataLabels
            .DataLabels.ShowValue = False
            .DataLabels.ShowSeriesName = True
            .DataLabels.Position = xlLabelPositionAbove
            .DataLabels.Orientation = -45
        End With
    Next
End Sub

The object model for the series object doesn't really specify any of the attributes' defaults, so I think your With block is pretty clean. You might want to create some variables or something like -

Dim decisionRecord As String
decisionRecord = "='Decision Record'!"

        .Name = decisionRecord & record.Offset(0, 1).Address
        .XValues = decisionRecord & record.Address
        .Values = decisionRecord & record.Offset(0, -1).Address

Your xlDown could be fixed like this -

Dim decisionRecordSheet As Worksheet
Set decisionRecordSheet = Worksheets("Decision Record")
Dim lastRow As Long
lastRow = decisionRecordSheet.Cells(Rows.Count, 3).End(xlUp).Row
Dim recordRange As Range
Set recordRange = decisionRecordSheet.Range(Cells(7, 3), Cells(lastRow, 3))
...
For Each record In recordRange

With all these variables using the sheet, why not use the CodeName - Worksheets have a CodeName property - View Properties window (F4) and the (Name) field can be used as the worksheet name. This way you can avoid Sheets("mySheet") and instead just use mySheet.

Unless you need it to be Public you should make it private

Private Sub UpdateDecisionTimelineChart()

Also, I don't see you ever using the labelRotation variable, so unless that part was removed, you don't need it.


Optimising String split into chunks of fixed size

Firstly, great implementation. Getting the maximum amount of characters for the next chunk, finding the last space in that and then using it to get the correct chunk is fast and works well.
Other ideas that spring to mind would be to split the string into words first and rebuild with a loop, but I think this would be slower.

Yes this is O(n) - the solution's speed is proportional to the amount of input passed.

Your solution is a loop, not a recursion. A recursive solution would be a function which calls itself. If you want to see this style, let me know and I can post it.

Some improvements:

You don't need to wrap the exampleTxt variable in backticks. This creates a template literal, which is unnecessary here - you can just use normal quotes.
Running the function with a 1 character string causes it to run the while loop, instead of returning early.
You can simplify the levels of nesting in the if ... else by returning early. If one of the returns is triggered then nothing after it will be run.

if (msg.length < 1) {
    return 0;
}

if (msg.length >= 1 & msg.length < 153) {
    return 1;
}

// while loop

return messages.length;

In the else if you have & (Bitwise AND) instead of && (Logical AND).
Your while loop mutates the state of the msg variable. Mutation can lead to hard to find bugs - clone the string first (remainingMsg = msg) and use that in the loop instead.
It's not necessary to have the getIndexOfLastSpace function separate. You can use something like this:

var nextChunk = msg.substring(0, 153);
nextChunk = nextChunk.substring(0, nextChunk.lastIndexOf(' '));

To make the function more reusable you could return the message chunks directly instead of the length. The user can then call .length on the returned value if that's all they want.
You could also pass the chunk length into the function as a parameter, so that it can handle chunking to any length.
If using the point above, setting some standard values as consts is a good practice.

const SMS_MESSAGE_MAX_LENGTH = 153;
// ...
getMessagesNumber(msg, SMS_MESSAGE_MAX_LENGTH);

For a higher level abstraction you could use a curryable function to create new functions with specific chunk lengths. I've used ES5 format as that's how the question was asked.

var chunk = function(chunkLength) {
    return (function splitChunks (message) {
        // ...
    });
};

var chunkSmsMessage = chunk(153);
chunkSmsMessage('Lorem ipsum...');


String de-duplication using a custom string pool

So, you want a Collection which should hold your strings. The easiest and fastest would be to simply use an array. So let us do it.

Because you are using this for pooling strings, we we only need a string[] array. We should add a method bool TryGetValue(string key, out string value) and a string Add(string value).

If we use an array we need to initialize this array to a given capacity at the constructor level and add a possibility to let the array grow if needed.

I decided to use the name you want CoolClass but it should be better named to something more meaningful.

We need to check if a given "key" is in the array at two places, the TryGetValue() and the Add() method. So let us introduce another method int IndexOf(string key) which returns the index of the given keyand if it isn't in the array it returns -1, which should be extracted to a const.

This leads to

public class CoolClass
{
    private string[] array;
    private int capacity;
    private int lastElement = -1;
    private const int elementNotFound = -1;

    public CoolClass() : this(1024) { }
    public CoolClass(int capacity)
    {
        this.capacity = capacity;
        array = new string[capacity];
    }

    public bool TryGetValue(string key, out string value)
    {
        int i;
        if ((i = IndexOf(key)) != elementNotFound)
        {
            value = array[i];
            return true;
        }

        value = null;
        return false;
    }

    public void Add(String value)
    {
        if (value != null)
        {
            int i;
            if ((i = IndexOf(value)) != elementNotFound)
            {
                lastElement++;
                if (lastElement >= capacity)
                {
                    Grow();
                }
                array[lastElement] = value;
            }
        }
    }

    private int IndexOf(string key)
    {
        for (int i = 0; i < lastElement; i++)
        {
            if (array[i] == key)
            {
                return i;
            }
        }
        return elementNotFound;
    }

    private void Grow()
    {
        capacity = capacity * 2;
        Array.Resize(ref array, capacity);

    }
}

But maybe we should think about this. Why shouldn't we rename the TryGetValue() to GetOrAdd() and remove the Add() method  ? Because we don't want to handle cases where the string isn't pooled in the client code.

public class CoolClass
{
    private string[] array;
    private int capacity;
    private int lastElement = -1;
    private const int elementNotFound = -1;

    public CoolClass() : this(1024) { }
    public CoolClass(int capacity)
    {
        this.capacity = capacity;
        array = new string[capacity];
    }

    public string GetOrAdd(string key)
    {
        if (key == null) { return null; }

        int i;
        if ((i = IndexOf(key)) != elementNotFound)
        {
            return array[i];
        }

        lastElement++;
        if (lastElement >= capacity)
        {
            Grow();
        }

        array[lastElement] = key;
        return array[lastElement];

    }

    private int IndexOf(string key)
    {
        for (int i = 0; i < lastElement; i++)
        {
            if (array[i] == key)
            {
                return i;
            }
        }
        return elementNotFound;
    }

    private void Grow()
    {
        capacity = capacity * 2;
        Array.Resize(ref array, capacity);

    }
}

You reallay should use braces {} for singleline if statements too, this won't harm but makes the code less error prone.

Also it isn't mentioned explicitly in the naming guidelines how to name internal static variables, you should use camelCase casing for naming them.

By using a guard clause like

if (string.IsNullOrEmpty(value) || value.Length > 200) { return value; }

you can return early and therefor you save horizontal spacing which improves the readability of the code.


Others have pointed out a fix you could make to your implementation.  But there is a way to write this which is much simpler.  That takes advantage of a simplified definition of palindrome: "a word which reads the same forwards and backwards".

Now I haven't done PHP in years, and don't have a test environment, so this might have issues, but the basic idea should be clear.

public static function isPalindrome($word)
{
    return $word == strrev($word);
}

Update

Based on suggestions in the comments, this would be nicer:

function isPalindrome($word) {
    $word = preg_replace('/[^a-zA-Z]/', '', $word);
    $word = strtolower($word);
    return $word == strrev($word);
}

That will now correctly identify "Level" (ignoring capitalization) and "Madam, I'm Adam." (ignoring spaces and punctuation.)


Finding min value of an array using SIMD

Correctness

  if( array.Length <= 0 )
    return 0;

This piece of code is suspicious. Maybe you should return sbyte.MaxValue, maybe null, or maybe throw ArgumentException. (I can imagine that there were a Max method, both, together is used to find the range of values, then maybe 0 is a valid return value.) This is one of the rare times I'd appreciate a comment to explain such extrinsic information.

Useless Code

 if( i < length )
      while( i < length )

Lose the if.

Excessive code

When you are operating on fixed size chunks,
 - pad the input with some appropriate value (sbyte.MaxValue)
 - handle the last fixed size chunk of the input separately.

The last suggestion should read something like this, (which means I don't even guarantee that it will compile):

if (length < stepSize)
    throw new ArgumentException($"this method cannot be used for arrays shorter than {stepSize}")

Vector128<sbyte> minVector;
SetAllVector128(minVector, sbyte.MaxValue);
for (var i = 0; i < length - stepSize; i += stepSize)
    minVector = Avx.Min(minVector, Avx.LoadVector128(pStep + i));

minVector = Avx.Min(minVector, Avx.LoadVector128(pStep + length - stepSize));

Then you can use the last loop altogether;


You should use iterators: when you use a line like this for i in 0..dest_len as isize, the compiler cannot optimize when going through the slice.

A better example:

fn read_float_vec_from_byte_vec(v: Vec<u8>) -> Result<Vec<f32>, &'static str> {
    #[inline(always)]
    fn float_from_u8_slice(s: &[u8]) -> f32 {
        let array = [s[0], s[1], s[2], s[3]];
        unsafe { std::mem::transmute(array) }
    }

    match v.len() % 4 {
        0 => Ok(v.chunks(4).map(float_from_u8_slice).collect()),
        _ => Err("Number not divisible by 4"),
    }
}

With the iteration over v.chunks(4).map(float_from_u8_slice).collect(), the code is smaller and more readable. Generally speaking, iterators are always better than indexing because indexing operation performs bounds checks.

Unfortunately, you cannot do the same with float_vec_as_byte_vec because (for now) arrays in Rust are not a first-class citizen. Due to the fact that genericity on integers does not exist, you cannot consume an array into an iterator. If it did, we could write something like:

// This code does not work currently
fn float_vec_as_byte_vec(s: &[f32]) -> Vec<u8> {
    s.iter().flat_map(|&f| unsafe { transmute::<f32, [u8; 4]>(f)).collect()
}

In this code, I accept the type &[f32], instead of &Vec<f32>. Slices are a view of memory, and that is what we want. &Vec<f32> does not really make sense, semantically.

In the first function I rewrote, I used &'static str and not String because we do not need an allocated string since it is literal.


Generic parameter class with HasChanged functionality

I'm still not sure about its usage but here's the review.

public T InitialValue
{
    get { return m_initialValue; }
}

public T UpdatedValue
{
    get { return m_updatedValue; }
}

As a user of this class I most probably don't want to think about which value I should use. I bet it'll be always the latest one so a single property like Value returning the most up-to-date value would be more appropriate.

public UpdatableParam(T initialValue, T updatedValue)
{
    m_initialValue = ObjectCopier.Clone(initialValue);
    m_updatedValue = ObjectCopier.Clone(updatedValue);
}

Initializing the class already with an updated-value is somehow counterintuitive to me. Why would I want to do that? I thought it should track changes and not be created in a changed state already.

public UpdatableParam(T initialValue)
{
    m_initialValue = ObjectCopier.Clone(initialValue);
    m_updatedValue = ObjectCopier.Clone(initialValue);
}

I don't want to update the value. I just want to set a new one via the Value property. The object tracking it should be able to figure out what's going on which leads me to the next point:

public virtual bool HasChanged()
{
    return !EqualityComparer<T>.Default.Equals(m_initialValue, m_updatedValue);
}

This should a property, usulay like IsDirty.

With all suggestions applied I could imagine the new clean object could be implemented like this:

public class TrackingValue<T>
{
    private readonly T _initialValue;
    private T _newValue;

    public TrackingValue(T initialValue)
    {
        _initialValue = ObjectCopier.Clone(initialValue);
        _newValue = _initialValue; // No cloning, it's the same value.
    }

    public T Value
    {
        get => IsDirty ? _newValue : _initialValue;
        set => _newValue = ObjectCopier.Clone(value);
    }

    public virtual bool IsDirty => !EqualityComparer<T>.Default.Equals(_initialValue, _newValue);

    public static implicit operator T(TrackingValue<T> value) => value.Value;
}

Additionally I want to be able to use the value without effort thus the implicit cast operator so that I can put the wrapper where I usually use the actual value and the compile will figure out the rest.


The structure looks fine. It is quite succinct and makes good use of const and let where appropriate.

To adhere to the D.R.Y. principle, process() can and should utilize remove() to remove items from the queue.

I considered suggesting that arguments be accepted with each function but that can be achieved with partially bound functions.

I also considered suggesting you consider using a class, since ES-6 featured can be utilized, but then you would either need to instantiate a queue once or else make all methods static.

I would suggest you consider accepting an error handler callback for each function. That way, instead of writing all errors to the console, the caller could add an appropriate handler.


Comments inline:

public class Parser
{
    public static void Main()
    {
        Console.WriteLine("Enter the url of the page:");
        var url = Console.ReadLine();

        var numOfPages = GetNumberOfPages(url);
        var numOfLinks = 1;

        for (int page = 0; page <= numOfPages; page++)
        {
            // if (page != 1) is redundant in the original code, did you mean numOfPages?
            var newUrl = url + (page > 0 ? string.Format($"{page}/") : "");
            GetYouTubeLinks(newUrl).ForEach(x => Console.WriteLine($"{numOfLinks++}." +
                x.Replace("embed/", "watch?v=").Replace("?feature=oembed", "")));   // remove string interpolation since it's just one value
            // newUrl = string.Empty;       // Not needed
        }
    }

    private static HtmlDocument GetWebPageHtmlFromUrl(string url)
    {
        var webGet = new HtmlWeb();

        return webGet.Load(url);
    }

    private static int GetNumberOfPages(string url)
    {
        var pages = GetWebPageHtmlFromUrl(url)
            .DocumentNode.SelectNodes("//div[@class='page-link']")  // This parsing may work on specific pages, but it won't work on all pages. This is concerning since the user is prompted to enter any URL?
            .Descendants("a")
            .Last().InnerText;

        return int.Parse(pages);
    }

    private static List<string> GetYouTubeLinks(string url)     // Made plural
    {
        var iframeLinks = GetWebPageHtmlFromUrl(url).DocumentNode.SelectNodes("//iframe");

        if (iframeLinks == null)    // reduce nesting
        {
            return new List<string>(0);
        }

        return iframeLinks.Select(link => link.Attributes["src"].Value).ToList();   // simplify allocation
    }
}


Switching from functional jQuery code to object-oriented

Your mistake is in your processInput() function, it is not created as part of the search object and is invalid syntax the way you have it written.

I try to avoid private functions in javascript as it makes them difficult to test, but if you really wanted to have private functions, you could write your module like this:

var AutoSearch = (function () {
    "use strict";

    // private
    var my = {},
        input;

    // private
    function processInput() {
        alert(input.val());
    }

    // private
    function bindEvents() {
        input.on('keyup', processInput());
    }

    // public
    my.init = function (options) {
        input = options.input;
        bindEvents();
    };

    return my;
}());

It's not obvious to me that you need jQuery or .proxy() at this point, since all the data and functions for the event handler are inside the closure.


Design

This sort of design isn't necessarily a bad thing, but in this example it's making things a lot more complicated, without providing any benefits:

ChangeLight suggests that null is not a valid state, but your TrafficLight class does not prevent its state from being initialized or set to null.
It's possible to create classes that inherit from State or one of your other state classes. This essentially means that there are an infinite number of possible states (PurpleState, RandomState, SchrodingerCatState, ...). That makes it unclear how exactly your traffic light is meant to be used.
Those state classes don't contain any actual state - it's only their type (and functionality) that matters. In that case, you might as well create static instances that can be reused. And because they all contain essentially the same logic (just different values), you don't really need separate classes either.
Methods like AllowTraffic and StopTraffic(TimeSpan delay) are probably more useful than a ChangeLight method that doesn't say anything about what the next state will be. But supporting such methods with logic inside those state classes alone is cumbersome.

Using a simple enum instead makes things a lot easier: there's no null to worry about and it's immediately clear what all the possible states are. The light-changing logic is fairly simple, so that can easily be kept in TrafficLight itself.

Further considerations

Different countries use different light patterns, and traffic lights may have different modes (such as daylight versus night, or an error state). In other words: red is not always followed by green - in some countries there's an orange-red state in-between, in some modes a light is flashing red continually, and so on.

With such requirements, the current light doesn't tell us everything about the traffic light's internal state. It would be more useful to treat each pattern as a different state. But even then I wouldn't create separate state classes with their own logic: a single data-driven class and some state-tracking logic inside TrafficLight itself should be sufficient.

Other notes

That Console.WriteLine is obviously some left-over test code, but be careful not to leave it lingering around. There's no reason why this code should depend on the presence of a console. If you're using Visual Studio, you may want to use tracepoints instead (breakpoints with a logging action). They're more flexible and don't clutter the code.
Comments like // Gets or sets the state are of no use: they're just stating the obvious, and they can only cause confusion when they become out-of-date.
State is a very generic name - TrafficLightState or TrafficLightColor may be more appropriate here.


The Next Palindrome: Is my code efficient?

Cache cache cache! :) All those substrings you take should be stored in variables, rather than using the expensive substring methods. Furthermore, comparing strings can also be expensive. When you store the substring in a variable, you could parse the integer and keep it for comparisons later.

Advanced:

Since you never need to look at the last half number (if it's a palindrome it must be the reverse of the first digits), you can just store two variables: big_half and small_half. for even-digit numbers, they will be equal, but for odd-digit numbers big_half will have the middle digit. This makes creating a that is adjacent to the number (either just smaller or just larger) as simple as big_half + small_half.reverse. If a test shows it's the smaller one, increment big_half and generate a new small_half from it, then add together as above.


Replicating C#-style events in Java using reflection

ArrayList<Method> Methods;
    ArrayList<Object> DeclaringClasses;

Two things: firstly, you're using C# naming conventions rather than Java. Secondly, code to the interface: the fields should be List<XYZ> rather than ArrayList<XYZ>.

    public boolean AddListener(Object Class, String MethodName)

Class isn't an obvious name for something which isn't a class. And given that you're using java.lang.Class inside the method without fully qualifying the name, it has even more potential to confuse.

            Method MTR = Class.getClass().getMethod(MethodName, Object.class, Object.class); // MTR = Method To Register.

If you have to add a comment explaining the name, perhaps you chose the wrong name? What's wrong with Method method = ...?

            if(Methods.contains(MTR))
                return false;

So I can't have the event notify two different objects of the same class?

    public boolean RemoveListener(Object Class, String MethodName)
    {
        try
        {
            DeclaringClasses.remove(Class);
            return Methods.remove(Class.getClass().getMethod(MethodName, Object.class, Object.class));
        }

Buggy. Collection.remove removes one instance of the object, but you're making no attempt to ensure it's the right one. If I register two methods on the same object, this could remove the wrong instance of the object, which would then make objects and methods not line up correctly.

In fact, it's even worse than that: if I register a method on one object and then remove it on another, or register one method on an object and then remove a different one, I'll end up with Methods and DeclaringClasses not even being the same size.

Also, why would you want to call getMethod again unless the method hasn't been registered? If the method has been registered, you've already resolved it; if it hasn't, you don't need to resolve it except to check for typos.

The best way to store the resolved methods is probably Map<Tuple<Object, String>, Method>: that allows you to iterate through the entry set in the Raise method and to efficiently implement RemoveListener.

            catch(IllegalAccessException error)
            { }

No. Swallowing exceptions like that is bad, especially when you've done nothing to prevent them occurring. You should check in AddListener whether the method is accessible, and throw an exception there if it isn't. Then here you should log an error for debugging purposes.

Other issues to consider:

Thread-safety. This has no thread-safety whatsoever.
Typing. If you're going to emulate C#'s events then don't just emulate the ungenericised EventHandler. At the very least, emulate EventHandler<T>. Because Java's generics aren't reified this requires a bit of boilerplate:

public class Event<T>
{
    private final Class<T> typeParam;

    public Event(Class<T> typeParam)
    {
        this.typeParam = typeParam;
    }

You can now use typeParam in the Class.getMethod call.


Making JSON requests to fetch relationships asynchronously

First, I would get that error check out of the way instead of in the middle of the operation. Just throw an error in the middle of the operation and let the catch handle the dispatch.

Also, fetch will always resolve. A common procedure is to use the very first then to evaluate the response and determine how the sequence proceeds. It's usually either resolving with the data or rejecting with the error. But in your case, since both success and error actions dispatch body, the only difference is the action creator. Instead of a resolution/rejection, we just resolve with the correct action based on ok.

export const fetchRelationships = url => {
  return async dispatch => {
    dispatch(fetchRelationshipsRequest())

    fetch(url, config)
      .then(res =>
        // We cannot return res.json() and do its then as part of the
        // outer sequence since we need res. This needs to nest.
        res.json().then(body =>
          res.ok ? fetchRelationshipsSuccess(body) : fetchRelationshipsError(body)))
      .then(action => dispatch(action))
      .catch((error) => dispatch(genericErrorAction())
  }
}

Now for async-await. The returned anonymous function from fetchRelationships will have to be async in order for its body to be able to use await. All promise-returning functions will need to use await. And then turn everything into synchronous-looking code. Here's the same procedure as above, but in async-await form.

export const fetchRelationships = url => {
  return dispatch => {
    dispatch(fetchRelationshipsRequest())

    try {
      const res = await fetch(url, config)
      const body = await res.json()
      const action = res.ok ? fetchRelationshipsSuccess(body) : fetchRelationshipsError(body)
      dispatch(action)
    } catch(error){
      dispatch(genericErrorAction())
    }
  }
}


Efficient way to remove duplicate records

I would use the ROW_NUMBER windowing function to identify the duplicates and delete those.

Given something like the following:

CREATE TABLE tbl
(
   v1 VARCHAR2(10)
  ,v2 VARCHAR2(10)
);

INSERT ALL
  INTO tbl (v1, v2) VALUES ('A','A')
  INTO tbl (v1, v2) VALUES ('A','A')
  INTO tbl (v1, v2) VALUES ('A','Z')
  INTO tbl (v1, v2) VALUES ('B','B')
  INTO tbl (v1, v2) VALUES ('B','B')
  INTO tbl (v1, v2) VALUES ('B','B')
  INTO tbl (v1, v2) VALUES ('C','B')
  INTO tbl (v1, v2) VALUES ('C','B')
  INTO tbl (v1, v2) VALUES ('keep', 'keep')
SELECT * FROM dual
;

I would do something like the following:

DELETE
  FROM tbl
  WHERE ROWID IN (
    SELECT id
    FROM (
      SELECT
         ROWID AS id
        ,ROW_NUMBER() OVER (PARTITION BY v1, v2 ORDER BY ROWID) AS rnum
      FROM tbl
    )
    WHERE rnum <> 1
  )
;

I wrote a blog post about this using SQL Server but the idea is the same on Oracle.

This blog post claims that using ROW_NUMBER for deleting duplicates is very fast in Oracle (my experience in SQL Server would lead me to believe the claim).

Never under estimate the power of windowing functions.


Best way to pass a 2d array to functions which size is unknown at compile time in pure C

Type-wise, it is ok to go from void pointers to array pointers and back. As long as the "effective type" is an int array of the specified size. Void pointers do however have non-existent type safety, so they should be avoided for that reason.

The best way is rather to use an array and let the compiler "adjust" it to an array pointer between the lines:

void fill (size_t rows, size_t cols, int arr[rows][cols], int val);

The VLA syntax requires that rows and cols exist, so arr must be declared on the right side of them in the parameter list. Please note that this is still a pointer and not a whole VLA passed by value - we can't pass arrays by value in C.

Fixed example:

#include <stdio.h>

void fill(size_t rows, size_t cols, int arr[rows][cols], int val);
void print(size_t rows, size_t cols, int arr[rows][cols]);

int main(void) {
  size_t iArr = 5, jArr = 3;
  int arr[iArr][jArr];
  fill(iArr, jArr, arr, 0x45);
  print(iArr, jArr, arr);
  return 0;
}

void fill(size_t rows, size_t cols, int arr[rows][cols], int val)
{
  for(size_t i = 0; i < rows; i++)
  {
    for(size_t j = 0; j < cols; j++)
    {
      arr[i][j] = val;
    }
  }
}

void print(size_t rows, size_t cols, int arr[rows][cols])
{
  for(size_t i = 0; i < rows; i++)
  {
    for(size_t j = 0; j < cols; j++)
    {
      printf("%3d ", arr[i][j]);
    }
    putchar('\n');
  }
}


Utilizing std::map and std::array for displaying a modulus grid

main() can be defined lastly, so that the function prototypes can be removed.  This will also allow NUM_ARR_ELEMS to be initialized within main().  The size of either the inner or outer structure can still be accessed via size().
For simple input like this, a command line argument is another option:

int main(int argc, char *argv[])
{
    unsigned int mod;

    // only argument being the file name
    if (argc < 2)
    {
        std::cin << mod;
    }
    // more than the file name, where only the second is used
    else
    {
        mod = std::atoi(argv[1]);
    }
}

Warning: std::atoi() returns an int, but mod is an unsigned int.  As this is a mismatch (and should be reported by the compiler), something else should be changed.  Either the return value of std::atoi() should be cast to an unsigned int, or mod should just be changed to an int (and adjusted elsewhere).  The latter may be a better option here, and the extra unsigned bit really isn't important.  Input validation (to avoid a negative value) can be done as well.
This type is quite long to copy in different places:

std::map<unsigned, std::array<unsigned, NUM_ARR_ELEMS>>

so it can become a typedef:

typedef std::map<unsigned, std::array<unsigned, NUM_ARR_ELEMS>> Grid;

Prefer "\n" over std::endl for just a newline.  The latter also flushes the buffer.