Brevity of code seems an odd point of focus, so I plan on ignoring that. I do, however, have quite a few suggestions, and, convieniently for you, those will probably shorten the code.

Don't assume user provided variables are actually set. For example, don't access $_POST['url'] directly. Either cover it in a isset guard like you've done other places, or use filter_input. Also, don't trust that user provided variables will be strings. They can be arrays. Might want to add a is_string check.

Your code is wide open to SQL injection. Never put an unescaped string into a query. Always either use prepared statements or properly escape strings. Prepared statements tend to be a bit harder to accidentally forget to do, so they are what I usually go with.

Use either $a=val or $a = val consistently. Inconsistent coding style is hard on the brain. I strongly suggest the $a = val style.

Your indention and line breaks are rather sporadic and odd. first.php is particularly bad. Don't include things on the same line as a brace like:

if ()
{ something here

Also, make sure you develop a habit for indention at each code block level and stick with it.

For such a simple script, or die is fine. In general though, it can be a bit of a problem since it doesn't allow for pretty error handling very easily. It's often better to throw an exception so that higher up code can catch it and gracefully render an error instead of just a plain text string. Like I said though, it doens't really apply here since nothing is being rendered anyway.

Queries should never fail in production code. This means that if( $Resut ) shouldn't be necessary. If the query is failing, something is majorly wrong as it means either an entity is missing (like a DB or table) or a syntax error happened. An entity missing is problematic since it means the DB is out of sync with the code, and a syntax error is worrying since it means that code either wasn't tested and legitimately has a syntax error or that SQL injection is occuring.

Basically all of the comments are meaningless. All they do is describe exactly what the code is doing. As long as someone can read PHP, they can already see what the code is doing. Typically comments should describe why something is being done not how. (In algorithmical code, it's fairly common to comment what is going on, but that's because it's much harder to follow than straight forward code like this.)

There's no reason to put the final closing tag in a PHP file. It can end up causing complications with trailing whitespace or non-printed characters, and it isn't syntactically required. For this reason, it's become customary lately to omit the closing tag.

This comes down to personal preference and OCD really, but I tend to avoid closing resources that last until the end of script execution. The mysql connection is about to be cleaned up anyway when PHP tears itself down, so the mysqli_close is really just superfluous. Some people like the explicitness of it though and it gives them peace of mind knowing that they closed something they opened. That's a very valid approach. There's just not technically a need for it, and I like to avoid clutter.

Note that this does not apply to resources that are not tied to the life time of the script. In general, resources should be held as briefly as reasonably possible.

empty($x) is equivalent to isset($x) && $x. This means that isset($x) && !empty($x) is the same as isset($x) && isset($x) && $x. In other words, just use !empty($x) if you want the behavior specified. The isset is redundant.

For code this simple and short, it's not really necessary, but if this grows, I would extract common setup in a bootstrapping mechanism of some sort. This would allow you to avoid having to duplicate your mysqli conneciton across every file. That means you won't have to change the DB credentials in n files if you need. Instead, you could just change them in one.

If the code grows more complex, I would extract functionality into functions. Two obvious functions that could exist now are getUrlFromId and createUrlShortening.

Functions allow your program flow to focus on program flow and not implementation.

Functions also allow for a central point of change. For example, if this grows into a complex website that has tons of pages and whatnot, you're likely going to need to be able to retrieve URLs from many pieces of code. Now imagine that you've found a bug in your URL retrieving code or you want to change a table name or something. You can either Control+F and fix it in a ton of places and hope you haven't missed anything, or you can have one centralized place to change it.

  And one more thing: there are 6-7 lines of whose meaning I can't understand, so please explain this to me this as well.

That block of code queries the database for a record in the table url that has an ID equivalent to the location ID the end user provided (via the l GET parameter -- like blah.php?l=33).

WHERE id LIKE `%s` LIMIT 0, 1

This is wrong for three reasons.

Simple equality should be used like id = blah since there's no pattern matching needed
The limit is unnecessary since id is (or should be) a primary key and primary keys are unique
id is (or should be) an integer, not a string and thus should be treated as such. Don't escape it with mysqli_real_escape_string, and don't interpolate it in as a string. Instead, make sure it's an integer format and put it in as an integer. The easiest way to do this is simply casting the variable like " ... WHERE id = " . (int) $locationID"

If you want to be able to actually detect an invalid integer, you can use something like ctype_digit or filter_input with the proper validation flags:

$blah = (isset($_GET['blah']) && is_string($_GET['blah'])) ? $_GET['blah'] : null;
if ($blah === null) {
    echo "You must provide blah!";
} else if (!ctype_digit($blah)) {
    echo "Blah is invalid!";
} else {
    $query = "SELECT blah FROM bleh WHERE id = " . (int) $blah;
    //(The int cast is unnecessary since you already know it's an int. It can protect
    //against a change in the code flow later allowing an invalid value through though)
}

Not only do prepared statements simplify this situation a bit, they can also allow it to be a bit briefer since you don't have to worry as much about validation or careful interpolation/concatenation.

In second.php: inserting a value only to immediately retrieve it is a bit odd. Just use mysqli_insert_id($conn) instead of fetching back the id.

Also, while($id = mysqli_fetch_array($result)) doesn't make sense. Only one row should be returned since the user just created one shortening. Oddly enough, this loop can actually return more than 1 item though since I'm assuming the url column isn't unique. If this is the functionality you desire, ignore the point about not fetching back the row. That is required to bring back all of the duplicates.


First things first. Since we are talking about an SQL backend (unless I'm mistaken) - you need to profile SQL and take each (sub)query seperately, then determine which query takes the longest. It would simply be pure guess work, taking answers out of thin air otherwise, since we have no reference for what the bottleneck actually is.

Next, what are you SQL indexes? You have many joins and where clauses. If you don't have your indexes set up correctly, then - there's your problem!

Finally compare your c# query to the actual SQL query. Sometimes your LINQ can look beautiful, but the actual code generated for the query is utter BS. I deal with LINQ2SQL myself and have many times been forced to make a list (ToList()) from the sub-queries, forcing the data into the client, into the realm of c# and doing the final query on top of those lists instead. I may use more memory for a brief period of time, but I gain orders of magnitude more speed...


Find common items between two collections, and set values in one collection when matched

It would be better to create a Dictionary<int, Job> of jobs and use it in the foreach loop. Otherwise, you have to parse dataRowView["ID"] field as many times as jobs are available (at worst). If number of jobs is less than 10, it is more performant to iterate the list of jobs instead of using a Dictionary<int, Job>:

//Step 3: Find match, and set the value from dataView to jobs when matched.
    Dictionary<int, Job> jobDict = jobs.ToDictionary(j => j.Id);

    foreach (DataRowView dataRowView in dataView)
    {
        var id = int.Parse(dataRowView["ID"].ToString());
        Job job;
        if (jobDict.TryGet(id, out job)
            //&& other logic here
         )
        {
            //once matched, it sets the value. This is what I need
            job.DiscountDate = (DateTime) dataRowView["DiscountDate"];
            break;
        }
    }


Computing the sum of squared differences

Here's a way to do it using pdist to generate both the differences in value, plus logical indices that you can use to select which distances you wish to look at/use further.

D1 = [1 2 3;4 5 6;7 8 9];
D2 = [9 8 7;6 5 4;3 2 1];
D = cat(3,D1,D2);

D(:,:,1) =

 1     2     3
 4     5     6
 7     8     9

D(:,:,2) =

 9     8     7
 6     5     4
 3     2     1

Y = repmat([1 2 3]', [1 3 2]); %# (' in comment to fix SO highlighting)
X = repmat([1 2 3],[3 1 2]);
T = repmat(cat(3,1,2),[3 3 1]);
D_diffsqrd = pdist(D(:),'euclidean').^2;
X_dist = pdist(X(:),'euclidean');
Y_dist = pdist(Y(:),'euclidean');
T_dist = pdist(T(:),'euclidean');
Angle_dist = pdist([X(:) Y(:)],'euclidean');

D_diffsqrd(X_dist==2 & T_dist==0 & Y_dist==0)
    4     4     4     4     4     4

D_diffsqrd(X_dist==0 & T_dist==0 & Y_dist==2)
    36    36    36    36    36    36

D_diffsqrd(X_dist==0 & T_dist==1 & Y_dist==0)
    64     4    16    36     0    36    16     4    64


divide a range of numbers into groups of 10, 100, 1000, 10000 and so on

Even the “extended version” does not handle the cases where start and end have more than 6 trailing zeros in common. Instead of hard-coding those ranges and a long if/else if/... statement you can determine the largest fitting range dynamically in a loop:

for (long i = st; i <= en; ) {
    // Determine `range` as largest power of 10 with `i % range == 0`
    // and `i + range - 1 <= en`:
    int range = 1;
    while (range <= i && i % range == 0 && i + range - 1 <= en) {
        range *= 10;
    }
    range /= 10;

    System.out.println(i / range);
    i += range;
}

Removing common zeros/nines is more efficiently done in integer arithmetic instead of string manipulation:

while (st % 10 == 0 && en % 10 == 9) {
    st /= 10;
    en /= 10;
}

I would move the computation from main() into a separate function and separate it from the I/O. That increases the clarity of the program and allows to add test cases more easily. In a comment you said that you need the result as List<String>:

public static List<String> computePrefixes(long start, long end) {
    List<String> prefixes = new ArrayList<String>();

    while (start % 10 == 0 && end % 10 == 9) {
        start /= 10;
        end /= 10;
    }

    for (long i = start; i <= end; ) {
        // Determine `range` as largest power of 10 with `i % range == 0`
        // and `i + range - 1 <= en`:
        int range = 1;
        while (range <= i && i % range == 0 && i + range - 1 <= end) {
            range *= 10;
        }
        range /= 10;

        prefixes.add(String.valueOf(i / range));
        i += range;
    }

    return prefixes;
}

public static void main(String[] args) {
    String start = "1230000";
    String end   = "1285999";

    long st = Long.parseLong(start);
    long en = Long.parseLong(end);
    List<String> prefixes = computePrefixes(st, en);
    System.out.println(prefixes);
}

You may also want to check the validity of the parameters (1 <= start <= end).

Finally note that there is still a problem with numbers close to Long.MAX_VALUE because the calculations can overflow. If that is an issue then the range calculations and comparisons have to be done more carefully:

public static List<String> computePrefixes(long start, long end) {
    List<String> prefixes = new ArrayList<String>();

    while (start % 10 == 0 && end % 10 == 9) {
        start /= 10;
        end /= 10;
    }

    for (long i = start; ; ) {
        // Determine `range` as largest power of 10 with `i % range == 0`
        // and `i + range - 1 <= end`:
        int range = 1;
        while (range <= Long.MAX_VALUE / 10 && range <= i && i % range == 0 && range - 1 <= end - i) {
            range *= 10;
        }
        range /= 10;

        prefixes.add(String.valueOf(i / range));
        if (i == end) {
            break;
        }
        i += range;
    }

    return prefixes;
}


Scraping content from a javascript enabled website with load more button

There are a few major things that immediately caught my eye:

bare except clauses should be avoided in favor of catching more specific exceptions
element locators quality - you should NOT be relying on layout-oriented classes like padding0 and pure-technical Angular classes like ng-binding and ng-scope
wait.until() calls in your case return a WebElement instance - you don't have to re-find an element after the wait
I think the code may benefit from comments explaining the logic behind the browser element interactions

Improved code:

from selenium import webdriver
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def get_field_text_if_exists(item, selector):
    """Extracts a field by a CSS selector if exists."""
    try:
        return item.find_element_by_css_selector(selector).text
    except NoSuchElementException:
        return ""

def get_link_if_exists(item, selector):
    """Extracts an href attribute value by a CSS selector if exists."""
    try:
        return item.find_element_by_css_selector(selector).get_attribute("href")
    except NoSuchElementException:
        return ""

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)

driver.get("https://www.zebra.com/us/en/partners/partner-application-locator.html")

location = driver.find_element_by_css_selector('.partnerLocation input')
location.clear()
location.send_keys("Colorado, USA")

# select the first suggestion from a suggestion dropdown
dropdown_suggestion = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'ul[id^=typeahead] li a')))
dropdown_suggestion.click()

# click more until no more results to load
while True:
    try:
        more_button = wait.until(EC.visibility_of_element_located((By.CLASS_NAME, 'showmore-bg'))).click()
    except TimeoutException:
        break

# wait for results to load
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '.seclection-result .partners-detail')))

# parse results
for result in driver.find_elements_by_css_selector('.seclection-result .partners-detail'):
    name = get_field_text_if_exists(result, 'a')
    address = get_field_text_if_exists(result, '.fullDetail-cmpAdres')
    phone = get_field_text_if_exists(result, '.fullDetail-cmpAdres p[ng-if*=phone]')
    website = get_link_if_exists(result, 'a[ng-if*=website]')

    print(name, address, phone, website)

driver.quit()


I can't find anything wrong.If really give some suggestions, it would be the case of the function name 'on_AddButton_clicked' and 'on_DeleteButton_clicked'.It will be better to use 'addButton' and 'deleteButton'.


If you think that those try/catch blocks look too verbose, then you can create utility method like:

def logExceptions[R](body: => R): R =
  try { body }
  catch {
    case e: Exception => log.error(e.toString)
  }

Then rewrite your code like:

def buyLinkAnalytics(notif: Notification, reqInfo: RequestInfo) {
  logExceptions {
    logActivity(buy_link_requested, Some(LoggedInAccount(AccountId(notif.emails.get.to._id))), notif.productId.get._id.toString, None, reqInfo)
  }
}

def productShareAnalytics(notif:Notification, reqInfo:RequestInfo) {
  logExceptions {
    logActivity(product_shared, Some(LoggedInAccount(AccountId(notif.emails.get.to._id))), notif.productId.get._id.toString, None, reqInfo)
  }
}

...


Highest floor of a building from which to drop an egg without breaking it

Here are some comments on your question:

Bad problem description – I can't help but to make a method which find the input parameter, seems kind of silly. It could simply do return n-1 and you're done. It would have been better if the problem description gave a predefined method which you could call at most two times before it gave some error. But I digress...
Choose good names for your variables – Two store the lower and higher test floors in a list t is bad. What is t[0] or t[1]. Say low, highis way better, and even they can be improved upon
Assign multiple values at once – If you want to use one line to assign multiple values you can do: low, high = 1, 11
Don't use magic numbers – If you have magic numbers, like the number of floors, do either declare them as constants at the top or as default parameters to the method in question
Give proper text output – It took me quite some time to understand what your output actually was meant to describe. It would have been much clearer if you had said "First egg broke on floor x" and "Second egg broke on floor y"
Switch to new style print formatting and function – It is recommend to switch to the new string.format() style for print output. I.e. print ('First egg broke on {}'.format(high))
Error handling is good – As the problem was limited to a 100 floor building, one could/should also let the code reflect that. One way can be to assert legal floor levels, and another could be to make sure that when returning you don't return an illegal level.

Finally you can reduce the number of attempts by a little if you start out attempting with a little higher delta value/range and let it shrink as you get closer to the top1. It can be shown that the optimal delta offset is the result of  \$\frac{\sqrt{1 + 8\cdot {floors}} - 1}{2}\$. With these suggestions, and a simple loop to test for all available floors we get:

import math

MAX_FLOOR = 100

def safest_egg_drop_floor(n):
    """Return the safest floor to drop an egg from."""

    assert 1 <= n <= MAX_FLOOR, 'Building has floors from 1 through {}'.format(MAX_FLOOR)

    # Calculate the optimal delta to start with, to reduce attempt numbers
    delta = int(math.ceil((math.sqrt(1 + 8*MAX_FLOOR) - 1)/ 2))

    low, high = 1, delta

    while low < MAX_FLOOR:
        if high >= n:
            print('  First egg broke on floor {}'.format(high))

            for i in range(low, high+1):
                if i >= n:
                    print('  Second egg broke on floor {}'.format(i))
                    if i == 1:
                        raise ValueError("Eggs will always break")
                    else:
                        return i - 1
        else:
            delta -= 1
            low, high = high, high + delta
            if high > MAX_FLOOR:
               high = MAX_FLOOR

    return MAX_FLOOR

def main():

    for i in range(0, MAX_FLOOR+2):
        print('\nFind egg drop when it breaks at {}'.format(i))
        try:
            max_floor = safest_egg_drop_floor(i)
            print('    Safest drop from floor {}'.format(max_floor))
        except (ValueError, AssertionError) as error:
            print(error)

Which outputs:

Find egg drop when it breaks at 0
Building has floors from 1 through 100

Find egg drop when it breaks at 1
  First egg broke on floor 14
  Second egg broke on floor 1
Eggs will always break

Find egg drop when it breaks at 2
  First egg broke on floor 14
  Second egg broke on floor 2
    Safest drop from floor 1

...

Find egg drop when it breaks at 100
  First egg broke on floor 100
  Second egg broke on floor 100
    Safest drop from floor 99

Find egg drop when it breaks at 101
Building has floors from 1 through 100

1 See http://datagenetics.com/blog/july22012/index.html for a better explanation.


Rock, Paper, Scissors game in JavaScript

Here are my 2 cents to improve your code.

First of all, if you're going to be using an infinite loop anyways to check for user input, why not make it a while loop instead of a for loop?

while (i === 0)
{
    var userChoice = prompt("You're playing rock, paper, scissors against the computer. Type your choice in lower case letters.")
    if (userChoice === "rock") {i=1;} //escapes loop
        else if (userChoice === "paper") {i=1;} //escapes loop
        else if (userChoice === "scissors") {i=1;} //escapes loop
        else {alert("Try again, stupid.");} //alerts, loops back to start
}

I personally feel that a while loop is far easier to read than a for loop, and in your case you have two variables which doesn't seem necessary. By using a while loop, you won't need to have the 'infiniteloop' variable.

Also, it looks like the victory messages won't be printed to the console as you're just calling the strings after each case.
This should do the trick:

else if (...) { console.log(victory); }

Congrats on finishing a game though! It's always a great place to start :)

Best of luck for your coding journey!!

shifubear


JavaScript closure: code trivia to keep the event handler separate

Add more spaces.
Use more named functions. (wrap the whole thing in an anonimous wrapper if you're worried about name space conflicts).
When you do use lamdas give them names (it makes the code easier to read and you don't get  showing up in the error log.
Declare variables in higher functions to take advantage of closures. eg x, y, elementStart and mouseStart.
camelCase.
Use === unless you explicitly want to force casting.
Don't make functions in a loop.

http://codr.cc/s/03c0d0af/js


Record parsing to Scala object with some unknown fields

I would parse the row into a Map[String,String] first (by collecting the key-value pairs that you already know how to split), and then do

this.imptField1 = map.get("imptField1").getOrElse("")
this.imptField2 = map.get("imptField2").getOrElse("")
this.remData = map  // just the whole Map, or maybe remove the above two keys

I would also change the class to be immutable and move the parsing code into the companion object (it would do the parsing, then pass the map to the constructor of the class which can directly assign to its val fields).


SQL is made to function on Joins, I wouldn't say that they are "kind of "expensive" operation" RDMS databases are made to relate to other tables.  if you had Primary and Foreign Keys set up and/or even indexes then it shouldn't be an "expensive operation".
edit
here is the best query for what you are trying to accomplish.
SELECT player.name, player.surname
FROM  player INNER JOIN person ON player.id = person.id
WHERE player.id = person.id
    AND player.name = person.name
    AND player.surname = person.surname

This is the write way to write the code, it's clean and straight forward to what is going on. your code essentially is doing the exact same thing, but is bad coding practice from my point of view.
SQL Fiddle Statistics and running code
SQL Fiddle Statistics for your code
(it actually looks like the execution is the same.)
I need to Note that both this query and the query that you are using join the two tables on their id columns.  this is an issue because there is 1 id that holds different values in either table. so those id columns mean two totally separate things and shouldn't be joined on in all reality.
example:

player table
| 2001       |    John     |    Carlin    |

AND

person table
| 2001       |    Pirlon   |    Austin    |

in this specific instance the where statement covers the id being different, in this one case.  BUT YOU NEED TO BE AWARE THIS IS BAD DATA  you should fix the database.
Sorry to say but the INTERSECT query that has been suggested actually takes longer and has more operations attached to it then both your original code and the code I posted.
SQL Fiddle from jmoreno's answer


Look for existing pivottables and change date/year colums based off the “Value” filter

Comepletely forgot to post an answer to this, that i found a little after asking this question. Hopefully someone can use it

The code we used before was not optimal and messy, since you had to write those six lines of code for each PT, and every time you added a new PT.

I then realised you could just add some for each ... then loops that would go through not only every PT, but also each field in the PT, and then I could add the If / elsif that would check which field each PT is using, and have it correct the dates accordingly.

I had to set the pt anme as a string pts = pt for it to recognize it as a name (I don't know why exactly), but just having it as ActiveSheet.PivotTables(pt).PivotFields( _ .... Didn't work as it thought the name was "pt" and not the actualt name like "PivotTable1"..

It works as intended, the process takes about 1 min to complete. I suspect you can make it faster, but I havn't looked at it.

Sub UpdateAllPivots_new()
'
'Looks through all pivots in the sheet and updates the dates accordingly
'
'Update time is approx. 1 min (How can this be improved)
'

Dim ws As Worksheet
Dim pt As PivotTable
Dim pf As PivotField
Dim pi As PivotItem
Dim pts As String

    D1 = Sheets("DATA").Range("B6").Value
    D2 = Sheets("DATA").Range("C6").Value
    D3 = Sheets("DATA").Range("D6").Value
    D4 = Sheets("DATA").Range("E6").Value
    D5 = Sheets("DATA").Range("F6").Value
    D6 = Sheets("DATA").Range("G6").Value
    D7 = Sheets("DATA").Range("H6").Value
    D8 = Sheets("DATA").Range("I6").Value
    D9 = Sheets("DATA").Range("J6").Value
    D10 = Sheets("DATA").Range("K6").Value
    D11 = Sheets("DATA").Range("L6").Value
    D12 = Sheets("DATA").Range("M6").Value

Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.EnableEvents = False

Set ws = ActiveSheet

    For Each pt In ws.PivotTables
    pts = pt

        For Each pf In pt.PivotFields

                    If pf.Name = "[StatusPickedDatetimeKey].[YearMonth].[YearMonth]" Then
                         ActiveSheet.PivotTables(pts).PivotFields( _
                         "[StatusPickedDatetimeKey].[YearMonth].[YearMonth]").VisibleItemsList = Array("", _
                         "[StatusPickedDatetimeKey].[YearMonth].&[" & D1 & "]", "[StatusPickedDatetimeKey].[YearMonth].&[" & D2 & "]", "[StatusPickedDatetimeKey].[YearMonth].&[" & D3 & "]", _
                         "[StatusPickedDatetimeKey].[YearMonth].&[" & D4 & "]", "[StatusPickedDatetimeKey].[YearMonth].&[" & D5 & "]", "[StatusPickedDatetimeKey].[YearMonth].&[" & D6 & "]", _
                         "[StatusPickedDatetimeKey].[YearMonth].&[" & D7 & "]", "[StatusPickedDatetimeKey].[YearMonth].&[" & D8 & "]", "[StatusPickedDatetimeKey].[YearMonth].&[" & D9 & "]", _
                         "[StatusPickedDatetimeKey].[YearMonth].&[" & D10 & "]", "[StatusPickedDatetimeKey].[YearMonth].&[" & D11 & "]", "[StatusPickedDatetimeKey].[YearMonth].&[" & D12 & "]")

                    ElseIf pf.Name = "[Date].[YearMonth].[YearMonth]" Then
                        ActiveSheet.PivotTables(pts).PivotFields( _
                        "[Date].[YearMonth].[YearMonth]").VisibleItemsList = Array("", _
                        "[Date].[YearMonth].&[" & D1 & "]", "[Date].[YearMonth].&[" & D2 & "]", "[Date].[YearMonth].&[" & D3 & "]", _
                        "[Date].[YearMonth].&[" & D4 & "]", "[Date].[YearMonth].&[" & D5 & "]", "[Date].[YearMonth].&[" & D6 & "]", _
                        "[Date].[YearMonth].&[" & D7 & "]", "[Date].[YearMonth].&[" & D8 & "]", "[Date].[YearMonth].&[" & D9 & "]", _
                        "[Date].[YearMonth].&[" & D10 & "]", "[Date].[YearMonth].&[" & D11 & "]", "[Date].[YearMonth].&[" & D12 & "]")

                     End If

        Next pf

    Next pt

Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.EnableEvents = True

End Sub
```


Returning containers from function - C++

In C++ 11 you probably would use

vector<string> BreakStringOnDelimiter( const string& dataStr );

The container classes can be very efficiently move constructed (this is a new and smart feature of C++ 11 which can avoid temporary objects in many cases), which means that on return no expensive copy construction of the containers (and the strings in the container) is needed. Essentially only the some pointers are passed around on return.

Alternatively the solution with unique_ptr would also work, but is in my opinion not as good (and probably not really more efficient).

Given these alternative options, returning a bare pointer is not recommended.

For maximum efficiency you should consider using the emplace function when filling the vector. This avoids additional copies of string.

Also probably const string & as argument is better suited.


Identifying a development and production server by http_host

Switching behaviour based on the Host header is not something I would recommend.  The environment should be a property of the server, rather than of the request.  Depending on your hosting situation (whether you have an IP-based virtual host or name-based virtual host, and the details of how your webserver is configured), you might even be able to hit code on the production server using a request with a forged (or missing) Host header.

I recommend that you identify the production environment by some other means — probably by some configuration file that exists on the production server.


I believe it's OK. This way, it is immediately clear from the code that the method returns a value only when no exception is thrown during parsing. If you used a variable to store the result, it becomes less clear. And, the reader has to track where the variable is initialized/modified/returned.

Logging an exception when it's rethrown is a bit confusing, because it is possible the caller expect the possibility of receiving an exception and deals with it. But sometimes a programmer needs it so that it's possible to examine what's happening even if the caller catches the exception. In such a case, I'd suggest using only debug or trace logging levels.


Checking a value before assigning it to variable

Indentation

I'm not quite sure if this is correct, but from what I know, I believe it is.

Indentation in JavaScript does not matter as, before your code is run, it is completely minimized - meaning it removes all comments and unnecessary spaces.

That being said, trying to crush your JavaScript into three lines does not make it any faster.

Calling

In your first example, you call the same function three times with the same arguments each time. This is extremely inefficient.

It would be optimal to call it once and save it in a variable.

Therefore, these lines:

var filter = ""
if ( typeof getQuery("filter") != 'undefined' && getQuery("filter") != "" ) filter = getQuery("filter")
if ( filter != "" ) createFilterView( filter )

Can become:

var filter = "";
var ret = getQuery("filter"); // for lack of a better variable name
if(typeof ret != 'undefined' && ret != "") filter = ret;
if(filter != "") createFilterView(filter)

(Yes, you fixed this in the second example)

Conditionals 1

In your first example, you check to see that the return value of getQuery isn't "undefined" and that it isn't "". If that passed, you take the return value and place it in a variable. Then, you go through another conditional to make sure that that variable isn't empty.

Well, since in your first conditional you already check to make sure that the return value isn't empty, why don't you put the body of the second conditional into the first one.

This:

if ( typeof getQuery("filter") != 'undefined' && getQuery("filter") != "" ) filter = getQuery("filter")
if ( filter != "" ) createFilterView( filter )

Becomes:

if(typeof getQuery("filter") != 'undefined' && getQuery("filter") != "") {
    filter = getQuery("filter")
    createFilterView(filter)
}

Conditionals 2

In the conditional statements in both of your examples, you check that the return value of getQuery is not "". You don't have to specifically specify that.

You can just remove the != "" part and it would work the same way.

The further reduce the size of your conditional, you can have your getQuery function actually return the value undefined (null would be better, however) instead of it returning a string of the word "undefined".

Then, you could reduce your conditional to:

if(getQuery("filter"))

Semicolons

In JavaScript, it is a good practice to close statements with a semicolon.

Example:

createFilterView(filter)

Should be:

createFilterView(filter);
                        ^
                        |
                    semicolon

Quotes

This isn't really important, but I just thought I'd point it out.

You are consistent in your code with your quotes. For some strings, you use single quotes and for others, you use double quotes.

It is best to stick to one.


Cryptographic Random Number Generator function implementation

This will be a better random number generator than the other options
you mentioned, yes.
The code is nicely indented, but some whitespace between variable declarations and logic would be nice.

Public Sub Randomgenerator()
    Dim byte_count As Byte() = New Byte(6) {}
    Dim random_number As New RNGCryptoServiceProvider()

    random_number.GetBytes(byte_count)
    Dim Output As Integer = BitConverter.ToInt32(byte_count, 0)

    MsgBox(Output)
End Sub

Method names should be PascalCased, so Randomgenerator should be RandomGenerator. Don't use underscore in variable/parameter names. They should be camelCased. Please see the official MSDN capitalization recommendations for more information.
This is begging to be a function that returns a Integer. There should be a main routine that calls and displays the generated number.

Public Function RandomGenerator() As Integer
    Dim byteCount As Byte() = New Byte(6) {}
    Dim randomNumber As New RNGCryptoServiceProvider()

    randomNumber.GetBytes(byteCount)
    Return BitConverter.ToInt32(byteCount, 0)
End Function

Sub Main()
    MsgBox(RandomGenerator())
End Sub

MsgBox is depreciated and left only for backwards compatibility with vb6. Replace it with a MessageBox.
RNGCryptoServiceProvider implements IDisposable. This means that you need to properly dispose randomNumber. From the documentation link you provided:

  This type implements the IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its Dispose method in a try/catch block. To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). For more information, see the “Using an Object that Implements IDisposable” section in the IDisposable interface topic.


I haven't been able to test it, but I'm fairly sure this will work:

$functionName = 'function';
switch(trim($this->uri->segment(5)))
{
    case 1: $functionName .= 'A'; break;
    case 0: $functionName .= 'B'; break;
    case 2: $functionName .= 'C'; break;
}
if($this->my_model->$functionName($this->uri->segment(8), $this->uri->segment(4)))
{
    $data['light'] = $this->my_model->data();
}
else
{
    show_error($this->my_model->errormessage());
}

For more information, see the PHP page on Variable Functions.


Cancelling an order with a side-effect of logging the operation

Cancelling?

  I have a data access layer method to cancel an order.

All I see is code that creates a history-entry for each order you have in your collection. Please forgive and correct me if I'm wrong but if that is the cancellation, I don't see any violation of a single responsibility principle.
Consistency

I see you declaring your variables explicitly and implicitly. Use var everywhere you can or declare them all explicitly. It's just a personal choice, although I'd prefer using var wherever I can.
Naming

Field names use camelCase. The name ´order_id´ is not bad as it describes well what it stands for, but orderId would be more correct as it follows the capitalization styles of Microsoft. Since order is a collection of items, rename it to orders,  order would imply you're only expecting one item.
Code

Checking if an IEnumerable<T> collection has any items, can be done using the Enumerable.Any() method. This is faster than using the Count() method. Let's say the collection has 3 items. Any() will return when it finds the first item whereas Count() will iterate the whole collection. But, if you have a collection that has a Length or Count property, use that for performance.

Since you also do a null-check, I would create an extension method that combines the two. I've written this one for myself which I use often:

public static class Extensions
{
    public static bool AnySafe<T>(this IEnumerable<T> coll)
    {
        return coll.AnySafe(null);
    }

    public static bool AnySafe<T>(this IEnumerable<T> coll, Func<T, bool> predicate)
    {
        if(coll == null)
            return false;

        return (predicate == null) ? coll.Any() : coll.Any(predicate);
    }
}

//Usage:
if (!order.AnySafe())
    throw new EntityNotFoundException();


IsImageUrl extension method written in F#

1.
F# has a good system of type inference. You don't need to specify the type explicitly, the compiler in many cases will do it for you.
You can read more about it here.

2.
As @JoelMueller said in comment, F# there's such an amazing opportunity as partial application.

  The idea of partial application is that if you fix the first N
  parameters of the function, you get a function of the remaining
  parameters

Taken from Partial application

So, you can rewrite the functions hasAnImageFileExtension, hasAnNonImageFileExtension:

let private hasAnImageFileExtension =
  hasAFileExtensionInList ImageFileExtensions

let private hasAnNonImageFileExtension =
  hasAFileExtensionInList NonImageFileExtensions

3.
Several very small comments:

a) In hasAFileExtensionInList instead urlSplitList.[urlSplitList.Length - 1] you can use Seq.last

b) for me, construction like:

if Path.HasExtension url = false then
         false
      else ...

better, rerwite as:

  if Path.HasExtension url then
     ...
  else
     false

4.
In function IsImageUrl it is better to use if-then-else instead pattern matching

5.
Question.

Why not use Path.GetExtension ?

When string not valid will throw the exception. It is better to provide this option.

I don't post a new version of the code, as I plan to edit the answer.


So I can reuse the InvokeSql and do not have to bother about the disposing.

Sure. Except InvokeSql is private, so reuse is rather limited to that class. And if that class has a GetUsers method, I dare expect only User-related stuff in that class... which InvokeSql isn't.

In all likelihood, your model is going to involve more than just User entities; I'd make a base class to encapsulate the CRUD and this InvokeSql method; then a derived type can be responsible for User entities, and another derived type can be responsible for another entity type - something like a "repository".

ExecuteReader returns a SqlDataReader instance, which also implements IDisposable: you're missing a using block here:

IDataReader reader = command.ExecuteReader();
while (reader.Read())

using (SqlDataReader reader = command.ExecuteReader())
{
    while (reader.Read())
    ...


Normally there's no need to specify the color to change from. You only need to specify the coordinates and leave it up to the flood fill routine to find out what color is at that location. I would define another method that is public, and make the recursive method a private implementation method. The public method would look up the color at the location and then call the private method.

public void fill(int x, int y, char newColor) {
    fill(x, y, newColor, pixels[x][y]);
}

private void fill(int x, int y, char newColor, char oldColor) {
    ...
}

You are not using oldColor correctly; you're overwriting the parameter value. The line:

oldColor = pixels[x][y];

should either be deleted or (better) amended to:

char color = pixels[x][y];

And the lines:

if (newColor == pixels[x][y]) return;
if (oldColor != pixels[x][y]) return;

should then be changed to use the color variable:

if (newColor == color) return;
if (oldColor != color) return;

Other than that, you have implemented the algorithm correctly.

It's worth noting that the way this algorithm uses recursion could lead to a stack overflow for a large block of color. Also, by dint of the +1 and -1, will end up calling fill() multiple times for each cell.


First of all, unrelated to your query, you can just inline the dependencies and the body of your factory and controller. It's bulky, but less visual noise. Also allows you to write them in separate files easily.

angular.module("myApp").controller("myCtrl",['$scope', 'demoService'], function($scope, demoService){
  // body
}])

// A more concise version. You'll need ng-annotate if you minify this
angular.module('myApp').controller('myCtrl', function($scope, demoService){
  // body
})

Also, semi-colons are optional in JS. Suggesting your remove them, they're just visual noise. Also convert double-quotes to single-quotes. They both mean the same thing, but the latter is is less visually annoying.

As for your query, first issue with your code is it's not doing what you think it's doing. The moment you call get1000, get2000, and get3000, your timers are already running. The only thing synchronous that's happening in that chain is when they get pushed into the array. In this case, your code can easily just use Promise.all().

function init(){
  var p1 = demoService.get1000()
  var p2 = demoService.get2000()
  var p3 = demoService.get3000()

  Promise.all([p3, p2, p1]).then(results => {
    vm.myList.push(...results.map(obj => obj.name))
  })
}

If you really want to make them synchronous (i.e. call get3000 then push, call get2000 then push, call get1000 then push), you will have to do the following:

function init(){
  demoService.get3000().then(obj => {
    vm.myList.push(obj.name)

    // Only call get2000 if get3000 resolves.
    return demoService.get2000()
  }).then(obj => {
    vm.myList.push(obj.name)

    // Only call get1000 if get2000 resolves.
    return demoService.get1000()
  }).then(obj => {
    vm.myList.push(obj.name)

    // get1000 completed
  })
}

If you're stuck with an environment that does not support async/await, the above syntax (which you're already doing) is pretty much all you've got. You can use arrow functions to make it less noisy. If you can do async/await, then it could be rewritten like so:

async function init(){
  const p1 = await demoService.get1000()
  vm.myList.push(p1)
  const p3 = await demoService.get3000()
  vm.myList.push(p2)
  const p2 = await demoService.get2000()
  vm.myList.push(p3)
}


Let's just focus on this part, because that's where your performance goes:

SELECT
    COUNT(1)
FROM Results LEFT JOIN Users ON Results.UserId = Users.Id
WHERE
    Results.TestId = Tests.Id AND
    Results.MarkedBy IS NULL AND
    Results.QuestionNumber >= 1 AND
    EXISTS (
      (SELECT ClassName FROM UserClasses WHERE UserClasses.UserId = Users.Id)
      INTERSECT
      (SELECT ClassName FROM TestClasses WHERE TestClasses.TestId = Tests.Id)
      INTERSECT
      (SELECT ClassName FROM UserClasses WHERE UserId = @teacherId)
    )

That pattern of EXISTS (... INTERSECT ...) is better written as a chain of INNER JOIN.

The query optimizer of your database already did that internally as well, but it chose the wrong order for the join, resulting in overly large temporary result sets. Especially when joining UserClasses straight on Results without applying the more selective filter by @teacherId first.

SELECT
    COUNT(1)
FROM Results
INNER JOIN TestClasses ON
    TestClasses.TestId = Tests.Id AND
    TestClasses.TestId = Results.TestId
INNER JOIN UserClasses AS TeacherClass ON
    TeacherClass.UserId = @teacherId AND
    TeacherClass.ClassName = TestClasses.ClassName
INNER JOIN UserClasses AS UserClass ON
    UserClass.UserId = Results.UserId AND
    UserClass.ClassName = TestClasses.ClassName
WHERE
    Results.MarkedBy IS NULL AND
    Results.QuestionNumber >= 1

I reordered the JOIN clauses to ensure that the product remains as small as possible after each single step. Further, I eliminated the unnecessary join on the User schema.

However, you don't actually need full INNER JOIN either. If your database system supports that, you can safely replace the 2nd and 3rd of the INNER JOIN with LEFT SEMI JOIN operators instead.

So much for fixing the inner select. But as a matter of fact, now we don't even need to do it as a subquery any more, but can just handle if as a LEFT JOIN with COUNT and GROUP BY on the outmost query.

Whether this actually gains any performance needs to be tested.

There are also a couple of flaws in your database scheme:

Take the UserClasses table schema. You are abusing it to describe both the roles of teacher and student for any given class, without distinguishing between these two. I suspect you coded the user role into the Users schema instead, but it would have been better to store different roles in different schemes.

You are apparently storing class names as string literals in multiple schemes, this is an indirect violation of the 2NF, but even worse, it requires string comparisons to match the corresponding columns against each other. This should be refactored ASAP.

There also appears to be a possible design flaw in Results. If the same test is reused by two different classes, and a pupil is enrolled into both, his test results are now shared between both classes. Test results should probably linked to a specific enrollment to a class, rather than just to the generic test. This also allows to simplify this query further, as the most expensive part of joining on UserClass for querying pupil enrollment is then obsolete.


Plotting Frequency of Vowels in a Paragraph

I strongly advise against CamelCase for your variable names – consider snake_case instead. Why? Because consistency with existing Python code.

I also suggest better spacing around your operators, e.g. x == vowel instead of x==Vowel and pylab.pie(vowel_perc, None, vowel_list, autopct='%1.1f%%') instead of pylab.pie(VowelPerc,None,VowelList,autopct='%1.1f%%'). In general, consistent, even spacing makes code easier to read.

Do not use map, or more precisely: do not use lambdas. Python has list comprehensions which are exactly as powerful as map and filter, but are considered to be more readable. Here, your line

VowelCount = [sum(map(lambda x: x==Vowel,VowelData)) for Vowel in VowelList]

would become

count = [sum([x for x in vowel_data if x == vowel]) for vowel in vowel_list]

Of course, that is far from optimal as we make five passes through the data. If we use a dictionary, we can reduce this to a single pass:

vowels = "aeiou"
counts = dict([(vowel, 0) for vowel in vowels])
for x in data:
    counts[x] += 1
percentages = [counts[vowel] * 100.0 / len(data) for vowel in vowels]

Note that I got rid of the unnecessary vowel_ prefix here, and that I replaced sum(VowelCount) with the likely cheaper len(data) (but with all “optimizations”, the improvement should be benchmarked, not guessed).

As per the pie-plot documentation, you should consider setting the aspect ratio of your axes, so that the resulting chart doesn't look distorted.


Code for saving / loading a class object

Why saving reference to Context and then create SharedPreferences each time? There's duplicate code for creating SharedPreferences You could just use context in constructor to create member SharedPreferences to use in your methods. If you want to keep it as it is, at least extract duplicate code into separate method.
I am missing null checks. I expect to get very obscure behaviour when passing null for keys or classes. Test for null and throw NullPointerException early, be fail-fast. For example checkNotNull or some NotNull annotation to help better fighting against null. Another way to fight is to use kotlin, which doesn't allow null on compiler level unless you make variable optional.
I don't like that gson is private and static.

That means there is no way to configure gson. Would be better if this was member property and I would be able to pass different configuration of gson. Can add consructor overloads for that. Maybe this is overdoing it for your case, but I usually configure Gson quite a lot, have my own TypeAdapters and I wouldn't be able to use my Gson configuration with your class.
At first I was concerned about thread-safety Gson is thread-safe, so there's no argument against static in this sense. Always check for that when you make something static like this.

Pretty sure that when saving preferences in android, you first put key and then value. Your saveObject has it the other way around, that is imho confusing. I'd switch parameters in loadObject too so that key is always first in those cases, but guess that's a bit subjective.
Immutability makes code simpler to use and read. If something is final, you don't need to keep be alert if it changed anytime. context member variable can be final and all method parameters can be final too. After refactoring possible SharedPreferences and Gson instances can also be final - set in constructor.


I this this class is not a Response. But a bundle of things.

class Response
{

Name its clear. But if it is clear, I suggest you to make this class final.

    private $headers = array();
    private $code = 200;
    private $body = '';
    private $sent = false;

By default a non sent response is 200 and without headers?

    private $log;

Here my first big confusion. Why a response should log something? A Response is just a response.

    public function __construct() {
        $this->log = Logger::getLogger(get_class($this));
    }

Alt ^_^. I really suggest you to inject a logger. If you like standards, I suggest to inject Psr\Log\LoggerInterface

    public function headers ($headers) { // Add some headers to the headers array
        $this->headers = array_merge($this->headers, $headers);
        return $this;
    }

I suggest 'set' prefix. From the api I do not understand if the method is a setter or a getter.

    public function header ($key, $value) { // set a single header in the headers array
        $this->headers[$key] = $value;
        return $this;
    }

As above: if this is a setter, ... I suggest 'set' prefix.

    public function code ($code) { // Set the status code
        $this->code = $code;
        return $this;
    }

Instead of comment "set the status code" change the method in `public function setStatusCode()".

    public function status ($code) { // Alternate method for setting the status code
        return $this->code($code);;
    }

Why?

    public function json($str) { // respond with json, set the body text and set the content-type header
        $this->header('Content-Type', 'application/json');
        if(is_array($str)) { // handle either raw JSON text, or php arrays

Why dont you use type hinting and create a method that accept array and one that accept text?

            $this->body = json_encode($str);
        } else {
            $this->body = $str;
        }
        return $this;
    }

    public function html ($str){ // respond with HTML

A method called toHtml is more appropriate here.

        $this->header('Content-Type', 'text/html');
        $this->body = $str;
        return $this;

Fluent interface is ok just for builders. This class should be rename in ResponseBuilder.

    }

    public function form ($str) { // Respond with form data

Why you comment your code instead of make it more readable?

        $this->header('Content-Type', 'application/x-www-form-urlencoded');
        // TODO: Allow the user to user an array
        $this->body = $str;
        return $this;
    }

    public function render ($file){ // Render an HTML file from the templates folder
        //TODO: Restrict to templates folder open
        //TODO: Add server-side rendering code
        $this->body = file_get_contents($file);
        return $this;
    }

    public function sent() { // Check if the request has been sent
        return $this->sent;
    }

This method return a boolan. Should be named to isSent. And also should have a return type hint like public function isSent() : bool.

    public function send () { // send the request

Comment is useless. $request->send() speaks very well.

        if($this->sent()){
            $log->error('Attempted to call send on a sent response!');
            exit('Attempted to call send on a sent response!');

I prefer Exceptions every time something unexpected happens.

        }

        // Log the request for debugging
        $this->log->info($this->headers);
        $this->log->info('HTTP Responce Code: ' . $this->code);
        $this->log->info($this->body);

Anytime you use a comment to group some lines of code, you should remove the comment and make a private method like $this->logRequestForDebugging().

        // Set the headers
        foreach($this->headers as $key => $value) {
            header($key .': ' . $value);
        }

$this->setHeaders()

        // Set the status code
        http_response_code($this->code);

$this->setResponseStatusCode()

        // Send out the body
        echo $this->body;

...

        // Set the sent variable
        $this->sent = true;
    }
}


Newton's Method Polynomial solver in Ruby

Use do...end instead of {...} for multi-line blocks.
return is implicit at the end of a method.
differentiate is a verb. derivatives is the plural noun you're looking for when naming the array.
Use Ruby's array methods (map, reduce, and friends) to your advantage.
Don't modify external variables from inside a block if you can avoid it. I.e. don't do things like n += 1, or x -= .... A combination of with_index and reduce should do the same trick more neatly.
There's some repetition in your handling of the order of coefficients (i.e. the n += 1 in the blocks). It'd be nice to get rid of that.
It'd be nice to specify the number of iterations the approximation should use.

Here's a pretty direct translation of your solution:

# Add a method to Array which zips the array with the index
# of each element in reverse order
class Array
  def zip_reverse_index
    zip((0...count).to_a.reverse)
  end
end

# Use a *-splat to make the method variadic
def solve(*coefficients)
  coefficients.map!(&:to_f)
  derivatives = coefficients.zip_reverse_index.map { |n, i| n * i }
  newton(coefficients, derivatives[0...-1])
end

# Added some (optional) arguments
def newton(coefficients, derivatives, iterations = 10, initial = -1)
  iterations.times.reduce(initial) do |x, i|
    x -= evaluate_polynomial(coefficients, x) / evaluate_polynomial(derivatives, x)
  end
end

# A simpler implementation using reduce
def evaluate_polynomial(coefficients, x)
  coefficients.zip_reverse_index.reduce(0) do |sum, (c, n)|
    sum += c * x ** n
  end
end

Here's a different version that keeps everything in 1 method:

def newton_raphson(coefficients, intial = -1, iterations = 10)
  evaluate = -> (array, x) do
    array.reduce(0) { |sum, (c, ord)| sum += c * x ** ord }
  end

  coefficients = coefficients
    .map(&:to_f)
    .zip((0...coefficients.count).to_a.reverse)

  derivatives = coefficients.map { |c, ord| [c * ord, ord - 1] }[0...-1]

  iterations.times.reduce(intial) do |approx, _|
    approx -= evaluate[coefficients, approx] / evaluate[derivatives, approx]
  end
end

It's pretty long for a Ruby method, but some of the methods in the other implementation seemed too specific to keep around in the global scope (and the Array mixin also seemed a little heavy-handed).

Edit: as @jQweirdy mentioned in the comments, this could also be solved with a class, but I was hesitant to add a class just for one method. But there are a few things here, that might be generically useful for Polynomial class. So here's an example:

class Polynomial
  attr_reader :coefficients

  def initialize(*coefficients)
    @coefficients = coefficients
  end

  def evaluate(x)
    coefficients.zip(ordinals).reduce(0) do |sum, (n, i)|
      sum += n * x ** i
    end
  end

  def derivative
    @derivative ||= begin
      derivatives = coefficients.zip(ordinals)[0...-1].map { |n, i| n * i }
      self.class.new(*derivatives)
    end
  end

  def order
    coefficients.count - 1
  end

  def ordinals
    (0..order).to_a.reverse
  end

  def newton_raphson_approximation(iterations = 1, initial = -1)
    iterations.times.reduce(initial) do |x, _|
      x -= evaluate(x).fdiv(derivative.evaluate(x))
    end
  end
end


Helper method to extract a specific string from long message

Consistent style
You kind of mixing your styles with curly braces - your indentation is inconsistent, and for two duplicate ifs with single statement you once omit the braces, and on the other not. Choose a style, and stick to it - it will make your code more readable

Magic numbers
You made a curious choice to omit the "&lt;" from you start and end indicators, which made you add the mysterious - 4 to your len calculation. This is a major maintenance issue, since tomorrow you will want to extract with unescaped text, where the "&lt;" will be reduced to "<", and your code will stop working...

Use the powers of the tools at hand
Your solution could be much simpler if you used Regex to solve it:

private string ExtractExceptionMesssage(string exceptionMessage) {
    string pattern = @"&lt;Message&gt;(.+?)lt;/Message&gt;";
    Regex rgx = new Regex(pattern);
    var sb = new StringBuilder();
    MatchCollection matches = rgx.Matches(input);
    if (matches.Count > 0) {
       foreach (Match match in matches) {
         sb.AppendLine(match.Value);
       }
    } else {
       return "Unknown error";
    }
    return sb.ToString();
}


Soooooooo many iterations

You can check if the nested braces are valid in a single run through the string. Your code currently does 6n+1 iterations (!!) - and I have no idea what n is there for. You have a loop which does not reference i at all, so at the very least you could just do that part once (which would drop you to just 7 iterations), but really you should do the loop zero times. That's why it's slow. Soooo much unnecessary work!

Wrong output

If maxDepth returns -1, you will print -1 instead of "NIE".

A better algorithm

This is a problem that calls for a stack. When you get an open brace, you add it to the stack (updating maximum size as necessary). When you get a close brace, you check the top value of the stack - if it matches, you're good and you pop. If it doesn't match or the stack is empty - it's invalid and you return -1. If at the end of the string the stack isn't empty, it's invalid and you return -1 too.

That's one single pass. It will also handle the case I mentioned in comments of ({)} which your code would incorrectly return 2.

Code specifics

Avoid using namespace std;
Prefer C++11's range based for loops. In maxDepth(), iterate for (char c : S).
When you're comparing against multiple things like you do, when you're not actually differentiating between the different values, it's clearer to just use a switch statement:

for (char c : S) {
    switch (c) {
    case '(':
    case '{':
    case '[':
       ...
       break;
    case ')':
    case '}':
    case ']':
       ...
       break;
    }
}

In maxDepth(), you don't alter the string, so you should take it by reference to const.
Declare variables when you need them. In main(), you loop over i so declare i in the for-loop itself, not up front. This isn't C.


You are just re-implementing the abs built-in here. (If a number is negative make it positive):
    xd = self.xf - self.xi
    yd = self.yf - self.yi
    if xd < 0:
        xd = xd * -1
    if yd < 0:
        yd = yd * -1

In general I do not understand why you have a whole class defined. I think this should be written more compactly because the actual calculations performed are very simple.
To be more user friendly I would have a function having as input the domain of integration and the function to integrate like:
def weighted_area(xrange, yrange, function, precision):

An argument should be the precision in case the user wants to change the integration step.


Creating a file of md5 hashes for all files in a directory in PowerShell

I rewrote your code from scratch how I would have written it myself. Maybe it can give you some ideas.

$lines = gci -Recurse -File |
    Get-FileHash -Algorithm MD5 | % {
        $unixPath = $_.Path -replace '\\','/'
        $hash = $_.Hash.ToLower()
        "$hash $unixPath" }

$lines -join "`n" |
    Out-File -Encoding ascii -NoNewline $ENV:USERPROFILE\Desktop\hashes.txt

Notes:

gci is an alias for Get-ChildItem.
I used gci -File to get files only.
% is an alias for ForEach-Object.
I didn't use it, but here is the help for FileSystemInfo.FullName
cat is an alias for Get-Content.

Feel free to ask any questions.


Does this Actor implementation has synchronization problems?

There is a problem.. You post() your message and it gets assigned in synchronized block, but it gets accessed in non-synchronized block. The field is not volatile therefore even though the reference to this.message might be visible to ThreadB, the inner state of the object might be still invisible. So message.run() may get you into a trouble.

In order to make things right this.message should be marked as volatile. Read about safe publishing in Java for more details.


This template is either unusable or would make you write HTML in the business logic part  spoiling the whole idea.

A template engine is a more complex application than people often think. There is always a presentation logic that could be quite complex. Which means a template must support programming statements. At least loops and conditions. Without them, it will be almost unusable.

Imagine you need to list 10 posts an a blog. How it could be done in your template? Going to add all the HTML formatting to variables before assigning them? Really?

So, such a simple template could be made viable only by letting PHP to interpret the template. So it could be like

public function render($template, $variables = []) {
    array_merge($this->variables, $variables);
    extract($variables)
    ob_start();
    include $template;
    return ob_get_clean();
}

this way you will be able to use full featured templates that will contain all the logic needed for the presentation of your data.


Authenticating and redirecting six specific users

What is common?

Let's take a look at the cases that look similar and see what is common among them.

case <THIS PART IS DIFFERENT>:
if(PASSWORD.equals(password)) {
    request.getSession(true).setAttribute("username", username);
    response.sendRedirect(<THIS PART IS DIFFERENT>);
}

Okay, so we have essentially that one string (username) leads to another string (a redirect). One thing is pointing at another. Oh, a map/dictionary!

Map<String, String> redirects = new HashMap<>();
redirects.put("client1", "app1/apk-1-index.html");
redirects.put("client2", "app2/apk-2-index.html");
redirects.put("client3", "app3/apk-3-index.html");
....

(Yes, you could use a simple for-loop to setup this)

Then we have to determine first of all: Is our username in the map or not? If it isn't, that corresponds to our default case.

String redirect = redirects.get(username);
if (redirect == null) {
    response.sendRedirect("/Test2/index.jsp");
    return;
}

So, if it is in the map, then let's do the common things and use the redirect we picked from the map:

if (PASSWORD.equals(password)) {
    request.getSession(true).setAttribute("username", username);
    response.sendRedirect(redirect);
}


(1) You define random_scatter as a class but then call it like a function, which works but is confusing. With your programme as it currently stands, there is no reason for it to be a class, so better simply to define random_scatter as a function (use def random_scatter(): at the top).

(2) You can remove repetition and make the code more readable using functions and loops, e.g. write a function

def insert_seperators(number):
    for _ in range(number):
        cmds.separator(height=20, style='in')

then you can replace

    cmds.separator( height=20, style='in')
    cmds.separator( height=20, style='in')
    cmds.separator( height=20, style='in')

with

    insert_separators(3)

(3) If you have other functions doing similar things with cmds then try to see what they have in common and put that in a single function, which accepts parameters according to what changes.


I would opt for another implementation.

You iterate over your map and for each value, you replace a character in the source string. So for n characters in your map, you run n replacement operations for a length of m. Given, that n = m, that takes n^2 steps.

I would make two maps; one for each direction:
(for simplicity reasons, I chose latin letters)

var form1 = {
    'a':'A',
    'b':'B'
};

var form2 = {
    'A':'a',
    'B':'b'
};

If I need to know, whether there is a translation, I could do a simple operation form1['a'] or form1['x'].

A translation - independent of the direction - could be defined as:

function translate(x){
  return (map[x])?map[x]:x;
}

Is a letter in the map, translate it, else return the original letter.

To specify the direction, you could define a closure, passing in the appropriate map:

 function makeTranslation(map){
    return function translate(x){
        return (map[x])?map[x]:x;
    }
}

If you want to translate more than one character, you have to split the string and translate each character. After that join the result:

function translate(expression, direction){
    return expression.split("").map(direction).join("");
}

Which results in two functions:

function toFinal(expression){
    return translate(expression, makeTranslation(form1));
}

function toRegular(expression){
    return translate(expression, makeTranslation(form2));
}

The resulting code looks like this:

var form1 = {
        'a':'A',
        'b':'B'
};

var form2 = {
    'A':'a',
    'B':'b'
};

function makeTranslation(map){
    return function translate(x){
        return (map[x])?map[x]:x;
    }
}

function translate(expression, direction){
    return expression.split("").map(direction).join("");
}

function toFinal(expression){
    return translate(expression, makeTranslation(form1));
}

function toRegular(expression){
    return translate(expression, makeTranslation(form2));
}

console.log(toRegular(toFinal("aabbcbb"))==='aabbcbb');
console.log(toFinal(toRegular("AABBcBB"))==='AABBcBB');


Querying all records from one table, add column from another with foreign key constraint

SELECT  M.id,
        M.name,
        U.custom_name as customName
FROM    mapping M
LEFT JOIN used_mapping U ON U. = M.id
WHERE U.administration_id = 2;

The problem is in the where statement. Here it checks whether the administration_id = 2. For mappings where there is no match in used_mapping this id will be null. So it gets filtered out. Essentially you're performing an inner join here.

Instead you can also allow rows that have administration_id is null:

SELECT  M.id,
        M.name,
        U.custom_name as customName
FROM    mapping M
LEFT JOIN used_mapping U ON U. = M.id
WHERE U.administration_id = 2 or U.administration_id IS NULL;


React Component Reuse with 2 similar components

You can take advantage of conditional rendering to concisely render the iconFile if it exists, and use the conditional operator to construct the outer class name. Using two separate classes for nearly identical functionality is pretty WET, I wouldn't recommend it.

Because the iconFile variable actually contains a string (if it exists), not a File, consider naming it something else, maybe iconPath:

        {iconPath &&

}

{text}

You currently reference properties of this.props a lot. Consider destructuring them all immediately instead.

Since you're using ES6+ syntax, always use const, never use var.

It sounds like Field is using the component prop as a tag name. Because variable tag names in JSX need to be upper-case, and because Component could easily be mistaken for React.Component, consider using a different name, maybe Tag.

const Field = ({ name, Tag, type, value, id }) => (
    <Tag name={name} type={type} value={value} id={id} />
);
class RadioImage extends React.Component {
    render() {
        const { radioGroup, value, iconPath, text } = this.props;
        const radioId = radioGroup + value.replace(" ", "");
        return (

                <Field
                    name={radioGroup}
                    Tag="input"
                    type="radio"
                    value={value}
                    id={radioId}
                />

                        {iconPath &&

}

{text}

        );
    }
}

ReactDOM.render(
    // The Fragments below can be replaced with <>  </> with an up-to-date Babel
    // (Stack Snippets do not support it)
    <React.Fragment>
        <RadioImage radioGroup="radioGroup" value="value1" text="text1" />
        <RadioImage radioGroup="radioGroup" value="value2" iconPath="iconPath" text="text2 with icon" />
    </React.Fragment>
    ,
    document.getElementById('root')
);

You might consider avoiding IDs when possible - they implicitly create global variables, which aren't always the best idea when avoidable. You can move the <input> inside the  so that no htmlFor={radioId} is needed.

You can make RadioImage a stateless functional component if you want, it doesn't look to have any need to be stateful:

const Field = ({ name, Tag, type, value, id }) => (
    <Tag name={name} type={type} value={value} id={id} />
);
const RadioImage = ({ radioGroup, value, iconPath, text }) => (

            <Field
                name={radioGroup}
                Tag="input"
                type="radio"
                value={value}
            />

                {iconPath &&

}

{text}

);
ReactDOM.render(
    // The Fragments below can be replaced with <>  </> with an up-to-date Babel
    // (Stack Snippets do not support it)
    <React.Fragment>
        <RadioImage radioGroup="radioGroup" value="value1" text="text1" />
        <RadioImage radioGroup="radioGroup" value="value2" iconPath="iconPath" text="text2 with icon" />
    </React.Fragment>
    ,
    document.getElementById('root')
);
.option {
  border: 1px solid black;
}


Command manipulation functions for a toy shell program

You indeed have a memory leak in your addcommand function, at this line:

srclist -> list[srclist -> len] -> function = malloc(sizeof(void*));

The reason is that the pointer that you obtained from malloc stored into function gets overwritten later by the following line:

srclist -> list[srclist -> len] -> function = fun;

After this point, the pointer to the memory returned by malloc is lost and you cannot free it, hence the memory leak.

In fact, you don't need to malloc anything for that function, since the memory for the function pointer was already allocated by this line:

srclist -> list[srclist -> len] = malloc(sizeof(command));

The command struct already contains the memory for the field function. So you can just set function to the fun pointer.

Note also that the fun is not a void pointer, but rather a function pointer, so you should declare it as void (*fun)(command_list *) instead of void *fun.

Another comment: why do you keep a command** list instead of command* list? You are currently allocating memory twice, once for the command * pointer, and then for the actual command struct. A simpler (and less memory-hungry) solution would be to have:

typedef struct
{
    command* list; // changed command **list to command *list
    int len;
    command_history* history;
} command_list;

and adding a new command in the list would look like:

void addcommand(char* str, void (*fun)(command_list*), command_list* srclist)
{
    printdebug("Adding command \"%s\" pointing to function at %p in command list located at %p... ", str, fun, srclist);
    srclist -> list = realloc(srclist -> list, sizeof(command) * (srclist -> len + 1));
    srclist -> list[srclist -> len] -> alias = malloc(sizeof(char) * (strlen(str) + 1));
    memcpy(srclist -> list[srclist -> len] -> alias, str, sizeof(char) * (strlen(str) + 1)); //       |
    srclist -> list[srclist -> len] -> function = fun; //                                    <|
    srclist -> len++;
    printdebug("Command added.\n");
}

Additionally, you should check the return value for malloc and realloc. They may return a NULL pointer if there is insufficient memory, and the code that dereferences these pointers will cause a segmentation fault and crash the program.


Named functions

I like the idea of named functions. It helps when you debug your app - you are getting error with name of function instead of "anonymous".

Defalt options

The default options location is good place to keep it. Filter has to be independant from controller and should manage its own data. Although, the default options object is created at every reference to filter. This is waste of resources.

angular.module('app', []).filter('myObjectFilter', function myObjectFilter() {
    //default filter setting
    var defaultFilters = {
        pending: false,
        refusedAt: null
    };

    function _filter(source, search) {
        if (!source) { return source; }
        var result = [];
        search = angular.extend({}, defaultFilters, search);
        ...

Last if

This code:

isFiltered = isFiltered && isEqual;
if(!isEqual) {
    break; //exit loop if filter not passed
}

checks for isEqual two times.

//isFiltered = isFiltered && isEqual; //you can delete this line
if(!isEqual) {
    isFiltered = false;
    break; //exit loop if filter not passed
}

My version checks it only once. I know that you don't get much performance here, but imagine situation when you would like to change the statement for making isFiltered false. You need to change condition in two places. This can lead to serious headache and long debugging in case one of them is forgotten ;)


Getting all the UTC "day stamps" between 2 dates

Instead of an infinite while loop + an if to break out, it would be more natural to convert this to a do-while loop.

The comment "//reached the end of our range. set time to the endDt and get the final day string" is pointless, it just says the same thing with words that the code already tells us perfectly clearly.

c is not a great name for a Calendar. How about cal, or even calendar ? Instead of startDt and endDt, I would just also them out.

It's a bit smelly about the interface that the method requires the date parameters in a specific order, but this is not obvious from the name. And if the caller uses the wrong order, the runtime exception is a heavy penalty, crashing the application. It's not great to have rules that cannot be enforced at compile time, but I don't have a good counter proposal for you.


Determine the index where two lists diverge

Some notes:

Use ArrayList. LinkedList is not random access list. LinkedList#get(index) has O(n), ArrayList#get(index) has O(1)
The second check valid(this) is not required
Use Iterator to avoid (index < size()) && (index < list.size())
Not sure it is really necessary to define a new Class. Simple static util method can also do the job
Avoiding “!= null” statements in Java?

Example:

static int firstMismatch(List<?> original, List<?> other) {

    int index      = -1;
    Iterator<?> it = other.iterator();

    for(Object el : original){

        ++index;

        if(!(it.hasNext() && el.equals(it.next()))){
            return index;
        }
    }

    // TODO: other.size() > original.size()
    return it.hasNext() ? (index + 1) : -1;
}

Prints:

Original: [name, first, middle, last, maiden]
Other:    [name, first, middle, last, maiden]
-1
---------
Original: [name, middle, last]
Other:    [name, first, middle, last, maiden]
1
---------
Original: [name, middle, last, maiden, honorific]
Other:    [name, middle, last]
3
---------
Original: []
Other:    []
-1
---------
Original: [name]
Other:    [address]
0
---------
Original: [name]
Other:    [name, address]
1 // TODO: original has only 1 element

For completeness, another approach is to determine the list with fewer items, then iterate against the larger of the two, and exit when no more matches are found:

public int diverges( DivergentList<E> list ) {
  int index = -1;

  // Determine the larger list for iterating.
  boolean smaller = list.size() < this.size();

  Iterator<E> iFew = (smaller ? list : this).iterator();

  // Iterate over the larger list.
  for( E e : (smaller ? this : list) ) {
    // Terminate when no more items exist in the smaller list.
    if( !(iFew.hasNext() && e.equals( iFew.next() )) ) {
      break;
    }

    index++;
  }

  return index;
}

This introduces a new variable, uses a single return statement, eliminates a final return calculation, and ensures list1.diverges( list2 ) == list2.diverges( list1 ) is always true.

The revised code prints:

Original: [name, first, middle, last, maiden]
Other:    [name, first, middle, last, maiden]
4
---------
Original: [name, middle, last]
Other:    [name, first, middle, last, maiden]
0
---------
Original: [name, middle, last, maiden, honorific]
Other:    [name, middle, last]
2
---------
Original: []
Other:    []
-1
---------
Original: [name]
Other:    [address]
-1
---------
Original: [name]
Other:    [name, address]
0

In this case, the return values indicate the last common index, which allows an empty list to be differentiated from an equal list.


I dislike that your class mixes functionality (a mathematical vector) with memory management. A class should only do one of those. If I prefer shared_ptr I have to rewrite your whole Vector class.

There is actually a thing in C++ that is better than smart pointers, which is value semantics. People rarely screw up the lifetime management of an int, it just works naturally. When you do tricky lifetime management try to mimic the way int does it.

The operator + should be const (as well as GetX, GetY and GetZ). It should also work on Vectors and not only on pointers. The standard way to add Vectors is this:

Vector operator +(const Vector &lhs, const Vector &rhs){
    return Vector(lhs.GetX() + rhs.GetX(), lhs.GetY() + rhs.GetY(), lhs.GetZ() + rhs.GetZ());
}

Note that this is a free function, not a member function of Vector. Prefer free functions, because they work in more cases (like multiplying an int to a Vector) and are thus more consistent.

This allows you to do this:

Vector v1{ 1, 2, 3 };
Vector v2{ 6, 5, 4 };
auto v3 = v1 + v2;

Now, if you do want to support unique_ptr you can do so basically the same way:

std::unique_ptr<Vector> operator +(const std::unique_ptr<Vector> &lhs,
    const std::unique_ptr<Vector> &rhs){
    return std::make_unique<Vector>(*lhs + *rhs); //uses above operator
}

This allows you to do this:

auto v1 = std::make_unique<Vector>(1, 2, 3);
auto v2 = std::make_unique<Vector>(4, 5, 7);
auto v3 = v1 + v2;

All in all you seem to have a pretty good grip on operator overloading and smart pointers already.


Declaring multiple arrays in PHP with one line

This is good as it is.
It's recommended to have one statement per line, for better readability:
code is easier to read when the logic flows from top to bottom,
with no distractions sideways.
So even if there was a way to do this on one line, you really shouldn't.


Script for removing empty rows in a sheet

Your macro does what you intend, but in a very confusing manner.

Whilst running, you're not actually analysing the currentRow but the currentRow + 1. For something like that I'd prefer a name like baseRow because it implies that other calculations will be done on top of it. In any case, it would be much simpler to just go last-row to first and avoid all the line-numbering messiness.

IMO, if you have a macro called RemoveEmptyLines (presumably attached to some descriptively-named Button) then asking the user to confirm that is what they want to do is unnecessary and probably annoying to the User-Experience.

I'm also not a fan of using worksheet functions in VBA, especially when used to determine the current state of the worksheet. Excel is notoriously unreliable at maintaining an accurate up-to-date version of things like usedRange, lastCell etc.

If you want to know the final row across all 10,000-odd columns then you're kinda stuck with it, but I think that's overkill. If somebody sends you a spreadsheet of data, there should be at least one column somewhere which contains data for every row. Might be names, might be ID/Reference numbers, might be dates etc.

I would structure your sub as a procedure that takes a column reference as an argument, or asks the user to input it, then uses that column for the basis of determining your finalRow.

You should also avoid multiple delete actions. It's fine for small worksheets, but try deleting a row in a worksheet with lots of data and it can take a long time, each time. Instead, I would create a range, name it deleteRange and use Union() to add any new "rows to be deleted" to it. Then, you can have just one delete action at the end of your sub and do it all in one go.

Your sub then looks like this:

Option Explicit

Public Sub RemoveEmptyLines()

    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual

    Dim columnReference As String
    columnReference = InputBox("Please input the Letter-Reference of the key data column")

    Dim columnNumber As Long
    On Error Resume Next '/ Check that it is a valid reference
        columnNumber = Columns(columnReference).Column
    On Error GoTo 0

    If Not columnNumber > 0 Then
        MsgBox "Your column reference was not recognised, please try again"
        Exit Sub
    End If

    Dim lastRow As Long, firstRow As Long, currentRow As Long
    Dim lineIsEmpty As Boolean
    Dim deleteRange As Range
    Dim deleteCount As Long

    last Row = Cells(Rows.Count, columnNumber).End(xlUp).Row

    firstRow = 1
    For currentRow = lastRow To firstRow Step -1

        lineIsEmpty = (Cells(currentRow, Columns.Count).End(xlToLeft).Column = 1 And IsEmpty(Cells(currentRow, 1)) And IsEmpty(Cells(currentRow, Columns.Count)))

        If lineIsEmpty Then
            If deleteRange Is Nothing Then Set deleteRange = Cells(currentRow, 1) Else Set deleteRange = Union(deleteRange, Cells(currentRow, 1))
            deleteCount = deleteCount + 1
        End If

    Next currentRow

    If Not deleteRange Is Nothing Then deleteRange.EntireRow.Delete

    MsgBox deleteCount & " rows have been deleted.", vbInformation, "Result"

    Application.ScreenUpdating = True
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic

End Sub

Succinct, clear, easy to read and understand.


Storing values from checkboxes in database

You can use the default parameter from the get method.
Reference

if request.POST:
        user.is_staff = request.POST.get('is_staff', False)
        user.is_active = request.POST.get('is_active', False)
        user.save()


Auditing a complex mix of reasonably small tables

Looks Like a nice, straight forward solution.

The only suggestion that I have , and while this is an unlikely situation, if the database were hosted on a failover cluster and the user were to connect to the instance locally (i.e. from anyone of the servers in the cluster), you wouldn't know which computer they logged in from. The value of @useraddress would be set as '<local machine>'.

This would also be the case when a user connects locally to the SQL Server instance, but if there's only one instance (i.e. not in a cluster), then it's not really a big deal, since you know which computer that is.

Although, to play it safe, why not modify the code to set the value for @useraddess like this, which will give you the computer name instead of '<local machine>':

DECLARE @useraddress nvarchar(128); --<== Originally set as varchar(48)

SELECT @useraddress = REPLACE(client_net_address
                     ,'<local machine>'
                     ,CAST(SERVERPROPERTY('MachineName') AS nvarchar(128)))
  FROM sys.dm_exec_connections
 WHERE session_id = @@SPID;

See:

SERVERPROPERTY (Transact-SQL)


With java 8 you can reduce your code using a more functional programming. It would be something like next. You could even reduce it to one line:

public static boolean allNegatives(int[] a) {
     //@bowmore suggestion edit
     return a != null && Arrays.stream(a).allMatch(i -> i < 0);
}


Right well first off, I'd consider looking into a framework such as Symfony, Laravel, or some other PHP web framework if you want to get serious about doing web design. Right now there is a lot less baggage in rolling your own framework, and the learning curve can be a little steep on them, but once you understand how they work you can spend way less time writing the framework and much more time implementing the actual features you care about.

There are a lot of suggestions I'd consider making, but most involve using routing/middleware layers to accomplish what you are doing here in order to make that form validation logic re-usable in register.php. The logic itself looks fine, but as your needs grow more and more complex you're going to run into some huge pitfalls with the architecture, or lack thereof, you are currently using.

Either way, I'd consider taking a look at Symfony's Validator component. It does a lot of what you're trying to accomplish, but in a really concise and powerful way and eliminates the need to write all of that rule logic in validate.class.php.

From a stylistic point of view, class names should be uppercased and given a noun not a verb. So your class validate -> Validator. Furthermore, your file names should be named after the class they represent and upper cased so validate.class.php -> Validator.php.

That being said, the code is organized quite nicely and is easy to read. Keep up the good work!


Best practice for properties initialization using constructor

I know very little about Dojo, but for me it makes sense to keep constructor as small as possible. I wouldn't also predefine properties with null values and go with this:

define([
    'dojo/_base/declare',
    'dojo/_base/lang',
], function (declare, lang) {
    return declare('xxx.xxx.Command', null, {
        uuid: utilis.UUID(),
        dateCreated: Date.now(),
        },
        constructor: function (action, receiver, properties) {
            this.action = action;
            this.receiver = String(receiver);
            this.properties = properties;
        }
    });
});


Performance-wise, yes, you can optimize it by going character-by-character through the input looking for / characters, such as below. It's weakly tested, and I wouldn't ever consider it in a whiteboard interview. This runs an order of magnitude faster than your method on my old laptop.

public static String getRelativePathMessy(final String from, final String to) {
    final int lastIndex = Math.min(from.length(), to.length());
    int index = 0;
    while ((index < lastIndex) && (from.charAt(index) == to.charAt(index))) {
        index += 1;
    }

    final StringBuilder relativePath = new StringBuilder();
    int fromIndex = from.lastIndexOf(PATH_SEPARATOR, index);
    while (fromIndex > 0) {
        relativePath.append("../");
        fromIndex = from.indexOf(PATH_SEPARATOR, fromIndex + 1);
    }

    if (index < lastIndex) {
        final String toPath = to.substring(to.lastIndexOf(PATH_SEPARATOR, index) + 1);
        relativePath.append(toPath);
    }
    return relativePath.toString();
}

Readability-wise, yes you can optimize it. This is marginally faster than your implementation, probably because it avoids the unnecessary use of Lists. I would argue it's a lot easer to understand what's going on. Why? Fewer branches, especially nested ones, and better names.

public static String getRelativePathNeat(final String from, final String to) {
    final String[] fromPathElements = from.split(PATH_SEPARATOR);
    final String[] toPathElements = to.split(PATH_SEPARATOR);

    final int firstDifferentPathIndex = findFirstDifferentPathIndex(fromPathElements, toPathElements);

    final StringBuilder relativePath = new StringBuilder();
    for (int i = firstDifferentPathIndex; i < fromPathElements.length; i++) {
        relativePath.append("..");
        relativePath.append(PATH_SEPARATOR);
    }

    for (int i = firstDifferentPathIndex; i < toPathElements.length; i++) {
        relativePath.append(toPathElements[i]);
        relativePath.append(PATH_SEPARATOR);
    }
    relativePath.delete(relativePath.length() - 1, relativePath.length());

    return relativePath.toString();
}

private static int findFirstDifferentPathIndex(final String[] fromPathElements, final String[] toPathElements) {
    final int maxIndex = Math.min(fromPathElements.length, toPathElements.length);
    int arrayIndex = 0;
    while ((arrayIndex < maxIndex) && fromPathElements[arrayIndex].equals(toPathElements[arrayIndex])) {
        arrayIndex += 1;
    }

    return arrayIndex;
}


Check if array is monotonic i.e either monotone increasing or monotone decreasing

static
IsMonotonic(...) does not need an instance of the MonotonicArray class to function, therefore it should be static.
Consistency
You special case an array of length 1 as monotonic.  Is it really?  It is neither increasing nor decreasing.
What about IsMonotonic(new int[]{1, 1, 1, 1})?  Seems to me that should be true, but it will return false.  Definitely should be added as a test case.  And if it should return true, then ...
Optimization
... checking for length 1 is too restrictive.  Any length 2 array will always be monotonic as well.  Perhaps:
    if (numbers.length == 1) {
        return true;
    }

should be:
    if (numbers.length <= 2) {
        return true;
    }

Looping
This is ugly.  Will Java optimize the numbers.length - 1 calculation as a constant?
    for (int index = 0; index < numbers.length - 1; index++) {

        if (numbers[index + 1] == numbers[index]){
            continue;
        }
        ...

It may be better to use Java's enhanced for loop to extract numbers, and rely on monotonic behaviour allowing equality to handle the first element:
    int current = numbers[0];
    for(int value : numbers) {
        if (value != current) {
           if (value < current) {
              ...
           } else {
              ...
           }
           current = value;
        }
    }


It just looks really good.

I think it stayed this long unanswered because there's not much feedback to give.

I reviewed and liked

The commenting
The naming
The sizes of your functions
Reading flow

I am not convinced that choosing a random int actually helps the load balancing much, but don't have a better alternative. I would also probably put the random number generator in a helper class, it does not really belong in a tooltip component.