Binary Search Tree implementation using templates

Exception handling

While it might make sense to handle the bad_alloc exception, the way you've done so is likely to lead to problems. The basic point of exception handling is that it decouples the point at which the exception is handled from the point at which it is generated. Right now, you've couple those by catching the bad_alloc immediately after the point at which it could be generated. Worse, you haven't handled it well at all. It looks like you intended to exit (stop execution), but in fact you only have EXIT_FAILURE, which is just a constant (typically 1). At least in theory, that's evaluated by the compiler as an expression which does nothing. In fact, there's a good chance the compiler will optimize such an expression way completely, so it does nothing.

Even assuming you corrected that so it exited the program correctly, code at that level (allocating a node) has no business deciding that bad_alloc should lead directly to exiting the program. In your test code that may make sense, but depending on how the search tree is being used, it make may sense to react to a bad_alloc in some other way. Leave that decision to the higher level code that can handle it more appropriately.

For example, it would make much more sense to handle it in main:

int main()
{
    try {
        Tree<int> tree;
        tree.insert(14);
        tree.insert(12);
        tree.insert(6);
        tree.insert(17);
        tree.insert(8);
        tree.print();
    }
    catch (std::exception const &e) {
        std::cerr << e.what << "\n";
    }
}

With that in place, your code to allocate a node:

    TreeNode * treeNode = NULL;
    try
    {
        treeNode = new TreeNode(val); // handle exception necessary?
    } catch (std::bad_alloc &exception)
    {
        std::cerr << "bad_alloc caught: " << exception.what() << std::endl;
        EXIT_FAILURE;
    }

...becomes more like:

TreeNode *treeNode = new TreeNode(val);

...Only in really shouldn't be quite that either, because (as detailed below) you should really use unique_ptr instead of raw pointers.

bad_alloc specifics

bad_alloc, however, is kind of a special case, and I sometimes question whether it makes sense to handle it at all, at least in code intended for most typical desktop OSes. Memory allocation failure used to be pretty simple: you had N kilobytes of memory, and when/if that ran out, malloc returned NULL or new threw an exception.

Virtual memory changed that though. When you run out of memory, the OS swaps data to the swap file to make more room. In most typical cases, long before allocation has truly failed, the system will run slow enough for long enough that the user will kill the program long before the memory allocation actually fails. In fact, Linux actually kind of automates that process--it has an "OOM Killer" process that will kill processes to keep memory free so the system doesn't drag down to running too slowly. In most cases, that means your process will be killed without bad_alloc ever being thrown.

As such, it's quite debatable (at best) whether it makes sense to try to deal specifically with bad_alloc, at least in code for these systems.

For an interview, handling bad_alloc would depend. For embedded software, you typically do want to handle it. For desktop/server software, you may not want to, but if you don't you need to be prepared to explain why you don't.

"Raw" pointers

Most of what you've currently defined as pointers could really be instances of std::unique_ptr instead (again, at least assuming you're using a new enough compiler to support it). unique_ptr automates most of the "cleanup", so you could pretty much (probably completely) eliminate what you've currently implemented as freeMemory.

The downside of this is that a unique_ptr stores a deleter object that's used to clean up the pointee object when the unique_ptr goes out of scope. In the case of your binary tree, you'd at least normally assume that all the nodes in the tree to be deleted the same way. In that case, you probably either store no deleter object at all (and just use delete) or else store only one deleter for the entire tree, and internally use raw pointers. This can save quite a bit of storage space with (at worst) fairly minimal cost in code complexity.

Recursion pattern

Although I've already pointed out how it can probably be eliminated completely, let's assume for the moment that you're using raw pointers so you still need your freeMemory. If so, it can (IMO) be cleaned up a bit. Instead of checking for null pointers before you make the recursive call, just check for a null pointer once:

template <class T>
void Tree<T>::freeMemory(Tree::TreeNode *node)
{
    if (node==nullptr)
        return;
    freeMemory(node->left);
    freeMemory(node->right);
    delete node;
}

Each chain of recursive calls will stop when you reach a null pointer (thanks to the one if that remains). This reduces the complexity of this function pretty noticeably at essentially no cost1.

Print

As @Jamal already pointed out, your print function doesn't modify the tree, so it should be const. I'd also prefer to see it allow the user to pass a specific stream to which the contents will be printed. In fact, it's at least worth considering overloading the stream insertion operator (operator<<) for your tree type, so you can insert a tree in a stream just like you would any other type:

Tree my_tree;

// code to insert data into tree goes here

std::cout << my_tree;

Alternative to Print

I'd at least consider whether you really want a Tree::print at all, or whether it's better to have the ability to walk the tree and apply essentially any function to all its nodes (with print as just one of those possibilities).

Return value from insert

I would say that yes, it's a good idea for insert to return a value indicating whether the insertion was successful. Your code is roughly analogous to std::set, which does return such a value, and I've used that return value quite a few times, so if I were going to use this, I'd probably make use of the same.

Iterators

If you were going to put this to real use, it would be preferable to be able to use it via a standard iterator interface. Alternatively, you might prefer to support a range interface (I'd probably prefer to use a range-based interface, anyway). This is probably getting beyond the scope of what you're currently thinking about though. You also quickly run into the fact that this provides pretty much a subset of what std::set already provides, so its practical use is probably limited in any case.

1. And in case you're wondering about the apparent contradiction of using nullptr in code that's only needed prior to C++11 (when nullptr was introduced), it's really pretty simple: nullptr is sufficiently trivial that a fair number of compilers supported it before they implemented rvalue references, which are crucial for unique_ptr. As such, even if you're using an older compiler that doesn't have unique_ptr there's a good chance it does have nullptr. It's even possible to define a nullptr class that works with C++03 compilers (a little Googling should turn up at least one).


A very basic web framework inspired by Flask

That's a nice mini-flask exercise.

ROUTES = None

Deferring the assignment to later, and initializing to Routes(), would seem more natural, to avoid having to test for is None.

    global ROUTES
    ROUTES = self
...
if __name__ == '__main__':
    @Route('/')

Oh, wait, you're not testing against None. You're just jamming it in there. Consider making the assignment the caller's responsibility.

    self.routes = self.__dict__

It's not obvious to me why you were reluctant to create a new dict(). Doesn't the current implementation preclude callers from creating routes to e.g. '/add' and '/get'?.

def add(self, route, cb):

I'm sure that's a very nice signature, and perhaps cb is the appropriate name to use. But it's obscure, and demands at least a docstring explaining it.

class Routes(object):
...
class Route(object):

Honestly, I'm not in love with the class names, there. It's not immediately obvious to the reader how a Routes is different from a Route, so distinguishing names with plural / singular probably isn't a win. Consider RouteCollection instead. But, better, consider deleting the Route class entirely, and using a method hanging off ROUTES to do the work instead. If you do retain two classes, you really really need to add a docstring to each one explaining what its Single Responsibility is.

class RequestHandler(BaseHTTPRequestHandler):
  Routes()

I suggest turning the ctor call into an assignment: ROUTES = Routes(). Better, make the assignment the responsibility of the "if __name__ is main" clause.

  self.send_msg(ROUTES(self.path))

Clearly this works. But it is less obvious than it might be. Consider ignoring __call__, in favor of boring syntax like ROUTES.get_document(self.path).

      self.send_msg('
404
')

This is correct.

def root():
    return '
It Works
'

I like the root identifier. But the HTML is incorrect, as  belongs outside of
. Consider using CSS style= to replace that center.

run()

Please run flake8 and follow its advice to precede this line with two blank lines, setting it off from the decorated root function.

Overall, it's an interesting piece of code, I'm glad you shared it.


Encryption/Decryption between Python and Node JS

The padding step is unnecessary - CFB works out of the box on any plaintext length since it XORS the plaintext with the AES output.
Lack of authentication means that the scheme is vulnerable to a bit flipping attack, where you can flip bits in the ciphertext and cause a corresponding bit flip in the plaintext.
Other nitpicks:

str.encode(url) should be url.encode()
your docstring has a :return: but it doesn't declare anything


Lack of separation of concerns

You have a single main function that:

Reads a String and parses it to an internal format
Applies logic to it (finds numbers that sum to the target)
Pretty prints the result

You should have at least 3 more functions:

public class NumPairs {

    // Pseudocode, to return two objects at once read
    // http://stackoverflow.com/questions/457629/how-to-return-multiple-objects-from-a-java-method
    public static (int[], int) parseInput(String input) {

    }

    public static int[][] sumsTo(int[] list, int result) {

    }

    public static String prettify(int[][] result) {

    }

    public static void main(String[] args) {
        // Simply use the other functions
    }

}

You may still need to subdivide sumsTo surther.


Fun question,

I believe the only reliable way of getting the name and parameters of a function is to indeed parse the toString. However, you can figure out whether the parameter is a function without a regex. I would propose from here :

function isType(object, type){
     return object != null && type ? object.constructor.name === type.name : object === type;
}

// Return the name of a function aka class name
function nameOf(o) {
    return isType( o , Function )
        ? Function.prototype.toString.call(o).match(/function\s?(\w*)\(/)[1]
        : false;
}

There are still a few things that bother me here, why is the parameter name o, which is the Spartan convention for Object whereas we expect a function ? Also, why name the function nameOf, which creates an expectation of being to name anything whereas it really only can give the name for a function, maybe it ought to be called nameOfFunction or functionName(). Finally, as per the comments, making a function with name return false is making the name lie, just return ''. Something like this then:

// Return the name of a function aka class name
function functionName(f) {
    return isType( f , Function )
        ? Function.prototype.toString.call(f).match(/function\s?(\w*)\(/)[1]
        : '';
}

Finally, for argumentsOf, I sincerely dislike dropping the newline in if statements, removing curly braces is fine, but no newlines makes it too hard to read.


Code organisation

At this moment, the code is there with no context. In order to make it easier to unerstand, reuse and test, you could try to define in a a function on its own.

It could for instance:

take data as a parameter
take fixed_value as a parameter (with a default of 255 ?)

In-place changes

When trying to explain or test the function, things are make slighly harder by the fact that the input is modified. In your case, it may be just as easy to return a new list of values.

Here is a tweet from Raymond Hettinger (Python core developer and trainer):

  Today's super-easy #python student question.

  Q. What are the best practices for modifying a list while looping over it?

  A. Don't. Seriously, just make a new list and avoid hard-to-read code with hard-to-find bugs.

At this stage, we have something like:

new_data = []
for i, base_tuple in enumerate(data):
    index_max = base_tuple.index(max(base_tuple))
    new_tuple = tuple(fixed_value*(i==index_max) for i in range(3))
    new_data.append(new_tuple)
return new_data

But the call to enumerate is not required anymore and we can write:

new_data = []
for base_tuple in data:
    index_max = base_tuple.index(max(base_tuple))
    new_tuple = tuple(fixed_value*(i==index_max) for i in range(3))
    new_data.append(new_tuple)
return new_data

More functions

We could extract out the tuple computation in a function on its own.
We would have something like:

def get_new_tuple(base_tuple, fixed_value):
    index_max = base_tuple.index(max(base_tuple))
    return tuple(fixed_value*(i==index_max) for i in range(3))

def get_new_val(data, fixed_value = 255):
    # data is the list of tuples
    new_data = []
    for base_tuple in data:
        new_data.append(get_new_tuple(base_tuple, fixed_value))
    return new_data

(Documentation and function names should be improved).

Now, this is a good occasion to use list comprehension in get_new_val.

At this stage, renaming the function, the parameter and adding a simple test, we have:

def get_new_tuple(base_tuple, fixed_value):
    index_max = base_tuple.index(max(base_tuple))
    return tuple(fixed_value*(i==index_max) for i in range(3))

def get_new_tuples(tuples, fixed_value = 255):
    return [get_new_tuple(tup, fixed_value) for tup in tuples]

def test_get_new_tuples():
    # This could/should be written with a proper unit-test framework
    data = [(12, 55, 27), (260, 55, 27), (12, 55, 255)]
    output = get_new_tuples(data)
    assert output == [(0, 255, 0), (255, 0, 0), (0, 0, 255)]

Improving get_new_tuple

There is the magic number 3. It would make sense to be more generic and accept tuples of any length.

For instance:

def get_new_tuple(base_tuple, fixed_value):
    index_max = base_tuple.index(max(base_tuple))
    return tuple(fixed_value*(i==index_max) for i in range(len(base_tuple)))

And we can test it with more unit tests:

def test_get_new_tuple():
    tup = (12, 55, 27)
    output = get_new_tuple(tup, 255)
    assert output == (0, 255, 0)
    tup = (12, 55, 27, 42)
    output = get_new_tuple(tup, 255)
    assert output == (0, 255, 0, 0)

Also, the pattern range(len(foo)) usually suggests we could do things in a better way. For instance, we could use enumerate:

return tuple(fixed_value*(i==index_max) for i, _ in enumerate(base_tuple))

Edge case

Another question we could ask ourselves is about the behavior of the function where the max value appears more than once. It probably deserves to be documented and properly tested. Based on what we want, we may have to change the implementation.

Another edge case that could be tested/documented is how the empty tuple is handled.


If you take a look at the argparse documentation, they suggest to use
set_defaults on each of the parsers to associate a processing function
depending on which parser is selected.  So if you do that then you can
get rid of the try/except blocks, which would improve things quite a
lot.

E.g.:

def handler_unity(res):
    if res.unity_deploy:
        print('Unity deploy')

    if res.unity_tagcheck:
        print('Unity tagcheck')

def handler_clc(res):
    if res.clc_deploy:
        print('Clc deploy')
...
parser_unity.set_defaults(func=handler_unity)
...
parser_clc.set_defaults(func=handler_clc)
...
res.func(res)


Concatenate unlimited amount of arrays with predefined function

The approach suggested by @Caridorc has the limitation that it requires the objects passed to be Iterables, which an array is not a subtype of due to certain limitations. Therefore, you either have to change your data type from an array to some Iterable extension or use a different approach.

A simple, naive solution would be to simple convert arrays to Lists and add all to a combined list like this:

private static <T> T[] merge2(T[] ... arrays) {
    final List<T> list = new ArrayList<>();
    for (T[] array : arrays) {
      list.addAll(Arrays.asList(array));
    }
    return list.toArray(arrays[0]);
}

which has certain runtime penalties as you create multiple new objects which furthermore on adding new lists via addAll(...) will increase the capacity of the list by 50% of its current length on exceeding the current size and therefore contain some unused space.

A further approach is based on your generic approach but contains only two loops. The first one to learn the total length, the second one to copy the data from the source array to the target array:

private static <T> T[] merge3(T[] ... arrays) {
    Class<?> componentType = arrays[0].getClass().getComponentType();
    int size = 0;
    for (T[] array : arrays) {
      size += array.length;
    }
    T[] result = (T[])arrays[0].getClass().cast(Array.newInstance(componentType, size));
    int pos = 0;
    for (T[] array : arrays) {
      System.arraycopy(array, 0, result, pos, array.length);
      pos += array.length;
    }
    return result;
}

This method is shorter and IMO easier to read then your implementation. A short comparison between the 4 algorithms reveals also, that it is faster then the other ones:

Original - Total: 51.402688 ms, Average: 5.1402688E-4 ms
Original Generics - Total: 42.150794 ms, Average: 4.2150794E-4 ms
Merge2 - Total: 87.06185 ms, Average: 8.706185E-4 ms
Merge3 - Total: 28.701731 ms, Average: 2.8701731E-4 ms

Note however, that I did a naive performance test and didn't take care of compiler optimizations or warm-up phases. The comparison therefore may be flawed and data messy.

Also note that I did not take care of checking if all of the passed arrays are of the same type. Mingling multiple arrays of different types might only work if the first passed array is of type object (or at least a supertype of any further arrays). In general, I wouldn't allow to pass arrays of different types though.

BTW: the double cast in merge3 is to get rid of Unchecked cast warnings


Min Heap implementation with Dijkstra's algorithm

The only memory that you are allocating is the four arrays: data, index, cost, and eval. That means that if you are running out of memory then you probably need to allocate more memory. An array of primitives is just about as compact a structure as you're going to get.

You don't say what  you mean by "large value of nodes", but you can figure that you will be allocating approximately 13 bytes (less because the boolean array will be packed) times the value of s passed into the constructor. I think the default heap is 64 MB, and some of that is allocated to other things, but you should be able to allocate at something in the millions range.

I added this main to your code and it showed that an array of 100,000 entries used just over 1.2 MB.

public static void main(String[] args) {
    Runtime r = Runtime.getRuntime();

    long t = r.totalMemory();
    long f = r.freeMemory();
    System.out.println("[Heap.main] " + t + "," + f);

    Heap h = new Heap(100000);
    h.init(0);
    h.push(1,2);
    System.out.println("[Heap.main] isEmpty returns: " + h.isEmpty());

    t = r.totalMemory();
    f = r.freeMemory();
    System.out.println("[Heap.main] " + t + "," + f);
}


Setting new lines and adding them to a list to be drawn

Do you know about radians?

Math.Cos (and the other trig functions in .Net) are based on radians not degrees.

Math.Cos(90) radians is roughly Math.Cos(5157) in degrees. Which is a bit odd...

There are 2π radians in a circle so 1 degree is π/180. As long as you use the same value the lines will be parallel anyway but I thought it was worth pointing out.

Why do you need the Cos at all?

You have a line from (x1, y1) to (x2, y2) with length L = Math.Sqrt((x1-x2)^2 +(y1-y2)^2).

You know that you need to offset the line by an amount (offset) orthogonal to the current line.

private Line CreateParallelLine(Line target, int offset)
{
    var parallelLine = new Line();
    var xDifference = target.point1.x - target.point2.x;
    var yDifference = target.point1.y - target.point2.y;
    var length = Math.Sqrt(Math.Pow(xDifference, 2) + Math.Pow(yDifference, 2));

    parallelLine.point1.x = target.point1.x - offset * yDifference/length;
    parallelLine.point2.x = target.point2.x - offset * yDifference/length;
    parallelLine.point1.y = target.point1.y + offset * xDifference/length;
    parallelLine.point2.y = target.point2.y + offset * xDifference/length;

    return parallelLine;
}

Edit:

I realised that I've only given you an opportunity to create a single parallel line but I think it's straightforward to call the method more times with different offsets!

You didn't show your Line class/struct but it's worth noting that point1 should be at least PascalCase (Point1) but preferably renamed to something more like: Start and point2 renamed to be End or similar.

As x and y are also public, you should PascalCase them too: X and Y.


Good start! There are some things that can be simplified.

Reuse of Java classes

Java provides the very helpful class Deque which can behave like a stack. So you can reuse this for easier coding :). There is also a Stack class, but that one is synchronized.

StackNode

There is no real need for StackNode. Just use generics to store the specified item directly into the Stack/Deque. This also prevents pushing and int and popping a StackNode, which is inconsistent.

Split checking capacity, current stack to separate methods

For readability, I would try to split the handling of multiple stacks from popping and pushing, increasing readability. The push() only needs to know that there is room and pop() needs to clean up after getting the element from the stack.

Also, if there is a method of keeping track of the current stack, the logic for checking also becomes easier.

Something like this:

public void push( T item )
{
    //Make room if needed
    ensureRoom();

    //The current stack has enough room to push the item
    currentStack().push( item );
}

(note that this is not thread-safe)

Besides easier to read, it also becomes easier to refactor. For example, if you decide not to use Deque but Stack or your own implementation, it is easier to change.

Error handling

What happens when an empty SetOfStacks gets a pop()? You should throw a nice exception to make sure that both your SetOfStacks stays consistent and make use the caller gets a nice exception.

Variable names

int c and int d are not that great for passing on information about what the integer means. Is c capacity? And the initial capacity? Or the maximum capacity?

Access modifiers

Make sure to apply public, protected and private to make sure you only expose functionality that needs to be exposed, and keep private stuff private.

Proposed solution

public class StackOfPlates<T>
{
    private Deque<Deque<T>> setOfStacks;
    private int     maxStackCapacity;

    public StackOfPlates( int maxStackCapacity )
    {
        setOfStacks = new ArrayDeque<>();
        this.maxStackCapacity = maxStackCapacity;
    }

    public void push( T item )
    {
        //Make room if needed
        ensureRoom();

        //the current stack has enough room to push the item
        currentStack().push( item );
    }

    private void ensureRoom()
    {
        if( setOfStacks.isEmpty()  || currentStack().size() == maxStackCapacity);
        {
            Deque<T> newStack = new ArrayDeque<T>();
            setOfStacks.add( newStack );
        }
    }

    private Deque<T> currentStack()
    {
        return setOfStacks.peek();
    }

    public T pop()
    {
        if (setOfStacks.isEmpty())
        {
            throw new NoSuchElementException();
        }

        //Remove top element of last sack
        T elem = currentStack().pop();

        //And remove the last stack if it is emty
        maybeRemoveLastStack();

        return elem;
    }

    private void maybeRemoveLastStack()
    {
        if (currentStack().isEmpty())
        {
            //remove empty stack
            setOfStacks.pop();
        }
    }

}


A few notes:

Shy away from eval(). TL;DR: impacts performance and is a security risk.  I don't know a better method to use for vanilla JavaScript however, so we'll have to stick with it for now.
Put your operators in an array:

var operators = ['+', '-', 'x', '÷'];

Right now your code doesn't handle decimal points very well.  I would add a Boolean flag to track if you have them in the number.
You don't consider the possibility of a user entering x or ÷ into your text field.  You should replace those with their respecting proper operators:

equation = equation.replace(/x/g, '*').replace(/÷/g, '/');

What happens if the last character of the equation is an operator or a decimal?  We should remove it and then process the equation:

if(operators.indexOf(lastChar) > -1 || lastChar == '.')
        equation = equation.replace(/.$/, '');

Let's consider failure cases where we don't want to process the equation.  I've implemented some checks handling these in the final code with comments explaining them.

If we start with an operator other than -
If there is more than one decimal in the number
Two operators appear together

Final Results

// Get all the keys from document
var keys = document.querySelectorAll('#calculator span');
var operators = ['+', '-', 'x', '÷'];
var decimalAdded = false;

// Add onclick event to all the keys and perform operations
for (var i = 0; i < keys.length; i++) {
  keys[i].onclick = function(e) {
    // Get the input and button values
    var input = document.querySelector('.screen');
    var inputVal = input.innerHTML;
    var btnVal = this.innerHTML;

    // Now, just append the key values (btnValue) to the input string and finally use javascript's eval function to get the result
    // If clear key is pressed, erase everything
    if (btnVal === 'C') {
      input.innerHTML = '';
      decimalAdded = false;
    }

    // If eval key is pressed, calculate and display the result
    else if (btnVal === '=') {
      var equation = inputVal;
      var lastChar = equation[equation.length - 1];

      // Replace all instances of x and ÷ with * and / respectively. This can be done easily using regex and the 'g' tag which will replace all instances of the matched character/substring
      equation = equation.replace(/x/g, '*').replace(/÷/g, '/');

      // Final thing left to do is checking the last character of the equation. If it's an operator or a decimal, remove it
      if (operators.indexOf(lastChar) > -1 || lastChar == '.')
        equation = equation.replace(/.$/, '');

      if (equation)
        input.innerHTML = eval(equation);

      decimalAdded = false;
    }

    // Basic functionality of the calculator is complete. But there are some problems like
    // 1. No two operators should be added consecutively.
    // 2. The equation shouldn't start from an operator except minus
    // 3. not more than 1 decimal should be there in a number

    // We'll fix these issues using some simple checks

    // indexOf works only in IE9+
    else if (operators.indexOf(btnVal) > -1) {
      // Operator is clicked
      // Get the last character from the equation
      var lastChar = inputVal[inputVal.length - 1];

      // Only add operator if input is not empty and there is no operator at the last
      if (inputVal != '' && operators.indexOf(lastChar) === -1)
        input.innerHTML += btnVal;

      // Allow minus if the string is empty
      else if (inputVal === '' && btnVal === '-')
        input.innerHTML += btnVal;

      // Replace the last operator (if exists) with the newly pressed operator
      if (operators.indexOf(lastChar) > -1 && inputVal.length > 1) {
        // Here, '.' matches any character while $ denotes the end of string, so anything (will be an operator in this case) at the end of string will get replaced by new operator
        input.innerHTML = inputVal.replace(/.$/, btnVal);
      }

      decimalAdded = false;
    }

    // Now only the decimal problem is left. We can solve it easily using a flag 'decimalAdded' which we'll set once the decimal is added and prevent more decimals to be added once it's set. It will be reset when an operator, eval or clear key is pressed.
    else if (btnVal === '.') {
      if (!decimalAdded) {
        input.innerHTML += btnVal;
        decimalAdded = true;
      }
    }

    // if any other key is pressed, just append it
    else {
      input.innerHTML += btnVal;
    }

    // prevent page jumps
    e.preventDefault();
  }
}
/* Basic reset */

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  /* Better text styling */
  font: bold 14px Arial, sans-serif;
}
/* Finally adding some IE9 fallbacks for gradients to finish things up */

/* A nice BG gradient */

html {
  height: 100%;
  background: white;
  background: radial-gradient(circle, #fff 20%, #ccc);
  background-size: cover;
}
/* Using box shadows to create 3D effects */

#calculator {
  width: 325px;
  height: auto;
  margin: 100px auto;
  padding: 20px 20px 9px;
  background: #9dd2ea;
  background: linear-gradient(#9dd2ea, #8bceec);
  border-radius: 3px;
  box-shadow: 0px 4px #009de4, 0px 10px 15px rgba(0, 0, 0, 0.2);
}
/* Top portion */

.top span.clear {
  float: left;
}
/* Inset shadow on the screen to create indent */

.top .screen {
  height: 40px;
  width: 212px;
  float: right;
  padding: 0 10px;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 3px;
  box-shadow: inset 0px 4px rgba(0, 0, 0, 0.2);
  /* Typography */
  font-size: 17px;
  line-height: 40px;
  color: white;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
  text-align: right;
  letter-spacing: 1px;
}
/* Clear floats */

.keys,
.top {
  overflow: hidden;
}
/* Applying same to the keys */

.keys span,
.top span.clear {
  float: left;
  position: relative;
  top: 0;
  cursor: pointer;
  width: 66px;
  height: 36px;
  background: white;
  border-radius: 3px;
  box-shadow: 0px 4px rgba(0, 0, 0, 0.2);
  margin: 0 7px 11px 0;
  color: #888;
  line-height: 36px;
  text-align: center;
  /* prevent selection of text inside keys */
  user-select: none;
  /* Smoothing out hover and active states using css3 transitions */
  transition: all 0.2s ease;
}
/* Remove right margins from operator keys */

/* style different type of keys (operators/evaluate/clear) differently */

.keys span.operator {
  background: #FFF0F5;
  margin-right: 0;
}
.keys span.eval {
  background: #f1ff92;
  box-shadow: 0px 4px #9da853;
  color: #888e5f;
}
.top span.clear {
  background: #ff9fa8;
  box-shadow: 0px 4px #ff7c87;
  color: white;
}
/* Some hover effects */

.keys span:hover {
  background: #9c89f6;
  box-shadow: 0px 4px #6b54d3;
  color: white;
}
.keys span.eval:hover {
  background: #abb850;
  box-shadow: 0px 4px #717a33;
  color: #ffffff;
}
.top span.clear:hover {
  background: #f68991;
  box-shadow: 0px 4px #d3545d;
  color: white;
}
/* Simulating "pressed" effect on active state of the keys by removing the box-shadow and moving the keys down a bit */

.keys span:active {
  box-shadow: 0px 0px #6b54d3;
  top: 4px;
}
.keys span.eval:active {
  box-shadow: 0px 0px #717a33;
  top: 4px;
}
.top span.clear:active {
  top: 4px;
  box-shadow: 0px 0px #d3545d;
}

    C

    7
    8
    9
    +
    4
    5
    6
    -
    1
    2
    3
    ÷
    0
    .
    =
    x


Refactoring binary search algorithm in Ruby

Rather than defining it at the top level, why don't you make it a new method on Array?
Taking l and r makes recursive calls possible, but would be annoying for the end user who always has to pass 0 and array.length-1. You should either make those arguments optional, or don't use recursion, or use a private helper method for the recursion.
Someone suggested you could make it tail-recursive, but I don't think any Ruby implementation I know of can optimize tail recursion, so I'm not sure what the point of that would be. Method calls are expensive in Ruby, so if you are after performance, I think a while loop would be more appropriate.
You could consider calling <=> once and switching on the return value using case. I'm not sure if you would like the way this reads better or not. If performance is important, definitely try it and benchmark both ways.
If you do want to use if statements, the 3rd if is redundant.
You are using the type of binary search which has 3 different branches (depending on whether the value at the probed index is >, <, or == to the value you are searching for). There is another to write a binary search which only uses a single if-else, which is more concise, generally faster, and which is guaranteed to return the first matching element in the array (if there are duplicates).


First, the code is technically off-topic, since it has a pretty clear bug (in main):

} while(userinput=0);

This is almost certainly intended to be userinput==0. As-is, it's an assignment, which yields 0, which is treated as false, so the loop only ever executes once, regardless of input from the user.

While I agree with the basic approach @Konrad has advocated, putting together a table of the data needed for the conversions, I think I'd implement it just a bit differently. I would not use std::pair. I'd explicitly define a struct so the values would have meaningful names:

struct conversion {
    double offset;
    double coefficient;
};

Then your conversion would look like:

double convert(conversion_type conversion, double input) {
   conversion c = conversions[conversion];
   return (input+c.offset)*c.coefficient;
}

...which seems more readable, at least to me. If you do want to maintain separate functions for each conversion, I'd still break things up into one function doing input. another doing the conversion itself, and a third to display the result. I'd still make it largely table drive, using a vector (or array) of pointers to functions, using the number entered by the user to to index into that (after assuring that it's within range, of course).


Catching Errors in Factory Method with express.js

First of all, by default ExpressJS does not support async routes. To solve that you can use express-async-errors plugin. Just add the following at the beginning of the file:
import 'express-async-errors'

Now ExpressJS will await promises and handle promise rejections. Then you can create custom errors handler:
export function handleApiErrors(): (err: unknown, req: Request, resp: Response, next: NextFunction) => unknown {
    return (err, _req, resp, next) => {
        if (err) {
          console.error(String(err))
          return resp.status(500).json({
              error: 'unknown error',
          })
        }
        next(err)
    }
}

Then include custom error handler just before app.listen:
app.use(handleApiErrors())

Now each route can return a promise and rejected promises will be returned as 500 response. You can also include http-errors to further improve error handling.

You can check the live example on torrent-stream-server

Other observations
null return
login has Promise<User> type, but you return null. If you don't get typescript error, you should consider enabling strictNullChecks option.
res.end and res.json
You mix res.json with res.end. Maybe some middleware handles, that res.end would return JSON. Or maybe you just return plain text response on error? In any case, it's confusing, so you should always use res.json() (you can chain it with end if you like, but I don't see a reason).
No spaces
I see that you don't like spaces. But it's hard to read with that style. You should at least add spaces after :. You should find a styleguide you like and follow it. Or you can just use prettier


Discern and perform an operation on a list

You could use Object.keys and Array#some to determine if any key in an object fits your criteria:

found = Object.keys(operations).some((op) => arrayses.letteros.indexOf(op) !== -1);

In general, you can use Object.keys and array iteration methods (forEach, map, reduce, some, every, etc.) to replace for..in loops.


Haskell's record system is not really good at providing you uniform access to record entries. That is the reason your findMoves implementation has to be so verbose: You cannot generalize over the fields.

There are a number of ways to get around that. One could be using a library such as fclabels that facilitates this job for you. You set it up like follows:

import Data.Record.Label

data Pos = ....

$( mkLabels [''Pos] )

This will give you "labels" with names such as lCabb that you can use with functions such as getL or modL. Without all this boilerplate, it is possible to write a much more satisfying findMoves function:

findMoves :: Pos -> [Pos]
findMoves pos = filter valid moves
  where
    moves    = [ foldr (\obj -> modL obj opp) pos objs
               | objs <- moveComb, same $ map (`getL` pos) objs
               ]
    moveComb = [[lCabb, lFarmer], [lGoat, lFarmer], [lWolf, lFarmer], [lFarmer]]
    same xs  = all (== head xs) xs


Script to determine the outcome(s) of any number of dice rolls

Use unpacking

        choices = roll_choice.split()
        size = len(choices)
        if size == 3:
            one = int(choices[0])
            two = int(choices[1])
            three = int(choices[2])
            dice_roller(one, two, three)
        else:
            print "Invalid Choice.\n"

Becomes:

dice_roller( * map(int, roll_choice.split()) )

Adding error handling it is:

 try:
     dice_roller( * map(int, roll_choice.split()) )
 except Exception as e:
     print("Invalid choice:" + e)

The * operator just goes from a list to free floating arguments and is called the unpacking operator. You use it to pass a list as argument to a function that takes separate arguments.

Naming in full

You should write the names of your variables in full to make them more understandable at first glance. show may be omitted. For example:

show_di_1 ➡ dice_1
show_di_b ➡ dice_bottom

A dictionary

A dictionary will allow you to avoid the first if elif chain easily. How is left as an exercise for the reader.


A filled_multi_array Template Function for Boost.MultiArray in C++

It looks bad, but that's not your fault. boost::multi_array just has a terrible interface. In any case, you want to avoid passing the shape twice, because this can give problems:
auto large_array = filled_multi_array(boost::extents[1][2][3][4][5], 1.0);
auto small_array = filled_multi_array(boost::extents[1], 1.0);
auto another_array = filled_multi_array<double, large_array.dimensionality>(small_array.shape(), 2.0);

The above will compile without errors, but might crash at runtime, since small_array.shape() is a pointer to an array that doesn't have as many elements as expected. I don't know why the interface is so terrible, if they would have .shape() return a (reference to a) boost::array<size_t, NumDims> it would all be checkable at compile time and without needing reinterpret_casts.
So to prevent errors, you want to avoid having to pass two separate pieces of information. One possibility is just passing the array whose shape you want to copy as an argument:
template<class T, std::size_t NumDims>
auto filled_multi_array(const boost::multi_array<T, NumDims> &input, const T& value) {
    boost::multi_array<T, NumDims> output(reinterpret_cast<boost::array<size_t, NumDims> const&>(input.shape()));
    std::fill_n(output.data(), output.num_elements(), value);
    return output;
}

But that interface will create confusion: does the following line modify the input?
filled_multi_array(filled_multi_array1, 2.0);

Another possibility is to keep just the first filled_multi_array() variant, but create a helper function to create a extent_gen from a multi_array:
template<std::size_t NumDims>
auto get_extents(const boost::multi_array &input) {
    boost::detail::multi_array::extent_gen<NumDims> output;

    // Set the shape of output according to input.shape(),
    // left as an exercise to the reader.
    ...

    return output;
}

And then you can use it like so:
auto filled_multi_array1 = filled_multi_array(boost::extents[3][4][2], 1.0);
auto filled_multi_array2 = filled_multi_array(get_extents(filled_multi_array1), 2.0);


condensing a list of lists with 'description' lines in Python

You can do this in one go, just keep a data piece you are going to yield and list of comment items. If you encounter a new comment item - append to list, if you encounter a ata piece - yield one you were holding with all the comments, wipe comments and hold a new data item instead, like this:

def is_comment(item):
    return item[0] == ''

def nonempty(item):
    return [x for x in item if x]

def fuse_comments(data):
    result = data[0]
    comments = []
    for element in data[1:]:
        if is_comment(element):
            comments += nonempty(element)
        else:
            yield result + [' '.join(str(comment) for comment in comments)]
            comments = []
            result = nonempty(element)
    yield result + [' '.join(str(comment) for comment in comments)]

from pprint import pprint

pprint(list(fuse_comments(data)))


This review will consist of two parts: One part that addresses the code you present and one part that will make the whole code completely superfluous...
The second part is easy:
Use a logging framework
Use the Android standard Log class. Everything else is just a configuration file. Other than that you won't need any configuration... This whole method becomes completely useless as soon as you do that..

Now for the first part:

if (MyApplication.sExternalStorageDirectory == null) {
    new NullPointerException("sExternalStorageDirectory is null")
            .printStackTrace();
    return;
}

This part of the code is basically useless (at least in this place). You should ensure on startup (or to be more correct in onCreate) that this "ExternalStorageDirectory" exists and is not null. Then you should obtain a lock on it and only give that away for onDestroy. If you can guarantee that this exists during the lifetime of your app, you don't need that check.

if (error == ErrorType.WEBSERVICE_RESPONSE_ERROR) {
    fileName = "web_api_error_log";
} else if (error == ErrorType.CLIENT_SIDE_ERROR) {
    fileName = "client_log";
}

This code implies that ErrorType is an enum. If it isn't, it should be. int-flags are a thing of the last millennium.

File f = new File(MyApplication.sExternalStorageDirectory, fileName + fileExtension);
try {
    if (!f.exists()) {
        f.createNewFile();
    }
    BufferedWriter bfw = new BufferedWriter(new FileWriter(f, true));
    bfw.append(tag + "->" + s);
    bfw.newLine();
    bfw.close();
} catch (IOException e) {
    e.printStackTrace();
}

This is where your performance problem is. What you actually want to do is cache the BufferedWriter instances in the static context to avoid the significant I/O overhead you incur when you create them.
You're looking for a "static initializer block":
class YourClass {
    private static final BufferedWriter webserviceLog;
    private static final BufferedWriter clientLog;
    private static final BufferedWriter defaultLog;
    static {
        // ensure external storage directory exists
        // wrap this in a try-catch block!
        webserviceLog = new BufferedWriter(new FileWriter(new File(MyApplication.sExternalStorageDirectory, "web_api_error_log.txt", true)));
        clientLog = new BufferedWriter(new FileWriter(new File(MyApplication.sExternalStorageDirectory, "client_log.txt", true)));
        defaultLog = new BufferedWriter(new FileWriter(new File(MyApplication.sExternalStorageDirectory, "logs.txt", true)));
    }

It should be rather obvious how you have to adapt the code of the method you showed to work with these instances instead of building filenames...


error management when parsing multiple floats

I miss the reason you are working with a pointer of an error and passing it in different functions.

Why not doing in the simple way?

func lorenzHandler(w http.ResponseWriter, r *http.Request) {
    rho, e1 := strconv.ParseFloat(r.FormValue("r"), 32)
    sigma, e2 := strconv.ParseFloat(r.FormValue("s"), 32)
    b, e3 := strconv.ParseFloat(r.FormValue("b"), 32)
    if e1 != nil || e2 != nil || e3 != nil {
        log.Printf("bad parameters: r=%s; s=%s; b=%s;\n", r.FormValue("r"), r.FormValue("s"), r.FormValue("b"))
        w.WriteHeader(http.StatusBadRequest)
        return
    }

    // draw lorenz GIF with parameters rho, sigma and b
    // but until then...
    log.Println("yay!", rho, sigma, b)
}

If the problem is about performance, and you want to stop after the first error, without waiting all three executions, you can do

func lorenzHandler(w http.ResponseWriter, r *http.Request) {
    rho, err := strconv.ParseFloat(r.FormValue("r"), 32)
    if err != nil {
        log.Printf("bad parameters: r=%s\n", r.FormValue("r"))
        w.WriteHeader(http.StatusBadRequest)
        return
    }

    sigma, err := strconv.ParseFloat(r.FormValue("s"), 32)
    if err != nil {
        log.Printf("bad parameters: s=%s\n", r.FormValue("s"))
        w.WriteHeader(http.StatusBadRequest)
        return
    }

    b, err := strconv.ParseFloat(r.FormValue("b"), 32)
    if err != nil {
        log.Printf("bad parameters: b=%s\n", r.FormValue("b"))
        w.WriteHeader(http.StatusBadRequest)
        return
    }

    // draw lorenz GIF with parameters rho, sigma and b
    // but until then...
    log.Println("yay!", rho, sigma, b)
}


You should separate IO actions from pure code. In your case the principal task of updateGame is to create the new game state given input data, and for this no IO is necessary. The fact that the state is stored and modified in an IORef.

It's not just the matter of style and code separation. Calling modifyIORef multiple times in the function means that you can easily get race conditions, if there is another thread working with the game state. It would get or modify an inconsistent state.

So my suggestion would be to split it into two parts - one a pure function, and another that does all the necessary IO:

updateGame :: UTCTime -> InputsData -> GameState -> GameState
updateGame time input game = ...

updateGameIO :: IORef InputsData -> IORef GameState -> IO ()
updateGameIO modifyIORef gameIORef = step
  where
    step = do
      time <- getCurrentTime

      keys <- readIORef keysIORef
      modifyIORef gameIORef (updateGame time keys)

      addTimerCallback 1 step
      postRedisplay Nothing

This way, you ensure that the game state is updated atomically, and keep the main function pure.

Updating a field in a complex data type is a common task, and it can be greatly simplified using the lens library. Instead of

\g -> g {keyCooldowns = updateCooldowns (keyCooldowns game) elapsed}

you let lens generate so-called lenses for your data type, so for example keyCooldowns won't be of type GameState -> Something, but Lens' GameState Something, and then the function that modifies the field inside GameState would be

over keyCooldowns (flip updateCooldowns elapsed)

See A Little Lens Starter Tutorial


Changing object attributes by calling getters and setters using reflection

The given code is only a snippet, so it's not really possible to compile and test it, but here's my review for what you posted:

Never say that a method throws Exception

The caller will either have to declare his method with throws Exception, or - in the worst case - he will wrap the call into a try-catch block like this:

try { ... } catch (Exception e) { /* ignore */ }

The problem is that this catches all exceptions. Even a NullPointerException.

The exception should be more specific - without leaking implementation details to the call site. There are different possible solutions for this. In any case, you then have to decide what should happen in each case. You could

wrap the exceptions into specific ones. Maybe an existing one, like an IllegalArgumentException
"ignore" the error, and just print a warning to the console

In both cases, the exception message or log output should contain the error message like

"Could not find method with name " + methodName

or

"Could not invoke method with name" + methodName

Stop the loop when you can stop it

Imagine there are 10000000 users. And imagine that the requiredUser is the first one in this collection. Then you will invoke the line

if (getter.invoke(refToUsersCache.get(user)).equals(whereValue))

unnecessarily 9999999 times. Changing this will also allow you to make the scope of the requiredUser variable smaller. And maybe it also forces you to think about what should happen when the user is not found. In your current implementation, this will cause a NullPointerException...

Avoid repeated map lookups

When iterating over the elements of a map, you often see this pattern:

for (Key key  : map.keySet()) {
    Value value = map.get(key);
    ...
}

But in your case, you are not interested in the keys. You are just interested in the values, and thus, can iterate over them:

for (Value value : map.values()) {
    ...
}

Even if you are interested in the exact key-value pair, you can iterate over the entries

for (Entry<Key, Value> entry  : map.entrySet()) {
    Key key = entry.getKey();
    Value value = entry.getValue();
    ...
}

thus also avoiding the unnecessary lookups.

Program to the interface

Your code contained the line

HashMap<String, User> refToUsersCache = usersCache.getUsersCache();

Declaring the variable as a HashMap is not necessary. And in fact, it should not be possible. The getUsersCache() method should return a Map<String, User>, and you should thus only be able to declare your variable as a Map<String, User>.

Also see What does it mean to “program to an interface”? on stackoverflow.

Use // Inline comments judiciously

It's not clear whether you added these comments only for posting the code here. In any case, you should avoid appending such comments at the end of (already long) lines

Use sensible variable names

This is certainly controversial. But the line

HashMap<String, User> refToUsersCache = usersCache.getUsersCache();

makes me shudder. What type does the variable usersCache have? And whatever type it has, shouldn't getUsersCache() return an object that has a type that justifies the name usersCache? For me, this line looks as odd as a line like

Engine theEngine = engine.getCar();

Something just looks wrong there...

However, here is a sketch of how I made some of these changes locally. But note that this involves some guesses about the part of the code that you did not post, so take this with a grain of salt:

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class GetterSetterReflection
{
    public static void usersUpdate(String attributeToBeChanged,
        String newAttributeValue, String whereKey, String whereValue)
    {
        Map<String, User> usersCacheMap = usersCache.getUsersCache();
        for (User user : usersCacheMap.values())
        {
            Object userWhereValue =
                invokeGetterUnchecked(User.class, user, whereKey);
            if (Objects.equals(userWhereValue, whereValue))
            {
                invokeSetterUnchecked(
                    User.class, user, attributeToBeChanged, newAttributeValue);
                return;
            }
        }
        // What should happen here?
        System.err.println("No user found where "+whereKey+" is "+whereValue);
    }

    private static Object invokeGetterUnchecked(
        Class<?> c, Object object, String propertyName)
    {
        try
        {
            String methodName = "get" + propertyName;
            Method getter = getDeclaredMethodIgnoreCase(c, methodName);
            return getter.invoke(object);
        }
        catch (NoSuchMethodException
            | IllegalArgumentException
            | InvocationTargetException
            | IllegalAccessException e)
        {
            throw new IllegalArgumentException(
                "Could not find or invoke getter for " + propertyName, e);
        }
    }

    private static void invokeSetterUnchecked(
        Class<?> c, Object object, String propertyName, Object value)
    {
        try
        {
            String methodName = "set" + propertyName;
            Method setter = getDeclaredMethodIgnoreCase(c, methodName);
            setter.invoke(object, value);
        }
        catch (NoSuchMethodException
            | IllegalArgumentException
            | InvocationTargetException
            | IllegalAccessException e)
        {
            throw new IllegalArgumentException(
                "Could not find or invoke setter for " + propertyName, e);
        }
    }

    //=========================================================================
    // Dummy code below this line

    private static Method getDeclaredMethodIgnoreCase(
        Class<?> c, String methodName) throws NoSuchMethodException
    {
        Method[] methods = c.getDeclaredMethods();
        for (Method method : methods)
        {
            String name = method.getName();
            if (name.equalsIgnoreCase(methodName))
            {
                return method;
            }
        }
        throw new NoSuchMethodException(
            "Method not found: " + methodName + " in " + c);
    }

    static class User
    {
    }
    static class UsersCacheHolder
    {
        HashMap<String,User> getUsersCache()
        {
            return null;
        }
    }
    private static UsersCacheHolder usersCache;
}


Increasing readability of maximum path sum algorithm

The purpose of your program was unclear to me before reading the problem description. I could understand the logic flow, but I had no idea what answer it was seeking.

The name matrix implies a rectangle. While triangle or pyramid are more descriptive, I'd go with rows for readability and a comment about the shape they form. The special handling of the first and last values of cur was confusing when assuming each row was the same size.
Since this same code will be reused in problem 67 and to improve testability, rename the function and move the specifics of problem 18 to its own method.

These two simple changes yield the following:

def prob_018():
    print(maximum_path(read_rows("018.txt")))

def read_rows(file):
    return [[int(i) for i in line.split(' ')]
            for line in files.get_lines(RESOURCES, file)]

def maximum_path(rows): ...

The main algorithm has three steps:

Iterate over each pair of rows.
Calculate the better path to each cell in the lower row from the two cells above it.
Return the maximum value from the last row.

One thing that makes this difficult is that you're modifying the rows along the way. This makes extracting functions harder since they have side-effects. Instead, leave the original values untouched and build up an accumulator to hold the best path sums. Extracting this to a new accumulate_steps function yields a very readable outer algorithm:

def maximum_path(rows):
    paths = None
    for row in rows:
        paths = accumulate_steps(paths, row)
    return max(paths) if paths else None

This introduces a common trick to simplify high-level logic: moving special-case checks into extracted methods. Writing accumulate_steps to accept None for paths also allows maximum_path to handle the empty list and single-row corner cases.

With that out of the way we can focus on combining the current best paths (accumulator) with the next row to form the new best paths. Rewriting your original code to build a new row is sufficient:

def accumulate_steps(paths, row):
    if paths is None:
        return row
    el_num in range(len(row)):
        total = row[el_num]
        if el_num == 0:
            total += paths[el_num]
        elif el_num == len(row) - 1:
            total += paths[el_num - 1]
        else:
            total += paths[el_num - 1] if paths[el_num - 1] > paths[el_num] \
                else paths[el_num]
        row[el_num] = total

but I found it easier to move the first/last element handling out of the loop. Also, negative list indexes reduce the calls to len which cleans up the logic a bit. My first refactoring built a new list in-place with similar procedural code:

def accumulate_steps(paths, row):
    if paths is None:
        return row
    sums = [0] * len(row)
    sums[0] = paths[0] + row[0]
    sums[-1] = paths[-1] + row[-1]
    for i in range(1, len(row) - 1):
        sums[i] = row[i] + max(paths[i - 1], paths[i])

While it works, converting this to a list comprehension and adding on the first and last cells using + seems more Pythonic to me:

def accumulate_steps(paths, row):
    if paths is None:
        return row
    return ([paths[0] + row[0]]
            + [row[i] + max(paths[i - 1], paths[i]) for i in range(1, len(row) - 1)]
            + [paths[-1] + row[-1]])

Putting it Together

def prob_018():
    return maximum_path(read_rows("018.txt"))

def read_rows(file):
    return [[int(i) for i in line.split(' ')]
            for line in files.get_lines(RESOURCES, file)]

def maximum_path(rows):
    paths = None
    for row in rows:
        paths = accumulate_steps(paths, row)
    return max(paths)

def accumulate_steps(paths, row):
    if paths is None:
        return row
    return ([paths[0] + row[0]]
            + [row[i] + max(paths[i - 1], paths[i]) for i in range(1, len(row) - 1)]
            + [paths[-1] + row[-1]])


Assigning book ids to certain students on registration of a new student

Instead of extracting all books and execute a separate sub-query on each FOR loop iteration - we can select only the books that don't have matches in studentbooks table for specified student (presented by id argument) by running PostgreSQL LEFT JOIN with specific WHERE clause.

Furthermore, to make it one-shot action - we can insert data from query using INSERT INTO SELECT statement.

The query for the whole task:

INSERT INTO
   studentbooks(bookid, studentid)
   SELECT
      b.bookid, your_function_name.id
   FROM
      books b
      LEFT JOIN
         studentbooks sb
         ON sb.bookid = b.bookid AND studentid = id
   WHERE
      b.isdelete = false AND b.published = true
      AND sb.bookid is NULL;

replace your_function_name with your actual function name to refer the function's argument name.


Here are some suggestions

be consistent: jsonStr vs. jsonString
be consistent: GetObjFromJson vs WriteObjAsJson (maybe Read & Write instead)
use guard clauses instead of nesting
avoid temporary variables like successfulWrite and retObj

Based on the suggestions, here is one alternative:

static class JsonHandler // class could be static
{
    public static T GetObjFromJson<T>(string filePath)
    {
        // use a guard clause to reduce nesting
        if (File.Exists(filePath)) return default(T);

        try
        {
            var jsonStr = File.ReadAllText(filePath);

            // guard clause again
            if(string.IsNullOrWhiteSpace(jsonStr)) return default(T);

            // we could use null coalesing operator ?? here
            return JsonConvert.DeserializeObject<T>(jsonStr) ?? default(T);
        }
        catch (Exception ex)
        {
            // do proper exception handling
        }

        return default(T);
    }

    public static bool WriteObjAsJson(string filePath, object obj)
    {
        try
        {
            string jsonStr = JsonConvert.SerializeObject(obj);
            File.WriteAllText(filePath, jsonStr);
        }
        catch (Exception ex)
        {
            // do proper handling
            return false;
        }

        return true;
    }
}

Also you should think about exception handling.

if the method returns default(T), maybe reflect that in the method name
if the method throws on failure, maybe wrap the exception into a custom one
if the method fails, return null to signal that
use the Try* pattern, look at bool int.TryParse(string,out int)

Also, in the DummyClass you can use Auto-Implemented Properties public string Name { get; set; }


Varying Parameter Names in Method Overloads

To answer your direct question - always name your parameters to match the intent of the type. If they are passing in an Id, call it an Id. What Microsoft is saying is if you had the following:

    public async Task<Foo> ShowAsync(string name, ...)
    {
        return await DoStuffAsync(foo);
    }
    public Task<Foo> ShowAsync(string resourceName, int id, ...)
    {
        return ShowAsync(resourceName + foo.ToString(), ...);
    }

In that case, name and resourceName represent the exact same concept: they are both the name of the resource. If you are using the same type and concept within overloads, always keep the name the same. For this, you are changing the type and concepts so change the name to match the concept.

With that said...

In this particular instance, I personally probably wouldn't use overloading and would, instead, say ShowBynameAsync and ShowByIdAsync.

Downside - there's two distinct methods.

A potential upside is that no matter how the developer uses your API, it's always clear (to future readers) what they are passing in. Also, it's extremely clear what's being requested. You could still delegate the "showing" to ShowByNameAsync.

It's not "wrong" to use overloading here and not "right" to use descriptive method names. Just a preference.


Python softmatcher using difflib impracticably slow

I recommend you try different approaches:

Use quick_ratio instead of ratio
Apply .lower().split(' ') to the data before sending it to the SequenceMatcher
Add a line somewhere that checks if the two strings are equal. In those cases don't call SequenceMatcher

The first approach will most likely reduce the overall run time, but decrease precision. The second approach should work pretty well, since SequenceMatcher knows how to handle lists and will match only two items: ['john', 'doe'] and ['john', 'doe'] instead of all the letters in the name.


Haskell MultiWayIf extension: When is it considered useful syntactic sugar?

Unsurprisingly, it's mainly useful when the if is not the top-level expression. Say:

forM_ [1..100] $ \i ->
  putStrLn $ if | i `mod` 15 == 0  -> "FizzBuzz"
                | i `mod` 3 == 0   -> "Fizz"
                | i `mod` 5 == 0   -> "Buzz"
                | otherwise        -> show i

I happen across similar cases quite often - up to this point this required either deep if trees or mis-using case in some way.


Better paradigms for posting JSON from a table?

$('button').click(function () {
    var row = $(this).parent().parent();

The button selector is not specific enough. To make sure that .parent().parent() will be what you think it is, and to clarify it in the code, I would recommend this way instead:

$('tr > td > button').click(function () {

Having the id value as the text of a td field is not great. Judging by the name "id", it sounds like technical information that shouldn't really be visible. In HTML5 you can use attributes prefixed with data- for embedding technical details invisibly inside your HTML. So I would write your rows this way:

    Goonies

        <textarea></textarea>

        <button>Save</button>

And then you could get id like this:

var id = row.attr('data-id');

  Perhaps there is a better way of doing this, without pressing a button, i.e. post on textarea/row change (could be a selectbox column).

You could trigger your function on a change to the textarea, in addition to the button, for example:

function onRowChanged() {
    var row = $(this).parent().parent();
    row.css("background-color", "red");
    var id = row.attr('data-id');
    var note = row.find('textarea').val();
    var data = {
        json: JSON.stringify({
            id: id,
            note: note
        })
    };

    // ...
}
$('tr > td > button').click(onRowChanged);
$('tr > td > textarea').change(onRowChanged);

  I want less code for the JavaScript and I was thinking how much effort if would be to remove the jQuery dependency entirely.

For the record, I don't think there's anything wrong with having some JavaScript code. On the other hand, getting rid of jQuery can be a good thing, if you only need a tiny subset of its power. It's certainly possible to rewrite this small piece of code without jQuery, but I'm not very good at that myself. Instead, I can recommend zepto.js as an ultra-light jQuery replacement. You can try it in your fiddle, just change the Framework to Zepto, and make a small modification to your AJAX call:

$.ajax({
    url: "/echo/json/",
    type: "POST",
    data: data,
    contentType: "application/json",
    complete: function (d) {
        console.log(d);
        row.css("background-color", "green");
    }
});

I hope this helps, but you might want to wait for some real JavaScript experts to respond!


Computing sum and counting matches in an array

From Steve McConnell, Code Complete 2nd Edition, 31.2 Layout Techniques, p737:

  Using blank lines is a way to indicate how a program is organized. You can use them
  to divide groups of related statements into paragraphs, to separate routines from one
  another, and to highlight comments.

It does not make sense if all groups contain only one line.
This comment is mostly noise:

return matches; // Returns the number of matches.

as well as this one:

// Uses total and the length of the
// array to computer the mean
double mean = total / grades.length;

They don't say anything more that the code already does. I'd remove them. (Clean Code by Robert C. Martin: Chapter 4: Comments, Noise Comments)
I would call both element1 and element2 as element. It's more common. Having element1 and element2 suggest a little bit that they are used together (but that's not the case).
Comments like this are not too easy to read on because of the horizontal scrolling and the unnecessary spaces:

{                                               // increases matches for each one that is.

You could put them a line above of the method/loop/variable declaration (and eliminate them later).

  [...] if I were going to write this sort of thing 'for real',
  I would assume it would probably need to calculate much more
  than just this small task (different averages,
  highest/lowest, etc.), so I would probably put each step
  in its own method so it could be used wherever you needed it.

You should to that now. It would eliminate most of the comments and increase the abstraction level of the method. A maintainer would be grateful, it's easier to get an overview what the method does (without the details) and you can still check them if you are interested in. Furthermore, you need to read and understand less code (not the whole original method) if you modify just a small part of it.

Finally, cleaning the code usually costs less during writing than later. Now you probably know the details better than later, therefore it's faster.

public int scoresBelowMean() {
    double total = getGradesTotal();
    double mean = total / grades.length;
    return gradesCountBelowMean(mean);
}

private double getGradesTotal() {
    double total = 0;
    for (double element: grades) {
        total = total + element;
    }
    return total;
}

private int gradesCountBelowMean(double mean) {
    int matches = 0;
    for (double element: grades) {
        if (element < mean) {
            matches++;
        }
    }
    return matches;
}

(Clean Code by Robert C. Martin, One Level of Abstraction per Function, p36)
Instead of doubles (and floating point numbers) you might want to use BigDecimals. Floating point numbers are not precise. Here is an example:

Effective Java, 2nd Edition, Item 48: Avoid float and double if exact answers are required
Why not use Double or Float to represent currency?


Jon Bentley's bitmap sort implementation

An idea: I'd try to implement the algorithm with bigger data types (int, long) instead of the byte.

Some notes:

I'd create a BYTE_SIZE constant for 8, try to avoid magic numbers.

private static final int BYTE_SIZE = 8;

It would help a lot if you change from byte to another data type.
The return type of sortDistinctIntegers is really confusing. It returns with the first argument. Users easily could believe that it returns another array despite the fact that it modifies the input array. Make it void.
For easier readability I'd

extract out some method for easier readability: createBitmapArray, processBitmapByte, doSort,
use longer variable and parameter names (outputIndex instead of k, bitmapSize instead of N, bitIndex instead of j),
create local variables for 1 << bitIndex (mask), etc.

Below is the code after a few refactoring steps. (I haven't checked that the algorithm is correct or not.)

private static final int BYTE_SIZE = 8;

public void sortDistinctIntegers(final int[] data, final int min, final int max) {
    final byte[] bitmap = createBitmapArray(data, min, max);

    doSort(data, min, bitmap);
}

private byte[] createBitmapArray(final int[] data, final int min,
        final int max) {
    final int bitmapSize = (int) (((long) max - min) / BYTE_SIZE + 1);
    final byte[] bitmap = new byte[bitmapSize];

    for (int i = 0; i < data.length; i++) {
        final long min2 = (long) data[i] - min; // TODO: need a better name
        final int mask = 1 << (int) (min2 % BYTE_SIZE);
        bitmap[(int) (min2 / BYTE_SIZE)] |= mask;
    }
    return bitmap;
}

private void doSort(final int[] data, final int min, final byte[] bitmap) {
    int outputIndex = 0;
    for (int bitmapArrayIndex = 0; bitmapArrayIndex < bitmap.length;
            bitmapArrayIndex++) {
        final byte currentBitmapByte = bitmap[bitmapArrayIndex];
        outputIndex = processBitmapByte(data, min, currentBitmapByte,
                outputIndex, bitmapArrayIndex);
    }
}

private int processBitmapByte(final int[] data, final int min,
        final byte currentBitmapByte, int outputIndex,
        final int bitmapArrayIndex) {
    for (int bitIndex = 0; bitIndex < BYTE_SIZE; bitIndex++) {
        final int mask = 1 << bitIndex;
        final boolean flagSet = (currentBitmapByte & mask) > 0;
        if (flagSet) {
            data[outputIndex] = bitmapArrayIndex * BYTE_SIZE + bitIndex + min;
            outputIndex++;
        }
    }
    return outputIndex;
}


I've used that before in my code. I find it is often used in libraries as an "initializer" that sets up the code and DOM for the library rather than forcing the user of the library to have to call an initialization function.
It depends. If you need to interact with the DOM right away(as in, find elements, change properties, or set element events), the code has to be at the bottom of the body. If it's just function declarations and definitions, you can keep your code in the head
Is this a question?
There is nothing that really pops out. You have very nice spacing in your code(everything isn't bunched together) and your formatting is perfect(in my opinion).


Determine local maximum from given points

Don't use "list" as a variable name, since it is a python function.
Don't initialize it a list and append to it, if you can
just create it and populate it with one line.
Don't call a function more than once, if you don't need to.
Use a loop with a break statement, instead of all the elif statements

original=mkPoint3D(x,y)
z1=mkPoint3D(x-d,y)
z2=mkPoint3D(x+d,y)
z3=mkPoint3D(x,y-d)
z4=mkPoint3D(x,y+d)

point_list = [original, z1, z2, z3, z4]

maxz = maxPoint(point_list).z

if maxz == original.z:
    print (" The local ...")

else:
    for next_point in point_list[1:]:
        if maxz == next_point.z:
            matching_point = next_point
            break

    hillClimb(matching_point.x, matching_point.y, d)


Variadic template class that stores a vector of each type given

A few points of criticism of your approach:

Prefer protected to private

This isn't really about your overall design, but - unless you have very good reason, use protected rather than private member. In few cases is it useful to hide data from your subclasses.

"Where did my data go?!"

Suppose you have vectors types T_1 and T_2 in your tuple, and you add() an element of type T_3, which may be implicitly cast into both a T_1 and a T_2. Where will it go? The answer is: It depends on which casting is preferred, which in turns depends both on language defaults and on your own choices of constructors and casting operations for T_1, T_2 and T_3.

Do you remember with certainty which implicit casts are preferred over which? I know I don't, and I write C++ all the time. Now, ok, maybe you're a smart guy and have that all memorized. What about the next person reading your code? And what if it's in code which itself is templated? And what if somebody adds or removes some T_1, T_2 or T_3 code? It seems to me this is just asking for trouble.

If your data goes in a vector other than the one you expect, you'll have to start searching vectors you have trouble even referring to, for that data.

So, you asked about what's "safe" - I would say this is not too safe.

Motivation

This is not a problem with the code, it's a problem with your presentation. Why would you need a tuple of vectors of arbitrary types? Are you really sure that's what you need? Not, say, an array of std::variants like one of the comments suggests? Or a class with named vector, e.g.

struct A {
    std::vector<Foo> foos;
    std::vector<Bar> bars;
}

Now, this is much less "fancy" and "hi-tech" and modern-C++'ish, but it is simpler and easier to debug. There are also other points in the design space. I just find it a bit hard to believe that you would really need a completely generic tuple of typed vectors.


UnionFind data structure implemented in Python

find is not a right name. A method find(x) is expected to find objects matching x. find_root seems more appropriate.

I know that Sedgewick & Wayne use find, and they are wrong.
find (or find_root) has no reason to be static. x.find_root() is way more natural than UnionFind.find_root(x).
Python does not eliminate tail recursion. I recommend to rewrite find as

def find(x):
    while x != x.parent:
        x = x.parent
    return x


Type aliases

The container alias is never used, it can be removed.
The const_reference alias is wrong, it is still an alias to T&.
Use a consistent aliasing scheme, only use T when aliasing value_type.
Provide a const_pointer alias.

With these points in mind, your type aliases become:

using value_type = T;
using reference = value_type&;
using const_reference = value_type const&; // is now actually reference-to-const alias
using pointer = value_type*; // use value_type alias
using const_pointer = value_type const*; // for iterators, casting, etc.
using size_type = std::size_t;

Consider the rule of 5 when your class manages a resource.

Whenever your class manages a resource, it probably needs to implement the destructor, copy and move operations. You definitely do not want pointers to be copied when a copy of circular_buffer<> is made. Possible issues:

Memory being freed twice.
Dangling references.
Invalid object states.

Use static memory when the size is known at compile-time.

This will be more efficient and exception-free during allocation. Possible replacement:

#include <type_traits>
std::aligned_storage_t<mcapacity * sizeof( T ), alignof( T )> data;

Now that you are using static memory, you can provide two private functions to avoid having to use ugly casts everywhere:

T* data() { return reinterpret_cast<T*>( &data ); }
T const* data() const { return reinterpret_cast<T const*>( &data ); }

Your constructor becomes:

circular_buffer() noexcept /* no exceptions with static memory allocation */ :
    /* members reordered to match class */
    begin( data() ),
    end( begin ),
    msize( 0 ),
    is_empty( false )
{}

We now explicitly initialize is_empty in the constructor initializer list. I think this is clearer.
To avoid weird bugs, members are initialized in the same order that they
are declared in the class.
If your class needs really big chunks of memory that aren't available statically, then don't make the capacity a template parameter: make it a constructor parameter.

Use universal references in the definition of emplace().

This avoids unnecessary copying of arguments. Replacement:

template <typename... ArgTypes>
void emplace( ArgTypes&&... args ); // variadic template of universal references

This change requires that we also perfect-forward these universal references wherever they may be used:

T{ std::forward<ArgTypes>( args )... }; // perfect-forward example

Use std::move() when you're finished with rvalue arguments.

In push( T&& ), argument value is actually used as an T const& (which calls the copy constructor) because you forget to call std::move(). The fix is simple:

end->T( value );

Becomes:

end->T( std::move( value ) );

Factor out repeated code.

Your push() overloads and emplace() have the exact same block of code being repeated; this block is a prime candidate for being extracted into a private function:

void tidy() noexcept // feel free to use a descriptive function name
{ // the repeating block of code
    ++end;

    if ( end == data + mcapacity )
        end = data;

    if ( msize != mcapacity )
        ++msize;
}

After modifications, emplace() and push() now look like this:

template <typename... ArgTypes>
void emplace( ArgTypes&&... args )
{
    ::new ( end ) T( std::forward<ArgTypes>( args )... );
    tidy();
}

void push( T const& value )
{
    ::new ( end ) T( value );
    tidy();
}

void push( T&& value )
{
    ::new ( end ) T( std::move( value ) );
    tidy();
}

Note the consistent use of the same construction approach (placement-new) which looks nice and prevents syntax issues with primitive types.

Mark functions as noexcept when appropriate.

Non-throwing functions of yours include size(), capacity() and a few more. This will help programmers know that certain functions do not throw, which can help with optimizations.

For compile-time conditional noexcept marking, use type traits. Here's a sample:

template <typename... ArgTypes>
void emplace( ArgTypes&&... args )
noexcept( std::is_nothrow_constructible<T, ArgTypes&&...>::value )
{ /* ... */ }

Mark non-modifying functions as const.

const functions of yours include front(), size() and a few more. Member functions that don't modify any of the class data members should be marked as const so that they can be used in the appropriate scenario (accessed through a circular_buffer<> const&).


First, don't use else. Or try to avoid it. The link method can be reduced drastically by just reading the docs.

host
Can be either a host name or an IP address. Passing the NULL value or the string "localhost" to this parameter, the local host is assumed. When possible, pipes will be used instead of the TCP/IP protocol.

Usually, using NULL in a variable will help you achieve the default behavior of things. Take advantage of it.
/**
 * Sets and gets the link to the database based on params
 * @param string $host
 * @param string $username
 * @param string $password
 * @param string $dbname
 * @return mysqli
 */
public function link($host = null, $username = null, $password = null, $dbname = null)
{
    static::$link->real_connect($host, $username, $password, $dbname);
    return static::$link;
}

Secondly, why is $link static? You're already using the Singleton Pattern, to make the $link variable static is double redundant against the pattern.


The value your looking for is more like a position rather then a grade.
Just add...

var position   = 0;
var last_grade = 0;

outside the for loop. then add a comparison before the document.write... statement like so.

if (grade>last_grade) position++;
document.write( 'Grade: ' + ( position ) +'
');
last_grade=grade;

That should give you the following result...

Grade: 1

Grade: 2

Grade: 2

Grade: 2

Grade: 3

Grade: 4

Grade: 5

Grade: 5

Grade: 5

Grade: 5

Grade: 6

Grade: 7

Grade: 7

Grade: 8


You can call reverse on String directly.

While it doesn't particularly apply here, instead of splitting on '', you should use the method chars.

Who says you'll be passing a sentence? Does this method not work for single words? If I call palindrome? 'radar' will I get an error?

I'd recommend using tr to strip out all non-alphabetic characters, instead of just deleteing spaces.

def palindrome?(testing)
  stripped = testing.downcase.tr('^a-z', '')
  stripped.reverse == stripped
end


Business with dbcontext and static class

What is wrong with using static class like the one below?

For one thing, your class isn't static, which means your client code can create an instance of it... which would make no sense at all.

Before the advent of static classes, you would prevent instantiation by sealing the class and providing a non-public default/parameterless constructor, like this:

public sealed class TenantManager
{
    private TenantManager() { }

Making the class static pretty much does that for you, and prevents anyone from inheriting the class and/or calling its constructor.

In Object-Oriented Programming, a class defines the "blueprint" for an object - its type. By making a class static, you're denying it the ability to create objects; you're writing procedural code, like vba macro-recorder code in a module - you're giving anyone anywhere the ability to run this code, because the code lives in a global state, a static context, a type, as opposed to an object. This simply isn't OOP code.

It wouldn't be that bad, if all there ever was to your application was a Tenant entity. I don't know about the rest of your app, but say you have new requirements and now you have to add a Landlord entity, with the corresponding LandlordManager class.

So you go and implement another static class:

public static class LandlordManager
{
    public static IEnumerable<Landlord> GetAll(AppDbContext context)
    {
        return context.Landlords;
    }

    public static Landlord GetById(int id, AppDbContext context)
    {
        return context.Landlords.Find(id);
    }

    public static Landlord Create(Landlord entity, AppDbContext context)
    {
        var landlord = context.Landlords.Add(entity);

        context.SaveChanges();
        return landlord;
    }

    public static void Update(Landlord entity, AppDbContext context)
    {
        context.Entry(entity).State = EntityState.Modified;
        context.SaveChanges();
    }

    public static void Delete(int id, AppDbContext context)
    {
        var landlord = context.Landlords.Find(id);
        context.Landlords.Remove(landlord);
        context.SaveChanges();
    }
}

Notice anything? Yes, I fixed the vertical whitespace and the shy indentation. Anything else? Isn't it striking how similar the two classes are? The two types desperately want to share an interface, but the classes being static, they can't.

public interface IEntityManager<TEntity>
{
    IEnumerable<TEntity> GetAll(AppDbContext context);
    TEntity GetById(int id, AppDbContext context);
    TEntity Create(TEntity entity, AppDbContext context);
    void Update(TEntity entity, AppDbContext context);
    void Delete(TEntity entity, AppDbContext context);
}

The fact that every single member of the interface takes an AppDbContext parameter, is a very strong indicator that the parameter belongs at instance level. This simplifies the interface to this:

public interface IEntityManager<TEntity>
{
    IEnumerable<TEntity> GetAll();
    TEntity GetById(int id);
    TEntity Create(TEntity entity);
    void Update(TEntity entity);
    void Delete(TEntity entity);
}

This is really starting to look like something familiar - in fact only the name is different:

public interface IRepository<TEntity>
{
    IEnumerable<TEntity> GetAll();
    TEntity GetById(int id);
    TEntity Create(TEntity entity);
    void Update(TEntity entity);
    void Delete(TEntity entity);
}

  I do not use repository. The entity framework is uow/repository.

The thing is, you are using a repository. You just gave it a different name. I can call an apple an orange all I want, it's still an apple. Yes, the EF DbContext is a powerful unit-of-work. Yes, an EF DbSet<T> is a nice repository. Yet you still feel the need to tuck it into its own type - and that's a good thing!

The difference between your TenantManager and the above IRepository<TEntity> interface, is that TenantManager is tightly coupled with AppDbContext, while it's an implementation detail as far as IRepository<TEntity> is concerned - the consuming/client code doesn't need to even know about AppDbContext. In your code, AppDbContext is a dependency: not only your code needs to be tightly coupled with a TenantManager, it's also coupled with AppDbContext. "Manager" is a smell all by itself - you don't have a "Manager", you have a repository... whether you like it or not!

Good design doesn't spread its dependencies to the client/consuming code; good design is cohesive, and has low coupling. That's why SOLID OOP guidelines tell us to depend on abstractions, not concrete types. With client code that only needs to know about an IRepository<Tenant>, the only concrete type it's working with is Tenant. With your code, it needs to know about Tenant, TenantManager, and AppDbContext. That's not exactly what low coupling is about!

  Many speak of using dependency injection.

There's a reason for this. Loosely coupled code is much easier to write tests for. And the DI principle (all of SOLID actually) completely steer your code/design in that direction.

Say you have a controller - with your code it could look like this:

public class SomeController : Controller
{
    public ActionResult Tenant(int id)
    {
        using (var context = new AppDbContext(connectionString))
        {
            var tenant = TenantManager.GetById(id, context);
            return View(tenant);
        }
    }
}

With proper DI it could look like this:

public class SomeController : Controller
{
    private readonly IRepository<Tenant> _repository;

    public SomeController(IRepository<Tenant> repository)
    {
        _repository = repository;
    }

    public ActionResult Tenant(int id)
    {
        var tenant = _repository.GetById(id);
        return View(tenant);
    }
}

Both do exactly the same thing. Yet, only one of these two snippets can be unit tested.


Usage of StringBuilder for returning copies of a string

I'd just like to make a slight change to the code. When you are instantiating a StringBuilder, you have the opportunity to specify the capacity of it. Using this constructor, we can avoid having it resized more than necessary.

public String frontTimes(String str, int n) {
    StringBuilder stringBuilder = new StringBuilder(3 * n);
    if (str.length() > 3) {
        str = str.substring(0, 3);
    }
    for (int i = 0; i < n; i++) {
        stringBuilder.append(str);
    }
    return stringBuilder.toString();
}

Note how many times that 3 is declared? Would be better to extract that to a constant, or even better, a parameter. And with a few other changes to the above (as suggested by @rolfl in chat):

public String frontTimes(final String str, final int frontLength, final int times) {
    String copyString = str.length() > frontLength ? str.substring(0, frontLength) : str;
    StringBuilder stringBuilder = new StringBuilder(copyString.length() * times);
    for (int i = 0; i < times; i++) {
        stringBuilder.append(copyString);
    }
    return stringBuilder.toString();
}


Gluing pieces of scrambled text (challenge on CodeEval)

First of all I don't think the solution is correct. There could be multiple candidates to combine. Consider for example that the file contains, among other, the abc, bcd and bce strings, in this order. Your code unconditionally joins abc and bcd to produce abcd whereas the actual text has abce.

Also, it looks like you assume that at each iteration of the outer loop at least one string is removed. It is not necessarily so. If - due to a wrong candidate selection, see above - you happen to reach a dead end (unable to append or prepend any string), you are in the infinite loop. That explains TLE much better than the quadratic nature of the algorithm.

I am afraid you need some sort of backtracking. Compute the "successor" relation between fragments, and join them in a DFS with backtracking. Keep in mind that succession does not impose a strict order (e.g. aba and bab are each other successors).


Generating time series for generator ON or OFF

I don't know of any method, but here are some small improvements:

(1) You want mix to be TTF and TTR intertwined. An easy, vectorized way to do that is:

mix <- c(rbind(TTF,TTR))

(2) You want sw to be an alternating vector of the capacity and 0. This can be vectorized as well:

cap <- 400
sw <- rep(c(cap,0), length(TTF))

(3) Next, simply find the index which is the first value above 8736 and rep that:

final <- 8736
ind <- which.max(cumsum(mix) > final)
out <- rep(sw[1:ind], round(mix)[1:ind])[1:final]

So full code would be:

MTTF <- 2940
MTTR <- 60
final <- 8736
cap <- 400
TTF <--MTTF*log(runif(100))
TTR <--MTTR*log(runif(100))

mix <- c(rbind(TTF,TTR))
sw <- rep(c(cap,0), length(TTF))
ind <- which.max(cumsum(mix) > final)
out <- rep(sw[1:ind], round(mix)[1:ind])[1:final]


Invoking only the last registered event handler

Yes, this is a reasonable way to implement the event. Another would be use the normal even implementation (without explicit add and remove) and get the last subscriber using GetInvocationList().

But I think the fundamental problem here is that what you want doesn't really behave like an event, so it probably shouldn't be an event.

What I would probably do is to make the abstraction something like “a collection of open Dialogs”, not “a collection of delegates that are going to be invoked when the back button is pressed”.

That way, you can easily access the top-most open Dialog and invoke its HandleBackPressed() method. But you could also use it for other purposes. So this would make your code more flexible, without adding much complexity.


Pythonic attempt at conversion of length

Firstly as highlighted by Tlomoloko using a class for this is really strange.

However I think the both of your are missing something rather important. If you wanted to hand write every SI prefix for metres alone then you'll rack up an unmaintainable amount of code. The table contains 21 prefixes, such as no prefix - m, centi - cm, and kilo - km. Whilst I'm sure many conversions you'll think are ridiculous. Who needs to convert from yoctometres to yottametres? But what's the harm in supporting it, if you allow something reasonable like zetta to yotta?

To write the conversions for all SI prefixes would require only \$\binom{21+1}{2}\$ or 231 bespoke functions. Which would be absolutely ridiculous to write by hand.

And so the solution to this is to have an intermarry value that you always convert to or from. And since all of your existing functions are nice simple multiplications or divisions we can simply assign a single value for each unit.

This may be a bit hard to visualize, and so we'll run through some examples.

Example

1 cm to mm

1 cm = 0.01 m
1 mm = 0.001 m

First we convert 1 cm to metres. This is as simple as \$1 \times 0.01\$. Afterwards we convert from metres to millimetres simply as \$\frac{1 \times 0.01}{0.001}\$.

Which results in 10.
1' to inches

1' = 0.3048 m
1" = 0.0254 m

First we convert 1' to meters. This is as simple as \$1 \times 0.3048\$. Afterwards we convert from metres to foot simply as \$\frac{1 \times 0.3048}{0.0254}\$.

Which results in 12.

Code

CONVERSIONS = {
    'm': 1,
    'cm': 0.01,
    'mm': 0.001,
    'in': 0.0254,
    'ft': 0.3048,
}

def convert(value, unit_in, unit_out):
    return value * CONVERSIONS[unit_in] / CONVERSIONS[unit_out]

print(convert( 1.0,   'ft', 'in'))
print(convert(12.0,   'in', 'ft'))
print(convert(0.3048, 'm',  'ft'))
print(convert(3,      'ft', 'm' ))

Now the code's not perfect. If you run it you should instantly notice that it outputs some ugly 12.000000000000002 rather than 12.0. Yuck.

And so we can convert your code to use fractions.Fraction. However this will print 1143/1250 rather than 0.9144. Since I dislike getting 12.0 rather than 12, we can fix these at the same time.

from typing import Dict, Union
from fractions import Fraction

Number = Union[int, float]
CONVERSIONS: Dict[str, Fraction] = {
    'm': Fraction('1'),
    'cm': Fraction('0.01'),
    'mm': Fraction('0.001'),
    'in': Fraction('0.0254'),
    'ft': Fraction('0.3048'),
}

def to_number(value: Fraction) -> Number:
    if value % 1:
        return float(value)
    else:
        return int(value)

def convert(value: Number, unit_in: str, unit_out: str) -> Number:
    return to_number(value * (CONVERSIONS[unit_in] / CONVERSIONS[unit_out]))

if __name__ == '__main__':
    print(convert( 1.0,    'ft', 'in'))
    print(convert(12.0,    'in', 'ft'))
    print(convert( 0.3048,  'm', 'ft'))
    print(convert( 3,      'ft',  'm'))


Extending DOM elements with prototype for easier function execution

I don't have any insight on extending host objects, because I've never done it, and quite frankly this scares me a little bit.

That said, I can shed a bit of light on that "enumerable" problem.

Objects in javascript are traversable, much like arrays. This means that when you do :

var o = {foo: "bar", baz: "buzz"};
for(var property in o){
  console.log(o[property]);
}

you get "bar" and "buzz" in the console.

Now in a for-in loop, the only properties that you get are those who are enumerable. What does this mean ? Basicly, this means that you only get properties for which o.propertyIsEnumerable('propertyName') is true (and by extension, for which o.hasOwnProperty('propertyName') is true).

When you create a property on an object, by default it is enumerable, and hasOwnProperty returns true for it. But it is possible to define properties with modifiers :

   o = {};
   Object.defineProperty(o, 'foo', {
     value:      function(){ console.log('foo'); },
     enumerable: false
   });

   o.foo();                      // "foo"
   o.propertyIsEnumerable('foo') // false
   o.hasOwnProperty('foo')       // false
   for(property in o){
     console.log(property); // this will never be reached - o has no enumerable property yet
   }

One reason to mark certain properties as not enumerable is that when extending an object, one usually copies all enumerable properties from a source object using a for-in loop. When writing a lib, you have to care about this, because if you don't your users will have to deal with properties they probably are not aware of or don't care about.

Also note that every fresh object already has non enumerable properties : prototype, hasOwnProperty, etc...

Hope this helps. For more info, see Object.defineProperty


I don't think your specialization is doing what you think it's doing. https://godbolt.org/z/Gfh7sv
You don't want ConstWrapper<ConstWrapper<Iterator>> to inherit from ConstWrapper<Iterator>; that would mean that a CW<CW<I>> "is-a-kind-of" CW<I>, which isn't true. You don't want an inheritance relationship here. What you want is simply for specializations of Storage to not wrap DataIterators that happen to be specializations of ConstWrapper already. The way you do that is with an extra layer of alias indirection:
template<class T> struct maybe_constwrap { using type = ConstWrapper<T>; };
template<class U> struct maybe_constwrap<ConstWrapper<U>> { using type = ConstWrapper<U>; };

template<class Size, typename DataIterator>
class Storage : public Size {
public:
    using iterator = DataIterator;
    using const_iterator = typename maybe_constwrap<DataIterator>::type;
    ~~~
};

Now, if DataIterator is already a ConstWrapper, then both iterator and const_iterator will be literally the same type... which is what you want.

Your MakeConst seems to be predicated on the dubious idea that const _Bit_reference is not going to be assignable-to. That's likely to change in C++23. See https://stackoverflow.com/questions/63412623/should-c20-stdrangessort-not-need-to-support-stdvectorbool for some context.

You repeat some metaprogramming in the return types of operator* and operator[]. They should just return the type reference which you have already computed above.
reference operator*() const { return *it_; }

Incidentally, I'm changing your data member's name from iterator to it_, because I suspect it is a terrible idea, Concepts-wise, to have a container-ish class type with a member named iterator which member is (A) not public, and (B) not a type.

Your operator!= should probably use the hidden friend idiom:
friend bool operator==(ConstWrapper a, ConstWrapper b) { return a.it_ == b.it_; }
friend bool operator!=(ConstWrapper a, ConstWrapper b) { return a.it_ != b.it_; }

In C++20 you could theoretically omit operator!= and provide operator== only. I don't know yet if that's a good idea.
Passing ConstWrapper by value should be fine, because it holds only an iterator, and iterators are cheap to copy.


Go practices

It's recommended to close things using defer as early as possible,
so that you won't forget them later.
For example you have:

html, _ := ioutil.ReadAll(rsp.Body)

// some code

defer rsp.Body.Close()

Using defer, you should write like this instead:

html, _ := ioutil.ReadAll(rsp.Body)
defer rsp.Body.Close()

// some code

Another thing, it's recommended to not ignore errors.
This example ignores the err value returned by ioutil.ReadAll,
and that may lead to crashes later in the program.

Single responsibility principle

It's recommended for functions to do just one thing.
The getBookTitle function does do many things:

Download a web page from bookSite (a free variable defined elsewhere)
Read content from a stream
Extract title from an HTML string

The name implies only the 3rd task. It would be better if it did only that,
and the other tasks should be performed in other functions.

Strange regex

This regex looks strange:

(
)[\n+\\s]*(
)[a-zA-Z–\\-\n\\s:]*(
)[\n+\\sdd]*(
)

For several reasons:

[\n+\\s] is odd. \\s already includes \n. You could write simpler as [+\\s]. But are you really expecting a literal + between the starting
 and
? I seriously doubt it. In which case the expression could be reduced to just \\s.
[\n+\\sdd] is similarly odd. Again, the \n is unnecessary. Two d are also unnecessary, and if there are literal d between
 and
, that would be invalid HTML.
Why the groupings with (...)? Those parentheses don't serve any purpose in this program.

All in all, it seems the regex is mistakenly over-complicated,
this simpler regex is probably good enough and much more clear:

\\s*
[a-zA-Z–\\s:]*
\\s*