A Simple C++ Client That Sends Data Over TLS Using OpenSSL

C++ review
You still need a C review!
Idioms/Patterns
RAII idiom
In C++ we have this concept that an object should clean up its own resources. So when an object is created it will create and hold onto resources and when it is destroyed it will clean up those resources.
When learning about the idiom people mostly talk about memory and smart pointers. This is how we stop memory leaks in C++ that happen in C when things don't got as planned.
You should also note that an objects destructor is called when the control leaves the scope in which the object is created. However that scope is left. So even if you throw an exception that causes the stack to unwind as it unwinds the stack the destructors for all automatic objects are being called.
You need to apply this to your code.
 // this is an anti pattern in C++
 Stuff*   data = crate_data();

 ... do stuff with data
 ... do stuff with data

 destroy_data();

If you see this in your code you should be using RAII.
 class StuffHolder
 {
     Stuff*   data;

     public:
         StuffHolder()
             : data(crate_data())
         {}
         ~StuffHolder()
         {
              destroy_data(data);
         }
 };

 // Then in your code
 StuffHolder   dataHolder;

 ... do stuff with data
 ... do stuff with data

That's the pattern you should be using.
Exceptions
Exceptions make code easier to understand. Use them.
In your code you have places that you call exit(). Which is fine as it makes the rest of the code easy to read as you are not writing code to pass error message back through many layers of code so it keeps the code nice and simple.
There is a disadvantage in that you have exit locations scattered through your code. Have you been consistent with the error messages that are generated? You have to search and check every exit location.
A lot of code (especially bigger apps or libraries) don't want want to exit. They are part of a bigger framework so in C code you need to add error logic explicitly to the code to force the stack to unwind to the point where the user can take an action based on the error, or in a server you have a single place that is doing the error logging (so that it is consistent; otherwise each library will end up generating logs in a different way).
Exceptions provide the best of both worlds. You have a single place to catch and log exceptions. You don't have to write explicit error handling code (this is what exceptions do they unwind the code).
When you use exceptions with RAII all your resource are also correctly handled and released so you have no issues with releasing resources.
I can see several different ways of generating error messages in the code:
    ERR_print_errors_fp(stderr);
    exit(EXIT_FAILURE);

    perror(hostname);
    exit(EXIT_FAILURE);

    fprintf(stderr, "%s: %s\n", hostname, gai_strerror(status));
    exit(EXIT_FAILURE);

    SSL_get_error(ssl, status);
    ERR_print_errors_fp(stderr); //High probability this doesn't do anything
    fprintf(stderr, "SSL_connect failed with SSL_get_error code %d\n", status);
    exit(EXIT_FAILURE);

When you start having automated tools run over your logs this will be a real pain. Have a single point generate the error message so it is consistent for all places in the code. Then you can write tools that can easily analyze your error logs.
Code Review.
Would like to point out you don't use a single C++ header file.
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <resolv.h>
#include <netdb.h>
#include <openssl/ssl.h>
#include <openssl/err.h>

Like the comment (It provides useful information).
//Not sure what headers are needed or not
//This code (theoretically) writes "Hello World, 123" to a socket over a secure TLS connection
//compiled with g++ -Wall -o client.out client.cpp -L/usr/lib -lssl -lcrypto
//Based off of: https://www.cs.utah.edu/~swalton/listings/articles/ssl_client.c
//The OpenConnection method was heavily based on the answer to this post: https://stackoverflow.com/questions/52727565/client-in-c-use-gethostbyname-or-getaddrinfo

Returning pointers
Returning pointers in C++ is very uncommon.
SSL_CTX *InitSSL_CTX(void)

You usually return an object (or reference). If you have a resource it is contained within an object that you return. That way the resource is correctly handled and released. If you are returning a pointer to an object that is owned locally by the function/method then you would normally return a reference. This guarantees that the object exists (can never be nullptr) but it also an indication that you are not releasing ownership of the pointer.
Terrible comment.
    // Bad comment
    const SSL_METHOD *method = TLS_client_method(); /* Create new client-method

    // Another terrible comment
    X509 *cert = SSL_get_peer_certificate(ssl); /* get the server's certificate */

Comments like this are useless. In fact they are worse than useless they are dangerous. The comment tells me no more than the function name so it is not providing any real information. Also in the future as this code is maintained and made better the next developer could change the function call but leave the comment. Then a third developer sees there is a discrepancy between code and comment. Now what does he do? Does he fix the comment? Does he fix the code?
The point is comments de-generate over time and become less useful unless you are very active in maintaining them. So write code that is self documenting. Add comments that is explain WHAT (you are trying to do) or WHY (you are trying to do it) don't write comments that explain HOW (you are doing it). The code explains how (there are exceptions to this rule but you will have people tell you when there is an exception and the code needs to be commented).
One variable declaration per line:
    struct addrinfo hints = {0}, *addrs;

One variable declaration per line. Also in C++ you don't need the struct. In C++ we normally (unlike C) put the * next to the type. Types are exceedingly important in C++ (much more than in C) so we like to know the exact type. To me the above line is hard to parse.
    addrinfo   hints = {0};
    addrinfo*  addrs;

That looks so much neater and I can see the exact type of each variable.
Dead Code
Remove dead code.
This function is not used anywhere. Delete it from your code.
void DisplayCerts(SSL *ssl)

Main is special
Don't need a return in main().
    return 0;

You can do it; but people use no return value to indicate that the app will never generate an error code. So if I see a return 0; at the end then I start looking through main to see if there are any return 1; in the code.
Now I will admit that I would also add return 0; because you have used exit() in your code. But If I had written the code I would not have an exit() and consequently probably not had an return 0;.
int main(int argc, char* argv[])
{
    try {
       std::vector<std::string>   args(argv, argv + argc);
       exampleClient(args);
    }
    catch(std::exception const& e)
    {
        std::cerr << "Exception: " << e.what() << "\n";
        throw;
    }
    catch(...)
    {
        std::cerr << "Unknown Error: Red Alert\n";
        throw;
    }
}

Issues
Not sure if this is an error but it looks like one.
SSL_CTX *ctx = InitSSL_CTX();
SSL *ssl = SSL_new(ctx);
const int sfd = OpenConnection("127.0.0.1", argv[1]);

...

SSL_free(ssl);
close(sfd);
SSL_CTX_free(ctx);

You are creating the resources in a different order to closing them. Seems very code smelly. I would expect resource to be released in the reverse order of creation to make sure there are no interdependencies.
Being Selfish
I have already written a wrapper for C++ clients to use sockets.
https://lokiastari.com/blog/2016/05/26/c-plus-plus-wrapper-for-socket/index.html
The source is here:
https://github.com/Loki-Astari/Examples/tree/master/Version2
Look at client.cpp to see how to use it look at Socket.h for the interface. Would be nice to have a SSL Implementation. It may be as simple as providing an implementation of Protocol.h ie SSLProtocol. Just saying. I would review that.


Clearing the screen using FillConsoleOutputAttribute()

Here is an idea; ANSI escape codes work on Windows, Linux and OSX:

cout << "\033c";

\033 - stands for octal ESC,
c    - resets the device (terminal is default) to the initial state ( clear the screen,clear the buffer also so it is not possible to scroll, reset the fonts and so on).

In some cases it may be more useful than well known which simply adds some empty lines and puts the cursor in the upper left corner:

cout << "\033[2J\033[1;1H"


try {
    FileInputStream input = new FileInputStream(file);
    bitmap = BitmapFactory.decodeStream(input);
    try {
        input.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        Log.e(TAG, e.getMessage());
    }
} catch (FileNotFoundException e) {
    Log.e(TAG, e.getMessage());
}

If decodeStream throws an exception the stream won't be closed. A proper solution is the following:

try {
    FileInputStream input = new FileInputStream(file);
    try {
        bitmap = BitmapFactory.decodeStream(input);
    } finally {
        input.close();
    }
} catch (FileNotFoundException e) {
    Log.e(TAG, e.getMessage());
} catch (IOException e) {
    Log.e(TAG, e.getMessage());
}

Or this:

try {
    FileInputStream input = new FileInputStream(file);
    try {
        bitmap = BitmapFactory.decodeStream(input);
    } finally {
        input.close();
    }
} catch (IOException e) {
    Log.e(TAG, e.getMessage());
}

(Since FileNotFoundException is a subclass of IOException).

AQuery aq;

I guess this field could be private. (Should I always use the private access modifier for class fields?; Item 13 of Effective Java 2nd Edition: Minimize the accessibility of classes and members.)

private String roseUrl;
...
private File ext;

These field is used only in one method (onStart and sacCb). They could be local variables instead. (Effective Java, Second Edition, Item 45: Minimize the scope of local variables)

public void xml_ajax() {

This method name does not follow the usual camelCase conventions and it should be a verb. From Code Conventions for the Java Programming Language:

  Methods should be verbs, in mixed case with the first letter
  lowercase, with the first letter of each internal word capitalized.

I'd use longer and more descriptive variable names (which explains their purpose) for better readability than this ones:

XmlDom r = xml.tag("reportrose");
...
String s = status.getMessage();
int i = status.getCode();
String e = s + " | Status Code: " + i;
...
String lm = dlm.toLocaleString();

Longer names would make the code more readable since readers don't have to decode the abbreviations every time and when they write/maintain the code don't have to guess which abbreviation the author uses.

private Bitmap getRose() {
    Bitmap bitmap = null;
    try {
        FileInputStream input = new FileInputStream(file);
        try {
            bitmap = BitmapFactory.decodeStream(input);
        } finally {
            input.close();
        }
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
    }
    return bitmap;
}

You can get rid of the bitmap variable here if you return immediately:

private Bitmap getRose() {
    try {
        FileInputStream input = new FileInputStream(file);
        try {
            return BitmapFactory.decodeStream(input);
        } finally {
            input.close();
        }
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
    }
    return null;
}

See Guideline 1-2: Release resources in all cases in Secure Coding Guidelines for the Java Programming Language

String lm = dlm.toLocaleString();

This method is deprecated, you should use something else.

// TODO Auto-generated catch block

Comments like this doesn't seem like professional work. Solve the issues and remove the comments.


I suggest you format

for(int i = 0; i < arrayToSort.size(); i++) {   // i = leftmost index of unsorted part of the array

as

// i = leftmost index of unsorted part of the array
for(int i = 0; i < arrayToSort.size(); i++) {

swap takes arguments a, b and arrayToSort. These arguments could be more explanatory: swap doesn't sort anything and it doesn't take an array, and a and b don't say much.

It's canonical to use i and j as indices, so that would be more appropriate - although longer names wouldn't hurt either. The List argument would be better as items or similar. items is this-like, so put it first.

private static void swap(List<Integer> items, int i, int j) {
    int temp = items.get(i);
    items.set(i, items.get(j));
    items.set(j, temp);
}

You can also make this more like the OpenJDK implementation by using the return value from set:

private static void swap(List<Integer> items, int i, int j) {
    int temp = items.set(i, items.get(j));
    items.set(j, temp);
}

or even

private static void swap(List<Integer> items, int i, int j) {
    items.set(j, items.set(i, items.get(j)));
}

You could also make it generic.

private static <T> void swap(List<T> items, int i, int j) {
    items.set(j, items.set(i, items.get(j)));
}

Your sort is of course inefficient; you're using selection sort. However, you can at least make it a little faster. First neaten it up - including changing the name to something more descriptive. Note that minimumValue is not a value but an index - this should be fixed.

public static void sortInPlace(List<Integer> toSort){
    // i = leftmost index of unsorted part of the array
    for(int i = 0; i < toSort.size(); i++) {
        int minimumValue = i;
        for(int j = i; j < toSort.size(); j++) {
            if(toSort.get(j) < toSort.get(minimumValue)) {
                minimumValue = j;
            }
        }
        swap(toSort, i, minimumValue);
    }
}

You can change the inner loop to start at i + 1. You can also cache the value to halve the number of toSort.gets you make.

public static void sortInPlace(List<Integer> toSort){
    // i = leftmost index of unsorted part of the array
    for(int i = 0; i < toSort.size(); i++) {
        int minimumIndex = i;
        int minimumValue = toSort.get(i);
        for(int j = i + 1; j < toSort.size(); j++) {
            if(toSort.get(j) < minimumValue) {
                minimumIndex = j;
                minimumValue = toSort.get(j);
            }
        }

        swap(toSort, i, minimumIndex);
    }
}

This gives a noticeable speed improvement.

Frankly, though, if you want a reasonably fast integer selection sort, use an array. int[] is unboxed, which means that it's some 4x the speed. It's actually faster to copy into a temporary int[], sort and copy it back than to sort in a boxed List.


Redirecting to the appropriate URL for some type of notification

Suggestions:

Break long methods into simple parts;
Avoid unnecessary local variables;
Use single quotes for strings without interpolation;
Move repeated parts of code into separate methods.

Code:

def notification_redirection_path(notification)
  notifiable_type = notification.notifiable_type
  notifiable_id = notification.notifiable_id

  case notification.action
  when 'commented'
    case notifiable_type
    when 'Post'
      posts_path(anchor: "post_#{notifiable_id}")#{}"/posts#post_#{notifiable_id}"
    when 'Product'
      product_path(notifiable_id, anchor: 'comment-panel')#/products/#{notifiable_id}#comment-panel"
    when 'ProductLead'
      product_product_lead_path(*lead_params(notifiable_id), anchor: 'comment-panel')#{}"/products/#{product_id}/#{notifiable_type}/#{notifiable_id}#comment-panel"
    when 'ProductCustomer'
      product_product_customer_path(*customer_params(notifiable_id), anchor: 'comment-panel') #/products/#{product_id}/#{notifiable_type}/#{notifiable_id}#comment-panel"
    end
  when 'invited'
    if notifiable_type == 'Product'
      product_path(notifiable_id, anchor: 'product-invitation-well')
    elsif notifiable_type == 'ProductCustomer'
      product_product_customer_path(*customer_params(notifiable_id))
    end
  when 'accepted'
    if notifiable_type == 'Product' #team member invitation
      product_product_owner_panels_path(notifiable_id)
    elsif notifiable_type == 'ProductCustomer' #referencer invitation
      product_product_owner_panels_path(*customer_params(notifiable_id).first)
    end
  when 'wrote'
    product_product_customer_path(*customer_params(notifiable_id))
  end
end

private

def customer_params(notifiable_id)
  [ProductCustomer.find(notifiable_id).product_id, notifiable_id]
end

def lead_params(notifiable_id)
  [ProductLead.find(notifiable_id).product_id, notifiable_id]
end


numberToWord.h

Consider renaming numbertoword to NumberToWord.  This uses a naming convention referred to as PascalCase, which is different from your variables and functions.  Also notice that the compound words have been emphasized.  This makes it easier for others to read the full name.
Since you're not using your own destructor, you can just leave it out.  The compiler will provide one for you that should be suitable.
These names make no sense to me:

int xN, yN;

Unless these shortened names are obvious in the program, they should be spelled-out entirely so that others can understand them.  It may also benefit you in case you ever forget what they mean.

Source.cpp

Elaborating on what @vnp has mentioned about initializer lists, you can use it in place of the multiple calls to push_back():

one2nine { "one", "two", "three" /* ... */ };

Moreover, consider renaming the vector to oneToNine, which is less-awkward of a name.  Apply this to the other similar names as well.

Better yet (regarding the use of vectors), you can use std::array instead.  It would be better-suited for this task as you're not needing a dynamic data structure here.
This can be simplified:

number = number / 10;

by using the /= operator:

number /= 10;

With the existing curly braces, these should be on separate lines:

display(number); return;

You should be doing input-validation with this.  If the user inputs a non-numerical value or a value below 0 or above 999, the program should display an appropriate error message and then terminate.
This program can be made more usable by accepting command line arguments:

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

    // the file name is considered an argument
    if (argc > 1)
    {
        number = std::atoi(argv[1]);
    }
    // only file name given
    else if (argc == 1)
    {
        std::cin >> number;
    }

    // ...
}

(std::atoi() requires <cstdlib>)
It would make more sense to construct numbertoword objects with the original number, rather than passing it to convert().  The function has no business doing that, and this initialization should only be done by the constructor.  The function should also no longer take arguments.

numbertoword n2w(999);
n2w.convert();

In order for this to work, you should replace the default initializer list with one that takes an argument:

numbertoword::numbertoword(int originalNumber)
    : xN(0)
    , yN(0)
    , originalNumber(originalNumber)
{}

(I've rearranged the list so that it's easier to maintain the data members.)


Implementing an "Add Company" section in a project

You are going very well. There is nothing wrong with it, except there are some things that can be further improved. To improve it you can further do:

addCompany should be in pascal case i.e. AddCompany
Try to use this i.e. use this.something instead of using addCompany.something everytime.
Module name should be noun instead of word. You may use Company instead of addCompany
You can make the private properties using the following version of Modular Pattern:

var Company = function () {

// ------- Start #PrivateSection ------

// Save elements references
var elements = {
  openForm: $('#add-company-btn'),
  form: $('#add-company-form'),
  usernameField: $('#username'),
  usernameErrorField: $('#username-error div'),
  passwordField: $('#password'),
  passwordErrorField: $('#password-error div'),
  password2Field: $('#password2'),
  password2ErrorField: $('#password2-error div'),
};

// Given an error, handle the display of error fields
var handleError = function(error_field, error) {
  if(error) {
    error_field.show();
    return false;
  } else {
    error_field.hide();
    return true;
  }
}

// ------- End #PrivateSection --------

// Public Properties and methods
return {
  // Initialize the object
  init : function () {
    bindUI();
  },

  // All the event bindings to go here.
  bindUI : function () {
    // Run on click
    addCompany.elements.openForm.click(
      addCompany.focusFirst();
    );

    // Run on focus
    addCompany.elements.form.submit(
      addCompany.validate
    );
  },

  // Focus some element
  focusElement: function( el ) {

    var toFocus;

    // If no value provided
    if ( typeof el == "undefined" ) {
      // Focus the first element
      toFocus = elements.usernameField;
    } else {
      // Focus the provided element element
      toFocus = el;
    }

    toFocus.focus();
  },

  // Validate the form
  validate: function() {

    // Store the error tests
    var noUsername = (addCompany.elements.usernameField.val().trim() === ''),
        noPassword = (addCompany.elements.passwordField.val().trim() === ''),
        differentPasswords = (addCompany.elements.passwordField.val() !== addCompany.elements.password2Field.val());

    // Return the results of running the tests
    return handleError(elements.usernameErrorField, noUsername) &&
           handleError(elements.passwordErrorField, noPassword) &&
           handleError(elements.password2ErrorField, differentPasswords);
  }

};
};

And then to use it,

var c = new Company();
c.init();


Simple wrapper for PHP mysqli connection

Error reporting
This is much better than your initial attempt, but somehow it become more verbose and I'll tell you why: you are, so to say, abused the error reporting. mysqli_sql_exception is not intended to be thrown manually. Like it's said in the article I gave you link to, mysqli can throw exceptions by itself - so just let mysqli to do it. And therefore there is no reason to check for errors manually, and it will greatly reduce the amount of repeated code.
Automatic binding
Your automated binding function is rather confusing. Apparently you didn't have any clear idea what this code is intended to do:
                else
                {
                    $types .= 'b';
                }

And I'll tell you - there is no good scenario for it.
Don't write a code just in case, when you just don't know what to write. In such circumstances just don't write any code at all.
Besides, I am scared by functions like this that sniff a type off a variable automatically. If you will have a query that will compare a string stored in a database to a number, the consequences would be fatal. And PHP is known for converting strings to numbers on its own will. So, although quite small, but there is still a possibility that your binding function will ruin your database.
That's why I prefer either a manual explicit type setting or just blunt setting a string type for all variables. At least it won't harm anyone.
In practice it means that I recommend to use string type for all parameters by default, with a possibility of a fallback with manual type setting. So, taken from ny other article, the mysqli binding function would be like
public function execute(string $sql, $params = [], $types = '') : mysqli_stmt
{
    if (!$params) {
        return $this->connection->query($sql);
    }
    $types = $types ?: str_repeat("s", count($params));
    $statement = $this->connection->prepare($sql);
    $statement->bind_param($types, ...$params);
    $stmt->execute();
    return $stmt;
}

this function does a lot of good stuff:

it lets you to run a query that doesn't support prepared statements

it does no harm automatically sniffing the variable's type

at the same time it lets you to provide a type string manually, like
  $conn->execute('INSERT INTO songs VALUES (?, ?, ?)', ['foo', 'bar', 1], "ssi");

I also removed an argument unpacking operator from the function definition as it makes no sense. Trust me, it takes no effort to add two square brackets around parameters, but it makes your code WAY cleaner and more maintainable.
Closing statements
PHP is incredibly programmer-friendly. Resources don't have to be closed manually, they will be closed automatically when no longer needed.
The code
<?php

final class MySQLiConnection
{
    public $connection;

    public function __construct($config)
    {
        mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
        try {
            $this->connection = new mysqli('localhost', 'id', 'password', 'database');
            $this->connection->set_charset('utf8');
        } catch (\mysqli_sql_exception $e) {
            throw new \mysqli_sql_exception($e->getMessage(), $e->getCode());
        }
    }

    public function execute(string $sql, $params = [], $types = '') : mysqli_stmt
    {
        if (!$params) {
            return $this->connection->query($sql);
        }
        $types = $types ?: str_repeat("s", count($params));
        $statement = $this->connection->prepare($sql);
        $statement->bind_param($types, ...$params);
        $statement->execute();
        return $statement;
    }

    public function getResult(string $sql, $params = [], $types = '') : mysqli_result
    {
        return $this->execute($sql, $params, $types)->get_result();
    }
}

As you can see, the final code is much more concise, thanks to code reuse and proper error reporting.
I also made $connection variable public, as there is no more getConnection() function but you will need to access it from outside for sure.
An exception is caught in the constructor because of security concerns. A stack trace for the exception thrown in case of a connection error would contain the database credentials that will end up either in the server logs or - the worst case - displayed on the screen. Once re-thrown this way, credentials are no more exposed. So although as a rule you don't catch an Exception right in place, here it's a special case to take care of.


Refactor the method which is the sequence of the similarly looking steps to (or towards) the design patterm(s)

I share your concern regarding the code presented to contain repetitions.

Design patterns are something to notice and use on an architectural level and do not apply here.

Suggestion:
• use in-line-comments for one-liners

(I kept several things the way you coded them (and, while not objecting strongly, I'd rather not): one guideline with say meaning code:
Say what you mean, mean what you say. (Scott D. Meyers(?)))
The @return doc comment will need improving, some lines remain overly long:

/**
 * Check if the given email exists in the SendGrid recipients global list
 * and its custom field 'status' has the value 'subscribed'.
 *
 * @param  string  $email The email to check.
 *
 * @return object  (object)['isfound'=>false, 'issubscribed'=>false];
 */
public function getSubscriberStatus(string $email): object
{
    $result = (object) ['isfound' => false, 'issubscribed' => false];

    // Find the email in the SendGrid global list.
    $endpoint = "contactdb/recipients/search?email=$email";
    $found = $this->callSendGrid('GET', $endpoint);
    if ($found->status !== 200) {
        Log::error(sprintf('[SENDGRID] Error while searching the email: %s in the SendGrid list, status: %s, message: %s', $email, $found->status, $found->message));
        return $result;

        // throw new \Exception("Error while searching the email: $email in the SendGrid list");
    }

    if (!($found->data->recipient_count > 0)) {
        return $result;
    }

    // Find the recipient with email exactly matching the required one.
    $recipient = collect($found->data->recipients)->first(function ($item) use ($email) {
            return $item->email === $email;
        });

    // No exactly matching emails.
    if (!$recipient) {
        return $result;
    }

    $result->isfound = true;

    // Get the status field of the recipient's 'custom_fields' array.
    $status = collect($recipient->custom_fields)->first(function ($item) {
            return $item->name === 'status';
        });

    if ($status->value === 'subscribed') {
        $result->issubscribed = true;
    }

    return $result;
}


Empty an array on focusout - jQuery UI Autocomplete

I believe this is a case of being too paranoid in optimization. Here's some problems:

Your arr is global. You should probably place this somewhere only the widget knows about.
You're clearning the array... by creating another array. You're spawning more objects (in this case, an array) instead of cleaning up. The proper way to clear an array is to set length to 0. If nothing references the items in the array, they'll get GC'ed eventually.
autocomplete, focus, and focusout can go out of sync. When you focus on the input, you do getJSON. However, your autocomplete will run regardless if the request has returned. So that means the array might be empty when autocomplete runs. When you focus out, you cleared your array, so if you focus in again, this happens.
You're making unnecessary AJAX calls. On focus, you're calling AJAX. In the real world, waiting for AJAX is a more painful experience than memory consumption. With proper practice, the GC can and will reclaim memory but you can't reclaim the time you waited for AJAX.

I suggest you do the following instead:

You can limit the returned results to a reasonable length. That way, even if you hit the server with AJAX for each keypress, the return won't take that long.
Cache your results. Have some internal logic which caches returned data into an array (add when non-existent, update if existing). The problem here isn't the size of your cached data. It's the way you're discarding data and retrieving them back again.


I introduced a bug into our codebase by calling #titleize on a string that could possibly come in as nil

When a problem is so pervasive, it's usually a sign that there is a conceptual problem with the language itself, some call it void safety, also dubbed "the billion-dollar mistake". Some languages, specially the functional ones, use an Option type. Let's see the options in Ruby:

medication.route_name.try(:titleize). This is probably the most idiomatic approach in Rails. You say you're not totally happy, yes, it's ugly that a method name ended up being a symbol. Note, however, that if you want an empty string as fallback, you should write medication.route_name.try(:titleize) || "".
Very similar to try, I prefer the proxy approach of andand/maybe: medication.route_name.maybe.titleize || "".
medication.route_name.to_s.titleize. IMO, that's dubious. You are calling to_s to a nil object. Yes, it happens to return "", but it could as well return "nil" (see for example Python: str(None) #=> 'None'). Too implicit.
medication.route_name.present? medication.route_name.titleize : ''. You are protecting yourself against nil objects, not empty strings, so there is no need to use present?: medication.route_name ? medication.route_name.titleize : ''. As you say, this is simple but verbose. Also, imagine you have a chain of  nullable values, it becomes a real mess. That's why andand and similar libraries were created.

By the way, I've wrote about this subject at RubyIdioms.


Besides not needing to return the result of window.open, it looks pretty good. See this thread for an explanation of what returning a value from event does. From this answer,

  return false from within a jQuery event handler is effectively the
  same as calling both  e.preventDefault and e.stopPropagation on
  the passed jQuery.Event object.

  e.preventDefault() will prevent the default event from occuring,
  e.stopPropagation() will prevent the event from bubbling up and
  return false will do both. Note that this behaviour differs from
  normal (non-jQuery) event handlers, in which, notably, return false does not stop the event from bubbling up.

Clearly, thats not what we want, so instead of returning the result of window.open, we should just omit the return.

This may not be necessary, but I would be more comfortable using

var comicID = location.pathname.split("/")[1];

over

var comicID = document.URL.split("/")[3]);

mainly because http:// may be omitted from the URL and the code will still work (shouldn't ever be a problem either way). It's also more intuitive. I would also leave a comment for the code such as

// where path name looks like /156/ for xkcd.com/156/

Indentation would also help the code be more readable, however it's short so it doesn't matter too much... That said, I would write your code:

// when a user clicks the comic open the explanation
$("#comic").click(function(){
   // where pathname is the comicID eg /156/ for xkcd.com/156
   window.open("http://explainxkcd.com/wiki/index.php/" + location.pathname.split("/")[1]);
});


Interesting code,

you are skirting the rules of 'code you wrote', but I still think review of this code is valuable. In essence this code is fine, there are some style changes you might want to consider.

I am guessing part of your goal is to have a "one page has it all" HTML page, but you should really have that JavaScript in separate script file
You create a video and a div tag with JavaScript, I would have these elements already in the HTML
You are not using canvasSupport anywhere
videoLoaded is a one liner that calls another functions without parameters, I would kill that function and do

videoElement.addEventListener("canplaythrough",canvasApp,false);

It is considered better to have one single comma separated var statement:

var videoElement;
    videoDiv;

I am a fan of early returns, I would write supportedVideoFormat like this:

function supportedVideoFormat(video) {
    if (video.canPlayType("video/webm") =="probably" || video.canPlayType("video/webm") == "maybe") {
        return "webm";
    }
    if(video.canPlayType("video/mp4") == "probably" || video.canPlayType("video/mp4") == "maybe") {
        return "mp4";
    }
    if(video.canPlayType("video/ogg") =="probably" || video.canPlayType("video/ogg") == "maybe") {
        return "ogg";
    }
    return "";
}

But probably I would then get irritated by the repeated calls for the same property, so I would probably shortcut those, it would also help with the horizontal stretching:

function supportedVideoFormatExtesion(video) {
   var supportsWebM = video.canPlayType("video/webm"),
       supportsMP4  = video.canPlayType("video/mp4"),
       supportsOgg  = video.canPlayType("video/ogg");
    if (  supportsWebM =="probably" || supportsWebM == "maybe") {
        return "Webm";
    }
    if( supportsMP4 == "probably" || supportsMP4 == "maybe") {
        return "mp4";
    }
    if( supportsOgg =="probably" || supportsOgg == "maybe") {
        return "ogg";
    }
    return "";
}

This would irritate me as well, at this point it is blindingly obvious that you are trying to map a video format string to an extension string.. The above code is not the best approach to do that..

function supportedVideoFormatExtesion(video) {
   var formats    = ['video/webm','video/mp4','video/ogg'],
       extensions = ['Webm','mp4','ogg'],
       support;
   for( var i = 0 ; i < formats.length ; i++ ){
     support = video.canPlayType( formats[i] );
     if( support == 'probably' || support == 'maybe' )
     {
       return extensions[i];
     }
   }
   return "";
}

Now I can support multiple versions, and adapt easily to future changes.
In canvasApp, I would put the var statements on top. It looks odd to see you access theCanvas without it being assigned. It works, because of hoisting, but that doesnt mean you have to put all the declarations at the bottom.
The messages code looks odd, I will just say that var messages = []; is preferred over var messages = new Array(); and that personally I would write

var messages = [
    {time:7,message:"", x:0 ,y:0},
    {time:1,message:"I love David Mathews Band!", x:90 ,y:200},
    {time:4,message:"Look At Those Waves!", x:240 ,y:240},
    {time:8,message:"Look At Those Rocks!", x:100 ,y:100}
]


Why below recursive DP solution is so slow? (Leetcode Q# 123 - Best Time to Buy and Sell Stock III)

Recursion comes with overheads. You need to push to the call stack and create a new context for your code to execute in.
I would convert this to an iterative solution.
You also don't need to allocate so much memory. Think closely about what information you actually need. HINT: If you could only go long on the stock, you would only need to store 2 ints as you iterate over the list to get your maximum profit.
Furthermore leetcode has the option of viewing code from the fastest solutions. Check that out and if you don't understand why their solution is so much faster, post on stack overflow.


Concurrent LRU cache using sychronizedMap() or ReadWriteLock

My experience with variants on the java.util.concurrent.locks.* classes suggests that their sweet spot in terms of performance is when the work to be done is relatively substantial compared to the lock overhead time. Remember, when you use Reentrant or ReadWrite locks, that there is a a call at both the beginning and end of the locked block.

As a consequence, I would advise against the ReadWriteLock system you have going. Apart from other things, it is not implemented correctly because, yes, multiple threads can be 'getting' values from the backing map, and they could each be modifying the access order. get(...) is not a read-only operation. It has side-effects.

Still, I don't like alternative of using Collections.synchronizedMap(...). This also has overheads, and can cause additional members in the call-stack as one synchronized method may call another, etc.

The most simple solution, and the one I recommend, would be to use plain-old-synchronization:

   private final Map<K,V> cache;

   public LRUConcurrentCache(final int maxEntries) {
      this.cache = new LinkedHashMap<K,V>(maxEntries, 0.75F, true) {
               private static final long serialVersionUID = -1236481390177598762L;
               @Override
               protected boolean removeEldestEntry(Map.Entry<K,V> eldest){
                  return size() > maxEntries;
               }
            };
   }

   public void put(K key, V value) {
       synchronized(cache) {
          cache.put(key, value);
       }
   }
   public V get(K key) {
       synchronized(cache) {
           return cache.get(key);
       }
   }

Note, while going through the code, I made the following additional changes:

I made the input parameter to the constructor maxEntries a final value. This means you can reference it from the constructor and removeEldestEntry methods of the LinkedHashMap without having to re-declare it on the instance
Your indentation is all off.... 3-space indents? That's unusual.
You have a lot of trailing white-space in your code. You do a block-based select instead of text-based?
Your whitespace handling before/after braces and operators is inconsistent.

I get the impression you are using vim or some other console editor to manage your code. You should consider the gg=G shortcut in vim to re-indent all your code consistently.


Java method refactoring: getting the file name or path

When we refactor the aim is to reduce code duplication. but you introduced even more duplication.

The way to go is to look out for code that is similar and make it the same.

When looking at your original method the duplication is in the if/else cascade. This means you should deal with that. The obvious differences are:

the string literal used
the else before the second if
the method called at the object file

Lets convert that in thee steps:

the else is not needed for business reasons. It is introduced for performance optimization. You can safely remove this else and verify by measurement it that has really an impact. My guess is it does not. so lets let rid of it:

if(pathOrName.equalsIgnoreCase("path")) {
    for (File file : listOfFiles) {
        if (file.isFile()) {
            files.add(file.toString());
        }
    }
}
if(pathOrName.equalsIgnoreCase("name")) {
    for (File file : listOfFiles) {
        if (file.isFile()) {
            files.add(file.getName());
        }
    }
}

now you can extract the first literal string into a variable:

String requestedPathName = "path";
if(pathOrName.equalsIgnoreCase(requestedPathName)) {
    for (File file : listOfFiles) {
        if (file.isFile()) {
            files.add(file.toString());
        }
    }
}
if(pathOrName.equalsIgnoreCase("name")) {
  // ...

Then, after the first if block we can resuse this variable:

String requestedPathName = "path";
if(pathOrName.equalsIgnoreCase(requestedPathName)) {
    for (File file : listOfFiles) {
        if (file.isFile()) {
            files.add(file.toString());
        }
    }
}
requestedPathName = "name";
if(pathOrName.equalsIgnoreCase(requestedPathName)) {
  // ...

The last change requires to use an interface. This interface should declare a method that takes a file object as a parameter and returns a String object. One option is to define such interface yourself:

@FunctionalInterface
interface FileToStringConverter{
     String convert(File file);
}

Or we use the Function interface provides by the Java standard Lib. I choose the latter.

The principle is the same as with the string literal before:

replace the original code with the interface usage:

if(pathOrName.equalsIgnoreCase(requestedPathName)) {
    for (File file : listOfFiles) {
        if (file.isFile()) {
            files.add(new Function<File,String>(){
      @Override public String apply(File t){
           t.toString();
         }
      }.apply(file));
        }
    }
}

extract the interface implementation to a local variable:

// interface implemented as Lambda and method reference.
Function<File,String> converter = File::toString; // interface implemented as Lambda and method reference.
 if(pathOrName.equalsIgnoreCase(requestedPathName)) {
    for (File file : listOfFiles) {
        if (file.isFile()) {
            files.add(converter.apply(file));
        }
    }
}

repeat this in the other `if block:

String requestedPathName = "path";
Function<File,String> converter = File::toString;
  if(pathOrName.equalsIgnoreCase(requestedPathName)) {
    for (File file : listOfFiles) {
        if (file.isFile()) {
            files.add(converter.apply(file));
        }
    }
}
requestedPathName = "name";
converter = File::getName;
if(pathOrName.equalsIgnoreCase(requestedPathName)) {
    for (File file : listOfFiles) {
        if (file.isFile()) {
            files.add(converter.apply(file));
        }
    }
}

Now both if blocks look exactly the same. You can select one of them and apply your IDEs extract method automated refactoring feature:

public static ArrayList<String> getFilePathOrName(String pathOrName) {
    ArrayList<String> files = new ArrayList<>();
    File folder = new File("C:\\Users\\damar\\OneDrive\\Documenten\\FolderTest\\Folderretouren\\Niet verdeeld");
    File[] listOfFiles = folder.listFiles();

        String requestedPathName = "path";
        Function<File,String> converter = File::getName;
        // of cause you should choose a better name for the method!
        extracted(requestedPathName, pathOrName, converter, listOfFiles, files);
        requestedPathName = "name";
        converter = File::getName;
        extracted(requestedPathName, pathOrName, converter, listOfFiles, files);

    return files;
}

private void extracted(
           String requestedPathName,
           String pathOrName,
           Function<File,String> converter,
           File[] listOfFiles,
           List<File> files) {
    if(pathOrName.equalsIgnoreCase(requestedPathName)) {
        for (File file : listOfFiles) {
            if (file.isFile()) {
                files.add(converter.apply(file));
            }
        }
    }
}

last step is inlineing the variables:

     extracted("path", pathOrName, File::toString, listOfFiles, files);
     extracted("name", pathOrName, File::getName, listOfFiles, files);

The complete result (with a better name for the extracted method) is:

public static ArrayList<String> getFilePathOrName(String pathOrName) {
    ArrayList<String> files = new ArrayList<>();
    File folder = new File("C:\\Users\\damar\\OneDrive\\Documenten\\FolderTest\\Folderretouren\\Niet verdeeld");
    File[] listOfFiles = folder.listFiles();

    addPathOrNameToList("path", pathOrName, File::toString, listOfFiles, files);
    addPathOrNameToList("name", pathOrName, File::getName, listOfFiles, files);

    return files;
}

private void addPathOrNameToList(
           String requestedPathName,
           String pathOrName,
           Function<File,String> fileToStringConversion,
           File[] listOfFiles,
           List<File> files) {
    if(pathOrName.equalsIgnoreCase(requestedPathName)) {
        for (File file : listOfFiles) {
            if (file.isFile()) {
                files.add(fileToStringConversion.apply(file));
            }
        }
    }
}

We could turn the repeated method call into a loop if we would introduce another interface or an enum to encapsulate the differing data.


You shouldn't pass a char* as buffer end but a size_t size corresponding to the size of the allocated buffer. So your available length will be size - 2 ("zero-indexed" and "trailing '\0'").
You return either 1 or 0, why don't using bool as return type? (Or maybe a size_t corresponding to the final string length, but, that's a design decision).
Variables where value doesn't change in your function (as locales or parameters) should be marked const. That's not faster but it show your intends.
You can maybe use strcpy, strncpy or  memcpy to ... copy the replacements string into destination (and replace multiple incrementation by a single add-assign).
For non-special chars sequences, you can maybe get them in chunk by chunk (between two special chars) with strcspn or strpbrk. (and after, copying them with same functions than former)

Edit

This is a raw try using theses functions.

I think it is safe, with no overflow, but maybe not the optimal implement.
Don't be scared about the size, there is a lot of comments :)

I outed two functions from source (strlenand replace_chrstr), 'cause I think they are reusable somewhere.

#include <string.h>

// Get the position of the c char in the str string.
// -> str: a null-terminated string where to lookup
// -> needle: char to find
// Return: Position of the char `c` or 1 past the end (strlen + 1)
size_t strpos(const char* const str, const char c)
{
    char* p = strchr(str, c);
    return p ? (p - str) : strlen(str) + 1;
}

// Scan `in_str` and replace all char occurrences from `search`
// by corresponding string from `replace`, then place the result in `out_str`.
// -> search: A null-terminated string with all char to fiend
// -> replace: An array of null-terminated strings with index based replacement from `search`
// -> out_str: a buffer to put the result, at least as big than max_size
// -> in_str: a null-terminated string where to process replacements
// Return: length of resulting string, or length+1 in case of overflow
size_t replace_chrstr(const char* const search, const char* const* const replace,
                      char *const out_str, const char* const in_str, const size_t max_size)
{
    size_t in_offset = 0;
    size_t out_offset = 0;
    size_t index;
    size_t length;
    const size_t index_max = strlen(search);
    const size_t length_max = strlen(in_str);

    while (max_size > out_offset) {
        length = strcspn(in_str + in_offset, search);
        // buffer overflow detected, here we truncate the input string
        // we add `\0` and return max_size (equivalent to strlen + 1)
        // but maybe you want another handling
        if (max_size <= out_offset + length) {
            strncpy(out_str + out_offset, in_str + in_offset, max_size-out_offset-1);
            out_str[max_size-1] = '\0';
            return max_size;
        }
        strncpy(out_str + out_offset, in_str + in_offset, length);
        in_offset += length + 1;
        out_offset += length;
        // normal end of input string
        // add a `\0`, then return out_offset (equivalent to strlen)
        if (in_str[in_offset-1] == '\0') {
            out_str[out_offset] = '\0';
            return out_offset;
        }
        index = strpos(search, in_str[in_offset-1]);
        length = strlen(replace[index]);
        // buffer overflow detected, here we truncate the replacement string
        // we add `\0` and return max_size (equivalent to strlen + 1)
        // but maybe you want another handling
        if (max_size <= out_offset + length) {
            strncpy(out_str + out_offset, replace[index], max_size-out_offset-1);
            out_str[max_size-1] = '\0';
            return max_size;
        }
        strcpy(out_str + out_offset, replace[index]);
        out_offset += length;
    }
    // we never reach here, normally
    return 0;
}

size_t www_specialchars_html(char* const dest, const char* const source, size_t max_size)
{
    const char search[] = "&\"'<>";
    const char * replace[] = {"&amp;","&quot;","&#039;","&lt;","&gt;"};
    return replace_chrstr(search, replace, dest, source, max_size);
}


Use of external memory or a custom allocator

I think that in order to be a good review candidate, this should be more than an "outline." Like, there should be an example of how you intend to use it.

But here's some stylistic feedback:

CamelCase your template parameter names: IntType (or just T), Alloc.
You can (and should) use the injected class-name uses_custom_buffers inside the class itself, rather than typing out uses_custom_buffers<int_type, alloc> every time.
Don't define multiple (member) variables on the same line.
Mark your constructors explicit unless you want to enable the implicit conversion for some specific reason.
Explicitly mark your base classes public and private, for clarity.
Writing std::size_t instead of size_t, or typename instead of class, is just extra keyboard practice. Personally, I always go for the shorter versions.
Always brace your if and for bodies. Don't goto fail!

    this->uses_custom_buffers<int_type, void>::set_buffer(count, buffer, size);

This seems complicated. Ideally we'd just write

    set_buffer(count, buffer, size);

But since that set_buffer is located in a dependent base class, we actually have to write this-> in front:

    this->set_buffer(count, buffer, size);

And then we still have trouble, because the declaration of set_buffer in uses_custom_buffers<int_type, alloc> hides the declaration of set_buffer in uses_custom_buffers<int_type, void>! There are two clean ways to fix this, depending on what you want to do. The first is to bring the hidden set_buffer back into scope with a using-declaration:

using uses_custom_buffers<int_type, void>::set_buffer;

The second is to pick a different name for one or both of the functions in this overload set.

  "If you have two [functions] that are doing something very very different, please, name them differently." —Titus Winters, 2018

I would even argue that uses_custom_buffers<int_type, void> is doing something "very very different" from uses_custom_buffers<int_type, alloc>, and therefore it should be named differently.

Very important:

typename alloc::rebind<int_type*>::other pointer_alloc;

This is (A) missing a template keyword, and (B) waaay too complicated for one line of code. Break it down by using a typedef:

using PointerAlloc = typename alloc::template rebind<int_type *>::other;
PointerAlloc pointer_alloc;

However, this is (C) still broken, because it fails to use allocator_traits. You need to write this instead:

using PointerTraits = typename std::allocator_traits<alloc>::template rebind_traits<int_type *>;
using PointerAlloc = typename std::allocator_traits<alloc>::template rebind_alloc<int_type *>;
PointerAlloc pointer_alloc;

And then on the next line:

int_type** buffer = pointer_alloc.allocate(count);

should be

int_type **buffer = PointerTraits::allocate(pointer_alloc, count);

However, after all that, I am still super duper confused about where your allocator is supposed to come from! You just default-constructed it and immediately used it to allocate some memory? Where is the memory supposed to come from?

If you want to use the standard allocator model, you need to provide a way for the user to pass in an allocator for you to use. You can't just default-construct one and expect it to magically know where its heap is located. (That happens to work for std::allocator because it just uses new and delete, which are global; but it is highly unlikely to work for any user-provided allocator type.)

Let's put it all together and see how it looks:

template<class T>
class use_custom_buffers_base {
public:
    use_custom_buffers_base *set_buffers(size_t count, T **buffers, size_t size) {
        this->m_buf   = buffers;
        this->m_count = count;
        this->m_size  = size;
        return this;
    }

private:
    T **m_buf;
    size_t m_count;
    size_t m_size;
};

template<class T, class Alloc>
class use_custom_buffers : private use_custom_buffers_base<T>
{
    using Base = use_custom_buffers_base<T>;
    using ATraits = std::allocator_traits<Alloc>;
    using PTraits = typename ATraits::template rebind_traits<T*>;
    using PAlloc = typename PTraits::allocator_type;

public:
    explicit use_custom_buffers(Alloc alloc) : m_alloc(std::move(alloc)) {}

    use_custom_buffers *set_buffers(size_t count, size_t size) {
        PAlloc pointer_alloc(m_alloc);
        T **buffers = PTraits::allocate(pointer_alloc, count);
        for (size_t i = 0; i < count; ++i) {
            buffers[i] = ATraits::allocate(m_alloc, size);
        }
        this->Base::set_buffers(count, buffers, size);
        return this;
    }

private:
    Alloc m_alloc;
};

There's still work to do. count and size are strange names, especially since size is also a count (of T objects), not the "size" of any entity in the program. I decided to punt on the question of what to call Base::set_buffers. The arguments to set_buffers are in a weird order (length, pointer, other-length). It is unclear from your description whether anyone in the codebase actually cares about use_custom_buffers_base or whether it could be completely hidden away in a detail namespace — or, indeed, inlined into use_custom_buffers, since the inheritance relationship here seems like it's doing more harm than good.

Finally, a possible performance issue: Why are you calling allocate in a loop?

        for (size_t i = 0; i < count; ++i) {
            buffers[i] = ATraits::allocate(m_alloc, size);
        }

Surely it would be more performant to allocate just once and then use pointers into different parts of that buffer?

        auto ptr = ATraits::allocate(m_alloc, count * size);
        for (size_t i = 0; i < count; ++i) {
            buffers[i] = ptr + (i * size);
        }


Actually #1 is called smurf naming (here is a question about it on Programmers.SE).

One thing to consider: Do you have to work with more than one ViewOptions at the same time (or at the same source file)? If that's true having a more specific name would help. Two possible advantages of smurfier names:

There aren't multiple editor tabs with the same filename.
You don't have to use full package names to declare two ViewOptions in the same source file.

  So I made a DatatablesOptions class for the general usecase and if
  I need additional fields I extend the DatatablesOptions class.

Check Effective Java, Second Edition, Item 16: Favor composition over inheritance if you don't know already.
Try to format the code in a way which avoid unnecessary horizontal scrolling. It would make it esasier to read.
@RequestParam (value="iDisplayStart")int startLine,
@RequestParam (value="iDisplayLength")int linesPerPage,
@RequestParam (value="iSortCol_0")int columnToSort,
@RequestParam (value="sSearch", required = false) String     searchString,

Some of the parameters have a space between the closing parentheses (...false) String) , some of them doesn't (...th")int linesPerPage). You can find another inconsistencies too. It should be consistent. Modern IDEs have autoformat, they do a really good job here, use them.


I tested it and it works as it should. I would only like to remark a couple of things.

You may want to split your long commented function into shorter ones:

static int[] InitArray(int length){...}
static int[] SelectionSort(int[]arr){...}
static void Swap(int[]arr, int i, int j){...}
print the result in the main(), as you do know.

This makes your code easier to read and easier to reuse.

Another thing I'd remove is the if(max != i). I'd rather make the swap every time.  If you look carefully, there's small chance that you do this operation unnecessarily, and when you do do it, it won't harm you.

Note: If you keep doing the swap as you do now, you won't have any problem by removing the if. However, if you modify it to make the swap without a temp variable, it might go wrong.


This TagName column holding all the tags is denormalized and the non-equi-join ON #MyPosts._tags LIKE '%<'+Tags.TagName +'>%' kills performance. There's no efficient way for the optimizer to do this join, thus it's like a Cross-Join to the 50000+ rows in Tags.

But the base data model is normalized, there's an associative table PostTags between Posts and Tags and then it's simple equi-joins:

with MyPosts as
 (
-- The tags and scores of my posts
   SELECT
     Question.Id AS PostId,
     Answers.Score
   FROM
     Posts as Answers
   INNER JOIN
     Posts AS Question
   ON
     Question.Id = Answers.ParentId
   WHERE
     Answers.PostTypeId = 2 AND
     Answers.OwnerUserId = ##UserId:int?8041461##
 )
-- All of the tags with the total score and the amount of times used
SELECT
  t.TagName,
  sum(score) as "Total Score",
  count(*) as "Answer Count",
  cast(sum(score) as FLOAT) / count(*) as 'Average Score'
FROM
  MyPosts AS p
JOIN PostTags AS pt
  ON p.PostId = pt.PostId
JOIN Tags AS t
 ON pt.TagId = t.Id
GROUP BY t.Id,t.TagName
ORDER BY "Total Score" DESC;

Your HAVING sum(score) IS NULL is not needed, there's no NULL score.

See SEDE query which runs fine with John Skeet, too :-)


Naming

I suggest renaming getShortestPathBetweenWords() to  findShortestLadderDistance() for the following reasons:

get is recommended as a prefix for simple lookup functions. Use another verb such as compute or find for meatier, computationally heavier functions.
You are actually computing the distance of the shortest path, not the path itself. And a ladder is a more specific word for path whose neighboring words differ by exactly one substitution.

Further naming suggestions:

Rename _generateNewWords() to generateNeighbors()
Rename level to distance
Rename st to start
Rename newWord to next
Rename q to queue
Rename listOfWords to neighbors
Rename charArray to chars

Style

Instead of while (queue.length !== 0) I suggest the more self-documenting while (queue.length > 0) as the length can never be negative.

Also, don't needlessly mix "" vs. '' for strings.

Specification

Right now you are returning a distance of 0 when there is no path and a distance of 1 if start equals end. I suggest following the common definition of path length and return Infinity and 0 instead.

You might also want to pass the alphabet as a parameter instead of having a hard-coded 'magic' constant in your _generateNewWords() function. It can easily be computed from your dictionary as alphabet = [...new Set(dict.join(""))].

Also, you currently allow any word for start while end must be part of the dictionary. I recommend allowing non-dictionary words in both cases for consistency.

Performance

Your main performance bottleneck is the checkinDictionary() function. If you keep track of a set of open words which you haven't visited yet, you can replace that function call with a simple open.has(word). Set lookup time is constant and thus much faster than iterating the whole dict array.

You then have to pass the open set to generateNeighbors(). The isVisited map is no longer needed.

Another performance drain is performing string splitting via let charArray = word.split('') in the inner loop of _generateNewWords. You can push that to the outer loop.

Also, you currently treat start.length < end.length as a special 'shortcut' case. You could generalize this to start.length != end.length.

Sample code

Applying all those modifications to your code yields:

function findShortestLadderDistance(start, end, alphabet, dict) {
  if (start === end) return 0;
  if (start.length != end.length) return Infinity;

  let queue = [start];
  let distance = 1;
  let open = new Set(dict);
  open.delete(start);
  open.add(end);

  while (queue.length > 0) {
    for (let i = 0, length = queue.length; i < length; i++) {
      let next = queue.shift();

      for (let neighbor of generateNeighbors(next, alphabet, open)) {
        if (neighbor === end) return distance;

        queue.push(neighbor);
        open.delete(neighbor);
      }
    }
    distance++;
  }
  return Infinity;
}

function* generateNeighbors(word, alphabet, open) {
  let chars = word.split("");

  for (let i = 0; i < chars.length; i++) {
    let char = chars[i];

    for (let j = 0; j < alphabet.length; j++) {
      chars[i] = alphabet[j];
      neighbor = chars.join("");
      if (open.has(neighbor)) yield neighbor;
    }
    chars[i] = char;
  }
}

let start = "sand";
let end = "acne";
let dict = ["slit","bunk","wars","ping","viva","wynn","wows","irks","gang","pool","mock","fort","heel","send","ship","cols","alec","foal","nabs","gaze","giza","mays","dogs","karo","cums","jedi","webb","lend","mire","jose","catt","grow","toss","magi","leis","bead","kara","hoof","than","ires","baas","vein","kari","riga","oars","gags","thug","yawn","wive","view","germ","flab","july","tuck","rory","bean","feed","rhee","jeez","gobs","lath","desk","yoko","cute","zeus","thus","dims","link","dirt","mara","disc","limy","lewd","maud","duly","elsa","hart","rays","rues","camp","lack","okra","tome","math","plug","monk","orly","friz","hogs","yoda","poop","tick","plod","cloy","pees","imps","lead","pope","mall","frey","been","plea","poll","male","teak","soho","glob","bell","mary","hail","scan","yips","like","mull","kory","odor","byte","kaye","word","honk","asks","slid","hopi","toke","gore","flew","tins","mown","oise","hall","vega","sing","fool","boat","bobs","lain","soft","hard","rots","sees","apex","chan","told","woos","unit","scow","gilt","beef","jars","tyre","imus","neon","soap","dabs","rein","ovid","hose","husk","loll","asia","cope","tail","hazy","clad","lash","sags","moll","eddy","fuel","lift","flog","land","sigh","saks","sail","hook","visa","tier","maws","roeg","gila","eyes","noah","hypo","tore","eggs","rove","chap","room","wait","lurk","race","host","dada","lola","gabs","sobs","joel","keck","axed","mead","gust","laid","ends","oort","nose","peer","kept","abet","iran","mick","dead","hags","tens","gown","sick","odis","miro","bill","fawn","sumo","kilt","huge","ores","oran","flag","tost","seth","sift","poet","reds","pips","cape","togo","wale","limn","toll","ploy","inns","snag","hoes","jerk","flux","fido","zane","arab","gamy","raze","lank","hurt","rail","hind","hoot","dogy","away","pest","hoed","pose","lose","pole","alva","dino","kind","clan","dips","soup","veto","edna","damp","gush","amen","wits","pubs","fuzz","cash","pine","trod","gunk","nude","lost","rite","cory","walt","mica","cart","avow","wind","book","leon","life","bang","draw","leek","skis","dram","ripe","mine","urea","tiff","over","gale","weir","defy","norm","tull","whiz","gill","ward","crag","when","mill","firs","sans","flue","reid","ekes","jain","mutt","hems","laps","piss","pall","rowe","prey","cull","knew","size","wets","hurl","wont","suva","girt","prys","prow","warn","naps","gong","thru","livy","boar","sade","amok","vice","slat","emir","jade","karl","loyd","cerf","bess","loss","rums","lats","bode","subs","muss","maim","kits","thin","york","punt","gays","alpo","aids","drag","eras","mats","pyre","clot","step","oath","lout","wary","carp","hums","tang","pout","whip","fled","omar","such","kano","jake","stan","loop","fuss","mini","byrd","exit","fizz","lire","emil","prop","noes","awed","gift","soli","sale","gage","orin","slur","limp","saar","arks","mast","gnat","port","into","geed","pave","awls","cent","cunt","full","dint","hank","mate","coin","tars","scud","veer","coax","bops","uris","loom","shod","crib","lids","drys","fish","edit","dick","erna","else","hahs","alga","moho","wire","fora","tums","ruth","bets","duns","mold","mush","swop","ruby","bolt","nave","kite","ahem","brad","tern","nips","whew","bait","ooze","gino","yuck","drum","shoe","lobe","dusk","cult","paws","anew","dado","nook","half","lams","rich","cato","java","kemp","vain","fees","sham","auks","gish","fire","elam","salt","sour","loth","whit","yogi","shes","scam","yous","lucy","inez","geld","whig","thee","kelp","loaf","harm","tomb","ever","airs","page","laud","stun","paid","goop","cobs","judy","grab","doha","crew","item","fogs","tong","blip","vest","bran","wend","bawl","feel","jets","mixt","tell","dire","devi","milo","deng","yews","weak","mark","doug","fare","rigs","poke","hies","sian","suez","quip","kens","lass","zips","elva","brat","cosy","teri","hull","spun","russ","pupa","weed","pulp","main","grim","hone","cord","barf","olav","gaps","rote","wilt","lars","roll","balm","jana","give","eire","faun","suck","kegs","nita","weer","tush","spry","loge","nays","heir","dope","roar","peep","nags","ates","bane","seas","sign","fred","they","lien","kiev","fops","said","lawn","lind","miff","mass","trig","sins","furl","ruin","sent","cray","maya","clog","puns","silk","axis","grog","jots","dyer","mope","rand","vend","keen","chou","dose","rain","eats","sped","maui","evan","time","todd","skit","lief","sops","outs","moot","faze","biro","gook","fill","oval","skew","veil","born","slob","hyde","twin","eloy","beat","ergs","sure","kobe","eggo","hens","jive","flax","mons","dunk","yest","begs","dial","lodz","burp","pile","much","dock","rene","sago","racy","have","yalu","glow","move","peps","hods","kins","salk","hand","cons","dare","myra","sega","type","mari","pelt","hula","gulf","jugs","flay","fest","spat","toms","zeno","taps","deny","swag","afro","baud","jabs","smut","egos","lara","toes","song","fray","luis","brut","olen","mere","ruff","slum","glad","buds","silt","rued","gelt","hive","teem","ides","sink","ands","wisp","omen","lyre","yuks","curb","loam","darn","liar","pugs","pane","carl","sang","scar","zeds","claw","berg","hits","mile","lite","khan","erik","slug","loon","dena","ruse","talk","tusk","gaol","tads","beds","sock","howe","gave","snob","ahab","part","meir","jell","stir","tels","spit","hash","omit","jinx","lyra","puck","laue","beep","eros","owed","cede","brew","slue","mitt","jest","lynx","wads","gena","dank","volt","gray","pony","veld","bask","fens","argo","work","taxi","afar","boon","lube","pass","lazy","mist","blot","mach","poky","rams","sits","rend","dome","pray","duck","hers","lure","keep","gory","chat","runt","jams","lays","posy","bats","hoff","rock","keri","raul","yves","lama","ramp","vote","jody","pock","gist","sass","iago","coos","rank","lowe","vows","koch","taco","jinn","juno","rape","band","aces","goal","huck","lila","tuft","swan","blab","leda","gems","hide","tack","porn","scum","frat","plum","duds","shad","arms","pare","chin","gain","knee","foot","line","dove","vera","jays","fund","reno","skid","boys","corn","gwyn","sash","weld","ruiz","dior","jess","leaf","pars","cote","zing","scat","nice","dart","only","owls","hike","trey","whys","ding","klan","ross","barb","ants","lean","dopy","hock","tour","grip","aldo","whim","prom","rear","dins","duff","dell","loch","lava","sung","yank","thar","curl","venn","blow","pomp","heat","trap","dali","nets","seen","gash","twig","dads","emmy","rhea","navy","haws","mite","bows","alas","ives","play","soon","doll","chum","ajar","foam","call","puke","kris","wily","came","ales","reef","raid","diet","prod","prut","loot","soar","coed","celt","seam","dray","lump","jags","nods","sole","kink","peso","howl","cost","tsar","uric","sore","woes","sewn","sake","cask","caps","burl","tame","bulk","neva","from","meet","webs","spar","fuck","buoy","wept","west","dual","pica","sold","seed","gads","riff","neck","deed","rudy","drop","vale","flit","romp","peak","jape","jews","fain","dens","hugo","elba","mink","town","clam","feud","fern","dung","newt","mime","deem","inti","gigs","sosa","lope","lard","cara","smug","lego","flex","doth","paar","moon","wren","tale","kant","eels","muck","toga","zens","lops","duet","coil","gall","teal","glib","muir","ails","boer","them","rake","conn","neat","frog","trip","coma","must","mono","lira","craw","sled","wear","toby","reel","hips","nate","pump","mont","died","moss","lair","jibe","oils","pied","hobs","cads","haze","muse","cogs","figs","cues","roes","whet","boru","cozy","amos","tans","news","hake","cots","boas","tutu","wavy","pipe","typo","albs","boom","dyke","wail","woke","ware","rita","fail","slab","owes","jane","rack","hell","lags","mend","mask","hume","wane","acne","team","holy","runs","exes","dole","trim","zola","trek","puma","wacs","veep","yaps","sums","lush","tubs","most","witt","bong","rule","hear","awry","sots","nils","bash","gasp","inch","pens","fies","juts","pate","vine","zulu","this","bare","veal","josh","reek","ours","cowl","club","farm","teat","coat","dish","fore","weft","exam","vlad","floe","beak","lane","ella","warp","goth","ming","pits","rent","tito","wish","amps","says","hawk","ways","punk","nark","cagy","east","paul","bose","solo","teed","text","hews","snip","lips","emit","orgy","icon","tuna","soul","kurd","clod","calk","aunt","bake","copy","acid","duse","kiln","spec","fans","bani","irma","pads","batu","logo","pack","oder","atop","funk","gide","bede","bibs","taut","guns","dana","puff","lyme","flat","lake","june","sets","gull","hops","earn","clip","fell","kama","seal","diaz","cite","chew","cuba","bury","yard","bank","byes","apia","cree","nosh","judo","walk","tape","taro","boot","cods","lade","cong","deft","slim","jeri","rile","park","aeon","fact","slow","goff","cane","earp","tart","does","acts","hope","cant","buts","shin","dude","ergo","mode","gene","lept","chen","beta","eden","pang","saab","fang","whir","cove","perk","fads","rugs","herb","putt","nous","vane","corm","stay","bids","vela","roof","isms","sics","gone","swum","wiry","cram","rink","pert","heap","sikh","dais","cell","peel","nuke","buss","rasp","none","slut","bent","dams","serb","dork","bays","kale","cora","wake","welt","rind","trot","sloe","pity","rout","eves","fats","furs","pogo","beth","hued","edam","iamb","glee","lute","keel","airy","easy","tire","rube","bogy","sine","chop","rood","elbe","mike","garb","jill","gaul","chit","dons","bars","ride","beck","toad","make","head","suds","pike","snot","swat","peed","same","gaza","lent","gait","gael","elks","hang","nerf","rosy","shut","glop","pain","dion","deaf","hero","doer","wost","wage","wash","pats","narc","ions","dice","quay","vied","eons","case","pour","urns","reva","rags","aden","bone","rang","aura","iraq","toot","rome","hals","megs","pond","john","yeps","pawl","warm","bird","tint","jowl","gibe","come","hold","pail","wipe","bike","rips","eery","kent","hims","inks","fink","mott","ices","macy","serf","keys","tarp","cops","sods","feet","tear","benz","buys","colo","boil","sews","enos","watt","pull","brag","cork","save","mint","feat","jamb","rubs","roxy","toys","nosy","yowl","tamp","lobs","foul","doom","sown","pigs","hemp","fame","boor","cube","tops","loco","lads","eyre","alta","aged","flop","pram","lesa","sawn","plow","aral","load","lied","pled","boob","bert","rows","zits","rick","hint","dido","fist","marc","wuss","node","smog","nora","shim","glut","bale","perl","what","tort","meek","brie","bind","cake","psst","dour","jove","tree","chip","stud","thou","mobs","sows","opts","diva","perm","wise","cuds","sols","alan","mild","pure","gail","wins","offs","nile","yelp","minn","tors","tran","homy","sadr","erse","nero","scab","finn","mich","turd","then","poem","noun","oxus","brow","door","saws","eben","wart","wand","rosa","left","lina","cabs","rapt","olin","suet","kalb","mans","dawn","riel","temp","chug","peal","drew","null","hath","many","took","fond","gate","sate","leak","zany","vans","mart","hess","home","long","dirk","bile","lace","moog","axes","zone","fork","duct","rico","rife","deep","tiny","hugh","bilk","waft","swig","pans","with","kern","busy","film","lulu","king","lord","veda","tray","legs","soot","ells","wasp","hunt","earl","ouch","diem","yell","pegs","blvd","polk","soda","zorn","liza","slop","week","kill","rusk","eric","sump","haul","rims","crop","blob","face","bins","read","care","pele","ritz","beau","golf","drip","dike","stab","jibs","hove","junk","hoax","tats","fief","quad","peat","ream","hats","root","flak","grit","clap","pugh","bosh","lock","mute","crow","iced","lisa","bela","fems","oxes","vies","gybe","huff","bull","cuss","sunk","pups","fobs","turf","sect","atom","debt","sane","writ","anon","mayo","aria","seer","thor","brim","gawk","jack","jazz","menu","yolk","surf","libs","lets","bans","toil","open","aced","poor","mess","wham","fran","gina","dote","love","mood","pale","reps","ines","shot","alar","twit","site","dill","yoga","sear","vamp","abel","lieu","cuff","orbs","rose","tank","gape","guam","adar","vole","your","dean","dear","hebe","crab","hump","mole","vase","rode","dash","sera","balk","lela","inca","gaea","bush","loud","pies","aide","blew","mien","side","kerr","ring","tess","prep","rant","lugs","hobo","joke","odds","yule","aida","true","pone","lode","nona","weep","coda","elmo","skim","wink","bras","pier","bung","pets","tabs","ryan","jock","body","sofa","joey","zion","mace","kick","vile","leno","bali","fart","that","redo","ills","jogs","pent","drub","slaw","tide","lena","seep","gyps","wave","amid","fear","ties","flan","wimp","kali","shun","crap","sage","rune","logs","cain","digs","abut","obit","paps","rids","fair","hack","huns","road","caws","curt","jute","fisk","fowl","duty","holt","miss","rude","vito","baal","ural","mann","mind","belt","clem","last","musk","roam","abed","days","bore","fuze","fall","pict","dump","dies","fiat","vent","pork","eyed","docs","rive","spas","rope","ariz","tout","game","jump","blur","anti","lisp","turn","sand","food","moos","hoop","saul","arch","fury","rise","diss","hubs","burs","grid","ilks","suns","flea","soil","lung","want","nola","fins","thud","kidd","juan","heps","nape","rash","burt","bump","tots","brit","mums","bole","shah","tees","skip","limb","umps","ache","arcs","raft","halo","luce","bahs","leta","conk","duos","siva","went","peek","sulk","reap","free","dubs","lang","toto","hasp","ball","rats","nair","myst","wang","snug","nash","laos","ante","opal","tina","pore","bite","haas","myth","yugo","foci","dent","bade","pear","mods","auto","shop","etch","lyly","curs","aron","slew","tyro","sack","wade","clio","gyro","butt","icky","char","itch","halt","gals","yang","tend","pact","bees","suit","puny","hows","nina","brno","oops","lick","sons","kilo","bust","nome","mona","dull","join","hour","papa","stag","bern","wove","lull","slip","laze","roil","alto","bath","buck","alma","anus","evil","dumb","oreo","rare","near","cure","isis","hill","kyle","pace","comb","nits","flip","clop","mort","thea","wall","kiel","judd","coop","dave","very","amie","blah","flub","talc","bold","fogy","idea","prof","horn","shoo","aped","pins","helm","wees","beer","womb","clue","alba","aloe","fine","bard","limo","shaw","pint","swim","dust","indy","hale","cats","troy","wens","luke","vern","deli","both","brig","daub","sara","sued","bier","noel","olga","dupe","look","pisa","knox","murk","dame","matt","gold","jame","toge","luck","peck","tass","calf","pill","wore","wadi","thur","parr","maul","tzar","ones","lees","dark","fake","bast","zoom","here","moro","wine","bums","cows","jean","palm","fume","plop","help","tuba","leap","cans","back","avid","lice","lust","polo","dory","stew","kate","rama","coke","bled","mugs","ajax","arts","drug","pena","cody","hole","sean","deck","guts","kong","bate","pitt","como","lyle","siam","rook","baby","jigs","bret","bark","lori","reba","sups","made","buzz","gnaw","alps","clay","post","viol","dina","card","lana","doff","yups","tons","live","kids","pair","yawl","name","oven","sirs","gyms","prig","down","leos","noon","nibs","cook","safe","cobb","raja","awes","sari","nerd","fold","lots","pete","deal","bias","zeal","girl","rage","cool","gout","whey","soak","thaw","bear","wing","nagy","well","oink","sven","kurt","etna","held","wood","high","feta","twee","ford","cave","knot","tory","ibis","yaks","vets","foxy","sank","cone","pius","tall","seem","wool","flap","gird","lore","coot","mewl","sere","real","puts","sell","nuts","foil","lilt","saga","heft","dyed","goat","spew","daze","frye","adds","glen","tojo","pixy","gobi","stop","tile","hiss","shed","hahn","baku","ahas","sill","swap","also","carr","manx","lime","debs","moat","eked","bola","pods","coon","lacy","tube","minx","buff","pres","clew","gaff","flee","burn","whom","cola","fret","purl","wick","wigs","donn","guys","toni","oxen","wite","vial","spam","huts","vats","lima","core","eula","thad","peon","erie","oats","boyd","cued","olaf","tams","secs","urey","wile","penn","bred","rill","vary","sues","mail","feds","aves","code","beam","reed","neil","hark","pols","gris","gods","mesa","test","coup","heed","dora","hied","tune","doze","pews","oaks","bloc","tips","maid","goof","four","woof","silo","bray","zest","kiss","yong","file","hilt","iris","tuns","lily","ears","pant","jury","taft","data","gild","pick","kook","colt","bohr","anal","asps","babe","bach","mash","biko","bowl","huey","jilt","goes","guff","bend","nike","tami","gosh","tike","gees","urge","path","bony","jude","lynn","lois","teas","dunn","elul","bonn","moms","bugs","slay","yeah","loan","hulk","lows","damn","nell","jung","avis","mane","waco","loin","knob","tyke","anna","hire","luau","tidy","nuns","pots","quid","exec","hans","hera","hush","shag","scot","moan","wald","ursa","lorn","hunk","loft","yore","alum","mows","slog","emma","spud","rice","worn","erma","need","bags","lark","kirk","pooh","dyes","area","dime","luvs","foch","refs","cast","alit","tugs","even","role","toed","caph","nigh","sony","bide","robs","folk","daft","past","blue","flaw","sana","fits","barr","riot","dots","lamp","cock","fibs","harp","tent","hate","mali","togs","gear","tues","bass","pros","numb","emus","hare","fate","wife","mean","pink","dune","ares","dine","oily","tony","czar","spay","push","glum","till","moth","glue","dive","scad","pops","woks","andy","leah","cusp","hair","alex","vibe","bulb","boll","firm","joys","tara","cole","levy","owen","chow","rump","jail","lapp","beet","slap","kith","more","maps","bond","hick","opus","rust","wist","shat","phil","snow","lott","lora","cary","mote","rift","oust","klee","goad","pith","heep","lupe","ivan","mimi","bald","fuse","cuts","lens","leer","eyry","know","razz","tare","pals","geek","greg","teen","clef","wags","weal","each","haft","nova","waif","rate","katy","yale","dale","leas","axum","quiz","pawn","fend","capt","laws","city","chad","coal","nail","zaps","sort","loci","less","spur","note","foes","fags","gulp","snap","bogs","wrap","dane","melt","ease","felt","shea","calm","star","swam","aery","year","plan","odin","curd","mira","mops","shit","davy","apes","inky","hues","lome","bits","vila","show","best","mice","gins","next","roan","ymir","mars","oman","wild","heal","plus","erin","rave","robe","fast","hutu","aver","jodi","alms","yams","zero","revs","wean","chic","self","jeep","jobs","waxy","duel","seek","spot","raps","pimp","adan","slam","tool","morn","futz","ewes","errs","knit","rung","kans","muff","huhs","tows","lest","meal","azov","gnus","agar","sips","sway","otis","tone","tate","epic","trio","tics","fade","lear","owns","robt","weds","five","lyon","terr","arno","mama","grey","disk","sept","sire","bart","saps","whoa","turk","stow","pyle","joni","zinc","negs","task","leif","ribs","malt","nine","bunt","grin","dona","nope","hams","some","molt","smit","sacs","joan","slav","lady","base","heck","list","take","herd","will","nubs","burg","hugs","peru","coif","zoos","nick","idol","levi","grub","roth","adam","elma","tags","tote","yaws","cali","mete","lula","cubs","prim","luna","jolt","span","pita","dodo","puss","deer","term","dolt","goon","gary","yarn","aims","just","rena","tine","cyst","meld","loki","wong","were","hung","maze","arid","cars","wolf","marx","faye","eave","raga","flow","neal","lone","anne","cage","tied","tilt","soto","opel","date","buns","dorm","kane","akin","ewer","drab","thai","jeer","grad","berm","rods","saki","grus","vast","late","lint","mule","risk","labs","snit","gala","find","spin","ired","slot","oafs","lies","mews","wino","milk","bout","onus","tram","jaws","peas","cleo","seat","gums","cold","vang","dewy","hood","rush","mack","yuan","odes","boos","jami","mare","plot","swab","borg","hays","form","mesh","mani","fife","good","gram","lion","myna","moor","skin","posh","burr","rime","done","ruts","pays","stem","ting","arty","slag","iron","ayes","stub","oral","gets","chid","yens","snub","ages","wide","bail","verb","lamb","bomb","army","yoke","gels","tits","bork","mils","nary","barn","hype","odom","avon","hewn","rios","cams","tact","boss","oleo","duke","eris","gwen","elms","deon","sims","quit","nest","font","dues","yeas","zeta","bevy","gent","torn","cups","worm","baum","axon","purr","vise","grew","govs","meat","chef","rest","lame"];
let alphabet = [...new Set(dict.join(""))];
console.log(findShortestLadderDistance(start, end, alphabet, dict));


The primary problem I see here is the way we're keeping track of the time passed.  NSTimer is not guaranteed to tick with the exact amount of time you passed it.  It will try getting as close as possible, but the most specific problem is when the thread has a lot of activity on it.

If between two ticks, the thread the timer is one gets a lot of activity stuck on it, then our timer can start displaying a strange time.

So, instead of using a count variable as an int, let's use a startTime as an NSDate object.  We may also need an NSTimeInterval variable in the case when the timer is starter, then stopped, then restarted without being reset.

Once this is done, the start method will do something like this:

func start() {
    self.startTime = NSDate()
    self.updateUI()
    timer.invalidate()
    timer = NSTimer.scheduledTimerWithTimeInterval(1.0f, target: self, selector: Selector("updateUI"), userInfo: nil, repeats: true)
}

while the stop method looks more like this:

func stop() {
    timer.invalidate()
    self.accumulatedTime += NSDate().timeIntervalSinceDate(self.startTime)
    self.updateUI()
}

and the reset method looks something like this:

func reset() {
    timer.invalidate()
    self.accumulatedTime = 0
    self.start()
}

We can replace convertSeconds and timeToString with the following method:

func timeIntervalToString(ti: NSTimeInterval) -> String? {
    let dcf = NSDateComponentsFormatter()
    dcf.zeroFormattingBehavior = .Pad
    dcf.allowedUnits = (.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond)
    return dcf.stringFromTimeInterval(ti)
}

And now our updateUI method looks something like this:

func updateUI() {
    var time = self.accumulatedTime + NSDate().timeIntervalSinceDate(self.startTime)
    self.timerLabel.text = self.timeIntervalToString(time)
}

Now our label should always give us an accurate representation of the time passed in hours, minutes, and seconds no matter how busy the thread is.  A busy thread would only mean that the UI isn't updated as often, but in the instant it is updated, it is perfectly accurate.

But more importantly, we're able to track more precisely the exact amount of time passed in case we ever decide we want to display more precision.

Moreover, if we ever decide we want to change the rate at which the UI is updated, we can do that, because our timer doesn't rely on the update method being ticked once per second in order to be accurate.  The time could be calculated in any instant, and we will get a precise time.

As one final note, rather than putting all of this code in our view controller, I'd probably abstract this into a stop watch struct.  Something like this:

func timeIntervalToString(ti: NSTimeInterval) -> String? {
    let dcf = NSDateComponentsFormatter()
    dcf.zeroFormattingBehavior = .Pad
    dcf.allowedUnits = (.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond)
    return dcf.stringFromTimeInterval(ti)
}

public struct StopWatch {
    private var startTime: NSDate?
    private var accumulatedTime: NSTimeInterval = 0.0

    public var elapsedTimeInterval: NSTimeInterval {
        get {
            return self.accumulatedTime + NSDate().timeIntervalSinceDate(self.startTime ?? NSDate())
        }
    }

    public var elapsedTimeString: String {
        get {
            return timeIntervalToString(self.elapsedTimeInterval) ?? "0:00:00"
        }
    }

    public mutating func start() {
        self.startTime = NSDate()
    }

    public mutating func stop() {
        self.accumulatedTime += NSDate().timeIntervalSinceDate(self.startTime ?? NSDate())
        self.startTime = nil
    }

    public mutating func reset() {
        self.accumulatedTime = 0.0
        self.start()
    }
}

And this allows us to minimize the amount of code that actually goes into our view controller, which can now look something more like this:

class StopWatchViewController: UIViewController {
    @IBOutlet var timerLabel: UILabel!
    var stopWatch: StopWatch = StopWatch()
    var timer: NSTimer?

    func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("updateUI"), userInfo: nil, repeats: true)
    }

    func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        self.timer?.invalidate()
    }

    func updateUI() {
        self.timerLabel.text = self.stopWatch.elapsedTimeString
    }

    @IBAction func start(sender: UIButton) {
        self.stopWatch.start()
    }

    @IBAction func stop(sender: UIButton) {
        self.stopWatch.stop()
    }

    @IBAction func reset(sender: UIButton) {
        self.stopWatch.reset()
    }
}

The main point here being that we've abstracted all of the non-UI code out of the view controller class.


Find the smallest positive integer that is absent from a given array

I then tried putting the array into an arraylist, which reduces big-O since each object is "touched" only once, and I can use .Contains which is more efficient than iteration (not sure if that's true; I just sort of remember reading it somewhere).

As was mentioned in the comments, for your purpose, there is no significant difference in performance between int[] and ArrayList. Both store their data in a similar way, and both will have to iterate through the array to check for Contains. So that doesn't help anything.

Sorting

You mention sorting in the title of your question. But you don't actually do any sorting. Let's look at the challenge:

  Write a function that, given an array A of N integers, returns the smallest >positive integer (greater than 0) that does not occur in A. For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5. The given array can have integers between -1 million and 1 million.

We need to know whether 1, 2, 3, etc are in the input. You can do this, by checking each and every option, one at a time. Since you don't know whether 1 would be at the start, or at the end of the array, you have to check the entire thing each and every time. That's inefficient.

However, if you sort the input, the array becomes somewhat predictable. You can loop through the sorted array until you find the first positive number. Is it higher than 1? Then we can return 1, since that is the smallest possible integer that's not in the list - the smallest positive integer is >1 after all. If it equals 1, we can go to the next element and check its value. If it is another 1, move on. If it is >2, we can return 2, else we must move on. And repeat.

In that way, what we have done, is sorting the array (\$O(n logn)\$), and then looping through it once. All in all, that's still \$O(n logn)\$.

public int solution(int[] a) {
  // sort
  Array.Sort(a);
  var answerCandidate = 1;

  // Find the first nonzero positive number.
  for(var index = 0; index < a.Length; index++) {
    if (a[index] < answerCandidate) {
      continue;
    } else if(a[index] == answerCandidate) {
      // Oops, we found our candidate in the list, so we move to the next one.
      // Since the list is sorted, we know the next one can only be farther
      // on in the list, so we don't need to restart the loop.
      answerCandidate++;
    } else {
      // In this case a[index] > answerCandidate. This means that we haven't found
      // the candidate in the list, so we can return answerCandidate. Break so
      // that we can handle the case where we pass the end of the array at the same time.
      break;
    }
  }

  return answerCandidate;
}

We can still make a marginal improvement by searching for the first positive number using a binary search on our sorted list.


Your code as it stand is on the border of being off-topic as it is a stub, however since the following actually works and seems to do the job, I'm going to answer it:

lst = [(106, 210, 108, 134, 134),
       (106, 210, 108, 134, 210),
       (106, 210, 108, 168, 268),
       (106, 210, 108, 168, 671)]

keep = (106, 210, 108, 168)

kept = [item for item in lst if set(keep) < set(item)]
print kept

Firstly some comments on the code:

Please provide a fully working example – In general, if there in the question is not a fully working example code, it'll be shut down immediately. Please provide something like the above code segment.
Name and comment – Providing good names and comment to illustrate what the code does is vital. Using anonymous name like lst, item, and no comments, makes the code a lot harder to read.
Do you keep lst in memory? – In the text you state that lst has over 2.6 million entries, do you keep all of this in memory? That could possibly effect your running times severly depending on your hardware resources. You might want to look into some algorithm leaving it in file or in a database, or whatever suits your needs.

Alternate solution

You're asking for a faster solution, so let us analyze what is happening in your code currently:

You loop through the entire in-memory lst once, and create a new set for each item
This set(item) is then compared to repeatedly created set(keep) (could be optimised away by the compiler), to check which is lesser
If lesser, the list comprehension keeps the item

The operations in here is \$O(N)\$ where N is the number in the list, and that you can't beat. The cost for each element is the creation of one or two sets, and the comparison of those sets, which is dependent on the size of the sets \$O(M)\$. In general since the \$N << M\$, the loop over the elements should be prominent.

This means, without changing the data structures there is not a whole lot to be gained, as you do need to loop through all elements, and you need to verify membership agains the keep list. If any optimization is to be performed it needs to address the actual comparison somehow.

Another view on your solution is the readability of your code, and how to understand what is happening. The list comprehension is understandable, but the set comparison is not obvious to me, at least, and I would have liked a comment. Or a rewrite, so let us attempt an rewrite for readability and see how it performs. This rewrite is using a Python specific concept to avoid a flag variable:

keepers = []
for candidate in lst:
  for keeper in keep:
    if not keeper in candidate:
      break

  else:
    keepers.append(candidate)

This code expands the list comprehension into the double for loop which is hidden in the list comprehension. The inner for loop breaks up the keep list into each element, and tests for memberships. The criteria for the candidate to be kept is that all elements should be members, so if any member is not present, we break out and start checking the next candidate.

The trick to this solution is that if the inner for loop doesn't complete naturally (aka no breaks), the else part is not executed. Try the following and play with it, to understand this mechanism:

for i in range(5):
  if i == 3:
    break
else:
  print "This didn't end naturally"           # Not executed

for i in range(5):
  if i == 7:
    break
else:
  print "The loop finished without breaking"  # Executes

Whilst I was writing this answer, the answer with using the all concept came in, so I included that in some basic timeit tests to check for running times, and the result surprised me a little:

Original method: 2.62324810028
Using all():     3.84744811058
Double for loop: 1.84868502617

This was tested using the original lst duplicated a few times to get a slightly larger set, but it does show that using the double for loop like I did, is currently the faster solution, and it runs at about 33% faster than the original code, and the solution using all() is actually quite a bit slower.


Replacing div if there is any validation error connected with the div value

Basically, 95% of your code is the same between the two sections, so I'd prefer to use just a single instance with a bool on the page.

@{
    var error = ViewModel.ModelState["StorateError"];
    var hasErrors = error != null && error.Errors.Any();
}

<div class="a" title="@( hasErrors ? error.Errors[0].ErrorMessage : string.Empty" )
    data-toggle="tooltip" data-placement="left" id="storage">
        @Html.DropDownList("storageId", null, new { @class="form-control",
            @style=" @( hasErrors ? "border-color:red", string.Empty ) })
</div>

You should also get into the habit of using .Any() instead of Count() > 0 as Any will stop iterating after it finds the first item that matches the filtering (usually not a big deal, but the collection could get rather large, and it's a minor change to coding that could give big performance enhancements).

The only other thing I might recommend would be to have a CSS class for border-color:red instead of inline styling.


What you need is a Map. A map is a collection of key --> value combinations. There can not be two equal keys pointing to different values.

There are a few ways to organize this map. The simplest is to make Map<String, Album> albumNames;, but that would make it possible for collisions if two albums had the same album name.

Another alternative is Map<String, List<Album>> for fixing the problem with albums having the same name.

There are more alternatives but they can get quite complex so I think this is enough for now.

Then when you loop through your songs, for each song:

List<Album> possibleAlbums = albumNames.get(song.getAlbum()).

If that returns null, then add a new list and add an album to it.
otherwise loop through the list to find the album you are looking for (that matches the artist). Again, if none is found create a new one.

Once you have found or created a matching album, you can add the song to it.

Other comments:

Declare by interface and not implementation. Make the method return List<Album>, also use for example List<Song> tmpList = getAllSongs(c);
Use longer and better names. s --> song, a --> album, c --> context, tmpList --> songs.
tmpList = null; in the bottom of the method will have no effect whatsoever. You can safely remove that line.


Different selects in one form with same name attribute?

These are nested selects, you can try awesome_nested_set, and use it like this:

<%= f.select :parent_id,
             nested_set_options(Category, @category) {|i| "#{'-' * i.level} #{i.name}" } %>