Fastest way to search istringstream for patterns in around 0.02 seconds

Without profiling data, I can only guess... so here goes:

At a quick glance the biggest inefficiency I can see is that you allocate and de-allocate the vector capacity for values in each iteration. This takes some time, just move the vector outside of the loop and use clear() at the head of the loop.

Like this:

vector<string> values;
while(getline(str, line))
{
   values.clear();

Another thing that you can do (even though I don't believe it will affect your result significantly) is to use emplace_back instead of push_back to avoid the possibility of a copy.

Like this:

 types.emplace_back(values[0], values[1]);

This will construct the pair in place and avoid the pair copy constructor (the compiler might have optimized this for you already). While we're at it, we can realize that values will not be used after this statement until it is cleared. So we can steal the memory and avoid another two new/deletes (unless your STL has SSO and your strings are small, in which case this is moot) just activate the move construction of the pair like this:

 types.emplace_back(std::move(values[0]), std::move(values[1]));


Method names should be named using PascalCase casing.
An if condition is just a boolean expression hence if (!string.IsNullOrEmpty(source) == true) is a little bit over the top. Either write

if (!string.IsNullOrEmpty(source))
{

}

or

if (string.IsNullOrEmpty(source)) { return source; }

which saves one level of indentation.
Why is the method protected ? Doesn't make sense to me.
The name of that method sounds rather like a class/object name than a method name. Methodnames should contain a verb or verb-phrase.

Instead of the Regex stuff and string.Contains() etc your method could just look like so

private static string SuperscriptRule(string source)
{
    if (string.IsNullOrEmpty(source)) { return source; }

    return source.Replace("<sup>", "^").Replace("<\sup>", string.Empty);
}


... a more compact and cleaner way of doing this? I especially don't like the fact that the RRULE string is parsed twice.

If you're going to use the rrule module's public API, then yes, your approach is the best way of doing this.


Enclose the file reading in a using statement
Use double.TryParse or regex to parse the numbers
Use Linq extention method Average() to calculate average
The size of strInput is strInput.Count, no need for a loop

Hear is a simpler code:

using (StreamReader bestand = new StreamReader(@"F:\RenoD_Oef_Strings\Punten.txt"))
{
    string strRow; // String used to read every row of .txt file
                    // Code
    while ((strRow = bestand.ReadLine()) != null) // Read row per row in .txt
    {
        List<string> strInput = strRow.Split(' ').ToList(); // String List used to store all data from .txt
        List<double> dblPoints = new List<double>(); // Double list used to store all values

        foreach (var x in strInput)  // Checks if elements in the list can be converted in to a double
        {
            if (double.TryParse(x, out double result))
            {
                dblPoints.Add(result);
            }
        }
        double dblAverage = dblPoints.Average();

        Console.WriteLine(dblAverage.ToString());
    }
}

Console.ReadKey();


Python & C: Trying to create a dict of all declared variables and functions and their types of a .c source file

I think this code is fundamentally broken. What about comments and the preprocessor? And just by eyeballing the code I doubt very much that it parses declarations remotely correctly.

This is the wrong approach. string.find will only take you so far. You need to parse the code to get reliable information. The easiest way to do this is to use a library, such as libclang.


Reading a string-to-string map from an archive

But is there a better way to read this data file from within the C# DLL?

You can write a C++/CLI wrapper. It'll compile as a .NET assembly that you can reference in your project as any other .NET dll but inside it'll be able to work with `C++ and use your current code as it is.

Visual C++ supports interoperability features that allow managed and unmanaged constructs to co-exist and interoperate within the same assembly, and even in the same file.
Mixed assemblies are capable of containing both unmanaged machine instructions and MSIL instructions. This allows them to call and be called by .NET components, while retaining compatibility with components that are entirely unmanaged. Using mixed assemblies, developers can author applications using a mixture of managed and unmanaged functionality. This makes mixed assemblies ideal for migrating existing Visual C++ applications to the .NET Platform.

Mixed (Native and Managed) Assemblies
I recommend reading

C++/CLI in Action and/or
Expert Visual C++/CLI: .NET for Visual C++ Programmers


This is what I came up with (untested):

I got rid of your settings-stuff, introduced a variable self so there's no interference with this, moved your initialization code to the only place it is (and can ever be) called from, extracted a method for padding and event handler registration and fixed your updateTimer so it works for values > 1000 (it's not fit for negative values, though). I hope you like it...

(function (MyApp, $, undefined) {
    // Using strict mode to throw exceptions for 'unsafe' actions and coding patterns
    'use strict';

    function addClickHandlerToButton(buttonId, handler) {
        document.getElementById(buttonId).addEventListener('click', handler, false);
    }

    function padLeft(number) {
        number = +number;
        return (number < 10 ? '0' : '') + Math.floor(number);
    }

    // Manages the stopwatch
    var stopwatch = (function(){
        var minutes = 0,
            seconds = 0,
            millis = 0,
            interval = 100,
            timerId = -1,
        displayTimer = function () {
            document.getElementById('stopwatch').innerHTML =
                padLeft(minutes) + ':' +
                padLeft(seconds) + ':' +
                Math.floor(millis);
        },

        updateTimer = function () {
            millis += interval;
            if (millis >= 1000) {
                seconds += millis / 1000;
                millis %= 1000;
            }
            if (seconds >= 60) {
                minutes += seconds / 60;
                seconds %= 60;
            }
            displayTimer();
        },

        pauseTimer = function () {
            window.clearInterval(timerId);
            timerId = -1;
        },

        startTimer = function () {
            if (timerId === -1) {
                timerId = window.setInterval(updateTimer, interval);
            }
        },

        resetTimer = function () {
            pauseTimer();
            millis = 0;
            seconds = 0;
            minutes = 0;
            displayTimer();
        };

        return function (startButton, pauseButton, resetButton) {
            addClickHandlerToButton(startButton, startTimer)
            addClickHandlerToButton(pauseButton, pauseTimer)
            addClickHandlerToButton(resetButton, stopTimer)
            displayTimer();
        };
    })();

    // PhoneGap, jQuery & device is ready now -> initialize
    $(document).on('deviceready', function() {
        stopwatch('startStopwatch', 'pauseStopwatch', 'resetStopwatch');
    });

}(window.MyApp = window.MyApp || {}, jQuery));

EDIT 1+2: updated the code to integrate suggestions from the comments by the OP and fix errors.


Finally, a question where we can use Roslyn!

I won't review your own code but instead I whipped up this small showcase of how you might do it with the Roslyn compilers. Do note that it is rather ugly, not in the least because I am not entirely comfortable with it myself yet but also because I know little VB.NET and it appears some things are handled differently from the C# compiler. That being said, this sample implementation can parse both

Dim foo As String

and

Dim foo As String, bar As String

El codos:

using System;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.VisualBasic.Syntax;
using Microsoft.CodeAnalysis.VisualBasic;

class Program
{
    static void Main(string[] args)
    {
        var stuffIWantToParse = "Dim foo As String, bar As String";

        var tree = VisualBasicSyntaxTree.ParseText(@"
            Module Module1
                 " + stuffIWantToParse +
            @" End Module
        ");

        var compilation = VisualBasicCompilation.Create("MyCompilation", syntaxTrees: new[] { tree });
        var moduleType = compilation.GetTypeByMetadataName("Module1");

        PrintVariableDeclarationByIndex(0, moduleType);
        PrintVariableDeclarationByIndex(1, moduleType);

        Console.Read();
    }

    private static void PrintVariableDeclarationByIndex(int i, INamedTypeSymbol moduleType)
    {
        var variable = moduleType.GetMembers().Skip(i).FirstOrDefault();

        var position = variable.Locations.First().SourceSpan.Start;
        var root = variable.Locations.First().SourceTree.GetRoot();
        var parent = root.FindToken(position).Parent;
        var node = parent.FirstAncestorOrSelf<FieldDeclarationSyntax>();
        var typeInfo = node.Declarators[i].AsClause;

        Console.WriteLine("Modifiers: " + string.Join(",", node.Modifiers));
        Console.WriteLine("Name: " + variable.Name);
        Console.WriteLine("Type: " + typeInfo.Type());
        Console.WriteLine();
    }
}

Output:

Using a workaround from here. If you want some more codesamples on Roslyn, look at my project here. In order to use the Visual Basic compilers look here. For more information on Roslyn, take a look at the roslyn tag wiki I put together.


cleaning up and increasing performance of js code

In code you posted, you pass through array three times instead of one:

1st pass when pushing absolute values to auxillary array
2nd pass when searching for minimum value (in Math.min)
3rd pass when you get the index of minimum value (in indexOf)

It is more efficiently to do it in just one pass:

function getClosestToZero(set) {
  if(0 === set.length) return null;
  var closest = Math.abs(set[0]), result = 0;
  for(var i in set) {
     var next = Math.abs(set[i]);
     if(closest > next) {
       result = i;
       closest = next;
     }
  }
  return result;
}

Also for the purpose of readability I will recommend you to use Math.abs library function instead of implementing it by yourself.

Note: The small theoretical disatavantage of my code consists in that it compares first element with itself. You can rewrite for loop to avoid it or ignore it because its impact is insigninficant.


Struggling to refactor code to remove duplication

It seems like each method is iterating over the list of lines and doing something. It is the "doing something" that is unique. Consider having a single method that iterates over the lines and takes an interface to do the "something". For each method, an appropriate interface instance would be passed (possible anonymous inner class) that takes the appropriate action.

Something like this:

private interface ProcessLine{
     void processLine(String line, int index, int charIndex);
     void complete();
}

private ProcessLine process(ProcessLine processor){
  String text = textArea.getText();
  int start = 0;
  int count = 0;
  String buildNewTextArea = "";
  int index = 0;
  while (start >= 0) {
    int nextLineStart = text.indexOf(NEW_LINE, start + NEW_LINE.length());
    if (nextLineStart == -1) {
        nextLineStart = text.length();
    }

    processor.processLine(line, count);
    index += buildNewTextArea.length();
    count++;
    start = text.indexOf(NEW_LINE, nextLineStart);
  }
  return processor;
}

private int getLineIndex(final int line) {
     int result = -1;
     return process(new ProcessLine(){
         public void processLine(String line, int index, int charIndex){
             if (index == line)
                 result = charIndex;
         }
     });
     return result;
}


Finding longest substring containing k distinct characters

//use set to keep track of distinct characters
Set<Integer> set=new TreeSet<>();

Use spaces, they're free. According to conventions, there should be spaces around each operator. If you want to use them more sparingly, it's your choice, but think about how they separate things. You code looks like composed of three things

Set<Integer>   set=new   TreeSet<>();

which is rather confusing.

You write "keep track of distinct characters" and declare Set<Integer>. Why not Set<Character>?

Don't use TreeSet unless you need it. HashSet is faster.

Don't call it set, when you can call it e.g. foundCharacters.

char arr[] = str.toCharArray();

Naming.

while(i<len && j<len){

Spacing. Always prefer "for" loops as they're much clearer. They also allow you to declare variables in a smaller scope. I'd go for

for (int i=0, j=0; i<len && j<len; ++j) ...

(add spaces to adhere to conventions), but you're modifying j somewhere in the middle (which is unexpected with a "for" loop). So feel free to stick with "while".

        int substrLen=Math.abs(i-j);

This looks like you lost track of what your variables do. I guess, j>=i always holds, but you should know. You may want to call them start and end.

        int substrLen = Math.abs(i-(j+1));

This makes me suspect. Why do you need a different expression for computing the same thing?

Optimizations

  How can I tweak my logic to improve running time for large strings?

What the problem? You run through the string until you find out that they're too many characters. Then you throw away all information collected so far and start over at the next index. This implies a complexity of \$O(n^2)\$, which is way too slow for \$n=10^6\$.

When you find out that you collected too many distinct characters, you could move the start index until their number gets smaller again. For this, a Set is insufficient, as you have to know, when you get rid of the last occurrence of a given character.

So instead of remembering what characters you ran across, you need to count their occurrences. A Map<Character, Integer> would do. Guava Multiset<Character> would be even better as a multiset is just like a set but allowing duplicates.

But the best solution is an array. As there are just \$2^{16}\$ characters (let's ignore surrogates), you can keep track of them in new int[Character.MAX_VALUE+1]. This gives you a nice speed bonus of maybe factor 10 (it's just a bonus, it would not help you with the quadratic complexity and it's most probably not needed with the new algorithm).

Just a snippet to get you started:

private int distinctChars;
private int[] counts = new int[Character.MAX_VALUE+1];

private void addCharacter(char c) {
    if (counts[c] == 0) {
        distinctChars++;
    }
    counts[c]++;
}

private void removeCharacter(char c) {...}

public int maximumLength(String str, int limit) {
     ...
     for (int i=0, j=0; j<len; ) {
         if (distinctChars <= limit) {
             max = Math.max(max, j-i);
             addCharacter(str[j++]);
         } else {
             removeCharacter(str[i++]);
         }
     }
     ...
}


Use toggle methods

Presuming that you are just toggling those two classes, you could just use classList.toggle() with those two class names:

function toggle_expandable_icon(elem) {
    elem.classList.toggle('fa-plus-circle');
    elem.classList.toggle('fa-minus-circle');
}

And it appears jQuery is used, so the .toggleClass() method could be used on a jQuery collection (i.e. remove the [0] in toggle_expandable_icon($(this).find('i')[0]);):

function toggle_expandable_icon(collection) {
    collection.toggleClass('fa-plus-circle').toggleClass('fa-minus-circle');
}

Those class names could also be added together in a single toggleClass() call:

function toggle_expandable_icon(collection) {
    collection.toggleClass('fa-plus-circle fa-minus-circle');
}

Demo

Without knowing the HTML structure it was challenging to know exactly how the toggles operated, but it wasn't very difficult to generate something.

$('.expandable_header').click(function() {
    toggle_expandable_icon($(this).find('i'));
    $(this).nextUntil('tr.expandable_header').slideToggle("slow");
});

function toggle_expandable_icon(collection) {
    collection.toggleClass('fa-plus-circle fa-minus-circle');
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.css" rel="stylesheet" />

                                                                                Zombies exist!


New list from the elements of two lists popping sequentially

There are a few possibilities...

from itertools import chain, izip_longest
def alternate(a, b):
    for i in range(max(len(a), len(b))):
        if i < len(a):
            yield a[i]
        if i < len(b):
            yield b[i]

def alternate2(list_a, list_b):
    unfound = {}
    for a, b in izip_longest(list_a, list_b, fill=unfound):
        if a is not unfound:
            yield a
        if b is not unfound:
            yield b

a = [1,9,'foo',5,7]
b = ['bar',4,8,6]
print list(alternate(a, b))
print list(alternate2(a, b))
print list(chain.from_iterable(zip(a, b))) + a[len(b):] + b[len(a):]


designing application using polymorphism

Yes, I don't see a problem with that.

If you don't have any implementation at all in the base class, consider making it an interface instead:

interface IWriter {
    void Write(List<WriteObj> writeObjList);
}

class ConsoleWriter : IWriter {
  public void Write(List<WriteObj> writeObjList) {
    foreach (WriteObj obj in writeObjList) {
      Console.Writeline("I am in Console Writer, parameter: " + obj.Obj1);
    }
  }
}

etc.


jQuery function to select user specified text within a div

Current solution

DOM queries

Whenever you call getSelection you select the same two elements again and again. You can simply store them in variables for re-use outside of the function. Also you never use the element #sentence itself, so you can actually store its textNode:

var textNode = document.getElementById('sentence').firstChild,
    source = document.getElementById('source');

I also renamed target to source as it represents the "source" of the selection. But this might be arguable.

You can even store the selection and range in variables:

var selection = document.getSelection(),
    range = document.createRange();

Cases

You don't handle these cases:

empty value or value not found
case sensitivity in both the value and the text
multiple occurrences of the value

If no value is given or no match is found, you should deselect any text. You could also present a message to the user:

if (0 === value.length || -1 === start) {
    selection.removeAllRanges();
    return;
}

Being case sensitive could be by design, but it would be great if I could type this and it would select the text This in the beginning of the sentence.

Your solution always selects the first occurrence of the string. Multiple ranges are only supported by Firefox and apparently by Edge, see MDN Selection.addRange(). So, this is by design. But it would be nice if the button's wording would reflect that:

  Select first occurence

Getting text using innerHTML

You're using innerHTML to get the content of the div element. We have stored the textNode already. You can simply use nodeValue instead, as it is way faster than innerHTML in Webkit browsers. It's about the same in Firefox:

textNode.nodeValue.indexOf(value);

Updated function

Taking everything into account, this could be the final function:

getSelectionText = function() {
    var value = source.value.toLowerCase(),
        start = textNode.nodeValue.toLowerCase().indexOf(value);

    selection.removeAllRanges();

    if (0 === value.length || -1 === start) {
        return;
    }

    range.setStart(textNode, start);
    range.setEnd(textNode, start + value.length);

    selection.addRange(range);
}

jQuery

I'm not sure, why you're trying to rewrite this code using jQuery. Let's assume it's an exercise to get to know jQuery better.

The thing is, you're creating a lot of overhead, as you'll see next.

DOM queries

If you follow through and create jQuery objects of all DOM elements, the selectors will look like this:

var textNode = $("#sentence").contents().first(),
    source = $('#source');

jQuery optimizes selectors, so this should end in a call to getElementById(). But calling contents().first() is overhead to a simple .firstChild.

Getting text the jQuery way

Use .val() for form elements and .text() for other nodes:

var value  = source.val().toLowerCase(),
    start = textNode.text().toLowerCase().indexOf(value);

.text() wil definitely be slower than the native options discussed before.

Other changes

Well actually you have only one change left. You have to pass the real node to the range methods instead of the jQuery object:

range.setStart(textNode[0], start);
range.setEnd(textNode[0], start + value.length);

Adding everything into the anonymous function

I would not advise to place everything into the anonymous function of the event handler. What if you need to call the function from another place? Keep it as is and bind the function call, for example like:

$("#getSelection").click(getSelectionText);

Updated function

getSelectionText = function() {
    var value  = source.val().toLowerCase(),
        start = textNode.text().toLowerCase().indexOf(value);

    selection.removeAllRanges();

    if (0 === value.length || -1 === start) {
        return;
    }

    range.setStart(textNode[0], start);
    range.setEnd(textNode[0], start + value.length);

    selection.addRange(range);
}

Final thoughts

I guess you can see, that there's no actual benefit from switching to jQuery for this particular task:

The code is not getting easier to read or maintain.
You create a lot of overhead.
You still have to access the contained native DOM element often.
You have additional weight of 87 KB for the compressed library.


Looks good except for your use of constants.

Constant variables is probably the biggest oxymoron I have ever heard. The whole point of a constant is that it does not change - the very name variable implies that it is prone to change.

A proper use of a constants is to hold immutable data where the value is clearly understandable by just reading the code:

# A very contrived example
class Week
  DAYS = [:monday, :tuesday, :wednesday, :thursday,
          :friday, :saturday, :sunday]
end

The key point here is that if the value is not known at before the class is evaluated it should be treated as an extreme code smell.

Here is  better but long example of how constants should be properly used: ActiveSupport::Timezone on Github.


Binary permissions system with bitwise operators + properties

I don't like how static and WET your class is.
You don't really need all the _rights, and you should probably remove the repetition in all your properties, except permissions.
I'd make a function to build properties for you.
Take the cmd property:

@property
def cmd(self):
    return self._perms & AppliancePerms._cmd_right

@cmd.setter
def cmd(self, boolean):
    if boolean:
        self._perms |= AppliancePerms._cmd_right
    else:
        del self.cmd

@cmd.deleter
def cmd(self):
    if self._perms & AppliancePerms._cmd_right:
        self._perms -= AppliancePerms._cmd_right

This is almost identical to the other two functions, the only difference is AppliancePerms._cmd_right.
And so if we were to want to write a function to build this then we'd start by replacing that, with a say variable bit.
Since you're using @property, rather than property I'm not sure how the del fn_name would work,
and so I'd change it to use the property function.
This means we can get:

def build_permission_property(bit):
    def get(self):
        return self._perms & bit

    def set(self, boolean):
        if boolean:
            self._perms |= bit
        else:
            delete(self)

    def delete(self):
        if self._perms & bit:
            self._perms -= bit

    return property(get, set, delete)

This works as you'd want, but I'd change the delete to use a bit mask.
Since it'll be a mask we can then use &=, and remove the branch.
To make the mask we need it actually really easy.
It's just ~bit and since Python's int's are 'infinite' it'll work on all numbers.
I'd also change get to return 1 or 0 as it stands it can return 0, 1, 2, 4, ....
Changing these can result in:

def build_permission_property(bit_index):
    bit = 1 << bit_index
    def get(self):
        return (self._perms & bit) >> bit_index

    def set(self, boolean):
        if boolean:
            self._perms |= bit
        else:
            delete(self)

    def delete(self):
        self._perms &= ~bit

    return property(get, set, delete)

And to use it is quite simple.
We just set the class' variable to the property.
I'd keep _num_of_rights, and would change the permissions getter to use str.format
And so could result in:

class AppliancePerms(object):
    def __init__(self, perm_digits=None):
        # Default to all permissions
        if perm_digits is None:
            perm_digits = (1 << type(self)._num_of_rights) - 1
        self._perms = perm_digits

    cmd = build_permission_property(0)
    rest = build_permission_property(1)
    ssh = build_permission_property(2)
    _num_of_rights = 3

    @property
    def permissions(self):
        return '{:0>{}b}'.format(self._perms, type(self)._num_of_rights)

    @permissions.setter
    def permissions(self, perm_digits):
        self._perms = perm_digits

    @permissions.deleter
    def permissions(self):
        self._perms = 0

This is quite nice, all you need to do is manually set the properties, and _num_of_rights to the amount.
But it's still too WET for me.
And so I'd use the more advanced Python feature of metaclasses.
This may not be good for developers that don't know Python too well.
I'd base this metaclass off one of martineau's answers on SO.

You can program this in two classes,
but I'd prefer three as then if you need more permission classes it's easy to implement.
These classes are:

Permission metaclass.
This will take a list from the class, and build the properties.
Base permissions class.
This will inherit the metaclass in a Python 2 and Python 3 friendly way. (the cross-Python metaclass inheritance is odd.)
It will also define the permissions property, and default _perms to zero, so subclasses don't have to.
Subclass.
This will be a domain specific class that provides the list of properties.
It will also define custom functionality, such as defaulting to all permissions.

This could become:

def build_permission_property(bit_index):
    bit = 1 << bit_index
    def get(self):
        return (self._perms & bit) >> bit_index

    def set(self, boolean):
        if boolean:
            self._perms |= bit
        else:
            delete(self)

    def delete(self):
        self._perms &= ~bit

    return property(get, set, delete)

class PermissionsMetaClass(type):
    def __new__(meta, classname, bases, class_dict):
        dict_ = class_dict.copy()
        dict_.pop('__module__', None)
        dict_.pop('__qualname__', None)
        for i, perm in enumerate(dict_.get('_permissions', [])):
            dict_[perm] = build_permission_property(i)
        return type.__new__(meta, classname, bases, dict_)

class Permissions(PermissionsMetaClass("Permissions", (object,), {})):
    _perms = 0
    @property
    def permissions(self):
        return '{:0>{}b}'.format(self._perms, len(type(self)._permissions))

    @permissions.setter
    def permissions(self, perm_digits):
        self._perms = perm_digits

    @permissions.deleter
    def permissions(self):
        self._perms = 0

class AppliancePerms(Permissions):
    _permissions = ['cmd', 'rest', 'ssh']
    def __init__(self, perm_digits=None):
        # Default to all permissions
        if perm_digits is None:
            perm_digits = (1 << len(type(self)._permissions)) - 1
        self._perms = perm_digits

I've provided both with and without a metaclass, as metaclasses are a bit harder to understand. And so it's up to you which design you'd rather use.
I mostly just recommend adding the function build_permission_property.


Automatically remove O365 license from AD user when using powershell

Not entirely sure if the code you have posted is exactly what you want reviewed but I am going to write this based on what I see.

Clear text passwords

Have to cover this one first to get it out of the way. I see that you have hardcoded a password. This is a bad practice of security though obscurity. Anyone opening the script via text will be able to see your credential set. While this is not always ideal I would suggest that you have your script prompt the user for credentials using Get-Credential.

Empty if clauses

  As you can see I have been using multiple conditions such as if, elseif, else

Yes, I can see that. However most of these blocks are empty with comments stating "Do nothing".

elseif (($ADuser.Enabled -eq $false) -and ($O365User.isLicensed -eq $false))
{
    #do nothing
    #"$ADuser.SAMAccountName has been already disabled and already without office 365 licence." | Out-File $LogFile -Append -Force

}

Why bother wasting CPU cycles on something that does not matter? I assume at one point you had code in there but now you don't so just remove those empty clauses.

Repeating code

At the start of your loop pass you have a call to Get-MsolUser.

$O365User = Get-MsolUser -UserPrincipalName $ADuser.UserPrincipalName

Then inside your loops you make that call again but it just go to standard output. Why bother getting the same information again? Nothing would have changed in that time. I would just removed those lines in your if clauses. If you wanted to see it on screen you could just write the line $O365User and that would save calling the cmdlet again.

Reducing if complexity

So of the remaining if clauses that acutally do something they are both doing the same thing! Removing a license via -RemoveLicenses "company:ENTERPRISEPACK". You seem to be doing this regardless of the user being enabled or not.

This is another part of the code that make me wonder if this is what you're actually doing or if you scrubbed it too much for this question. Either way I am taking if for face value here.

Instead of checking whether the user is enabled or not simply filter for $O365User.isLicensed and process those.

$userID = Import-Csv "c:\export\list.csv"
$LogFile = "C:\export\logs.txt"
foreach ($user in $userID)
{
    $ADuser = Get-ADUser -Filter "EmployeeId -eq $($user.EmployeeID)" -Properties whenCreated, Enabled, SAMAccountName
    $O365User = Get-MsolUser -UserPrincipalName $ADuser.UserPrincipalName
    if ($O365User.isLicensed){Set-MsolUserLicense -UserPrincipalName $ADuser.UserPrincipalName -RemoveLicenses "company:ENTERPRISEPACK"}
}

Error prevention

In your code and my snippet there is not error prevention built in. If there was a bad entry in the CSV or something along those lines the script would fail if it did not find a user. Consider using -ErrorAction SilentlyContinue and then checking if the variables contain data.

$ADuser = Get-ADUser -Filter "EmployeeId -eq $($user.EmployeeID)" -ErrorAction SilentlyContinue
if($ADUser){
    # Process as normal
} else {
    Write-Warning "No matching user for $($user.EmployeeID) was located."
}

You will notice that I dropped the properties parameter from your Get-ADUser call. Enabled and samaccountname are returned by default. While whenCreated is not, you don't use it either. True, the return in performance is likely not measurable - but if you don't use it just remove it.

Jobs and workflows

This can be a large subject so I will touch on it here. If you have 1000's of these entries to process you might want to have a look at jobs or parallel processing:

https://stackoverflow.com/questions/4016451/can-powershell-run-commands-in-parallel
https://stackoverflow.com/questions/8781666/run-n-parallel-jobs-in-powershell
about_foreach_parallel


This code is not exactly linear as member is a o(n) time function and grown in proportion to  curr-seq, making the whole function about O(n^2).

However without an algorithmic trick, the function requires a search of past results, and the best search that I know of on a mutable structure is O(log (n)), so the best you can hope for here is O(n*log(n)). But this is only if you go off to infinity.

This sequence seems reasonably dense, so you could probably create a boolean vector a bit bigger than the sequence initialized to true,and as you add numbers to the sequence flip the value of that index to false.

First to translate to scheme...

(define (recaman-seq size)
  (define (recaman-iter curr-seq n goal)
    (if (= n goal)
        (reverse curr-seq)
        (cond
          ((and (= n 0) (null? curr-seq))
           (recaman-iter (list n) (+ n 1) goal))
          (else
           (let* ((a      (- (car curr-seq) n))
                 (b      (+ (car curr-seq) n))
                 (is-new (not (member a curr-seq))))
           (cond
             ((and (positive? a) is-new)
              (recaman-iter (cons a curr-seq) (+ n 1) goal))
             (else
              (recaman-iter (cons b curr-seq) (+ n 1) goal))))))))
  (recaman-iter '() 0 (+ size 1)))

(recaman-seq 10) ]=>(0 1 3 6 2 7 13 20 12 21 11)

Next making some modifications, using a let to make a temperary vector,  changing the define and call with a named loop,

;lang rsr5

(define (recaman-seq size)
 (let ((rman-vect (make-vector (* 10 size) #t)))
;;hopefully generous enough
  (let recaman-iter ((curr-seq '()) (n 0))
;; goal is unneccesary, if and cond are essentially the same, nest them
    (cond ((> n size)
           (reverse curr-seq))
          ((and (= n 0) (null? curr-seq) (vector-ref rman-vect 0))
           (vector-set! rman-vect 0 #f)
;;Mark number as used, this is a side effect,not a returned value
           (recaman-iter (cons n curr-seq) (+ n 1)))
          (else
           (let* ((a      (- (car curr-seq) n))
                 (b      (+ (car curr-seq) n)))
             (cond ((and (> a 0))  (vector-ref rman-vect a)
                    (vector-set! rman-vect a #f)
                    (recaman-iter (cons a curr-seq) (+ n 1)))
             (else (vector-set! rman-vect b #f)
                   (recaman-iter (cons b curr-seq) (+ n 1))))))))))

Can get the first 500,000 terms that way before I run out of memory.


Polling like this is a very inefficient mechanism, but for pseudo-files in /sys/, you may find that the usual kernel interfaces as used by inotifywait and the like don't get notified of changes in the same way that they do for real storage-backed files.  So it may be that you need to poll, unfortunately.  But do check, for the files you care about.
There doesn't seem to be any value creating shutdownSignal to immediately use - simpler to just insert the value directly:
while [ $(</sys/class/gpio/gpio$SHUTDOWN/value) = 1 ]

sudo is intended for interactive use, and doesn't work well in scripts.  I think it's better to assume (or check) that the script is invoked with sufficient capabilities to do the work it needs to do.
Don't forget to add a shebang line (#!/bin/bash).


Splitting an array in 2 parts such that one part sums to a multiple of 10 and other sums to an odd number

You could simplify findSum. I would also rename the variables and reorder the parameters:

private int findSum(int[] nums, int i, int accum) {
    if (i == nums.length) {
        return accum;
    }
    return findSum(nums, i + 1, nums[i] + accum);
}

The end part of the ifGroupExistsThatSumsToValue method can also be simplified:

public boolean ifGroupExistsThatSumsToValue(int start, int[] nums, int target) {
    if (start == nums.length - 1) {
        return target - nums[start] == 0;
    }
    if (target == 0) {
        return true;
    }
    return ifGroupExistsThatSumsToValue(start + 1, nums, target - nums[start])
            || ifGroupExistsThatSumsToValue(start + 1, nums, target + nums[start]);
}

When logic is kind of tricky, like in this problem, it's good to add the examples in the problem statement as proper unit tests:

@Test
public void test_5_5_5() {
    assertTrue(splitOdd10(new int[]{5, 5, 5}));
}

@Test
public void test_5_5_6() {
    assertFalse(splitOdd10(new int[]{5, 5, 6}));
}

@Test
public void test_5_5_6_1() {
    assertTrue(splitOdd10(new int[]{5, 5, 6, 1}));
}

And then keep adding some more to try to cover all corner cases, for example:

@Test
public void testEmpty() {
    assertFalse(splitOdd10(new int[0]));
}

@Test
public void testSingleNum() {
    assertTrue(splitOdd10(new int[]{1}));
    assertFalse(splitOdd10(new int[]{2}));
    assertFalse(splitOdd10(new int[]{10}));
}

As others have pointed out, your formatting is awful. Please reformat nicely next time, Control Shift f in Eclipse does this easily, and any decent IDE has the equivalent.

To be honest, I don't really understand why splitOdd10 and ifGroupExistsThatSumsToValue have to be so complicated. If I simply follow the problem description in a straightforward way and just try to add up the numbers from left to right and check the conditions, I arrive at something that's much shorter and easier to understand:

private boolean splitOdd10(int[] nums) {
    return splitOdd10(nums, 0, 0, findSum(nums, 0, 0));
}

private boolean splitOdd10(int[] nums, int i, int left, int right) {
    return left % 10 == 0 && right % 2 == 1
            || i < nums.length && splitOdd10(nums, i + 1, left + nums[i], right - nums[i]);
}

I'm wondering if I'm missing something. Both your and my solutions are passing all my unit tests.


First, you should not be using Python 2 anymore, if at all possible. It will reach end of support at the end of the year.

In Python 3 your code would just be:

def all_eating_unicode_converter(input_string):
    """
    Converts every input to unicode.
    :param input_string: may be a string or unicode or bytes.
    :return: returns unicode

    Tested with: 'äöü', b'\xc3\xa4\xc3\xb6\xc3\xbc', u'äöü'
    """
    if isinstance(input_string, bytes):
        return input_string.decode("utf-8")
    return input_string

Note that I used isinstance instead of type, to also allow derived types of bytes to work properly.

I also shortened the logic by not insisting on having a single return from the function. Here it is clear enough what is happening, and I am in general a fan of early returns.

Docstrings only work when they are actually right after the function header, so I moved the testcases inside the docstring.

In addition, one reason the logging module is so powerful is that it allows you to write log messages which are costly to print and never print them. In other words the replacement of the placeholders is only performed if the message is actually being printed, i.e. if the log level is high enough. So you should always do this:

l.debug("type: %s\n message:%s",  type(input_string), input_string)


Your _patchfs and wrap_patchfs functions are virtually identical.  You don’t need the _patchfs version, just the internal one.  One function instead of two is easier to maintain:

def patchfs(_func=None, *,
            additional_skip_names=None,
            modules_to_reload=None,
            modules_to_patch=None,
            allow_root_user=True):
    """Your docstring here ..."""

    def wrap_patchfs(f):
        @functools.wraps(f)
        def wrapped(*args, **kwargs):
            with Patcher(
                    additional_skip_names=additional_skip_names,
                    modules_to_reload=modules_to_reload,
                    modules_to_patch=modules_to_patch,
                    allow_root_user=allow_root_user) as p:
                kwargs['fs'] = p.fs
                return f(*args, **kwargs)

        return wrapped

    if _func:
        if not callable(_func):
            raise TypeError("Decorator argument not a function.\n"
                            "Did you mean `@patchfs(additional_skip_names=...)`?")
        return wrap_patchfs(_func)

    return wrap_patchfs

The if not callable: ... ensures you don’t accidentally try to use @patchfs(names_to_skip).  Using * forces the remaining arguments to keyword only arguments; you cannot just list the four arguments, which makes the decorator a little less error-prone.

Your docstring's Usage:: examples lack the required def keywords for defining functions.


Passing variable to BackgroundWorker and use the same value later

BackgroundWorker already has a mechanism for passing and retrieving arguments.  The DoWorkEventArgs has a property for a passed in method argument and a property for the DoWork result.  The RunWorkerCompletedEventArgs has a property for retrieving the result.  No sub-classing is necessary, although you may need to make a custom container if you need to pass/return more than one object.

for (int i = 0; i < 10; i++)
{
  BackgroundWorker bw = new BackgroundWorker ();
  bw.WorkerReportsProgress = false;
  bw.DoWork += delegate(object sender, System.ComponentModel.DoWorkEventArgs eargs)
  {
    int i = (int)eargs.Arugment;  //get argument
    Console.WriteLine(String.Format("Thread {0} started", bw.value));
    System.Threading.Thread.Sleep(bw.value * 1000);
    eargs.Result = i;            //set result
  };
  bw.RunWorkerCompleted += delegate(object sender, System.ComponentModel.RunWorkerCompletedEventArgs eargs)
  {
    int i = (int)eargs.Arugment;  //get argument
    Console.WriteLine(String.Format("Thread {0} finished", i));
  };

  bw.RunWorkerAsync(i);
}


Efficiently returning the string basis on current datacenter

final is meaningless on static methods :

private static final String getHostNameOfServer() {

For the following :

// below if else, looks pretty  odd, may be it can be improved better?
if (f.equals(FlowTypeEnum.DEVICEFLOW)) {
    prefix = "/testdevice";
} else if (f.equals(FlowTypeEnum.USERFLOW)) {
    prefix = "/test";
}

there are 2 alternatives

make a getPrefix() method on FlowTypeEnum, reducing the above code to :

prefix = f.getPrefix();

FlowTypeEnum could then look like this :

public enum FlowTypeEnum {
    USERFLOW("/test"), DEVICEFLOW("/testdevice");

    private final String prefix;

    FlowTypeEnum(String prefix) {
        this.prefix = prefix;
    }

    public String getPrefix() {
        return prefix;
    }
}

make a map that maps the the FlowTypeEnum instances to a prefix, reducing the above code to :

prefix = mapToPrefix.get(f);

In both cases you might even inline the prefix variable.

Try to make code resistant to likely changes. In this case, server names and paths are likely to change. Pull these from config files.

All these static methods don't seem to be at home on the DatacenterEnum, they don't really operate on DatacenterEnum instances. Perhaps they need to find a home on a new class, where they can be non static.

It is unwise to hard code the data centers as enum instances. It simply won't scale. Renaming, removing or adding data centers in the field will require a new release.

Use more meaningful names for variables :

dc -> dataCenter
f -> flowType

Replace this :

currenthost.indexOf(namepart) >= 0

by the more readable :

currenthost.contains(namepart)


Very good. There are small things that could be improved.

It is possible to give window_length type std::iterator_traits<ForwardIterator>::difference_type. I think std::size_t is fine for most cases.

ForwardIterator begin,
ForwardIterator end

Usually those are called first and last.

if (window_length == 0)
{
    std::stringstream ss;
    ss << "Bad window_length: ";
    ss << window_length;
    throw std::runtime_error{ss.str()};
}

Well, the result of ss.str() is obvious :) It is possible to write constexpr there, or throw the string right into the constructor. Also, runtime_error is a good fit, but it has child called invalid_argument, which perfectly matches the case.

if (count < window_length)
{
    std::stringstream ss;
    ss << "The length of the range (";
    ss << count;
    ss << ") is too short. Must be at least ";
    ss << window_length;
    throw std::runtime_error{ss.str()};
}

I think that using std::stringstream is an overkill here. Throwing just "The length of the range is too short. It must be at least of length window_length" is pretty good by itself, since most IDEs will probably stop execution, so that programmers could have a look. Even if they had a catch for this, they would need to parse a string to be actually able to do something. I don't think it worth the troubles it brings.

Some caveats:

Currently if T = int the algorithm is going to produce somewhat incorrect results. May be you could write something like warning mechanism that will warn when integer type is used. I would consider #pragma message("your warning message here"). It might get portability problems but the code will still compile since unrecognized #pragmas are ignored.


Command Pattern with Undo , returning response in Invoker and Command class or Callback?

Excellent "by the book" realization of the command pattern with undo/redo ;)

Just 2 comments:

If receiver changes the state of the database, I would definitively handle the error case - the current implementation seems to ignore it. Imagine that undo fails (group was not deleted) and the previous command created the subscription. Then another undo (which tries to delete the subscription) also fails because there is still a group referencing the subscription.
Maybe it is a matter if taste, but I don't see a case where the implementation of execute and redo differs. Usually, I use only 2 methods do and undo where do will be used for execute as well as redo.

  Having Invoker and Command to return boolean indicating success or
  failure feels better. I have seen an example where they use callbacks.
  Is this something only for asynchronous operations or I can also use
  it here? Which would be better?

If a boolean (without error message) is enough, I would prefer the boolean return value because of its simplicity. Otherwise, I would even prefer something like an ErrorInfo object that contains a success flag and an optional error message (or even other information like the exception) as return value.

Another option is to throw an exception - may be also valid in your case. For that kind of error handling, the command should be executed before being pushed to the undoStack obviously.


Check whether a number is positive, negative, or zero

We should use the comparison operators.  Greater than, less than.

if dif > 0:
    print 'Player wins!'
elif dif < 0:
    print 'Computer wins!'
else:
    print 'Player and computer tie!'

Another option, which I'm led to believe is "more Pythonic" (although, I'm not a Python dev, so don't take my word for it...), looks like this:

def tie():
    print 'Player and computer tie!'

def player():
    print 'Player wins!'

def computer():
    print 'Computer wins!'

options = {
     0 : tie,
     1 : player,
     2 : player,
     3 : player,
     4 : player,
    -1 : computer,
    -2 : computer,
    -3 : computer,
    -4 : computer
}

options[dif]()

If explicit values are important, than this solution is probably good.  However, if you really only care whether a value is greater than, less than, or equal to a specific value, than a simple if/elif/else as I first demonstrated is a good option.

Note that this bottom option will run into a KeyError if dif is not in the range of expected values.  The if/elif/else will work for any number.


You have a compile error since MathObject has 2 identical substract methods; I assume this is a copy-paste error and the second should have Constant instead of MathObject as its parameter.

substract -> subtract.

MathObject only has abstract methods. If it is not going to give any common implementation, I would recommend making it an interface instead of an abstract class, as that would allow implementations to extend a different class as well.

Additionally, I would change evaluate() to doubleValue(), similar to the identically named method in the Number class. What if you want to have a CAS system that computes using BigDecimal, but you want to reuse your code?

Constant has a public final double c. That should be private; you (almost) never want to have a public field for a class.

The Big Problem

There is currently a rather big problem with your design: MathObject treats Constants differently from MathObjects. This should not be the case. Rather, the Constant class should comply with the MathObject interface:

public class Constant implements MathObject {
    private final double c;

    public Constant(double c) {
        this.c = c;
    }

    // Always add this when you override a method. It doesn't enforce anything
    // in Java's compile (unfortunately), but you will get a warning if you have
    // a method with @Override that doesn't actually override anything. However,
    // what this annotation does do is that it documents. If I come in and look at your
    // code, it is immediately clear to me that these methods are overriding
    // some parent method. Otherwise, I might look at this and think, "What is
    // this for?" For other examples, it can be clearer why @Override is useful,
    // but get in to the habit of always adding @Override
    @Override
    public MathObject add(MathObject that) {
        // This is an example of something you could do
        if (that instanceof Constant) {
            return new Constant(c + ((Constant) that).c);
        }
        return that.add(this);
    }

    @Override
    public MathObject subtract(MathObject that) {
        // return that.subtract(this);
        // Some implementation here
    }

    @Override
    public double doubleValue() {
        return c;
    }
}

So then MathObject would be:

public interface MathObject {
    MathObject add(MathObject that);

    MathObject subtract(MathObject that);

    double doubleValue();
}


review

comparison

no need to compare against True or False. (begin == True) can be easier expressed as begin and (end == False) as not end. and comparison chaining is done with and, not &(bitwise and)

iteration

In python, it is very seldomly needed to iterate over the indices. Instead of for y in range(len(array)): and for x in range(len(array[0])), you can do

for row in array:
    ...
    for x, element in enumerate(row):
        if element == 0 and begin and not end:

alternative solution

try to vectorise as much as possible. The easiest thing to do is count the zeroes in front and at the back:

def count_zeroes(array):
    return (array.cumsum(axis=1) == 0).sum(axis=1)

zeroes_front = count_zeroes(array)

and then the same for the reverse:

zeroes_back = count_zeroes(test_data[:,::-1])

The amount each row needs to roll is:

roll = (zeroes_front + zeroes_back) //2 - zeroes_front

array([ 0, -1, -2, -2])

and then you apply this roll over each row:

np.array([np.roll(row, r) for row, r in zip(test_data, roll)])

array([[0.   , 0.149, 0.064, 0.736, 0.   ],
       [0.   , 0.258, 0.979, 0.618, 0.   ],
       [0.   , 0.786, 0.666, 0.   , 0.   ],
       [0.   , 0.782, 0.954, 0.   , 0.   ]])

in total:

def centre(array):
    zeroes_front = count_zeroes(array)
    zeroes_back = count_zeroes(array[:,::-1])
    roll = (zeroes_front + zeroes_back) //2 - zeroes_front
    return np.array([np.roll(row, r) for row, r in zip(array, roll)])


I think the dictionary is overkill.  Plus adds a lot more code with the TryGet.  I would make a class to help and hide the magic strings.

As a side note magic strings should be made into constants so they are maintained in one place and if a typo you just need to fix it in one place.    Also having a 1 or 2 being passed in also seems magic to me. I would make that into an enum.  If we left it as an int then when coming back I have no idea what values I can pass in.  Is negative numbers allowed?  What about 9999?

public enum RefNumber
{
    One = 1,
    Two = 2,
}

I'd create a class to hold the magic strings

public static class ControlsNames
{
    private const string GenericPrefix = "coolControl";
    private const string DepartmentSufix = "Department";
    private const string JobTitleControlSuffix = "JobTitle";
    private const string DirectDialControlSuffix = "DDI";
    private const string EmailDialControlSuffix = "Email";

Looking at your example you always format with the Prefix then refnumber then optional suffix.  I'll make a method in the class to handle that for us

private static string FormatName(string suffix, RefNumber refNumber)
{
     return string.Concat(GenericPrefix, (int)refNumber, suffix);
}

Now we just need to make an easy way to know what suffix we need. I'm going to make some static methods that will do that for us and return back the string.  The only exception is Generic we don't want a suffix but we can just pass in string.empty

public static string Generic(RefNumber refNumber)
{
    return FormatName(string.Empty, refNumber);
}

public static string Department(RefNumber refNumber)
{
    return FormatName(DepartmentSufix, refNumber);
}

public static string JobTitle(RefNumber refNumber)
{
    return FormatName(JobTitleControlSuffix, refNumber);
}

public static string DirectDial(RefNumber refNumber)
{
    return FormatName(DirectDialControlSuffix, refNumber);
}

public static string Email(RefNumber refNumber)
{
    return FormatName(EmailDialControlSuffix, refNumber);
}

Now we don't have any dictionary or TryGets and the code looks like this now

public void DoStuffWithControls()
{
    string genericControl1 = ControlsNames.Generic(RefNumber.One);
    string genericControl2 = ControlsNames.Generic(RefNumber.Two);
    string departmentControl1 = ControlsNames.Department(RefNumber.One);;
    string departmentControl2 = ControlsNames.Department(RefNumber.Two); ;

    EnquiryForm.GetEnquiryControl(genericControl1, EnquiryControlMissing.Exception).Value = "some value";
    EnquiryForm.GetEnquiryControl(departmentControl1, EnquiryControlMissing.Exception).Value = "some value";
    EnquiryForm.GetEnquiryControl(genericControl1, EnquiryControlMissing.Exception).AnotherProperty = "some other value";
    EnquiryForm.GetEnquiryControl(genericControl2, EnquiryControlMissing.Exception).Value = "some value";
    EnquiryForm.GetEnquiryControl(genericControl2, EnquiryControlMissing.Exception).AnotherProperty = "some other value";
    EnquiryForm.GetEnquiryControl(departmentControl2, EnquiryControlMissing.Exception).Value = "some value";
}


Performance: repeated sweep through large binary dataset

You did not provide any performance measurements, so every answer here is basically guesswork, but I suspect that the lack of speed you are experiencing could have something to do with std::vector<bool>.

The problem is that std::vector<bool> is not really what it appears to be. While a vector of any other type actually works in units of bytes, the specialization for bool works with individual bits, packing them as tightly as possible. This is, of course, great if you want to reduce memory usage, but it also is really slow since you have to mask and shift bits around every time you want to access a value.

For this reason, in combination with the fact that it doesn't behave like a normal vector in certain cases (which are, sadly, not exactly rare), std::vector<bool> is mostly seen as a design flaw in the standard library and does not see much use.

You should try to replace std::vector<bool> with a similar fitting type, e.g. std::vector<char>, and measure that to determine whether and by how much this alleviates your issue.

If you are not convinced yet, here is a quick-and-dirty benchmark to show just how much slower std::vector<bool> is.


Implementing console.table in JavaScript

Here are some things that can be improved

Naming:

toTable is expressive but also confusing. It looks like it is converting something to table. When used in conjunction with HTML this could be confused with <table>. Adding comments to the function can be helpful to understand what the function is doing. But again, if comments are needed that means you're not naming variables correctly.
obj the short of object is descriptive when used for naming object. However, for this function it is wrong as the function is expecting an array. arr or array would be better.
arr Again, the variable is used to store a string. str can be used or some developers even use str as prefix e.g. strTable, strLine.

Repetitive Code:

'--------------------------\r\n' is used three times in the code. You can create a variable to store this string value and use it anywhere to add the line of hyphens.

for loops:

for loops is used three times in the code. Nested loops should be avoided. There are very few cases when nested loops are required. Always try to avoid nested loops wherever possible.

In the first loop, the keys of the object are joined using tab character.

for (let [key, value] of Object.entries(obj[0])) {
    arr += ' ' + key + '\t';
}

This can be done using Object.keys() which returns an array of keys. Then Array#join can be used on keys array to join the array elements by glue-\t in this case.

So, the new code will be

Object.keys(arr[0]).join('\t') // That's it!

The other nested loop will be slow if object is having large number of properties.

for (let i = 0; i < obj.length; i++) {
    arr += '\r\n--------------------------\r\n';
    for (let [key, value] of Object.entries(obj[i])) {
        arr += ' ' + value + '\t\t';
    }
}

Looking at it carefully shows that this only create a string of values separated by tab. Object.values can be used for this. But again, as the objects are inside array, it need to be iterated over and then values can be extracted from object. New code using this function will look like

arr.forEach(function(obj) {
    someVar += line + Object.values(obj).join('\t\t'); // Sweet!
});

Apart from these, below are some suggestions:

Using console.table consistently: If console.table is supported by target environment then why not use the beautiful function? Although, this function(toTable() from question) is not complete as it doesn't support printing object in table, object containing different keys, nested object, etc. For the basic implementation, it can override default method.

if (!console.table) {
    // Use fallback only when not available
    console.table = function(arr) {
        // Code here
    };
}

Creating the horizontal line dynamically.

The horizontal line is static. In case when the object contain less/more properties, it'll not fit correctly. To create the line dynamically again, Object.keys() can be used.

'-'.repeat(8 * keys.length) // Assuming a tab(\t) is eight characters long

Using monospace font to log data

For non-monospace fonts not all characters occupy same space. For example, i takes less space than O. console.log can be set with custom font using the second parameter which is CSS styles.

console.log('%c' + someString, 'font-family: monospace');

Here's code with these changes

if (!console.table) {
    console.table = function(arr) {
        'use strict';

        let keys = Object.keys(arr[0]);
        const horizontalLine = '\r\n' + '-'.repeat(8 * keys.length) + '\r\n';
        let heading = Object.keys(arr[0]).join('\t');

        let str = horizontalLine;
        str += heading;

        arr.forEach(function(obj) {
            str += horizontalLine + Object.values(obj).join('\t\t');
        });
        str += horizontalLine;
        console.log('%c' + str, 'font-family: monospace');
    };
}

let arr = [
    { firstName: 'Sirwan', lastName: 'Afifi', age: 27 },
    { firstName: 'Person2', lastName: 'P2', age: 32 }
];
console.table(arr);

Here's fiddle to try out it.

And here's output of the above code

------------------------
firstName   lastName    age
------------------------
Sirwan      Afifi       27
------------------------
Person2     P2      32
------------------------

Note:

As some of the features are only available in latest browsers/nodeJS version and some are experimental, see the MDN link embedded for browser support and polyfill.
This, by any means is not polyfill for console.table. This is just another version of the OP's code. console.table is overriden with assumptions that only the provided input format is used to log in table.
The horizontal lines are not perfect. They can contain less/more depending on the min and max length of key in the object.


Searching for an object in a list returning boolean and referencing variable

The List type provides a List-specific Exists method which will return a boolean telling you whether a value that meets the specified predicate exists in the list:

var found = Accounts.Exists(a => a.Name == tBox_wName.Text);

Instead of using that though, just use Find(predicate) to return the first value for which the predicate returns true (or the type's default value if not found which is null for reference types).

Array has similar methods.

If you're using any IEnumerable you can use .Any() or FirstOrDefault().

If I was rolling this by hand (which in your case I don't believe is necessary), I'd prefer the following pattern:

Account account;
if(TryFindAccount(accounts, out account))
{
    ....
}

or

Account account;
if(TryFindAccountByName(accounts, name, out account))
{
    ....
}

Unless you really needed to track by index across layers (for which I don't usually find a compelling reason to do so), I'd deal directly with the account as soon as possible.

The above implementation also avoids checks against magic values, like checking if account is null, or in your example, -1. If you can, avoid attributing special meaning to certain values.


Find sum of number of times that each character of source occurs in the target

Your code is neat, well structured, and generally very readable. People solving this problem are often beginners, and your code, for a beginner, is good.

My only style complaint is the use of a for the array variable name.

Your algorithm is technically a nested loop. You loop through each character in the source, and for each of the source characters, you loop through the characters in target.

Note that the indexOf function is essentially a loop, it starts at the start index, and loops until it gets to the end, or the character. Your while loop is just a way to 'pause' the loop at significant places.

So, your algorithm will scan the target one time for each source character. Each time there is a match, you increment the occurrences.

Your algorithm could be made more apparent if you were to make the inner loop more obvious:

for (int j = 0; j < target.length(), j++) {
    if (target.charAt(j) == a[i]) {
        occurrences++;
    }
}

That makes the logic more visible, and removes the call to indexOf....

Obviously, it would help to convert the target to a char array outside the loop:

char[] tchars = target.toCharArray();

and then the inner loop would be:

for (int j = 0; j < tchars.length, j++) {
    if (tchars[j] == a[i]) {
        occurrences++;
    }
}

There is a potential bug with your solution.... if a character is duplicated in the source, you will double-count it in the result.

You will want to deal with that.

There is also a possibly more efficient algorithm which would be useful for large strings, but, with anything less than say 100 chars, I would not bother. That algorithm would require setting up a HashMap or other data structure from the source chars, and then just looping once through the target chars to get the counts.


Optimizing/Cleaning up Python Script for Zipf's Law

I must confess that I do not understand what you're trying to achieve and how Zipf's law come into play !
But I've some suggestions about the code itself :

Use meaningful variable names.
Concatenating strings only to split the result afterward is terribly costly, for no advantage.
Instead, use meaningful data structures. You deal with a sequence of (count, title) pairs. Flattening that and playing with index parity is confusing.

So, here is my take on it :

import sys
from operator import itemgetter

def main(source = sys.stdin):

   nb_in, nb_out = (int(x) for x in source.readline().split())

   #(lazely) collect Count and Title.
   data = ( source.readline().split() for i in range(nb_in) )

   #multiply each count by rank.
   answers = [ (title, int(count)*(rank+1)) for (rank, (count, title)) in enumerate(data) ]
   answers.sort(key = itemgetter(1), reverse = True)

   for title, _ in answers[:nb_out]:
      print title

main()


Wrong bounds

Your filters on your day/month aren't right:

day = [i for i in (x,y,z) if i < 31]
month = list(set(i for i in (x,y,z) if i < 12))

31 is a valid day and 12 is a valid month, so those should be <=. Additionally, you're not excluding negative numbers - so you'll want 1 <= i <= 31 for the first filter and 1 <= i <= 12 for the second.

Dealing with the tuple

Since just about everywhere you deal with (x,y,z) as a tuple, I would just keep it as a tuple the whole way and not unpack it. You only unpack it to check the length, so we can just make that check explicit. Also, if I passed in something like 1/2/3/4/5, you'd tell me that my date was too short, so this can get both right:

elems = un_ambiguous_date.split('/')
if len(elems) != 3:
    raise ValueError("The date is too {}, format should be X/Y/Z".format(
        'short' if len(elems) < 3 else 'long'))

try:
    elems = map(int, elems)
except ValueError:
    raise ...

day = [i for i in elems if 1 <= i <= 31]
# etc.

The last join

Instead of:

return '/'.join(map(str, (day[0], month[0], year[0])))

I would just use format:

return '{}/{}/{}'.format(day[0], month[0], year[0])

It's shorter and more readable.

Combine the last two checks

I would write a helper function that returns the first element of a single-element list:

def front(lst):
    if not lst:
        raise ValueError("The date cannot be valid")
    if len(lst) > 1:
        raise ValueError("Ambiguous date was given")

    return lst[0]

And then you can just write:

return '{}/{}/{}'.format(front(day), front(month), front(year))


Remaking std::to_string in C++ with UDLs (User Defined Literals)

I'm ignoring all the testing stuff, and just focusing on the two conversion functions.

std::string operator"" _str(unsigned long long int num)
{
    std::deque<char> digits;

There's really no need for the deque. You can push_back() all the digits directly into a std::string, and then use std::reverse().

To make it even better, you could use the max value of an unsigned long long and calculate the maximum number of digits you'll need, then use reserve(). But that probably won't net you any real gains in reality, since you'll likely always be under the small-string optimization size where std::string won't actually allocate any memory... another reason to ditch the deque and stick with strings.

for(char i = 0; num != 0;num = num / 10)

Have you tested your conversion functions with zero? Because if num is zero, this loop won't fire at all, and digits will be empty. So "0"_str will result in "".

This is a pretty weird and confusing loop in general. i looks like it's going to be some kind of loop counter, but it's not. All-in-all, this just looks like a case of trying to be too clever, and outsmarting yourself (due to the zero issue).

This could be expressed much more simply and clearly as something like:

do
{
    digits.push_front('0' + (num % 10));
    num /= 10;
} while (num != 0);

and it won't have the zero bug. (do loops are less common than while, but the reason to use one here - and this should be documented in a comment - is to guarantee that even if num is zero, the loop will fire at least once.)

{snipped section about digit character codes}

std::string converternum;

I already mentioned that the deque is unnecessary, but if you're really going to use it, you should take advantage of the fact that you know digits.size(), and use reserve() for this string to prevent unnecessary allocations.

char * operator"" _cstr(unsigned long long int num)

This function is mostly identical to the first one, and thus has the same problems. Again, I would ditch the deque and just work with a string. The digits will be in reverse order, but in this case you can fix that with std::reverse_copy() when you copy them into your output buffer.

char * string = (char *)converternum.c_str();
return string;//converternum.c_str();

Here is where you get into real trouble.

First, never, ever use C-style casts. In this case, you've cast away the constness of c_str()... that's bad. Prior to C++17, if you want a non-const pointer to std::string's data, you have to jump through some hoops - you have to do something like &convertnum[0] or &convertnum.front() - and I agree that's a pain. But casting away constness is a red flag that won't pass most code reviews, because it is extremely dangerous.

Second, you are taking a pointer to convertnum's internal data, and returning that... even though convertnum is being destroyed. In other words, you are returning a pointer to freed memory, which is UB.

How do you solve these problems? Well, the don't answer is: Don't use C-style strings. In other words, don't have a _cstr UDL. It's only going to give you grief (it already has!).

But if you really, really must... one option is to do what @hoffmale suggests, and instead of char*, return std::unique_ptr<char[]>. That might look something like this:

char* operator"" _cstr(unsigned long long int num)
{
    auto digits = std::string{};
    do
    {
        digits += '0' + (num % 10);
        num /= 10;
    } while (num != 0);

    auto p = std::make_unique<char[]>(digits.size() + 1);

    std::reverse_copy(digits.cbegin(), digits.cend(), p.get());
    p[digits.size()] = '\0'; // have to manually add the null terminator

    return p;
}

The problem with that is you're now longer returning a C-string, which makes "_cstr" kind of a lie.

So another option is to have some kind of storage with a lifetime longer than the function that will retain the memory for you. Something like:

char* operator"" _cstr(unsigned long long int num)
{
    // Note: you *can't* use a vector<string>, because string's
    // memory may be invalidated on moves, like if the vector
    // resizes.
    static auto storage = std::vector<std::unique_ptr<char[]>>{};

    auto digits = std::string{};
    do
    {
        digits += '0' + (num % 10);
        num /= 10;
    } while (num != 0);

    auto p = std::make_unique<char[]>(digits.size() + 1);

    std::reverse_copy(digits.cbegin(), digits.cend(), p.get());
    p[digits.size()] = '\0';

    // Get the char*, and then move the unique_ptr into storage
    // to let it be managed there.
    auto result = p.get();
    storage.push_back(std::move(p));

    return result;
}

This will "work", and it's basically what some C libraries do (when they don't simply leak). But with no way to release the memory, it will just grow and grow. You could add a mechanism to release the memory, but you would need a way to be sure it's safe for every string. This solution is possible, but unwieldy.

The last solution - the worst case (other than outright UB) - is to define some sort of contract that client code must follow. In plain English, document the function by saying "you must delete[] the memory when you're done with it". That requires programmers to behave, and is very easy to break, so it is not recommended. But... if you really want a C-string function, it's an option. A bad one, but an option nonetheless.

Summary

You have one critical error in your code:

In ""_cstr(unsigned long long), you return a pointer to the internal memory of a std::string that gets destroyed at the end of the function, meaning you're returning a pointer to invalid memory.

You have a couple of logical errors in your code:

Both functions will return an empty string when the number is zero, instead of "0".

You have a few inefficiencies:

You use deques because you want to add the numbers in reverse order, and reason that makes sense because neither strings nor vectors have push_front(). But that's all unnecessary. You can simply push_back() directly into your result string, and then use std::reverse(). (Or push_back() into a string buffer, and std::reverse_copy() into your final buffer.)

And here are some tips to keep in mind:

It's really good that you're doing testing, but if you're going to do that, you might as well go all in and use something like Google Test. It's header-only, a single include, and it produces very pretty output. A full battery of tests can give you great confidence in your code. Using Google Test might look something like (fair warning, I don't actually use Google Test that often):

TEST(StrTest, HandlesZero) {
    EXPECT_EQ(0_str, "0");
}

To test that the types are right, rather than trying to demangle the names (which, by the way, it's been a long time since I've used abi::__cxa_demangle(), but I'm pretty sure you're not using it correctly), it's so much easier to just use type traits:

TEST(StrTest, ReturnType) {
    EXPECT_TRUE((std::is_same_v<decltype(0_str), std::string>));
}

Another dirty trick you can use to examine types is deliberately generating errors:

template <typename T>
struct TD; // note, never define TD

TD<decltype(0_str)> t; // will trigger an error

The error generated will print the exact type of whatever is in the angle brackets, on every compiler. This is a hackish way to check types, but it can help when you're experimenting.


OOP design of code representing units of measurement

raise TypeError, "Units derived from %s and %s are incompatible." % (self.base_unit)

The python style guide recommends raising exceptions in the raise TypeError(message) form. TypeError is also questionable as the correct exception to throw here. The error here doesn't seem to be quite the same as making inappropriate use of python types. I'd have a UnitError class.

def __repr__(self):
     return "%s (%s)" % (self.name, self.suffix)

__repr__ is supposed to return either a valid python expression or something of the form <text>

base = BaseUnit("Cubic metres", "m3")

I'd make a global cubic meter object

My overall thought is: do you really need this? My inclination would be to convert all data to  the correct units as I read it. That way all data in my program would be using consistent units and I wouldn't have to worry about whether data is in some other exotic unit. Of course, depending on your exact scenario, that may not be a reasonable approach.


I will focus on the get_date() method. First of all, what sort of date is it? Currently the name makes me think it will get the current date, but it's sort of a banking date? Something along the lines of get_last_banking_day() would be more descriptive?
You can move the return to the end of the function as that is the same in both blocks of the if/else:
def get_last_banking_day(): # Date -1 day unless Monday then -3 days
    d = datetime.date.today()

    if d.weekday() == 0:
        date = d - datetime.timedelta(days=3)
    else:
        date = d - datetime.timedelta(days=1)

    return date

You could clean up the import and only import the 2 things needed from datetime, date and timedelta.:
from datetime import date, timedelta

The function would become:
def get_last_banking_day(): # Date -1 day unless Monday then -3 days
    d = date.today()

    if d.weekday() == 0:
        date = d - timedelta(days=3)
    else:
        date = d - timedelta(days=1)

    return date

Now we can look at variable names and do some cleanup, especially the d variable. Always try to avoid non-descriptive names:
def get_last_banking_day(): # Date -1 day unless Monday then -3 days
    today = date.today()

    if today.weekday() == 0:
        last_banking_day = today - timedelta(days=3)
    else:
        last_banking_day = today - timedelta(days=1)

    return last_banking_day

As the today - timedelta(days=1) is the default we use it as such and set the value to this and only use an if-statement to set the exception:
def get_last_banking_day(): # Date -1 day unless Monday then -3 days
    today = date.today()
    last_banking_day = today - timedelta(days=1)

    if today.weekday() == 0:
        last_banking_day = today - timedelta(days=3)

    return last_banking_day


A method which, given a string, returns a string in which each character is separated by an asterisk

Well, you've used recursion, but I wouldn't say that's a recursive solution because you have variables outside your functions that control what your functions do.

A recursive solution will have a function that is repeatedly called with smaller and smaller sub-problems, terminating in a base case, that together will accomplish your goal. A key aspect of recursive solutions is that the recursive function returns a value - your method is void and so returns no value.

As a first step, discard your index variable entirely. At each recursive step, call BuildNewString with a smaller version of the same problem. Combine the results in such a way as to produce the desired result.


Remove Empty String array from ArrayList

There are a few tricks you can use to improve this code.

First of all,

List<String[]> someList = (List<String[]>) csvMappedData.get(Constants.CSV_DATA);
List<String[]> cloneCSV = new ArrayList<String[]>(someList);
for (String[] csvSingleLine : cloneCSV) {

I understand that you're using this "copy the list"-approach to avoid a ConcurrentModificationException, but instead of doing that you can use an Iterator.

List<String[]> someList = (List<String[]>) csvMappedData.get(Constants.CSV_DATA);
Iterator<String[]> iterator = someList.iterator();
while (iterator.hasNext()) {
    String[] strings = iterator.next();
    if (stringsShouldBeRemoved) {
        iterator.remove();
    }
}

Now, as for your code to check for whether to remove a String[]:

List<String> strings = new ArrayList<String>(Arrays.asList(csvSingleLine));
strings.removeAll(Arrays.asList(null, ""));
if (strings.isEmpty() || Validator.isNull(strings)) {
    someList.remove(csvSingleLine);
}

Again, you're using a copying-approach. To check for whether or not an object fulfills a criteria, you don't need to copy it, modify it, and check if it fulfills another criteria. Copying it and modifying it makes it slower and uses more memory.

Instead, let's use a method:

boolean shouldRemoveCSVSingleLine(String[] csvSingleLine) {
    for (String str : csvSingleLine) {
        if (str != null && !str.equals("")) {
            return false;
        }
    }
    return true;
}

Now you can use this method in the while(iterator.hasNext()) loop:

List<String[]> someList = (List<String[]>) csvMappedData.get(Constants.CSV_DATA);
Iterator<String[]> iterator = someList.iterator();
while (iterator.hasNext()) {
    String[] strings = iterator.next();
    if (shouldRemoveCSVSingleLine(strings)) {
        iterator.remove();
    }
}


These observations are for the most in the order of the code

  At this point, the user will probably want to know if this system is Long Mode capable, which is indicated by the word CPUID in green. This is determined by attempting to toggle bit 21 in EFLAGS.

Seeing "This is determined by..." makes this paragraph somewhat mis-leading because it would seem that Long Mode capability is determined merely by looking at EFLAGS[21]. Your code correctly does it in a 3-step process, but that's not something that the reader sees right away. People with less time on their hands might have given up reading already!

push     bp
mov      bp, sp
...
or       [bp-6], 20H
...
pop      bp

You've used the BP register to set a bit in a stacked number. This can be optimized by writing or [esp+2], 20H. Although this instruction requires 2 extra bytes (ASP prefix and SIB byte), you gain 4 bytes from dropping the push, mov, and pop instructions.
There's a trade off here. If in a similar situation, you were to manipulate several stacked values in a row then using BP would be shorter.

bt       ax, 5           Is bit 21 on
jnc      603             No if CY=0

Bit 5 lives in the AL register. Testing to see if it is on or off can be shortened by not using the double opcode instruction BT. Best choice here is the Modr/m byte less instruction test al, imm8.

test    al, 20h
jz      603          ;Bit 21 is off

5DF  66B801000080      mov      eax, 0x80000000 Ext Func supported?

Noticed the discrepancy between the dump and the instruction's immediate?
If you copy/pasted this code then there's something amiss with the disassembler, else it's a typo.

push     eax
cpuid
pop      ecx
cmp      eax, ecx
jna      603         AX >= 80000001H
mov      [bp], YELLOW
mov      al, 1       AX = Read feature bits
cpuid
bt       edx, 29     Long Mode?
jnc      603

With the instruction mov al, 1 you're avoiding to have to write the much longer mov eax, 80000001H. Very understandable but the 1 byte inc ax would still be shorter.
There's also some danger lurking in this code snippet. Who is to say that Intel/AMD in future iterations of the processor will not be returning non-zero values in EAX[8,31] ? Already today some leaf numbers aren't used.

push    eax           ;(1)
cpuid
xchg    ecx, eax      ;Result from CPUID
pop     eax           ;(1)
cmp     ecx, eax
jna     603
mov     [bp], YELLOW
inc     ax
cpuid
bt      edx, 29     Long Mode?
jnc     603

By popping exactly 80000000h, you guarantee that the inc ax will produce the desired 80000001h.
I've used xchg ecx, eax because it's 1 byte shorter than mov ecx, eax.

mov      bx, cx
mov      bl, [bp]        Selected color

Since the first instruction just wants to zero the BH register, you could shave off 1 byte by writing:

movzx    bx, [bp]        Selected color

push      di
push      si
lodsw
neg       ax
stosw
cmp       [si-2], ax   If equal A20 is off
pop       si
pop       di

When I first saw this use of string primitives I expected to see a range of addresses to be compared, but you only process a single word. Next code then uses less instructions and is a few bytes shorter. Note the use of the Segment Override Prefix.

mov     ax, [si]
neg     ax
mov     [es:di], ax
cmp     [si], ax

Using the previous code you can also stop using DI and shave off another 4 bytes since you know that DI=SI+16:

mov     ax, [si]
neg     ax
mov     [es:si+16], ax
cmp     [si], ax

One final point about this code is about the use of neg. The negation of zero is also zero. That's why this kind of testing often uses not which guarantees the value gets modified.  This doesn't impact your code however since you've chosen an address that certainly does not contain zero. But choosing a fixed address like eg. 21h*4 (DOS isn't loaded for sure) would make setting up SI much shorter and even allow you to not use SI at all.

mov     ax, [0084h]
not     ax
mov     [es:0084h+16], ax
cmp     [0084h], ax

61F  81C66000          add       si, 60H       Offset from CS

I don't know what happened here, but I think the compiler ought to give you the sign-extended version of this instruction automatically. Bytes 83h,C6h,60h.

648  49                dec       cx
649  75E4              jnz       62f        Execute test again

This of course is just loop. 1 byte shorter.

My last concern

6D4  B21C              mov       dl, 0x1c

You didn't initialize the DH register because you know it has the correct value from the code above. That's fine but given the separation between setting it up and using it, and considering the note you've included, ...

  NOTE: There is 125 bytes reserved here for additional methods of enabling A20.

... I wonder if you will remember to preserve DH the day you're ready to add these additional methods?


I use Jon Skeet's version of a thread safe Singleton with fully lazy instantiation in C#:

public sealed class Singleton
{
    // Thread safe Singleton with fully lazy instantiation á la Jon Skeet:
    // http://csharpindepth.com/Articles/General/Singleton.aspx
    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return Nested.instance;
        }
    }

    class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        internal static readonly Singleton instance = new Singleton();
    }
}

It works wonders for me! It's really easy to use, just get the instance from the Instance property like so; SingletonName instance = SingletonName.Instance;


Remove duplicates from an unsorted Linked List in Ruby

Alternatives

There are other alternatives (spoiler alert) with around the same time complexity, that adhere to the specification of in-place removal.

Review

  This is in \$O(n)\$.

I'm not sure it is. The outer iteration while (node = node.next) is \$O(n)\$.

while (node = node.next)
  h[node.data] += 1
  if h[node.data] > 1
    previous_node = find_previous(node.data)
    previous_node.next = previous_node.next.next
  end
end

And find_previous(data) is \$O(\log{n})\$.

 def find_previous(value)
    node = @head

    return false if !node.next
    return node if node.next.data == value

    while(node = node.next)
      return node if node.next.data == value
    end
 end

This makes remove_duplicates to be \$O(n\log{n})\$.

If you keep track of the previous node while iterating the nodes, you could optimize your algorithm to be \$O(n)\$, but as you are using a hash table, it fails to meet the requirements of the challenge.


The PriorityQueue was no good idea. What are you doing?

After the nth element, you copy all the previous n-1 elements into a temporary queue, which has complexity \$O(n)\$. Then you drain half the queue, which has complexity \$O(n \log n)\$. Summed up you get \$O(n^2 \log n)\$.

You're just misusing the queue as a sorting vehicle. That's not optimal as Arrays.sort has a faster algorithm (quicksort is faster, except when it goes wrong and this one tries pretty hard to avoid going wrong).

It would be probably faster to use an int[], track the size manually and re-sort the array after each element added. This has the same complexity, but could be faster as you at least avoid the copying.

Inserting the element in the proper position would lead to a total complexity of \$O(n^2)\$.

A much faster solution (I hope \$O(n \log n)\$) could be implemented using a TreeSet with higher and lower. There are also smart algorithms allowing to compute median without sorting the collection as you sort of need to sort only the middle part.

Review

public static float calculateMedian(PriorityQueue<Integer> pq) {

Don't use float unless you really have to conserve memory. They're pretty imprecise and they're no faster than double, at least on modern Desktop CPUs.

    int halfQueueSize = (temp.size() >> 1);

    if(temp.size() % 2 != 0) {

Do you optimize division by 2 as shift or don't you? Note that it hardly matters as this is surely not the most time-consuming operation here.

    if(temp.size() % 2 != 0) {
        while(index++ <= halfQueueSize) {
            number = temp.poll();
        }
        return number;
    } else {
        while(index++ < halfQueueSize) {
           number = temp.poll();
        }
        return ((number+temp.poll())/2.0f);
    }

You really shouldn't have two nearly identical branches. It makes it hard to spot the difference. With something like

    int halfQueueSize = (temp.size() >> 1) + (temp.size() & 1);

you can use < in both branches and pull the loop out.


There's not much weak points I can see.

The biggest one is the way to use it. One needs to declare a variable to be caught in the block (closure), and I think it's unnecessary. You should be able to do this:

  Repeater.new do
    event_present_in_database
  end.until do |result|
    result
  end.repeat(times: 10, delay: 0.1)

If you changed the break like like this:

  break if @until_block.present? && @until_block.call(result)

The second, tiny point would be: make it clearer to understand the extraction to method conditionals:

  # ...
  break if exit_criteria_satisfied?(result)
  # ...

  private
  def exit_criteria_satisfied?(result)
    @until_block.present? && @until_block.call
  end

That's all I got. The rest of the code seems pretty clear to me.

  I know Ruby has all sorts of tricks

Yeah, but I don't know a single one that could help with the readability here.


I would suggest to:

Define an interface with a method that will be called inside every case, e.g.

public interface ServiceMethod {
    public void execute();
}

Create a map that will contain contain instances of ServiceMethod findable by the a String key, e.g.:

Map<String, ServiceMethod> serviceMethodMap = new HashMap<>();

Fill up the serviceMethodMap map with ServiceMethod instances (this is to avoid the switch), e.g.:

serviceMethodMap.put("getTemperature", new ServiceMethod() {
    public void execute() {
        getDeviceTemp();
    });
serviceMethodMap.put("getBrightness", new ServiceMethod() {
    public void execute() {
        getBrightness();
    });

Finally replace the switch with:

final ServiceMethod serviceMethod = serviceMethodMap.get(methodName);
if(serviceMethod != null) {
    serviceMethod.execute();
}

Update 2/18/2015, added Java 8 support

Define an interface with a method that will be called inside every case, e.g.

@FunctionalInterface
public interface ServiceMethod {
    public void execute();
}

Create a map that will contain contain instances of ServiceMethod findable by the a String key, e.g.:

Map<String, ServiceMethod> serviceMethodMap = new HashMap<>();

Fill up the serviceMethodMap map with ServiceMethod instances (this is to avoid the switch), e.g.:

serviceMethodMap.put("getTemperature", () -> getDeviceTemp());
serviceMethodMap.put("getBrightness", () -> getBrightness());

Finally replace the switch with:

final ServiceMethod serviceMethod = serviceMethodMap.get(methodName);
if(serviceMethod != null) {
    serviceMethod.execute();
}


Checking to see if an area of the screen changes

Let's start with your algorithm. You're using Bitmap.GetPixel to convert the entire bitmap image pixel by pixel into matrix of colors. I tried this approach several years ago - it was pretty slow on .Net 2.0 and I suppose it is still slow. You should convert image into byte[] and extract color bytes out of this array, it should be hundred times faster. Look into Bitmap.Lockbits method and BitmapData class.

Remaining points are about your code readability. There are several general rules which may improve readability a lot:

If method has some result of execution then return this result instead of assigning it to some field. Also use method parameters to accept arguments instead of class fields.
If variable is not needed outside of one method's scope then do not declare a field for it, use local variable instead.
Be strongly typed. Do not cast anything to string until you really need string.

These simple rules being applied to your code mean:

Rules #1 and #3 mean that your methods should have following signature:

void GetImage() -> bool CompareCurrentImageWithPrevious()
bool CompareArrays() -> static bool CompareImageArrays(Color[,] imageArray1, Color[,] imageArray2)
void CaptureScreen() -> Bitmap CaptureScreen()

This

var x = CompareArrays();
_valueX = x != true ? "false" : "true";

Should be replaced with:

return CompareArrays();

This

for (var i = 0; i < _memoryImage1.Width; i++)
{
    for (var j = 0; j < _memoryImage1.Height; j++)
    {
        if (_first == null) continue;
        if (_second != null)
            if (_first[i,j] != _second[i,j])
            {
                return false;
            }
    }
}
return _first != null && _second != null;

Should be:

 if (_first == null || _second == null) return false;
 if (_memoryImage1.Width != _memoryImage2.Width ||
     _memoryImage1.Height != _memoryImage2.Height)
     return false;
 return _first.SequenceEquals(_second);

Do not assign result of GetImage() to class field, DoWorkEventArgs have Result property which can be used to return value computed by background worker.

private void BackgroundWorker1DoWork(object sender, DoWorkEventArgs e)
{
    e.Result = GetImage();
    Thread.Sleep(100);
}


When you find yourself repeating code like this (just with slight differences), that's usually a sign that it's time to separate the logic into its own function so it can be reused. You could also maybe clean up your conditionals using a switch statement too - but that's more of a personal taste thing.

Here's my take on it:

function myFunction() {
    var cellData = ["2016-08-24 15:45", "2016-08-24 16:00"];
    var myTable = document.getElementById("myTable");

    // Defined inside the function so the data/table are in scope -
    // alternatively, you could define it outside and pass them as
    // parameters.
    function setCells(hours) {
        var times = [];

        for (var i = 0; i < cellData.length; i++) {
            var date = moment(cellData[i]).add(hours, 'h').format('MM/DD/YYYY hh:mm a');
            times.push(date);

            myTable.rows[i].cells[1].innerHTML = times[i];
        }
    }

    switch (document.getElementById("sel1").value) {
        case "VIC":
            setCells(1);
            break;
        case "NSW":
            setCells(5);
            break;
    }
}

And a demo of this code in action: https://jsfiddle.net/5q46xu77/1/


Run arbitrary INSERT INTO SQL Query using parameters

This code can't handle fields with spaces in them unless you specifically pass them pre-wrapped in square brackets. Things such as My Field would need to go into your parameter as "field1, [My odd field], field3". So, a definite area for improvement would be to handle that corner case.

I also don't really care for the comma delimited string parameter. I feel that it would be much cleaner and nicer to pass in a string array representing the field names. So, something along the lines of this psuedo code might be a bit cleaner.

Dim fields As Variant
fields = Array("field1","My odd field","field3")

InsertInto "Table1", fields, values)

' ...

Public Sub InsertInto(...)
    AddBracketsToStrings fields

    '...

End Sub

The next thing I notice is these comments:

'Assigns strParams value in format "[p1],[p2],[p3],...,[pN]"
...
'Construct SQL
...
'Give values to parameters
...

The comments are nice, and add a bit of clarity to the code, but these kinds of comments indicate an opportunity to extract subroutines/functions. Each of these comments could be replaced with a well named function.

ConvertValuesToParameters values
Set qdf = CurrentDb.CreateQueryDef("", ConstructSQL(TableName, Fields, strParams))
SetParameterValues qdf, values

Which brings me to the SQL Injection issue. It's never a good idea to concatenate SQL strings together. It's much better to use parameterized queries. This may require that you switch to using ADODB instead of DAO. I'm not sure. I don't know if DAO supports parameterized queries.

Case 13   'Type mismatch i.e. Values is not an array

That's a good comment, but a constant value would be better.

Const TypeMismatchError As Long = 13

Select Case Err.Number
    Case TypeMisMatchError
        ' ...


Generate random unit vectors around circle

To answer your question, you need to add a new dimension to the ndarray:

vecs /= mags[..., np.newaxis]

However

  uniformly distributed unit vectors around the unit circle

No it's not, at least not in \$\theta\$. You're generating uniformly distributed points on the unit n-sphere and modifying it to the unit circle; effectively reducing it to an angle. These angles will not be uniformly distributed, and this is easiest to show in 2D:

Notice how the corner piece is larger than the side piece, despite both being \$30^{\circ}\$.

Instead, generate the original points with a normal distribution.

This is because the standard normal distribution has a probability density function of

$$
\phi(x) = \frac{1}{\sqrt{2\pi}}\exp\left(-x^2/2\right)
$$

so a 2D one has probability density

$$
\phi(x, y) = \phi(x) \phi(y) = \frac{1}{2\pi}\exp\left(-(x^2 + y^2)/2\right)
$$

which can be expressed solely in terms of the distance from the origin, \$r = \sqrt{x^2 + y^2}\$:

$$
\phi(r) = \frac{1}{2\pi}\exp\left(-r^2/2\right)
$$

This formula applies for any number of dimensions (including \$1\$). This means that the distribution is independent of rotation (in any axis) and thus must be evenly distributed along the surface of an n-sphere.

Thanks to Michael Hardy for that explanation.

This is as simple as using instead

np.random.normal(size=(number,dims))

Generating mags can also be just

np.linalg.norm(vecs, axis=-1)

A few minor changes then gets one to

import numpy as np
import matplotlib.pyplot as plt

def gen_rand_vecs(dims, number):
    vecs = np.random.normal(size=(number,dims))
    mags = np.linalg.norm(vecs, axis=-1)

    return vecs / mags[..., np.newaxis]

def main():
    fig = plt.figure()

    for e in gen_rand_vecs(2, 1000):
        plt.plot([0, e[0]], [0, e[1]], 'r')

    plt.show()

main()

The plotting is quite painful, so here's a cleaner, faster version (credit HYRY):

import numpy
from numpy import linalg, newaxis, random
from matplotlib import collections, pyplot

def gen_rand_vecs(dims, number):
    vecs = random.normal(size=(number,dims))
    mags = linalg.norm(vecs, axis=-1)

    return vecs / mags[..., newaxis]

def main():
    ends = gen_rand_vecs(2, 1000)

    # Add 0 vector to start
    vectors = numpy.insert(ends[:, newaxis], 0, 0, axis=1)

    figure, axis = pyplot.subplots()
    axis.add_collection(collections.LineCollection(vectors))
    axis.axis((-1, 1, -1, 1))

    pyplot.show()

main()


A few general points:

(1)  GlobalVariables.Regions -- I don't know how big your application is, but if I'm looking at a code base and I see some static class called "GlobalVariables" that usually makes me leery.  In a pure object-oriented language, all data can (and arguably ought to be) associated with some object.  A GlobalVariables class with a bunch of statics on it is the kind of thing that is likely to grow and rot with as the application grows (and rots).

(2)  As mentioned by Lars-Erik, I think that breaking some of that functionality out into other methods would be beneficial.  Personally, I look at control statements, especially nested ones for opportunities to do that.  Looking at your code, the logic inside for (int i = 0; i < regions.Length; i++) would be a good candidate.  Just by looking at the code casually, it's hard to tell what all is going on inside that loop.  But if you pulled it out into a method and gave it a descriptive name, someone looking at your code could easily understand what the loop was doing.

(3)  You have a lot of code (as Linq tends to) with sequences of statements like Foo.Bar().Baz().Rebar();  Generally speaking, if anything in those sequence chains returns null, you're going to get null reference exceptions.  Perhaps clients of this method handle exceptions that it generates, but I can't see that you're handling anything but the "happy path" in this method.  What happens if things go unexpectedly?