First of all, there's a problem with the HTML approach you have:

That's risky (XSS most of the time)
Do you expect them to be web developers? I can be a gamer/reviewer with zero HTML knowledge.
We're writing a review, we should only write reviews, not HTML. Leave HTML to the developers.

Now, as you said, you can do JSON, and your other approach seems to be right:

Form

<form>

Advantages

  <button>Add</button> // get nextAll advantages, find the last and append after
  <input type="text" name="advantages[]" />
  <input type="text" name="advantages[]" />
  <input type="text" name="advantages[]" />

Disadvantages

  <button>Add</button> // get nextAll disadvantages, find the last and append after
  <input type="text" name="disadvantages[]" />
  <input type="text" name="disadvantages[]" />
  <input type="text" name="disadvantages[]" />
</form>

Data structure to server

{
  advantages : ['foo','bar','baz'],
  disadvantages : ['foo','bar','baz']
}


The performance might be improved if you used more efficient synchronization mechanism.  The @synchronized directive is notoriously inefficient. It's pretty convenient way of doing mutex lock, but there are more efficient alternatives.

A common pattern is to use dedicated GCD serial queue to synchronize access. Even better, one can use the the reader-writer pattern: It's a concurrent GCD queue where you dispatch_sync to read operations to enjoy concurrency on read operations, but use dispatch_barrier_async to write). See the discussion of this pattern in WWDC 2012 video Asynchronous Design Patterns with Blocks, GCD, and XPC (it's in the latter portion of the video).

A couple of other reactions to the provided code snippet:

If you use @synchronized, I wouldn't suggest using string constants like that. The typical convention is to use the object that is being mutated (thus make sure it is instantiated up-front, and then you can do @synchronized (self.dict)).
Note, the provided code is not thread-safe. It has several issues:

One cannot just synchronize the initial read and final write separately. You generally have to wrap the whole routine in some synchronization mechanism. (And obviously, make sure any reads outside of this method are synchronized, too.)
BTW, the current code that adds of the entries to the existing array isn't currently synchronized at all.

This is really unrelated, but I wouldn't suggest three separate arrays for the URL,  LR (?), and isdir. I'd personally rather see an array of objects (either custom object or NSDictionary for which each object has its own URL, LR, and isDir). There are other approaches, too, but having three separate arrays doesn't seem very appealing.
Also unrelated, but I'm surprised that if you call this method and the key/URL both exist, that you don't update the existing record. Right now, you leave the old values there.


Function that returns words in string not exceeding max number of characters

You code can end up falling out of the loop and implicitly returning undefined if there are no spaces within the first numberOfCharacters characters in the input string.  You might want to add an explicit return statement at the end of the function to handle that case.

Also, in your loop you only test for spaces, not for newlines, tabs or other whitespace characters.  You could simply add tests for those into your if statement, like this:

if (input[i] == ' ' || input[i] == '\t' || input[i] == '\r' || input[i] == '\n') {

but it would be shorter and cleaner to use either indexOf():

if (" \t\r\n".indexOf(input[i]) >= 0) {

or a regexp test:

if (/\s/.test(input[i])) {

You may also wish to ensure that input[i-1] is not a whitespace character.  You could do it like this:

const spaces = " \t\r\n";
for (var i = numberOfCharacters; i > 1; i--) {
    if (spaces.indexOf(input[i]) >= 0 && spaces.indexOf(input[i-1]) < 0) {
        return input.slice(0, i) + ' ...';
    }
}

or, using a regexp, like this:

for (var i = numberOfCharacters; i > 1; i--) {
    if (/\S\s/.test(input.slice(i-1, i+1))) {
        return input.slice(0, i) + ' ...';
    }
}

Also note that the output of your function may be up to 4 characters (the length of the " ..." suffix) longer than the specified length limit.  If that's not what you want, you may wish to change your for loop to:

for (var i = numberOfCharacters - 4; i > 1; i--) {


List.subList(low, high)

Is probably the easiest approach to take to the list management without requiring the copying of a lot of nodes.  It does make a lot of Lists though, which are very short lived.  This should be fine.  If you really needed to keep things under control, then you would replace the sublist implementation with one that uses Arrays.sort(a[], low, high, Comparator)

Reviewing the code as is:

root.leftChild = buildKDTree(left, !depth);
depth = !depth;
root.rightChild = buildKDTree(right, !depth);

This looks to me like a bug - I would expect each layer of the tree to be sorted in the same direction, so flipping the bit doesn't make sense.  Instead

root.leftChild = buildKDTree(left, !depth);
root.rightChild = buildKDTree(right, !depth);

I don't like using the boolean to control the direction of the insert -- the variable is answering a question about direction, not logical truth.  An enum would be a more readable fit

private enum SORT_DIRECTION {
    X_SORT, Y_SORT;
}

Alternatively, it might be clearer to track how deep you are in the tree, and choose the direction of the sort based on the depth.  In that case, depth would be an int, and you would use something like a modulus operation to choose which way you want the comparators to go.

Comparator<Node> order = Node.xComparator;

if(0 == (depth % 2){
    order = Node.yComparator;
    Collections.sort(list, Node.xComparator);
}
Arrays.sort(nodes, low, high, order);

Or better, explicitly spell out what you are doing

Comparator order = getOrderForDepth(Node, depth);
   Arrays.sort(nodes, low, high, order);

When dealing with recursion, my usual recommendation is to have a different function set up your pre conditions, and return the root.

Node buildKDTree(List list) {
       int depth = 0;
       return buildKDTree(list, depth);
   }

Finally, when implementing something recursively, make sure that you have a clear and obvious terminating condition (in other words, you need to handle the case where there are no more sub trees).  In this case, it's probably easiest to manage if the buildKDTree method handles an empty List.


InternedString as alternative to regular String

Assuming each time you receive a new query you create an instance of InternedString to get/add another item from/into the dictionary, the performance benefit seems questionable:

Impact of string.Intern

a) It needs to calculate a hash of the original string to make a lookup in the pool of strings

b) From official documentation -

  The memory allocated for interned String objects is not likely to be
  released until the common language runtime (CLR) terminates. The
  reason is that the CLR's reference to the interned String object can
  persist after your application, or even your application domain,
  terminates.

High rate of collisions seems to be the only beneficial scenario

The equality comparison that Dictionary does for items in the bucket is the case when you implementation might win when the bucket grows huge.

But do you really have that many collisions?

P.S.

Comparing strings you're not using String.ReferenceEquals to compare references of the interned strings, but rather == operator which for (sting vs string) leads to values comparison.


Merge two DataTables by adding corresponding entries

You are not testing for same size.

You don't use combinedDT34.  You are changing an input which is not a good practice.  I am not sure if dt3 will be passed by reference.

You are starting column on 1.

static DataTable CombineDT34(DataTable dt3, DataTable dt4)
{
    if(dt3.Rows.Count != dt4.Rows.Count)
        throw new ArgumentOutOfRangeException);
    //...

    for (var r3 = 0; r3 < dt3.Rows.Count; r3++)
    {
        for(var c3 = 0; c3 < dt3.Columns.Count; c3++)
        {
            dt3.Rows[r3][c3] = ( Convert.ToInt32(dt3.Rows[r3][c3]) +
                                 Convert.ToInt32(dt4.Rows[r3][c3]) );
        }
    }
    return dt3;
}


I guess foremost, I question the mutability of this class. Should one really be able to change the value of $binaries?

I very much question the optional "nullable" thing here.  First of all, name-wise this doesn't seem to make sense as typically when you think of something as "nullable" it means it is a variable, property, field, etc. that is allowed to be set to null.  You are not setting anything here, so the terminology seems weird.  Perhaps it should be called $returnFalseOnMissingValue or something that more directly ties it to the return behavior of the normalize() method.

I would however get rid of it, as it will become a source of fragility to calling code, as in some cases (including default case) your calling code would not be able to distinguish a false "hit" result from a false "miss" result.  Let the calling code deal with converting null to false if it needs to send false up the call stack.  Don't obfuscate the result right here in this class which is designed to own this determination.

Why use strcasecmp()?  This seems an odd choice vs. just casting $value to lowercase for direct comparison.
 i.e.

$value = strtolower($value);
if ($value === $truthy) return true;
if ($value === $falsey) return false;
return null;

I also don't understand the lookup mechanism and comparison mechanisms here.  It seems obscure upon first read to have key/value positioning determine how the string is mapped to true/false. I think I would be more explicit like:

protected $mappings = [
    'yes' => true,
    'no' => false,
    '1' => true,
    '0' => false,
    'on' => true,
    'off' => false;
    'enabled' => true,
    'disabled' => false
];

And have your comparison method simply do something like:

public function normalize($value) {
    $value = strtolower($value);
    if(!array_key_exists($value, $this->mappings) return null;
    return $this->mappings[$value];
}

If you truly need to keep the concept of true/value pairs for some reason not shown in this code, then perhaps a structure like:

protected $mappings = [
    'yes' => ['boolean' => true, 'inverse' => 'false'],
    'no' => ['boolean' => false, 'inverse' => 'true'],
    ...
];

This prevents you from having to iterate through the $binaries values every time you want to do a lookup like you are currently doing.  The name $binaries also seems odd here as that typically has a much different meaning when talking about writing code.

I would suggest that 'true' and 'false' should be strings in your default mapping of boolean values.

Does this class really need a concrete instantiation?

Consider adding some parameter validation anytime you have public methods.  Ideally this could be a combination of type hinting and/or variable inspection to make sure you are being passed a valid parameter.  What happens now you if your method is passed an integer, array, object, empty string, etc.?


Your "getters" should be const since they don't modify any data members.  This will also protect you against any accidental modifications in those functions.

unsigned int getLength() const { return length; }

The constructor can instead be an initializer list:

linked_list() : length(0), start(NULL) {}

Be aware of the issues regarding using namespace std.
If you have a C++11-compliant compiler, use nullptr instead of NULL.
Be aware that _tmain() and _TCHAR* are non-portable, so anyone using this code outside of Visual Studio will not be able to compile it.  In order to make this portable, change them to main() and char* respectively.
Since you're using std::pow(), you should include <cmath>.  Although <iostream> is already covering it, you should add this library anyway.
There's not really a need for getLength2().  You just need to increment or decrement length, depending on the list operation.  Your inline "getter" will, of course, return this updated length.

Regarding incrementing/decrementing, length += 1 and length -= 1 can respectively be length++ and length--.
The val argument for add() should be passed by const&, especially if it happens to be of a non-primitive type.
You should consider error-checking (empty list) in pop() if you'd still like it to return the popped value.  Otherwise, you can make it void and simply return if the list is already empty.
Instead of (*start).value, use the -> operator for readability: start->value.


Is a filter a good way to accomplish a dynamic class in angular?

Fun question, I think this is okay.

I would name klass -> class and I would consider building a map for the values:

var classMap = [
  { from : 3 , to : 5       , class : 'alert-success' },
  { from : 5 , to : 10      , class : 'alert-warning' },
  { from : 10, to : Infinity, class : 'alert-danger'  }
];


Discord.py Bot : Sends with the loverate between 2 persons

Never iterate over indices in python
In Python this pattern is generally not recommended:
for y in range(len(wordBanList)):
    if(Personne1 == wordBanList[y] or Personne2 == wordBanList[y]):
        printIt = 0

You almost never need to iterate over and access elements by their indices. Instead you should directly iterate over the elements of the iterable:
for word in wordBanList:
    if Personne1 == word or Personne2 == word:
        printIt = 0

Also notice that you do not need the parentheses around the or statement.
If you do need the index as well you can use built-in enumerate:
for index, word in enumerate(wordBanList):
    ...

Membership tests
As Harsha pointed out, sets are optimized for membership tests, so use them when possible. Doing so can also make your assignment of printIt way more concise:
wordBanList = {'@everyone', '@here', '<@&763489250162507809>', ...}
printIt = 0 if (Personne1 in wordBanList or Personne2 in wordBanList) else 1

Parantheses are also not required here, but might improve readability.

Naming convention
PEP 8:

Function names should be lowercase, with words separated by
underscores as necessary to improve readability.
Variable names follow the same convention as function names.

Variable and function names should follow snake_case.

debug == True
As a general rule of thumb, you should always use is with the built-in constants: True, False and None. It might also suffice to check debug for truthiness (if debug:). This however depends on the use case, since the expressions are not equivalent. The second one will fail for all falsey values, not just False (e.g. an empty string, an empty list). If you're interested, you can read more about Truthy and Falsy Values in Python.

String formatting
LoveRate = str(random.randrange(0, 100))

LoveRate (or better love_rate) should not be of type str, since you only need its str-represantation to print it. You can let Python handle formatting for you, by using f-strings. That way you never have to think about casting to str.
print("[DEBUG] !love : The love rate ("+LoveRate+"%) between "+Personne1+" and "+Personne2+" has been printed in channel ID "+str(ctx.channel.id))

becomes
print(f"[DEBUG] !love : The love rate ({LoveRate}%) between {Personne1} and {Personne2} has been printed in channel ID {ctx.channel.id}")

A few other small points:

Instead of wrapping the main code inside an if-else-block we can use ctx.message.channel.id == 763352957579690018 as an exit condition.
print_it is of type int, but basically acts as a variable of type bool. We can also eliminate that variable entirely, since we only use it once.
Line length should ideally not exceed 80 characters. You can use parantheses to conveniently concatenate strings across multiple lines, as described in this reddit tip. My IDE is set to hard wrap only at 100 characters, so that's the maximum length for the lines below.

@bot.command(name="love", aliases=["l"])
async def love(ctx, personne1, personne2):
    if ctx.message.channel.id == 763352957579690018:
        bot_channel = discord.utils.get(ctx.guild.channels, id=768194273970880533)
        message_bot = await ctx.send(f"Va faire cette commande dans {bot_channel.mention} "
                                     f"ou je te soulève <:rage:831149184895811614>")
        await asyncio.sleep(5)
        await ctx.message.delete()
        await message_bot.delete()
        return

    word_ban_list = {'@everyone', '@here', '<@&763489250162507809>', '<@&777564025432965121>',
                     '<@&822200827347075132>', '<@&763815680306184242>', '<@&764422266560839680<',
                     '<@&763815728972300338>', '<@&763815728972300338>', '<@&763815228323528725>',
                     '<@&763815784904261632>', '<@&764422166116171806>', '<@&764422057353936897>',
                     '<@&804807279043674143>', '<@&828664814678179861>', '<@&823562218095640646>',
                     '<@&823638574809219163>'}

    love_rate = str(random.randrange(0, 100))

    if personne1 in word_ban_list or personne2 in word_ban_list:
        await ctx.send("Tu t'es pris pour qui ?")
        if debug:
            print("[DEBUG] !love : Someone tried to use a banned word !")
    else:
        await ctx.send(f"L'amour entre **{personne1}** et **{personne2}** est de **{love_rate}%** "
                       f"<:flushed:830502924479758356>")
        if debug:
            print(f"[DEBUG] !love : The love rate ({love_rate}%) between {personne1} and"
                  f"{personne2} has been printed in channel ID {ctx.channel.id}")


Extension method to return a default value for any null value

Took a quick look at your code and a few things came to mind.

As Magus mentioned in the comments it seems odd that you have a generic extension method on the object class, which returns a dynamic type. You should (with a few modifications) be able to use the generic type instead:

public static T CreateDefaultIfNull<T>(this T item)

Since it rarely makes sense to check value types for null, you could also restrict it to reference types only.

public static T CreateDefaultIfNull<T>(this T item) where T : class

You will have to cast the result of CreateInstance before returning.

The name is bothering me. The default value for a reference type is null, so if I saw your method used somewhere I would wonder what exactly it returns. (I don't know of a better name though. This method could return all kinds of things.)

I would invert the first if statement. It would reduce some of the indentation and I think it looks cleaner:

if(item != null)
{
    return item;
}
...

I haven't worked much with the GetConstructors method, but in what order is the constructors returned? If there is no guarantee, can you be sure that the first constructor is the most appropriate?

I have often seen constructors that throw exceptions when given null. Is that the behavior you want?

EDIT: If you look here, you will see that there is no guarantee of the order and it is not recommended to depend on the order.

  The GetConstructors method does not return constructors in a particular order, such as declaration order. Your code must not depend on the order in which constructors are returned, because that order varies.

Also, as mentioned in the comments, you should probably look into the situation mentioned by Jesse in the comments.

  What will happen if the "first" constructor's parameter list has value types (such as int)..

It might/might not work as you expect in all situations. (I don't know what the defined behavior is)

You should be able to change

var paramNullList = new List<object>();
for(int i = 0; i < paramCount; i++)
{
    paramNullList.Add(null);
}
return Activator.CreateInstance(type, paramNullList.ToArray());

to

var nullParams = new object[paramCount]; //All elements null by default.
return Activator.CreateInstance(type, nullParams);

Finally, your method doesn't work if there is no public constructor. What should happen in that case? You can't select the first constructor if there are none, so First would throw an exception (InvalidOperationException if I remember correctly).


Good

Naming of parameters and methods follow the naming convention

Bad

not checking input parameter for constructor
not listening to previous answers ( pop() returning nothing )
not using braces {} for every if..else statement

Additional

int size should be final as it won't be changed.
Instead of display() you can override toString() as this is more common.
Instead of writing to System.out you should throw an exception.
give your variables some space to breathe. E.g top=top+1; would be more readable if written like so top = top + 1;


I don't notice any major issues with your code.

Use _name naming for private variables, since everything is global (and thus, accessible) by default in lua. You can use the normal variable name for getters and setters.
You can modify the getter (get_handSize) and setter (set_handSize) a little as functions in lua don't need the parameters:

function Player.new( startingHandSize )
    local self = setmetatable( {}, Player )
    self._handSize = startingHandSize
    return self
end
function Player:handSize( newHandSize )
    if not newHandSize then return self._handSize end
    self._handSize = newHandSize
end

You can now simply use player:handSize() or player:handSize(n) for getting and setting the private variable.
Since you are simply inserting new players to self.players table, you can iterate using ipairs to list them sequentially (depends on your game design).
You can save a little disk space by using the oop approach of defining functions instead of passing self every time.

That much was a basic approach to oop in lua. Now, extending the concept, you can use closures for proper private variables.

function Player.new( startingHandSize )
    local self = setmetatable( {}, Player )
    local h = (function()
        local _handSize = startingHandSize
        return function( self, newHandSize )
            if not newHandSize then return _handSize end
            _handSize = newHandSize
        end
    end)()
    self.handSize = h  -- self._handSize will always be nil
    return self
end

and in a similar fashion:

function Game.new()
    local self = setmetatable({}, Game)
    local c, a = (function()
        local _turn = 0
        return function( self )
            return _turn
        end, function( self )
            _turn = _turn + 1
        end
    end)()
    self.getTurnNumber, self.advanceTurn = c, a  -- self.currentTurn will always be nil
    return self
end


Overall - looks good and readable. Just a few comments.

I didn't quite get it but looks like you are relying on exception to be thrown to get a signal and download file - this is bad and expensive.
Is there a way to check if this is file and download instead of trying to treat it as directory - cwd - and catch exception.
Is this what you are trying to do?

In general it is bad to organize program workflow around exceptions - they are for exceptional situations - not for routine work.

Use os.path.join to concatenate paths - link
Use some constant like ROOT_PATH instead of hard-coding '/'
Use logging module for debug/error logging - this is industry standard
Don't swallow exceptions - log them, use extended except:

except Exception as e:
Minor - use "{0}{1}/{2}".format(host, current, file) instead of % notation as this is sometimes wonky and format is just better and industry standard.
Small comment - you are hard-coding logic on where to download files on local disk inside Ftp class which is working but not the best - just add optional parameter to be able to override root directory where to download data to.


Double click to edit and add new value to li

I wasn't sure how to answer this, so I went with what your code does...

Scope your variables.
Change your code to target all li instead of one element with the id li.
Use this when events are triggered to make sure you have the correct element.
Remove the added elements instead of hiding them.
Remember to call on using the smallest possible parent container. Possibly a <ul> or <ol>?
Use short circuiting where appropriate.
Use jQuery.parent() to get the appended elements parent.

Putting all those change together:

var oriVal;
$("#parentUL").on('dblclick', 'li', function () {
    oriVal = $(this).text();
    $(this).text("");
    $("<input type='text'>").appendTo(this).focus();
});
$("#parentUL").on('focusout', 'li > input', function () {
    var $this = $(this);
    $this.parent().text($this.val() || oriVal); // Use current or original val.
    $this.remove();                      // Don't just hide, remove the element.
});

Here's the JSFiddle.


Excel VBA: Set the background-color & border for a user-defined range of rows

Quick notes -

The inputbox can restrict the input by the type argument.

You can also just format it as a table and then unlist the table to keep it as a range -

Sub example()
    Dim targetTable As ListObject
    Dim targetRange As Range
    Set targetRange = Application.InputBox("Select Range", Type:=8)
    Set targetTable = ActiveSheet.ListObjects.Add(xlSrcRange, targetRange)
    targetTable.TableStyle = "TableStyleMedium16"
    targetTable.Unlist
End Sub

Now just make your own custom table style and you're good to go.

Also, integers are obsolete. According to msdn VBA silently converts all integers to long.


Determine whether any permutation of a string is a palindrome

This is similar to a previous question of yours, Find the elements that appear only once, and the same advice applies: use a Set and maintain a flag instead of a count.  If your Set ends up with size of zero or one, it's a palindrome.  Otherwise no.

const isPalindrome = s => s.split("").reduce(
    (once, x) => (once.delete(x) || once.add(x), once),
    new Set()
  ).size <= 1

If inputs are constrained to 26 letters, you can map each letter to a unique power of 2 and replace the set with a bit vector (aka an "integer"), using XOR to track which bits appear an odd number of times.  This may or may not be faster than a Set but it will certainly use less memory.  I'll leave the implementation as an exercise for the reader.


Asynchronously loading a point in chart on drag

You don't follow capitalization conventions: ChartLastPoint, LastShownPoint, PMActualMinimumY, PMActualMaximumY, StartTime, EndTime, LoadedPoints should all be camelCase.

I suspect Lock must be camelCase as well, since I doubt it is a public property.

Use proper variable names, not temp or temp1. Same problem with param: it doesn't tell me anything, only through the code I know it's some kind of ID.

Your code suffers from the Arrow anti-pattern. You can easily reduce some of the nesting by returning earlier:

private void UpdateHistoryAndReSizeWhenDrag(string param, long duration)
{
    lock (Lock)
    {
        if (Boxes.Count() < 1)
        {
            return;
        }

        BoxStruct temp = Boxes.Where(key => key.id == param).FirstOrDefault();
        if (temp == null)
        {
            return;
        }

        int index = Boxes.IndexOf(Boxes.Where(key => key.id == param).First());
        if (index < 0)
        {
            return;
        }

        /* rest of your code */
    }
}

I don't know what Boxes is, but I suspect an ICollection<T> or an IList<T> of sorts, so why then use Boxes.Count() when you can use Boxes.Count (as you do later on in your code)?

I don't see why you're using Boxes[index], since the temp contains the BoxStruct you need to work with. Later on again you do Boxes.Where(k => k.id == param).First() twice, even though you could simply use temp.

I also don't see the point of this check: if (Boxes.Count > 0 & index < Boxes.Count): the second part is always true, and the first part you checked right at the start of your code: if (Boxes.Count() > 0).

I find it a bit odd that you carefully check that Boxes contains a value you can work with, but then never check if that object's Series isn't null, and if Series's Points isn't null etc. Also, you don't do anything if you can't find an appropriate BoxStruct -- shouldn't you inform the user?

I see the magic number 10800 appear twice. This should be stored in a constant and have a descriptive name.

Why do you retrieve the same value twice, yet store it in different variables?

    double LastShownPoint = (from x in Boxes where x.id == param select x.PlotModel.Axes[0].ActualMinimum).Min();
    double PMActualMinimumY = (from x in Boxes where x.id == param select x.PlotModel.Axes[0].ActualMinimum).Min();

Moreover, since you need to use the result of from x in Boxes where x.id == param select x.PlotModel.Axes[0] three times, store it in a variable and use that variable.

PMActualMinimumY and PMActualMaximumY both end in Y, yet you compare them to a value named X.

I'm a bit worried to see a method named LoadPointsRange which seemingly returns some kind of object, from which you then take its property Points.


Many CRUD operations for a list of technicians' shifts

For what I see, it should suffice - in order to increase time performance of the cycle - to transform the branches, technicians, and mwmAbsenceList into dictionaries with the respective ids as keys. In this way the following lines:

        var mwmAbsence = mwmAbsenceList == null ? null : mwmAbsenceList.FirstOrDefault(it => it.AGIErpId == absence.AGIErpId);
        AGIBranchModel branch = branches.FirstOrDefault(b => b.ERPId == absence.BranchCode);
        AGITechnicianModel tech = technicians.FirstOrDefault(t => t.ERPId == absence.TechCode);

can be executed in \$O(1)\$ time instead of the current \$O(n)\$. The resulting code after the change should be something in the lines of:

        Absence mwmAbsence = null;
        if(mwmAbsenceList != null)
        {
            mwmAbsenceList.TryGetValue(absence.AGIErpId, out mwmAbsence);
        }
        AGIBranchModel branch;
        branches.TryGetValue(absence.BranchCode, out branch);
        AGITechnicianModel tech;
        technicians.TryGetValue(absence.TechCode, out tech);

Another optimization I would suggest is to try and change the method into a set operation (try to get all items via a LINQ query). Just keep in mind that doing it in this way passes the burden to the database.

As for a review of the code I'd suggest three things:

Reduce the space between the lines of code. Right now is a bit too much.
Reduce indentation.
Reduce width.

The end result - after applying the changes in the first solution and the changes for these 3 points - should be something like the following:

public void ProcessShifts(IList<NavTechAbsenceDto> navShifts)
{
    var branches = _iagiBranchModelFactory.GetAll()
        .ToDictionary(/* insert key and value expressions here */);
    var technicians = _iagiTechnicianModelFactory.GetAll()
        .Where(it => it.IsActive)
        .ToDictionary(/* insert key and value expressions here */);
    var activeTechCodes = technicians.Select(t => t.ERPId).ToList();
    var absencesForActiveTech = navShifts
        .Where(a => activeTechCodes.Contains(a.TechCode)).ToList();
    var absences = _iagiTechnicianModelFactory.GetAllWithAbsences()
        .SelectMany(it => it.Absences);
    Dictionary</*TKey*/, /*TVal*/> mwmAbsenceList = absences == null
        ? null
        : absences.Where(a => a.Start >= DateTime.Today)
                  .ToDictionary(/* Insert key and value expressions here */);

    foreach (NavTechAbsenceDto absence in absencesForActiveTech)
    {
        Absence mwmAbsence = null;
        if(mwmAbsenceList != null)
        {
            mwmAbsenceList.TryGetValue(absence.AGIErpId, out mwmAbsence);
        }

        AGIBranchModel branch;
        branches.TryGetValue(absence.BranchCode, out branch);
        AGITechnicianModel tech;
        technicians.TryGetValue(absence.TechCode, out tech);

        if (branch == null || tech == null)
        {
            Logger.Trace("NOT AVAILABLE: Shift Branch: {0}, Shift Technician: {1}",
                absence.BranchCode,
                absence.TechCode);
            continue;
        }

        if (mwmAbsence == null)
        {
            if (absence.AGILogicallyDeleted == 1)
            {
                // is string.Format() necessary?
                Logger.Trace(string.Format(
                    "DELETED absence:{0} from Navision, but it does not exist in Scheduler",
                    absence.AGIErpId));
            }
            else
            {
                Logger.Trace(string.Format("ADD absence:{0}", absence.AGIErpId));
                tech.AddAbsence(absence, branch);
            }

            continue;
        }

        if (absence.AGILogicallyDeleted == 1)
        {
            Logger.Trace(string.Format("DELETE absence:{0}", absence.AGIErpId));
            tech.DeleteAbsence(mwmAbsence);
        }
        else
        {
            Logger.Trace(string.Format("UPDATE absence:{0}",
                absence.AGIErpId));

            mwmAbsence.Start = absence.Start;
            mwmAbsence.End = absence.End;
            mwmAbsence.AGIBranchId = branch.Id;
            mwmAbsence.TechnicianId = tech.Id;
            mwmAbsence.Technician = tech;
            mwmAbsence.AGIType = absence.AGIType;
            mwmAbsence.AGIMobile = absence.AGIMobile;
            mwmAbsence.AGIErpId = absence.AGIErpId;

            tech.UpdateAbsence(mwmAbsence);
        }
    }
}

Let me know if anything's unclear.


Pandas Groupby operation on a large dataset

Consider the following points:

Pandas has a good datetime functionality; you shouldn't cast into strings and then later on group by those. It's unnatural and slow. Instead, just do:

isd['YYYYMM'] = pd.to_datetime(isd['YYYYMMDDHH'],format='%Y%m%d%H')

And then in the groupby, you can simply do

stn_month = isd.groupby(['STATION', isd['YYYYMM'].dt.to_period('M')]) ...

In general, using apply is usually not great for performance. First, notice that you are doing a lot of things inside Nstat that are not necessary: all the lines like d['NDU6']  = (df.loc[ df['RH']<=90,'MW']==6 ).sum() are unnecessary in a sense that you can just precompute this outside of the function. As a side note, the way that you write is unnatural to me and I would more simply do:

df[(df['RH'] <= 90) & (df['MW'] == 6)]

Second, the agg function also takes a dictionary so that you can just do:

isd.groupby(['STATION', isd['YYYYMM'].dt.to_period('M')]).agg({'MW' : 'count', 'PW' : 'count', 'Vi': 'mean'})

I hope this will get you started.


Encapsulation

An object's behaviour should be with the object. This means that the UFO should control how it flashes (or blinks):

public class UFO ...
  public void blink() {
    setVisible(false);
    pause(200);
    setVisible(true);
    pause(200);
  }

  /** You will have to implement and test this method. */
  private void pause( int milliseconds ) {
    Thread.sleep( milliseconds);
  }
}

Information Hiding

The following code exposes the internals of how a UFO is piloted:

ufos[i].alien.setColor(rgen.nextColor());

Rather, this should be exposed as an accessor:

ufos[i].setPilotColor(rgen.nextColor());

Similarly, exposing the UFO's location is not necessary to determine the winner:

if(ufos[i].getX() > WINDOWX){
  winner = i;
  flag = false;
}

Rather, the above code is more clearly stated as:

if(ufos[i].crossedFinishLine( WINDOWX ) ){
  winner = i;
  flag = false;
}

Only the UFO need know if it has crossed the finish line. The code is now self-documenting.

Make the following attributes private:

public GOval body, bubble, alien;

Otherwise your code will be susceptible to race conditions (no pun intended) and be difficult to debug. This is because the UFO class has no control over when its data changes.

While True

In my opinion, while( true ) is poor form. Instead, add a condition that allows the loop to exit:

    while( gameOver() ) {
        ufos[winner].blink();
    }


Generating the maximum number possible from an array

Your algorithm is good, but the implementation is a bit wasteful:

In IntOrdering.compare, x and y are converted to String twice, and then converted to Int

It's especially bad since the numbers in the sequence may pass through compare multiple times in different pairs, and get converted to String even more times

You could reduce the casts:

Convert all numbers to String once in the beginning
Compare as strings. The algorithm will work with alphabetical comparison too
Convert to Long once at the end

Creating a custom Ordering seems a bit overkill

This one-liner will do the job:

nums.map(_.toString).sortWith(
  (a, b) => (a concat b).compareTo(b concat a) > 0).mkString.toLong


multiple instances of maps and markers using object oriented javascript

The problem I see on your code is that you try to be OO but still thinking in a procedural way.

for example, your code is full procedural, as you didn't design your class, instead you just wrote the code in the sequence it will be executed.

So far it is not so bad written for a procedural one.

Let's go on to explain the points.

What is the purpose to wrap a google map inside a function that contains only an attribute that is the map?

How do you use it:

maps_1 = new google_map('maps_1',{"lat" : 32.93,"lng" : 85.06},12);
maps_2 = new google_map('maps_2',{"lat" : 70.88,"lng" : 45.97},12);
maps_3 = new google_map('maps_3',{"lat" : 60.49,"lng" : 38.00},12);
maps_4 = new google_map('maps_4',{"lat" : 85.85,"lng" : 89.63},12);

So why you just don't directly create the google map instead?

What mean thinking in a object orientation way. you should first think about the object you use.

In your case you have a Map, that have reference to a DOM element, a configuration, and a list of markers.

// Please provide meaningful names for parameter
var Map = function (elementId, mapConf) {
    this.markers = []; //  Will use later
    this.elementId = elementId;
    var domElement = document.getElementById(this.elementId);
    this.map = new google.maps.Map(domElement, {
        zoom : parseInt(mapConf.zoom),
        center : mapConf.center,
        mapnameId : google.maps.MapnameId.ROADMAP,
        disableDefaultUI : true,
        styles : {
            featurename : "poi",
            elementname : "labels",
            stylers : [{
                    visibility : "off"
                }
            ]
        }
    });
};

// Now you need some methods
Map.prototype.addMarkers = function(markers) {
    markers.forEach(function (marker) {
        this.markers.push(new Marker(marker, this.map, infoWindow));
    }.bind(this));
};

Now you need a Marker class:

var Maker = function (markerConf, map, clickHandler) {
    var icon_url =  'icons/' + markerConf.dname + '_' + ((markerConf.dname2 === 0) ? '0.png' : '1.png');
    var lat = parseFloat(marketConf.lat), lng = parseFloat(marketConf.lng);

    if(lat*lng > 0) {
        this.marker = new google.maps.Marker({
            icon : icon_url,
            position: {"lat":lat,"lng":lng},
            description : ''+x.name+'
'+x.desc,
            title: marketConf.dname,
            start: marketConf.start,
            map: map
        });

        // You should handle this by your class (the Marker)
        // or by configuration, like shown here
        // so it's flexible
        if (clickHandler) {
            this.marker.addListener('click', clickHandler);
        }
    }
};

So your init function will be:

function init() {
    maps_1 = new Map('maps_1',{"lat" : 32.93,"lng" : 85.06},12);
    maps_2 = new Map('maps_2',{"lat" : 70.88,"lng" : 45.97},12);
    maps_3 = new Map('maps_3',{"lat" : 60.49,"lng" : 38.00},12);
    maps_4 = new Map('maps_4',{"lat" : 85.85,"lng" : 89.63},12);

    performPostAjaxRequest("ajax.php", function (data) {
        maps_1.addMarkers(data);
        maps_2.addMarkers(data);
        maps_3.addMarkers(data);
        maps_4.addMarkers(data);
    });
}

And loadJson will change to be more general purpose:

function performPostAjaxRequest(url, cb) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST", url, true);
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlhttp.send(data);

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4) {
            cb(JSON.parse(xmlhttp.response));
        }
    }
}

This is just a first step, a lot more could be done, the purpose of OO is to design the objects you need as classes, and put all the logic that is connected with those objects inside the class.
You should not have a function that know how to attach a Marker object to a Map object. Instead, the Map object should know how to do that. You just need to know that Maps need Markers.
When you define a class it's important to start the name with a capital letter, to distinguish a class constructor from a normal function.


Going from Spaghetti PHP OOP to SOLID OOP

Reading through this code and your goals, it seems this class has two responsibilities:

Provide a Key-Value store
Get data from the database (potentially with caching)

To make it more SOLID, you can pick one of these responsibilities for this class and put the other one somewhere else.

If you wanted to use this class to provide a KV store, you would inject an array pre-filled with all of the data into the constructor rather than injecting DB information. You could then use a factory that takes those parameters to build the DataID object with the data. This removes a dependency on anything database related, simplifies your constructor, and reduces the class to a thin veneer over the underlying array. It cannot, however, get new information by itself, nor can it provide database caching. You could create an adapter class around the database result set and inject that instead of the array. The result set adapter could then handle getting additional information and caching, but this might end up replicating the concerns you have here, just somewhere else.

If you wanted to use this class as an adapter over the StorageInterface class, you would not do all the work in the constructor and simply make calls to the underlying storage object in the getID method. This allows you to simplify the constructor once again, but does not in itself provide caching. You said the StorageInterface implementation provides query-level caching, but you can create a separate adapter wrapper around it that encapsulates your SQL and caches a whole table whenever one element is retrieved from it, and can limit those caches based on table size. Once again you can use a factory method so that your external application does not need to know about this internal adapter. This option seems to fit most closely with what you want to achieve while still having better SOLID-ness.

EDIT:

Here's how this achieves better adherence to the SOLID principles:

S: This class's responsibilities have been reduced from two to one.
O: I can add additional functionality by adding decorators and adapters around the various objects to add additional functionality, without having to change those objects directly.
L: StorageInterface uses Liskov Substitution, but an adapted class around the StorageInterface can also follow Liskov Substitution by adding decorators around it to add functionality.
I: The adapters are small, client-focused APIs.
D: StorageInterface is an abstraction, and your StorageInterface adapters/decorators can also be build as abstractions.

Bonus Points:

By removing the work out of the constructor, you are adhering more closely to the Law of Demeter. Rather than asking for something to get something through it, you are asking for what you really want.


Optimising sum of 2 from an array - leetcode challenge

Style
Your code is pretty readable already. But you mix var and let. I prefer consistent style.
Also, you use a function expression instead of a function declaration - there are subtle differences, but it's mostly a matter of personal preference. To me, the function declaration seems simpler.
Runtime complexity
Your main issue is performing full array searches via checkedNums.includes (in linear time) within the inner loop. By using an alternative data structure such as a simple object {}, a Set or a Map which complete such lookups much faster (in constant time), your performance will improve drastically for large inputs.
You can also get rid of the final nums.indexOf by mapping numbers to their indices. This doesn't improve theoretical runtime complexity, but still improves performance. The same holds for breaking out of the loop early as soon as a solution is found.
Implementation

// Return indices of first two number summing up to target:
function twoSums(numbers, target) {
  const map = new Map();
  for (let i = 0; i < numbers.length; ++i) {
   if (map.has(target - numbers[i])) {
      return [map.get(target - numbers[i]), i];
    } else {
      map.set(numbers[i], i);
    }
  }
}

// Example:
console.log(twoSums([-3, 0, 3, 2, 4, 0], 0)); // [0, 2]

Benchmark
Measuring average runtime over 1000 runs for input arrays of different length, we get the following results:
length  original [ms]  improved [ms]
   100            2.4            7.2
   500           32.8           37.6
  1000          120.6           71.2
  5000         2703.4          401.2
 10000        11132.5          792.5
 50000       265770.5         3633.5
100000      1052582.0         7776.5

While the original implementation performs better for very small inputs, the improved implementation performs much better for longer arrays. This confirms our above runtime complexity analysis.
Plotting the times against the input length clearly shows the quadratic nature of the original runtime complexity vs. the linear runtime complexity of the improved implementation:


Optimization of a Qt QByteArray conversion

Try to avoid deep copying of source array, this can be achived with right method:

QByteArray restoreData(const QByteArray &data, char prepender = 'x')
{
    return QByteArray::fromHex(data.right(data.size() - data.indexOf(prepender) - 1);
}


Script to clean up old files that should only run one instance

General impressions - nice neat code, well commented.  It's good that you use trap to clean up on exit.

Shellcheck picks up a couple of oversights:

206596.sh:11:11: note: Check exit code directly with e.g. 'if mycmd;', not indirectly with $?. [SC2181]
206596.sh:22:1: warning: Use 'cd ... || exit' or 'cd ... || return' in case cd fails. [SC2164]
206596.sh:27:5: note: read without -r will mangle backslashes. [SC2162]
206596.sh:44:1: warning: Use 'find .. -print0 | xargs -0 ..' or 'find .. -exec .. +' to allow non-alphanumeric filenames. [SC2011]

Let's do a walk-through:

#!/bin/bash

Why bash?  I don't think there's anything here that can't be achieved with standard POSIX shell.
NUM_PROCS=4

What's special about 4?  If it's the number of cores you have available, then we could automate that:

NUM_PROCS=$(getconf _NPROCESSORS_ONLN)

PIDFILE="/tmp/cleanup.pid"

I'm not sure about CentOS, but on the platforms I'm more familiar with, pidfiles normally live under /run (or /var/run on older installations).
PID_NOW="$$"

Never modified; I think it's clearer to simply use $$ where it's needed.
echo "$1" > "$PIDFILE"

if [[ "$?" -ne 0 ]]; then

Instead of testing $?, we should use the result directly (and since we never call this with anything other than our own pid, let's just embed that in the function rather than passing as argument).  Give the function a POSIX-compliant name, and declare it without the deprecated function keyword:

save_pid() {
    if ! echo $$ >"$PIDFILE"
    then
        # If we couldn't save the PID to the lockfile...
        echo >&2 "Failed to create PID file for PID $$ in $PIDFILE; exiting"
        exit 1
    fi
}

Note that the message is printed to standard error (stream 2) rather than standard output.
cd /scratch

There's no checking that this command succeeded.  We could append || exit 1 or similar, but we can catch more errors by setting shell flags -e and -u at the beginning of the script.

There's really no need to change working directory at all; we could just omit this command, and use the directory name where we need it.
if [[ -f "$PIDFILE" ]]

The comment says we're testing for existence, so we should be using -e (or change the comment).  And we can use the standard [ command; there's nothing to be gained from Bash-specific [[.
    read PID_SAVED < "$PIDFILE"

Shellcheck complains about using read without -r option.  Whilst we don't expect to see shell escapes in this file, there's no harm in pacifying the warning.  Or, we could just interpolate the file directly:

if ps --quick-pid "$(cat $PIDFILE)" &> /dev/null

Or just test for the existence in procfs:

if [ -e "/proc/$(cat $PIDFILE)" ]

We could add further tests to ensure that we don't have a re-used pid that's running a different program, but I won't pursue that here.
This structure can be simplified:

if a
then
    if b
    then exit 1
    else do-c
    fi
else do-c
fi

It's exactly equivalent to

if a && b
then exit 1
fi
do-c

That simplification gives us:

if [ -e "$PIDFILE" ] && [ -e "/proc/$(cat $PIDFILE)" ]
then
    # A process exists with our saved PID
    echo >&2 "Cleanup script is already running with PID $PID_SAVED; exiting"
    exit 1
fi

save_pid

trap clean-up HUP INT QUIT ILL ABRT BUS SEGV PIPE TERM ERR

Instead of listing all these signals, we just want to clean up however the shell exits:

trap clean_up EXIT

ls | xargs -P "$NUM_PROCS" -I{} \

It's dangerous to pipe the output of ls like that.  Files not under your control can contain almost anything, including newlines and other significant space.  I don't think we really want to ignore dot-files, either.  I recommend find -maxdepth 1 -mindepth 1, which can then write safely to xargs using --print0.  We might want to eliminate symlinks from the listing, although we know that the inner find won't follow them without -H or -L.
save_pid and clean_up are only used once each now, so could be usefully inlined.

Modified code

#!/bin/sh

set -eu

LIMIT_TIME=30 # days
NUM_PROCS=$(getconf _NPROCESSORS_ONLN)
PIDFILE="/var/run/cleanup.pid"

# check pidfile
if [ -e "$PIDFILE" ] && [ -e "/proc/$(cat $PIDFILE)" ]
then
    # A process exists with our saved PID
    echo >&2 "Cleanup script is already running with PID $PID_SAVED; exiting"
    exit 1
fi

# write pidfile
    if ! echo $$ >"$PIDFILE"
then
    # If we couldn't save the PID to the lockfile...
    echo >&2 "Failed to create PID file for PID $$ in $PIDFILE; exiting"
        exit 1
    fi

trap 'rm "$PIDFILE"' EXIT

# Now start working
find /scratch -maxdepth 1 -mindepth 1 \! -type l --print0 \
     | xargs -0 -P "$NUM_PROCS" -I{} \
             find {} -xdev -type f -mtime "+$LIMIT_TIME" -delete

After all that, consider that you might be reinventing a wheel.  Most likely, you have a tmpreaper package available that can be configured to do exactly this task.


As Flambino points out, the method is very problematic for negative integers.

You need to either change the function to only accept unsigned integers or come up with some solution that makes sense for negative numbers.

In general though, I don't particularly like operator-overloading.  Using functions/methods means there's some plain-English name to the operation you're performing that will give me some sort of hint at what the operation does so I don't have to guess.

As someone coming from an Objective-C/Foundation background (which will likely be most Swift programmers) and having zero Ruby experience, I could maybe guess at what the first one does:

println("Andrew rules! " * 42)

But as for the second one?

println("Andrew rules! " ** 42)

I'd have absolutely no clue.  And I doubt I'd be the only one.

The amount of time you save typing ** instead of a more descriptive function name (which the IDE will autocomplete for you meaning the amount of time is basically the same either way) is definitely not worth the amount of time that other programmers behind you take to go figure out what this does:

let myVar = "Hello world!" ** 27

There's not even the slightest hint as to what this returns, and there's no descriptive function name to give any clues... so now I have to go hunt down where ever you've put the operator overload function for a string/int.


Naive approach: use StringUtils.repeat (source) without the ThreadLocal:

public static String repeat(final char ch, final int repeat) {
    final char[] buf = new char[repeat];
    for (int i = repeat - 1; i >= 0; i--) {
        buf[i] = ch;
    }
    return new String(buf);
}

Anyway, I suppose you did some profiling and it turned out that this is a bottleneck. Otherwise I'd really not complicate it with the ThreadLocal nor the doubling/concatenation logic.
substring in Java 6 used the same character array as the original String instance but it was changed in Java 7. So, substring calls copies the character array anyway, therefore string doubling and calling substring does not seem beneficial to me. (Anyway, it should be measured.)

There is one exception (according to the source which Eclipse brings up for Java 8) when beginIndex is zero and endIndex is the length of the original string. In this case substring returns the same String instance without copying. This case seems unlikely here, I guess there's a little chance that PAD_BASE.lenght will be the same as the length parameter since the while loop doubles the size of the padding string on every iteration.

So, in an average case the naive approach would create less new String (and underlying char[]) objects here than the one with substring.
Another idea is storing an array of strings in the ThreadLocal and extending the array on demand if the required lenght is longer than paddings.lenght:

String paddings[] = new String[max];
for (int i = 0; i < max; i++) {
    paddings[i] = StringUtils.repeat('.', i);
}

2 could be a named constant.


PS1 for Bash prompt showing last exit status, written mostly in Python

The typo

If we look at the beginning and the of the posted code:

PS1="\$(export LAST_RETURN_VALUE="\$?" WHOAMI="\$\(whoami\)" HOSTNAME ; python -c \"
from __future__ import print_function
... more python code
\" "

The end part is incorrect.
The \" closes the python -c \",
and the final " closes the PS1=",
but a ) is missing to close the \$(export.
(Pro tip: if you edit the script in vim, and press % on an opening (, it shows where's the closer, or emits an error beep if missing.)

I guess the last line was meant to be:

\")"

An easier way to escape stuff

Escaping things correctly within "..." can be quite painful in very long strings as in this example.
In this particular example there's easy alternative using literal here documents:

PS1=$(cat << "EOF"
...
EOF
)

All the code you previously had within the "..." could go there in place of the ..., and it will be taken literally as if enclosed within single-quotes, but no need to escape ", or ' or $.

PS1=$(cat << "EOF"
$(export LAST_RETURN_VALUE="$?" WHOAMI="$(whoami)" HOSTNAME ; python -c "
from __future__ import print_function
import os
import datetime

ESC = '\033[{0}m'
esc = ESC.format

OFF, BOLD, UNDERSCORE, BLINK = 0, 1, 4, 5
BLACK, BLACKBG = 30, 40
RED, REDBG = 31, 41
GREEN, GREENBG = 32, 42
YELLOW, YELLOWBG = 33, 43
BLUE, BLUEBG = 34, 44
MAGENTA, MAGENTABG = 35, 45
CYAN, CYANBG = 36, 46
WHITE, WHITEBG = 37, 47

LAST_RET = os.environ['LAST_RETURN_VALUE']

print(esc(YELLOW) + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
      esc(GREEN) + os.environ['WHOAMI'] + esc(RED) + '@' +
      esc(CYAN) + os.environ['HOSTNAME'],
      esc(BLUE) + esc(BOLD) + os.getcwd())
if LAST_RET != '0':
    print(esc(OFF) + esc(MAGENTABG) + LAST_RET + esc(OFF), end='')
print(esc(OFF) + '$ ', end='')
"
)
EOF
)

Safety

If PROMPT_COMMAND is set, PS1 will be ignored.
To avoid confusion, I would add unset PROMPT_COMMAND.

What's wrong with doing this in Python?

It's an additional dependency to worry about.
If your friend asks you how to do that cool prompt,
it gets less cool when you explain how he needs Python to get it.
And running a Python script for every single command is a bit of a waste.

Why not do it in Bash?

The script basically sets variables, formats the date and prints stuff.
That's easy enough to do in Bash.
The script gets all its critical elements from Bash.
It uses the Bash variable $? to get the exit code of the last command,
the whoami command to get the current user,
and the HOSTNAME variable that's already defined in the environment.

In other words,
you already know everything it takes to make this work in Bash,
and Python doesn't bring real benefits,
the only thing left to do is to translate it to Bash.

This is pretty much a word-for-word translation of Python to Bash,
with some minor improvements, such as \u instead of calling whoami,
and unused variables dropped.
I don't see the readability suffering significantly compared to the Python solution.

PS1=$(cat << "EOF"
$(
LAST_RET=$?
WHOAMI='\u'
HOSTNAME='\h'
DATE=$(date +'%Y-%m-%d %H:%M:%S')

OFF='\033[0m'
BOLD='\033[1m'
RED='\033[31m'
GREEN='\033[32m'
YELLOW='\033[33m'
BLUE='\033[34m'
MAGENTABG='\033[45m'
CYAN='\033[36m'

echo "$YELLOW$DATE $GREEN$WHOAMI$RED@$CYAN$HOSTNAME $BLUE$BOLD$PWD"
test $LAST_RET = 0 || printf "$OFF$MAGENTABG$LAST_RET$OFF"
printf "$OFF\$ "
)
EOF
)


Avoiding a call to CommandBarControl.Picture

SetButtonImage is called for every single CommandMenuItem in Rubberduck, regardless of whether or not Picture and Mask are overridden.

Whether a CommandBarButton has a Picture property depends on the [version of the] host application, and the bool result of HasPictureProperty will be the same for every single CommandMenuItem being initialized: if a RuntimeBinderException is thrown with the first button, it will be thrown and logged for every single button - this is a massive performance hit: throwing and catching exceptions like this, is pretty expensive.

I'm ok with the dynamic cast - though some reflection might actually perform better, but without changing the logic to stop making that test for every single button it would still be inefficient.

The first HasPictureProperty return value will be the value returned by every single subsequent call: you need to change the logic so as to avoid making that check more than once.


There's a bit of redundancy in your implementation. b <- return a is effectively the same as let b = a. There's no need to “inject” pure values into a monadic context with return, a pure value in scope is a pure value in scope so just use a and b in place of your x and y.

The parentheses around x : y : xs are also technically redundant. Regardless of the ordering of the application of x : y : and xs ++ ys you'll still end up with the same list. This is always the case for list cons and append, if you think about it you should see why. Note that the fixity precedence for both functions is infixr 5.

prependTupleConcatMaybeLists :: (a, a) -> Maybe [a] -> Maybe [a] -> Maybe [a]
prependTupleConcatMaybeLists (a, b) cs ds =
  do xs <- cs
     ys <- ds
     return $ a : b : xs ++ ys

I do question the necessity of writing this particular function. Concatenating cs and ds should probably be taken care of separately to prepending a tuple to a list. E.g.,

prependTupleMaybe :: (a, a) -> Maybe [a] -> Maybe [a]
prependTupleMaybe (a, b) xs = fmap (a:b:) xs

-- call site: let zs = liftA2 (++) (prependTupleMaybe pair xs) ys
-- or       : let zs = prependTupleMaybe pair (liftA2 (++) xs ys)


Improvements with a new solution:

import string. If the function is a top-level commonly used function - better to move that import at the top of enclosing module.Though in my proposed solution string won't be used.
flagged_words. Instead of generating a list of flagged words on every function's call - make it a constant with immutable data structure defined in the outer scope:

FLAGGED_WORDS = ('help', 'asap', 'urgent')

empty subj. To avoid multiple redundant checks/conditions on empty subj argument, if such would be passed in, a better way is handling an empty string at start:

subj = subj.strip()
if not subj:
    raise ValueError('Empty email subject!')

if subj[-3:] == '!!!' and if subj.isupper() checks lead to the same result.That's a sign for applying Consolidate conditional expression technique - the conditions are to be combined with logical or operator
the last for ... while ... for traversal looks really messy and over-complicated.When trying to untangle that, your test cases allowed me to make an assumption that the crucial function (besides of trailing !!! chars and all upper-cased letters) should catch:

exact word match with any of the flagged words, like urGent asAP (test case #1)
exact word match with repetitive allowed chars like asaaap (test case #2)

and should not allow strings that contain only words which combine both allowed and unallowed chars like Headlamp or wastepaper (though they contain he..l..p, .as....ap..) (test case #3)

Instead o going into a mess of splitting/loops I'd suggest a complex regex solution that will cover both exact word matching and exact matching with repetitive allowed chars cases.The underlying predefined pattern encompasses the idea of quantifying each char in each flagged word like h+e+l+p+ with respect for word boundaries \b:

import re

FLAGGED_WORDS = ('help', 'asap', 'urgent')

def quantify_chars_re(words):
    """Adds `+` quantifier to each char for further use in regex patterns"""
    return [''.join(c + '+' for c in w) for w in words]

RE_PAT = re.compile(fr"\b({'|'.join(quantify_chars_re(FLAGGED_WORDS))})\b", re.I)

def is_stressful(subj):
    """
        Recognize a stressful email subject
        we are looking for any of: all uppercase, or ending in 3 !!!, or
        containing 'help', 'asap', or 'urgent' despite have extraneous spellings
    """

    subj = subj.strip()
    if not subj:
        raise ValueError('Empty email subject!')

    if subj.isupper() or subj[-3:] == '!!!' or RE_PAT.search(subj):
        return True

    return False

if __name__ == "__main__":
    print(is_stressful("H!E!L!P! its urGent asAP"))
    print(is_stressful("asaaap"))
    print(is_stressful("Headlamp, wastepaper bin and super-magnificently"))
    print(is_stressful("I neeed advice!!!!"))

The output:

True
True
False
True


Perhaps the simplest solution is to read the input line and parse it. You are also correct it is a good idea to write a function for reading a vector.

Consider the following:

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>

std::vector<int> read_vector()
{
    std::string line = "";
    std::getline(std::cin, line);
    std::istringstream iss(line);

    std::vector<int> v;

    int x = 0;
    while (iss >> x)
        v.push_back(x);

    return v;
}

int main()
{
    std::cout << "Enter the elements of 1st vector\n";
    std::vector<int> v1 = read_vector();

    std::cout << "Enter the elements of 2nd vector\n";
    std::vector<int> v2 = read_vector();

    std::cout << "v1 = { ";
    for (auto e : v1)
        std::cout << e << " ";

    std::cout << "}\nv2 = { ";
    for (auto e : v2)
        std::cout << e << " ";
    std::cout << "}";
}

The functionality of reading a vector is now found from read_vector; quite obviously, it reads the input string (until the delimiter, which is by default an end of the line), and reads space-separated integers, pushes them to the vector, and returns it.


Since command line arguments are null-terminated, we can avoid strlen() entirely by just running through the string until we hit '\0'; this also gets rid of contin and i
(*p > 0x2F && *p < 0x3A) isn't very obvious, I'd just use '0' and '9' to make it easier to understand the intention and to be consistent with the rest of the code
You could use EXIT_SUCCESS and EXIT_FAILURE instead of 0 and 1 respectively
For consistency, I'd replace your call to exit() with a simple return
I'd remove the amount: part of the print; it should be clear from the context (running this program) what the output actually is; this would also make processing the output easier

Putting it all together, we end up with this short piece:

int main(int argc, char *argv[]) {
    if (argc < 2)
        return EXIT_FAILURE;

    char *p = argv[1];
    int amount = 0;

    while (*p) {
        if (*p < '0')
            return EXIT_FAILURE;
        if (*p > '9')
            return EXIT_FAILURE;

        amount = (amount * 10) + (*p++ - '0');
    }

    fprintf(stdout, "%i\n", amount);
    return EXIT_SUCCESS;
}

Note, however, that this doesn't account for:

negative numbers (starting with a -)
positive numbers starting with a +
any leading whitespace

Furthermore:

If the input starts with a number and has a letter following sometimes later, it will break out and print the number it has found until then; but if the first character found is a letter, the program prints 0 and reports success, which could be by design, but could also be considered a bug
The use of *p++ can be a bit dangerous if this was code shared with less experienced programmers, as simply changing it to ++*p would increase the value pointed to instead of the pointer itself; changing it to *(p++) might help
While this comes down to taste, I would argue to always use curly braces, even for one-liners: otherwise, adding another line later would break the code; also consistency is a plus
Adding support for leading whitespace is easy and also supports my previous point, as missing brackets would break the program:

    if (*p == ' ') {
        *p++;
        continue;
    }

If you don't want to implement support for negative numbers, it might be reasonable to change the type of amount to unsigned or - even better - unsigned long long, which would give you a possible range of [0, +18446744073709551615]
Naive handling of negative integers would be quite easy to implement (but note Roland's answer for caveats with this):

    int sign = 1;

    if (*p == '-') {
        sign = -1;
        *p++;
    }

    /* loop */

    amount *= sign;


HTML template for win-loss data in Javascript with Mustache

I think it would be much cleaner to put your template in your markup instead of having it as that JavaScript string literal. You can do this by wrapping your template in a script block:

Next, we can fetch our template HTML from the DOM:

var template = $('#RowTemplate').html();

The Mustache documentation says that we can pre-parse our template:

Mustache.parse(template);

Finally, you will have noticed that I did not include the {{#data}} tags in my template. It seemed to me that name-spacing my data in this way was unnecessary. So my call to render looks as follows:

$teams.append(Mustache.render(template, standings.standing));

However, it looks odd to me that the data for each table row is getting individually loaded via AJAX. If it is possible to load all of the data with one AJAX call, then I would do so. My template would then look something like the following:

This assumes the server response contains a standings array of objects, where each object would correspond to a row in our table:

{
    standings: [
        /*...*/
    ]
}


Extending method chaining IEnumerable with Add..If

I like the idea - but have the following comments:
  var originalList = Enumerable.Range(1, 12).ToList();
  IEnumerable<int> myList = originalList.Add(12).If((list, item) => !list.Contains(item));

If the originalList is defined explicit as something that implements ICollection, then you get a compiler error saying: "Operator '.' cannot be applied to operand of type 'void'", because Add() is already a method returning void.

    public IEnumerator<T> GetEnumerator()
    {
        if (_added)
            return _sequence.GetEnumerator();

        _sequence = _sequence.AddItem(_elementToAdd);
        _added = true;

        return _sequence.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        if (_added)
            return _sequence.GetEnumerator();

        _sequence = _sequence.AddItem(_elementToAdd);
        _added = true;

        return _sequence.GetEnumerator();
    }

Don't repeat code - the second method can call the first:
IEnumerator IEnumerable.GetEnumerator()
{
  return GetEnumerator();
}

public interface IAddEnumerable<T> : IEnumerable<T>
{
    IEnumerable<T> If(Func<IEnumerable<T>, T, bool> expression);
}

By renaming this interface you could extend its usability to for instance a sequence like:
data.Remove(12).If(<predicate>);

Maybe IPredicate or something like that.

Although I know that @new, @this etc. are valid variable names, I personally always avoid them, because they distract the reading. I have never been in a situation where it was unavoidable to use them.

I understand, that you want a fluid approach, and therefore define the If method separately, but I think, I would concatenate the behavior to a single function like:
public static IEnumerable<T> AddIf<T>(this IEnumerable<T> source, T element, Func<IEnumerable<T>, T, bool> predicate)
{
  return predicate(source, element) ? source.AddItem(element) : source;
}

An idea came to my mind: Because you return this from If(), I think, you can avoid the repetitive code in there by saving the predicate and then handle everything in GetEnumerator():
  internal class AddEnumerable<T> : IAddEnumerable<T>
  {
    private IEnumerable<T> _sequence;
    private readonly T _elementToAdd;
    private Func<IEnumerable<T>, T, bool> _expression;

    private bool _added;

    public AddEnumerable(IEnumerable<T> sequence, T elementToAdd)
    {
      _sequence = sequence;
      _elementToAdd = elementToAdd;
    }

    public IEnumerable<T> If(Func<IEnumerable<T>, T, bool> expression)
    {
      _expression = expression;
      return this;
    }

    public IEnumerator<T> GetEnumerator()
    {
      if (_added)
        return _sequence.GetEnumerator();

      if (_expression == null || _expression(_sequence, _elementToAdd))
      {
        _sequence = _sequence.AddItem(_elementToAdd);
      }
      _added = true;

      return _sequence.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
      return GetEnumerator();
    }
  }


Leetcode: Detecting duplicate elements in an array within a k-element window

The lookup dictionary might grow as large as the size of array (all array elements are distinct). It immediately gives an \$(O(n))\$ space complexity, and has detrimental effect on the time complexity as well. It is possible to get away with \$O(k))\$.

It makes no difference if \$k \approx n\$, but boosts the performance for \$k \ll n\$ (which I presume is so for the bulk of test cases).

To keep the dictionary "small", observe that if its size reaches k, it is safe to remove the oldest element. As a side benefit, you wouldn't need to test for cur - prev <= k anymore.


Design that avoids undesired dependencies in Kotlin for a chess engine

The cyclic import dependencies can only be removed in one way: By removing one of them. :)

As I see it now, you have:

Client, which needs to create the MateSearcher object, and also know about the API.
An API
An implementation class

Naturally, the implementation class - MateSearcher - needs to be aware of the API, so that's not an import that you want to remove.

I'd recommend putting a ChessFactory class (or rather, object) in the same package as the MateSearcher. It can look something like this:

object ChessFactory {
    fun mateSearcher(): Searcher = MateSearcher()
}

Some things to note here:

It's an object, not a class, meaning the method can be called with ChessFactory.mateSearcher() (no need for a companion object)
The method declares to return a Searcher, it doesn't need to declare that it is a MateSearcher since that will make the client aware about the implementation details.

Now, removing the construction of the MateSearcher leaves your Chess class with... two interfaces and a data class. The Chess class is basically wrapping them, which I personally don't find very useful, but I'll leave that to you to decide whether to keep it or not.

Looking a bit closer at what the Chess class contains,

class Chess {
    interface Move {
        override fun toString(): String
    }
    data class TextMove(val text: String): Move { override fun toString() = text }
    interface Searcher {
        var board: String
        fun findBestMove(): Move
    }
}

The Move interfaces specifies that a toString method should exist. Such an interface always exists. It's also not recommended to make your code dependent on the return values of toString. The toString method should be used for only one thing: Printing information to you, the programmer. Its results should not be shown to users of the program and its implementation details should not be important for the application logic.
It's currently hard to tell what your Move interface should contain as the only implementation is your TextMove class, which makes me doubt that you need the Move interface at all. What other implementations will you have?

Your generic Move class should possibly have methods like Move.validate(ChessBoard) and Move.perform(ChessBoard).

You have code in your MateSearcher that is commented with Complicated code that should not be exposed to the client. I'd like to make you aware of the fact that that function is marked private, and no function or field marked private will ever be exposed to anything else other than the class itself, no matter if we're implementing an interface or not.

The Searcher interface stings a bit to me, especially when looking at your usage of it. Let me ask you this: What if I have a Searcher and call findBestMove() without setting the board? That shouldn't be allowed, right? Why is the board not a parameter to findBestMove()?

Making this change would leave us with:

interface Searcher {
    fun findBestMove(board: String): Move
}

Which could be changed to:

typealias Searcher = (board: String) -> Move

Which, in my opinion, is more Kotlinic (like Pythonic but for Kotlin), and it would make it easier to use lambdas or method references for the searcher.


First of all, you should read about MVC.

There are a lot of tutorials out there, as well as frameworks (like CodeIgniter) that implement it. Basically your code should be divided into 3 main categories:

Controllers - where all logic should be placed like validations, checks. This is also where Views and Models are used, hence "controller"
Models - basically the source of data. Usually this is the abstraction of the data storage (databases, sessions, external requests) in the form of functions.
Views - the presentation, or in this case, the HTML.

Reasons to use MVC or MV* patterns is

Portability.

The files, especially the views and models, can be plucked out of the architecture, and be used elsewhere in the system without modification.

Models are simply function declarations one can just plug in the controller and call their functions. Views are simply layouts that, when plugged with the right values, display your data. They can be used and reused with little or no modification unlike with mixed code.
Purpose-written code and Readability

You would not want your HTML mixed with the logic, nor the data gathering mechanism. This goes for all other parts of your code. For example, when you edit your layout, all you want to see on your screen is your layout code, and nothing more.

Never, and I mean NEVER return marked-up data using AJAX (use JSON).

The main reason AJAX is used is because it's asynchronous. This means no page-loading, no more request-wait-respond, and you could do stuff in parallel. It's pseudo-multitasking for the human.

On the same train of thought, the reason why JSON was created was because XML was too heavy for data transfer and we needed a lightweight, data transport format. XML is NOT a data-transport format but a document and mark-up language (Though by "X" for extensibility, it has served a lot of purposes beyond document).

Use client-side templating

JavaScript engines have become fast these days that even developers create parsers/compilers on JavaScript. And with that comes client-side templating, like Mustache.

Coupled with raw data from JSON, which is very light, you can integrate that data into a template to form your view and have JavaScript display it, like you already do.

Have a rendered version and a data version

Taking into account the previous answer, if you are making a website rather than a web app, where JS is optional rather than required, one should create a website that works without JS.

However, for the same data but different format, the URL should not change (much). You should then take into account in the request what data type is requested by the client. And so you must accept a parameter which indicates the data type.

An example url would look like this:

//for a website page format (default: HTML):
http://example.com/my/shop/available/items.php

//for the JSON version
http://example.com/my/shop/available/items.php?format=JSON

//for the XML version
http://example.com/my/shop/available/items.php?format=XML

This means, that for the same page (available items), you have 3 formats you can use. This can be seen in the Joomla Framework (the framework that powers the Joomla CMS)

With these 3 tips, your code will be cleanly separated and purposely written (MVC), fast on transport and rendering (JSON + client-side templating) and extensible (multi-format support).


Proper way to execute parameterized commands within a method

Why is it static?

First off, I would remove the check for no parameters.  You've already checked that it is not null, if somebody passes in an empty list, the foreach for parameters will just be ignored.

As svick said, I would not return a null value if no results are found.  This complicates code on the calling side because you have to check for null before you work with it.  Same principle as the parameters.  If I have a foreach on an empty list, my code within the foreach would not be called.

I would change conString == "" to string.IsNullOrEmpty(constring)  I would do the same thing for query, because most people will pass an empty string before they pass a space string.  If you think space will be a problem, do both.

I would change this DataTable data = new DataTable(); to use var var data = new DataTable();  It makes the code easier to scan quickly.

If you insist on returning null for empty sets, change (data.Rows.Count > 0) to (data.Rows.Any()).  I think it makes the code much easier to read because it says exactly what you are looking for.


full_path = "{}/{}".format(top_level, filename)

You can use os.path.join(top_level, filename) for that. That way it will also work on any system which does not use / as a directory separator (that's not really a realistic concern in this case, but using os.path.join doesn't cost you anything and is a good practice to get used to).

cmd = "cd ~/src/gnome/{} && git clean -dfx".format(filename)

First of all spelling out ~/src/gnome again is bad practice. This way if you want to change it to a different directory you have to change it in all 4 places. You already have it in the top_level variable, so you should use that variable everywhere.

On second thought you should actually not use top_level here, because what you're doing here is you're joining top_level and filename. However you already did that with full_path. So you should just use full_path here.

You should also consider using os.chdir instead of cd in the shell. This way you only have to change the directory once per iteration instead of on every call. I.e. you can just do:

if os.path.isdir(full_path):
    os.chdir(full_path)
    if subprocess.call("git clean -dfx", shell=True) != 0:
        if subprocess.call("make distclean", shell=True) != 0:
            subprocess.call("make clean", shell=True)

(Note that since full_path is an absolute path, it doesn't matter that you don't chdir back at the end of each iteration.)

Another good habit to get into is to not use shell=True, but instead pass in a list with command and the arguments, e.g. subprocess.call(["make", "clean"]). It doesn't make a difference in this case, but in cases where your parameters may contain spaces, it saves you the trouble of escaping them.


MIPS program to find the sum and square sum of 10 integers

Your program is correct. I ran it and verified the results against a C program. So, it works and the code is pretty good, too.

You did a good job of commenting. Especially, the top block where you detail the algorithm and the intended register usage. And, putting a sidebar comment on each asm line is also very good.

But, you also wanted to know how to improve it. So, a few things ...

I realize you're just starting out, but sidebar comments should talk about intent. That is, what are we doing with the algorithm, instead of just rehashing the mechanics of the asm instruction.

I tightened things up a bit. Instead of what you did (in C/pseudo code):

int i;
int val;

for (i = 0;  i <= (length - 1);  ++i) {
    val = array[i];
    ...
}

I changed this into:

int *arrptr;
int *arrend;
int val;

arrptr = array;
arrend = &array[length];
for (;  arrptr < arrend;  ++arrptr) {
    val = *arrptr;
    ...
}

I was also able to eliminate a few extra instructions by changing some of the registers being used and eliminate a extra branch instruction in the loop

Anyway, here's the cleaned up/improved code [please pardon the gratuitous style cleanup]:

    .data
array:      .word       23,-2,45,67,89,12,-100,0,120,6
arrend:

sumMessage: .asciiz     "The sum of the array(sign) is: "
squareMessage:  .asciiz "The sum of the squares(sign) is: "
newLine:    .asciiz     "\n"

    # array = {23,-2,45,67,89,12,-100,0,120,6}
    # the sum of the integers (in array) is 0
    # the square sum of the integers (in array) is 0

    # Algorithm being implemented to sum an array
    # sum = 0 (use $t0 for sum)
    # squarSum = 0 (use %t5 for squarSum)
    # for i = 0 to length-1 do (use $t1 for i)
    # sum = sum + array[i] (use $t2 for length-1)
    # squareSum = squareSum + array[i]*array[i]
    # end for (use $t3 for base addr. of array)

    # registers:
    #   t0 -- sum
    #   t5 -- squarSum
    #
    #   t3 -- pointer to current array element (e.g. arrptr)
    #   t2 -- pointer to end of array
    #
    #   t4 -- current value fetched from array
    #   t6 -- temp to hold squared value

    .text

main:
    li      $t0,0                   # sum = 0
    li      $t5,0                   # squarSum = 0

    la      $t3,array               # load base addr. of array
    la      $t2,arrend              # load address of array end
    j       test

loop:
    lw      $t4,0($t3)              # load array[i]
    addi    $t3,$t3,4               # increment array pointer

    add     $t0,$t0,$t4             # update sum
    mul     $t6,$t4,$t4             # get val * val
    add     $t5,$t5,$t6             # update squareSum

test:
    blt     $t3,$t2,loop            # more to do? if yes, loop

    # print sum message
    li      $v0,4
    la      $a0,sumMessage
    syscall

    # print value of sum
    li      $v0,1
    addi    $a0,$t0,0
    syscall

    # print new line
    li      $v0,4
    la      $a0,newLine
    syscall

    # print square sum message
    li      $v0,4
    la      $a0,squareMessage
    syscall

    # print value of squareSum
    li      $v0,1
    addi    $a0,$t5,0
    syscall

    li      $v0,10
    syscall

If you'd like to see some further tips on writing good/clean asm, based on my own personal experience, see my answer here: https://stackoverflow.com/questions/36538325/mips-linked-list/36560575#36560575

UPDATE:

  I didn't understand the "arrend" part. how does it know that $t2 = 10?

$t2 no longer has a count. It was repurposed to hold the address of the array's end address. The two loops are fundamentally different in how they iterate and terminate. This was evidenced in the C samples given above.

Your code used $t2 to hold the length/count of array, which was 10. Your loop was using an index variable [contained in $t1] to iterate through the array and stopping when the index value hit the count. It was incrementing the index value by 1 on each loop iteration.

In the modified code, $t2 holds the address of arrend. This is "one beyond" the last element of array. The loop stops when the pointer to the current array value [in $t3] hits/equals the array end. It was incrementing the pointer by 4 on each iteration.

In strictest terms, the loop doesn't use or care about the count. What it cares about is: "If I know the address of the array end, has my current address/pointer gone past it?"

Just for completeness, let's go the other way. In mars, array has address 0x10010000 and arrend has address 0x10010028. If we subtract the addresses, arrend is offset from array by 0x28 bytes, which is 40 (decimal). If we divide this by 4 [the size of a word] to get the count, we have 10


Encoding/decoding protocol messages to/from various bits of hardware

OK. I doubt it is irrelevant.

//ref_type is a smart pointers class - not really so relevant to my question

Also smart pointers are very hard to get perfectly correct. The standard ones took years and thousands of people looking at them to get correct. So It is usually preferable to use one of the standard smart pointers rather than a home grown one (especially one that is not being reviewed).

So who owns this pointer?

    virtual const char* ProtocolName() const = 0;

There are no ownership semantics associated with pointers. So After I call this I am not sure who is responsible for deleting it. Use a std::string internally and return a const reference to the string.

Not sure why you would want two methods that look like they do the same thing.

    //for binary protocols
    virtual void getMessage(unsigned char*& serialised, size_t& length) {};
    //for text/xml protocols
    virtual void getMessage(std::string& serialised) {}

Both are going to be inefficient as you are copying across multiple buffers (input stream buffer into this buffer which is then returned and read again to build an object). What you really want is a getMessage() method that returns a fully constructed object from the stream.

This calss:

class ABCMessage : public BaseMessage {

Is totally broken as it contains an owned RAW pointer but does not implement the rule of three.


Validating an IP address and returning the reason it's invalid

Your code has three major errors that all the previous reviewers failed to spot. If I were a lecturer, I'd show your code to the students as an example why they should always use libraries, even doing something seemingly simple as validating the IPv4 address.

It accepts 127.0.0.1..... as a valid IP address, which it is not. Pass -1 as a second argument to the split function.
Because of your faulty isNumeric function, the address 0.00123.0000034.12 is considered valid, too.
Similar to above, the address 127.-0.-0.1 is accepted too.

Consider using a library for validating the IP addresses

As described above, you can never be too careful. Besides that, we are starting to make the migration to the IPv6 standard, which is harder to validate.

So, if you can rely on a well tested library for IP validation that does not bring an additional huge dependency to your code, use that instead.

It is not resilient against crafted inputs

Depending on the source of the input, the validation function might pose a huge performance risk and cause OM (out of memory) errors.

See, even really short strings of just dots ".........x" create one String object per character. String object and a pointer overhead in Java is rather in the neighborhood of 44 bytes. Therefore, someone sending you a 10 MiB string is typically going to overflow the heap space.

Code locality (tie error messages to enum values)

Because error strings are tied to enum values, it is a good thing to specify them in the actual enum construct.

public enum IpValidation {
    INVALID_NUMBER("You have entered an invalid octect(s) value"),
    INVALID_LENGTH("You have entered an IP with an invalid length"),
    NON_NUMERIC("You have entered an IP with an invalid length"),
    VALID("This IP address is valid");

    private final String error;

    private IpValidation(final String error) {
        this.error = error;
    }

    public String getError() {
        return error;
    }
}

Give the enum a more meaningful name

Strings is just a bad name to give an enum. Pick something else.

Nits

Do put a space after the switch, if, and for keywords.
Using enums on Android might have performance consequences. Depending on the use case, you might want to avoid it.


There are some obvious possible simplifications for elegance, if not necessarily for speed.

The while condition should be written as a double-ended inequality:

while 0 < n < pop_max:
    …

The variable j is unused.  The convention is to use _ as the name of a "throwaway" variable.

The if-elif chain can be eliminated with a smarter randint() call:

for j in range(n):
    n += randint(-1, 2)

NumPy is overkill here, when all you want to know whether the population went extinct.  The built-in sum() function can do the counting for you.

Each simulation run is independent.  I'd put the code in a function for readability.

from random import randint

def population(pop_max=100):
    n = 1
    while 0 < n < pop_max:
        for _ in range(n):
            n += randint(-1, 2)
    return n

iterations = 100000
print(sum(population() == 0 for _ in range(iterations)) / iterations)


Checking against user input and returns a response based on that input

Use rustfmt. I know the code you've presented is formatted correctly now, but that's because I reformatted it for you over on Stack Overflow (I wouldn't have touched it here).
Read and address the compiler's warning messages!

warning: unused variable: `b`
  --> src/main.rs:13:12
   |
13 |         Ok(b) => {
   |            ^ help: consider using `_b` instead
   |
   = note: #[warn(unused_variables)] on by default

warning: unused variable: `err`
  --> src/main.rs:22:13
   |
22 |         Err(err) => panic!("incorrect"),
   |             ^^^ help: consider using `_err` instead

warning: function cannot return without recursing
  --> src/main.rs:10:1
   |
10 | fn shell(input: &mut String, version: &String) {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot return without recursing
...
16 |                 shell(input, version);
   |                 --------------------- recursive call site
...
19 |                 shell(input, &version);
   |                 ---------------------- recursive call site
   |
   = note: #[warn(unconditional_recursion)] on by default
   = help: a `loop` may express intention better if this is on purpose

    Finished dev [unoptimized + debuginfo] target(s) in 2.16s
     Running `target/debug/playground`

Don't have infinite recursion; that's almost always a bad idea and you will run out of stack space. Write an infinite loop instead.
There's no reason to put input outside of the function, as it's only ever used inside it.
Use clippy. It will point out things like:

warning: writing `&String` instead of `&str` involves a new object where a slice will do.
 --> src/main.rs:9:19
  |
9 | fn shell(version: &String) {
  |                   ^^^^^^^ help: change this to: `&str`
  |
  = note: #[warn(clippy::ptr_arg)] on by default
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#ptr_arg

warning: needlessly taken reference of both operands
  --> src/main.rs:15:16
   |
15 |             if &input.trim() == &"ver" || &input.trim() == &"what are you" {
   |                ^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: #[warn(clippy::op_ref)] on by default
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#op_ref
help: use the values directly
   |
15 |             if input.trim() == "ver" || &input.trim() == &"what are you" {
   |                ^^^^^^^^^^^^    ^^^^^

See also:

Why is it discouraged to accept a reference to a String (&String), Vec (&Vec), or Box (&Box) as a function argument?

Use Result::expect instead of doing the match yourself. This has the beenfit of printing out the underlying error message as well.
Store the result of trim to avoid doing the work multiple times.
Consider using a match on the trimmed string to decide what to work on.

use std::io;

fn main() {
    let version = "0.0.1";

    shell(version);
}

fn shell(version: &str) {
    let mut input = String::new();
    loop {
        input.clear();
        io::stdin().read_line(&mut input).expect("incorrect");
        let input = input.trim();

        match input {
            "ver" | "what are you" => {
                println!("C ute R ust A mateur B eginner Shell ver: {}", version)
            }
            _ => println!("Command '{}' Not Recognized", input),
        }
    }
}

Now we can consider how best to use enums here. An enum is good for a type that can be one of many values. You have that structure in your "command" decisions. You could create an enum from those strings:

use std::io;

fn main() {
    let version = "0.0.1";

    shell(version);
}

fn shell(version: &str) {
    let mut input = String::new();
    loop {
        input.clear();
        io::stdin().read_line(&mut input).expect("incorrect");
        let command = input.trim().parse::<Command>();

        use Command::*;
        match command {
            Ok(Version) | Ok(WhatAreYou) => {
                println!("C ute R ust A mateur B eginner Shell ver: {}", version)
            }
            Err(_) => println!("Command '{}' Not Recognized", input),
        }
    }
}

#[derive(Debug)]
enum Command {
    Version,
    WhatAreYou,
}

impl std::str::FromStr for Command {
    type Err = ();

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        use Command::*;
        Ok(match input {
            "ver" => Version,
            "what are you" => WhatAreYou,
            _ => return Err(()),
        })
    }
}