If you chose the code-first approach, I presume you don't have to deal with the constraints of an existing database. If that assumption is correct, then I'd say you've done it the hard way.

Convention Over Configuration

Entity Framework can infer keys (primary and foreign) from the names of your entity members; your code isn't leveraging this formidable capability.

For a greenfield project, I like to start with a base entity type:

public abstract class EntityBase
{
    public int Id { get; set; } // inferred PK
    public DateTime DateInserted { get; set; }
    public DateTime? DateUpdated { get; set; }
}

Now I can derive, say, Document from that class:

public class Document : EntityBase
{
    public bool? Status { get; set; }
    public string DocumentText { get; set; }
    // ...

    public virtual DocumentMetadata Metadata { get; set; } // inferred FK
}

The PK is inferred from the inherited Id property (or [TypeName]Id), and the mere mention of a virtual property referencing another entity type is enough for EF to understand you want a FK there.

I'll pause here to mention that I was somewhat thrown off by your non-usage of the C# language aliases for System.String, System.Int32 and System.Boolean. They're typically written as string, int and bool.

You mention you're only reading from the database. This sounds like you're going code-first with an existing database. It's certainly possible, but the best way to do this in my opinion, is to reverse-engineer the database into entity classes - then you get the best of both worlds, and the generated code can teach you a lot about how EF works.

I think the presence of DisplayAttribute and NotMappedAttribute smells like you're possibly using your entities as both data entities and presentation / ViewModels. I think I would separate these concerns and create separate classes for presentation purposes,  where HighlightedText means something relevant.

Also note that relying on a declarative DisplayAttribute will make it quite a pain to localize the application, if you ever need to do that in the future; you'll want these things resolved at run-time, accounting for Thread.CurrentThread.CurrentUICulture.

The naming is overall ok, except I don't like the Status column. It's just too vague of a name. What do the null, true and false values mean? The name should convey that meaning. Also I wouldn't prefix most of Document's members with the word "Document", and ID should follow the PascalCasing convention and be Id.


Improvement in function isprime:
for(let i = 2; i <= number / 2; i++)

can be
for(let i = 2; i <= Math.round(Math.sqrt(number)) + 1 ; i++)

Otherwise, the best easy to understand approach(in accordance to my knowledge) is to use the Sieve of Eratosthenes. Your problem can be a subset of the following problem Sieve of Eratosthenes JavaScript implementation - performance very slow over a certain number. Credits of the code below goes to the owner of this post.
function getPrimesUnder(number) {
  var start = new Date().getTime();

  var numbers = [2];
  var sqNum = Math.sqrt(number);
  var i, x;
  for (i = 3; i < number; i = i + 2) {
    numbers.push(i);
  }
  for (x = 0; numbers[x] < sqNum; x++) {
    for (i = 0; i < numbers.length ; i++){
       if (numbers[i] > numbers[x]) {
        if(numbers[i] % numbers[x] === 0){
          numbers.splice(i, 1)
        }
      }
    }
  }
  var end = new Date().getTime();
  var time = end - start;
  alert('Execution time: ' + time/1000 + ' seconds');
  return numbers;

}

There is something much more efficient (Which is the fastest algorithm to find prime numbers?) known as Sieve of Atkin. You can do more research on it.


Shortening

  Can I get some help on shortening the amount of code I have in this program?

Shortening shouldn't be a primary concern. But ok let's go.

In get_file,
if an error occurs while downloading the page,
you print the exception, and then execution continues,
and the program will crash on the next line that tries to access the downloaded response.
You could just as well remove the try-except,
the result will be actually better,
because that way the crash will show the real problem (download error).

The same argument goes for the try-except in find_movies too.

You use two libraries to download data: requests and urllib.
You only need either of those, so you can get rid of one import.

file_name = file_name + '.torrent' can be shortened to file_name += '.torrent'

Instead of this:

torrent = select_torrent()
test(torrent)

You can delete the select_torrent function and write this:

torrent = raw_input('>>')
test(torrent)

Making it better

Follow PEP8, the Python coding style guide.

test is a very poor name for what it does.

Some validation for the selected torrent would be good.


Finding all pairs of numbers in a collection whose sum is some particular number

You haven't clarified what you're expecting your input to be but your code doesn't work unless the input is a set of positive integers starting at 1 and increasing 1 at a time.
For example:
var inputCollection = new List<int> { 5, 6, 7 };
var targetNumber = 12;

var pairs = ExtractPairs.Extract(inputCollection, targetNumber);

Clearly, 5 + 7 = 12 but your code returns no pairs! That's either a huge bug or the algorithm is expecting a very restricted input. I'd put my money on a huge bug.

Don't make structs with public mutable fields (unless you're in a very specific performance critical scenario). As pointed out in comments, I should have backed up this advice with some evidence. Here's an SO question about it or simply quoting the MS guidelines for struct design

X DO NOT define mutable value types.
Mutable value types have several problems. For example, when a property getter returns a value type, the caller receives a copy. Because the copy is created implicitly, developers might not be aware that they are mutating the copy, and not the original value. Also, some languages (dynamic languages, in particular) have problems using mutable value types because even local variables, when dereferenced, cause a copy to be made.

public struct Pair
{
    public int First;
    public int Second;
}

Make them readonly properties and add a constructor. I'd probably just use a Tuple<int, int> though.

Prefer formatting strings over concatenation:
Console.WriteLine(pair.First + ", " + pair.Second);

could be:
Console.WriteLine("{0}, {1}", pair.First, pair.Second);

In C#6 we also have string intperpolation:
Console.WriteLine($"{pair.First}, {pair.Second}");

In this simple case, the concatenation is actually fine. It's clear because it's short. As things become longer and more complex, the format string approach can make the final string clearer to see for a human. There are also a great many options for things like padding and formatting numbers and dates that are easily done in the format string.
Just an FYI, the concatenation is turned into a call to string.Concat:
Console.WriteLine(string.Concat(new[] { pair.First, ", ", pair.Second }));


jQuery on-change using multiple selectors

Some general points:

Watch your indentation
Watch your whitespace
An id is unique on a page - there is no benefit to 'element#id' vs '#id' as a selector
It is usually better to store references to elements that don't get removed

Let's apply some of these on the change handler to store the focus field. Here's what we're starting with:

$(document).on('change','.submittable',function(){
    if($('input#focus_field').length){
        var $focus_field = $(this).attr('id')
        $('input#focus_field').val($focus_field)
    }
    $('input[type=submit]').click();
    return false;
});

We don't want to search the DOM for the element every time (unless it can be added/removed) so let's pull it out:

var $focusField = $('#focus_field');

Notice that I've simplified the selector to just the Id. Now we can use our knowledge of jQuery to simplify the next bit of the function.

$(document).on('change', '.submittable', function(e) {
     e.preventDefault();
     $focusField.val(this.id);
     $('input[type=submit]').click();
}

The reason this works is that selecting a set of elements that don't exist in the DOM returns an empty jQuery array which is more than happy to be chained - it just won't do anything. I've also modified your return false to use the recommended preventDefault function on the event object.

If you want you can pull out common functionality into separate functions. For example:

var showAndReload = function (selector) {
    $(selector).show();
    $('#reload_form').val('true');
    $('input[type=submit].btn-primary').click()
};

// nested_form - fields added
$document.on('nested:fieldAdded', function() {
    showAndReload('#ajax_working')
});

// nested_form - fields removed
$document.on('nested:fieldRemoved', function() {
    showAndReload('#please_wait');
});

I'm not really sure it adds much though.


With some short code like that, I decided I'd run it to get a better feel for the program.  Here's my first session:

Guess Number: 45
3 Turns left
Try again - N was  9
Guess Number: 9
2 Turns left
Congratulations, You won!

Do You Want To Play Again? (Y / N): yes

(end)

You didn't give any rules at the beginning of the file, so how was I to know the number had to be between one and ten?  I know only because I looked at your code.  I typed 45 and there was no indication that it was invalid.  It told me it wasn't the right answer and said I had three turns left, but it also told me what the right answer was.  That made my second guess easy.  I was right, but it still printed 2 Turns left.  I said yes when it asked if I wanted to play again, but it exited the program anyway.  Another minor thing: you want to look professional and that includes more than just how the program works.  It includes how your text is formatted.  Your caPitaliZatioN maKes a diFfErence iN How yOur ProGram LooKs.  You have a lot of unnecessarily capitalized letters.  I would recommend looking up a good style guide on capitalization.

print 4-turns, ...

Why 4?  Well, of course, it's because that's how many turns there are.  It's an arbitrary number (called a magic number) that should instead be defined as a constant at the beginning of the file to be used in all cases instead of typing in magic numbers.  You also shouldn't be printing how many turns are left unless the user did not win or lose.  That means that it should come after the if and else blocks.

exit()

It is unnecessary to exit; you can just use break.

if int(user_guess) == int(computer_guess):

What if the user typed wheeeee!?  It's a common thing to say, right?  Well, anyway, the user might type something invalid and you wouldn't want to have an error if he did.  You'd have a disgruntled user on your hands.  You also don't need to convert computer_guess.  It's already an integer.

if play_again.upper() == 'Y':
    continue
else:
    exit()

You shouldn't just continue.  You also need to reset turns.

You shouldn't use a bare else.  What if the user typed yes as I did?  It still exits.  You should use a loop there that validates the user's input.  If you want to be really fancy, define a function that excepts a bunch of different inputs as positive and a bunch as negative.  I once wrote a function that even counted uh huh as a valid way of saying yes.

print "Try again - N was ", computer_guess

You shouldn't tell the user what the answer is until the game is over.

The new code:

from random import randint

TOTAL_TURNS = 4

turns = 1
computer_guess = randint(1, 10)
while True:
    try:
        user_guess = int(raw_input("Guess number between 1 and 10: "))
    except ValueError:
        print "Please type an integer."
        continue
    if not 1 <= user_guess <= 10:
        print "Please type a number between 1 and 10."
        continue
    if turns == TOTAL_TURNS:
        print "You lost! Loser!"
        break
    else:
        if user_guess == computer_guess:
            print "Congratulations, You won!\n"
            while True:
                play_again = raw_input("Do you Want To Play Again? (Y / N): ").upper()
                if play_again in "YN": break
                print "Please type Y / N"
            if play_again == 'Y':
                turns = 1
                computer_guess = randint(1, 10)
                continue
            else:
                break
        else:
            turns += 1
            print "Try again"
    print TOTAL_TURNS - turns + 1, "Turns left"


The performance of this will largely depend on filesystem I/O,
and the number of files and subdirectories in your target folder.

It won't make a difference in practice,
but in theory it will be faster to check the extension against a set instead of a list, for example:

extensions = {'.mp3', '.wma', '.wav', '.ogg'}
for dirpath, dirnames, filenames in os.walk(path):
    for item in filenames:
        name, ext = os.path.splitext(item)
        if ext in extensions:
            allSongs.append(name)

Notice that I changed the for folder in os.walk(path) to the more intuitive for dirpath, dirnames, filenames in os.walk(path),
which makes the inner loop more intuitive too,
for item in filenames instead of the cryptic for item in folder[-1].

But most of all,
I'm wondering if it's really os.walk you want to use.
This function is useful for traversing a directory tree,
down into arbitrary levels of subdirectories.
I'm questioning your intention because you only keep filenames, not their paths.
So for example a song The Four Horsemen.mp3 may exist in both /Users/ceaser/Music/Metallica and in /Users/ceaser/Music/Mix/Oldies-But-Goodies, and then you will have The Four Horsemen.mp3 in allSongs twice.
Not caring about the intermediary directories suggests that perhaps there are no intermediary directories, all songs are simply directly under /Users/ceaser/Music.
In that case, instead of os.walk, using os.listdir would be more appropriate and simpler too.

Lastly, there is an official coding style guide for Python,
called PEP8,
I recommend to give it a good read and follow it in the future.


Extremely simple stack implementation using a vector

Remove int n;from member variable.
Underlying container std::vector holds the size information of the stack class. It increases the size of stack class object by sizeof(int).

Remove various default definition methods from your class. Compiler would generate it for such classes. Due to these definition your class looks more verbose.

Implement all your member functions using the underlying container classes.

Prefer the standard name of your method instead of other. This way any program would easily use your custom class instead of std::stack. Change the isEmpty() to empty()

Your implementation can be simplified as below.

template<class T>
class Stack {
public:
    Stack(const std::initializer_list<T>& i):elem(i) {}
    int size() const { return elem.size(); }
    bool empty() const { return elem.empty();}
    void push(const T&);
    T pop();
    T peek();
private:
    std::vector<T> elem;
};

template<class T>
void Stack<T>::push(const T& t) {
    elem.push_back(t);
}

template<class T>
T Stack<T>::pop() {
    if (empty()) {
        throw std::out_of_range("underflow");
    }
    auto x = elem.back();
    elem.pop_back();
    return x;
}

template<class T>
T Stack<T>::peek() {
    if (empty()) {
        throw std::out_of_range("underflow");
    }
    return elem.back();
}


Matplot lib : scalling of the axes on bar plot

Use plt.xticks - https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.xticks.html.
One may to xticks np.arange(len(cluster.clusters)) as an argument
And for yticks it works in a same fashion -if you pass np.arange(int(max(cluster_sizes))), there will be integer ticks along the y-axis


Uploading and downloading files with FTP

You aren't doing proper error handling.  For example, changing the directory could fail due to a permission problem.  In addition to pre-screening each commands, you need to check the status returned by the server.  In RFC 959, linked from the ftplib documentation, you'll see that status codes ≥ 400 indicate an error.  (You'll need to include an English-to-German translation table for the errors listed in Section 4.2.2 of the RFC.  Unfortunately, the errors aren't very specific as to the exact cause.)


Well, first off, I must commend you on the readability of your code.  You've employed nice spacing and enough comments to be able to find different sections easily without a lot of reading.  I think I could learn a thing or two from you here.  Nice job!

There are a few things you can do to improve your code, though.  Let's start with the general practices first.

General practice advice

Unless your script is intended to set environment variables for other scripts or applications, you should always use setlocal.  Even if the script you're writing is intended to append a new directory to %PATH%, you should still setlocal at the top until your internal flow is complete and you're ready to commit the change to %PATH%.  This way you don't pollute your environment with a bunch of variables that only have meaning within a particular script -- or worse, have meaning in a different script that expects the variable not to be defined yet.  Whenever you @echo off, setlocal should automatically be the next thing you type.
When setting variables to string values, it's good practice to set "varname=string" with the quotation marks surrounding both the variable and its value.  That way, whenever you use your variable later, there's no ambiguity whether your variable="value" or variable=value.  Also, in a future script, you might capture special characters into a variable, like an ampersand or a percent.  Get into the habit of set "variable=value" now and you won't have to change your coding style for special cases like that, and you'll spend less time debugging.
Likewise, in your if statements, you should enclose the items on both sides of your comparison operator.  if "%foo%" equ "%bar%", or if "%%~xI"==".exe".  I can't count all the times as a rookie scripter I would struggle with errors when %foo% contained a space, causing "blah was unexpected at this time" because I didn't use quotes.
set /a has some shorthand syntax you might find helpful.  Interestingly, when you're doing math with variables, you don't have to use % around the variable names.  For example, instead of set /a year=%year%-1 you can set /a year=year-1.  You can also combine operator and assignment like +=, *=, /=, etc.  So instead of set /a year=%year%-1 you can set /a year-=1.

Now, there are a few issues specific to this script that can be improved.

Script-specific suggestions

%date% and date /t are ambiguous.  Some locales list date as MM/DD/YYYY, while others use DD/MM/YYYY, and still others use YYYY/MM/DD.  (more information.)  A more agnostic way of scraping the date would be to use wmic.  See Method 2 on this page for a way to put the date into variables that should work more universally.
When using del with a wildcard, consider adding the /q switch to suppress confirmation, unless you intentionally want your script to ask the user to confirm deletion.
Consider changing ping -n 5 192.168.100.44 > nul to ping -n 5 0.0.0.0 >NUL.  Having an actual IP there might (at at glance) prompt the reader to wonder whether the script will behave differently whether the host does or does not respond; whereas 0.0.0.0 makes it obvious that you're using the ping command as nothing more than a period of sleep.
if Not exist bkp-%lastmonthfiles%.zip <-- If this is ever true, you are going to pause twice, then exit.  Examine your logic here.  Did you leave out a goto compress?

What it looks like you intended to do is attempt to zip; then if the zip file doesn't exist, echo a notice to the user, pause, then loop back to :compress to try again.  Otherwise, assume everything went fine and delete all the old stuff and exit.  What happens if a file is in use and locked, and 7-zip skips archiving it but was otherwise successful with the other log files?  bkp-%lastmonthfiles%.zip still exists, and your script could potentially delete the file that was skipped.

If I may make yet another suggestion, you should rewrite the end of your script to take advantage of 7-zip's exit codes.  Try this instead.  (Note: "%zip%" is in quotes on the assumption that you followed "General practice advice #2" above.)

:compress
"%zip%" -tzip  a -y "bkp-%lastmonthfiles%.zip" %lastmonthfiles%* && (

    DEL /q %lastmonthfiles%*
    echo Zipping complete.  Press any key to exit.
    pause >NUL
    goto :EOF

) || (

    if ERRORLEVEL 2 (

        echo Zipping failed ^(exit status %ERRORLEVEL%^).  Trying again in 5 seconds...

    ) else (

        echo Zip completed with warnings ^(most likely because a file was locked by another
        echo process and had to be skipped^).  Trying again in 5 seconds...

    )

    del "bkp-%lastmonthfiles%.zip" >NUL 2>&1
    ping -n 6 0.0.0.0 >NUL
    goto compress

)

A note about the && and || notation there: That's shorthand code for testing the exit code of the command preceding it.  program.exe && success || fail.  See conditional execution for more details on how this works.


I see you aren't using any sort of multithreading or asynchrony. That means that your server is an iterative one - i.e. it can only process one client request at a time. If a request takes long, subsequent requests may have to wait to be processed. Depending on what you're doing, this may be acceptable or not.

What I don't quite like with your implementation is the way you're dealing with incoming data. You're doing low-level buffer read operations, and you are then looking for the \0 to see where it ends, and then transforming it into a string.

The reason you're doing this is that if your buffer is 10 bytes long and the incoming data is 5 bytes long, then the buffer will look like this:

Hello\0\0\0\0\0

But that can lead to a number of problems. What if the incoming data is larger than the buffer? What if there's a \0 within the actual data itself?

There is no single way to do this, as this is a protocol design thing. Let's take a look at a few ways you could have done this.

1. Newline-delimited requests

If you know your data will never contain newlines, then you can end each request with a newline, and then easily use StreamReader.ReadLine() to process your data without all the low-level buffer details. Example:

        var server = new TcpListener(6969);
        server.Start();
        var client = server.AcceptTcpClient();
        var stream = client.GetStream();

        using (var reader = new StreamReader(stream))
        {
            string data = reader.ReadLine();

            // do something with the data...
        }

2. Counting bytes read

#1 above isn't always an option, e.g. if your data contains newlines.

An important observation here is that your data can arrive at the application in chunks - not necessarily as one long string as you might expect. So it is a good idea to likewise read it in chunks, similar to the following:

        var server = new TcpListener(6969);
        server.Start();
        var client = server.AcceptTcpClient();
        var stream = client.GetStream();

        using (var reader = new StreamReader(stream))
        {
            var sb = new StringBuilder();
            var buffer = new char[8192];
            int bytesRead = reader.Read(buffer, 0, buffer.Length);

            if (bytesRead > 0)
            {
                var buffer2 = new char[bytesRead];
                Array.Copy(buffer, buffer2, bytesRead);
                sb.Append(buffer2);

                // if sb meets some criteria, process the data...
            }
            else
                Console.WriteLine("Client disconnected!");
        }

Over here we're reading data into a buffer - not much different from what you were doing. But there are a few things we're doing differently:

We are reading in chunks. We aren't assuming that we get all the data at once; we're appending the partial data to a StringBuilder, and then doing something with it once any criteria are met (e.g. there is a terminator character, or a predefined number of bytes have been read).
We're copying into a secondary buffer. If we keep to the example I mentioned earlier where we had a 10-byte buffer but 5 incoming bytes, then we copy just those 5 bytes into a second, 5-byte buffer, to get rid of the extra padding (\0s).
We know how much data was read with each call to StreamReader.Read(), because it returns the number of bytes read. This allows us to both do #2 above and also to detect a disconnect.

3. Length-prefixed requests

In #2 above, I mentioned that you must check the data itself to see that you received a whole, integral request and that you can now start processing it. Some protocols do this using a terminator character (e.g. \n, which may or may not be a candidate for #1 above, or possibly other characters).

Another variant places the number of bytes at the beginning of the request, so that the receiving end knows how many to expect. For example, the agreed protocol would be that the first four characters are a number representing the data length, allowing a maximum of 9999 bytes. The actual data would look something like this:

38  Indiana Jones and the Fate of Atlantis

The code would be quite similar to #2 above, but you'd have to extract the length as soon as you have those four bytes available in your buffer, and then call Read() repeatedly until you have all the bytes you were expecting. At that point, you can process the data.

Encoding

I also noticed that you're using an ASCII encoding to convert your data between bytes and strings. This may be okay for some scenarios, but you'll have trouble if you need to deal with multilingual data. UTF8 may be more appropriate in such cases.


Just a few quick things I see to help improve your code:

I would start using the HTML5 Doctype, unless you have a specific reason not to. <!doctype html>
Instead of having an
 tag why not just put a border-bottom:2px solid #06f; on your #header div.  And then add like a padding-bottom:5px;
Instead of having

Link

Another Link

Why not just do this:

Link

Another Link

And just change your CSS accordingly:

 .menu { text-decoration:none; margin:0; padding:0; }
 .menu li { display:inline; }


A few words about assumptions:

You're assuming that arp is installed. This is definitely not true for my system. arp as well as other "core network tools" like ifconfig have been superseded by ip. The more modern equivalents are ip neigh show and ip addr. The obsolescense is explicitly mentioned on the manpage
IIUC (because traceroute isn't available on my arch) similar considerations apply for traceroute. Also do note that you should be able to use the same idea as for the arp-check in the creation of private_route:

route = $(tracepath -n 8.8.8.8 | awk '{print $2}')
private_route = # consider ipcalc or use $route as a smaller input to python

Final considerations:

You're inconsistent in the indentation of block scopes. In arp_checker the then and else block are indented, in route_checker they are, but the for loop body is not.
I strongly recommend indenting every block to increase readability.

Aside from that: Good job of not falling into common traps like:

not double-quoting variables
not using subshells
using unsafe condition checks
missing a shebang

From what I can see, this is a well-crafted script :)


Refactor Oxford Comma function (and other functions)

Oxford comma

Are these really your expected outcomes?

# for ['a']
Configs not found for:  and a.

# for ['a', 'b']
Configs not found for: a and b.

# for ['a', 'b', 'c']
Configs not found for: a,  b, and c.

In particular, the case of a single item looks like a bug, and in the case of 3 or more items the 2 spaces between a,  b looks a bit strange.

In any case, it would make sense to split the method, for example:

def _format_missing_message(self, missing):
    if missing:
        message = _oxford_comma(missing)
        self._tab_pane.currentWidget().update_status(
            "Configs not found for: {}.".format(message))

@staticmethod
def _oxford_comma(items):
    length = len(items)
    and_clause = '{} and '.format('' if length <= 2 else ',')
    return and_clause.join([',  '.join(items[:-1]), items[-1]])

This way it's easier to unit test the Oxford comma logic.

Finally, I think the method would be slightly easier to read like this:

def _oxford_comma(items):
    length = len(items)
    if length == 1:
        return items[0]
    if length == 2:
        return '{} and {}'.format(*items)
    return '{}, and {}'.format(', '.join(items[:-1]), items[-1])

Count Duplicates

My only objection is the method name, count_duplicates. You are counting elements, not necessarily duplicates, and returning a map of item => count pairs. So for example get_counts would be more natural.

That's all I can pick on ;-)


General Observations
This code should work just fine, but performance can be enhanced.
Initialize Arrays to Zero at Compile Time
Currently there is a performance hit in the code when initializing the array t to zero. The function memset() is a runtime function, by initializing the array t to zero there is no run time cost:
    char t[32767] = {0};

The previous line of code initializes the entire array to zero (equivalent to the call to memset()) and should not affect run time.
Use Table Lookup Over Long Switch Statements
The Scrabble word scoring question linked to in this question uses a table look up instead of a long switch statement. Table lookup is better for 2 reasons, the first is that it will only be one line of code rather than at least 26 lines of code, the second reason is that table lookup should be much faster than the logic that implements the switch/case statement.
Magic Numbers
The code includes unistd.h for the definition of the symbolic constant STDIN_FILENO but the numeric constant 32767 is used multiple times rather than defining a symbolic constant for it. It would be better to define a symbolic constant for 32767 using either a const declaration or a #define preproccessor statement.
    const size_t INPUT_BUFFER_SIZE = 32767;

or
#define INPUT_BUFFER_SIZE 32767

This makes the code more readable and much easier to maintain, since an edit to change the value would only need to be performed on one line rather than having to search through the code to replace every instance of the numeric constant.
    char t[INPUT_BUFFER_SIZE];
    unsigned int val = 0;
    if (argc == 2)
    {
        memset(t, '\0', sizeof(t));
        strcpy(t, argv[1]);
    }
    else
    {
        read(STDIN_FILENO, t, INPUT_BUFFER_SIZE);
    }

Portability
The include file unistd.h does not port to Windows or some other non POSIX systems, which means this code won't even compile on some systems. While it is less readable, using zero is more portable, or have an ifdef in the code to define STDIN_FILENO on all systems.
#ifndef STDIN_FILENO
#define STDIN_FILENO 0
#endif

The Code Doesn't Allow for Switches on the Commandline
The code makes an assumption that there is no commandline switch that precedes the input to be processed if argc is greater than 1. This could result in bugs in the future. It might be best to have some kind of check for switches in the command line processing.
Complexity
If the code continues to use the switch/case statement then it would be better to move that statement into it's own function that returns an integer value.


Duplicate like a weapon, arrays like heaven

@tim suggested a way to do this with less memory by sorting the array. There's another way to do it with less memory without needing to sort.

Let's say that \$k\$ is the duplicate value in the array. Then we know that the sum of the elements in the array is equal to

\begin{align}
0 + 1 + 2 + 3 + \cdots + (n - 2) + k = \frac{(n - 2)(n - 1)}{2} + k,
\end{align}

where we're using the identity

\begin{align}
1 + 2 + 3 + \cdots + n = \frac{n (n + 1)}{2}.
\end{align}

So if sum is the sum of the values in the array, the duplicate value will be sum - (n - 2) * (n - 1) / 2.


Laravel - Repository and Entity patterns

Maybe I'm just thinking of a different approach, but I normally would've reversed the dependency between UserEntity and UserRepository.  I would expect the UserEntity to represent a singular record in the database and that I would use the UserRepository to retrieve one.

In this case, I would inject the UserRepository into the controller and call UserRepository.Login(userId, password) that would actually perform the lookup against the DB and return a UserEntity representing the logged in user.

Also, I would suggest defining interfaces for your injected classes so that it's easier to provide future implementations


Is Janua really a valid month? If so, then you're fine, but I have a feeling that this would be more appropriate.

DateMonthJanuary ::= 'January' | 'Jan' | '0'? '1'

Which brings me to my next problem. It's case sensitive, right? So, 22-JAN-2015 wouldn't match. I believe it should, but I'm not familiar with Robol. Please correct me if I'm wrong.

I've seen this handled by defining case insensitive tokens for each letter.

A ::= 'a' | 'A'

And then define your rules from those tokens like this.

DateMonthJanuary ::= J A N U A R Y | J A N | '0'? '1'

My syntax may be a little off, I'm accustomed to ANTLR's flavor of EBNF, but that should illustrate the idea.

DateYearLeap ::=

I'm really not sure that I would handle that in your grammar. The logic is convoluted (not yours, just leap years in general) and I'm pretty sure this will match a few leap years that aren't. Much better for this one to be validated by your parser if that's possible.

/* Need to constrain to valid hours */
TimeHour ::= Sign Digit* | Sign? Digit+

/* Need to constrain to 0-59 */
TimeMinute ::= Sign? Digit Digit?

/* Need to constrain to 0-59.999999 */
TimeSecond ::= Sign? ((Digit Digit?)? '.' Digit+ | Digit Digit? '.'?)

I think you should be able to define tokens for these. It may take a bit of doing to get the precedence right, but start with something like this.

TimeMinute ::= Sign? [0-6] Digit
/* Optional Sign, Optional 10s Digit 0-6, 0-9*/


My first point would be that if I want throttling for my API, I would put it in some kind of interceptor. However since this is an interview assignment and for the sake of simplicity I would recreate that as a function call:

public synchronized void create() {
    if(isAccessible()) {
        create(employer);
    }
}

Secondly, I don't think it is a good idea to block with the while-loop you have, when the quota of calls have been made. Instead return a meaningful message that explains why the request was denied.

With the current implementation you are using the InterruptedException as part of your control flow, which is usually considered an anti-pattern https://softwareengineering.stackexchange.com/questions/189222/are-exceptions-as-control-flow-considered-a-serious-antipattern-if-so-why.

I feel like a simpler solution would be to simply reset the counter every 60 seconds in the Timer class, similar to what you are already doing. Maybe I am missing something, but I don't understand why you are doing the check:

System.currentTimeMillis()<=timer.getElapsetime();

You are already resetting the counter every 60 seconds, so I would just return false in this method.

My last point would that generally the client would be passing Employee (or whatever data needed to create an employee) in the request, so it does not make sense to have Employee as a field. Rather it should be a parameter of the create function.

If this came as an interview question I would also see it as an opportunity to talk about throttling, and what alternatives there are. For example, maybe checking the rate of calls instead of having a fixed window of 60 seconds would make sense. However that's not that related to this code review.


You do not need to use Date, parse, Exception, .... You only need LocalDateTime :

LocalDateTime d1 = LocalDateTime.now();
LocalDateTime d2 = LocalDateTime.parse("25/11/17 09:00:00", DateTimeFormatter.ofPattern("yy/MM/dd HH:mm:ss"));

long days = d1.until(d2, ChronoUnit.DAYS);
d1 = d1.plusDays(days);
long hours = d1.until(d2, ChronoUnit.HOURS);
d1 = d1.plusHours(hours);
long minutes = d1.until(d2, ChronoUnit.MINUTES);
d1 = d1.plusMinutes(minutes);
long seconds = d1.until(d2, ChronoUnit.SECONDS);

System.out.println(days + " days " + hours + " hours " + minutes + " minutes " +
                                                         seconds + " seconds.");

Step by step, from large precision to small, it will look the difference with this precision and then add it to be nearer of the target


Write a function to determine whether an array contains consecutive numbers for at least N numbers

One issue to consider: what if an element in the array is 0, and thus falsey? Then if (prev && will not be fulfilled:

console.log(hasConsecutiveNums([-1, 0, 1], 3)) // false... oops

function hasConsecutiveNums(array, N) {
  if (array.length < N) return false;
  if (N === 0) return true;
  const sortedArray = array.slice().sort((a, b) => a - b);
  let count = 0;
  let prev = null;
  for (const num of sortedArray) {
    if (prev && num === prev + 1) {
      count++;
    } else {
      count = 1;
    }
    if (count === N) return true;
    prev = num;
  }

  return false;
}

console.log(hasConsecutiveNums([-1, 0, 1], 3)) // false... oops

Another tweak to make the code a bit more elegant would be to assign prev to the first element of the array first, and initialize count to 1, thus starting comparison on the second element rather than on the first, avoiding the need to compare against null.

With this method, you also need to return true immediately if the array's length is only 1, like the other answer recommends, otherwise there won't be any iterations within which return true could be reached:

function hasConsecutiveNums(array, N) {
  if (array.length < N) return false;
  if (N <= 1) return true;
  const sortedArray = array.slice().sort((a, b) => a - b);
  let prev = sortedArray.shift();
  let count = 1; // first element of the array is already in prev
  for (const num of sortedArray) {
    if (num === prev + 1) {
      count++;
    } else {
      count = 1;
    }
    if (count === N) return true;
    prev = num;
  }

  return false;
}

console.log(hasConsecutiveNums([1, 4, 5, 6], 3)) // true
console.log(hasConsecutiveNums([1, 4, 5, 6], 4)) // false
console.log(hasConsecutiveNums([-1, 0, 1], 3)) // true

If, as the comment notes, you'd want [1, 2, 2, 3] to return true, de-duplicate the numbers with a Set:

function hasConsecutiveNums(array, N) {
  if (array.length < N) return false;
  if (N <= 1) return true;
  const sortedArray = [...new Set(array.slice().sort((a, b) => a - b))];
  let prev = sortedArray.shift();
  let count = 1; // first element of the array is already in prev
  for (const num of sortedArray) {
    if (num === prev + 1) {
      count++;
    } else {
      count = 1;
    }
    if (count === N) return true;
    prev = num;
  }

  return false;
}

console.log(hasConsecutiveNums([1, 4, 5, 6], 3)) // true
console.log(hasConsecutiveNums([1, 4, 5, 6], 4)) // false
console.log(hasConsecutiveNums([-1, 0, 1], 3)) // true
console.log(hasConsecutiveNums([1, 2, 2, 3], 3)) // true


Just a small suggestion.

Typical typing rate is 40 WPM (with keyboard). It means more or less one character every 300ms. With mobile phone (and a good virtual keyboard) rate is typically slower (around 20/30 WPM).

Assuming:

You can start a request in few milliseconds.
User will have a useful result after few typed characters.

It means that for each user and for each typed word you will start few HTTP connections with your server (in the best case where user will pick something from the autocomplete). Multiply for all the searched words for all your user base and you will see that you add a useless load to your server (and you consume mobile bandwidth...)

Do not start lookup while typing but AFTER user stopped typing for a short period, let's say 300 ms for mobile devices but you may tune this value with some usage statistics. Network latency, server response time and UX fluidity need to be considered to find a trade-off.

Note that this may be done also with a simple Task.Delay(300) inside GetAutocomplete(), before calling _client.GetAsync(). It has the advantage to keep GetAutocompleteSearchResultsAsync() unchanged.

await Task.Delay(DebouncingDelayInMilliseconds, cancellationToken);


Top to bottom, here we go.

COUNT(DISTINCT ID_ORDER)

This DISTINCT aggregation seems superfluous, if ID_ORDER is a true identity column then there should not be duplicates. This will improve performance.
LEFT JOIN DELIVERY AS d USING (ID_COURIER)

I'm not a big fan of the USING keyword as I find it ambiguous. Agreed it's a useful shorthand but to the next person going back to read your code they would have to go and check that both tables have a ID_COURIER column. Plus if one of the columns got renamed at any point it would be more difficult to find the bug.

My suggestion:

LEFT JOIN `DELIVERY` AS d ON c.ID_DELIVERY = d.ID_DELIVERY

WHERE c.ID_COMPANY = ?

This doesn't seem to have any purpose I'm sure you could take it out with no difference.
CASE WHEN (SELECT MAX(START_DATE) and the rest of the statement.

This I find very unusual and not optimal for performance. I'm not sure I completely understand what you are trying to do but I'll give it my best shot. You may want to instead build this into your select. Here is what I suggest for the complete script. I made some edits to the layout to make it easier to read. If I misunderstood the intention of your CASE statements let me know and I can revise.

SELECT
    c.ID_COURIER,
    c.NAME,
    c.NICKNAME,
    c.AREA_CODE,
    c.PHONE_NUMBER,
-- This will return NULL if ID_GEOLOCATION is NULL
    (SELECT MAX(ID_GEOLOCATION) FROM GEOLOCATIONS) AS 'ID_GEOLOCATION',
    d.DESCRIPTION,
-- This will return NULL if START_DATE is NULL
    (SELECT MAX(START_DATE) FROM ORDERS) AS 'START_DATE',
    d.END_DATE,
    d.CANCELED,
    r.LAT,
    r.LNG,
-- Subquery JOIN moved to FROM and WHERE statements
    COUNT(ID_ORDER) AS 'REMAINING ORDERS'
FROM COURIER AS c
    LEFT JOIN DELIVERY AS d ON c.ID_DELIVERY = d.ID_DELIVERY
    LEFT JOIN GEOLOCATIONS AS r ON r.ID_DELIVERY = d.ID_DELIVERY
    LEFT JOIN ORDERS AS o ON d.ID_DELIVERY = o.ID_DELIVERY
WHERE c.DISABLED = false
AND o.DELIVERY_DATE IS NULL AND o.CANCELED = false
GROUP BY c.ID_COURIER
ORDER BY d.START_DATE DESC;


You have quite a few methods that need to run for all words. Currently you always make sure that you output a list again, but you could use generator expressions to avoid these intermediate lists.

from typing import Generator, Iterable

REMOVE_PUNCTUATION = str.maketrans('', '', string.punctuation)

def filter_words(words: Iterable[str], max_length: int) -> Generator[str, None, None]:
    """
    Filters each of the words by the criteria passed by the user. Also
    ensures that the word is a "word" (no numbers or special characters).

    :param Iterable[str] words: Words to filter
    :param int max_length: Max word length

    :return Generator[str, None, None]: Filtered words
    """
    return (word for word in words if len(word) <= max_length and word.isalpha())

...

def get_words(url: str) -> Generator[str, None, None]:
    """
    Returns all the words in the website. Steps this function takes:

    1. Get all text from website
    2. Creates a list with words that have punctuation removed
    3. Removes newlines from each word in the list and lowers it
    4. Removes each "" in the list and joins to a string
    5. Returns a list of each word as an element of the list

    :param str url: Url of website

    :return Generator[str, None, None]: Iterable of all text in website
    """
    body = urllib.request.urlopen(url).read()
    soup = BeautifulSoup(body, 'lxml')
    texts = soup.findAll(text=True)

    # Steps begin #
    visible_texts = filter(visible_tag, texts)
    words = (str(word).translate(REMOVE_PUNCTUATION).rstrip().lower()
             for word in visible_texts)
    return filter(None, words)

Note the () instead of []. I also made the trans a global constant instead of re-creating it every iteration, grouped up some of the methods and used the faster LXML parser. The generator expression will be run by the call set(words) in main.

Your write_to_file can also be slightly improved by using writelines:

def write_to_file(filename: str, words: Iterable[str]) -> None:
    """
    Creates a file in the same directory as the file.

    :param str file_name: Filename of word file
    :param Iterable[str] words: Words to write to file

    :return None:
    """
    with open(f"{FILE_DIRECTORY}/{filename}", "w") as file:
        file.writelines(f"{word}\n" for word in words)

You might want to consider using requests instead of urllib, since it is much more usable (although the difference in this case is negligible). Instead of manually parsing sys.argv, you could use argparse, which allows much more complicated argument parsing and automatic help message generation.

Regarding style, PEP8, the official style-guide, recommends using less than 80 characters per line, which your code does not and mine mostly does (stupid signature for generator type...). However, larger values are also acceptable, if applied consistently. More than 100 characters should be avoided nevertheless.


Here's a different approach, using the DOM instead of innerHTML, and using document fragments to append all at once and improve performance. Also you don't need that many regex, specially if you're copy/pasting them; splitting by any whitespace character and removing empty elements from the resulting array will do.

Then you could make use of the builtin higher-order functions such as map and
reduce to minimize the use of for loops and make the code a bit cleaner:

var doc = document;

var extend = function(a, b) {
  Object.keys(b).forEach(function(k){a[k] = b[k]});
  return a;
};

var elem = function(tag, props) {
  return extend(doc.createElement(tag), props);
};

/**
 * @param words {Array}
 * @returns {Object} Frequency of words per length
 */
var frequency = function(words) {
  return words.filter(Boolean).reduce(function(acc, x) {
    acc[x.length] = ++acc[x.length] || 1;
    return acc;
  },{});
};

var empty = function(x) {
  while (x.hasChildNodes())
    x.removeChild(x.lastChild);
  return x;
};

/**
 * @param freq {Object} Frequence of words per length
 * @returns {Node} Document fragment
 */
var resultOf = function(freq) {
  return Object.keys(freq).reduce(function(frag, k) {
    frag.appendChild(elem('p', {
      textContent: 'Words with '+ k +' chars: '+ freq[k]
    }));
    return frag;
  }, doc.createDocumentFragment());
};

var textarea = doc.getElementById('text');
var button = doc.getElementById('analyse');
var result = doc.getElementById('results');

button.addEventListener('click', function() {
  var res = resultOf(frequency(textarea.value.split(/\s+/)));
  empty(result).appendChild(res);
});

Demo: http://jsbin.com/motoy/1/edit

To learn more about these idioms, I'd recommend reading JavaScript Allonge, and Functional JavaScript. For JavaScript documentation visit the MDN


I personally prefer your 3rd example

Object addressParam =
    String.IsNullOrEmpty(Address.Text) ?
    (Object) DBNull.Value :
    (Object) Address.Text;

 comm.Parameters.AddWithValue("@Address", addressParam);

It easily reads that you are evaluating and initializing your Object and directly after you're using your newly instantiated Object. It also doesn't take up as much space as your if-statements and it doesn't really slow you down when reading the code -> you see an Object being initialized and then used, and when needed you can always take an extra second to see what you're evaluating.


Manipulate JSON data from the client with JavaScript

I see several problems.

Redeclaring function arguments as local variables
Assigning variables undefined by default
Failing silently when "falsey" arguments are passed

Redeclaring Function Arguments

This is absolutely unnecessary. You're only creating more variables that must be garbage collected by the browser, adding weight to your code and getting no tangible benefit from it. Now if you wanted copies of the arguments because you need to modify the data but still know the original values passed to the function, then you have a case for creating variables separate from the arguments, but this is an exception to the rule.

Assigning Variables undefined By Default

This is already how JavaScript works. This pattern should be used to give meaningful default values where applicable.

Failing Silently When "Falsey" Arguments Are Passed

Fail early, and fail noisily. You don't want to chase production bugs caused because someone forgot to pass an argument and have no indication that the argument was required. If they truly are required, throw errors:

var addMod = function(modContent, sectionName, sessionName) {
    if (!modContent) {
        throw new Error("Missing required argument: modContent");
    }

    if (!sessionName) {
        throw new Error("Missing required argument: sessionName");
    }

    if (!sessionName) {
        throw new Error("Missing required argument: sessionName");
    }

It makes for extra code, but development and maintenance become easier because you get clear errors (and stack traces). This really is a judgement call. There is a fine line between bullet proofing your code and expecting some level of intelligence from the people using it, especially for dynamically typed languages like JavaScript. If you have a public API, document it thoroughly. And "public" could mean "pushed to GitHub" or "used by coworkers at work."


Parsing error messages using regular expressions in Java 8

First, let's optimize what you already have. Extract the regexes, and simplify the logic:

private static final String LINE_EX = "^Line\\s(?:(\\d+)\\s)?\\s*:\\s+(\\d+)?.+"
private static final Pattern LINE_PARSE = Pattern.compile(LINE_EX);

private LawfirmInvoice getInvoiceForErrormessage(InvoiceParcel parcel, String message) {
    if (parcel.getInvoices() == null) {
        return null;
    }

    if (parcel.getInvoices().size() == 1) {
        return parcel.getInvoices().get(0);
    }

    Matcher mat = LINE_PARSER.matcher(message);
    if (!mat.matches()) {
        return null;
    }
    String group = mat.group(1) != null ? mat.group(1) : mat.group(2);
    if (group == null) {
        // neither regex group had digits....
        return null;
    }
    int lineNumber = Integer.parseInt(group);
    return parcel.getInvoices().get(lineNumber);
}

OK, the regex is more complicated, but, there's only one of them, and it is compiled only once. The regex looks for digits on either side of the colon, and returns them in either group 1, or group 2. Note that the regex expression (?: .... ) is a non-grouping match, so does not count as a group, but the (\\d+) inside it, does.

Also, note that your original regex probably has a bug, because it searches for just a single-digit in it: String regex2 = "^Line\\s\\d\\s\\:\\s+.+"; when it should probably look for \\d+ and not just \\d.

Additionally, there is no need to escape the : in your regexes.

Now, there's only 1 regex, not three. It is statically compiled, and our code logic is streamlined.

What we now have, is a function, it takes two arguments, and returns a third. I cannot see any references to 'state' in your class, so your method can easily be a static method. This makes your function a proper java.util.function.BiFunction function if you want it to be, e.g.:

BiFunction<InvoiceParcel, String, LawfirmInvoice> GET_ERROR_INVOICE =
               MyClass::getInvoiceForErrormessage;

This is where you can start having 'fun' with java 8 streams and so on:

final List<InvoiceParcel> parcels = ......

// create an array of all LawFirmInvoices that have errors...
parcels.stream()
    .flatMap(parcel -> getMessagesFor(parcel)
         .stream(message -> getInvoiceForErrormessage(parcel, message))
    .filter(invoice -> invoice != null)
    .toArray(size -> new LawFirmInvoice[size]);

(Assuming a getMessagesFor(parcel) exists....)


Calculate number of words and characters (/statistics) from an HTML Textarea

I will give it a try:

These days I would recommend using document.querySelector, to write generic code which is well amenable to code re-factoring without introducing bugs.

So either:

var  textarea = document.querySelector("#my-textarea")
    ,statusBar = document.querySelector("#status-bar");

or in later JavaScript versions, I believe >=1.6 (i.e. OK Server-side, when a specific JS-runtime can be guaranteed):

var [eltxtarea, elstatusbar] = document.querySelectorAll("#my-textarea,#status-bar");

Do not assign elements to Id's that are also keywords/attributes in the HTML specification (as such not textarea but e.g. my-textarea )
Bind the invocation of your function to an event or directly to underlying data-changes(requiring additional frameworks such as backbone.js). Do not use the respective exposed handler attribute but rather the attachEventHandler.

elstatusbar.attachEventHandler( "change", changeHandlerStatusbarUpdate);

The Handler:

    var changeHandlerStatusbarUpdate = function(evt){
        if(evt instanceof Event && evt.target instanceof HTMLTextAreaElement){
        //you can be more specific. Event is just the Baseclass.
        //for instance you may test for "KeyboardEvent" only

        //the following logic should be improved: See threads of how to count words in a language/culture-specific fashion
            var text = textarea.value,
            chars = text.length,
            words = text.split(/\b\S+\b/g).length - 1,
            lines = text.split("\n").length,
            stat = lines + " lines, " + words + " words, " + chars + " characters";
            evt.target.value = stat;
        }
    }

Do not put the updateStatusBar function in the global or window scope when the function relies upon textarea in the outside-scope, but use scope-encapsulation via closures (example), or a retrieve the target element within the function or through the event-target in a handler-function.

As pointed out in the source-comment, the word-counting is much to trivial and not "culture-invariant" as is the case right now.


I suppose the simplest thing is to go through the principles:

SRP - Cannot see any 'too big' things in your example
OCP - The example is small enough and you are not using class
inheritance that I cannot think of how this would apply
LSP - You only have one implementation of each interface so hard to
say
ISP - Your interfaces seem to serve a single purpose that might serve
the needs of several users - so no complaints there
DIP - You have pushed the more variable 'decision' making out,
keeping the API more abstract which seems reasonable.

Much of this, of course, depends on your specific aims and requirements. some thoughts:

How likely is it that the mapper and reader will vary independently?
Are you going to get any reuse out of all the different readers and mappers (actual not future-proofing)
Will each reader have a mapper in practice, in which case your comment about combining the mapper and reader is worth more thought.
Do you really need an interface for the reader, it seems like you are just wrapping what could be a function/lambda
What is the motivation in restricting the outbound data?
I appreciate this may just be an exercise, but it's good practice to think if you need to do this kind of restriction

It can be difficult to have a good instinct for principles like SOLID on toy problems due to the lack of realistic constraints and compromises.


String validation based on multiple criteria

Your five functions only differ by the predicate used to test each character, so you could have a single one parametrized by said predicate:

def fulfill_condition(predicate, string):
    for character in string:
        if predicate(character):
            return True
    return False

if __name__ == '__main__':
    s = input()
    print(fulfill_condition(str.isalnum, s))
    print(fulfill_condition(str.isalpha, s))
    print(fulfill_condition(str.isdigit, s))
    print(fulfill_condition(str.islower, s))
    print(fulfill_condition(str.isupper, s))

Note that you don't need to convert the string to a list for this to work, strings are already iterables.

Now we can simplify fulfill_condition even further by analysing that it applies the predicate to each character and returns whether any one of them is True. This can be written:

def fulfill_condition(predicate, string):
    return any(map(predicate, string))

Lastly, if you really want to have 5 different functions, you can use functools.partial:

from functools import partial

func_alnum = partial(fulfill_condition, str.isalnum)
func_isalpha = partial(fulfill_condition, str.isalpha)
func_isdigit = partial(fulfill_condition, str.isdigit)
func_islower = partial(fulfill_condition, str.islower)
func_isupper = partial(fulfill_condition, str.isupper)


Optimise Division function using divide and conquer, (and multiplication only)

Before optimising your code, it is probably a good idea to write a few tests to ensure you don't break anything as you go. There is something quite good in your situation : your code is supposedly easy to test as you know the mathematical properties that your result should have : a = b * q + r with 0 <= r < b.

Writing something like :

std::cout << "j" << "*" << "q" << "+" << "r" << " = " << "t" << " (" << "i" << ")" << std::endl;
for (uint i = 2; i < 10; i++)
    for (uint j = 2; j < 10; j++)
    {
        uint q = 0;
        uint r = 0;
        DivisionDivideAndConquer(i, j, q, r);
        uint total = j * q + r;
        if (total != i)
                std::cout << j << "*" << q << "+" << r << " = " << total << " (" << i << ")" << std::endl;
    }

shows that there is something wrong in your result which is the first problem (Hint: the problem is in the shortcut). Trying to perform tests with j starting from 1 shows that there is another issue (Hint: a loop does not finish).

Actual optimisation

Think about the cases you are trying to handle or how you are trying to reduce the search range.

With the following code, you compute less in each iteration while making the search range smaller :

    // if too small then we have a new max
    if (possibleremainder < 0) {
        max = number - 1;
    }
    // too big we have a new min
    else if(possibleremainder >= static_cast<int>(den) )
    {
        min = number + 1;
    }
    else
    {
        //  got it!
        quo = number;
        rem = static_cast<uint>(possibleremainder);
        break;
    }


Logging observable values while extending service

One way to achieve what you want is to use .do() and may be .catch() operators.

.do() operator taps on a target stream and executes a function on each non-error event in the stream. It is designed specifically for this purpose, which you can define more generically as side effects:

  This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. -- RxJs docs

Notice that .do():

does NOT affect the original Observable stream in any way. This function itself returns an Observable of the same type as the original one.
does NOT subscribe to the original Observable, so the .subscribe() invocation is required down the road.
does NOT react to error events in the original Observable. Therefore, you may want to use .catch() to log the errors.

fromEvent<T>(eventName: string): Observable<T> {
  return super
    .fromEvent(eventName)
    .do(eventData => {
      console.group();
      console.log('----- SOCKET INBOUND -----');
      console.log('Action: ', eventName);
      console.log('Payload: ', eventData);
      console.groupEnd();
    })
    .catch(error => {
      console.group();
      console.error('----- SOCKET INBOUND -----');
      console.error('Action: ', eventName);
      console.error('Error: ', error);
      console.groupEnd();
    });
}


Simple string-split by root and sufix algorithm

About "best thing"... The "principle of simplest is best"  seems valid. The number of commands, and the computational simplicity of each command.

str_splitByRoot1: 2 fast commands (strpos and substr) and 1 condition and strlen
str_splitByRoot2: 2 fast commands (substr) and 1 to be checked (strspn+str ^ str)
str_splitByRoot2 optimized: 1 fast command (substr), 1 to be checked (strspn) and 1 condition.
...

So, my doubt was about strspn+str ^ str performance... And its time  struck me most,  was near time for str_splitByRoot1...

  $str_splitByRoot = array(
       function  ($str, $root){  // str_splitByRoot1()
            if (strpos($str,$root)===0)
                return array($root, substr($str, strlen($root)) );
           else
                   return array( '', $str );
       },

       function  ($str, $root){ //str_splitByRoot2()
           $rootLen = strspn($str ^ $root, "\0");
           return array( substr($root,0,$rootLen), substr($str,$rootLen) );
       },
       function  ($str, $root){ //str_splitByRoot2() optimized
           $rootLen = strspn($str ^ $root, "\0");
           return array( $rootLen?$root:'' , substr($str,$rootLen) );
       },

       function  ($str, $root){  //str_splitByRoot3()
         $s = explode($root,$str);
         return ( count($s)>1  && !array_shift($s) )?
             array($root,join($root,$s)):
             array('',$str);
       }

       function ($str, $root){ // str_splitByRoot5
            $root2 = str_replace(array('/','.','-'),array('\\/','\\.','\\-'),$root);
           if (preg_match("/^$root2(.+)$/",$str,$m))
                 return array($root,$m[1]);
           else
                 return array('',$str);
       }
  );

  function str_sepByRoot($i,$str,$root){
       global $str_splitByRoot;
       global $debug;
            $func = $str_splitByRoot[$i];
            $s = join(' * ', call_user_func($str_splitByRoot[$i],$str,$root)); // $func($str,$root));
            if ($s &&  $debug)
                 print "\n ___ $s";
  }

  $debug=0;
  for ($i=0; $i<count($str_splitByRoot); $i++) {
       print "\n--- $i ---";
       $time = microtime(true); // time in Microseconds
       for($j=0;($j<333 && !$debug) || ($debug && $j<1); $j++){
            str_sepByRoot($i,"walking","walk");
            str_sepByRoot($i,"hello","walk");
            str_sepByRoot($i,"walking-walk-walk","walk");
            str_sepByRoot($i,"/var/www/myApp","/var/www/");
            str_sepByRoot($i,"DOI:10.1038/ncomms7368","DOI:10.1038/ncomms");
       }
       echo "\n", (microtime(true) - $time) . ' elapsed';
  }

Result:
--- 0 ---
0.0037140846252441 elapsed
--- 1 ---
0.0045409202575684 elapsed
--- 2 ---
0.0040040016174316 elapsed
--- 3 ---
0.0088369846343994 elapsed
--- 4 ---
0.0075829029083252 elapsed
--- 5 ---
0.0037930011749268 elapsed

Conclusion, using str_splitByRoot1 as reference (100%),

str_splitByRoot2 optimized  is ~105% , so for practical use it's as good as  str_splitByRoot1.
str_splitByRoot2  is ~115%, something good when compared with str_splitByRoot3 (~125%).
str_splitByRoot5 is 225%... as expected, the worst (even without  str_replace regex escapes).

... But, the performance changes (!) when using a big root, an Lorem ipsum of 800 words. The performance profile changed to:

str_splitByRoot2 (optimized or not)  ~244%... bad!
str_splitByRoot3  (with direct split by explode) is ~120%, very good!
str_splitByRoot5 (regex)  ~390%, the worst of course.

So, the only that shows more "stability" (~120%)  about root length was str_splitByRoot5, and str_splitByRoot2 is not a good replacement for  str_splitByRoot1 in the context of big roots.


Your code is pretty clean and well-formed, but I do have several critiques.
Unexpected behavior
Your program will exhibit unexpected behavior if the phrase entered by the user is longer than GETNAME_SIZE - 2 chars.  In that cases, the fgets() call in getPhrase() will leave the tail of the line unread, and reading should be expected to pick up there in the subsequent getChangedPhrase() call (to terminate no later than the end of that line).  The user will no doubt expect the phrase to be encoded according to the next line they enter, not the tail of the first.
To fix that, you should either arrange in getPhrase() to keep reading through the end of the line.  You can discard characters after the GETNAME_SIZE - 1th if you like, or you can arrange to append them to the phrase (you'll need realloc()).  Just don't leave a tail of the line unread.
getChangedPhrase() behaves similarly when it reads the key, which again could be surprising.  It is not certain to be sufficient to limit the input key length to the message length because you don't necessarily use all of the key characters (you skip those that aren't ASCII letters).  Cutting off the tail of the key can therefore change the result.
This fragment looks wrong:
                if( phrase[i] + pace > 90 && code[j] < 90)
                phrase[i] = phrase[i] + pace - 26;

I think you mean
                if( phrase[i] + pace > 90 && phrase[i] < 91)
                phrase[i] = phrase[i] + pace - 26;

See also below.
Flawed implementation
Your code can easily be made to overrun the bounds of the code array.  In fact, that will happen if the number of usable key characters is smaller than the number of letters in the message.  To (partially) fix this, you need to wrap around the end of the key inside the while loop, rather than at the end of the for loop where you now do that.
That will, however, expose another flaw in your implementation: it does not handle the case where there are zero usable key characters.  Your current implementation will just immediately run off the end of the array in that case; after the fix, it will loop infinitely.  See below for a suggestion that will help.
Error handling
getPhrase() does a decent job of noticing when memory allocation fails or nothing is read from the input.  It helpfully returns NULL in those cases.  main(), however, ignores those signals and unconditionally passes the result to getChangedPhrase().  For its part, getChangedPhrase() assumes that its argument is always valid.  Either main()'s behavior or getChangedPhrase()'s could be ok in isolation, but together they constitute a flaw producing undefined behavior under some circumstances.
Similarly, getChangedPhrase() returns NULL in some failure conditions, but main() pays no attention, assuming that the return value is a valid pointer, in attempting to print it.
Implementation improvement
If you have strdup() (which is standardized by POSIX, not C itself) then it is a convenient alternative to strlen() + malloc() + strcpy().
getChangedPhrase() calls fflush(stdout); before prompting for the encoding key.  This is useless.  Move the flush after the prompt, or remove it altogether.  Since the prompt ends with a newline, it is probably unnecessary to flush even after printing the prompt.
I remarked above on problems with your key handling.  I observe also that you handle your key inefficiently if it is short relative to the phrase to encode.  You shouldn't need to check on each pass through the key which characters are usable.  You shouldn't need to account for upper- vs. lowercase on each pass, either, if indeed you make them behave the same way.  Instead, process the key once, before the encoding loop: remove characters other than letters, and convert all the letters to a standard case.  Then it's also easy to validate result to ensure that there is at least one (or two, or whatever) key characters.
It doesn't make sense to me that your encoding code is not parallel for upper- and lowercase key characters.  The code for uppercase keys looks equally applicable to lowercase keys except the computation of pace, but you use a more complicated and difficult to follow scheme for lowercase key characters.  Indeed, one of the alternatives for lowercase keys cannot even be exercised, because code[j] < 90 and code[j] > 96 cannot be true at the same time.
Design improvement
Your function getChangedPhrase() modifies the input string in-place, but also returns a pointer to it.  On the other hand, the function's name suggests that it will create a new phrase.  I suggest changing that function's signature to
void encodePhrase(char *);

to clarify what it's doing.  If you wish to have the ability to signal an error, then you could consider using an int return value to signal the status, following the model of many standard library functions.


Creating a Ruby gem that talks to another gem

I suggest you take a close look at how the gem you are using is tested. Those tests include mocks for all responses of the API (I assume) and is a good example for testing gems in general.

Notice:

helper methods in the support folder including shared examples
mock data to simulate responses from the source API
custom matchers to make code better readable and reduce repetition of code (DRY-principle)

Those to me are the three most important you should embrace for now.


Codility binary gap solution using indices

Converting from string to int in your first comprehension isn't needed as you're comparing to a literal anyway.
You can merge the first two comprehensions.
you don't need to return early, as you can default max to 1.
You shouldn't need the 8 in your format, as it shouldn't matter if there's padding or not, as it'll be filtered anyway.
From Python 3.6 you can use an f-string.

def solution(N):
    indices = [bit for bit, x in enumerate(f'{N:0b}') if x == '1']
    lengths = (end - beg for beg, end in zip(indices, indices[1:]))
    return max(lengths, default=1) - 1


You don't need to explicitly build the tree to compute its depth.

class TreeDepth(object):
    def __init__(self, parents):
        self._parents = parents
        self._n = len(parents)
        self._max_depth = None
        self._depths = [None] * self._n

    def max_depth(self):
        if self._max_depth is None:
            for idx, parent in enumerate(self._parents):
                depth = self.get_depth(idx)
                if self._max_depth < depth:
                    self._max_depth = depth
        return self._max_depth

    def get_depth(self, idx):
        depth = self._depths[idx]
        if depth is not None:
            return depth
        parent = self._parents[idx]
        if parent == -1:
            depth = 1
        else:
            depth = self.get_depth(parent) + 1
        self._depths[idx] = depth
        return depth

>>> TreeDepth([4, -1, 4, 1, 1]).max_depth()
3

If my math is good, this goes over each item in self._parents at most twice, so it will have \$O(n)\$ performance. Also, I have used a recursive approach to compute the depth, but if speed is your main goal, you will probably want to turn that into an iterative approach:

def max_depth2(self):
    if self._max_depth is not None:
        return self._max_depth
    for idx, parent in enumerate(self._parents):
        parent_stack = []
        while parent != -1 and self._depths[idx] is None:
            parent_stack.append(idx)
            idx, parent = parent, self._parents[parent]
        if parent == -1:
            depth = 1
        else:
            depth = self._depths[idx]
        while parent_stack:
          self._depths[parent_stack.pop()] = depth
          depth += 1
        if self._max_depth < depth:
            self._max_depth = depth
    return self._max_depth


You say you're new to Python. Well, that's ok. And a Caeser Cipher is a good place to start since it's complex enough for an absolute beginner while easy enough to understand what goes on, why and when.

One thing to keep in mind is that Python comes batteries included. This means a lot of what you want to accomplish is already written, one way or another. You just have to know where to find it.

For example, take the first function of your program:

def charSplit(str):
    return [char for char in str]

Simple enough. charSplit('foo') returns ['f', 'o', 'o'].

Did you know we can do the same with list? list('foo') returns ['f', 'o', 'o'] as well.

So, we're down 1 function. Let's create a new one. You're wrapping your code quite nicely here:

if __name__ == "__main__":

This makes sure the code is only running when the file itself is called, not when it's imported by another file. How about taking it a step further to clean things up?

def main():
    # all code that was previously behind the mentioned if-statement goes here

if __name__ == "__main__":
    main()

Everything above the if are global variables. I'm not a fan of global variables, so we'll get rid of them later. But let's assume for a moment you want to keep them around.

Since some of those are only read and never overwritten (pseudo-constants), it's usually preferred to CAPITALIZE them. Makes them easier to recognize.

How about another function? It may be a bit overkill here since the main function I wrote earlier already covers everything and the code only has one purpose, but code usually grows. Function-creep comes in and all of a sudden you have 300 lines of code in the same function. Better to split things up already, keeps things easier. Besides, it gives me an excuse to tell something about arguments.

def caesar_cipher(inp, shift):
    """
    Take inp(ut) as string, shift as integer and return ciphered string.
    """
    # code here

s wasn't a particularly descriptive variable name, so that's inp now (input is already taken.) Can you see this growing? While we're at variable names, having both a result and finalResult is somewhat confusing. The entire construct is somewhat confusing.

# Iterates through result and adds each string to the empty string, "finalResult".
for l in result:
    finalResult += l

You're really just copying result here, so finalResult can go. Well, almost. We still need to go to a string, so we're interested in ''.join(result). That takes an empty string, and joins all parts of the result list into it.

I don't like the while loop. There's 3 reasons for this and I'm going to fix 2 now and 1 later. Why? To keep things simple and easy to follow.

It starts out like this:

while found == False:

Did you know you can rewrite that to make it even more obvious what's going on?

while not found:

Which, if you're familiar with other languages, reads like while(!found). Python has the not operator, which returns True if the expression behind it is False.

The other end of the loop can be improved as well. You're printing the result of the cipher, while we may want to do something completely different with it. Perhaps the result should be used in a different function? That's not the cipher's problem. Let main figure that out. All in all, the code so far would look like this with the above taken into account:

# Imports the lowercase alphabet as a whole string.
from string import ascii_lowercase

LETTERS = list(ascii_lowercase)

def caesar_cipher(inp, shift):
    """
    Take inp(ut) as string, shift as integer and return ciphered string.
    """
    found = False
    strIndex = 0
    letterIndex = 0
    result = []

    while not found:
        # Checks if the string has been converted to the cipher.
        if len(result) == len(inp):
            found = True
        # Adds a space to the result variable if the string index is a space.
        elif inp[strIndex] == " ":
            result.append(" ")
            strIndex += 1
        # Checks if the string index is equal to the letter index.
        elif list(inp)[strIndex].lower() == LETTERS[letterIndex]:
            result.append(LETTERS[letterIndex - 1])
            strIndex += 1
        #
        else:
            if len(LETTERS) - 1 == letterIndex:
                letterIndex = 0
            else:
                letterIndex += 1

    return(''.join(result))

def main():
    print(caesar_cipher("abcde test bla bla bla", -1))

if __name__ == "__main__":
    main()

We haven't actually used shift yet, but we'll need it to fix another problem in your code: it's a very limited Caesar cipher. After all, a proper Caesar cipher takes a shift parameter. How far should the text be shifter? 1 character? 2? 13? We can make this go round and round and round. That's one of the good things about a Caesar cipher.

I'm still not a fan of the while loop here, so let's fix 2 things at a time. If our algorithm is correct, we can simply iterate over the input and know the output is correct at the end without keeping track of a found variable. And while we're at it, let's try to remove the other variables that are just to keep track as well.

You made a good start with importing ascii_lowercase, so let's build on that. Did you know string.ascii_lowercase (just like string.lowercase) has an index function? It provides us with the position of a character in a string.

What if we use that index to retrieve a different value of the alphabet instead? After all, an index is just a number. We could modify that number to get a different character altogether.

  For every character in the input, if the character is a letter, get a different letter from the alphabet instead.

Oh, we can use a for loop instead of a while loop!

# Imports the lowercase alphabet as a whole string.
from string import ascii_lowercase

LETTERS = list(ascii_lowercase)

def caesar_cipher(inp, shift):
    """
    Take inp(ut) as string, shift as integer and return ciphered string.
    """
    result = []

    for character in inp:
        if character in LETTERS:
            # If it's a letter, we cipher it
            result.append(LETTERS[ascii_lowercase.index(character) + shift])
        else:
            # If it's NOT a letter, we won't cipher it
            result.append(character)

    return(''.join(result))

def main():
    print(caesar_cipher("abcde test bla bla bla", -1))

if __name__ == "__main__":
    main()

See how much easier that is to read? Now we just need a minor modification to account for the limited length of the alphabet. After all, what happens if someone wants a shift of 40? Or 51? Please welcome the % modulo operator. Divide by the length of the alphabet (26) and return the remainder.

# Imports the lowercase alphabet as a whole string.
from string import ascii_lowercase

LETTERS = list(ascii_lowercase)

def caesar_cipher(inp, shift):
    """
    Take inp(ut) as string, shift as integer and return ciphered string.
    """
    result = []

    for character in inp:
        if character in LETTERS:
            # If it's a letter, we cipher it
            result.append(LETTERS[(
                ascii_lowercase.index(character) + shift
                ) % len(LETTERS)])
        else:
            # If it's NOT a letter, we won't cipher it
            result.append(character)

    return(''.join(result))

def main():
    print(caesar_cipher("abcde test bla bla bla", 51))

if __name__ == "__main__":
    main()

Now, compare this to the original version. Can you see how we got here? You started out right, and now we got something even better. And this can probably be improved even further, I'm fairly sure we don't need result to be a list in the first place. Have fun figuring that out :-)


Script to push data from one database via api to another

A few notes on your code above:

connect_mssqlserver and connect_mysqlserver could be condensed to a single 'connect' function that takes a conn_str arg to be used in create_engine.
I believe create_df seems to be unnecessary at this point. If the process for creating the df involves more than just calling read_sql in the future, then I would opt for moving that logic into a separate function.
nitpick: I would change source_df.empty == False and the following True check to just not source.empty and dest_df.empty


Sed script to update a version number in an RPM SPECS file

Variables don't interpolate inside single quotes.  You need double quotes.

No need to capture the old version that we're throwing away. The /g is redundant since the pattern can never match more than once per line (being anchored to start-of-line).

What happens with Version: 0.9a?  Version:1?  Version:?  Better to take the whole line, possibly excluding comments, and relax the space requirement.

sed -ri "s/^(Version:\s*)[^#]*/\1$version/" SPECS/*.spec

It's possible for the description or another section to contain the trigger text, and we probably don't want to change that.  Use sed's start,stop addressing to limit replacement to the top block only, stopping at the first %whatever header:

sed -ri "1,/^\s*%/s/^(Version:\s*)[^#]*/\1$version/" SPECS/*.spec


From this Stack Overflow question :

import random

foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))

In your case,

def get_one_random_domain(domains):
        return domains[random.randint( 0, len(domains)-1)]

becomes :

def get_one_random_domain(domains):
        return random.choice(domains)

and maybe removes the need for a function in the first place.

Your letters list can easily be defined with a list comprehension and some manipulation of ord and chr :

>>> [chr(ord('a')+i) for i in range(12)]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']

As suggested in the comments, you can also use string.ascii_lowercase[:12]

Now, your get_one_random_name could be easily improved.

def get_one_random_name(letters):
    email_name = ""
    for i in range(7):
        email_name = email_name + letters[random.randint(0,11)]
    return email_name

using the previous trick, it becomes :

def get_one_random_name(letters):
    email_name = ""
    for i in range(7):
        email_name = email_name + random.choice(letters)
    return email_name

Also, here is a recommandation from PEP 8 :

  For example, do not rely on CPython's efficient implementation of
  in-place string concatenation for statements in the form a += b or a =
  a + b. This optimization is fragile even in CPython (it only works for
  some types) and isn't present at all in implementations that don't use
  refcounting. In performance sensitive parts of the library, the
  ''.join() form should be used instead. This will ensure that
  concatenation occurs in linear time across various implementations.

In your case, you can easily build a list of random letters and call join.

def get_one_random_name(letters):
    return ''.join(random.choice(letters) for i in range(7))

In generate_random_emails :

you don't need conversions.
you don't need temporary variables
you don't need the first argument of range if it is 0.

so you get:

def generate_random_emails():
    for i in range(0,10):
         print(get_one_random_name(letters) + '@' + get_one_random_domain(domains))

Also, it might be a good idea to return a list instead of printing values to make code easier to reuse.

At this stage, the code looks like :

import random
domains = [ "hotmail.com", "gmail.com", "aol.com", "mail.com" , "mail.kz", "yahoo.com"]
letters = string.ascii_lowercase[:12]

def get_one_random_domain(domains):
    return random.choice(domains)

def get_one_random_name(letters):
    return ''.join(random.choice(letters) for i in range(7))

def generate_random_emails():
    return [get_one_random_name(letters) + '@' + get_one_random_domain(domains) for i in range(10)]

def main():
    print(generate_random_emails())

if __name__ == "__main__":
    main()

A good idea would be to change the function names and add arguments instead of hard coded values :

import random
domains = [ "hotmail.com", "gmail.com", "aol.com", "mail.com" , "mail.kz", "yahoo.com"]
letters = string.ascii_lowercase[:12]

def get_random_domain(domains):
    return random.choice(domains)

def get_random_name(letters, length):
    return ''.join(random.choice(letters) for i in range(length))

def generate_random_emails(nb, length):
    return [get_random_name(letters, length) + '@' + get_random_domain(domains) for i in range(nb)]

def main():
    print(generate_random_emails(10, 7))

if __name__ == "__main__":
    main()


This should do it:

SELECT U1.Unit, U1.[Date], U1.Mileage
FROM tbl_unit U1
WHERE U1.id IN (
    SELECT MAX(U2.id)
    FROM tbl_unit U2
    GROUP BY U2.Unit
);

This uses a simple subquery correlated on the tbl_Unit.Unit.  This approximates your GROUP BY and LAST() functions in Access by SELECTing the most recent row for each Unit.  LAST() in Access returns the most recently added record, and since the id field is an Autonumber (or IDENTITY() in SQL Server) field, MAX(id) will automatically return the most recent row for each unit.


First, Simplify the function to a pattern match form.

updateColorPickerState :: ColorPicker -> (GLfloat, GLfloat) -> Bool -> ColorPicker
updateColorPickerState c (x,y) mouseClicked =
  case isPointWithinColorPicker c (x, y) of
    True -> case mouseClicked of
      True -> case state c of
        Opened -> c {state = Idle, selectedColor = getColorAt (x',y')}
        _      -> c {state = Opened}
      False -> case state c of
        Opened -> c
        _      -> c {state = Hovered}
    False -> case state c of
      Opened -> case mouseClicked of
        True -> c {state = Idle}
        _    -> c
      _      -> c {state = Idle}
  where
    (posX, posY) = pos c
    (sizeX, sizeY) = openedSize c
    x' = truncate ((x - posX) * 25 / sizeX)
    y' = truncate (((-y) - posY) * 11 / sizeY)

Then, convert case-based pattern matches to function-based pattern matches.

updateColorPickerState :: ColorPicker -> (GLfloat, GLfloat) -> Bool -> ColorPicker
updateColorPickerState c (x,y) mouseClicked
    | isPointWithinColorPicker c (x, y) = mouseInside (state c) mouseClicked
    | otherwise                         = mouseOutside (state c) mouseClicked
  where
    -- mouse is inside bounding box
    mouseInside Opened True  = c {state = Idle, selectedColor = getColorAt (x',y')}
    mouseInside Opened False = c
    mouseInside _      True  = c {state = Opened}
    mouseInside _      False = c {state = Hovered}
    -- mouse is outside bounding box
    mouseOutside Opened False = c
    mouseOutside _      _     = c {state = Idle}
    (posX, posY) = pos c
    (sizeX, sizeY) = openedSize c
    x' = truncate ((x - posX) * 25 / sizeX)
    y' = truncate (((-y) - posY) * 11 / sizeY)


You are close to right on the complexity. You have two dimensions that are independent in your system though. The sort is sorting the letters in a word, and its performance is dependent on the length of the word, not the number of words.

You have essentially an outer loop which is linear \$O(n)\$ and an inner sort which is dependent on m, the number of letters in each word...., and those combine to create an overall complexity of \$O({n} \times {m}\log{m})\$

If you double the average size of each word, the execution time will slightly-more-than-double. If you double the number of words, the same will happen.

Now, how can it be improved?

your class is called anagram ? It should be capitalized to Anagram.
you should use the interface declaration not the implementation, where you can. For example, your HashMap should be HashMap<String, List<String>> instead of HashMap<String, ArrayList<String>> (note, use List instead of ArrayList).
The two lines:

ArrayList<String> anagramList = map.get(key);
anagramList.add(str);

could be simplified to:

map.get(key).add(str);

You iterate through the keys of the HashMap to get the value arrays, but you don't need to. Consider the following (which just iterates the values...):

for (List<String> anagramList : map.values()) {
    if (anagramList.size() > 1) {
        result.addAll(anagramList);
    }
}


Get collection in blade and check if empty

You don't need to check if your array is empty before using it in a foreach.

But if you need to check if it is empty (to show a message, for example), you can use the @empty tag.

I'd do something like this: (Check also @forelse):

  @forelse ($addresses as $address)

      {!! displayText($address->toString()) !!}

  @empty($addresses)

 No addresses...

  @endforelse


Extracting address information from non-formatted text

BUG
First you split by space and then you test if those chunks contain it. The answer will always be no. From the fact that you still test for it however, I guess that you actually expect them to be there, so some valid postal codes will not be detected.
Mistakes

You iterate one too many times,
In … || highlightdata[i].indexOf(' ') && … you probably forgot  == 1,
Due to precedence of && over || and lack of parentheses your logical statement works differently than you probably intended,

Remarks

Use of for…of would benefit readability and performance,

No need to define 4 array variables that will later end up in an object — create an object with 4 arrays right away and push there directly,

Use strict equality === operator — it performs no type conversion and you avoid potential pitfails,

Use const and let rather than var — they won't exist in the entire execution context and enable performance optimization,

highlightdata[i].indexOf('-') == 1 will at most go through the entire string — use highlightdata[i].charAt(1) === '-' instead,

!highlightdata[i].includes('-') is more idiomatic and concise than highlightdata[i].indexOf('-') !== -1,

No need to declare var i before the loop,

Naming convention: use camelCase,

2 space and line break after } are more popular formatting choices,

Be consistent with the kind of quotes you use.

Rewrite
Effectively it works like the original code. Therefore it is broken as well.
const checkAddress = serverPackage => {
  const info = {postal: [], streetNumber: [], streetType: [], potentialName: []};

  for (const token of serverPackage.split(' ')) {
    if(!isNaN(token)) {
      info.streetNumber.push(token);
    }
    else if (postalCheck.test(token)) {
      if (token.charAt(1) === '-' || token.length === 6) {
        info.postal.push(token);
      }
      else if (!token.includes('-') || token.length === 7) {
        info.postal.push(token);
      }
    }
    else if (streetTypeCheck.test(token)) {
      info.streetType.push(token);
    }
    else if (nameCheck.test(token)) {
      info.potentialName.push(token);
    }
  }

  return info;
};


Multicast Socket Configuration for Pub/Sub

Unfortunately, I'm unable to comment about the actual options you are setting since

while I've used Sockets in Java, I haven't used them in C#
I'm finding it a bit hard to see what your code is doing because it isn't very expressive

So, while I can do nothing about the first point (someone with more experience will have to help you out), we can certainly remedy the second problem by refactoring your code into a more readable form with less duplication.

Let's start by declaring a new member variable to keep hold of the parsed IP address:

private static IPAddress _ipAddress = IPAddress.Parse(_configuration.Server.AddressV4);

We'll use this field in the methods that result from splitting up your monolithic function into several helpers, leaving us with the following:

_broadcastSocket = CreateBroadcastSocket();
_broadcastListeningSocket = CreateBroadcastListeningSocket();
_broadcastSocket.Connect(GetEndpointOf(_ipAddress));
_broadcastListeningSocket.Bind(GetEndpointOf(IPAddress.Any));

Those methods are defined as the following:

private static Socket CreateBroadcastSocket()
{
    Socket s = CreateSocket(new MulticastOption(_ipAddress));
    s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, _configuration.Server.TimeToLive);
    return s;
}

private static Socket CreateBroadcastListeningSocket()
{
    return CreateSocket(new MulticastOption(_ipAddress, IPAddress.Any));
}

private static Socket CreateSocket(MulticastOption multicastOption)
{
    Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, false);
    s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
    s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, multicastOption);
    return s;
}

Note that it would have been possible to set the instance variables (_broadcastListeningSocketand _broadcastSocket) directly from the helper methods, instead of returning a new Socket, however I find the above implementation more expressive because we seperate the concerns: The helper methods know about how to create a configured Socket, while the method that calls them knows about what they have to be assigned to.

What to do if you find out you need to set the options differently?

Create a new CreateXXXSocket() method
From that method, call CreateSocket() and
configure the result and pass it back to the caller


Generate prime factorisations of factorial numbers

Given that you do y=factorial(n) inside your decomp(n) function, I'm gonna assume that this is really about factoring factorials. And my review is gonna be:

Don't compute the factorial at all.
Use a better function name.
Document what the function does.
Separate the factorization from the presentation. Return something more useful than a string, like pairs of primes and their exponents. That can then be pretty-formatted if desired, or used for computations.
Test your code, because for example for decomp(10) returns '2 * 3 * 5 * 7', missing the exponents.

Instead of computing the factorial and then factoring that, factor all the numbers from 1 to n and combine their prime factorizations. Or even better... compute, for every prime from 1 to n, its exponent in n!. Let's say we want to find the exponent for 3 in 100!. Every third number from 1 to 100 (i.e., 3, 6, 9, 12, etc) contributes a factor 3, so there are \$\lfloor\frac{100}{3}\rfloor=33\$ numbers that contribute factor 3. Of those, every third number (i.e., 9, 18, 27, etc) contributes another factor 3. Of those, every third number (i.e., 27, 54 and 81) contributes yet another. And 81 even contributes a fourth. So the exponent for 3 in 100! is 33+11+3+1=48.
Here's an O(n) solution doing that. Takes my laptop about 0.33 seconds to factor 1,000,000!. Compare that to just computing math.factorial(10**6), which already takes about 10 seconds.
def factorial_factorization(n):
    """Return the prime factorization of n! as list of (prime, exponent) pairs."""

    # Compute primes from 2 to n, see https://cp-algorithms.com/algebra/prime-sieve-linear.html
    lp = [None] * (n+1)
    primes = []
    for i in range(2, n+1):
        if not lp[i]:
            primes.append(i)
            lp[i] = i
        for p in primes:
            if p > lp[i] or i * p > n:
                break
            lp[i * p] = p

    # Find prime exponents for n!
    result = []
    for p in primes:
        e = 0
        m = n // p
        while m:
            e += m
            m //= p
        result.append((p, e))
    return result

Demo:
>>> factorial_factorization(3)
[(2, 1), (3, 1)]

>>> factorial_factorization(4)
[(2, 3), (3, 1)]

>>> factorial_factorization(100)
[(2, 97), (3, 48), (5, 24), (7, 16), (11, 9), (13, 7), (17, 5), (19, 5), (23, 4), (29, 3), (31, 3), (37, 2), (41, 2), (43, 2), (47, 2), (53, 1), (59, 1), (61, 1), (67, 1), (71, 1), (73, 1), (79, 1), (83, 1), (89, 1), (97, 1)]

>>> factorial_factorization(10**6)[:10]
[(2, 999993), (3, 499993), (5, 249998), (7, 166664), (11, 99998), (13, 83332), (17, 62497), (19, 55553), (23, 45453), (29, 35713)]

If you want a less useful but prettier presentation, that's easy to do then:
>>> n = 42
>>> print(f'{n}! =', ' * '.join(f'{p}^{e}' if e > 1 else f'{p}'
                                for p, e in factorial_factorization(n)))
42! = 2^39 * 3^19 * 5^9 * 7^6 * 11^3 * 13^3 * 17^2 * 19^2 * 23 * 29 * 31 * 37 * 41

Checking that:
>>> s = '2^39 * 3^19 * 5^9 * 7^6 * 11^3 * 13^3 * 17^2 * 19^2 * 23 * 29 * 31 * 37 * 41'
>>> (result := eval(s.replace('^', '**')))
1405006117752879898543142606244511569936384000000000

>>> (expect := math.factorial(42))
1405006117752879898543142606244511569936384000000000

>>> result == expect
True