For beginner code, this is quite good. I am impressed. Good enough for me to assume you have worked from some example code. That is not a criticism, everyone does that (me too).
Still, many examples are based on other examples, and they have some issues that are 'historical' in nature, and then there are some practices in Java which make sense which are not visible in your code.
Style
Really, it's good, no big problems.
There is an extra empty-line in the middle of your if/else/else statement which is inconsistent. If I were to be extremely nit-picky, I would say that I personally would not put the empty line after the return statement (but like you I also would put one before the statement).
Order of comparison.... I am not sure why I dislike this one, and I have no reference for it, but, you have the line:

} else if (arr[mid] < search) {

and I would strongly prefer it to be:
} else if (search > arr[mid]) {

'Finally', the arr and search parameters to your method are constants, and are not changed. You should show this by adding 'final' to the declaration:
final int[] arr, ...., final int search

Mid Point Bug
There is a 'famous' bug in your code.
Basically, for large arrays, you risk overflowing the calculation. Your code should be:
int mid = start + (end - start) / 2;

Generalized search
In Java it is common practice to have a general method that will search in any sub-part of the array. Then, there should also be a version which searches the whole array.
Your method is unusual because it does neither..... it searches sub array sections, but only from the beginning (it has a size argument...). Your method should look like:
public int binarySearch(int[] arr, int start, int length, int search) {
    int end = start + length - 1;

In addition, you should have the 'simplified search everything method' that looks like:
public int binarySearch(int[] arr, int search) {
    return binarySearch(arr, 0, arr.length, search);
}

Input Validation
It is common in Java to validate the inputs. You should have this as your first lines:
if (start < 0 || start >= arr.length) {
    throw new IllegalArgumentException("Invalid start index " + start + " in array of size " + arr.length);
}

if (length < 0 || start + length > arr.length) {
    throw new IllegalArgumentException("Invalid length " + length + " in array of size " + arr.length + " and start from " + start);
}

Redundant else
You have the following code:

    if (arr[mid] == search) {
        return mid;
    } else if (arr[mid] < search) {
        end = mid - 1;

    } else {
        start = mid + 1;
    }

Because the first part has return mid;, there is no need for it to be an else afterwards:
    if (arr[mid] == search) {
        return mid;
    }

    if (arr[mid] < search) {
        end = mid - 1;

    } else {
        start = mid + 1;
    }

A return statement inside an if block means that the block will never complete normally. This is considered to be good practice in Java (both having 'early returns' and also removing the else when you have an early return).
Insertion Point
One of the features of Java's library functions for binary search (and what many people find complicated) is the "insertion point". This is a 'clever' way for the method to say: Well, I could not find the value when I searched, but, if it as here, it would need to go at position x.
So, in a small array [1, 3, 5], if we were to search for 2, it is not there, but, if it were to be inserted, it would be at position 1 (where the 3 is now). How has java 'standardised' for showing you this?
It returns a negative value for when the value is not found. It would be 'nice' if it could return just -1 if the value was not found but should be inserted at position +1. Unfortunately, if the value should be inserted at position 0, then it can't return -0, so, it has to take the negative of the insertion point, and then subtract 1. So, an insertion point of 0 becomes -1, an insertion point of 1 becomes -2, and so on.
This is actually really easy to implement (even if it is hard to understand sometimes).
In your code, you just need to change the line:

return -1;

to be:
return -start - 1

Result
Putting all the above together, I would have your function as:
public int binarySearch(final int[] arr, int start, final int length, final int search) {
    if (start < 0 || start >= arr.length) {
        throw new IllegalArgumentException("Invalid start index " + start + " in array of size " + arr.length);
    }

    if (length < 0 || start + length > arr.length) {
        throw new IllegalArgumentException("Invalid length " + length + " in array of size " + arr.length + " and start from " + start);
    }

    int end = start + length - 1;

    while (start <= end) {
        int mid = start + (end - start) / 2;
        if (arr[mid] == search) {
            return mid;
        }
        if (search > arr[mid]) {
            end = mid - 1;
        } else {
            start = mid + 1;
        }
    }

    return -start - 1;
}


Generate random and unique array of int values for a given size

While your code looks right, there are two concerns I have with it.

The first is the somewhat arbitrary use of desiredSize * 3 as the limit of the random numbers. Why that value?

The performance issue you have is the nested looping you have first to generate the values, and then inside you loop again to check for duplicates. You can reduce the inner loop significantly by using a Set in combination with the array to check for uniqueness. The set will consume more memory, but it will allow a check without any looping (it will reduce your \$O(n^2)\$ algorithm to \$O(n)\$).

The code would look something like:

public static int[] generateRandAndUniqSet(int desiredSize) {
    int[] arrayResult = new int[desiredSize];
    Set<Integer> uniq = new HashSet<>();
    Random rand = new Random();
    int counter = 0;
    while (counter < desiredSize) {
        int randValue = rand.nextInt(desiredSize*3);/* a larger interval! */
        if (uniq.add(randValue)) {
            arrayResult[counter++] = randValue;
        }
    }
    return arrayResult;
}

That Set change will have a significant impact on your performance.... but, is there a better way?

Assuming your limit of desiredSize * 3 and assuming a relatively small dataset (less than a million, or so), then a better option would be for you to:

create an array of size desiredSize * 3
populate it with consecutive numbers [0, 1, 2, 3, 4, ....., desiredsize * 3 - 1]
shuffle it using a Fisher-Yates shuffle.
return the first desiredSize elements from the shuffled array.

This would require no duplicate-checking at all.

I put together some code to demonstrate this:

public static final int[] generateRandAndUniqRGL(int desiredSize) {

    // generate set of sequential values from 0 ... desiredSize * 3
    int[] set = IntStream.range(0,  desiredSize * 3).toArray();

    // shuffle them
    int index = set.length;
    // Fisher-Yates.
    Random rand = new Random();
    while (index > 1) {
        final int pos = rand.nextInt(index--);
        final int tmp = set[pos];
        set[pos] = set[index];
        set[index] = tmp;
    }

    // return the first batch of them
    return Arrays.copyOf(set, desiredSize);
}

I timed this method against yours for a few sizes of data here in ideone: https://ideone.com/MrwWLV

Note the timing results:

OP function for 10 input took  0.012ms
RL function for 10 input took  0.016ms
OP function for 100 input took  0.054ms
RL function for 100 input took  0.032ms
OP function for 1000 input took  3.896ms
RL function for 1000 input took  0.603ms
OP function for 10000 input took 164.937ms
RL function for 10000 input took  1.750ms


Reverse Polish Notation calculator in Python

In Python, list is designed to grow efficiently from the end. Implementing a stack using append and pop at the end is therefore a better approach.
I would expect is_number to return False instead of the implicit None which usually stands for a missing value.
An explicit math. in front of functions makes clear where they come from. If you want to support more functions you have other things to worry about. For example, the forced conversion from degrees to radians only makes sense with certain functions.
You need to store explicitly the number of arguments each operator expects. Your current solution is to infer that from the length of the operator's name. That is not an extensible approach.


Skeleton for a command-line tool to scan domains for vulnerabilities

Validation logic

When checking whether the program should print the usage message or not,
I find it an unusual approach to say "is the state (of initial parameter values) unchanged?"
It would be more natural to check facts more directly.
For example in this program the only input you really require is one or more domain names.
Then that should be the determining factor for displaying the usage message: "did the user specify a domain name?"
Direct, straightforward, to the point.

Naming

The current names are not very intuitive:

State is state of what? It's the command line parameters. Something like CmdParams would be better.
Banner is a noun, so it sounds like an object, not something that takes some action. PrintBanner would be better.
Names starting with capital letters are exported (~ public API) in go. Many if not all names in the posted could be private, so their names should start with lowercase.
Instead of InitX, when creating a new instance of X, the name NewX is more common.

Performance

Every time you evaluate s == InitState(), InitState() creates a new instance to perform the comparison. It would be enough to have just one such instance as a frame of reference, created as a var at top-level scope, no need to create a new instance every time.

Style

Many of the functions specify a name for the returned value, but don't actually use it in the function body. So those optional names can be dropped.

Instead of this:

return State { "", "", "", "", false, 20, false, false, false }

You could take advantage of the default zero-values of strings and booleans, and write simpler like this:

return State{Threads: 20}

In my experience, negative boolean variables such as NoColour are often confusing in practice.
Inverting the meaning and using !Colour tends to work better.

Use short boolean conditions

Instead of if state.Silent != true, you can write shorter as if !state.Silent.

Banner printed twice

When the script is called without parameters,
the banner will be printed twice.
Swap these two statements to avoid that.

if state.Silent != true {
    Banner()
}

if libprojectstart.IsUnchanged(*state) || state.Usage {
    Banner()
    flag.PrintDefaults()
    os.Exit(1)
}


Custom timer code needs reviewing for thread safety

System.Threading.Thread.Sleep() has an accuracy (resolution) of around 15 milliseconds, and so I would stay far away from using that in your code if you need millisecond accuracy. Can you use Stopwatch instead? - this uses a high resolution timer where available, by default. You might find this post on StackOverflow here useful as well.


What you're doing here, essentially, is creating two Model items for each item in your source list, and storing them in a list. Here's a somewhat contrived usage of the SelectMany LINQ function which flattens a hierarchical list:

drawDates
  .Select(dd => new SoonestDrawDateModel[2]  // create a 2-item array for each item.
                 {
                   new SoonestDrawDateModel
                    {
                      DrawDay = item,
                      DrawDayId = item.drawDayId,
                      CutOffDayId = item.CutOffDayId
                    },
                   new SoonestDrawDateModel
                    {
                      DrawDay = item,
                      DrawDayId = item.drawDayId + 7,
                      CutOffDayId = item.CutOffDayId
                    }
                }) // end of Select method.
 .SelectMany(items => items) // flatten collection of arrays into one collection.
 .OrderBy(x => x.DrawDayId); // order by.
 .ToList() //convert to a List<SoonestDrawDateModel>.

What we're doing here is creating a 2-item array or each Draw item, meaning we have an IEnumerable<SoonestDrawDateModel[]>, then use SelectMany to take all the members of each SoonestDrawDateModel[] and flatten them into one big IEnuemrable<SoonestDrawDateModel>, which we then sort and return.

You can simplify the syntax by extracting the main creation block into a method:

private SoonestDrawDateModel[] CreateDateModelPair(DrawItem item)
{
    return new SoonestDrawDateModel[2]
    {
     new SoonestDrawDateModel
     {
        DrawDay = item,
        DrawDayId = item.drawDayId,
        CutOffDayId = item.CutOffDayId
     },
     new SoonestDrawDateModel
     {
        DrawDay = item,
        DrawDayId = item.drawDayId + 7,
        CutOffDayId = item.CutOffDayId
     }
  }
}

then call it with this LINQ call that conveys the intent rather well:

drawDates
  .Select(CreateDateModelPair)
  .SelectMany (dateModels => dateModels)
  .OrderBy (dateModel => dateModel.DrawDayId)
  .ToList();

Or, as @anaximander suggests, an even terser (but less explicit) version that combines the Select and SelectMany calls. It saves a step, but it's less clear that we have two things going on - one to convert the DrawDate to two SoonestDrawDateModels, and another to flatten that list of lists.

drawDates
  .SelectMany (CreateDateModelPair)
  .OrderBy (dateModel => dateModel.DrawDayId)
  .ToList();


Hackerrank: "Cut the sticks" Javascript solution

Once the array is sorted, as you have it, the crux of this algorithm is simply:

subtract the smallest element from every element, then remove elements that equal 0

With es6 and method chaining, this can be expressed in a single line of code.  The rest is just the boilerplate and a condition to check when the recursion is finished -- all similar to what you have now.

Here's the rewrite:

function main() {
  readLine();
  const input = readLine().split(' ').map(Number).sort((a,b) => a-b );
  cut(input);

  function cut(arr) {
    if (!arr.length) return;
    console.log(arr.length);
    cut(arr.map(x => x - arr[0]).filter(x => x > 0)); // <-- the essence of the algorithm
  }
}

I should also point out that the above, as well as your solution, runs in \$O(n^2)\$.  You can in fact do better: \$O(n\log n)\$.  Because after the array is sorted, you can solve the problem with a single pass through the array, as follows:

function main() {
  readLine();
  const input = readLine().split(' ').map(Number).sort((a,b) => a-b );
  cut(input, input[0]);

  function cut(arr, min) {
    if (!arr.length) return;
    console.log(arr.length);
    while(arr[0] == min) arr.shift();
    cut(arr, arr[0]);
  }
}

Here we're taking advantage of the fact that after each cut, the elements that are removed are precisely those equal to the minimum element.  And to produce the output required for the problem, we notice that we don't actually have to do the cuts for every element of the list.  We merely have to remove the elements of 0 length.


Count the occurence of nucleobases in DNA string

Your code is fine and readable from a C/Java perspective. I don't think it's particularly Ruby-ic to use return statements. Just put list at the end on its own.

Why your case is slow

You have this extra puts here:

str.scan(/A|C|G|T/) do |sub|
  puts case sub
  ^^^^
  when "A"
     ...

You may want to get rid of that :) That's why you interpreter prints the list every time. You told it to...

Functionally better

But functionally, we can do way better. Ruby's enumerables have a group_by method:

def countACGT(str)
    str.chars.group_by(&:chr)
end

That'll give you a hash from each key (nucleotide base) to the values in the collection (a list of each occurence of each nucleotide base). All you have to do then is map it to just give you the size:

def countACGT(str)
    str.chars.group_by(&:chr).map { |k, v| [k, v.size] }
end

That'll give you, for your example, the list:

[["T", 228], ["C", 209], ["A", 214], ["G", 220]]

If you want to get it in ACGT order like your original, you can just sort it and map off the key:

def countACGT(str)
    str.chars.group_by(&:chr).sort.map{|k, v| v.size}
end


A regex in Java. Latin letters, digits, dots, and minus signs

That regex does not meet the requirements of your rules... so ... No, it is not OK.

The missing aspect is that the regex requires at least two characters, but the rules say one char is OK.

Also, I don't like that the last group has the + on it. While it is accurate in the sense that the last characters can be alpha/digit, it implies that the rule is for more than just the last character.

Another problem is that you allow logins of more than 20 characters.

A more meaningful/accurate regex would be:

^[a-z]([a-z\\d\\.\\-]{0,18}[a-z\\d])?$

Which requires 1 character, and then up to 18 'broad' characters followed by a constrained alpha/digit character.

EDIT:
2 things:

Aseem has rightly pointed out that the preceding if-condition essentially makes the {0,18} limit redundant. My preference is to keep it there for clarity, but, it does create duplication of logic which may lead to bugs later (How did I miss that the lenght is checked first... hmmm). Your call as to whether you should replace the {0,18} with just {*}.
The Pattern should be made static. There is no reason to re-compile the pattern for every call to the method (Patterns are thread-safe):

private static final Pattern pattern = Pattern.compile(
        "^[a-z]([a-z\\d\\.\\-]{0,18}[a-z\\d])?$", Pattern.CASE_INSENSITIVE);

private static final int maxLength = 20;

boolean checkLogin(String login) {

    if (login == null || login.isEmpty() || login.length() > maxLength) {
        return false;
    }

    return pattern.matcher(login).matches();
}


One function two functionalities or two functions each with one functionality

This would be better if you could post a real extract of the four layers and the real proposed C replacement code rather than pseudocode.

But you might also consider why software four levels up from the hardware even knows about the names of registers and the polarity of signals at pin level. In other words, the upper level might know that it wants to turn on the "bit-digester" (or some such), but only the driver (ie. lower) layer needs to know which register/bit/level that involves.  That is just my general feeling without knowing any details of your project - of course there might be good reasons for this information to propagate upwards in your application, but it needs to be strong reason to propagate very far...

EDIT after OP updated question

There are always many ways to do these things and my guess is that someone senior set down this arrangement and will be unimpressed by you suggesting it should be changed.

However, that doesn't mean you shouldn't try :-)  I can think of a number of approaches:

What you currently have.  This has the advantage of being simple to understand, but is verbose and involves many conditionals.
What others have suggested, namely passing the 'value' straight through without the conditionals.  This would be more efficient but effectively extends a dependency from the hardware level all the way up through these layers.  The dependency is hidden because the values passed are just assumed to be all the same - 1 on, 0 off.  But it is a dependency all the same and so I don't subscribe to this option.
Use a translation at each level that doesn't involve a conditional.  For example in component_deviceA_set

#define COMPONENT_DEVICE_A_MASK    0x1
void component_deviceA_set(U8BIT value)
{
    static const U8BIT level[] = {IO_INACTIVE, IO_ACTIVE};
    const U8BIT output = level[value & COMPONENT_DEVICE_A_MASK];
    io_outputDriver_setOutput(DEVICE_PIN_A, output);
}

When I try this, I get significantly less code and no conditional as long as the compiler cannot inline the call to io_outputDriver_setOutput.  If the compiler can inline that function, it recreates the conditional (looking in the assembler on x86).

So this approach is probably faster than what you have, and the level[] array need not be repeated for every such function.  But on the downside it involves an extra #define and becomes more complicated if there are cases where there are, say, 3 options instead of 2 (ie. what to do about the invalid 4th option covered by a mask of 0x11).
Use the functional approach you suggest.  This leads to  even simpler code than (3) and in my mind gives the nicest result.  It does lead to a doubling of the number of functions but they are all trivial and take no parameters. The noisy #defines (COMPONENT_DEVICE_B_ON, etc) disappear, which is nice.

So (4) looks like the nicest option to me.

Note that if the compiler can see the guts of all of these functions it might be able to optimise away the conditional in option (1).  But I expect they are in different files, so that will not happen.

Note also that using U8BIT instead of int gains nothing and in fact probably makes the code slightly slower, because the compiler will insert byte-to-long sign extensions when passing them around.   These U8BIT parameters are also dishonest, because the value parameters  don't contain a 'bit', they contain a logical on/off state (or conceivably an on/off/standby etc); yes that in general does come down to a bit at the lower level, but the upper level has no business knowing that.  As far as the upper level is concerned it is just turning something on and whether that involves setting one or a hundred bits is not its concern.

Note also that these U8BIT parameters cause warnings in my compiler ("passing argument 1 of 'io_outputDriver_setOutput' with different width due to prototype") due to my default warning settings


Yet another lightweight Enum for Python 2.7

An interesting bit of code.  :)

The downsides would be the things missing from enum341:

printing a variable gives no indication that it's an enum and not a string
enums that have the same value will compare equal
depending on the value of the member, is won't always work
etc.

Plus the surprise other developers will have when your enum doesn't work like the now-standard Python Enum2.

On the bright side, you shouldn't have any problems with pickling.

1 Disclosure:  I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum)  library.

2 See this answer for the standard Enum usage.


First of all, make attention - your code twice convert and check value. Suppose it's not efficient. Another tiny problem - 1280 and 1500 values is not change prefs.mtuSize…

My code:

class MainActivity : AppCompatActivity() {
    val TAG = MainActivity::class.simpleName.toString()

    private val defaultSize = 1500
    private var prefsMtuSize: Int = defaultSize

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val textMTU = findViewById<EditText>(R.id.textMTU)

        // Extension function
        textMTU.addTextChangedListener { text ->
            val textToInt = try { text.toInt() } catch (e: NumberFormatException) { 0 }
            if (textToInt in 1280..1500) { // 1280 <= textToInt <= 1500
                textMTU.error = null
                prefsMtuSize = textToInt
            } else {
                textMTU.error = getString(R.string.errorTroubleshoot)
                prefsMtuSize = defaultSize
            }
            Log.i(TAG, "prefsMtuSize = $prefsMtuSize")
        }
    }
}

private fun EditText.addTextChangedListener(testFunction: (text: String) -> Unit) {
    addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {
            testFunction(s.toString())
        }
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { }
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { }
    })
}


Is my C style good? 100 line timer program

Compiler Warnings

Firstly, always enable maximum warning settings for your compiler, it will catch things that you miss. For example, with gcc -Wall -Wextra, the following is produced:

  timer.c:20:5: warning: first argument of 'main' should be 'int' [-Wmain]

  timer.c: In function 'main':
  timer.c:20:22: warning: unused parameter 'argc' [-Wunused-parameter]
  timer.c:20:34: warning: unused parameter 'argv' [-Wunused-parameter]

  timer.c: In function 'printTime':
  timer.c:92:21: warning: format '%u' expects argument of type 'unsigned int', but argument 2 has type 'long unsigned int' [-Wformat]

Nothing major, which is good, but we can fix some of these up. Firstly, as it says, main should have signature:

int main (int argc, char* argv[])

not the current signature of

int main(const char argc, char* argv[])

The next warnings complain about unused parameters of argc and argv. If you aren't going to utilize command line arguments in your program, you can simply leave them out:

int main()

Fixing the printf warning is a simple matter of replacing the %u\n with %lu\n.

Code Style

Generally, there is too much whitespace. Very few programmers use 8 space indentation - I'd recommend sticking to 4. Also, leaving a space between method declarations and the trailing semicolon is slightly odd - char getChar() ;. None of this is wrong, it's just unorthodox, and will probably be a bit jarring to most C programmers (and programmers are a picky bunch). Pretty much the first thing I did with your code is modify the indentation and remove any whitespace for trailing semicolons.

Never, ever #define a type. Utilize typedef instead. This also means types should not be ALL_CAPS.

typedef unsigned long time_type;

There are very good reasons for this. For example, if we define a pointer type:

#define ptr_int int *

Now, what happens if we do the following:

ptr_int x, y;

The preprocessor will expand this to:

int *x, y; //Uh-oh!

This is declaring a pointer to integer (x) and a normal integer (y). This is sure to introduce annoying and hard to track down bugs. If instead we used a typedef, this will fix the above problem (although it shows you one must be careful when having more than declaration per line).

Comments are sparse (then again, this program probably doesn't really need them). However, you've fallen into the "obvious comment" trap:

/* Basic declarations */
/* Assigning crap, reassigning remaining seconds to 'time' */
/* Days */

and so on. None of these is really helpful. We can see that up the top the basic declarations happen, and that then some assignment takes place. The variable names of days, minutes and seconds are descriptive enough that they make the comments superfluous.

Other Quibbles

getChar actually returns an int. Pretty much anywhere you have a char, you should replace it with an int:

int getChar()
{
    int retVal = -1;
    int trashVal = -1;
    ...
}

int main()
{
    int command = 0;
    ....
}

Also, why getc(stdin) over simply getchar()? Either is fine really, but getchar is slightly more idiomatic when reading from stdin.

With any slightly more modern version of C, prefer const declarations to using #define. It's good that you didn't simply write magic numbers all over the place, but prefer things like:

const int seconds_per_minute = 60;

to their #defined counterparts. (They should probably also be static, but don't get too hung up on this while learning).

There are a number of reasons for this. The biggest reason is the fact that #define is just a dumb text replacement mechanism. Say you have a larger program and you are trying to debug it - since #define simply replaces a textual pattern with a given value, all symbols are lost. It's great in the source code to not have any magic numbers, but in a debugger, you won't have that luxury with #define - it'll be back to magic numbers all over again.

The other more minor reasons are that const guarantees it won't change, and if you need to take the address of any of these variables for any reason, well, you're totally out of luck with #define.

That being said, you cannot always get away with using const instead of #define. There's a big post about this on StackOverflow that is worth reading.

Finally, try to avoid using global variables (variables outside the scope of any function, so TIME_TYPE start, end;). In a small program like this it doesn't matter too much, but it's a good habit to get into.

I've typed a bit of a wall of text, but most of this stuff is pretty minor. Summing up:

Always compile with all warnings enabled.
Prefer 4 space to 8 space indentation.
Don't use #define to introduce a new type or a type alias; use typedef.
Prefer to use const variables to #define'd variables.
Try to avoid global variables if possible.


Check whether '.' and '/' are escaped properly

What about, instead of search for every . and / and check the predecessor character, you write a regexp that find a . and / that don't have \\ before?
This way, you can avoid the loop and the short circuit to an array

function isValidEscaped(str) {
  const pattern = /[^\\]{2}[./]/g;
  return str.search(pattern) === -1;
}


Given an integer s and a list of integers ints finding (x,y) in ints such that s = x + y

Your code's complexity is \$O(n^2)\$, this means that worst case it's on-par with looping through ints in a nested loop, and returning the maximum for x, or the minimum for y. And so it's on-par with:

def sum_pairs(ints, s):
    try:
        return max(
            (x, y)
            for x in ints
            for y in ints
            if x + y = s
        )
    except ValueError:
        return None

You could speed this up, if ints is sorted, which your code implies, then you could change max to next, and flip the x and y. However, this still has \$O(n^2)\$ time.

The simplest way to force \$O(n)\$ time is to use a deque, and consume both ends of the sorted deque. This works by removing the tail of the deque to the point that \$x + y \le s\$. After this if \$x + y = s\$, then we return that. If not we take the next item at the head of the deque. Something like:

from collections import deque

def sum_pairs(ints, s):
    q = deque(ints)
    try:
        while True:
            y = q.popleft()
            n = s - y
            while q[-1] > n:
                q.pop()
            if q[-1] == n:
                return q[-1], y
    except IndexError:
        return None


Reading from a text file into a structure and posting to list boxes

Opinion: there is no benefit to building an array like this. I agree it is a clunky use of arrays which I think is unnecessary (and old-school). For instance you don't even need to know in advance how many records, nor do you need to dimension the array to a predetermined size. There are more flexible data types available than arrays for the job.
When adding items to controls like a ListView or ListBox using .Items.Add you can use BeginUpdate at the beginning of your loop and EndUpdate at the end as you are populating the items from a loop.
The aim is to make the UI more responsive - if you have a large file and you're adding lots of items, the interface may freeze while the loop is running.
Although I would probably bind the list to a datatable instead, or another structure. Just append items to the datatable and let the control update itself.
So here is a refactored example: I have converted your structure to a class and I use List Of instead of an array (note the addition of a binding source). For this to work I need to use properties to expose class members (so I think), which is why I am using a class instead of a structure, but there should be a way to retain a structure if you wish.
There are several ways of reading a file, in this example I am using StreamReader. Note the use of a context manager (the Using block), which means I don't have to worry about closing the file, including in case of an exception. This happens automatically past the End Using statement.
In your code PetFile.Close() will not be executed if an exception occurs. Your procedure will exit after MsgBox. But what you can do is move PetFile.Close() to a Finally section within your Try-Catch block. But if you're attempting to close a file that isn't even open, this will raise an exception within the exception. The best solution is not to bother with it and use the context manager.
Note that each line in the file has to contain at least 4 comma-separated fields or the code will crash. So it is advisable to verify for each line that fields.Count = 4 and skip lines that don't match this criterion.
Here I am populating only one listbox, you can figure out the rest easily hopefully.
Imports System.IO

Public Class Form1

    Public Class PetsRecord
        Private m_CustomerName As String
        Private m_CustomerAddress As String
        Private m_PetType As String
        Private m_Vaccinated As String

        Public Property CustomerName() As String
            Get
                Return Me.m_CustomerName
            End Get
            Set(ByVal value As String)
                Me.m_CustomerName = value
            End Set
        End Property

        Public Property CustomerAddress() As String
            Get
                Return Me.m_CustomerAddress
            End Get
            Set(ByVal value As String)
                Me.m_CustomerAddress = value
            End Set
        End Property

        Public Property PetType() As String
            Get
                Return Me.m_PetType
            End Get
            Set(ByVal value As String)
                Me.m_PetType = value
            End Set
        End Property

        Public Property Vaccinated() As String
            Get
                Return Me.m_Vaccinated
            End Get
            Set(ByVal value As String)
                Me.m_Vaccinated = value
            End Set
        End Property
    End Class 'Structure

    Private Sub btnLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoad.Click
        Dim PetArray As New List(Of PetsRecord)
        Dim bs As New BindingSource()
        Dim PetFile As String = "C:\Users\test\Documents\pets.txt"

        Using r As StreamReader = New StreamReader(PetFile)
            Dim line As String
            line = r.ReadLine
            Do While (Not line Is Nothing)

                ' split the line into fields
                Dim fields As New List(Of String)(line.Split(","c))
                If fields.Count < 4 Then
                    Console.WriteLine("Skipping line (contains less than 4 fields): " & line)
                Else
                    ' flag this line
                    If fields(3) = "No" Then
                        Dim pet As New PetsRecord
                        pet.CustomerName = fields(0)
                        pet.CustomerAddress = fields(1)
                        pet.PetType = fields(2)
                        pet.Vaccinated = fields(3)
                        PetArray.Add(pet)
                    End If
                End If

                line = r.ReadLine
            Loop
        End Using

        ' bind the listbox to PetArray
        bs.DataSource = PetArray
        Me.lstCustomer.DisplayMember = "CustomerName"
        Me.lstCustomer.DataSource = bs

    End Sub
End Class


What if any design issues are there in this method of loading configuration data from YAML in Ruby?

You use eval, but eval is evil.

I tried a solution without eval. For this I used:

Module.const_set to define constants
Module.const_defined to check if a constant is defined
Module.const_get to navigate inside modules
Module.new to define new modules.

My solution (including a little test):

def def_constants!(hash, context)

  #context should be a module. If not, then get (or build) it.
  if context.is_a? String
      lcontext = Object
      context.split('::').each{ |module_name|
        lcontext.const_set(module_name, Module.new) unless lcontext.const_defined?(module_name)
        lcontext = lcontext.const_get(module_name)
      }
    context = lcontext
  end

  raise ArgumentError unless context.is_a?(Module)

  hash.each do |key, value|
    case value
      when Hash
        module_name = key.upcase #fixme --  convert_string_to_camel_case(key)
        def_constants!( hash[key], [context.name, module_name].join('::'))
      when /::/  # explicitly build out this module (since it doesn't exist) so that we can talk about it
        context.const_set(key.upcase, Module.new)
        lmod = context.const_get(key.upcase)
        value.split('::').each{ |module_name|
          lmod = lmod.const_set(module_name, Module.new )
        }
      else
        # define the given constant
        context.const_set(key.upcase, value)
    end
  end #hash
end

module AA #define a start
end

require 'yaml'
def_constants!(YAML.load(DATA), AA)
p AA.constants
p AA::KEY
p AA::SAMPLE_MODULE::SOME_KEY
p AA::KEY_SHOULD_BE_MODULE
p AA::KEY_SHOULD_BE_MODULE::I
p AA::KEY_SHOULD_BE_MODULE::I.constants
p AA::KEY_SHOULD_BE_MODULE::I::Am
p AA::KEY_SHOULD_BE_MODULE::I::Am::A
p AA::KEY_SHOULD_BE_MODULE::I::Am::A::Module

__END__
key: value
numeric_data: 3.221
sample_module:
    some_key: another value
key_should_be_module: I::Am::A::Module

I haven't tested it for each usecase. I expect problems, when you try to define modules, where you have already constants with the same name.

Some changes, to use it in your code:

I skipped convert_string_to_camel_case(key) and replaced it with upcase
Your @project_name is my initial context.
(and sure: I renamed the method ;-) )


Iconography - How would you improve this?

My recommendation would be to use a tool to generate a sprite sheet + CSS, rather than writing it out manually yourself.  I've not used it myself, but the sprite helpers found in Compass (see: http://compass-style.org/reference/compass/helpers/sprites/, but it only works with PNGs) are very popular.  If your set of icons expands in the future, you'll be thankful that you don't have to go back and fix everything manually:  just run your tool again with the new images and you're good to go.

Just because browser support isn't perfect, that doesn't mean you can't have both PNG and SVG.  The only browsers that are widely used that do not support SVGs as a background image are IE8 and Android 2.3x.

By taking advantage of the fact that the browsers that do not support SVGs as a background image either do not support the background-size property (IE8) or require a prefix for it (Android 2.3x), you can serve the correct file to the correct browser:

.foo {
    background: url(foo.png) no-repeat; /* IE8 and Android 2.3x */
    background: url(foo.svg) 0 0 / auto auto no-repeat; /* everyone else */
}

In addition to being able to resize gracefully, SVGs have one other little-known advantage:  you can use media queries inside them.  This is an excellent way of reducing details as the SVG gets smaller or adding details as the SVG gets bigger.  When used as a background image, support for media queries inside the SVG is somewhat limited (the demo below appears to only work as expected in IE9+ and Chrome)

http://codepen.io/cimmanon/pen/HldKw

Foo

Foo

Foo

p {
  display: inline-block;
}

p:before {
  background: url(http://people.opera.com/andreasb/demos/demos_svgopen2009/update/circle.svg) 0 0 / cover no-repeat;
  height: 200px;
  width: 200px;
  display: block;
  content: ' ';
}

.two:before {
  height: 100px;
  width: 100px;
}

.three:before {
  height: 50px;
  width: 50px;
}

The SVG:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="400" height="400">
 <g>
  <title>Simple SVG + mediaqueries</title>
  <defs>

  </defs>
  <circle cx="200" cy="200" r="150" id="circle" />
 </g>
</svg>

Learn more:  http://blog.cloudfour.com/media-queries-in-svg-images/


Sqlite.swift -- Selecting all rows and returning them in an array of tuples

Don't use tuples like this. The purpose of tuples is to make simple, short lived collections of values. For a use case like this, it is preferable to use a struct or a class to contain your results. There are many disadvantages.
Don't return non-sensical default values as a way of error handling. "" isn't a city, and "" isn't a valid zip code, so why try to claim them as such? This is what optionals are for, use them.
Narrow your do block to contain only the function calls that throw.
Avoid force casting if you can. Handle your errors sensibly.
Currently, you manually create an empty array, and repeatedly add to it in a for loop. This is discouraged for several reasons:

arr must be mutable.
It's a lot of boiler-plate code.
You can incur a lot of reallocation overhead, because you didn't call reserveCapacity on your array.

Using map is preferable instead.
Improve your naming. sql is a result set, it's not an sql code snippet, nor is it an sql connection. Name it so.
Don't use the pattern of: array += [newElement]. This technique causes an unnecessary array allocation. Instead, just use array.append(newElement).
Change your DB variable to not be an Optional. If there is something like a connection issue that causes DB to be nil, this should be handled at the time that you attempt to open the connection. Leaving it as an Optional, and using optional chaining DB?.doSomething() is a terrible idea. It makes the nil case fail silently, leading to very annoying to catch bugs.
"weather" is an awkward name for a table. Try something like "WeatherReading"

Here's how I would write this code:

struct WeatherReading {
    let city: String
    let zipCode: String
    let temperature: String
}

func queryAllWeatherReadings() -> [WeatherReading]?  {
    guard let queryResults = try? DB.prepare("SELECT city, zip, temperature FROM WeatherReading") else {
        debugPrint(error)
        return nil
    }

    let weatherReadings = queryResults.map{ row in
        guard let city = row[0] as? String,
              let zipCode = row[1] as? String,
              let temperature = row[2] as? String else {
            fatalError("There was a type error in the received result set: \(row)")
        }
        return WeatherReading(city: city, zipCode: zipCode, temperature: r temperature)
    }

    return weatherReadings
}


Erlang: pmap with max number of processes

General

Use standard library as many as possible, usually it given better result therefore function partition can be easily rewritting with wrapper on lists:split/2 and it will be consider as perfomance improvement

split(List,Max)->
    L = length(List),
    split_by(List,L rem Max + L div Max,[]).

split_by([],_N,R)->lists:reverse(R);
split_by(List,N,R)->
    {Part,NewList} = lists:split(N,List),
    split_by(NewList,N,[Part|R]).

Idiomaticness

Add to head of list and reverse instead append. For explanation - SO question.
Tail recursion better for readability and may be faster, so function gather become:

gather([Pid|T], Ref,R) ->
    receive
        {Pid, Ref, Ret} -> gather(T, Ref,[Ret|R])
    end;
gather([], _,R) -> lists:flatten(lists:reverse(R)).

List comprehensions instead lists:map/2:

Min = min(length(L), Max),
Pids = [spawn(
    fun() -> do_f(S, Ref, F, SubL) end) || SubL <- split(L, Min)],
...


Swift - Finding longest binary gap of a given integer

Naming

According to the
API Design Guidelines,
needless word should be omitted, and  prepositional phrases should be made
argument labels. Also variable names should generally be lower (camel) case.

Therefore a better function name would be

public func longestBinaryGap(for n: Int) -> Int

Also variable names should not contain type information, that applies
for example to

var arrayOfIndexes: [Int]

Simplifying your approach

Let's start with func getCurrentBinaryGapFor(), that looks unnecessary
complicated. Without additional local variables it can be written as

func getCurrentBinaryGapFor(_ array:[Int]) -> Int {
    if array.count >= 2 {
        return array[array.count - 1] - array[array.count - 2] - 1
    } else {
        return 0
    }
}

In the main function,

let currentBinaryGap = getCurrentBinaryGapFor(arrayOfIndexes)
if arrayOfIndexes.count == 2 {
    longestBinaryGap = currentBinaryGap
} else if index > 2 {
    if currentBinaryGap > longestBinaryGap {
        longestBinaryGap = currentBinaryGap
    }
}

can be simplified to

let currentBinaryGap = getCurrentBinaryGapFor(arrayOfIndexes)
if currentBinaryGap > longestBinaryGap {
    longestBinaryGap = currentBinaryGap
}

and the loop

var index = 0
for char in binaryString {
    if char == "1" {
        // ... do something ...
    }
    index += 1
}

can be written as

for (index, char) in binaryString.enumerated() where char == "1" {
    // ... do something ...
}

Only the last two elements of arrayOfIndexes are used in the program.
I would

either store all positions of ones in the array first, and then determine
the longest run from that array once,
or use two variables for the recent two positions instead of an array.

In either case, a separate function to compute the current gap seems
unnecessary.

Summarizing the changes so far, the function would look like this:

public func longestBinaryGap(for n: Int) -> Int {
    var bitPositions: [Int] = [] // Positions of all `1` bits in `n`
    let binaryRepr = String(n, radix:2) //

    for (index, char) in binaryRepr.enumerated() where char == "1" {
        bitPositions.append(index)
    }

    var longestGap: Int = 0
    if bitPositions.count >= 2 {
        for i in 0...bitPositions.count - 2 {
            let gap = bitPositions[i + 1] - bitPositions[i] - 1
            if gap > longestGap {
                longestGap = gap
            }
        }
    }

    return longestGap
}

Using Swift's functional methods this could be written as

public func longestBinaryGap(for n: Int) -> Int {
    let binaryRepr = String(n, radix: 2) //

    let bitPositions = binaryRepr.enumerated()
        .filter { $0.element == "1" }
        .map { $0.offset }

    let longestGap = zip(bitPositions, bitPositions.dropFirst())
        .map { $1 - $0 - 1 }
        .max() ?? 0

    return longestGap
}

which looks elegant, but is actually a bit slower than the previous version.

Boosting the performance

Your approach is \$ O(d) \$ (in time and memory), where \$ d \$ is the
number of digits in \$ n \$. That seems very good since any solution must
somehow traverse all digits of the given number.

As said above, the memory usage can be reduced to \$ O(1) \$ by keeping
only the last two bit positions, instead of using an array.

However, much time can be saved by not converting the integer to a string.
The binary digits of a number can be determined efficiently in pure
integer arithmetic.

That leads to the following implementation (essentially a Swift version
of Find the binary gap of a number N),
which is considerably faster:

public func longestBinaryGap1(for n : Int) -> Int {

    if n <= 0 {
        return 0
    }

    var n = n // Make a mutable copy
    // Remove trailing zeros:
    while n % 2 == 0 {
        n /= 2
    }

    var longestGap = 0
    var gap = 0
    repeat {
        n /= 2
        if n % 2 == 0 {
            // Current bit is `0`: increase gap size.
            gap += 1
        } else {
            // Current bit is `1`: check current gap, then reset.
            if gap > longestGap {
                longestGap = gap
            }
            gap = 0
        }
    } while n > 0

    return longestGap
}

And it gets even faster if we use the “find first bit set”
function ffsl() (which might take advantage of compiler intrinsics):

public func longestBinaryGap2(for n : Int) -> Int {

    var n = n // Make a mutable copy
    let firstPosition = ffsl(n)
    if firstPosition == 0 {
        return 0
    }
    n = n >> firstPosition

    var longestGap = 0
    while n > 0 {
        let position = Int(ffsl(n))
        if position - 1 > longestGap {
            longestGap = position - 1
        }
        n = n >> position
    }

    return longestGap
}

Benchmark

My simple benchmark:

let M = 1_000_000

do {
    var sum = 0
    let start = Date()
    for n in 1...M { sum += longestBinaryGap(for: n) }
    let end = Date()
    print(sum, end.timeIntervalSince(start))
}

On a 1.2 GHz Intel Core m5 (with the program compiled in Release mode, i.e.
with optimizations), I measured approximately:

Your original code: 3.3 seconds
longestBinaryGap1(): 0.08 seconds
longestBinaryGap2(): 0.04 seconds


Mocking utility class for database testing

You are right about the problem with static variables and methods possibly causing problems in a multithreaded environment. I recommend turning your MockUtil into an abstract class with no static methods and then have your test classes extend that. That way you are guaranteed to have fresh mocks for all your test classes.


Hash table in Java with arrays and linear probing

I formatted your code and added a main method to test the functionality of your HashTable.

I removed all System calls from the HashTable class and replaced the important text displays with Exceptions.  Generally, utility classes don't write to System.out or System.err.

I modified your getHashedValues method to return the values.

I'd change your use of i to index, but that's a minor point.

All in all, good work.

public class HashTableTestbed {

    public static void main(String[] args) {
        HashTableTestbed test = new HashTableTestbed();
        HashTable hashTable = test.new HashTable(3);

        hashTable.add("alpha", "zeta");
        hashTable.add("beta", "theta");
        hashTable.add("gamma", "tau");
        System.out.println(hashTable.get("alpha"));
        System.out.println(hashTable.get("beta"));
        System.out.println(hashTable.get("gamma"));

        hashTable.remove("beta");
        System.out.println(hashTable.get("beta"));

        hashTable.add("beta", "theta");
        System.out.println(hashTable.get("beta"));
    }

    public class HashTable {
        // known limitation: This will break if the key value
        // is set to none because I
        // use none as the identifier string for deleted keys.
        private int capacity;
        String values[];
        String keys[];

        public HashTable(int capacity) {
            this.capacity = capacity;
            values = new String[this.capacity];
            keys = new String[this.capacity];
        }

        public int hash(String key) {
            int sum = 0;
            for (int i = 0; i < key.length(); i++) {
                sum += key.charAt(i);
            }
            return sum % capacity;
        }

        public void add(String key, String value) {
            int keyhash;
            int i = 0;
            while (i != capacity - 1) {
                keyhash = (hash(key) + i) % capacity;
                if (values[keyhash] == null ||
                        values[keyhash].equals("none")) {
                    // add delete flag to this condition
                    // after implementing delete.
                    values[keyhash] = value;
                    keys[keyhash] = key;
                    break;
                }

                if (values[keyhash] != null &&
                        keys[keyhash].equals(key)) {
                    values[keyhash] = value;
                    break;
                }
                i++;
            }
            if (i == capacity - 1) {
                String text = "Table appears to be full, "
                        + "unable to insert value";
                throw new ArrayIndexOutOfBoundsException(text);
            }
        }

        public String get(String key) {
            int i = 0;
            int keyhash = (hash(key) + i) % capacity;
            while (values[keyhash] != null && i < capacity) {
                if (keys[keyhash].equals(key))
                    return values[keyhash];
                i++;
                keyhash = (hash(key) + i) % capacity;
            }
            return null;
        }

        public void remove(String key) {
            int i = 0;
            int keyhash = (hash(key) + i) % capacity;
            while (keys[keyhash] != null && i < capacity) {
                if (keys[keyhash].equals(key)) {
                    keys[keyhash] = "none";
                    values[keyhash] = "none";
                    return;
                }
                i++;
                keyhash = (hash(key) + i) % capacity;
            }
            String text = "Key does not exist in table";
            throw new IllegalArgumentException(text);
        }

        public String[] getHashedValues() {
            return values;
        }

    }

}


Another even Fibonacci numbers implementation

Sorry if I sound Fortranish. Project Euler is about math, not programming.

A Fibonacci number is even if its index is \$3n+2\$. A Binet's formula reduces their sum to the sum of 2 geometric progressions. That, and some error estimation, is pretty much it.


Your naming of variables is good, they're mostly descriptive and easy to follow.

You could use reverse conditional to reduce the cyclomatic code complexity, doing that your code would look something like:

module.exports = {
  meta: {
    schema: []
  },

  create(context) {
    return {
      MemberExpression(node) {
        if (!node.property || !node.property.object || node.property.name !== 'length') {
          return
        }

        const variableName = node.object.name

        const expectAncestors = context.getAncestors(node)
        for (const expectAncestor of expectAncestors) {
          if (!expectAncestor || expectAncestor.type !== 'CallExpression' || !isExpect(expectAncestor)) {
            continue
          }

          const thenAncestors = context.getAncestors(expectAncestor)
          for (const thenAncestor of thenAncestors) {
            if (!thenAncestor || thenAncestor.type !== 'CallExpression') {
              continue
            }

            const thenCallback = isThenCallBack(thenAncestor)
            const hasParams = thenCallback && thenCallback.params && thenCallback.params.length > 0

            if (!hasParams) {
              continue
            }

            const [thenCallbackParam] = thenCallback.params
            const paramIsDesiredVariable = thenCallbackParam && thenCallbackParam.name === variableName

            const isElementArrayFinderResolution = thenAncestor.callee && thenAncestor.calle.object && isElementArrayFinder(thenAncestor.callee.object)

            if (!paramIsDesiredVariable || !isElementArrayFinderResolution) {
              continue
            }

            context.report({
              node,
              message: 'Array.length inside promise resolution function detected. Use count() instead.'
            })

            return
          }
        }
      }
    }
  }
}

I've included some extra changes in the above code, such as using some ES6.

Property shorthand: { node: node } -> { node }
Method properties: create: function(context) { -> create(context) {
For-of: for (var i = 0; i < ancestors.length; i++) { expectAncestor = ancestors[i] -> for (const thenAncestor of thenAncestors), which is nice since the index was only used to access the ith element
Constants: Using const to denote variables that cannot be re-assigned
Using param instead of "argument" to be consistent with eslint api
Creating expectAncestors/thenAncestors instead of re-assigning ancestors

We could further refactor using extract method:

const getExpectAncestor = (context, node) =>
  context.getAncestors(node).find(expectAncestor => expectAncestor && expectAncestor.type === 'CallExpression' && isExpect(expectAncestor))

const getThenAncestor = (context, expectAncestor) =>
  context.getAncestors(expectAncestor).find(thenAncestor => thenAncestor && thenAncestor.type === 'CallExpression')

const getThenCallbackParam = thenAncestor => {
  const thenCallback = isThenCallback(thenAncestor)
  const hasParams = thenCallback && thenCallback.params && thenCallback.params.length > 0

  if (hasParams) {
    return thenCallback.params[0]
  }
}

// Ideally you'd rename this something even more descriptive
const isDesiredVariable = (thenCallbackParam, variableName) => {
  const paramIsDesiredVariable = thenCallbackParam && thenCallbackParam.name === variableName
  const isElementArrayFinderResolution = thenAncestor.callee && thenAncestor.calle.object && isElementArrayFinder(thenAncestor.callee.object)

  return paramIsDesiredVariable && isElementArrayFinder
}

module.exports = {
  meta: {
    schema: []
  },

  create(context) {
    return {
      MemberExpression(node) {
        // You could extract this into a `isLengthVariable` function
        if (!node.property || !node.property.object || node.property.name !== 'length') {
          return
        }

        const expectAncestor = getExpectAncestor(context, node)
        if (!expectAncestor) {
          return
        }

        const thenAncestor = getThenAncestor(context, expectAncestor)
        if (!thenAncestor) {
          return
        }

        const thenCallbackParam = getThenCallbackParam(thenAncestor)
        if (!thenCallbackParam) {
          return
        }

        const variableName = node.object.name

        if (isDesiredVariable(thenCallbackParam, variableName)) {
          context.report({
            node,
            message: 'Array.length inside promise resolution function detected. Use count() instead.'
          })
        }
      }
    }
  }
}

Here, we have extracted the main logic into seperate methods: getExpectAncestor, getThenAncestor, getThenCallbackParam

These methods are using Array.prototype.find() to find the first element that matches the predicate provided. If no such element is found, it returns undefined and we can exit MemberExpression

Further notes

You could use arrow functions shorthand since you are directly returning:

create = context => ({
  MemberExpression(node) {
    // ...
  }
}

You could declare MemberExpression outside of module.exports to further reduce the indentation level, though since the function relies on context you would need to pass context as an additional parameter. You could achieve this through a higher-order function:

const MemberExpression = context => node => {
  // ...
}

module.exports = {
  // ...

  create: context => ({
    MemberExpression: MemberExpression(context)
  }
}

You'd probably want to refactor this further since there are some especially long lines when checking conditionals, you can use a formatter such as prettier

Prettifying the solution with extracted methods gives the following:

const getExpectAncestor = (context, node) =>
  context
    .getAncestors(node)
    .find(
      expectAncestor =>
        expectAncestor &&
        expectAncestor.type === "CallExpression" &&
        isExpect(expectAncestor)
    );

const getThenAncestor = (context, expectAncestor) =>
  context
    .getAncestors(expectAncestor)
    .find(
      thenAncestor => thenAncestor && thenAncestor.type === "CallExpression"
    );

const getThenCallbackParam = thenAncestor => {
  const thenCallback = isThenCallback(thenAncestor);
  const hasParams =
    thenCallback && thenCallback.params && thenCallback.params.length > 0;

  if (hasParams) {
    return thenCallback.params[0];
  }
};

// Ideally you'd rename this something even more descriptive
const isDesiredVariable = (thenCallbackParam, variableName) => {
  const paramIsDesiredVariable =
    thenCallbackParam && thenCallbackParam.name === variableName;
  const isElementArrayFinderResolution =
    thenAncestor.callee &&
    thenAncestor.calle.object &&
    isElementArrayFinder(thenAncestor.callee.object);

  return paramIsDesiredVariable && isElementArrayFinder;
};

module.exports = {
  meta: {
    schema: []
  },

  create(context) {
    return {
      MemberExpression(node) {
        // You could extract this into a `isLengthVariable` function
        if (
          !node.property ||
          !node.property.object ||
          node.property.name !== "length"
        ) {
          return;
        }

        const expectAncestor = getExpectAncestor(context, node);
        if (!expectAncestor) {
          return;
        }

        const thenAncestor = getThenAncestor(context, expectAncestor);
        if (!thenAncestor) {
          return;
        }

        const thenCallbackParam = getThenCallbackParam(thenAncestor);
        if (!thenCallbackParam) {
          return;
        }

        const variableName = node.object.name;

        if (isDesiredVariable(thenCallbackParam, variableName)) {
          context.report({
            node,
            message: "Array.length inside promise resolution function detected. Use count() instead."
          });
        }
      }
    };
  }
};


Drawing an Archimedean spiral using Pillow

With the default values, the spiral does not look very smooth: it's easy to see that it's been drawn using a series of straight-line segments. That's because the step in \$\theta\$ is quite large — 0.5 radians is more than 28°. Setting step=0.1 and loops=10 is an improvement:

But you can still see deviations from smoothness in various places. The problem here is that the step in \$\theta\$ is constant, but as \$r\$ gets bigger this becomes a bigger step in actual distance. What we would like is a (roughly) constant step in terms of distance along the curve, which we get by replacing

theta += step

with

theta += step / r

This makes step into an approximate distance along the curve in pixels (rather than a change in angle, as in the original code). Now, with step=1 and loops=10, we get this spiral:


Tic Tac Toe code could probably be optimized more

Recently, "Tic-tac-toe" game is gaining popularity on CR.It may even deserve a separate playlist like "Tic-tac-toe" Refactorings on various programming languages.You may find how other guys on CR already succeeded with different implementations (some on pure Python, some - involving numpy functionality).

But let's return to your current variation.

moves list. It's better named as board (as a game field).Instead of typing all board items it could be easily initiated with board = [['1','2','3'] for _ in range(3)]
win function. It sounds like affirmative but it's actually testing for a win.Thus a better name would be check_win
set(moves[i][i] for i in range(3)) == set([letter]) condition. Instead of generating 2 set objects - use a convenient all function:

all(board[i][i] == letter for i in range(3))

for loop (in check_win function) that checks for crossed row can be replaced with any call to serve a more wide consolidation.
2 statements:

print("~~~ " + letter + " WON!!! CONGRATS!!!! ~~~")
quit()

are duplicated across 3 different conditions. That's an explicit case for Consolidate conditional expression technique - we'll combine the conditions that share the same "body" with logical operator.Eventually the optimized check_win function would look as:

def check_win(letter):
    if any((board[i][0] == board[i][1] == board[i][2] == letter) or
            (board[0][i] == board[1][i] == board[2][i] == letter) for i in range(3)) \
            or all(board[i][i] == letter for i in range(3)) \
            or all(board[i][2 - i] == letter for i in range(3)):
        print(f"~~~ {letter} WON!!! CONGRATS!!!! ~~~")
        quit()
    if acc == 5:
        print("TIE YOU BOTH LOSE")
        quit()

playerInput and boardDraw should be renamed to player_input and board_draw to follow naming conventions
printing game's board in board_draw function looks really sad and painful.Python provides a good string formatting features.Just use them, as shown below:

def board_draw():
    board_fmt = '''
1| {} | {} | {} |
 |---+---+---|
2| {} | {} | {} |
 |---+---+---|
3| {} | {} | {} |
    '''
    print(board_fmt.format(*[v for row in board for v in row]))

    check_win("X")
    check_win("O")
    player_input()


Style

Your function name doesn't tell me whether you compute the symmetric or non-symmetric set difference. How about symmetricDifference instead of diffArray?
Instead of newArr I'd prefer reading e.g. result which tells me something about the role of that variable instead of its type.
There is an empty else { } clause in the first inner loop but not the second inner loop. Without that purely stylistic difference, the similarity of these two code blocks becomes more apparent.
The statements within the succeeding if clauses are identical, so you can merge them into one by combining the conditions with a logical OR operator.
The type checks and equality tests performed within the if conditions seem overly complex. AFAIK == is identical to === when both operands have the same type, so there is no need to mix them. Also, a generic function named diffArray should handle all possible array values, not only numbers and strings. This would allow you to simplify the two if conditions to e.g. a simple if (arr2[i] === arr1[j]) { ... }.
The iterator variable i is used to iterate through arr2 while iterator variable j is used to iterate through arr1. Readability improves by matching i with arr1 and j with arr2 according to their alphabetical order.

Performance

The inner loops are counting how often elements from the first array appear in the second array and vice versa. However, you are not interested in the exact count, only if count > 0. So you could use a labeled continue as soon as the count increments for the very first time:

outer: for (var i = 0; i < arr1.length; i++) {
  for (var j = 0; j < arr2.length; j++) {
    if (arr1[i] === arr2[j]) continue outer;
  }
  result.push(arr1[i]);
}

Now, it is much easier to see that the inner loop is actually just checking the existence of an element within an array. You can use the faster built-in indexOf method instead:

for (var i = 0; i < arr1.length; i++) {
  if (arr2.indexOf(arr1[i]) < 0) result.push(arr1[i]);
}

Even better, use the newer and more explicit includes method. However, this changes the semantics of your code due to the different handling of NaN:

NaN === NaN // false
[NaN].indexOf(NaN) // -1
[NaN].includes(NaN) // true

Now, your updated code could look as follows:

function symmetricDifference(arr1, arr2) {
  const result = [];
  for (const val of arr1) {
    if (!arr2.includes(val)) result.push(val);
  }
  for (const val of arr2) {
    if (!arr1.includes(val)) result.push(val);
  }
  return result;
}

Declarative vs. Imperative

Those two remaining loops actually filter the input arrays and return the remaining unique values. A more descriptive and possibly self-documenting way of writing such an operation is given by the filter method:

function symmetricDifference(arr1, arr2) {
  const difference1 = arr1.filter(val => !arr2.includes(val));
  const difference2 = arr2.filter(val => !arr1.includes(val));
  return difference1.concat(difference2);
}

However, the performance of plain for loops is superior.

Runtime Complexity

If you have to deal with larger arrays and prefer to have an implementation with higher setup costs but linear instead of quadratic runtime complexity, convert the input arrays into sets first and use the much faster set.has(val) instead of arr.includes(val).

Generalization

A generic solution which is not restricted to arrays but handles any iterable input could look as follows:

function* symmetricDifference(iterable1, iterable2) {
  const set1 = new Set(iterable1);
  const set2 = new Set(iterable2);
  for (const val of set1) if (!set2.has(val)) yield val;
  for (const val of set2) if (!set1.has(val)) yield val;
}


Naming

I recommend not using acronyms or shortened names where possible for your variables. You might as well use the full name, it aids in quick reading.

e.g.

public dynamic Insert<T>(T dataTransferObject) where T : class
{
    return Execute((x, t) => x.Insert(dataTransferObject,t));
}

Although for that method item may work just as well.

The same goes for single-letter variable names in your lambda expressions. If there's only parameter to your lambda, it's probably ok, but with multiple parameters it can quickly become confusing.

return Execute((connection, transaction) => connection.Insert(dataTransferObject,transaction));

Shows the exact purpose of your lambda much more clearly.

I also note that you have a method called GetList that does not return a List. This is just plain confusing.

Lastly, you should avoid putting the type of the variable in its name.

E.g.

public void Insert<T>(List<T> dtoList)

would be better as:

public void Insert<T>(List<T> dtos)

Otherwise it can lead to confusion should you decide to change it to a different type, and forget to update the variable name.

var

You have used var appropriately and consistently, making this (as far as I'm aware) the first code review I've ever posted that does not contain some guidance on var. Well done.

Parameter types

You take a List with this method:

public void Insert<T>(List<T> dtoList) where T : class
{
    IEnumerable<T> enu = dtoList;
    // yadda yadda yadda...

And then immediately convert it to an IEnumerable in your body. Just take the parameter as IEnumerable in the first place, passing a List in will still work. By requiring a List you're actually making it harder to use your own function (because you can't, for example, pass in an array) for no reason at all.


Reasonable way to implement "safe" math operations using _Generic?

Very impressive! A few notes:

I really like how you are using C11 stuff.

#define safe_add(x, y) _Generic((x + y),                    \
                            unsigned int: safe_add_uint,    \
                           unsigned long: safe_add_ulong    \
                       )(x, y, __FILE__, __LINE__)

It's good that you are using the more modern items the C standards have given us to use.  My only nitpick with this #define is that your aligning is a bit off.

#define safe_add(x, y) _Generic((x + y),                        \
                                unsigned int: safe_add_uint,    \
                                unsigned long: safe_add_ulong)  \
                                (x, y, __FILE__, __LINE__)

@Morwenn touches on your error handling a bit, but I want to go deeper.  For now, I want to talk about the style of error reporting I've come to adopt for such APIs. Options for error reporting from C functions include the following:

Return an error code from functions that can fail.
Provide a function like Windows GetLastError() or OpenGL's    glGetError() to retrieve the most recently occurring error code.
Provide a global (well, hopefully, thread-local) variable containing the most recent error, like POSIX errno.
Provide a function to return more information about an error, possibly in conjunction with one of the above approaches, like POSIX's strerror function.
Allow the client to register a callback when an error occurs, like GLFW's glfwSetErrorCallback.
Use an OS-specific mechanism like structured exception handling.
Write errors out to a logfile, stderr, or somewhere else.
Just assert() or somehow else terminate the program when an error occurs.

There are loads of tradeoffs among these options, and it's a matter of opinion as to which ones are better than others. Like all matters of style, unless a style is just plain unsuitable (like the last two options above might be for many uses), it's probably most important to apply the style you choose consistently.

Let me illustrate the style of error handling I use for C APIs with the following re-written function of yours:

unsigned int safe_add_uint(unsigned int x, unsigned int y,
      const char* filename, int line_num, char* error)

Where we call it as:

char* error = /* allocate memory */;
safe_add_uint(x, y, __FILE__, __LINE__, &error)`

Now your function can set the value of error within the functions, and then print the output in something such as an atexit() function.

You might think that this could be a bit cumbersome for an error handling system in C, but here's the catch: this C error handling style that plays nice with C++ exceptions too.  This can be nice when implementing an hourglass API.
You should probably be using exact-width integer types.
Always declare what parameters your function takes in, even if nothing.

int main(void)

You might wonder why we have to do this.  Imagine we have the function foo() declared as such:

int foo()

In C, this is known as an identifier list and means that it "can take any number of parameters of unknown types".  We can actually pass values to the function even though we don't mean to or intend to.  If the caller calls the function giving it some argument, the behavior is undefined. The stack could become corrupted for example, because the called function expects a different layout when it gains control.

Using identifier lists in function parameters is depreciated.  It is much better to do something like:

int foo(void)

In C, this is known as a parameter type list and defines that the function takes zero arguments (and also communicates that when reading it) - like with all cases where the function is declared using a parameter type list, which is called a prototype.   If the caller calls the function and gives it some argument, that is an error and the compiler spits out an appropriate error.

The second way of declaring a function has plenty of benefits. One of course is that amount and types of parameters are checked. Another difference is that because the compiler knows the parameter types, it can apply implicit conversions of the arguments to the type of the parameters. If no parameter type list is present, that can't be done, and arguments are converted to promoted types (that is called the default argument promotion). char will become int, for example, while float will become double.


How often do you change parameter names? How often does the code run?  Under any normal distribution of those, you should go with a minor code efficiency gain over a programmer efficiency gain.

On the other hand, if you (for some bizarre reason) change the parameter name almost every time the code runs, the tradeoff is probably worth it.

But just remember, that whether or not the string matches the actual parameter name, it should still let you find exactly which parameter was null so long as there isn't anywhere else in that function which throws an ArugmentNullException with the same string.


Extension method to enumerate a hierarchical object

There is a way, and it is beautiful. Instead of using recursion, you use iteration by placing the top level object on a Stack (or Queue depending on whether you want a depth-first or a breadth-first search). Then you go into a loop where you pop off the first item, check to see if it has descendants, and add them to the stack. By the time the stack/queue is empty you'll have traversed the entire tree.

You were halfway there with your decision to manage a collection that represents the entire set of objects, but the nature of the Stack/Queue allows you to access deeper and deeper properties without having to go deeper and deeper in the call stack.

Example from MSDN on how to traverse a directory tree:
http://msdn.microsoft.com/en-us/library/bb513869.aspx

Whether you choose to implement this as an extension method or not is up to you. I also strongly advise asking yourself whether you really need a collection of all descendants, or if you simply want to iterate through all descendants of a certain object? The answer to that question will determine whether the traversal belongs in what would be acting on the top-level object or whether the traversal should be abstracted away.


Loading tab-separated tweet data into an array

The prohibition on ArrayList is unfortunate.  One natural solution would be to use Files.readAllLines(), but that returns a List<String>, which is probably off-limits to you.  Likewise, Files.lines() produces a Stream<String>, which would be even better and thus probably even more forbidden to you.

Your workaround is to open the file twice, which is definitely undesirable.  (File I/O is considered "expensive".)  If I had to make a recommendation based on arrays, I would suggest

Files.readAllBytes() to slurp the entire file into a byte array.
Make a String from the byte array.
Use String.split() to form an array of lines.
For each line, retain only the third field.

My reasoning is that you eventually have to read the entire file anyway, so you might as well read it all at once, and only once.  Once you have a string, you can take advantage of String.split().

I would also like to note that catching IOException to print a stack trace is counterproductive.  If you don't have a good way to handle an exception, just let it propagate by declaring public void loadTweets(…) throws IOException.  That way, you're letting the caller know that something went wrong — which is exactly what exceptions are meant for.


Removes course objects from the course list

Your toString() method iterates up to courses.length rather than courseCount, so you will end up outputting nulls if the CourseList is not filled to capacity.

Just a minor note: most StringBuilder methods are designed to allow chaining, like this:

sb.append(courses[i]).append("\n");

In your remove() method, you fail to decrement courseCount, so a subsequent add() will result in an awkward null gap.

You should never omit the "optional" braces of a for loop.  Someday, you will contribute to a coding accident, and it will be your fault.  Not to mention, the missing braces make the code look ugly and hard to read.

The method would be clearer and more reusable if you broke out part of the code into an indexOf(Course) method (which could be public or private — your choice).

public void remove(Course course) {
    int courseIndex = this.indexOf(course);
    if (courseIndex >= 0) {
        for (int i = courseIndex; i < courseCount - 1; i++) {
            courses[i] = courses[i + 1];
        }
        courses[--courseCount] = null;
    }
}


Most optimized way to get minimum strpos from multiple needles

Well, any time you have nested for loops, you should cringe a little because it means you're running in O(n^2) time. Sometimes it's unavoidable, but often you can do something to bring it down significantly. Edit: this algorithm is actually O(n).

In your case, you can reduce your algorithm to O(n), which is a huge performance boost.

Here are your new steps:

Loop through each needle
    Get the position of the needle in the haystack
    If the position is less than our current minimum:
        Set the minimum to the position of the needle

Basically, we find the first minimum and then overwrite it as each new minimum is found.

Here is my version of your code:

function min_strpos_array($haystack, $needles){
    $length = count($needles);
    $min = strlen($haystack) + 1;
    for($i = 0; $i < $length; $i++){
        $strpos = strpos($haystack, $needles[$i]);
        if ($strpos !== FALSE){
            if($strpos < $min){
                $min = $strpos;
            }
        }
    }
    return $min;
}

echo min_strpos_array('hello#,?', array('#', '?')); //5

Outside of the algorithm, I made a few other changes.

for ($i; $i < count($needles); $i++) became for ($i = 0; $i < $length; $i++). When you have a function in a for loop, it gets called every iteration, which is unnecessary when the value doesn't change. Just get the number of needles outside the loop and reference that. You could also use a foreach loop, but I'm not familiar enough with PHP to definitively say that it's better.

$min = null; became $min = strlen($haystack) + 1;. This ensures that if our needle exists in the haystack, we can compare the position with our minimum. It also has the side effect of returning strlen($haystack) + 1 if none of the needles are found in the haystack, which may or may not be desirable. If you don't like that, just add an if statement before you return.

You really don't need to nest your if statements like you did either, but I decided to leave those in in case you chose to so intentionally.

Two important things to take away from this:

Watch out for nested for loops. Pretend they're screaming at you to find a better algorithm.
Don't call functions in the argument of a for loop unless you need to get a value that might change during the loop.


Basically I use option 1. The usage of constructor is initialize the properties and creating an object in memory.  Value types sets the default values (int = 0 etc), reference types sets  null. If you want use own default values, you must use own constructor. This is option 1 in your post. In my opinion this is the safest and most logical option.


String decryptionAlgorithm = manager.getStringValue(SymmetricDecryptionAlgorithm);

What manager is this, and why does the method have to perform its own configuration?

// Key bytes are only the first 16 bytes
final int KEY_BYTES_STARTING_BYTE = 0;
final int KEY_BYTES_ENDING_BYTE = 16;

final int IV_BYTES_STARTING_BYTE = 0;
final int IV_BYTES_ENDING_BYTE = 16;

Entirely not needed, and if they were they should be private static class variables, the Java equivalent of constants. What about using Cipher#getBlockSize()?

// 1. Get the cipher ready to start doing the AES transformation
Cipher cipher = Cipher.getInstance(decryptionAlgorithm + "/" + cipherBlockMode + "/" + padding);

The comment is dangerous, as it mentions AES but you configure the decryptionAlgorithm. I'm not sure why you would need 3 separate configuration fields for this.

byte[] trimmedKeyBytes = Arrays.copyOfRange(keyBytes, KEY_BYTES_STARTING_BYTE, KEY_BYTES_ENDING_BYTE);

So if the user supplies a 256 bit key, then just use the 128 bits and do not throw error? That's not good practice at all.

byte[] encryptedBytes = null;
byte[] ivBytes = null;

You are already assigning the references in the if statement, no need to initialize them to null. You can even make them final so that you know that each branch will initialize the variables!

//      -do +2 from start because we want to remove \r\n at the beginning and -2 to remove \r\n from the end
// Remove the new line and carriage returns from beginning and end, if they are there

You have got binary data, which has been base 64 decoded, and your originally binary ciphertext could maybe include a carriage return + line feed? Well, a random IV or ciphertext will probably contain that with a chance of 1/65536, which means that your decryption will fail once in about 4 billion times. You'll just have to wait long enough for it to happen.

encryptedBytes = Arrays.copyOfRange(encryptedAttachmentBytes, CIPHER_BYTES_STARTING_BYTE, encryptedAttachmentBytes.length);

First of all, I have no clue why you would copy the encrypted data and then the IV bytes, as that makes no sense at all - you never receive or need them in that order.

But note that both the IvParameterSpec() constructor and Cipher#doFinal() method have forms that already let you define an offset and amount of bytes to use. For the IV that doesn't matter much, for the ciphertext it adds insult to injury.

private byte[] symmetricDecryptAttachment(byte[] encryptedAttachmentBytes, byte[] keyBytes) throws IOException, GeneralSecurityException, EIPException {
    try {
        ...
    } catch (Exception e) {
        System.err.println("Exception occurred in symmetricDecryptAttachment() of SOAPDecryptionProcessor: \n" + e.getMessage());
        throw new EIPException(e.getMessage());
    }

Pokemon exception handling, using System.out, removing the exception from the stack trace, not specifying which exceptions can be thrown, no distinguishing between different types of exception (NoSuchAlgorithmException is different from a bad ciphertext, right?).

That kind of exception handling has to go.

Be warned that CBC is only useful for confidentiality, and then preferably only over authenticated messages or for in place encryption / decryption. I'm not sure if you're using that, but using GCM is probably a better option (within an IV of 12 bytes).

As for your question: yes, use streaming. Incremental updates are also possible, but given that your ciphertext is likely arriving per stream, using CipherInputStream makes most sense. Note that the Base64 encoder class can also be wrapped over a stream.


Populating and saving checkboxlist items to the database

I think it's reasonable to look at whether a single column design is possible - it certainly makes life easier:

For Each DataRow dr in CodeDataTable.Rows
    Dim li as ListItem = Me.cblCodes.Items.FindByText(CType(dr["Text"], String))
    li.Selected = True
Next

You could alternatively do a two column design, with a Text varchar and a Value bit:

For Each DataRow dr in CodeDataTable.Rows
    Dim li as ListItem = Me.cblCodes.Items.FindByText(CType(dr["Text"], String))
    li.Selected = CType(dr["Value"], Boolean)
Next

But even the wide table could be done with less repetitive code by using DataTable.Columns to get the names of the columns:

Dim codeData as DataRow = CodeDataTable.Rows(0)
For Each DataColumn dc in CodeDataTable.Columns
    Dim li as ListItem = Me.cblCodes.Items.FindByText(dc.Name)
    If Not codeData.IsNull(dc) AndAlso CType(codeData[dc], Boolean) Then
        li.Selected = True
    End If
Next


SQL LIKE search in Angular filter objects

I think you inverted startLike with endLike.

const like = format.indexOf("%") >= 0;
const startLike = like && format.charAt(0) === "%";
const endLike = like && format.charAt(format.length - 1) === "%";

When I read startLike I could misunderstand with startWith, that is the popular term used in APIs.

So it's complicated to read the code, as you work with an inverted logic.

I will use startWith(== endLike) and endWith (== startLike), instead.

Another point about naming is:

const split = [];

I think it is meaningless and a very bad choice for an array name.

Consider the case in a future time if you need to use Array.split():

split.split(...);

Not so good in readability.

Consider the code:

const split = [];

split.splice(0, 0, ...format.split("%"));

Not sure why you want to do all this work to just assign an array.

You could just use:

const split = format.split("%");


Find the kth element which is either divisible by l or r or both

First, there's a couple of things you're not doing which I think you should: you should provide a comment describing what this program does, and you should validate your inputs.

That is, give a banner like:

/* Given inputs L, R, and K, print the Kth element of the sequence
   of integers made up of all positive multiples of L and/or R, in
   ascending order. */

And validate the inputs with an assert, an error message, or just by swapping L and R if they're not in order. Also, ensure the numbers are positive.

Another approach

With that said, I'd like to encourage you to think about the problem a different way: assuming that L < R, what happens when you add a multiple of R in the sequence?

Let's use 5 and 11 instead of 2 and 3, because they have a bunch of problems and they produce numbers that are all fairly distinct when you divide them. (They're a better example than 2 and 3, or 3 and 7 which were the first two examples I tried. ;-)

If you have L=5, R=11, K=10, consider adding a multiple of R to the sequence:

sequence = {}                // empty sequence
add a multiple of R          // R is 11, remember
sequence = {5, 10, 11}

We'll call that a "block". Adding a "block" adds all the numbers up to the next multiple of R.

Each multiple of 11 brings with it 11/5 = 2+1/5 multiples of 5, because 11/5 == 2+1/5. But when the fractions finally add up to a whole number, it won't count! That's when the multiple of 11 will also be a multiple of 5 (55, 110, 165, etc.) and the numbers aren't added to the sequence more than once. So really, adding a multiple of 11 to the sequence adds 1 (the multiple of 11) plus floor(11/5) == 2 multiples of 5 to the sequence.

In general, adding a "block" -- that is, adding one multiple of R -- to the sequence adds 1 + floor(R/L) numbers to the sequence. We'll call that the "block size" or blocksize.

blocksize = 1 + int(R/L);

We can use this in reverse: If K=10, as above, then K/blocksize == K/3 == 3 (remainder 1). So the 10th value in the sequence would be 3 blocks plus one non-block number. That is:

sequence = {
    /*block 1*/ 5, 10,11,
    /*block 2*/ 15,20,22,
    /*block 3*/ 25,30,33,
    /*block 4*/ 35,         // <-- K=10th number
                   40,44,
    /*block 5*/ 45,50,55,
    /*block 6*/ 60,65,66,
}

The only tricky part will be finding the fractional-block numbers, since you can't just add 5 to 33.

This leaves us with two cases: the cases where K is a multiple of the block size, and cases where there is a remainder.

If K is a multiple of the block size, then the result is simply

R * (K/blocksize)

For the 9th number in the sequence, we'd have K/blocksize == 3, and R * 3 == 33, as shown above.

If K is not a multiple of the block size, we have to find a multiple of L that is less than or equal to the highest number in the previous block, then add L * remainder(K/blocksize) to it.

So if K=10, as above, we look for the multiple of L (5) that is less than or equal to the highest number in block 3. 3 * R == 33, so we'd use 30, then add remainder(10/3) == 1 multiple of 5: 30 + 1*5 = 35.

Similarly, if K=17, we would find the highest multiple of 5 less than or equal to 55, which of course is 55. Then we'd add remainder(17/3) == 2 multiples of L, or 2 * 5, to get 65.

The upshot of this is that you can find your result directly, with just a few integer operations, no looping required.


Length of longest palindrome subsequence

Back to the basic of code review, what does this code do and how do you do it. At first glance I've got not clue what so ever this code does. I don't know what the content of the table is. I don't know what the h or the gap is referring to, and I don't know why the table[0][n-1] is the correct answer.

The only thing I know is that your function is supposed to return the "maximum length palindrome subsequence" of a. Which is not entirely clear either. (I wrote an answer (now deleted) based on a misconception of the terms included, as I didn't fully realize the definition of subseqence)

So let us review some unknown code:

Vague variable naming – The variable could strongly benefit from indicating what they are actually containing. Like instead of a, it could be sourceString or source or text. The i and n is commonly known as the loop counter, and the number of elements. The a, gap, h and table, no idea what they contain. Especially the table is badly named.
No comments – It would have been nice to see some comments describing what the various loops are trying to achieve, or how the table is initialized. For the method possibly some examples of valid responses.
Break out early – As in the answer by @Dair, since i is ever increasing, whenever the h >= n you can do a break.
Strange comparison, no I – You compare a[i] == a[h], why? If i == h this will always be true. However h = i + gap, so this does essentially say a[i] == a[i + gap] which would be a little bit clearer, although I still don't quite get why we compare this.
Strange comparison, no II – Right below you compare i+1 ==h, which is the same as i + 1 == i + gap, which can be simplified to gap == 1.
Unneeded if h<n – If you get this far, then it's a given that h < n, as otherwise you'd continue'd. Hence the if could be removed all together.

Based on the code so far I'm guessing that table holds the length of the palindrome starting at that first index and ending at last index. Not quite how it gets there, but that is my assumption. Let us rewrite the code according to this, and my comments above:

def maximum_length_palindrome_subsequence(text):
    """Search through text to find the maximum length of a
       palindrome looking at subsequences of the text.
         text = "abcda" -> palindrome: aca -> length = 3
         text = "xaybzcydxe" -> palindrome: xyzyx -> length = 5
    """
    text_length = len(text)

    # palindrome_length is a two dimensional table of palindrome
    # lengths where the first dimension is start index, and the
    # second dimension is the end index of the palindrome in text

    # Initialize with all zeroes
    palindrome_length = [[0 for i in xrange(text_length)] for j in xrange(text_length)]

    # As a base, every single character through text is a
    # palindrome of length 1
    for i in xrange(text_length):
        palindrome_length[i][i] = 1

    # Loop through the various gaps in text, and check for
    # similarity for every index of the text. Update the
    # palindrome_length accordingly if matching characters
    for gap in xrange(1, text_length):
        for i in xrange(text_length - 1):

            # h is the candidate index? (or something like that?!)
            h = i + gap
            # If candidate index is after length of text, break out
            if h >= text_length:
                break

            # If equal characters, update palindrome_length
            if a[i] == a[h]:
                if gap == 1:
                    palindrome_length[i][h] = 2
                else:
                    palindrome_length[i][h] = palindrome_length[i + 1][h - 1] + 2
            else:
                # Characters not equal, so choose a max based upon
                # ... some criteria ...
                palindrome_length[i][h] = max(palindrome_length[i + 1][h],
                                              palindrome_length[i][h - 1])

    # Return the maximum length based upon entire text
    return palindrome_length[0][n - 1]

print maximum_length_palindrome_subsequence('abcda')

Based upon this rewrite I've got some additional comments:

Simplify initialization of palindromeLength – Instead of first filling it with 0, and then refilling parts with 1, you could do:

palindrome_length = [[ 1 if i == j else 0
                         for i in xrange(text_length)]
                            for j in xrange(text_length)]

Criteria for the max() – Is this somewhat related to palindromes of an even or odd length? That it chooses the longest of those two alternatives?

To conclude, your code does follow proper indentation, is a little lacking in space around operators, but the main issue is bad naming and unclear intentions of the various code blocks. There is some magic happening in this code, which could benefit from clear comments sprinkled out in the code.

  Imaging what you yourself would think of your code if it was presented to you as it stood originally, but with the name function_x and the question: What does function_x do? Would you be able to answer it?

If my assumption on the max is correct, my final version is:

def maximum_length_palindrome_subsequence(text):
    """Search through text to find the maximum length of a
       palindrome looking at subsequences of the text.
         text = "abcda" -> palindrome: aca -> length = 3
         text = "xaybzcydxe" -> palindrome: xyzyx -> length = 5
    """
    text_length = len(text)

    # palindromeLength is a two dimensional table of palindrome
    # lengths where the first dimension is start index, and the
    # second dimension is the end index of the palindrome in text

    # Every character is considered a palindrom of length 1, whilst
    # the rest is initialized to 0
    palindrome_length = [[ 0 if i != j else 1
                             for i in xrange(text_length)]
                                 for j in xrange(text_length)]

    # Loop through the various gaps in text, and check for
    # similarity for every index of the text. Update the
    # palindrome_length accordingly if matching characters
    for gap in xrange(1, text_length):
        for i in xrange(text_length - 1):

            # h is the candidate index? (or something like that?!)
            h = i + gap
            # If candidate index is after length of text, break out
            if h >= text_length:
                break

            # If equal characters, update palindrome_length
            if text[i] == text[h]:
                if gap == 1:
                    palindrome_length[i][h] = 2
                else:
                    palindrome_length[i][h] = palindrome_length[i + 1][h - 1] + 2
            else:
                # Characters not equal, so choose a max based upon
                # the even or odd length palindrome length?
                palindrome_length[i][h] = max(palindrome_length[i + 1][h],
                                              palindrome_length[i][h - 1])

    # Return the maximum length based upon entire text
    return palindrome_length[0][text_length - 1]

print maximum_length_palindrome_subsequence('abcda')           # "3"
print maximum_length_palindrome_subsequence('xaybzcydxe')      # "5"
print maximum_length_palindrome_subsequence('abcdaabcda')      # "6"
print maximum_length_palindrome_subsequence('racecar')         # "7"
print maximum_length_palindrome_subsequence('racecars')        # "7"
print maximum_length_palindrome_subsequence('iiiiragceciars')  # "7"

At the very end I presented a few more cases, to verify the correctness of the revised version.

Update: Changed to snake_case to conform to standards. Hopefully I didn't break the code. :-)


Query for combining results of same query running across multiple databases

You probably don't need any temp tables unless you need access to these temp tables across different stored procedures, here is how I would write it.

DECLARE @sql VARCHAR(MAX)

SELECT  @Sql = COALESCE(@sql + ' UNION ALL ', '') + 'SELECT [' + name + '].dbo.Session.Browser, COUNT(['+name+'].dbo.Session.Browser) AS Counts FROM [' + name + '].dbo.Session WHERE [' + name + '].dbo.Session.Browser IS NOT NULL GROUP BY ['+name+']dbo.Session.Browser'
from sys.databases
where name like '%Test2Portal%' and name not like '%_Test%'

EXEC @sql --this will perform the select for you

hope this is helpful


So one thing about not using objects is that it makes getters/setters a bit less flexible in that you can't start them out as pure properties and then move them to property() values later.

Also, by using something like helpers.login(..), you're implicitly limiting yourself to one login at a time since the helpers namespace isn't managed like an object namespace would be.  That may or may not be a problem for you now, but it's definitely a corner you may not be aware you're coding yourself into.  If in the future you had two things you wanted to log into using the same code, you'd have to restructure quite a bit.