All-core MediaWiki website upgrade script

Naming
Try not to use generic names like $file. Make your code read easy for others. Say $files_to_backup for example.

Check for errors when it matters
If backup is important: check that the backups succeeded:

if cp "${files[@]}"${war}/mediawiki_specific_backups";then
     rm -rf "${war}/${domain}"
     mkdir "${war}/${domain}"
     ...
     ...
 else
    # handle error condition
fi

Document the code
I prefer a comment in the script header describing what the script. If the script does useful work, document what it does so others understand what it does and how to use it. Similarly, comment anything in the code which is important and you think might require some explanation to help readers.

#!/bin/sh
# Usage: how-to-use-script
# Purpose: upgrade all core MediaWiki websites
# etc


When coming up with an OO design, always ask yourself "What is the responsibility of this class?" There should be only one. If you have to describe it with a bunch of ANDs, e.g. "it runs the game and prompts for player names and sets up the board and..." then it is a sign you may want to break it down further. This is called the Single Responsibility Principle. Resist the temptation to put all functionality into one class that does everything, as it is very easy to grow the class into the antipattern known as the God Object. Sometimes naming helps. If instead of TicTacToe, you called the object GameRunner (for example), you may be less tempted to put any and all Tic Tac Toe related things into it.

In your case, I'd try to keep TicTacToe as lean as possible. Prompting for a player's name should be something a Player object knows how to do, so I'd move that to the Player class. Also prompting for a mark can certainly be moved into the Player class. Possible interface:

marks = ["X", "O"] #this would be in the initialization
player1.mark = player1.select_mark(marks)
player2.mark = marks - player1.mark

Also, you'll want to create an object to represent the game board.


First you should define your ordering separately from your merge:

bool operator<(people const& lhs, people const& rhs)
{
    if (lhs.lname < rhs.lname)  {return true;}
    if (lhs.lname > rhs.lname)  {return false;}

    // lhs.lname == rhs.lname
    if (lhs.fname < rhs.fname)  {return true;}
    if (lhs.fname > rhs.fname)  {return false;}

    // lhs.lname == rhs.lname  && lhs.fname == rhs.fname
    if (lhs.dob < rhs.dob)      {return true;}

    // Optimize away the last test.
    //if (lhs.dob > rhs.dob)      {return false;}

    return false;
}

Incrementing by one can be done with the operator++

j += 1;
// Easier to write as:
++j;

Or you can do it in-place with:

temp[k] = arr[i];
i += 1;
// Easier to write as
temp[k] = arr[i++];

Using new/delete is a bad idea. It makes you do all the memory management. It is better to use classes that do it all for you. In your case std::vector is a better choice for memory management of arrays

people * temp = new people[end2];
....
delete [] temp;
// Better to use std::vector
std::vector<people>  temp(end2);
....

Prefer to use standard algorithms rather than manual loops.

  for(int c = 0; c < end2; c += 1) {
    arr[c] = temp[c];
  }
  // Use std::copy
  std::copy(temp.begin(), temp.end(), arr);

If you are copying something and not going to use the original again. Then try and move the object to the destination rather than copying it.

  temp[k] = arr[i];
  // Prefer to move rather than copy
  // if you are not going to use the value at arr[i] again.
  temp[k] = std::move(arr[i]);

  // Note this assumes you have defined move constructor and move assignment operator
  // for the class people. If you have not defined these operations then it will
  // default to use the normal copy versions.

Now your merge becomes more readable:

void mymerge(people  *arr, int end1, int end2)
{
  int i = 0;
  int j = end1;
  std::vector<people>  temp;
  temp.reserve(end2);

  while(i < end1 && j < end2)
  {
      people&  src =  (arr[i] < arr[j])
                         ? arr[i++]
                         : arr[j++];
      temp.emplace_back(std::move(src));
  }

  std::move(&arr[i], &arr[end1], std::back_inserter(temp));
  std::move(&arr[j], &arr[end2], std::back_inserter(temp));

  std::move(temp.begin(), temp.end(), arr);
}

Now that I have cleaned up the mymerge() function I can understand what you are doing and it looks like it should work. But it requires the input sections to be already pre-sorted. I am not sure how your double loop in main() achieves this.


There's quite a lot to address here, but I'm going to start with my absolute largest concern--one that will cause problems for anyone who uses this:

func getData(completionHandler: ((NSArray!, NSError!) -> Void)!) -> Void

There are places where it's okay to use the implicitly unwrapped optional !, but this is not one of those places by any means.

First of all, you use it on the completion handler as a whole, which means it's somehow okay for the user to call:

getData(nil)

But you never check whether or not a completion handler was passed to you.  You just assume one was and call it anyway, which means any time someone calls this method and passes nil, there will be a crash.

But the arguments the completion handler takes also should not be implicitly unwrapped options.  They should just be regular optionals: ?.  This is especially true here as we are explicitly passing nil into the completion handler in some cases.  Implicitly unwrapped optionals are for very special cases.  You need to use the regular optional which tells any user "YOU MUST CHECK THIS FOR NIL!".  Implicitly unwrapped optionals say "This object is never nil so never bother checking it!  It's only an optional because of some extraordinarily special scenario that's handle entirely by the internal class in initialization."

If I start using your RemoteAPI class, I'd never check the objects in the completion handler for nil (until I got a crash).

Unless you're Apple making Objective-C code in their massive libraries work correctly with Swift (and even here, Apple is only using ! as a placeholder and intends to replace these all with either non-optionals or regular optionals) OR you're writing something where a property can be nil in the init sometimes, then you don't need to be using the implicitly unwrapped optional!  It looks like you've got a handleful of implicitly unwrapped optionals that need to be removed.


Get tuple data in an array containing only one element from another tuple

You don't need parenthesis around the conditions in your if statements
if x in y and another_x in y is the same as if (x in y) and (another_x in y)

Use list comprehensions when possible see PEP8#202

Use intersection of sets to get how many elements occur in both tuples
If duplicated don't matter (as they do not in your code) it is possible to convert the tuples into sets and check if the intersection between the sets are 1 (Meaning there is only 1 element that occurs in both) Like @Maarten Fabré suggested

JUDGE = (5, 12, 24)

def valid_bet(bets):
    return [bet for bet in bets if len(set(bet) & set(JUDGE)) == 1]
    # return [bet for bet in best if len(set(bet).intersection(set(JUDGE))) == 1]
    # set_a & set_b == set_a.intersection(set_b)

if __name__ == "__main__":
    bets = [(3, 12, 24, 29, 30),
            (3, 13, 18, 19, 22),
            (1, 11, 16, 17, 22),
            (3, 4, 5, 16, 30),
            (1, 11, 15, 20, 24)]
    print(valid_bet(bets))


A couple notes:

I would use classes instead of ids for the nested links. I don't know if it's faster to search the DOM for all elements with a specific class, but it looks cleaner and doesn't require you to create unique ids for each element:

$('a.nested-trigger').click(...);

I would also use classes for the icons, as it's less expensive than replacing DOM nodes:

HTML:

CSS:

.oc {
  position: relative;
  right: 10px;
  display: inline-block;
  width: 16px;
  height: 16px;
}
.collapsed {
  background: url(icons/bullet_add.png);
}
.expanded {
  background: url(icons/bullet_take.png);
}

JS:

$(this).next("span").removeClass("collapsed").addClass("expanded");

This is related more to the UX of your demo but I would make the icons themselves clickable as well, because they're big enough to look like buttons, and they overlap part of the node.


Return Function Pointer based upon String

You could create a table mapping strings to functions:

typedef struct {
    char* name;
    FP    func;
} FP_mapping;

FP_mapping FP_map[] = {
    { "str1", fun1 },
    { "str2", fun2 },
    { NULL, NULL }
};

Then iterate over the array:

static FP getFunction1(char* name)
{
    for (int i=0; FP_map[i].name != NULL; i++)
    {
        if strcmp(FP_map[i].name, name)
        {
            return FP_map[i].func;
        }
    }
}


Interesting question,

I am not sure there is such a thing as over-use of underscore, and what the drawback would be. I think that code looks okay from that perspective.

However, from a once over:

deserialize as a function name is unfortunate, especially since it does not deserialize JSON
profileJSON is equally unfortunate, it does not contain JSON
This seems out of order, and a roundabout way of doing things:

current.text = []
acc.push(current)
current.text.push(
  _(el).pick('version', 'text', 'language')
)

could be more like

current.text = [ _(el).pick('version', 'text', 'language') ]
acc.push(current)

You are wrapping el 3 times, wrap it once and assign it to a variable, perhaps that is what your colleague meant?
You call _(el).pick('sequence', 'textType') twice, again you should have cached this, see above
acc and el are meaningless variables and don't give me any insight as to what is inside productText


Small DSL: Converting JSON to MSSQL query

Escaping and SQL injections
One of the major problems in the presented code is that the code is vulnerable to SQL injection attacks and does not properly sanitize, validate and escape the field values.
For example, if a last_name contains a single quote, for example O'Reilly:
{
    "field": "last_name",
    "operator": "NEQ",
    "value": "O'Reilly"
},

The generated query would be:
SELECT * FROM table WHERE  ( first_name = 'Dixie') AND ( ( last_name != 'O'Reilly') OR ( middle_name = 'Sam') )

which is syntactically incorrect query and would raise an error if executed (which may be a sign of not properly sanitized inputs for a potential "bad" user).
Then, we can try:
{
  "endpoint": "rfc",
  "expression": [
    {
      "field": "first_name",
      "operator": "EQ",
      "value": "' or '1' = '1"
    }
  ],
  "limit": "2"
}

which will result into:
SELECT * FROM table WHERE  ( first_name = '' or '1' = '1')

which will match everything in the table.
Possible to solution to the problem
A possible solution to the problem would be to use parameterized queries and named placeholders where names would come from the field parameter (assuming it's unique). Something along these lines (please test thoroughly):
def process(data, parameters={}):
    """
    :param data: JSON Object (dict).
    :param parameters: dict.
    :return: where clause (str) built from data
    """
    where_clause = ""
    if isinstance(data, list):
        for part in data:
            if part not in LOGICAL_OPERATORS:
                where_clause += " ({}) ".format(process(part, parameters))
            else:
                where_clause += process(part, parameters)
    elif isinstance(data, dict):
        where_clause += " {} {} %({})s ".format(data["field"], COMPARISON_OPERATORS[data["operator"]], data["field"])
        parameters[data["field"]] = data["value"]
    elif isinstance(data, str):
        return data
    return where_clause

def main():
    expression = get_data("other.json")["expression"]
    parameters = {}
    where_clause = process(expression, parameters)

    return "SELECT * FROM table WHERE {}".format(where_clause), parameters

Is there an already builtin in out there for this?

I would look into using ORMs like SQLAlchemy to generate queries. This way you would not have to deal with SQL at all, working with Python abstraction layer only.


You can collapse the summation using sum():

sum_dims = sum((data_x[dim] - data_y[dim]) ** 2
               for dim in range(dimensions))

Or, what if you would "zip" the x and y:

sum_dims = sum((x - y) ** 2 for x, y in zip(data_x, data_y))


script to check sequence number in a binary file

Style

Python comes with an official style guide (often just called PEP8) which is commonly accepted among Python programmers. Since you said you are new to Python, I wholeheartedly recommend to read and follow it.

E.g. one of the recommendations of the style guide is to indent code by 4 spaces per indentation level, while you have a mix of 2 and four spaces. Even if you decide to stick with 2 spaces: be consistent!

Another very widely accepted convention is to have no whitespace around = if used in keyword-arguments to functions, e.g. instead of

def is_sequence_missing(filename, packet_size = 5392, sequence_offset = 11):

use

def is_sequence_missing(filename, packet_size=5392, sequence_offset=11):

Outdated Python

Your code uses some parts of the Python language which have become a bit "rusty", i.e. have been superseded in later versions of the language. Especially in the light of soon to come end-of-life of Python 2.7, I would highly recommend to have a look at Python 3 or at least use "more current" features of Python 2.7.

A few examples:

Command-line arguments

Your code uses getopt to parse command-line arguments. getopt has been superseded by optparse, which in turn has been marked as deprecated starting from Python 2.7 to be replaced by argparse (see also this SO post from 2010!) from there on. Apart from being easier to use, argparse will e.g. also generate and show usage instructions if the user fails to give the correct arguments.

Further reading: The official and reasonably comprehensive tutorial on argparse.

String formatting

String output is generated using the old % formatting. As of Python 2.6, the recommended way is to use str.format for string formatting. If you happen to have access to Python 3.6 and later, also so called f-strings are available to you which make the whole thing even more comfortable. An example from your code:

"not matching expected: 0x%x received: 0x%x at 0x%x"% (counter, v, i)
"not matching expected: 0x{:x} received: 0x{:x} at 0x{:x}".format(counter, v, i)  # Python 2.6+
f"not matching expected: 0x{counter:x} received: 0x{v:x} at 0x{i:x}"  # Python 3.6+

Further reading: This blog post has a nice comparison of all three variants and their possibilities.

General recommendations

Variable definition

Usually it's always a good idea to define your variables as close as possible to where they are needed, and also arguably define one variable per line. This helps to avoid unused or uninitialized variables, although the later part is not so critical here in Python as it would be e.g. in C or C++.

Documentation

Also not strictly specific to Python: Do yourself (and possible also others) a favor and document your code. Maybe in a few months time where you have done something different you will (have to) come back and wonder why the default value for sequence_offset is 11. Python has a feature called docstrings which are also described in the style guide (and in more detail in PEP 257) and are very commonly found in Python code. docstrings are essentially """triple quoted strings""" placed immediately after the function definition, trying to describe what to expect from the function. As an example:

def is_sequence_missing(filename, packet_size=5392, sequence_offset=11):
    """Check file for gaps in the sequence number

    read up binray data from filename and check for ascending
    sequence numbers starting sequence_offset (default: 11) bytes away
    from the sentinel value
    """
    # rest of the code here

Documentation written using docstrings will be picked up by Python's built-in help(...) as well as by most Python IDEs.

That's all for now. Maybe I can spare some time tomorrow to have a closer look at the actual algorithm. Edit: See the second answer for a more detailed feedback on the actual algorithm.


Usage of Stack

Don't use a Stack. This class is very old, it's thread safe (which you don't need) and achieves it by synchronizing the push and pop methods, which will have an impact in performance.

I would use ArrayDeque. By default it's initialized with size 16. To reduce number of re-allocations, allocate a larger size, perhaps ou can guess how many elements you'll need based on the size of the string. For example:

Queue<Character> queue = new ArrayDeque<>(str.size()/2);

Boxing of char

Note that each time you push/pop from the queue, you are boxing and unboxing char (to Character). For ultimate performance, create a char[] queue, but then you'll have to manage resizes and pointers to the top element yourself.

Fail fast

Consider that the input is {(])}. When finding ], your program can already know that the string is invalid and stop iterating. This will make the processing of invalid inputs potentially much faster.
So what about replace this:

else if (!stack.empty())
{
  top   =   stack.peek();
  if (top == ch)
    stack.pop();
  else
    stack.push(ch);
  }
  else if (stack.empty())
  {
    stack.push(ch);
  }
}
else if (stack.empty())
{
  stack.push(ch);
}

by:

else if (!stack.empty())
{
  top   =   stack.peek();
  if (top == ch)
    stack.pop();
  else
    return false; // quit
  }
}
else
{
    return false; //quit
}

I didn't test and I might be missing something, but it looks that as soon as you have an char not matching the expected closing parenthesis, you can  conclude that it's invalid.

My suggestion

This has all the previous points applied and runs much faster:

public boolean isValid(String str) {
char[] stack = new char[str.length()];
int p = -1;

for (int i = 0; i < str.length(); i++) {
  char ch = str.charAt(i);

  if (ch == '(') {
    stack[++p] = ')';
  } else if (ch == '[') {
    stack[++p] = ']';
  } else if (ch == '{') {
    stack[++p] = '}';
  } else if (p >= 0) {
    char top = stack[p];

    if (top == ch) {
      p--;
    } else {
      return false;
    }
  } else {
    return false;
  }
}

return p < 0;
}

EDIT: Benchmarks

I'm adding the results of benchmarks done with JMH with some different solutions to show how performance is impacted.

I used one valid input: ([[{{([[{{[[[[]]]]}}]])}}]]) and one invalid input: ([[{{([[{{[[[[]]]]}}]]})}}]]).

Parameters of the benchmark:

# Warmup: 5 iterations, 1 s each
# Measurement: 5 iterations, 1 s each
# Benchmark mode: Average time, time/op (nanoseconds)

Results:

Benchmark               (input)  Mode  Cnt    Score    Error  Units
Benchmark.finalSolution   valid  avgt    5   67.468 ±  1.411  ns/op
Benchmark.finalSolution invalid  avgt    5   53.832 ±  1.543  ns/op

Benchmark.toCharArray     valid  avgt    5  241.692 ± 11.705  ns/op
Benchmark.toCharArray   invalid  avgt    5  261.955 ±  6.192  ns/op

Benchmark.original        valid  avgt    5  245.888 ±  3.329  ns/op
Benchmark.original      invalid  avgt    5  265.483 ±  3.312  ns/op

Benchmark.useArrayDeque   valid  avgt    5  100.597 ±  1.621  ns/op
Benchmark.useArrayDeque invalid  avgt    5  102.695 ±  0.659  ns/op

Benchmark.useLinkedList   valid  avgt    5  180.679 ±  4.395  ns/op
Benchmark.useLinkedList invalid  avgt    5  190.591 ±  4.010  ns/op


My query is pretty quick now, but as this grows is NOT IN the most efficient solution for this?

I expect it would be quicker if you had an indexed Status field in the Leads table (so that records in the LeadsDead table had a corresponding Status=Dead in the Leads table); and quicker still if Status were a clustered index, so that all the leads with a given Status were contiguous in the Leads table.


Concatenating strings into a fixed-size char array in C

Back in the day, even before the official C89 standard was released, people were asking "why the hell does strcat not return the end pointer?"

I believe that the C standards committee, in a fit of pique, "doubled down" on their mistake and made a willful effort not to remedy it, simply because it would be admitting that they made a boneheaded error in the first place. It's been a sore spot ever since, and now they've switched to strcat_s which doesn't return a pointer at all, which leaves the problem unresolved, and leaves strcat as an unloved and underused function.

Also pretty much from the get-go, there were libraries of string functions that provided an alternative version of strcat that did the right thing and returned a pointer to the end of the string. Often, those functions were named strecat or strcate, with the e meaning "return a pointer to the end." There were also strecpy and various strne___ functions. (IIRC, Borland provided them with their Turbo C++ compiler.)

Considering that you know the size of the buffer, I'd suggest you simply write (or search for) a version of strnecpy and strnecat and maintain your own count of characters remaining.

I suppose you could maintain both pointer and count in static variables, and accept a NULL destination to mean "use the previous values". You should read up on strtok first, though, to understand the implications - in general that sort of code isn't thread-safe, interrupt-safe, etc. (strtok has nothing to do with strcat but it's defined to have similar "use the last string" behavior, and usually comes with a bunch of caveats in the documentation.)

register char *p = buffer;
register char *pe = buffer + sizeof(buffer);

p = strnecpy(p, start_str, pe - p);

for (i = 0; i < argc; ++i) {
    if (i) p = strnecat(p, sep_str, pe - p);
    p = strnecat(p, argv[i], pe - p);

    if (p >= pe - 1) break;
}

Or, if a NULL destination means "re-use the last pointer and size info" you might have:

strnecpy(buffer, start_str, sizeof(buffer));

for (i = 0; i < argc; ++i) {
    if (i) strnecat(NULL, sep_str);
    if (strnecat(NULL, argv[i]) >= buffer + sizeof(buffer) - 1) break;
}

FWIW, I actually think this last bit would be a bad idea, simply because it relies so very much on hidden behavior. It's not at all clear, just reading the code, that there's a bunch of secret-squirrel things happening in the background. With a C++ string class, that's okay - with C strings, secret accounting is surprising.


Use of Ninject and an injectable DataLayer in MVC3

One tip I would give is to use the "Ninject for ASP NET MVC 3" NuGet package. Install that package into your project. After doing this, you should find a file named "NinjectMVC3.cs" located in the "App_Start" folder. In this file, look for a method named RegisterServices():

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<IDataLayer>().To<MockDataLayer>().InRequestScope();
}

This sets up a MockDataLayer to be returned for each separate web request. This ensures that MockDataLayer is disposed when the web request is completed. Now, when you want to create an instance of the data layer, use MVC's built-in DependencyResolver class:

var dataContext = DependencyResolver.Current.GetService<IDataLayer>();


Sending an SMS message using zenoss and python

The one coding standard is
PEP8 and indeed it would
be good if at least names are in common Python spelling, not like
Java.  E.g. it should be join_path (if you really want to rename
it), not joinPath, etc.
The names vs. positional arguments for format are a bit
inconsistent; I'd say that unless you have a lot of arguments you can
usually get by with unnamed positional instead, i.e.
"{} {}".format(...).
I don't like the tendency for stripping out characters in names
unnecessarily:  hdrs and evt aren't exactly much saving compared
to headers and event.
The import for os.path is mentioned twice, that could also be just
one line instead.
'{0}'.format(...) should probably be str(...) if you need the
string conversion.

Now for the structure I see a couple of things.

The try/catch block looks like it's not very much improving on
what the Python interpreter would print by default.
"Declaring" the isInProduction variable is not needed and
considering it's set to True immediately it looks like it's not
needed at all.  Or the indentation is wrong, in which case it should
instead be immediately initialised like
is_in_production = event['prodState'] == 'Production'.
Actually, initialising variables this way like again with
alertContactContent is just not useful in Python.  I'd likely move
reading the file and splitting the content into a function and use
that instead (like
alert_contact_content = read_and_split(ALERT_POINT_PATH) or so).
Again, the body of the innermost for-loop looks like it should be a
function instead, like create_auth_manager() and should only be
created once - unless I'm missing something all of those
password_manager instances are the same, so it makes sense to reuse
them instead.
I don't understand the break.  Or the comment on it.  At all.

Basically reading all of this nested stuff would be much easier if it
was structured, e.g. using functions or so.


Activating Lightbox on HTML elements with the has-lightbox class

Objects not classes
In JavaScript there are no classes only Objects. The token class is just an alternative syntax (often referred to as syntactical sugar) for defining an Object.
Many ways to create objects
The following shows two very similar objects defined using class syntax and standard syntax
class Foo {
   constructor() { this.bar = "A" }
   poo() {}
}

function Foo() { this.bar = "B" }
Foo.prototype = { poo() {} }

You can also define the object as...
function Foo() {
   this.bar = "C";
   this.poo = function(){};
}

or...
const Foo = {
    bar: "D",
    poo() {},
};

or...
const Foo = () => ({
    bar: "D",
    poo() {},
});

...and there are many more ways to define an object.
Which to use
Which you use is very dependent on how you use the object.

Is there more than one instance?
What is the life time of an instance?
Do you need to extend the object? (polymorphic)
What level of encapsulation is required?
Do you need an inheritance model?
How do you wish to instantiate the object?
What is the legacy support requirement?

To know the language you must be proficient in all its forms, and know what is the appropriate code to use.
Questions

Is this something that would benefit from being a class?

No as there are no classes in JavaScript.

A LightboxCollection class for example? That has an array Lightbox?

You can create a collection from an Array. Assuming you are using only a single instance. It has all the functions that an array has plus what ever you want to add. Eg add
const LightboxCollection = (() => {
    return Object.assign([],{
         add(lightBox){ this.push(lightBox) },
    });
})();

Or encapsulate the array, so you can maintain the array state (vet items and expose only functions that you need)
const LightboxCollection = (() => {
    const items = [];
    return Object.freeze({
         add(lightBox) { lightBox instanceof LightBox && items.push(lightBox) },
         get length() { return items.length },
         set length(len) { items.length = len < items.length ? len : items.length },
         forEach: items.forEach.bind(items),
    });
})();


The arithmetic mean is not necessarily a closed operation: the mean of integers is, in general, not an integer.  Therefore, you should provide a specialization of the template for integer inputs.


Handling arguments in a Python-like range() function in JavaScript

I like the edited version.  I'd suggest just one small change:

const range = (...args) => {
  if (args.length < 1 || args.length > 3) {
    throw new Error('This function takes between 1 and 3 arguments')
  }
  let [start, stop, step = 1] = args
  ;[start, stop] = (stop === undefined) ? [0, start] : [start, stop]
}

Aside from reducing the visual clutter of the if statement, in general I find that expressions (which always execute) are easier to reason about than branching statements, even though the resulting logic is the same.


Pick what maintenance check required for game

You can get rid of your duplications by using loops. This comes without any performance hit in this case. Again, the limits have to be defined outside of the function, but this function can deal with a variable number of arguments, just like the numpy solution below.

limits = amax, bmax, cmax, dmax

def get_check_loop(*args):
    # assert len(limits) == len(args)
    for x, limit in zip(args, limits):
        if x == 0:
            i = len(args) - 1
            for t in reversed(args):
                if t - limit < 0:
                    return i
                i -= 1
    return -1

I had to use the slightly ugly manual decreasing of the inner loop variable, because enumerate is not an iterable, at least not as understood by reversed.

Ok, I found a numpy solution for this. It is slower than your approach, but shorter. Specifically, it is about 50 times slower (~10\$\mu\$s instead of ~200ns per call, on my machine).

First, I took your code and put it into a function. I left the max values outside of it. (This makes it slightly slower, because looking up global variables is slower. On the other hand, re-defining variables every call is also costly. In the end the two seem to cancel out.) I also changed the code to return numeric values (because that is easier for the numpy code I wrote). You can always use it as an index into the list ["a", "b", "c", "d", None], where the last entry is for the case that none of the values is zero, which I also included:

amax = 500
bmax = 1000
cmax = 2000
dmax = 10000

def get_check(a, b, c, d):
    if a == 0:
        if d - amax < 0:
            return 3
        elif c - amax < 0:
            return 2
        elif b - amax < 0:
            return 1
        else:
            return 0
    elif b == 0:
        if d - bmax < 0:
            return 3
        elif c - bmax < 0:
            return 2
        else:
            return 1
    elif c == 0:
        if d - cmax < 0:
            return 3
        else:
            return 2
    elif d == 0:
        return 3
    else:
        return -1

For the numpy approach we need to realize that if one of the variables is zero, then we need to subtract that variables max interval from all arguments. For example, if x = a, b, c, d = 351, 0, 304, 1500, then we need to have a look at x - bmax < 0 and choose the index of the last one that is below zero.

In code this is:

import numpy as np

bounds = np.array([500, 1000, 2000, 10000])

def argmax_last(x):
    """
    Returns the last occurrence of the maximum value in x.

    From http://stackoverflow.com/a/8768734/4042267
    """
    return len(x) - np.argmax(x[::-1]) - 1

def get_check_np(*v):
    if any(x == 0 for x in v):
        return argmax_last(v - bounds[np.argmin(v)] < 0)
    return -1

np.argmax (np.argmin) returns the index of the first maximum (minimum) in the passed array. argmax_last returns the last index where the value is the maximal value in that array. Examples:

>>> max([4, 1, 2, 4, 3, 2])
4
>>> np.argmax([4, 1, 2, 4, 3, 2])
0
>>> argmax_last([4, 1, 2, 4, 3, 2])
3

Note that the numpy function is more easily extendable (it only cares that bounds is at least as long as the position of the zero in the input arguments).


I'd propose a 3rd way: Make it a method:

def client
  @client ||= HTTPClient.new
end

def read_page(url)
  client.get(url).body
end

There are some advantages to this:

You get the same scoping as with a constant (which you wouldn't get with a $-global), as well as visibility modifiers.
It's flexible. You can return anything that fulfils the API contract. It's the Dependency Inversion Principle (the D in SOLID) of relying on an abstraction. It also allows you to stub/mock the method and return value in tests much more easily.
If you want it to be shared across instances, use object composition (e.g. PageReader.new(existing_client)); if you want different instances to have their own client, use the implementation above.

I'd agree that constants should for be kept "primitive" - or at any rate, they should be data-only. E.g. a Hash, while not "primitive" per se, used as constant lookup table is fine. But a HTTP client instance is a bit much.

A 4th option is to make it a singleton, which is more or less a "constant instance". It'd probably require you to wrap (or extend) the HTTPClient class, e.g.:

require 'singleton'

class Client
  include Singleton

  def initialize
    @client = HTTPClient.new
  end

  def get(url)
    @client.get(url)
  end
end

# ...

def read_page(url)
  Client.instance.get(url).body
end


Roman letter to value map

if (!(num % 1000)) { roman += "M"; num -= 1000; }
else if (!(num % 500)) { roman += "D"; num -= 500; }
else if (!(num % 100)) { roman += "C"; num -= 100; }
else if (!(num % 50)) { roman += "L"; num -= 50; }
else if (!(num % 10)) { roman += "X"; num -= 10; }
else if (!(num % 5)) { roman += "V"; num -= 5; }
else if (!(num % 1)){ roman += "I"; num -= 1; }

You should be using a map here to store the roman numeral values and their corresponding characters:

var romanCharacterMap = {
    "M": 1000,
    "D": 500,
    ...
}

With this, you can easily add on more letters if you ever felt like expanding it. Now, here is what your code would look like there:

while (num > 0) {
    for(var romanCharacter in romanCharacterMap) {
        var value = romanCharacterMap[romanCharacter];
        if(!(num % value)) {
            roman += romanCharacter;
            num -= value;
            break;
        }
    }
}

Then, to OOP this code up, you could move this function and the new map to an object to keep things together:

var RomanNumberalConverter = {
    ...
}

Then, the map won't be created every time the function is called; it will be created and referenced once.

Moar regexes... moar!

In this loop:

  for (var i in translationMap) {
    roman = roman.replace(new RegExp(i,'g'), translationMap[i]);
  }

Every iteration, you are creating a regex for every entry in the map. However, every time this function is called, the same regexes are created because that map is the same every time.

To speed things up, try creating the regex once and keeping it in the map that is also in this RomanNumberConverter object:

translationMap: {
    DCCCC: {
        replace: "CM",
        regex: /DCCCC/g
    },
    ...
}

Your code will now be faster because a new series of regexes doesn't have to be created every function call.


It looks like you're basically writing Entity Framework. If so...why not use Entity Framework?

It also looks like in addition to your rewriting of Entity Framework, you're writing the whole generic repository pattern + unit of work pattern that people like to add on top of it. I would strongly recommend against that. It ends up being a lot of extra code and very little or negative benefit, considering that EF/your ORM pretty much uses the repository pattern anyway (if you have a DataContext structured like EF's).

On top of all of that, you're also writing your own custom dependency injection/IOC container now with your static dictionary. The generic type problems you have are based on your unit of work problem. See my answer on this CR post for details.

Instead of writing everything from scratch, I would recommend using vanilla EF with no repository pattern, along with an already-existing IOC container, and wire up DI the plain old vanilla way the Web API site recommends or the way Mark Seemann recommends if you're opinionated about DI.


Method to determine redirect after login

You are correct in feeling uneasy about the hardcoded URLs: I would put them in a config file.

By hardcoding them you will be forced to rebuild the project should you change to a different server while using a configuration file you can change it whenever you want and it will get picked up automatically.


Distinct unordered pairs of an array which satisfy a condition

Scope

    int sum = 0, val = 0;
    for(unsigned int i = 0; i < N; i++)
    {
        for(unsigned int j = i+1; j < N; j++)
        {
            if(a[i] < a[j])
            val = 1;
            else
            val = 0;

            sum = sum + val;
        }
        F[i] = sum;
        sum = 0;
    }

This won't affect speed, but this would be more simply written

    for (unsigned int i = 0; i < N; i++)
    {
        int sum = 0;
        for (unsigned int j = i+1; j < N; j++)
        {
            int val = 0;
            if (a[i] < a[j])
            val = 1;
            else
            val = 0;

            sum += val;
        }
        F[i] = sum;
    }

Now we only declare variables in the scope in which they are used.

Don't create unnecessary variables

But we can actually do even better

    for (unsigned int i = 0; i < N; i++)
    {
        F[i] = 0;
        for (unsigned int j = i+1; j < N; j++)
        {
            if (a[i] < a[j])
            {
                F[i]++;
            }
        }
    }

We don't actually need val or sum at all.

There is the slight possibility that constantly calculating the memory location of F[i] would add time, but I would expect any decent compiler to only set it once.  The rest of the time it will work with a register.

This also saves some time in that it only adds if we're incrementing by 1.  If not, this does nothing.  That has the same effect as adding 0 but with fewer instructions.  Of course, your compiler may have already optimized that out.

Many recommend always using the block form of control structures, even when there's only a single statement.

Don't forget what you know

In this case, you are working with segments going from a point in the array to the end.  But you are looping from the beginning to the end.  What happens when you loop from the end to the beginning?

    for (int i = N - 1; i >= 0; i--)
    {
        F[i] = 0;
        for (unsigned int j = N - 1; j > i; j--)
        {
            if (a[i] == a[j])
            {
                F[i] += F[j];
                break;
            }
            else if (a[i] < a[j])
            {
                F[i]++;
            }
        }
    }

Now when we encounter two equal array entries we can stop looping.

    int count = 0;
    for(unsigned int i = 0; i < N; i++)
    {
        for(unsigned int j = i+1; j < N; j++)
        {
            if(F[i] + F[j] >= K)
            count++;
        }
    }

Same kind of insight here.

    int n = N - K / 2;
    unsigned int count = 0;
    for (unsigned int i = 0; i < n; i++)
    {
        int remainder = K - F[i];
        if (remainder <= 0)
        {
            // if F[i] >= K, every remaining entry will work
            count += N - i - 1;
            continue;
        }

        for (unsigned int j = N - remainder; j > i; j--)
        {
            if (F[j] >= remainder)
            {
                count++;
            }
        }
    }

By precalculating the remainder, we save some math in the inner loop.  And we can save some iterations of the inner loop (if remainder is too high, there is no way to add up to it at the end of the loop).  But more importantly, we can check remainder against 0.  Because if the remainder is less than or equal to zero, we can immediately say that every remaining entry will work.


Look into the itertools library in general, for list-and-sequence-manipulating commands. You're looking for a way to "flatten" a list of lists; itertools calls this itertools.chain.

def multiple_get(targets):
    return list(itertools.chain.from_iterable(single_get(target) for target in targets))

However, Python can do it natively as a nested list comprehension:

def multiple_get(targets):
    return [r for target in targets for r in single_get(target)]


I would advise you to count neighbours from alive points, not for cells to be checked. Null a 100x100 int array Neighbours. For every alive cell add +1 into every neighbouring cell in Neighbours. After the pass you have number of neighbours for the every cell, but time used is about 1/4 at most, because you saved the time not counting neighbours for zero cells.
You are taking left neighbours for utmost left cells, for example. Out of boundaries! You are blocking this by taking a function and modulo and thus making the toroid out of plane, but thus you are counting much longer - division or modulo are slow, functions even more slow. Simply count neighbours normally for the field except boundaries, otherwards for the four sides and four corners. More to write, but less to count later.
If you want a shorter code, you could use a help arrays ( I have invented them for myself in 1978)

// neighbor-vectors in xy coordinates clockwise from algebraic x axis.
int [8] dx={1,1,0,-1,-1,-1,0,1};
int [8] dy={0,-1,-1,-1,0,1,1,1};

and in counting neighbours for a cell do:

if(cell[x,y]>0)
for(i=0;i<8;i++){
   x1=x+dx[i];
   y1=y+dy[i];
   if(x1>=0 & x1<100 & y1>=0 & y1<100){
       neighbours[x1,y1]++;
   }
}

Count the time spent for different activities, for not to waste time on optimizing part that takes 0.1% of time.

So you can throw off many objects, not to create them at all. Only hold 2 desk in 2x100x100 array - each time one will be active, the other will be old.  You can even count neighbours and later make living/dead cells on the same desk. No garbage collection.


You are mixing various things here. For some values you use the try/catch and for others the TryParse. I think you should stick to one of them.

What I also don't understand is why you are checking whether this is true string.IsNullOrEmpty(TB_Discount.Text) and then try to parse it anyway int.TryParse(TB_Discount.Text)?

Here is what you can do:

Create a property for each value:

public int TotalInv
{
    get
    {
        int totalInv;
        return int.TryParse(TB_TOTAL_INV.Text, out totalInv) ? totalInv : 0;
    }
}

public int PaidCash
{
    get
    {
        int paidCash;
        return int.TryParse(TB_PAID_CASH.Text, out paidCash) ? paidCash : 0;
    }
}

public int Discount
{
    get
    {
        int discount;
        return int.TryParse(TB_Discount.Text, out discount) ? discount : 0;
    }
}

For the reminder too:

public int Reminder
{
    get
    {
        return PaidCash - TotalInv - Discount;
    }
}

Then when the text changes you can update the text box with only one line:

private void TB_PAID_CASH_TextChanged(object sender, EventArgs e)
{
    if(PaidCash < TotalInv)
    {
         // todo: show message...
    }
    TB_REMAINDER.Text = Reminder.ToString();
}


Note: This answer is based on Java 8 and newer. This does not apply to Java 7, as Java 7 does not support Lambda
For starters, your test function is wrong in multiple places:
boolean test(function someSortFunction){//This is not how you pass functions
    int n; //this has to be initialized
    for (int i=0; i<=n ; i++) {//Depending on how n is used, you may have to use < instead of <=
        int[] A = generateArray()//Missing semi-colon
        if (isSorted(someSortFunction(A)) = false) {//Comparing is done with ==, not =
            return false;
        }
    }
    return true;
}

In order to pass a function, you can either use Consumer<Void>, Supplier<Void>, Predicate<Void> or Function<Void, Void> (don't use Void as the type if you have return values)
Supplier defines return type, Consumer defines input type, and function both. Meaning:

Use Predicate when you have a boolean return type with arguments
Use Supplier when you have a return type
Use Consumer when you have an argument
Use Function when you have both an argument and a return value

Since you have both arguments and return types, use Function. The first argument you give it is the argument it receives, and the second is the return type. For an instance, in your case, this would be:
boolean test(Function<int[], int[]> someFunction)

Using Function requires calling apply to execute the method:
int[] res = someFunction.apply(input);

Before I move on, I'd like to take a second to mention naming conventions. In Java, class names always start with an upper case letter. Instances and functions start with a lower case letter. So your classes would be:
public class ManyFunctions {...}
public class MainClass {...}

Passing methods are not done using someClass.someFunction. In your case, since you are not using static methods, you need to create an instance:
ManyFunctions functions = new ManyFunctions();

now, you pass the functions:
test(functions::mergeSort);

if you make the methods static, you can just skip the instance and use the class name directly:
test(ManyFunctions::mergeSort);

So your class would be:
class MainClass{
    public static void main(String[] args){
        ManyFunctions manyFunctions = new ManyFunctions();
        test(manyFunctions::mergeSort);//Notice the missing "()" and arguments
        test(manyFunctions::otherSort);

    }

    boolean test(Function<int[], int[]> someSortFunction){
        int n = 10;//THIS HAS TO BE INITIALIZED! Otherwise, it won't compile
        for (int i=0; i<=n ; i++) {
            int[] A = generateArray();
            if (isSorted(someSortFunction.apply(A)) == false) {//comparing is done with ==
                return false;
            }
         }
         return true;
    }
}//Don't know if it was a copy-paste problem or not, but you had a missing bracket


Split Circular linked list into two halves

This is an interesting problem! I don't know that I've ever needed to split a linked list before. I'd love to know whether this is for solving a real-world problem or if you're just doing it for fun. Here are some thoughts on it.

Naming

The first thing I'd do to improve this code would be to fix the naming. That's almost always a good first step for a code review, but in this case, I think it's imperative as some of your methods are deceptively named, implying they do something they do not. For example, the split_list() method does not split the list. Instead, it finds the middle node in the list. It should be called something like get_middle_node(). You even have a comment next to it saying that it does something other than its name. That's a big clue that it's named incorrectly.

Inside the method, there are 2 pointers named slow_ptr and fast_ptr. I had to read the code about 5 times before I understood that the "fast" pointer was incrementing by 2 and the "slow" pointer was incrementing by 1. The names don't even make sense, as pointers don't have a speed. They both access their data in the same amount of time! I would rename them to something like advance_by_1 and advance_by_2. And I would probably also leave a comment explaining that when advance_by_2 hits the head, advance_by_1 will be pointing to the mid node, because that's a fairly clever way of finding the middle node. I don't think it's so clever that you shouldn't do it, but I think you should clarify with a comment.

The name of print_split_lists() is accurate, but I was confused because I thought a caller would end up getting back 2 lists, or that the method would need to be passed the second list, or something. The method doesn't actually split the list - it makes some temporary variables that act like 2 lists, and then prints those. And if I'm not mistaken, it leaves the list in a bad state. That's confusing to me. What would be the use case where I would want to print a single list as 2 lists, but then not actually end up with 2 lists? This seems like a method that's not needed. I'd think you'd want to have a method to split the list in 2 (and return 2 lists), and then just call print_list on each of those 2 new lists.

You ask:

  How can I write a function which returns two lists and how to use it in main() function?

There are a couple of ways to handle this. You can:

Write a function that finds the middle node, constructs a new list with the second half of the old list, and sets the old list to be the first half
Write a function that creates 2 new lists and fills them with the 1st and 2nd half of the original list, respectively.

Let's assume for now that version 1 is acceptable. I'd do it like this (not tested) :

void circular_linked_list::split_list_at_middle(circular_linked_list& secondHalf)
{
    Node* tail = find_tail_node();
    Node* mid = find_middle_node();

    // Move the second half of the list into a new list
    second_half.head = mid->next;
    tail->next = second_half.head;

    // Set our list to only be the first half
    mid->next = head;
}

Note that I left out the code to check for empty lists and lists with only a single node. You'll need to handle those, too.

Then in main(), you call it like this:

circular_linked_list secondHalf;
originalList.split_list_at_middle(secondHalf);
std::cout << "First half of list \n";
originalList.print_list();
std::cout << "Second half of list \n";
secondHalf.print_list();

Performance

One of the main weaknesses of linked lists is random access. If you need to find the nth node, you need to iterate over n nodes to get there. So finding the middle node will always require iterating over (list length) / 2 nodes. And finding the tail node always requires iterating over (list length) nodes. Unless you know you'll need to do those 2 things and prepare for it.

One common way to make list insertion very fast (O(1)) is to keep not only a head node, but a tail node. (Some people will just keep a tail node, and then have a method to return the head node that just returns tail->next. It's not worth the tradeoff in my opinion, but you may disagree.) Now an insertion at the end of the list just involves:

newNode->next = tail->next; // or just head
tail->next = newNode;

No searching the list for the end first.

So why can't we do the same thing with the middle node? If you keep a midNode pointer and keep track of the length of the list, you can do something similar. Every time you do an insertion, you increment the length counter. Every time you do a deletion, you decrement it. When the length counter is even during an insertion, increment the midNode pointer to point to midNode->next. If you want to keep it up-to-date during deletions, you need to have a doubly-linked list or you need to walk the list and find the previous node. It is often the case that you need to walk the list to find the node to delete, anyway, so that's not too onerous. It's a little trickier on delete because you need to know whether the node you're deleting is ahead of or after the mid node. But it turns out that your class doesn't actual handle deletions!

Handle Deletions

This class doesn't handle deleting a node. That seems like a pretty big thing that a user of this class will want to do. It's fairly rare to want to be able to insert but not remove in a list, so I recommend adding such a method.


Leeetcode - Best time to buy and sell stock to get maximum profit

Your use of whitespace is inconsistent, which makes the code harder to read and understand. There should be whitespace between control flow statements and open parentheses, and there should be whitespace on both sides of operators.

Your comment is noise and should be deleted.

Unless leetcode promises you'll never get a null input, you should check to make sure the prices array is not null.

It's cleaner to check if the array length is < 2 rather than enumerating the cases. Also, your algorithm works correctly without the check, since the loop falls through correctly.

size should be marked as final since it does not change. There's also no real value in storing this in a variable, since it's obvious what prices.length is, and it's not a computed value.

You can use Math.max() instead of doing subtraction and int comparison yourself. It makes the code easier to read.

You can save a comparison in some cases by always doing the subtraction. It's easier to read, and in some cases will be faster.

If you were to make all these changes, your code might look more like:

public int maxProfit(final int[] prices) {
    if (prices == null) {
        return 0;
    }

    int maxProfit = 0;

    for (int i = 0; i < prices.length; i++) {
        for (int j = i + 1; j < prices.length; j++) {
            maxProfit = Math.max(maxProfit, prices[j] - prices[i]);
        }
    }

    return maxProfit;
}

As far as algorithmic performance, you can do this in O(n) time and O(1) space. Walk through the input array one time, tracking the minimum value seen so far and the current best profit. At each step, update those two values.

public int maxProfit(final int[] prices) {
    if (prices == null) {
        return 0;
    }

    int minPrice = Integer.MAX_VALUE;
    int maxProfit = 0;

    for (int i = 0; i < prices.length; i++) {
        maxProfit = Math.max(maxProfit, prices[i] - minPrice);
        minPrice = Math.min(minPrice, prices[i]);
    }

    return maxProfit;
}


Fast "index of minimum" for distances to points on single thread

The major compilers did not really auto-vectorize this, but it can be done manually. For example with AVX, we could do something like (not tested)

int indexOfMin(double pt_x, double pt_y, double pt_z, int n)
{
    __m256d ptx = _mm256_set1_pd(pt_x);
    __m256d pty = _mm256_set1_pd(pt_y);
    __m256d ptz = _mm256_set1_pd(pt_z);
    __m256d xdif = _mm256_sub_pd(ptx, _mm256_loadu_pd(cx));
    __m256d ydif = _mm256_sub_pd(pty, _mm256_loadu_pd(cy));
    __m256d zdif = _mm256_sub_pd(ptz, _mm256_loadu_pd(cz));
    __m256d min_dist = _mm256_add_pd(_mm256_add_pd(_mm256_mul_pd(xdif, xdif),
                                                   _mm256_mul_pd(ydif, ydif)),
                                                   _mm256_mul_pd(zdif, zdif));
    __m128i min_index = _mm_set_epi32(3, 2, 1, 0);
    __m128i index = min_index;
    __m256d dist;
    for (int i = 4; i < n; i += 4) {
        xdif = _mm256_sub_pd(ptx, _mm256_load_pd(cx + i));
        ydif = _mm256_sub_pd(pty, _mm256_load_pd(cy + i));
        zdif = _mm256_sub_pd(ptz, _mm256_load_pd(cz + i));
        dist = _mm256_add_pd(_mm256_add_pd(_mm256_mul_pd(xdif, xdif),
                                           _mm256_mul_pd(ydif, ydif)),
                                           _mm256_mul_pd(zdif, zdif));
        index = _mm_add_epi32(index, _mm_set1_epi32(4));
        __m256 mask256 = _mm256_castpd_ps(_mm256_cmp_pd(dist, min_dist, _CMP_LT_OS));
        // mask256 has the masks as 4 x int64, but we need 4 x int32
        // there's no nice 'pack' to do it, but shufps can extract
        // the relevant floats, and then we can reinterpret as integers
        // mask256 = * D * C * B * A (* is an ignored float)
        __m128 maskL = _mm256_castps256_ps128(mask256);   // * B * A
        __m128 maskH = _mm256_extractf128_ps(mask256, 1); // * D * C
        __m128 maskps = _mm_shuffle_ps(maskL, maskH, _MM_SHUFFLE(2, 0, 2, 0)); // D C B A
        __m128i mask = _mm_castps_si128(maskps);
        min_dist = _mm256_min_pd(min_dist, dist);
        // if the mask is set (this distance is LT the old minimum) then take the current index
        // otherwise keep the old index
        min_index = _mm_blendv_epi8(min_index, index, mask);
    }

    double mdist[4];
    _mm256_storeu_pd(mdist, min_dist);
    uint32_t mindex[4];
    _mm_storeu_si128((__m128i*)mindex, min_index);
    double closest = mdist[0];
    int closest_i = mindex[0];
    for (int i = 1; i < 4; i++) {
        if (mdist[i] < closest) {
            closest = mdist[i];
            closest_i = mindex[i];
        }
    }
    return closest_i;
}

The relevant header to include is <immintrin.h> and to compile you would need to enable AVX with -mavx (GCC, Clang) or /arch:AVX (MSVC).

Most of the code is just subtracting the values from the given coordinate, squaring the difference, and summing the squares. That's not very interesting to discuss, though it plays a significant part in making the code fast. Finding the minimum is more interesting, and is what prevented auto-vectorization. The approach I used is comparing the distance (obviously that was going to be part of it) which results in a bit-mask that is all set where the comparison is true, and then I use that to blend between the "index of best-so-far" and the current index, to conditionally replace values without branching.

Because AVX was targeted instead of AVX2, the simpler approach of using an __m256i for the indexes could not be used. That would have removed the need to extract/shuffle the mask, as it would have already been the right size. With AVX2 there are no 256 bit wide integer operations (well, mostly) so it would not be possible to add 4 to the indexes. It would be possible to do a 256 bit blend by using a floating point type blend, then the blend mask is easy but it just pushes the problem to incrementing the indexes.

Finally at the end there is a small loop to select the best index among the 4 candidates.

The array size must be a multiple of 4, it would not be hard to remove that requirement. 32-byte alignment of the arrays is not required but would be better.

By the way this is related to an SSE2 version that I did a couple of years ago, which used single precision floats.


Aborting a program for invalid floating-point input

There are a couple of issues.

Why is the application pausing for 2 seconds before exiting?  Why not just exit straightaway?  (And if the answer is that you are running this via Windows 'cmd.exe' then you are better off handling the pausing at that level ...)
Given that you do need to pause, then you are better of writing a helper method to do something like "print a message, pause, and exit with a non-zero exit code".  Then use that in multiple places, as required.
You should be setting a non-zero exit code when you exit due to a failure.  This allows the script or whatever that launched the java app to detect the failure and (maybe) do something about it; e.g.  pause so that the user can see the error message ...
The InterruptedException is not a program error, so printing a stacktrace is probably not appropriate.

Figuring out what to do with an InterruptedException exception is not straightforward.  The exception indicates that something (either the user or the application) has interrupted the application, either before or during the sleep.

In this use-case you are just about to exit anyway, so the best strategy is to ignore it an exit anyway.
You need to decide what is a sensible thing to do.  Some possibilities are:

Ignore the interrupt and carry on regardless.
Take steps to cause the application to stop what it was doing; e.g. throw a custom unchecked "stop now" exception.  (You could also call System.exit() directly, but that can also be a bad thing to do, depending on the nature of the code.  For instance, calling System.exit() in a library ... or a webapp ... is a big non-no.)
Punt: reinstate the "interrupted" state by calling Thread.currentThread().interrupt() in the exception handler.  For instance, you might do this if some enclosing code is checking the "interrupted" flag.


How to append ajax return data to a table

You could do:

ajax.callback=function(data){
    var elements = ["ID", "test", "year", "code", "Label", "contents", "test"];

    for (var i=0; i<dataObj[0].data.length; i++){
        var td;
        var tr=document.createElement('tr');

        for (var j=0; j < elements.length; ++j){
            td = document.createElement('td');
            td.innerHTML=dataObj[0].data[i][elements[j]];
            tr.appendChild(td);
        }

        $('#Table').append(tr);
    }
}


Using jQuery you can't make it more DRY than it already is.
I tried encapsulating your code in a function with a foreach statement but it only got uglier and generally less readable.

Using callbacks is a good practice but in this case it made your code scary and reduced the readability.

Unfortunately moving css3 animations is not supported on IE9 & IE8 and I'm assuming that from question that this is an issue.

Below are two implementations of the fade in and fade out functionality with animation-delay for reference.

The first implementation is by using jQuery.

$(document).ready(function() {
  var a = $('#A'),
    b = $('#B');

  // The reason I'm adding the animation delay in javascript and not setting it
  // in css is to demonstrate the control over when the animation starts.
  a.css('animation-delay', '3.5s').addClass('fadeOut');
  b.css('animation-delay', '3.8s').addClass('fadeIn');
});
#A,
#B {
  width: 500px;
  height: 500px;
  position: absolute;
  top: 0;
  left: 0;
}
#A {
  background: red;
}
#B {
  background: blue;
  opacity: 0;
}
.fadeIn {
  animation: fadein 2s;
}
.fadeOut {
  animation: fadeout 2s;
}
@keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
@keyframes fadeout {
  from {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}

The second implementation is without jQuery (Vanilla JS)

  document.addEventListener('DOMContentLoaded', function() {
    var a = document.getElementById('A'),
      b = document.getElementById('B');
    a.style.setProperty('animation-delay', '3.5s');
    a.classList.add('fadeOut');
    b.style.setProperty('animation-delay', '3.8s');
    b.classList.add('fadeIn');
  });
#A,

#B {

  width: 500px;

  height: 500px;

  position: absolute;

  top: 0;

  left: 0;

}

#A {

  background: red;

}

#B {

  background: blue;

  opacity: 0;

}
.fadeIn {
  animation: fadein 2s;
}
.fadeOut {
  animation: fadeout 2s;
}
@keyframes fadein {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
@keyframes fadeout {
  from {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}


Is device mounted? Both UUID and device names accepted

Nice work.  I approve of set -eu, and the script pleases Shellcheck.

Here's the things I'd consider changing.

I think error messages should go to the error stream.  Example:

[ "${#}" -ne 1 ] && { echo "Invalid number of arguments." >&2; exit 1; }
#                                                         ^^^ here

Instead of using the negation operator, I'd replace the form ! test && error with plain test || error like this:

is_block_device "${device_string}" || { echo "The given argument is not a block device." >&2; exit 1; }

The script doesn't work when I use other links to block devices, such as those in /dev/disk/by-label.  I'd fix that by abandoning the /by-uuid/ test, and instead following symlinks until a real file or dangling link is found:

resolve_symlink() {
    f="$1"
    while [ -h "$f" ]
    do f=$(readlink -f -n "$f")
    done
    printf '%s' "$f"
}

is_empty_string "${device_string}" && { echo "The given argument is not a device path." >&2; exit 1; }
is_block_device "${device_string}" || { echo "The given argument is not a block device." >&2; exit 1; }

readonly device_name=$(resolve_symlink "$device_string")

if is_device_mounted "$device_name"
then

Why does is_device_mounted ignore its argument and use $device_name instead?

Minor issue: we assume that the block device name contains no regex metacharacters here:

grep "^${device_name} "

That's probably a fair assumption on a non-weird Linux system; I normally use Awk for robust versions such tests ($1 = $device_name, with a suitable -v option) but I don't know how well that meets your portability goals.

If using grep (without the non-standard -q option), then it's usual to discard the output, and use grep's exit status directly, rather than capturing the output and testing it's non-empty.

Minor/style: I'm not a big fan of using braces for every variable expansion.  I prefer to reserve them for when they are really needed, and that seems to be the usual idiom.


Find the minimum value in a circular list of integers

You can fix the bug, that @Misha pointed out, by changing

    if (input.get(highestIndex) > input.get(lowestIndex)) {
      if (lastCheck) {
        return input.get(lowestIndex);
      }
      return Main.findMinRecursive(input, lowestIndex, highestIndex / 2);
    }

to

    if (input.get(highestIndex) > input.get(lowestIndex)) {
      return input.get(lowestIndex);
    }

because, if the value to the right is greater than the value to the left in the subsection you are searching through, then that subsection is already perfectly sorted in ascending order.

I also think you can achieve a very tiny performance improvement if you don't use so many calls to get(). You can store the values in properties(a.k.a. variables) first, and then use those variables/properties in place of the get(), but it's probably an almost imperceptible performance boost


Exercising in copy constructors and assignment operators

This is reasonably clean and reasonably complete code but I see some things that might improve your code.

Consider making this a template

There is no reason that this data structure should be limited to just storing int values.  Consider reworking it as a templated class to make it more general and to get additional practice.

Implement member functions non-inline

All of those inline functions can increase the size of your code.  If you declare them first and then have out-of-line implementations(at least for the non-trivial functions), it has advantages, especially if you decide to make this a templated class.

Consider making the destructor virtual

By having a concrete destructor rather than a virtual one, you are effectively prohibiting derived classes.  If that's not your intent, making your destructor virtual will make it possible to derive classes from this one.

List the required #include files

By my reckoning, this code requires the following to work:

#include <cstring>
#include <initializer_list>
#include <iterator>
#include <stdexcept>

These are therefore an essential part of the class interface.

Reconsider the use of size_t

Although it's used often in the C standard library, you don't really need it here, and requiring a C-flavored include file doesn't help much in keeping the interface small.  You could use unsigned instead and reduce the number of required include files.

Avoid comparing signed to unsigned

In your operator[], idx is declared as int but _size is size_t so the range check at the top of the function compares signed and unsigned numbers without a cast. Since negative numbers are already eliminated by the first clause, so you could use either a C-style cast (gasp!) or a reinterpret_cast on idx in the second clause.

Add a default constructor

Because DumbArray has no default constructor (one with no arguments), code like this:

std::vector<DumbArray> dv(10);  // make ten arrays

cannot compile or run.  You could either add a default value for your existing constructor or create a new default constructor.

Consider using std::fill_n instead of memset

Instead of using the old-school

memset(_buf, 0, _size * sizeof(int));

you might consider instead using fill_n:

std::fill_n(_buf, _size, 0);

since you're already using the similar std::copy in one of the constructors.

Add a const version of operator[]

As it is currently written, there's no way to index into a const DumbArray.  Adding const to operator[] will fix that problem but make sure it returns a copy of an int rather than a reference to one.


maxPossibleValue seems to be an instance-independent constant and should therefore be static and final (and, as such, should conventionally be in uppercase letters with words being separated by an underscore character, i.e. MAX_POSSIBLE_VALUE).
array[i] = (int)Math.floor(Math.random() * maxPossibleValue);

The problem with this line is that the array will never contain maxPossibleValue itself, because the value returned by Math.random() will always be less than, but never equal to 1.0. Besides, there is a simpler way of accomplishing what you want: Instead of using Math.random(), use an instance of Random:

Random randomGenerator = new Random();
for(int i = 0; i < n; i++){
    array[i] = randomGenerator.nextInt(maxPossibleValue + 1);
}

Your method of sorting the array doesn't work correctly. First of all, the integer at the index inv will never be modified, because your first sort only sorts the indexes 0 to inv - 1 and the second sort sorts the indexes inv + 1 to n - 1 (the end index passed to the sort method is exclusive).

But even if you corrected this issue, the problem remains that you still don't know which of the two adjacent indices contains the greater integer. For example, when you have the array {1,2,3,4,5} and define 2 as the inversion point index (i.e. the third number in the array), and sort the first three numbers and the last two numbers separately, then you will get {1,2,3,5,4}, meaning the inversion point will be 3 instead of 2. If you really want to ensure that the number at the inversion point will be the largest number in the array, I don't think you will get around doing that manually, i.e. finding the largest number in the array and moving it to the inversion point by swapping it with the number previously there.
The constructor Bitonic(int, int) does not check whether the passed arguments are valid. If it did, you would not need to use expressions like Math.min(inv + 1, n) when you sort the numbers on the right side of the inversion point (regardless of the fact that the sorting algorithm does not work correctly, as I previously pointed out).
int currentPoint = (int)Math.floor(end + start)/2;

There are several problems with this line. First, you probably forgot a pair of parentheses around the expression (end + start)/2. But even so, wrapping (end + start)/2 in Math.floor(double) is pointless, because (end + start)/2 already returns an integer (see here).

Finally, you are risking an integer overflow with end + start. A way to prevent this would be to write start + (end - start)/2 instead (this is only guaranteed not to overflow if end >= start).
This:

if(currentValue < target){
    return finder(target, right, end);
}
else{
    int result = finder(target, start, left);
    if(result != -1){
        return result;
    }
    return finder(target, right, end);
}

can be written more concisely as:

int result;
if (currentValue >= target
        && (result = finder(target, start, left)) != -1) {
    return result;
} else {
    return finder(target, right, end);
}

The same goes for the analogous code when currentValue lies after the inversion point.

Update

Another thing just occurred to me: You can save unnecessary recursive calls if you changed the conditions of your two if blocks for being before and after the inversion point to allow one (but not both) of the two adjacent values to be equal to the current value. For example, if you are looking for the number 5 in the array {0,5,4,4,3,2,1}, and currentPoint == 3, so that leftValue == 4, currentValue == 4 and rightValue == 3, your program would enter the final else block and pointlessly search the numbers to the right of currentPoint.

So instead, you could change the conditions to something like this:

if(leftValue <= currentValue
        && currentValue <= rightValue
        && leftValue != rightValue)


You should never really be doing any manual casting.
Virtual functions usually provide you with the functionality you are looking for.

How about:

struct State
{
    virtual void sing() = 0;
};

struct Drunk: State
{
    virtual void sing() { std::cout << "Singing while drunk.\n"}
}

struct Sober: State
{
    virtual void sing() { std::cout << "Singing Opera.\n"}
}

class Person
{
     std::auto_ptr<State>   state;
     public:
         Person()
            : state(new Sober)
         {}
         void sing()
         {
             state->sing();
         }
         void drink()
         {
             state.reset(new Drunk);
         }
         void sleep()
         {
             state.reset(new Sober);
         }
};

Then your code in main is even more trivial:

int main() {
    Person   bob;
    bob.drink();  // Don't allow manual changes in state.
                  // Provide actions that internally modify the state of your object.
    bob.sing();
    bob.sleep();
    bob.sing();
}

  This is just an example of course. In reality, I have states like FlySpellState, with the function flies(), which also seems to have no place in Person (since people cannot fly normally), though it could be.

Sure. So what you want is a bunch of different states. These states can all be changed when diffent situations apply.

struct Action
{
    virtual void doAction()  {std::cout << "Nothing Happens\n";}
};

class Person
{

    std::map<std::string, std::unique_ptr<Action>>  actionMap;
    Action& getAction(std::string const& action)
    {
        static Action defaultAction;    // Will do Nothing by default.

        auto find = actionMap.find(action);
        return find == actionMap.end()
                  ? defaultAction
                  : *(find->second);
    }

    void sing()
    {
        getAction("sing").doAction();
    }
    void fly()
    {
        getAction("fly").doAction();  // Default do nothing unless you have read the scroll of flying
    }
    void drink()
    {
        actionMap["sing"].reset(new Drunk);
        actionMap["walk"].reset(new Stumble);
        actionMap["talk"].reset(new Slur);
    }
    void readScrollOfFlying()
    {
        actionMap["fly"].reset(new FlySpellState);
    }
};

Rather than using std::unique_ptr and lots of calls to new. You may want to look up the flyweight pattern.


C# - Linq - Techniques for avoiding repeating same pieces of code

If you're willing to use the DynamicLinq library, the problem becomes trivial. It allows you to pass a string parameter to the OrderBy method, bypassing your entire logic:
queryResult.OrderBy(column)

If this is related to doing a SQL database lookup, if you think about it, the issue you're facing it a bit of a self-imposed issue, because you start from a string value and you're eventually going to generate a string value (in the SQL query). The issue you're facing is that standard LINQ forces you to map it to an actual property of the entity, which in this case is an unnecessary mapping which DynamicLinq allows you to bypass.
If you want, you could add a bit of validation to confirm that the passed string is a known property of your entity type.
bool columnIsProperty = typeof(MyModel)
                           .GetProperties()
                           .Any(prop => prop.Name.ToLower() == column.ToLower());

if(columnIsProperty)
    queryResult = queryResult.OrderBy(column);


As I already said in the comments, some white space would be good to add, especially around { and }. Then I mentioned that you could possibly avoid creating the vector of strings, but well, that's not that easy:

template<class... T> struct pack {
    static_assert(sizeof...(T) == 0, "Unmatched argument data");
    static constexpr size_t count = 0;

    template<class Action>
    bool exec(size_t pos, Action&& action = Action()) {
        return false;
    }
};
template<class T> struct pack<T> {
    static constexpr size_t count = 1;
    template<size_t I = 0> using type = std::enable_if_t<I == 0, T>;
    T value;
    pack() = default;
    template<class V>
    pack(V&& value) : value(std::forward<V>(value)) {}

    template<class Action>
    bool exec(size_t pos, Action&& action = Action()) {
        if (pos > 0) return false;
        action(value);
        return true;
    }
};
template<class T, class... Next> struct pack<T, Next...> {
    static constexpr size_t count = 1 + sizeof...(Next);
    template<size_t I = 0> using type = std::conditional_t<I == 0,
        T, typename pack<Next...>::template type<I == 0 ? 0 : I - 1>>;

    T value;
    pack<Next...> next;

    pack() = default;
    template<class First, class... Args>
    pack(First&& value, Args&&... args)
        : value(std::forward<First>(value))
        , next(std::forward<Args>(args)...) {}

    template<class Action>
    bool exec(size_t pos, Action&& action = Action()) {
        if (pos >= count) return false;
        if (pos == 0) action(value);
        else next.exec(pos - 1, std::forward<Action>(action));
        return true;
    }
};
template<class... Args>
inline auto make_pack(Args&&... args) {
    return pack<std::decay_t<Args>...>(std::forward<Args>(args)...);
}
template<class... Args>
std::string format(std::string_view fmt, Args&& ...args) {
    auto pack = make_pack(std::forward<Args>(args)...);
    std::ostringstream result;
    for (std::size_t at = 0; at < fmt.size();) {
        char c = fmt[at++];
        if (c == '{') {
            for (std::size_t start = at; at < fmt.size();) {
                c = fmt[at++];
                if (c == '}') {
                    try {
                        std::size_t index = std::stoi(std::string{ fmt.substr(start, at - 1 - start) });

                        if (index < pack.count)
                        {
                            pack.exec(index, [&result](auto it) { result << it; });
                            break;
                        }
                    }
                    catch (...) {
                    }
                    result << fmt.substr(start - 1, at - start + 1);
                    break;
                }
                if (c == '{') {
                    result << fmt.substr(start - 1, at - start + 1);
                    break;
                }
            }
        }
        else {
            result.put(c);
        }
    }
    return result.str();
}

I have also changed the indexing a bit, not that big of a difference.
The pack is in no way perfect (reduced version of my data pack) and pack.exec(index, [&result](auto it) { result << it; }); is not easy for the compiler to optimize, but the machine code I have observed was not bad (two arguments, release build).


Split a char array with NUL terminators and inner delimiters

// not sure where the NUL terminator is, so use strcpy
strcpy(value, 1 + delimiter);

This is really dangerous. strncpy exists to prevent the possibility of buffer overflows, which are a risk precisely when you don't know how much memory you're throwing around.

If you are copying to an array of fixed size and you don't know how much to allow it to copy, use strncpy and restrict it to copying up to the length of the detination buffer. Note: strncpy(dest, src, length) copies at most length characters, or up to a null terminator if sooner. So that will not guarantee that your program works correctly (and in particular it will not guarantee that your destination is a valid null-terminated C string). It will prevent a buffer overflow if something goes wrong, which would be a much harder problem to handle.

It would still be better if you did know ahead of time how much to expect to copy, because that allows you to handle failure cases. You can do this: just use strlen(delimiter). In fact, you're already doing this! You're just doing it to p and two lines too late.

However, strncpy is not a magic bullet if used incorrectly. strncpy(key, p, delimiter - p); is vulnerable to overflow because it does not consider the capacity of key. If delimiter - p is say 15 then that line says "Copy from here into this array of size 10, but not more than 15 characters."

Take home is always know the sizes of arrays that you're dealing with, and ritually prefer the functions that check sizes such as strncpy(dst, src, sizeof(dst)) as a second line of defence so that if you do have a bug in handling array lengths the bug is less likely to be of the worst case security vulnerability sort.

A second concern I have with this code is that it relies on str being double null terminated. This is an unusual convention, and so requires a lot of conscious effort to get right. If you pack this into a function and it gets called by anyone else, or even by yourself when you're thinking about the logic of the calling component rather than the splitting component, you are going to keep reading through a bunch of junk.

Even worse, because it is not unusual for debug builds to be more generous with initialising stuff to zero than release builds, you stand a very real risk that it will appear to work fine for ages until you push it out to someone else!

The third thing to mention, and a general mindset one, is be careful not to assume that you are on the so called "happy path". Your code should do the right thing if given inputs in a form you expect, and it does. It should also confirm whereever possible that the inputs are in the form you expect.

For example, consider delimiter = strchr(p, '=');
Great, finds the "=" character to split on. If this bit of the string does not contain "=" anywhere, it returns NULL. You should check that this has not happened. Of course delimiter - p where delimiter is NULL is going to have some weird behaviour! You should check that any functions which might fail have not failed before relying on their output.


Strictly answering your question about what the \$Big-O\$ run-time complexity,

public class TempBubbleSort
{

static Integer[] myArray = {10,9,8,7,6,5,4,3,2,1};

static int counter = 0;

public static void main(String[] args)
{
    // **This is O(n), as we're touching every point in your array.
    for(int anchor=0; anchor<myArray.length; anchor++)
    {
        // **This is O(n-1), but since we don't care about constants as n grows, we consider this as O(n)
        for(int compare=anchor+1; compare<myArray.length; compare++)
        {
            // **Everything in here then is a bunch of constant operations so we'll just ignore them.
            counter++;
            // sort ascending
            if(myArray[anchor] > myArray[compare])
            {
                int tmp = myArray[compare];
                myArray[compare] = myArray[anchor];
                myArray[anchor] = tmp;
            }
        }
    }
    // **So the total of the brunt of your work would be O(n)*O(n) or O(n^2), because for every element in your array n, you touch every other element in your array, so you can look at it as touching n things in your array, n times.

    System.out.println("Comparision Count : "+counter);

    // **In case you're curious, this is also O(n)
    for(int i : myArray)
        System.out.println(i);

    // **Which would bring the grand total to O(n^2+n), again with Big O notation, we only care about what happens as n continues to grow, and since n^2 grows faster than n, as our n gets super big, the second term n becomes insignificant, so we look at this overall total as O(n^2). In fact, for any polynomial time complexity, you can safely drop all terms that are not your largest degree.
}

}

In closing, its usually easy to tell the time-complexity of simple iterative functions like this by the number of nested for loops you have, which can be a good rule of thumb for a nice approximate guess for time complexity in a pinch.


Simple shell script to backup to Amazon over iSCSI

Extract common logic to a helper function

Notice the similarity in these statements:

echo "$(date "+%Y-%m-%d %k:%M:%S") - Volume mounted" >> "$LOG_FILE"
...
echo "$(date "+%Y-%m-%d %k:%M:%S") - Mounting!" >> "$LOG_FILE"
...
echo "$(date "+%Y-%m-%d %k:%M:%S") - Sync started." >> "$LOG_FILE"

They all have the same pattern:

echo "$(date "+%Y-%m-%d %k:%M:%S") - MESSAGE" >> "$LOG_FILE"

So it's a good candidate to turn into a function:

log() {
    echo "$(date "+%Y-%m-%d %k:%M:%S") - $@" >> "$LOG_FILE"
}

So that you can simplify the uses like this:

log "Volume mounted"
...
log "Mounting!"
...
log "Sync started."

Result of mount

The mount command might fail. When that happens, you might want to abort:

if ! mount -U "$VOL" /mount_folder; then
    log "Unable to Mount"
    exit 1
fi

Pointless touch

This code is completely unnecessary.
Whether the file existed or not, whether you touch it or not,
it won't affect the rest of the script.
You can safely remove it.

if [ ! -e "$LOG_FILE" ]; then
    touch "$LOG_FILE"
fi

Simplify

This is kind of tedious:

echo "" >> "$LOG_FILE"

You can just drop the "" to simplify:

echo >> "$LOG_FILE"

And, you don't need exit 0 at the end of the script.


I think a big first improvement for you will be to start DRYing out your code. You should create a function which returns the ratio of two sides -- there is much too much repetition in your code. Something like:

function get_ratio(x, y) {
    if (y === 0) {
        return 0
    }
    return x/y | 0
}


Take your "pair" version to its logical conclusion:

using Mnemonic = std::string;
enum AddressMode { /* ... */ };
using Size = int;
using InstructionDescription = std::tuple<Mnemonic, AddressMode, Size>;
using Opcode = uint8_t;
std::map<InstructionDescription, Opcode> OpcodeTable = {
    {{"ADC", Indirect_X, 2},    0x61 },
    {{"ADC", Stack, 2},         0x63 },
    {{"ADC", Direct, 2},        0x65 },
    {{"ADC", Indirect_Long, 2}, 0x67 },
    {{"ADC", Immediate, 2},     0x69 },
    {{"ADC", Direct, 3},        0x6D },
    {{"ADC", Direct, 4},        0x6F },
    {{"ADC", Indirect_Y, 2},    0x71 },
    {{"ADC", Indirect, 2},      0x72 },
    {{"ADC", Stack_Y, 2},       0x73 },
    // ...
};

There will only be 256 rows in this table, so it's totally manageable.

Or, do what real assembler-writers do: read the instruction set specification to learn how the bits of the opcode correspond to the meaning of the instruction, and then turn that into a short mathematical formula instead of a huge lookup table.

For example:

enum AddressMode : uint8_t {
    Indirect_X = 0x01,
    Stack = 0x03,
    Direct = 0x05,
    Indirect_Long = 0x07,
    Immediate = 0x09,
    Indirect_Y = 0x11,
    Indirect = 0x12,
    Stack_Y = 0x13,
    // ...
};

Opcode get_opcode(Mnemonic instr, AddressMode mode, Size size)
{
    if (instr == "ADC") {
        unsigned size_mask = (size == 2) ? 0 : (size == 3) ? 8 : 10;
        return 0x60 + int(mode) + size_mask;
    } else if // ...
}

  I'd think having to search all the instructions every time (up to 3 times per instruction based on optimizations) instead of an O(1) lookup seems like it may increase the time taken to assemble the code which may be over 100k lines in some tests, but I don't have any data to back that up.

Lookups in a std::map are not \$O(1)\$; they're \$O(\log n)\$ and involve a ton of pointer traversals. Doing the same \$O(\log n)\$ operations on a sorted array (which is going to be contiguous in memory, therefore cache-friendly) will be faster — probably even faster than using some actually "\$O(1)\$" (cough handwave cough) yet still cache-unfriendly container such as std::unordered_map.

Anyway, my second code example above is what you'll want to do if you really need the speed (which I'm sure you don't). Simple arithmetic operations will always be lightning-fast compared to any kind of container lookup. But at some point, probably long before any of this starts mattering, the real performance bottleneck will be in how fast you can read that 100K of assembly code off the filesystem and how fast you can write the machine code back out. The code that turns mnemonics into opcodes isn't the bottleneck; I guarantee it.


Code performs as expected.

Insertion sort has an expected O(n2) performance and OP's code has about 0.25*n2 compares per length n of a linked list.

By adding a counti to sortedInsert() and providing various length lists with random data to insertionSort(), the below graph was determined.

void sortedInsert(element_t** head_ref, element_t* new_node) {
  element_t* current;
  if (*head_ref == NULL || (*head_ref)->val >= new_node->val) {

    counti++;  // *****

    new_node->next = *head_ref;
    *head_ref = new_node;
  } else {
    current = *head_ref;

    counti++;  // *****

    while (current->next != NULL && current->next->val < new_node->val) {

      counti++;  // *****

      current = current->next;
    }
    new_node->next = current->next;
    current->next = new_node;
  }
}

No functional implementation problem found.

Lots of review-able issues (format, lack of supporting code, etc.), but OP did not ask for that.


Positive integer to Roman Numeral conversion function

This code is bound far too tight to your form. The first thing we need to do is separate the logic for converting an integer to a roman numeral from the event procedures of the form. This will allow us to reuse this code anywhere.

Module IntegerExtensions

    Dim ind() As Integer = {1, 2, 3, 4, 5, 10, 50, 100, 500, 1000}
    Dim rom() As String = {"I", "II", "III", "IV", "V", "X", "L", "C", "D", "M"}
    Dim limit As Integer = 9
    Dim output As String = ""

    Private Function ConvertToRomanNumeral(ByVal input As Integer) As String
        output = ""
        While input > 0
            input = find(input)
        End While
        Return output
    End Function

    Private Function Find(ByVal Num As Integer) As Integer
        Dim i As Integer = 0
        While ind(i) <= Num
            i += 1
        End While
        If i <> 0 Then
            limit = i - 1
        Else
            limit = 0
        End If
        output = output & rom(limit)
        Num = Num - ind(limit)
        Return Num
    End Function

End Module

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        txt2.Text = IntegerExtensions.ConvertToRomanNumeral(999)

    End Sub
End Class

Next we need to make sure that the argument passed to ConvertToRomanNumeral is within the accepted range of 1-999. Receiving a Index out of bounds message is not nearly as useful as knowing that ConvertToRomanNumeral doesn't accept the value you passed into it.

Private Function ConvertToRomanNumeral(ByVal input As Integer) As String

    If (input < 1 Or input > 999) Then
        Throw New ArgumentOutOfRangeException("input","Input must be in the range 1-999")
    End If

    output = ""
    While input > 0
        input = find(input)
    End While
    Return output
End Function

ind and rom are not very good variable names. I get that rom stands for Roman Numerals, but I have no idea what ind means. Indices maybe? Also, I like plural names for arrays. Let's replace those. ind >> indices and rom >> romanNumerals.
There are way too many class level variables. Limit should be strictly declared inside of Find. I also don't find it a good idea to set the value of output from the Find function. I would consider this to be a side effect, and side effects are confusing and hard to debug. The only way for me to properly scope output was to merge Find into ConvertToRomanNumeral.

Module IntegerExtensions

    Private Function ConvertToRomanNumeral(ByVal input As Integer) As String

        If (input < 1 Or input > 999) Then
            Throw New ArgumentOutOfRangeException("input","Input must be in the range 1-999")
        End If

        Dim indices() As Integer = {1, 2, 3, 4, 5, 10, 50, 100, 500, 1000}
        Dim romanNumerals() As String = {"I", "II", "III", "IV", "V", "X", "L", "C", "D", "M"}
        Dim limit As Integer = 9
        Dim output As String = ""

        While input > 0
            Dim number as Integer = input
            Dim i As Integer = 0
            While indices(i) <= number
                i += 1
            End While
            If i <> 0 Then
                limit = i - 1
            Else
                limit = 0
            End If
            output = output & romanNumerals(limit)
            number = number - indices(limit)
            ' this was previously our return statement
            input = number
        End While
        Return output
    End Function

End Module

You may have noticed earlier that I named the module IntegerExtensions. That's because I've been planning on making this exactly that the entire time. Extension methods will allow us to call the function directly on any integer, instead of passing an integer into it. It looks a little cleaner when in use. I changed the function name to ToRomanNumberal and adjusted the ArgumentOutOfRangeException message accordingly.

Module IntegerExtensions

    <Extension()>
    Public Function ToRomanNumeral(ByVal input As Integer) As String

        If (input < 1 Or input > 999) Then
            Throw New ArgumentOutOfRangeException("input","Cannot convert integers outside of the range 1-999")
        End If

        Dim indices() As Integer = {1, 2, 3, 4, 5, 10, 50, 100, 500, 1000}
        Dim romanNumerals() As String = {"I", "II", "III", "IV", "V", "X", "L", "C", "D", "M"}
        Dim limit As Integer = 9
        Dim output As String = ""

        While input > 0
            Dim number as Integer = input
            Dim i As Integer = 0
            While indices(i) <= number
                i += 1
            End While
            If i <> 0 Then
                limit = i - 1
            Else
                limit = 0
            End If
            output = output & romanNumerals(limit)
            number = number - indices(limit)
            ' this was previously our return statement
            input = number
        End While
        Return output
    End Function

End Module

Excercises for you:

How could this be done using a dictionary instead.
How can this be changed so that numbers outside of 1-999 can be converted?


def reflect_x(i, j, coordinates):
    for pair in xrange(i-1, j):
        coordinates[pair][1] = -coordinates[pair][1]
    return coordinates

Something like:

def reflect_x(i, j, coordinates):
    coordinates[i-1:j] = ((x,-y) for x,y  in coordinates[i-1,j])

Is clearer and possibly slightly faster. Also, modify or return, don't do both.

def count(i, j, coordinates):
    quad_one, quad_two, quad_three, quad_four = 0, 0, 0, 0

If you have a count attached to your variable, the probably means it should be a list

    quad = [0] * 4

    for pair in xrange(i-1, j):

You may be better off slicing the list. That will be happen entirely in C, but looking up the value each time happens in python.

        x, y = coordinates[pair][0], coordinates[pair][1]

Same as:

        x, y = coordinates[pair]

...

        if x >= 0 and y >= 0:
            quad_one += 1
        elif x < 0 and y >= 0:
            quad_two += 1
        elif x < 0 and y < 0:
            quad_three += 1
        elif x >= 0 and y < 0:
            quad_four += 1

    print "%d %d %d %d" % (quad_one, quad_two, quad_three, quad_four)

def reflect(coordinates, queries):

bad name, this function doesn't only reflect

    for query in queries:
        if query[0] == "X":
            reflect_x(query[1], query[2], coordinates)
        elif query[0] == "Y":
            reflect_y(query[1], query[2], coordinates)
        elif query[0] == "C":
            count(query[1], query[2], coordinates)
        else:
            print query

if __name__ == "__main__":
    N = int(raw_input())
    coordinates = [[int(pair[0]), int(pair[1])] for pair in (pair.split() for pair in (raw_input() for i in xrange(N)))]

You don't need to do everything on one line. You can also unpack the tuple in the for clause.

    coordinate_lines = (raw_input() for i in xrange(N))
    coordinates = [(int(x),int(y)) for x,y in line.split for line in coordinate_lines]

As for optimisation: Firstly, you need to realise that you don't actually care what the coordinates are. All you care about is the quadrants. The reflection operations merely move you from one quadrant to the other.

I have to disagree with Jeff Mercado, as I don't think his approach will work. (maybe I've missed what he's hinting at.) Basically what you have is a worst case O(N*Q) running time. Since both N and Q are large numbers you cannot get away with doing that. His approach reduces the complexity to O(1) for the count operation, but leaves O(N) for the reflect operations. That's still going to give you O(N*Q).

We need to reduce the cost of the reflect operations as well.

Basically, for each quadrant we need to keep track of the points in that quadrant. We'll put them in some sort of data structure. We need a data structure that will allow the efficient implementation of:

Finding all points with indexes between a start/stop index
Swapping those points between two different versions of the data structure
Finding the count of all points currently in the data structure

Basically, we need all of these operations in logarithmic time or better. Figuring out what kind of data structure gives you that is left as an exercise for the reader.


You could use ThreadPool.RegisterWaitForSingleObject to register a callback when a the WaitHandle (Semaphore extends WaitHandle) is signaled.

Together with a TaskCompletionSource you could completely remove all your wait loops.

Example:

private async Task Run()
{
    var semaphore = new Semaphore(0, 1);
    await AwaitWaitHandle(semaphore, CancellationToken.None, TimeSpan.FromMilliseconds(-1));
}

private Task AwaitWaitHandle(WaitHandle handle, CancellationToken cancellationToken, TimeSpan timeout)
{
    var taskCompletionSource = new TaskCompletionSource<bool>();

    var reg = ThreadPool.RegisterWaitForSingleObject(handle,
        (state, timedOut) =>
        {
            // Handle timeout
            if (timedOut)
                taskCompletionSource.TrySetCanceled();

            taskCompletionSource.TrySetResult(true);
        }, null, timeout, true);

    // Handle cancellation
    cancellationToken.Register(() =>
    {
        reg.Unregister(handle);
        taskCompletionSource.TrySetCanceled();
    });

    return taskCompletionSource.Task;
}

You could use AwaitWaitHandle in your SemaphoreAsync implementation to await the Semaphore.


Find All Substrings Interview Query in C++

Your problem is in O(n²), at least. This seems not to be optimizable. If you want only distinct substrings, then you will have to use a table of already encountered strings, which will make your code slower.

However, you can switch the algorithm from recursive to iterative, which is usually slightly faster. It's a micro-optimization, so do not expect a x2 improvement in speed...

void findAllSubstrings2(const char *s)
{
    while(*s)
    {
        int x=0;
        while(*(s + x))
        {
            for(int y = 0; y <= x; y++)
                std::cout << *(s + y);
            std::cout << "\n";
            x++;
        }
        s++;
    }
}

I've done a profile test, on Codepad and Ideone (different versions of same compilers + different machines). The io operations are left for the profile test, because what matters here is the comparison between the 2 functions.