Sorting numbers using Java Collections.sort()

There are a few improvements I can see, but not really related to performance (though it may run a bit faster anyway).

If the files are small (less than 10Megabytes or so), then the relative performance of different approaches are slight (obviously, you can bork your code, but the IO part will remain about the same). So, it comes down to readability.

For readability, I would recommend using the 'cool' toys in Java7. Consider the following:

List<String> lines = Files.readAllLines(Paths.get(args[0]));
for (String line : lines) {
    String[] parts = line.split("\\s+");
    double[] values = new double[parts.length];
    for (int i = 0; i < parts.length; i++) {
        values[i] = Double.parseDouble(values[i]);
    }
    Arrays.sort(values);
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < values.length; i++) {
        if (i > 0) {
            sb.append(", ");
        }
        sb.append(values[i]);
    }
    System.out.println(sb.toString());
}

Note the key elements here:

use Files and Paths classes
use StringBuilder for the string concatenation
use String.split, not a scanner....
use primitive data structures (arrays of double, not Double)
that means using Arrays.sort, not Collections.sort

Other things to consider.....

a method called integerFromString ... that returns a double is ... confusing.
using List.toString() and the stripping off the [ and ] is backward.


I can make a small improvement in your logic structure that may make a very small improvement in performance. If limit < currentPosition, all you need to do is that code block, and you can use else if and remove testing its opposite. See code:

$(window).load(function () {
/*-----------------------*/
 * Fixed Widget on Scroll
 *-----------------------*/

    // set some Div vars
    var stickyID = $("#sticky-scroll-wrapper"),
        footerID = $('#footer'),
        stickyDivHeight = stickyID.outerHeight(),
        stickyIDMargin = 70;

    $(window).scroll(function () {
        var currentPosition = $(document).scrollTop() + stickyIDMargin;
        var stickyIDPosition = stickyID.offset().top;

        // cut off point/un sticky when we reach this far down the page
        var limit = footerID.offset().top - stickyDivHeight;

        // Un-stick once we reach the #fotter section of the page to prevent overlapping
        if (limit <= currentPosition) {
            var diff = limit - currentPosition;
            $('#sticky-elements').css({
                'top': diff + stickyIDMargin,
                'position': 'fixed',
            });
        }
        //determines whether sidebar should stick and applies appropriate settings to make it stick
        else if (currentPosition >= stickyIDPosition) {
            $('#sticky-elements').css({
                'position': 'fixed',
                'top': '70px'
            });
        }
        else {
            $('#sticky-elements').css({
                'position': 'static',
            });
        }
    });

});

Also, you might consider consolidating var diff = limit - currentPosition; with 'top': diff + stickyIDMargin if you are comfortable with that.
Otherwise, it looks great to me. :)


My own method for sorting numbers in array

There is a big flaw in your program: This

if (min > temp)

compares the addresses of the number objects, not their values.
The correct way is

if ([min compare:temp] == NSOrderedDescending)
// ...
if ([max compare:temp] == NSOrderedAscending)

You probably didn't notice the problem because "small" numbers are
represented as "tagged pointers", but with

NSArray *array = @[@40000000000000, @300000, @10000000000000, @16];

your code gave a wrong result in my test.

Resetting min after the loop seems a bit counter-intuitive to me.
I would do that at the beginning, this also allows to restrict the scope of that variable to where it is needed. Also the second if should be
an else-if:

NSNumber *min = nil;
for (NSNumber *temp in inputMutableArray) {
    if (min == nil) {
        min = temp;
    } else if ([min compare:temp] == NSOrderedDescending) {
        min = temp;
    }
}

Of course you could contract the if statement to

    if (min == nil || [min compare:temp] == NSOrderedDescending) {
        min = temp;
    }

that is a matter of taste.

You could get rid of this loop by using Key-Value Coding to determine the minimum
value in the array:

NSNumber *min = [inputMutableArray valueForKeyPath:@"@min.self"];

But note that this can be significantly slower for large arrays
(compare Finding the smallest and biggest value in NSArray of NSNumbers).

Having almost identical code for the two cases (ascending/descending sort) is not necessary. If you define

NSComparisonResult sortOrder = ascending ? NSOrderedAscending : NSOrderedDescending;

at the beginning, then both cases can be treated with

while (inputMutableArray.count > 0) {
    NSNumber *first = nil;
    for (NSNumber *temp in inputMutableArray) {
        if (first == nil || [temp compare:first] == sortOrder) {
            first = temp;
        }
    }

    [sortedArray addObject:first];
    [inputMutableArray removeObject:first];
}


That looks quite good actually, minor stuff only.

for (int i = 1; i <= 12; i++) {

I'm a persistent advocate for using "real" names for loop variables, like index or count or factor in this case.
        for (int factor = 1; factor <= 12; factor++) {
            int result = number * factor;
            System.out.println(number + " x " + factor + " = " + result);
        }

        Scanner input = new Scanner(System.in);
        int number;

Do not declare all variables at the beginning of the method, declare them only when needed, that will limit the variable from creeping into scopes they don't belong in.

You could define the maximum factor as a constant.


Counting paths in an n-dimensional grid that stay within the boundaries

Naming

The name Grid_Walking is discouraged in Java. You should use GridWalking (without the _). The names hm and br are terrible.

Members

The field br isn't used outside of the main method and you can simply make it local.

Leaking resources

You really should use Try-with-resources to auto-close the readers.

try(InputStreamReader is = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(is)){

to make sure resources are properly closed in all scenarios.

Performance

Here's something you can try. Consider this you're taking \$M\$ steps and have \$2N\$ possible ways to go each step. Assuming for a second that the grid is so large that you never exit, then you have \$(2N)^M\$ different ways to step inside the grid. It might be easier to calculate in how many ways you can end up outside the grid...

Better algorithm hints

Lets look at a simple version of the problem see if we can't find some ideas. Let \$N=1\$ and \$M=3\$ and lets draw the states we can be in, specifically lets count in how many ways we can end up in each cell:

We start with step zero, there is only one possible state we can be in. Taking one step we can either go left or right so there is one way we can end up in either cell shown under \$M=1\$. From there we can either take left or right from both cells. So there are two ways we can end up back at the starting position and one way we can reach each edge. Try to do the steps yourself you'll see you'll get the same values.

So by now you see how this is going. The number of ways you can end up in a cell is the sum of the number of ways you can end up in the neighboring cells. For \$M=4\$ this would be 1 0 4 0 6 0 4 0 1.

There are two things to note here: First, the sum of all the values in the cells is actually equal to the possible routes you can take with \$M\$ steps. Take a moment to think about it, it makes sense, this is your answer (after applying suitable modulus). Second, notice anything familiar with the shape of the numbers? Yepp, that's Pascal's triangle with zeros injected between each cell! The answer for \$N=1\$ is the sum of \$M\$th row of pascals triangle after cutting off the edges due to the size of the grid (the zeros wont affect the result)!

So solving this problem for arbitrary \$N\$ you just need to generalize Pascal's triangle to \$N\$ dimensions. You can easily do this by using a hyper-cube and using the above realization that:

  The number of ways you can end up in a cell is the sum of the number of ways you can end up in the neighboring cells.

I will leave the details up to you to figure out, let me know if you need more help.


Selecting data from a table based on value in another table (SQL server)

The first query, i.e. using explicit JOINs, is generally the preferred way, and has benefits like:

verbosity
easier to read and maintain
less likely to have accidental cross joins

For more precise and detailed answers, see the answers to this question on SO (bearing in mind it is tagged mysql, it still is relevant for sql-server). Also read this related blog post by Baron Schwartz.


Receiving and sending notifications from database

Should I use this?

NO

If not then why?

Reference TaskFactory.StartNew Method

Remarks
Starting with the .NET Framework 4.5, the Task.Run method is the recommended way to launch a compute-bound task. Use the StartNew method only when you require fine-grained control for a long-running, compute-bound task. .......

Which would end up as
//...omitted for brevity

Task.Run(() => {
    notificationService.MarkNotificationsAsSent(notification.NotificationId);// A database Hit
});

//...omitted for brevity


Generating a QuestionID Using a Nested Loop for a Quiz Game

You ask for a refactoring of the current method. It could be:

public void saveToDB()
{
  int setID = 0;
  foreach (Set set in sets)
  {
    int brandID = 0;
    foreach (Brand brand in set.brands)
    {
      int questionID = 0;
      foreach (Question question in brand.questions)
      {
        PlayerPrefs.SetString(
          key: $"s{setID}|b{brandID}|q{questionID}",
          value: $"value:{set.setName}|{brand.brandName}|{question.questionID()}"); // save to the database

        questionID++;
      }
      brandID++;
    }
    setID++;
  }
}

Here is used string interpolation $"s{setID}...." instead of string concatenation which is considered to be bad practice because it results in too many string instantiations and is hard to read.

It could be done by using LINQ, but that is maybe more confusing and will actually be slower:

public void saveToDB()
{
  var questionInfos = sets.SelectMany((set, setId) => set.brands.SelectMany((brand, brandId) => brand.questions.Select((question, questionId) => new { key = $"s{setId}|b{brandId}|q{questionId}", value = $"value:{set.setName}|{brand.brandName}|{question.questionID()}" })));

  foreach (var questionInfo in questionInfos)
  {
    PlayerPrefs.SetString(questionInfo.key, questionInfo.value);
  }
}

Just for the sport, it can be done in inline query syntax (with a little help from method syntax) as t3echb0t suggested:

public void saveToDB()
{
  var questionInfos = from setAndId in sets.Select((set, id) => (set, id))
                      from brandAndId in setAndId.set.brands.Select((brand, id) => (brand, id))
                      from questionAndId in brandAndId.brand.questions.Select((question, id) => (question, id))
                      select new
                      {
                        key = $"s{setAndId.id}|b{brandAndId.id}|q{questionAndId.id}",
                        value = $"value:{setAndId.set.setName}|{brandAndId.brand.brandName}|{questionAndId.question.questionID()}"
                      };

  foreach (var questionInfo in questionInfos)
  {
    PlayerPrefs.SetString(questionInfo.key, questionInfo.value);
  }
}

That said, I would consider an mandatory Id to be a property on each Set, Brand and Question instance:

public abstract class ObjectBase
{
  public ObjectBase(string name, int id)
  {
    Name = name;
    Id = id;
  }

  public string Name { get; }
  public int Id { get; }
}

public class Set : ObjectBase
{
  public Set(string name, int id) : base(name, id)
  {

  }

  public Brand[] Brands { get; set; }
}

public class Brand : ObjectBase
{
  public Brand(string name, int id) : base(name, id)
  {

  }

  public Question[] Questions { get; set; }
}

public class Question : ObjectBase
{
  public int FontSize;
  public string[] Choices = new string[3];  //choices for each question
  public readonly int CorrectAnswerId;  //will hold the correct answer for a question

  public Question(string question, int correctAnswerId, string[] choices, int id) : base(question, id)
  {
    CorrectAnswerId = correctAnswerId;
    Choices = choices;
  }

  public string TheQuestion => Name;

  public string QuestionID()
  {
    // making a id for question
    return $"{TheQuestion}|{string.Join("|", Choices)}|{CorrectAnswerId}|{FontSize}";
  }

}

public class QuestionManager //: MonoBehaviour
{
  Set[] sets = new Set[0];

  public void saveToDB()
  {
    foreach (Set set in sets)
    {
      foreach (Brand brand in set.Brands)
      {
        foreach (Question question in brand.Questions)
        {
          PlayerPrefs.SetString(
            key: $"s{set.Id}|b{brand.Id}|q{question.Id}",
            value: $"value:{set.Name}|{brand.Name}|{question.QuestionID()}"); // save to the database
        }
      }
    }
  }
}

Notice here that there is no point in calling the name of a Set "setName - Name is sufficient.
Further notice that it is common practice in C# to use PascalCase for public members.

The benefit of having the entities be born with an id, is that you can use that id to identify each instance uniquely throughout the session/lifetime of each object. And as shown the key/value-pair for PlayerPrefs.SetString is easier created.


Insert a digit to maximize the given number

Presumably, if array[i] == '-' is meant to check if the number is negative. Having it like you have though doesn't make a lot of sense. If it's in the loop, that suggests that a - could be expected at any point within the number. In reality though, it will only ever occur as the first character in the string. I'd just check N the number with if N < 0 to see if it's negative. You can streamline this check right in the definition of mod:

mod = 1 if N >= 0 else -1

Unfortunately, that slightly complicates adding - to result. The simplest way to deal with it I think is just to change the definition of result to be similar to that of mod:

result = [] if n >= 0 else ['-']

Since the checks are the same though, you could combine then into returning a tuple instead then unpacking it:

mod, result = (1, []) if n >= 0 else (-1, ['-'])

And, array will need to have the - cleaved off if we're doing it before the loop:

mod, result, checked_digits = (1, [], digits) if n >= 0 else (-1, ['-'], digits[1:])

Normally, I don't think a triple variable definition like this should be encouraged, but there's nothing too fancy or complicated going on here to make the line confusing. I think it's fine.

I'd rename array and N:

array isn't really a correct or useful description. I think digits would be better.
N should be n.

You're iterating over the indices of digits and using digits[i] all over the place even though you don't even need the index in most cases. I'd iterate over the digits themselves, and use enumerate to get the index in the couple cases that you actually need it for:

for i, digit in enumerate(digits):
    . . .

    if int(digit) * mod > 5 * mod:
        result.append(digit)

I'd move the if i == len(array): check out of the loop as well. Really, it's just checking if at no point a break was encountered. That's exactly the use case for for's else clause (yes, for can have an else):

for i, digit in enumerate(checked_digits):
    . . .

else:
    result.append(5)

The else will only execute if no break was encountered. In the case of this code, that means that no digit greater than 5 was found.

Honestly, this is the first time I've ever found a useful case for for...else. It worked out nice here though.

I'd add 5 and '5' as constants at the top. Having the magic strings and numbers floating your code makes your code harder to change latter, and doesn't indicate what the 5 and '5' actually are for:

TARGET_NUM = 5
TARGET_DIGIT = str(TARGET_NUM)

def solution(n):

Or, just make that number a parameter with a default to make it easy to use different target numbers:

def solution(n: int, target_num: int = 5) -> int:
    target_digit = str(target_num)

I also added some type hints in there, because why not?

In the end, this is what I ended up with:

def solution(n: int, target_num: int = 5):
    target_digit = str(target_num)
    digits = str(n)

    mod, result, checked_digits = (1, [], digits) if n >= 0 else (-1, ['-'], digits[1:])

    for i, digit in enumerate(checked_digits):
        if int(digit) * mod > TARGET_NUM * mod:
            result.append(digit)

        else:
            result.append(TARGET_DIGIT)
            result.append(checked_digits[i:])
            break

    else:
        result.append(TARGET_DIGIT)

    return int("".join(result))


I'll answer your second question first! The fact that one of your your checkboxes needs to be checked is a validation that is more about your class than one of your checkbox. I mean, individually, a checkbox doesn't need to be checked, but your model requires one of them to be. Which is why I would put the validation attribute on your class instead of on one of the checkbox. Then, to show your error message on your client HTML you would need to set Html.ValidationSummary(true) in your view.

For your first questions, there a lot of possibles way to do what you did, but your way is fine I believe. I'll propose another one though.

I think you should make another Model that would only contains your checkboxes. A CheckBoxList or something that is more appropriate in your context (that I know nothing about). Then you could use reflection to get all checkboxes and check if one is checked.

It would look like this :

public class ValidateAtLeastOneCheckedAttribute : ValidationAttribute
{
   protected override ValidationResult IsValid(object value, ValidationContext validationContext)
   {
      Type type = value.GetType();
      IEnumerable<PropertyInfo> checkBoxeProperties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(p => p.PropertyType == typeof (bool));

      foreach (PropertyInfo checkBoxProperty in checkBoxeProperties)
      {
         var isChecked = (bool)checkBoxProperty.GetValue(value);
         if (isChecked)
         {
            return ValidationResult.Success;
         }
      }

      return new ValidationResult(base.ErrorMessageString);
   }
}

[ValidateAtLeastOneChecked]
public class CheckBoxList
{
   public bool Checkbox1 { get; set; }
   public bool Checkbox2 { get; set; }
   public bool Checkbox3 { get; set; }
   public bool Checkbox4 { get; set; }
   public bool Checkbox5 { get; set; }
}

The advantages of using such a solution is that you don't need to write down every property in a string[], which could lead to errors (if you forgot one or wrote one incorrectly). Also, you don't need to use validationContext.ObjectInstance since the target of your attribute is the instance itself.

I'll review your current code too, because there is three points that I see could be "better" :)

By convention, attributes should end with the suffix Attribute (which I changed already in my example). You won't need to write Attribute when you use it (as shown in my example, which compiles!).

Also, your brackets are following the Java standard, not the C# one. You should put opening brackets on a new line.

Finally, instead of doing this :

Object propertyValue = type.GetProperty(s).GetValue(instance, null);
if (bool.Parse(propertyValue.ToString())) {//...

You can cast the propertyValue to bool directly, it will save you a cast to string.


Tree Node class - deallocation in the destructor

This is not real C++ code.
This is C written with a couple of classes.

Pointers are dangerous and should rarely be used in code. C++ has moved away from C in this regard over the last decade and all pointers should be either wrapped in a smart pointer or be part of a container structure.

For this a technique called RAII has been introduced. This is the concept that creation and destruction of an object are linked within the objects lifetime thus allowing you to control resources even in the face of exceptions.

There are a couple of ways to fix the code.
The simplest technique is to just use std::unique_ptr (or std::auto_ptr if you are using C++03).

    Node( Node* parent );

Are you passing ownership of the parent?
No. You have a seprat constructor for no parent and ownership is not being passed as a result you should pass the parent by reference (if it has a parent it must not be NULL and must exist).

    Node( Node& parent );

All these methods that return pointer.
Should they?

    Node* GetFirstChild();
    Node* GetChild( int index );
    Node* GetLastChild();

If there is a possibility of NULL then yes, otherwise return a reference.

Here you are adding a child:

    void AppendChild( Node* child );
    void AddChild( Node* child ,int index );

But there is no indication you are passing ownership. The person reading the code has to know how the internals of how your class works. Otherwise they do not know if the pointer passed should be dynamically allocated or not. You need to make this knowledge explicit in the interface. Here I would pass a unique_ptr to indicate that you are passing ownership of the pointer into the node.

OK. Parent is allowed to be a pointer.

    Node* _parent;

You do not own the object and it is possible to be NULL. There is no responsibility for this node to clean up its parent.

_children should not be a pointer. It should be an object. Thus allows automatic cleanup and no requirement to manually create it. Also this simplifies the copy construction and assignment operator (that you have currently failed to define).

Secondly the container should not be holding pointer. Here you have an option either it should be a container of smart pointers, or it should be a container designed specifically to hold ownership of pointers (so that it can be done safely).

    // Option 1:
    std::deque<std::uniqur_ptr<Node>> _children;

    // Option 2:
    boost::ptr_deque<Node>            _children;

Personally I prefer option 2. As the contain provides access to the pointers as if they were normal objects. This makes writing functors and the interacting with the standard algorithms much easier.

Also I would question the use of deque over vector but that is a minor detail.
    };
}

Secondary Comments:

Do initialization in the initialization list. You sort of try to NULL everything in the initialization list. It is best to actually initialize them and have an empty body.

Node::Node(): _parent(NULL), _index(NULL),             _children(NULL){
                      ^^^^ OK       ^^^^ Questionable  ^^^^^^^^ Should be an object

Node::Node( Node* parent ): _parent(parent), _index(NULL),     _children(NULL){
                                    ^^^^^^ OK       ^^^^ Questionable

In the constructor that takes a parent you don't check your input for NULL

// If somebody passes a NULL parent then this is no good.
_parent->AppendChild( this );

The use of your functions should be consistent.

Getting the first and last children can be badly defined if the node has no children. But the generic GetChild() function will throw an exception if you try and retrieve a child from an invalid index. These two different behaviors makes using your code hard to be consistent. I would change these so that they all or none throw an exception.

Node* Node::GetFirstChild(){
    return _children->front();
}
Node* Node::GetLastChild() {
    return ( _children->back() );
}
Node* Node::GetChild( int index ){
    return _children->at(index);
}

Manually calling the destructor is wrong here:

_children->at(index)->~Node();

Unless you allocated the memory in some other way the used 'Placement New' you should not be calling the destructor manually. But nothing in your interface indicates that. So this should be a normal call to delete.

delete _children->at(index);

When inserting a child into the middle is it intentional to only set the index of the inserted child?

void Node::AddChild( Node* child ,int index ) {
    std::deque<Node*>::iterator i = _children->begin();
    i = i + index;
    _children->insert( i, child );

    // You set this node
    // But what about the nodes from index+x to the end.
    // Currently their internal index is unchanged.
    //     This could be intentional but it is hard to tell without a comment.
    child->SetIndex( index );
}

I would try something like this:

#ifndef HEADER_GUARD__TREE
#define HEADER_GUARD__TREE

#include <boost/ptr_container/ptr_deque.hpp>

namespace Sandbox {
    class Node;
    class Node {
        public:
            Node();
            // Removed the constructor that passes a parent
            // this has problems when you need to define who owns the object.
            // Thus safer to just remove the interface.
            virtual ~Node() {}

            Node& GetFirstChild();
            Node& GetChild( int index );
            Node& GetLastChild();

            Node& AppendChild(std::auto_ptr<Node> child );
            Node& AddChild(std::auto_ptr<Node> child ,int index );
            void RemoveChild( int index );

            int  GetIndex() { return _index; }
            void SetIndex( unsigned int index ) { _index = index; };
        protected:

        private:
            Node* _parent;
            int _index;
            boost::ptr_deque<Node> _children;
    };
}

#endif // HEADER_GUARD__TREE

using namespace Sandbox;

Node::Node()
    : _parent(NULL)
    , _index(0)
{
}

// All node child node access fails with an exception if the child is not there.
// Thus we always return a reference to the node
Node& Node::GetFirstChild()
{
    return _children.at(0);
}

Node& Node::GetChild( int index )
{
    return _children.at(index);
}

Node& Node::GetLastChild()
{
    return _children.at(_children.size() - 1);
}

// Inserting a node will return a reference to the node after insertion.
// The nodes are passed by std::auto_ptr to indicate transfer or ownership into the tree
// Note an empty auto_ptr inserted into the boost_deque will result in an exception so
// the node must have been created.
Node& Node::AppendChild(std::auto_ptr<Node> child )
{
    _children.push_back( child );
    unsigned int index = _children.size();

    _children[index].SetIndex(index);
    return _children[index];
}

Node& Node::AddChild(std::auto_ptr<Node> child ,int index )
{
    boost::ptr_deque<Node>::iterator i = _children.begin();
    i = i + index;

    _children.insert( i, child );
    _children[index].SetIndex( index );
    return _children[index];
}

void Node::RemoveChild( int index )
{
    boost::ptr_deque<Node>::iterator i = _children.begin();
    i = i + index;

    _children.erase( i );
}
// Destruction is done automatically no code here.


Scheduling a task into a period within a day, depending on whether or not it is a weekend

You return what is effectively an enum as a double. Why? create the enum and return that it's much clearer that way wat the return value means:

If you still want a single point of return (for whatever reason) then you can use an if-else chain:

enum PartOfDay{
    morning = 0,
    firstWorkPart = 1,
    lunch = 2,
    secondWorkPart = 3,
    afterWork = 4,
    beforeSleep = 5,
    sleepTime = 6
}

PartOfDay PartOfDayRule::ExtractFeature(dto::ActionableItem & item) {

    dto::DateTime lunchStart;
    dto::DateTime lunchStop;
    if(!item.ctx->isWorkingDay){
        lunchStart = item.ctx->workTimeStart;
        lunchStop = item.ctx->workTimeFinished;
    }else{
        long firstWorkPartLength = util::time::between<std::chrono::hours>(item.ctx->workTimeStart, item.ctx->workTimeFinished) / 2;
        lunchStart = item.ctx->workTimeStart + std::chrono::hours{firstWorkPartLength};
        lunchStop = lunchStart + std::chrono::hours{1};
    }

    dto::DateTime itemTime = item.scheduledStart;
    dto::DateTime sleepPreparationTime = item.ctx->sleepTimeStart - std::chrono::hours{1};
    PartOfDay result = sleepTime;

    if(util::time::inRange(item.ctx->sleepTimeEnd, item.ctx->workTimeStart, itemTime)){
        result = morning;
    } else if(util::time::inRange(item.ctx->workTimeStart, lunchStart, itemTime)){
        result = firstWorkPart;
    } else if(util::time::inRange(lunchStart, lunchStop, itemTime)){
        result = lunch;
    } else if(util::time::inRange(lunchStop, item.ctx->workTimeFinished, itemTime)){
        result = secondWorkPart;
    }else if(util::time::inRange(item.ctx->workTimeFinished, sleepPreparationTime, itemTime)){
        result = afterWork;
    }else if(util::time::inRange(sleepPreparationTime, item.ctx->sleepTimeStart, itemTime)){
        result = beforeSleep;
    }else {
        result = sleepTime;
    }
    return result;

}

Or you can sort the ranges and then use std::find to get the range you want.


Correct usage of EF's DBContext in ASP.NET MVC application with Castle Windsor

You're doing it right - per-request lifestyle is exactly what you need, and you got it; this ensures your favorite IoC container disposes your context at the end of each request, and serves a new instance at each new one.

One thing bothers me though, and it's not about your code:

  Use UnitOfWork and Repository patterns seems to be overkill because whole web application will be pretty straightforward.

You're using Entity Framework. DbContext, with its DbSet<T>'s, is a unit-of-work/repository pattern implementation. Some will argue it's done wrong and it's their right to be religious about a design pattern. The point is that if you use it correctly, a DbContext is a perfectly acceptable unit of work, especially if you're looking to get the damn thing done and in-line with KISS. Just make sure you call SaveChanges() as little as possible - once per request, i.e. once per instance.

If you're worried about db connections, open up your favorite SQL profiler against your database server instance, and see for yourself!

Bottomline, a DbContext is an abstraction layer over lots, lots of plumbing already. Abstracting it is often over-the-top, unless you wish to decouple your data layer from the rest of your app (say, swap EF for NHibernate).


JavaFX design writes to static field from constructor

One alternative is to use the Borg Pattern. Allow creating multiple instances, all of which, simply share the same state. Most online references will be in Python (where it is real easy to code), but the idea can be transplanted to Java too.

The advantage over the Singleton pattern is that it hides the fact that there is shared state from clients of the class, especially those that are interested in creating instance.

Clients (in casu the JavaFX framework) can simply use the constructor. Your own code can also easily get the Application by creating a separate instance.

so some sample code :

public class LJGM extends Application {

    private static SharedState sharedState = new SharedState();

    private static class SharedState {

        private Object variable;

        private Object getVariable() {
            return variable;
        }
    }

    public LJGM() {
    }

    public Object getVariable() {
        return sharedState.getVariable();
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        // (add GUI to the primaryStage here)
    }

    public static void main(String[] args) {
        launch(args);
    }
}

All that being said, I don't see any reason why you could not simply use dependency injection to avoid having global state here. So rather than having low level components query the Application object, let the Application pass them the parameters they will need, by passing itself (preferably implementing an interface) or by passing in the variables themselves.

public class LJGM extends Application implements ApplicationContext {

    private Object variable;

    public LJGM() {
    }

    public Object getVariable() {
        return variable;
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        // (add GUI to the primaryStage here)
        new LowLevelComponent(this);
        new OtherLowLevelComponent(variable);
    }

    public static void main(String[] args) {
        launch(args);
    }
}


Hex encoding and decoding of ASCII strings in VBA

I think you have an opportunity for using Application.Caller in that error-handling subroutine, and make the function behave differently when it's used as a UDF vs. when it's called from VBA code.

Instead of GoTo-jumping when there's an invalid argument to early-return an Excel error value that's only really useful when the function is used as a UDF (and confusing when it's called from VBA code), you could be raising an actual meaningful error (which would still be jumping to the DecodeError label).

First, because we're raising an error in several places, I'd make a little utility procedure:

Private Sub OnHexDecodeError(ByVal message As String)
    Err.Raise 5, "HexDecode", message
End Sub

If Not StrComp(Left$(HexString, Len(HexPrefix)), HexPrefix, vbTextCompare) = 0 Then
  OnHexDecodeError "Parameter value '" & HexString & "' is not in the expected format."
End If

If Len(hexRaw) Mod 2 = 1 Then
  OnHexDecodeError "Parameter value '" & HexString & "' is invalid."
End If

  If Not IsNumeric(hexchar) Then
    OnHexDecodeError "Hex character '" & hexchar & "' is not a valid hexadecimal digit."
  End If

And then the error-handling subroutine could do this:

DecodeError:
  If TypeName(Application.Caller) = "Range" Then
    'function is used as a UDF
    HexDecode = CVErr(xlErrValue)
  Else
    'function is called by other VBA code
    Err.Raise Err.Number 'rethrow
  End If

That way the calling code can handle a runtime error 5 (aka invalid procedure call or argument) with a useful description:

?HexCode("test")

And now you have a function that's just as friendly to use as a UDF as it is in plain VBA code.

This doesn't strike me as intuitive:

If Len(hexRaw) Mod 2 = 1 Then

"Is value a multiple of X" is usually written as:

If value Mod x <> 0 Then

That way you're not assuming what the remainder might be - of course here it's either 1 or 0, but the point is that the way the comparison is written in foo Mod bar {comparison} never has to change, regardless of what the value of bar is.


Some notes:

If you use += instead of <<, you don't need to flatten the array.
DRY code by identifying common patterns and create suitable data structures accordingly.

A rewrite capturing the pattern:

def experiences
  fields = [
    [:work_experience, Db::Experiences::Work],
    [:education, Db::Experiences::Education],
  ]

  fields.flat_map do |field, db_class|
    @coach.delete(field).map do |experience|
      db_class.new(experience.for_indexing)
    end
  end
end


The $` and $' are very cryptic, I had to look them up in man perlvar to find that they contain whatever was before and after the match. It also turns out that they are discouraged due to performance considerations. Either way the while block really smells.

A simpler approach is to use s///ge to replace the matched pattern with the output of a function call, like this:

sub parseFile {
  my ($fn) = @_;
  my $str = read_file($fn);
  $str =~ s/include\s+"(.*?)"/parseFile("include\/$1.json")/ge;
  return $str;
}

Also consider adding some error handling. For example, what should happen if the file doesn't exist? Ignore / warn / raise error?

It might be a good idea to make parseFile handle multiple parameters:

sub parseFile {
    foreach my $fn (@_) {
        my $str = read_file($fn);
        $str =~ s/include\s+"(.*?)"/parseFile("include\/$1.json")/ge;
        return $str;
    }
}

Maybe you don't really need to handle multiple files, but a side effect of this approach is that it automatically handles the case gracefully if somebody incorrectly calls the method without any parameters.

Finally, notice that I used spaces around operators like = and =~ to improve readability. I borrow this practice from other programming languages where this is a standard, and let's face it, Perl scripts need all the readability aid they can get...

UPDATE

@amon added some excellent points in his comment:

Notice that in the replacement pattern s/include\s+"(.*?)"/parseFile(".\/$1")/ge; I had to escape the delimiter /. Another way is changing the delimiter so I don't have to escape anything: s{include\s+"(.*?)"}{parseFile("include/$1")}ge;
My multi-argument suggestion is kinda broken, because of the return statement: it will only process the first file. It would be better to use Carp::confess "parseFile expects one file name or file handle" if not @_ == 1, and the caller could still map { parseFile($_) } @files if really required


Imports

There is a more idiomatic way of doing

import tkinter
tk = tkinter

it is import tkinter as tk.

You’re also importing StringVar, Label and Button from tkinter but still calling them using the tk namespace. Either remove the import line or remove the tk. part when creating such objects.

Same for font, you import it from tkinter and use it only for font.Font. Either do from tkinter.font import Font and call it using only Font or call it with tk.font.Font. All in all, it’s more a matter of consistency than saving on typing.

ComboBox management

First of, you should define your values as a constant somewhere. Either at the top-level of the file or as a class attribute. That way you could re-use it in both __init__ and findInBox without having to define it twice.

Secondly, your alpha is pretty much string.ascii_uppercase. No need to redefine it again.

Lastly, you’d be better of using a combination of for and enumerate to iterate over your different values. Both because a for loop makes the intent of iteration clearer, and the index management is simpler using enumerate:

import tkinter as tk

from tk.font import Font
from tk.ttk import Combobox

from string import ascii_uppercase

class Parking_Gui(tk.Frame):

    PARKING_LOTS = ('ARTX', 'BURG', 'CLAY_HALL', 'GLAB', 'HAMH_HUTC',
                    'HHPA', 'JVIC', 'LIBR', 'PLSU', 'POST', 'PROF',
                    'STEC', 'STRO_NORTH', 'STRO_WEST', 'TROP')

    def __init__(self):
        ...
        self._LotCombo['values'] = Parking_Gui.PARKING_LOTS
        ...

    ...
    def findInBox(self, event):
        keypress = event.char.upper()

        if keypress in ascii_uppercase:
            for index, lot_name in enumerate(Parking_Gui.PARKING_LOTS):
                if lot_name[0] >= keypress:
                    self._LotCombo.current(index)
                    break

PEP8 & PEP257

Small improvements in readability but:

class names should be TitleCase not Title_Snake_Case
functions and variable names should be snake_case and not TitleCase or camelCase. (And constants like PARKING_LOTS in UPPER_SNAKE_CASE.)
new lines in docstring should be indented at the same level than the start of the """, not their end. Multi-line docstrings should also have the closing """ on their own line.


Since you’re primarily interested in efficiency, that’s what I’m going to focus on in my review.
However, first I do need to point out that int32_t main() is not legal C++. I’m mildly surprised it even compiles. There are only two legal forms of main():

int main(); and
int main(int, char*[]).

I should also mention that a message queue is probably better done as a class, with the mutex and other implementation details as private data members, rather than as global variables, and details like notifying the condition variable handled automatically. But that isn’t a performance issue, just a design one.
std::list<std::vector<char>> msg_queue;

Using a std::list for the actual queue is an odd choice. It’s not wrong; it’ll work perfectly fine. And std::list is not the most performant container, but its inefficiencies will be absolutely dwarfed by all the thread context switching and locking/unlocking.
Normally for a message queue like this you’d use a std::vector, or maybe a std::deque. Or sometimes you’d actually use a std::array (or a std::vector with a fixed size), and either treat it like a ring buffer—so if there are too many unhandled messages, older messages get lost—or block any new messages until some older messages are handled.
As I said, std::list isn’t wrong. It’ll work. I just don’t see any benefits to using it, because at least in the example code, you don’t really benefit from iterator stability (which is the primary reason to prefer a std::list), and you’ll pay a lot more for allocations and cache misses.
char buff[2048];

Is there a reason you use a fixed-size buffer? I don’t see any performance gains from it, and you’ll just lose any messages longer than 2k.
I’ll offer alternative suggestions later.
while(true) {

You have a bug in your program in that the loops are infinite. Infinite loops are UB. (Correction: Infinite loops are UB if and only if they have no observable side effects. These loops have side effects (like printing to standard out, and locking mutexes). However, there is no portable way to end the program, and—more importantly (because it’s the subject of the review)—the message queue. If you tried to put this message queue as-is in an existing program, like the example one, it will never end; it will deadlock while waiting for the thread to join, while the thread loops and waits on the condition variable.)
What you really need is a way for the recv() function to realize the program’s ending. For example, you could use a message "done" as a signal to wind things up:
// in recv()
while (true)
{
    // ... [snip] ...

    if (buf == "done")
        break;
}

// in main()
for (auto n = 0; n < 10000; ++n) // instead of while (true)
{
    // ... [snip] ...
}

// artificial scope
{
    auto lock = std::scoped_lock(mu);
    msg_queue.emplace_back({'d', 'o', 'n', 'e'});
}

cv.notify_one();

th.join();

It doesn’t need to be a special message to signal the end, but if you use something else, like a flag, then you might need to be sure you finish handling all the messages before ending the recv() loop, and you need to consider what happens if the flag is set while the queue is empty (and the condition variable is waiting on it to not be empty).
while(msg_queue.empty())
    cv.wait(ul);

Rather than a manual loop like this, it’s cleaner and less likely to cause problems if you use the other form of wait() that takes a lambda:
cv.wait(ul, [] { return not msg_queue.empty(); });

This removes the temptation for some later code monkey to fool with the loop in some way. Raw loops are a code smell, because you should generally prefer algorithms. They’re fine in the use cases here, but you never know what some future coder might think to do. Also, this reads much clearer, even to someone who doesn’t understand condition variables (who might ask, “why a loop and a call to a wait function?”).
std::vector<char>& queue_msg = msg_queue.front();
if(queue_msg.size() < sizeof(buff)) {
    std::memcpy(buff, queue_msg.data(), queue_msg.size());
    buff[queue_msg.size()] = '\0';
}

msg_queue.pop_front();

Okay, here’s where the biggest inefficiencies lie. I don’t see a reason—at least in this code—why you copy the message from the message queue into a buffer, then delete the message from the queue. Why not just take the message right from the queue and use it?
In other words, why not do this:
void recv()
{
    while (true)
    {
        std::unique_lock<std::mutex> ul { mu };
        cv.wait(ul, [] { return not msg_queue.empty(); });

        // *TAKE* the message from the queue. This will be *LIGHTNING* quick;
        // possibly *thousands* of times faster than copying the message into a
        // buffer.
        auto queue_msg = std::move(msg_queue.front());

        // Remove it from the list.
        msg_queue.pop_front();

        // No need to hold the lock anymore.
        ul.unlock();

        // Now you have the message as queue_msg, and you can do whatever you want
        // with it. For example, print it:
        std::cout.write(queue_msg.data(), queue_msg.size());
        std::cout << '\n';
    }
}

But that’s just the tip of the performance iceberg. It’s very wasteful to do all that locking and so on for ONE message at a time. What if there are several messages in the queue? Why not handle them all at once?
For example:
void recv()
{
    while (true)
    {
        std::unique_lock<std::mutex> ul { mu };
        cv.wait(ul, [] { return not msg_queue.empty(); });

        // Take the ENTIRE QUEUE. Even if there are multiple messages, this could
        // still be thousands of times faster than copying a SINGLE message into a
        // buffer, and that's not even taking into account the gains you get from
        // avoiding multiple locking and unlocking and waiting cycles.
        auto messages = std::vector<std::vector<char>>{};
        messages.resize(msg_queue.size()); // make space for the messages
        std::move(msg_queue.begin(), msg_queue.end(), messages.begin()); // move them all out of the queue
        msg_queue.clear(); // clear the queue of the (now empty, moved-from) messages

        // No need for the lock anymore.
        ul.unlock();

        // Now we can handle all the messages at our leisure.
        std::for_each(messages.begin(), messages.end(),
            [](auto&& message)
            {
                std::cout.write(message.data(), message.size());
                std::cout << '\n';
            });
    }
}

As an optimization, you could also move messages out of the loop, and call messages.clear() at the end of the loop. The advantage of this is that it will mean that messages.resize() will almost never need to allocate because you can reuse the memory. That means that that entire block of code in the middle of the function above will amount to a few measly pointer copies… which will be FAST… far faster than copying entire strings, even with std::memcpy(). And that in turn means much less time spent with the mutex locked, which means you should be able to get a MUCH higher throughput for your messages.


YUIDoc syntax for optionally static constructor

Naming
As Bhathiya pointed out, you should be using actual, descriptive variable names rather than just a single character.
A descriptive variable name means everything, as it increases readability and understanding 10-fold, even if it means typing a few more characters each time you write the variable name.
And, if you really, really don't want to type out a full variable name each time, most text editors or IDEs come with auto-complete. This could help you type less.

I think that the best way to express that the class can be instantiated in comment form would be to write something like this:
@instantiate: (new) Complex(r, i, m, t);

Then, in your code, I recommend adding a comment to these lines:
if (!(this instanceof Complex)) {
    return new Complex(r, i, m, t);
}

That says that those lines allow for the object to be instantiated with new.
However, do you really need both options? Is there something in the full program that you are using that blocks you from using new? I can't think of any case where you would be blocked by using new, I think you should always use it because it is then very clear that Complex is a class.


SKAction on SKLabel with array of Strings

The first array element configText[0] is never used, so you can
remove it from the array (and modify the index calculations accordingly).
Incrementing the counter with wrap-around can be simplified using the
remainder operator:

self.counter = (self.counter + 1) % self.configText.count

The three "run" actions can be combined into one.
Inside the actions array you can refer to the SKAction members
without specifying the type explicitly, e.g. .wait instead
of SKAction.wait.

Putting it all together:

parentNode_Label.run(
    SKAction.sequence([
        .wait(forDuration: 3.0),
        .run {
            self.sprite_Label.text = self.configText[self.counter]
            self.counter = (self.counter + 1) % self.configText.count
        },
        .fadeIn(withDuration: 0.5),
        .wait(forDuration: 3.0),
        .fadeOut(withDuration: 0.5),
        ]).forever()
)

Also have a look at the Swift naming conventions:

  Names of types and protocols are UpperCamelCase. Everything else is lowerCamelCase.

For example: parentNode, textLabel, without underscores.


Finding occurrence of a given character in a String?

Your program doesn't print a prompt to the user and I couldn't make it output the warning to enter a string. I have made a few basic changes. The actual counting is done in a very basic but robust way

public class Main {

    /**
     * How to count occurrence of a given character in a String?
     */

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        System.out.println("Please enter a string to search");

        String givenString = in.nextLine();

        System.out.println("Please enter the character to search for");
        char givenChar = in.next().charAt(0);

        int occurance = occuranceOfChar(givenString, givenChar);

        System.out.println(givenChar + " occured " + occurance + " times!");
    }

    private static int occuranceOfChar(String givenString, char givenChar){

        int sum = 0;

        for (int i = 0; i < givenString.length(); i++) {

            char charAtI = givenString.charAt(i);

            if (charAtI == givenChar) sum++;
        }

        return sum;
    }
}


Harmonic partial sum calculator with multithreading

Try not to use using namespace std in global scope.  If you must use it, keep it in local scope, such as in a function.  More info about that here.
I don't need any need to use printf() over std::cout here.  You are also using C-style casting and no std:: for clock_t, so some of this code still looks C-like.

If you're using printf() because you're having trouble with formatting, then take a look at the <iomanip> library for something useful.
Unless you're debugging, assert may be unnecessary.  You can easily output an error message to std::cerr and return EXIT_FAILURE from main().
The value 4 used in main() appears to be a magic number and should be a constant.
Each use of std::endl flushes the buffer and takes extra time. Luckily, you're not using it in the timed section.  It's still not needed in most cases and you can also output a newline with "\n", which doesn't do a flush as well.  More info about that here.


In general, you don't need to split the string and then process the array. Simply you must start from the first letter and store its charcode and then process the next later and check with the incremented charcode. If there is a difference than just break.

function f(str) {
    if (str && 0 < str.length) {
        var desCharCode = str.charCodeAt(0);
        for (var i = 1; i < str.length; ++i) {
            ++desCharCode;
            if (str.charCodeAt(i) != desCharCode) {
                return String.fromCharCode(desCharCode);
            }
        }
    }

    return undefined;
}


Implement an algorithm for a room cleaning robot

TL;DR - I would not hire you
I am going to be fair here and state that I am judging this code more harshly because you are a not just any junior developer or applicant, but you are actually responsible for testing and technically evaluating potential hires. This implies a certain skill level, and it means that you should be innately able to display what the bar for the quality of the company's code is.
And to be quite frank, as an applicant, if I saw this as the proposed solution, I would genuinely back out of working for this company.
I spent more time reviewing this than you did writing it (if you kept to your own 45 minute limit), so I hope you appreciate that I'm not trying to be mean, but I am trying to be very direct about the many issues I've uncovered. The more I looked at your code, the more started realizing that it is deeply flawed, suffers from multiple reality 101 failures, and most of all it is painfully apparent that you never even tested it, not even once.
I wouldn't hire you (for any position above junior) for several reasons:

You are asking applicants to solve pathfinding, a notoriously difficult problem that has existed for decades and that to this day still has not been optimized (with reasonable performance), and you're giving them 45 minutes to do so. This is sheer insanity. Unless you are hiring for a game developer (or roomba developer) with significant prior experience, the posed challenge just doesn't fit the kind of applicant you're looking for.
Some of the issues I found are related to not grasping the elemental basics of the field you're trying to work with. That's general grounds for rejecting any applicant, let alone the interviewer who created the challenge to begin with. Interviewers who don't understand the subject matter they're interviewing about are not good interviewers.
You never even bothered to test your code. Some of these issues are blindingly obvious from the most barebones example, without even factoring in features like obstacles.
There is not a single situation in which your code works. It's not that you've forgotten to account for fringe cases, or specific features such as obstacle avoidance. Your code fails for a 2x2 empty room.
Furthermore, you also therefore didn't consider that applicants would like to be able to test and debug their code, which in my opinion raises red flags for both your roles as an interviewer and as a developer.

That being said, the code was formatted nicely.
I don't want to make you feel bad. We've all struggled with certain problems at one time or another. There are plenty of projects I've started that have been deeply flawed.
But I would strongly suggest you re-evaluate if you are the right person to evaluate these applicants for technical interviews. In the interest of the company, I do not think that you are the right person for the job without some significant improvements being made.
Test data and visualization tool
This is more a comment on the question rather than the solution, but behavioral logic of this kind is notorious for needing shotgun debugging. It's exceedingly hard if not impossible to see if this algorithm works as intended based on reading the code and not seeing it in action.
This applies to me needing to review your code now, you needing to check your applicants' code, as well as any applicant who'd like to debug their code while developing to find any obvious flaws.
I would strongly advise you to create a default test fixture where you have some predefined room setups to test the robot with, and a visual tool that shows you the room and the robot's progress step by step.
I will try to review your algorithm to some degree, but keep in mind that I did not write an entire test scenario for this. This is just based on what I can interpret by reading the code, and some experience I have with pathfinding logic.
Code structure
Based on the question as presented, I find it counterintuitive that you only add a robot interface without implementation, and then develop the "algorithm for a robot" in another class altogether. I'm not against separating the movement logic from the cleaning logic, but the names leave something to be desired. IRobot (and the presumed Robot class) don't indicate movement, and RobotManager doesn't indicate cleaning.
Especially for an interview question, I find this a really important sticking point. It shows you how well this developer is independently going to be able to keep your code clean.
Stack overflow
Your code relies on recursion, and the recursive stack size is finite. Therefore, you've implemented a natural cap on how big a room can be, and the way it behaves when it reaches that cap (StackOverflowException) is ugly.
I would strongly advice using some kind of iteration instead of recursion here. A for(each) is not going to be appropriate since you don't know the size of the room in advance, but a while would be appropriate here.
DRY and method naming
I don't like the Clean method name, because it is also the method which handles traversal, even though you also have a separate Traverse method. Something has gone awry here. You've duplicated the movement logic in both methods, and implemented them slightly differently.
That's not promoting reusability the way it should.
Your algorithm in general
There are frankly a lot of glaring issues with the logic itself. I can't delve into all of them in full depth. If you had had a visualization tool and test data, some of these would've been easy to spot. I'll elaborate on a few core issues, but quite frankly there's little logic to salvage here when you've noticed all the bugs.
It's important to observe that your Clean method is the only method being called to handle both the cleaning and the room traversal. Traverse is only used after the cleaning has been completed.
private void Clean(Node currentNode)
{
    if(currentNode.Cleaned)
    {
        return;
    }

If you back out of every cleaning operation when the current node has already been cleaned, that means that you are not allowing the robot to cross a cleaned node. That is a significant flaw in your logic. The easiest test case is having a room whose obstacles are laid out like a Bomberman level:

Try traversing all the green tiles in a continuous line without crossing your path.
You might be able to snake around the level and then get into the first dead-end street, and your robot will never turn itself around (it only attempts straight, left and right).
But even if it did turn around, when it tries to exit that dead-end street, it has to drive over a path it already drove over. And what does you code do then? Refuse to continue. It tries to backtrack back into the dead-end street.
Since it is no longer adjacent to any uncleaned and accessible tile, and therefore it will report that the cleaning has been completed.
You might think that my example is a fringe case for a room that's designed to trip up your system. But your logic fails for a completely empty room as well. Your logic is as follows:

Go straight
If you can't, go left
If you can't, go right
In any of the above cases, repeat the logic
In none of the above cases, back out and continue that recursion level's logic.

Placing the robot in a room, it's going to go straight until it can't, turn left once, go straight until it can't again, etc,... Think about what that means in visual terms:

Edit: I just noticed I forgot to number the first straight. Oops! Let's just say I totally intended to zero-index them...
After the straight that is (incorrectly) labeled 6 in the image, since it will never cross a tile that has already been cleaned, your robot has boxed itself in and will never clean the left half of the room (except the outer edge which it cleaned in the beginning).
Node-based traversal
This system just doesn't make any sense. The robot's interface is fine. You are clearly understanding that the robot only knows its own orientation, and therefore must be issued commands relative to its own position (without knowing its location in the room).
But then your node-based system throws all of that out the window and tries to dynamically build a room-scale grid, and issues commands based on the grid (which has the room as a reference point) to the robot (which has itself as a reference point).
You never check the robot's orientation. That's a massive red flag. It makes no sense to actively need to rotate a robot, and then never bother with using that rotation in your logic. Your logic decides to "go left", but since it doesn't know the orientation of the robot, how can it even figure out what "left" means to the robot?
I can't elaborate on the full ramification of this, but it essentially means that you cannot just assume that "node left" == "robot left", since the robot's orientation alters how the robot is oriented in the room. You've mixed two completely different coordinate systems and have not made sure they are compatible with one another.
Node-based traversal 2 - the big one
In my opinion, this is the biggest issue in your algorithm. This is something you should have spotted without even running the code.
Every movement moves onto a new Node(). You are not tracking any meaningful node state.
Let's imagine a 4 tile room, and the robot starts in the bottom right corner.

For brevity, I'm only focusing on the successful movement actions. The first 4 steps are what you intended them to be:

Go straight (new location: top-right)
Go left (new location: top-left)
Go left (new location: bottom-left)
Go left (new location: bottom-right)

I want to focus on what happens in step 3 when you realize that moving to the left was possible:
this._robot.TurnLeft();
if(this._robot.Advance())
{
    currentNode.Left = new Node();
    Clean(currentNode.Left);

The next node is a new Node(). But you actually already knew this location (because you have been there before). But your code makes no effort to check if this is a known location. It always blindly makes a new node.
Therefore, your entire clean-node-tracking logic is defeated:
    if(currentNode.Cleaned)
    {
        return;
    }

Since currentNode is always a newly created node, which by definition could not have been cleaned yet.
You've fallen into the age-old trap of thinking that compilers read intent, speak English, and figure out your system for you. Putting it another way:
var topLeft = new Node();
var topRight = new Node();

topLeft.Right = topRight;

var whatIsThisValue = topRight.Left;

Tell me what will be in whatIsThisValue. Is it your topRight object?
Nope. It's null. Just because left is the opposite of right doesn't mean that your code will automatically understand that "if B is right of A, then A must be left of B". That's just not how it works.
This issue renders your entire floor node state tracking logic, which the entire cleaning logic hinges on to know both how to avoid double work and to figure out when it's done, completely defeated.
Recursive backtracking
Next, we get to the recursive logic. It just doesn't make much sense. You lay out your pathfinding in recursive steps. Each recursive level will at some point attempt going forward, left and right. It doesn't just attempt one of these, it attempts all of them sequentially. When a movement attempt succeeds, it first drills down further, but the remaining movement attempts are still "queued" to happen when the recursive stack starts bubbling up again.
Following the above example, the robot will go straight for a few steps. Each step, that's a new recursive level. But you mustn't forget about the "queued" left/right commands from the first few steps. For now, you've drilled down into a new level, but what drills down will eventually bubble back up. Numbering the levels of recursion, you're looking at something like:

Straight 1 - success

Straight 2  - success

Straight 3  - success

Straight 4 <---- we are currently here

Left 3
Right 3

Left 2
Right 2

Left 1
Right 1

No matter how deep we dig into the recursive tree, Left/Right 1/2/3 will eventually be executed when we're done digging.
The problem with this is that backtracking on the recursive stack does not backtrack the robot's actual location. Therefore, the location in which Left 1 will be executed will be completely different depending on whether or not Straight 1 succeeded or not. This makes it impossible to know which location Left 1 is actually going to visit.
When you realize the chaos that this entails, you start understanding that you don't have an algorithm here, you have a brute force attack with just loads and loads of uncoordinated random movement.
If your robot had backtracked (i.e. moved backwards) whenever your Clean method returned (and bubbled up one recursive level), your logic would have been more correct. Still bugged, but the recursive approach would've at least made more sense.
The kind of recursive logic you're using here only works when each recursive level works in its own fixed location. But because you are dealing with a real robot in a room, whose location is altered by all of those recursive levels, it becomes impossible for each recursive level to ensure that its sequential operations (straight/left/right) are executed on the same fixed location regardless of what happened on lower recursive levels.


"Intelligent" removal of carriage returns that preserves paragraph breaks, headings, etc

Two things:

Try using String instead of [Char], it reads a lot easier (imho).
Don't use head, use pattern matching instead. It reads better, and it's good practice, because if it passes an empty list you will get an error (though you will not encounter that in this program, since you already check for empty lists).

If you wanted to have your program consider multiple lines, a quick and dirty solution would be something like this:

function :: [String] -> [Bool]
function [] = []
function [line1,line2] = [(shouldMerge line1 line2)]
function (line1:line2:morelines) = [(shouldMerge line1 line2)] ++ function (line2:morelines)

NOTE: I haven't tested the above code for bugs.

Another solution would be to make shouldMerge recursive, with a type of [String] -> [Bool].


Function to remove duplicated elements from an Array

Is there a better solution?
Yes, always... biting my tongue.
So first let's look at the function you have.
The JS array functions that take a callback as an argument, like reduce, are slow in comparison to standard loops so for more code you can get a performance increase by implementing only what you need in a reduce function. But we can avoid that as well.
Using a Set
The includes function is also a little inefficient. It needs to iterate each item in the new array and test it against the current item. This can be improved by using a hash table. JS has two objects that use hash table lookups Set and Map. For this case Set will improve the search for duplicates and will also serve to hold the unique array while processing.
If we are going to use a Set we can take advantage of the constructor that will create a set from any iterable object. Thus all we need to do is create the set from the array, then convert the set back to an array as it will have removed the duplicates.
Thus

const withDuplicates = [1, 2, 3, 4, 4, 4, 5, 5, 6, 7, 8, 9, 9, 9, 10];
function removeDuplicates(arr){
   return [...(new Set(arr)).values()];
}
console.log(removeDuplicates(withDuplicates));

I think that is what you may consider better, however it does involve an extra iteration when converting back to the array. To improve on that we would need to create our own Set with a hash table lookup. To do that in JS will never be as fast as the native code, so we can just accept that the complexity is unavoidable in favor of speed.


Using the max of two consecutive values is asymmetric.
(I'd simply use the value sampled, avoids the following issue, too:)
For most every "sample" (i), the code computes the value of f() twice (f(prevI)): keep prevF instead
a double (64 bits in Processing, as in Java) may be a saner type designator than float (32 bits),
especially for "the accumulator" sum.  When the number of summands approaches the number representable by its mantissa, you need a more sophisticated strategy than adding in numbers one by one.
the code multiplies each and every h by step:
don't, instead, multiply sum by step after the loop
(similarly, don't count trips/iterations, compute as (b-a)/step)
consider making step a parameter
(My pet idea would be setting a time limit and adding samples until time is up.
Depending on sampling strategy, keeping track of weights (width of the trapezoids, step) is a challenge.)


Use a bit more spaces. It will make your code more readable.
Try to be coherent with your indents
You should sanitize input. What happen if user enter a number greater than 9 ? Or 0, 1, or 2? Or negative number? Or not a number? Never trust user, They all try to broke your program.
When you just print on char, prefer putchar() instead of printf().

Here's my solution, maybe not the most optimal, but clean and short. I compute the distance from the current coordinate to nearest side and then remove it to the base number.

#include <stdio.h>
int main(void) {
    int n = 5;
    int a;
    int b;
    const int m = 2*n-1;
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < m; ++j) {
            a = (i >= n) ? m - i - 1: i;
            b = (j >= n) ? m - j - 1 : j;
            putchar('0' + n - ((a < b) ? a : b));
        }
        putchar ('\n');
    }
    return 0;
}

To improve this, you could split the inner loop to avoid the two conditional assignments. I let you trying to do it yourself.


You might be able to save the overhead of constructing a new generator on each call, with something like:

static std::mt19937 default_generator(std::random_device{}());

static int getInt(int min, int max)
{
    return std::uniform_int_distribution{min, max}(default_generator);
}

But, given that most uses require several values from a single distribution and there's rarely a need to use more than one generator, is this header really worth its cognitive load?  Each function is a one-liner, and even less if the distribution can be re-used over several calls.

We'd also expect to have versions for longer or unsigned integer types, and for double and other floating-point types.  It probably makes more sense for it to be a template:

#include <random>
#include <type_traits>

template<typename T>
inline T getUniformRandom(T min, T max)
{
    static std::mt19937 default_generator(std::random_device{}());
    if constexpr (std::is_integral_v<T>) {
        return std::uniform_int_distribution{min, max}(default_generator);
    } else if constexpr (std::is_floating_point_v<T>) {
        return std::uniform_real_distribution{min, max}(default_generator);
    }

    static_assert(0, "getUniformRandom requires an arithmetic type");
    return min+max;             // just to eliminate compiler warnings
}

Alternatively, use std::enable_if instead of if constexpr:

#include <random>
#include <type_traits>

template<typename T>
inline std::enable_if_t<std::is_integral_v<T>, T> getUniformRandom(T min, T max)
{
    static std::mt19937 default_generator(std::random_device{}());
    return std::uniform_int_distribution{min, max}(default_generator);
}

template<typename T>
inline std::enable_if_t<std::is_floating_point_v<T>, T> getUniformRandom(T min, T max)
{
    static std::mt19937 default_generator(std::random_device{}());
    return std::uniform_real_distribution{min, max}(default_generator);
}


First of all, readyState 4 simply means XHR is done. The response, however, can still either be a success (2xx) or a failure (4xx, 5xx). In order to distinguish a success from an error, you should also check status.

Next would be the reuse of the XHR instance. Although it's perfectly valid (open reinitializes the instance), you'll have to be absolutely sure subsequent calls aren't affected by the previous calls. It's probably much safer to just create a new instance of XHR for each request.

Then instead of window.onload, consider using addEventListener. The issue is that there might be other scripts assigning a callback to window.onload, overwriting your handler. On the other hand, multiple calls to addEventListener will just append handlers.

A simpler way to do it, assuming your target audience doesn't use legacy browsers, is fetch. It's essentially jQuery's $.ajax but natively implemented.

window.addEventListener('load', event => {
  setInterval(() => {
    fetch('data.geojson', {
      method: 'GET',
      headers: { authenticated_user: 'terrain' }
    }).then(() => {
      console.clear();
      console.log(request.response);
    })
  }, 2000)
})


There are several things worth considering when you are about to design an API, which should either return an IAsyncEnumerable<IAsyncEnumerable<T>> or return an IAsyncEnumerable<T>

IAsyncEnumerable < IAsyncEnumerable < T > >

Pros

It is flexible from the consumer point of view. It allows you to use a single or multiple consumer model
In case of multiple consumers the throughput can be higher, because the parallel processing potential
It allows to use different Timeouts for different providers
It allows custom code injection between two yield return statements

Cons

In case of single consumer the ingestion logic can be a bit more complicated (compared to the flatten version)
Nested async loops can complicate the exception handling logic (and also the debugging)

IAsyncEnumerable < T >

Pros

It is easier to use for a single consumer
If the multiple provider model is just an implementation detail then it can hide this information behind a good abstraction
It provides easier error handling capabilities

Cons

It is harder to support multiple consumers model
It is harder to inject custom code between yield returns
Spanning new processing based on different providers is impossible

If you are considering to provide a flattened API then I would suggest to check that package, which is called System.Interactive.Async. Inside this package there is a class called AsyncEnumerableEx which defines a Merge function.


Pandas add calculated row for every row in a dataframe

iterrows
Of all the ways to iterate over a pandas DataFrame, iterrows is the worst. This creates a new series for each row. this series also has a single dtype, so it gets upcast to the least general type needed. This can lead to unexpected loss of information (large ints converted to floats), or loss in performance (object dtype).
Slightly better is itertuples
append
Appending row per row can be very slow (link1link2)
Better would be to assembly them in a list, and make a new DataFrame in 1 go.
vectorise
One easy change you can make is not iterating over the database in 'Python' space, but using boolean indexing
x = df["variable"] == "x"
y = df["variable"] == "y"

df2 = df.copy()
df2.loc[x, "value"] = df.loc[x, "value"] * a + b
df2.loc[y, "value"] = df.loc[y, "value"] * c + d
df2.loc[x, "variable"] = "x1"
df2.loc[y, "variable"] = "y1"

wide vs long
This can be made a lot easier by reforming your dataframe by making it a bit wider:
df_reformed = (
    df.set_index(["id", "variable"]).unstack("variable").droplevel(0, axis=1)
)

variable  x   y
id
1     5   5
2     7   7

Then you can calculate x1 and y1 vectorised:
df_reformed.assign(
    x1=df_reformed["x"] * a + b,
    y1=df_reformed["y"] * c + d
)

and then convert this back to the long format:
result = (
    df_reformed.assign(
        x1=df_reformed["x"] * a + b,
        y1=df_reformed["y"] * c + d
    )
    .stack()
    .rename("value")
    .sort_index()
    .reset_index()
)


Starting at the top

//any suggestions

Yes, plenty. But don't add that to the code.

using namespace std;

Nearly every beginner includes this (and it's understandable because this is what they do in books).

In actual practice this is a bad idea. Never include this line in real code. The reason books include it is to save space (because each printed page costs extra). When writing real code, this will create bad habits that will bite you in the end so it is a habit you should break now.

see: Why is “using namespace std;” considered bad practice?

node class

protection level

There is no need to make the node class public. This is internal to your linked list so you should hide its implementation from other people by making it a private member class of the linked class.

style

class Node
{
        friend class linked;

        private:
                int data;

        public:
                Node *link;
                Node()
                {
                        data=0;
                        link=NULL;

                }

};

Small note on vertical spacing: there is way too much here. It's a small class so it does not stand out. But if you do the same thing on a bigger class it becomes hard to read. Now don't take this to the extreme and completely eliminate vertical space-- break things up into logical units.

Since we are making this class a private member of linked there's no need for friendship; just make everything public.

But we can improve the code by having a constructor that takes the data value and the link (if you look at your code you could use both at the same time. When writing constructors, it's preferred to use the initializer list syntax to initialize members:

                Node(int data, Node* link)
                    : data(data)
                    , link(link)
                {}

You will notice here that everything is lower case. It is relatively common to define user-defined types with an initial capital letter, while objects have an initial lower case letter. This allows you to quickly see the difference between types and objects (an important distinction in C++).

So, following this style, your code should look like this:

class Linked
{
    struct Node
    {
        int    data;
        Node*  next;
        Node(int data, Node* next)
            : data(data)
            , next(next)
        {}
    };

    ....

linked class

class linked
{
        public:
                Node *start=NULL;
                Node *ptr;
                Node *temp=NULL;

                void append(int item);
                void traverse();

};

Not sure what all the pointers are for? OK start marks the start of the list (usually called head). But what are the others supposed to represent? If they are really just things you use a throw away then they can be local to the function methods and not part of the class.

You call new in your code. For every call to new there must be a corresponding call to delete. Otherwise you will leak memory (and resources). So the best place to do this is in the destructor.

Also you are missing a constructor. This means that all you member variables are likely to be undefined (this means they have random values in them. C++ (unlike Java and other languages at this level) does not do automatic initialization of variables.

see: Why aren't pointers initialized with NULL by default?

So lets add the constructor and destructor

class Linked
{
    struct Node
    {
        int    data;
        Node*  next;
        Node(int data, Node* next)
            : data(data)
            , next(next)
        {}
    };

    Node*   head;

    Linked():
        head(nullptr)
    {}
    ~Linked()
    {
        Node* tmp;
        for(;head;head = tmp)
        {
            tmp = head->next;
            delete head;
        }
    }
    ...

If we look at append. You get the correct test for adding an element to an empty list. But it starts to go wrong in the second half where you are using a loop.

The member temp is not initialized. It is also public -- this means it could have been altered since last time you used it. So it is best to use a local variable that you initialize to head.

Note: you can also use the new constructor for node to reduce code in this function.

void Linked::append(int item)
{
    if (head == nullptr)
    {
        head = new Node(item, nullptr);
    }
    else
    {
        // First find a pointer to the last item in the chain.
        Node* last = head;
        while(last->next)
        {
             last = last->next;
        }
        // Now just add the node.
        last->next = new Node(item, nullptr);

        // Notice this loop happens each time you add an element.
        // This makes adding an element relatively expensive.
        // To avoid this a lot of implementation keep two pointers
        // in the list a `head` and a `tail`. That way data elements
        // can be quickly added to the tail.

        // When you start adding things like delete.
        // It becomes useful to know your previous element.
        // So it is also very common for the node object to have
        // two pointers `next` and `prev`
     }

Note: we always seem to place nullptr as the second argument. So we could potentially remove it. But if you try to implement an insert function then it becomes useful:

void Linked::insert_at_head(int value)
{
    head = new Node(item, head); // See very useful.
}

Not sure what your traverse is doing.

void linked::traverse()
{
        Node *trav=start;
        while(trav!=NULL)
        {
                cout<<trav->data<<endl;
                trav=trav->link;
        }

}

I would just name that print; traverse implies going through a tree.

One way to improve the functionality and modularity of traverse would be for it to take a parameter of a function that should be applied to all the nodes (but I think that is a bit beyond this exercise). So a couple of things here:

Rename to print
Mark the function as const
It does not alter the state of the object. So it is safe to call on a const version of the object.
Printing in C++ is usally done by operator<<
so create one of these that calls your print method.

Like this:

void Linked::print(std::ostream& str = std::cout) const // Note const
{
        Node *trav=start;
        while(trav!=NULL)
        {
                // Added space here so yo can see the <<
                // and what they are applied too.
                //
                // Also prefer "\n" to std::endl (especially in here)
                // The std::endl forces a buffer flush. Doing this
                // after printing every integer becomes very inefficient.
                str << trav->data << "\n";
                trav=trav->next;
        }
}
std::ostream& operator<<(std::ostream& str, Linked const& data)
{
     data.print(str);
     return str;
}

I think we have now covered enough in one review. I would have another bash at this example. Once you have done that post the code for review again and we can go into some other details.


Function/method to get selective columns

I'd suggest your code to be rewritten like this (please, take note of the inline comments):

<?php

// Requires PHP >= 5.4

public function getRows($ntt, $cols = array(), $where = array(), $result_type = null)
{
    $data = 'nulllllll';

    // Early return after checking arguments,
    // instead of nesting the rest of the code inside the if{}
    if (!($ntt && $where && is_array($where))) {
        return $data;
    }

    $filters = [];
    $param = [];

    // The callback function here uses outer variables: `$filters` and `$param`,
    // that are passed by reference `&`
    array_walk($where, function($value, $key) use (&$filters, &$param) {
        static $i = 0;
        $i++;

        $placeholder = "v{$i}";
        $condition = is_array($value) ? "in (:{$placeholder})" : "= :{$placeholder}";
        $filters[] = "tm.{$key} {$condition}";
        $param[$placeholder] = $value;
    });

    // Use `implode` to concatenate the `$filters` into a string
    $filter = implode(' AND ', $filters);

    $select = 'tm';
    if (!empty($cols) && is_array($cols)) {
        $select = implode(', ', array_map(function($column) {
                return "tm.{$column}";
            }, $cols));
    }

    $repository = "AppBundle:{$ntt}";
    $data = $this->em->getRepository($repository)->createQueryBuilder('tm')
        ->select($select)
        ->where($filter)
        ->setParameters($param)
        ->getQuery();

    if ($result_type === 'array') {
        return $data->getArrayResult();
    }

    return $data->getResult();
}


Find "secure file erase" commands on the system

You have no synchronization for these package variables
var shredPath, shredFlag string

Therefore,
fmt.Println(shredPath, shredFlag)
go func() {
    for i := 0; i < 1000; i++ {
        shredCmd()
    }
}()
for i := 0; i < 1000; i++ {
    shredCmd()
}
fmt.Println(shredPath, shredFlag)

WARNING: DATA RACE
Found 3 data race(s)

os.Remove() and commands may fail if the file is open.
If you encounter something unexpected, for example Windows, you do nothing, not even os.Remove().
The if statements are ugly. Since shredCmd() is effectively a test, use the standard testing package technique, table-driven tests.
You provide no context for usage or testing, for example
func ShredFile(filename string) error {
    // ...
}

And so on.

Here's an attempt to fix some of the issues:
shred.go:
package main

import (
    "errors"
    "fmt"
    "io/ioutil"
    "os"
    "os/exec"
    "time"
)

var shredCmds = []struct {
    name, opts string
}{
    {"shred", "-u"},
    {"srm", "-f"},
    {"rm", "-Pf"},
    {"rm", "-f"},
    {"sdelete", "-a"},
}

func shredTemp(path, opts string) error {
    file, err := ioutil.TempFile("", "shredTemp.")
    if err != nil {
        return err
    }
    filename := file.Name()
    defer os.Remove(filename)
    defer file.Close()

    err = file.Close()
    if err != nil {
        return err
    }
    err = RunCmd(path, opts, filename)
    if err != nil {
        return err
    }
    return nil
}

var shredPath, shredOpts = func() (string, string) {
    for _, cmd := range shredCmds {
        path, err := exec.LookPath(cmd.name)
        if err != nil {
            continue
        }
        err = shredTemp(path, cmd.opts)
        if err == nil {
            return path, cmd.opts
        }
    }
    return "", ""
}()

func ShredFile(filename string) error {
    fi, err := os.Stat(filename)
    if err != nil {
        return err
    }
    if !fi.Mode().IsRegular() {
        err := errors.New("filename is not mode regular")
        return err
    }

    if shredPath == "" {
        return os.Remove(filename)
    }

    err = RunCmd(shredPath, shredOpts, filename)
    if err != nil {
        return err
    }
    return nil
}

func RunCmd(command string, args ...string) error {
    cmd := exec.Command(command, args...)
    cmd.Stdin = os.Stdin
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    err := cmd.Start()
    if err != nil {
        return fmt.Errorf("RunCmd cmd=%q err=%w", command, err)
    }
    err = cmd.Wait()
    if err != nil {
        return fmt.Errorf("RunCmd cmd=%q err=%w", command, err)
    }
    return nil
}

func main() {
    file, err := ioutil.TempFile("", "ShredFile.")
    if err != nil {
        fmt.Println(err)
        return
    }
    filename := file.Name()
    file.Close()
    defer os.Remove(filename)
    start := time.Now()
    err = ShredFile(filename)
    since := time.Since(start)
    fmt.Println(filename, since, err)
}


@Flambino has already explained the main problems in your code. I'd only add: 1) why do you use each_with_index if you don't actually use the indexes? 2) Ruby would have a terrible standard library if you needed 4 lines just to read the contents of a file: contents = File.read(path).

That's how I'd write it:

require 'nokogiri'
require 'json'

kml = Nokogiri::XML(open("Stateborders.xml"))
coordinates_by_state = kml.css("Placemark").map do |placemark|
  state = placemark.at_css("name").text.strip
  coordinates = placemark.at_css("coordinates").text.strip.lines.map do |line|
    line.split(",").map { |coord| coord.to_f.round(6).to_s }
  end
  [state, coordinates]
end.to_h

jscode = "var stateBorders = #{coordinates_by_state.to_json};"
File.write("stateborders.js", jscode)


Directory that lists employee information

The answer is that there is a definite performance gain in having it all in a single join. Just the reduction in back and forth should greatly decrease the latency, and the database engine should be way more effective.

For a more general view on that topic :

Will the request be hard to understand later ? This is the most important question, as it will be the difference between maintainable code and code nobody will dare touch. In this particular case, I would say there is an obvious request to write, and that it will be fairly easy to understand. If you don't feel this is the case, then you probably should not go this way (premature optimization, etc.).
How complex will be the whole solution ? Displacing logic from PHP to SQL is often a good idea, but might have drawbacks :

hidden logic (triggers, or opaque stored procedures) that is hard to understand later
vendor lock-in (when using advanced features that are not standard).
poor performance : with complex queries, it becomes hard to evaluate the run-time performance

It seems to me that a straightforward 5 tables join is far from complex, and is a lot less ugly than the PHP code displayed here. You would get rid of all the content of the while loop ...
How much will the performance be impacted ? For a low-traffic web application, which is the most common case, this should be the last concern.


First of all, I recommend you to ensure your code is correct (see my comment on your question).

Here are a few suggestions about improving your code.

Please do not use non-informative names like w, ww, sep, kArg, cW, CK, and even the "well-known" i, j, k, m, n. They are absolutely horrible. They make decent code be an unreadable puzzle. They hide the intent and make me think where I should not be.
Please always make sure you use Type when a) the compiler loses (or is unable to infer) the type information; b) you can narrow down the type. That includes the function return type. Typing is not panacea but it helps prevent an entire class of bugs.
Do not use generic methods smth<T>(...) unless you use the type T information anywhere in the function.
Minimize the distance between variable declaration, assignment, and first usage. Better declare and assign in the same place. Ideally, find a way to not even declare a variable.
In error messages be more specific about what went wrong.

  const star = '*';
  const twoStars = '**';

  export class RadioService {
    private separator = ':';
    private _eventBus = new Subject<RadioEvent>();
    private _eventCacheBus = new ReplaySubject<RadioEvent>();

    keyMatch(keyList: string, wildcardList: string): boolean {
      const isMatch = (wildcard, key) => (wildcard === star) || (wildcard === key);

      const allKeys = keyList.split(this.separator);
      const allWildcards = wildcardList.split(this.separator);

      const keyWildcardPairs = allKeys
        .reduce((accum, current, index) => {
          accum.push([current, allWildcards[index]]);
          return accum;
        }, <string[][]>[]);

      return keyWildcardPairs.some(pair => {
        const key = pair[0];
        const wildcard = pair[1];
        // '**' match all gragments
        if (wildcard == twoStars && (typeof key !== 'undefined')) {
          return true;
        }
        // test if fragments match
        if (!isMatch(wildcard, key)) {
          return true;
        }
        return false;
      });
    };

    cast(key: string, data?: any): void {
      if (typeof key !== 'string' || key.length <= 0) {
        throw `Bad key '${JSON.stringify(key)}'. Please provide a non-empty string.`;
      }

      this._eventBus.next({ key: key, data: data });
      this._eventCacheBus.next({ key: key, data: data });
    };

    on(key: string, count?: number): Observable<any> {
      const _this = this;

      const normalObservable = this._eventBus
        .filter(event => _this.keyMatch(event.key, key))
        .map(event => event.data);

      const withoutReplay = _.isNil(count);
      if (withoutReplay)
        return normalObservable;

      const subject = new ReplaySubject<number>(count);
      this._eventCacheBus
        .filter(event => _this.keyMatch(event.key, key))
        .map(event => event.data)
        .subscribe(value => subject.next(value));

      return Observable
        .merge(normalObservable, subject)
        .distinct();
    }
  }


Workaround for have 2 column with pseudo AUTO INCREMENT

$query_Recordset4 = "SELECT MAX(IDyear) AS maxyear FROM order";

Whenever you need to postfix the name of a variable, class or anything else with number because you already used that name...you're doing it wrong. Either your function does too much and should be split into smaller functions, or you need to choose better names.

$query_Recordset5 = "SELECT MAX(numberorder) FROM order WHERE IDyear=$thisyear ;";

Even when you declare the variable, you should make a habit out of using parameterized queries.

There's something wrong about your table layout. At the moment I imagine it should look something like this:

TABLE order
    numberorder INT
    IDyear INT

A more sane layout would be this:

TABLE order
    id INT AUTO_INCREMENT
    idYear INT
    orderedAt DATETIME

The main difference is that I rely on an ID field which is managed by the database. It does not matter what the accountant wants or how your boss thinks the billing numbers should look like, you need something unique to identify a record and nothing beats a unique, automatically managed counter for doing that job.

Creating the necessary number you want is as easy as

SELECT CONCAT(idYear, '/', YEAR(orderedAt)) FROM order;

and if you place this in a stored procedure or in a function in your object you never need to think about it again. Incrementing this number is also rather easy:

SELECT IFNULL(MAX(idYear), 0) + 1 FROM order WHERE YEAR(orderedAt) = yourYear;

It can not break and you're free to put the date of the order into the past or the future (which is sometimes needed in accounting). In your method working outside of the current year will break the numbering.

Ideally you would set that number if you insert the record into the database to minimize race-conditions (and possible duplicate numbers).


Project Euler problem 44: sums and differences of pentagonal numbers

Some observations:

To do integer division in Python 3, you should use the // operator. For example, you should prefer to do (x*(3*x-1))//2 over int(x*(3*x-1)/2); the latter expression can run into annoying rounding issues for very large values of x.
It looks like the variables test, lst, and list2 all contain the same set of numbers (in fact, lst and list2 even point to the same object). There's no reason you need different variables for all of these.
In particular, it is completely fine to do for x in lst: followed by for y in lst:; no need to rename the second list for some reason.
I am not sure what the point of the set comprehension [dict(t) for t in set([tuple(d.items()) for d in dic])] is; it seems like it will just return to you the original list dic, possibly permuted.
You don't really need to store an auxiliary dictionary at all; just keep track of which valid pair of pentagonal numbers has the smallest difference. To do this, I'd recommend adding a best variable to keep track of the best valid pair so far, and moving the checks you do in your last two nested for loops into the loop where you iterate over lst.


SEDE Query to Find... Weird Question/Protect Combinations

One of the first things you should do if you have an arbitrary data set (as you do in your list of UserIds) would be to extract it out of the WHERE clause. Just make a @TempTable variable. If the data set gets very large, consider a "physical" #TempTable.
DECLARE @UsersToExclude TABLE (UserId INT PRIMARY KEY);
INSERT INTO @UsersToExclude (UserId)
VALUES
  /*Some comments to explain these numbers would be good:*/
  (419),
  (1228),
  (1288),
  (19679),
  (23354),
  (50049),
  (59303),
  (102937),
  (106224),
  (246246),
  (-1);

Then you can just do an existence check in your query:
   AND ph.UserID NOT IN (
     SELECT usrExcl.UserID from @UsersToExclude as usrExcl
   )

Please get into the habit of using the (optional) keyword AS to reference to table aliases. If not used it can be ambiguous whether it's supposed to be an alias or a query hint for something else, like NOLOCK.
FROM PostHistory AS ph
  JOIN Posts AS p ON ph.PostID = p.id

This bracketing style is a bit unusual:

LEFT JOIN
  ( SELECT foo
   FROM bar
   WHERE ...) AS Unprotected ON Unprotected.PostID=ph.PostID

It looks like LISP-style brackets. Most often in SQL either C# or Java style brackets are used (depending on the programming shop).
C#-style
LEFT JOIN
(
    SELECT foo
    FROM bar
    WHERE ...
)
AS Unprotected ON Unprotected.PostID=ph.PostID

Java-style
LEFT JOIN (
    SELECT foo
    FROM bar
    WHERE ...
) AS Unprotected ON Unprotected.PostID=ph.PostID

What does this number mean?

WHERE ph.PostHistoryTypeID=19

No easy way to tell. Consider something like:
DECLARE @QuestionProtected INT = (SELECT Id FROM PostHistoryTypes WHERE Name = 'Question Protected');

Then it's easier to follow:
WHERE ph.PostHistoryTypeID = @QuestionProtected

SEDE magic
You can get this valueat the top, or assign a default value for newbies like me:
-- postViews: Number of post views
DECLARE @postViews INT = ##postViews:int?10000##;

The other one is a script variable so it can't be manipulated as easily, but can still be assigned a default value (and documented):
WHERE
  ph.UserID IN (
    -- NumbUsers: Max number of users
    SELECT TOP ##NumbUsers:int?5000##

One more thing,
  AND isnull(Protected.ProtectCount,0) != isnull(Unprotected.UnprotectedCount,0)

The != operator is not SQL standard. Instead, use <>. Also, consider using COALESCE() instead of ISNULL() for some of the reasons listed here. Performance is right about the same, but it handles types better, usually (and can take more than 2 arguments, if needed).

Everything combined (demo on SEDE)
-- postViews: Number of post views
DECLARE @postViews INT = ##postViews:int?10000##;

DECLARE @UsersToExclude TABLE (UserId INT PRIMARY KEY);
DECLARE @QuestionProtected INT = (SELECT Id FROM PostHistoryTypes WHERE Name = 'Question Protected');
INSERT INTO
  @UsersToExclude (UserId)
VALUES
  /*Some comments to explain these numbers would be good:*/
  (419),
  (1228),
  (1288),
  (19679),
  (23354),
  (50049),
  (59303),
  (102937),
  (106224),
  (246246),
  (-1);
SELECT
  [Post Link] = ph.PostId,
  [User Link] = ph.UserId,
  Protected.ProtectCount,
  Unprotected.UnprotectedCount,
  p.ViewCount
FROM
  PostHistory AS ph
  INNER JOIN
    Posts AS p ON ph.PostID = p.id
  LEFT JOIN (
    SELECT
      count(UserID) AS ProtectCount,
      PostID
    FROM PostHistory ph
    WHERE ph.PostHistoryTypeID = @QuestionProtected
      GROUP BY PostID
  ) AS Protected ON Protected.PostID = ph.PostID
  LEFT JOIN (
    SELECT
      count(ph.UserID) AS UnprotectedCount,
      PostID
     FROM PostHistory ph
     WHERE ph.PostHistoryTypeID=20
     GROUP BY PostID
  ) AS Unprotected ON Unprotected.PostID = ph.PostID
WHERE
  ph.UserID IN (
    -- NumbUsers: Max number of users
    SELECT TOP ##NumbUsers:int?5000##
      ph.UserId
    FROM PostHistory ph
      JOIN Posts p ON ph.PostID=p.id
    WHERE ph.PostHistoryTypeId = @QuestionProtected
      AND p.ViewCount < @postViews /* exclude former moderators */
      AND ph.UserID NOT IN (
         SELECT usrExcl.UserID from @UsersToExclude as usrExcl
      )
    GROUP BY ph.UserId
    ORDER BY COUNT(ph.UserId) DESC
  )
  AND ph.PostHistoryTypeId = @QuestionProtected
  AND p.ClosedDate IS NULL
  AND p.ViewCount < @postViews
  AND COALESCE(Protected.ProtectCount,0) <> COALESCE(Unprotected.UnprotectedCount,0)
ORDER BY ph.UserId ASC;