I don't understand the need for two queries.  They seem to be retrieving the same exact result set, so why query twice?

Your code is difficult to read because of the inconsistent indentation and the inconsistent way in which you render your HTML output (sometimes dropping out of PHP, sometimes echoing out of PHP, for more or less that same type of use case).
 I would also encourage you to get better with overall style consistency.  Variable names are not very meaningful (querya/queryb). Spacing around operators is inconsistent. Spacing around parenthesis is inconsistent.  Use an IDE that allows you to enforce a styleguide and stick with it.

The nesting in your while loop is a bit out of control. You should think about inverting conditionals and/or using continue to clean up these nested conditionals.  Consider how much easier it is to read code like this:

<?php
while ( $findquetes = $querya->fetch() ) {
    if ($queryb->fetchColumn() <= 0) {
?>
<button
    class="peter-river-flat-button"
    style="border-radius:6px; padding-left:45px; padding-right:45px;"
    onclick="window.location.href='../quete/vigier.php'"
>Quête - Le Vigier (Disponible)</button>
<?php
        continue;
    }
    if ($findquetes["comp_quetej"] <= 0) {
        continue;
    }
    if ($findquetes["comp_quetej"] < 1) {
?>
<button disabled class="pomegranate-flat-button"
    style=" border-radius:6px; font-size:15px; padding-left:45px; padding-right:45px;">Quest - Quest 1 (Ongoing)</button>
<?php
        continue;
    }
    if($findquetes["recomp_quetej"] <= 0) {
        continue;
    }
    if ($findquetes["recomp_quetej"] < 1) {
?>
<form action="" method="POST">
    <input type="submit" class="peter-river-flat-button"
        style=" border-radius:6px; font-size:15px; padding-left:45px; padding-right:45px;"
        value="Quest - Quest 1 (Confirm the quest)" name="confirmerquete"></form>
<?php
        continue;
    }
?>
<button class="emerald-flat-button"
    style=" border-radius:6px; font-size:15px; padding-left:45px; padding-right:45px;">Quest- Quest1 (Finished)</button>';
<?php
}

Now, the code path is much more clear, and having done your conditionals this way, you can clearly see what might be problematic conditional logic in your current approach (what happens with certain values between 0 and 1?). What I have shown above obviously still needs to be cleaned up to the point where the design intent is made clear.  The general philosophical approach should be to make quick exits from functions/loops, etc. to enable you to de-nest your happy path code.  Also note that there are very few times where you really need an else condition.  If you have written an else, you may want to revisit your condition to see if there is a better way.

Note that you should also de-nest your very last conditional.  You have ~15 lines of code inside a conditional when it doesn't need to be.

Why so much inline styling?  If you have class names being used, why are these styles not attached to the classes in external CSS? This certainly makes code harder to read the way you have it. This along with perhaps getting to a better approach for templating your display code would server you well in getting to a higher quality code base.

onclick="window.location.href='../quete/vigier.php'"

Do you really need this in javascript as opposed to setting form's action or using a simple <a> styled similarly to button?

If you really need to apply javascript here, consider moving away from in-line usage.  Over time you will begin to realize that separation of application display and behavior code allows for a tremendous amount of code re-use.  Consider putting this in document.ready handler and applying it to element based on class or id.

You should be able to combine you to update queries against users table into a single query.

I don't know what DB class you are using, but it is unclear how you handle unexpected database interactions.  What happens is prepare fails? What happens if execution fails?  Are there any possible exceptions you should be catching or error handling that should be in place?  You code seem to really only consider "happy path".

I find it odd to have all you POST logic crammed way down at the bottom of the script after the point where you have already rendered output to the browser. Ideally, if you have a script which have different GET and POST logic, you would handle all the database interactions up front and make it much clearer earlier in the script whether the code is relevant to GET or POST.

Why would $findquetes be part of the conditional criteria for this POST logic?  This variable may or may not even be populated with a record.


The <iostream> header is not used.

min_distance can theoretically return an uninitialized value if all elements of visited_set are nonzero.  This shouldn't happen here, but initializing min_index = 0 would remove a potential problem and compiler warning.

display assumes that node 0 is the start node, but that value is passed in to dijkstra.  It should be passed in as a parameter.

In dijkstra, the graph parameter could be const int graph[N][N], which would then allow the graph variable in main to also be const.  The parent[0] = -1 assignment seems to be a typo.  It should be parent[i] = -1; to initialize all elements of parent.  The for (int n = 0; n < N; n++) loop should have curly brackets around its body.  While not currently necessary, having them in can avoid future problems when the code is modified and makes it clearer what is in the loop body rather than looking like a line with bad indentation.


Function for checking if a string is a path or an URL be improved

Some high level comments:

Checking if a string is a url (or a path) is usually done using regular expressions that can be found online. Not sure what's the scope of this function, but it can be seen as reinventing the wheel and might miss some uncommon cases
The method name gives the impression that returning True means it's a path, and False means that it's not, where in fact False has the meaning of being a URL. I would split this function into two: isPath where False just means that the given string is not a Path, and isUrl where False means it's not a URL. Or at the very least renaming it to isPathOrUrl
It's a personal preference but I'd change elif to be if as all the conditional bodies are returning something so no need to use else


Perhaps switching the outputfile for each line can be avoided by sorting the inputfiles first or with some changes in your script:
# Store the 2-letter filenames
outfile[Fpath];
# Store the highest index for given outputfile
i[Fpath]++;
# Store current line in output array for that file
a[Fpath][i[Fpath]]=$0
# And in the END block print for array per output file
      for (out in outfile) {
         for (j=1;j<=i[out]; j++) {
            print a[out][j] >> out;
         }
      }

This results in
awk '
    BEGIN {
        FS=":"
    }
    {
        gsub(/^[ \t"'\'']+|[ \t"'\'']+$/, "")
        $0=gensub("[,|;: \t]+",":",1,$0)
        if (NF>1 && $1 ~ /^[[:alnum:]_.+-]+@[[:alnum:]_.-]+\.[[:alnum:]]+$/ && $0 ~ /^[\x00-\x7F]*$/)
        {
            Fpath=tolower(substr($1,1,2))
            Fpath=gensub("[^[:alnum:]]","_","g",Fpath);
            outfile[Fpath];
            i[Fpath]++;
            a[Fpath][i[Fpath]]=$0
        }
        else
            print $0 >> "errorfile"
    }
   END {
      for (out in outfile) {
         for (j=1;j<=i[out]; j++) {
            print a[out][j] >> out;
         }
      }
   } ' "$FILE"


Your client JavaScript indentation is very, very messed up. I can hardly understand what's going on.

Some lines are missing an indentation, and some have an extra indentation, or even an extra space (which is extra very messed up, because you are leaving the alignment of a tab/indentation).

Everything inside the very first function should be indented one tab. Everything inside the socket.on's second parameter should be indented another tab. Everything inside $(#button).on's first parameter should be indented another tab.

Here is your tab code cleaned up:

$(function(){
    var groupid = 2; //this groupid will change in the actual app. Right now is hardcoded. At tun time, this roupid is passed from php.
    var socket = io("http://104.236.19.119:3000");
    socket.on('connect',function(){
        window.alert("You are connected.");
    });

    $('#button').on('click',function(){
        var entry = $("#entry").val();
        var reply_msg = {"content" : entry, "group":groupid};
        socket.emit('reply',reply_msg);
        $("#entry").val("");
    });
    var groupname = groupid + "chat";
    //got the msg and append to chat window
    socket.on( groupname , function(data){
        var new_msg = $("<p>" + data.content + "</p>");
        $('#msg').append(new_msg);
    });
})

This code is much, much easier to read.

$('#button').on('click',function(){
    var entry = $("#entry").val();
    var reply_msg = {"content" : entry, "group":groupid};
    socket.emit('reply',reply_msg); // <--
    $("#entry").val("");
});

You have a potential error here: in this function, you attempt to send a signal to the server that you are connected to. However, if the client had not yet connected to the server, socket.emit will fail.

To fix this, create a variable called isConnected and set it to false. Then, when the first socket.on fires you can set this variable to true. That way, you can setup an if statement in the code above so that you don't try to reply to the server without first connecting to the server.

Here is what I mean:

var isConnected = false;
socket.on('connect',function(){
    window.alert("You are connected.");
    isConnected = true;
});

$('#button').on('click',function(){
    if(isConnected) {
        var entry = $("#entry").val();
        var reply_msg = {"content" : entry, "group":groupid};
        socket.emit('reply',reply_msg);
        $("#entry").val("");
    } else {
        alert("You are not connected yet.");
    }
});


ResourceManager class consisting of multiple singletons

The fact that you have "Manager" as part of the name of the class is a code smell.  This class violates the Single Responsibility Principle.

In particular, Preferences sounds like it contains user-specific data; I wouldn't call it a "resource".  It should be split into its own class.

On the other hand, Texts, getImage(), and UserInterface.titleFont appear to contain data that would be application-wide constants.  A class like this could make sense:

public class UIResources {
    public static UIResources getInstance(Locale locale) {
       …
    }

    public Image getImage(String name) {
        …
    }

    public String getText(String name) {
        …
    }

    public Font getFont(String role) {
        …
    }
}


Redirecting the web client after deleting an item

There really is not much tangible difference between the two. I think I would not want to introduce a second route that does precisely the same thing as another route. I think it is sufficient to differentiate the redirect behavior based on the request properties.

In first, code example I think $badreferrers is a bad variable name. There is nothing bad about the referrer right? Those refererr values lead to a different redirect.


Confusion over using generics in MVC project

First of all, I appreciate the fact that you want to keep your code DRY as many developers are not concerned with this.  Also, I like the idea of having the generic Data type.  This makes your code flexible so that in the future new, more derived types of Data can be created without affected significant portions of unrelated code.  That being said, there are some things I would consider.

Style Notes:

Use consistent syntax conventions

On some lines, you have an opening curly on a new line, on others, it is on the same line as the function block / signature.  Either way is fine, just make sure you're consistent.

For generic types, give them more descriptive names than T to improve readability

Presumably, your T is a Data type (more on this later), so name your generic type parameter: TData, instead of T.  This gives a more clear understanding of what is expected.

Programming Notes:

As far as your use of Generics goes, I would use something more like this (and I'll explain why):

public class Request<TData> where TData : Data {

    public Request() {
        this.RequestDetail = new Details<TData>();
    } // end default constructor

    public string ApiKey { get; set; }
    public Details<TData> RequestDetail { get; set; }

} // end class Request{TData}

public class Details<TData> where TData : Data {

    public Details() {
        this.DetailData = new MoreDetails<TData>();
    } // end default constructor

    public string Action { get; set; }
    public string SecondAction { get; set; }
    public MoreDetails<TData> DetailData { get; set; }

} // end class Details{TData}

public class MoreDetails<TData> where TData : Data {

    public TData RequestData { get; set; }

} // end class MoreDetails{TData}

public class Data {

    public string Query { get; set; }

} // end base class Data

public class SpecialData : Data {

    public string AdditionalQuery1 { get; set; }
    public string AdditionalQuery2 { get; set; }

} // end derived class SpecialData

Then, in your implementation:

Request<Data> newRequest = new Request<Data>();
newRequest.ApiKey = "12345";
newRequest.RequestDetail.Action = "Search";
newRequest.RequestDetail.DetailData.RequestData = new Data(); //You could also use SpecialData

What I did:

1. Use Generic Type Constraints

Using Generic type constraints is a great way to both enhance the readability and maintainability of your code because you'll have some basic compile-time checking.  It also tells future developers what your expectations are.

See here for more on this subject: http://msdn.microsoft.com/en-us/library/d5x73970.aspx

2. Give more specific names to properties and fields

Your naming of properties being the same as the class names is confusing.  I renamed some of the properties to make the code easier to understand.  In addition to this, I would think of more descriptive names for your classes than Detail and MoreDetail as these don't really help understand the code or how it should be used.  Without knowing more about what your final aim is, I can't really provide more useful names, but you should consider being more explicit.

3. Instantiate defaults for complex types in constructors

You are passing generic type arguments for your initial request, which doesn't seem like what you want.  All of your generics ultimately are interested in what TData will be, not the property chain all the way down.  The generic type argument only specifies the type of, not the actual value of the property (which is why I have an additional assignment in my implementation code) that actually creates a new instance of the Data class.

By instantiating each property within the constructor, the object creation is simpler in your implementation.  Additionally, your implementation should not have to be concerned with the finer details of how the class and it's property chains are initialized.  The fact that your implementation code has to go so many levels deep in your properties may be a code smell.  Also, I am unclear on the usefulness of the MoreDetail class.

4. Simplify object creation

The object initializer syntax you're using is helpful sometimes, but when you are creating a complex object, it's best to KISS to improve the readability of the code (remember, this isn't JavaScript ;) ).

Let me know if I need to add any clarification on these points.


Grouping into more groups in one iteration

public static IDictionary<string, Dictionary<object, HashSet<T>>> MultiGroupBy<T>(this IEnumerable<T> source, params (string Label, Func<T, object> Getter)[] groupers)

I don't understand the mixture of interfaces (IDictionary) and implementations (Dictionary, HashSet), nor the mixture of generics (<T>) and non-generics (object). Why is it not

public static IDictionary<string, IDictionary<K, ISet<T>>> MultiGroupBy<T, K>(this IEnumerable<T> source, params (string Label, Func<T, K> Getter)[] groupers)

?

  IDictionary<string, Dictionary<object, HashSet<T>>> results = new Dictionary<string, Dictionary<object, HashSet<T>>>();

  using (var enumer = source.GetEnumerator())
  {
    while (enumer.MoveNext())
    {
      foreach ((var label, var func) in groupers)
      {
        if (!results.TryGetValue(label, out var dict))
        {
          dict = new Dictionary<object, HashSet<T>>();
          results[label] = dict;
        }

        ...

I'm not quite sure why you want to return an empty dictionary if the source is empty. As a caller of your library, I'd probably rather get a dictionary mapping the grouper names to empty dictionaries.

That also simplifies the initialisation:

  var results = groupers.ToDictionary(grouper => grouper.Item1, _ => new Dictionary<object, HashSet<T>>());

  using (var enumer = source.GetEnumerator())
  {
    while (enumer.MoveNext())
    {
       ...
    }

  }

KISS. foreach is much kinder on the maintenance programmer, who doesn't have to check for correct usage patterns of the unsugared API. Using MoveNext() / Current for speed is the epitome of premature optimisation unless benchmarking shows that it's a bottleneck, in which case there should be a comment explaining the bottleneck to justify the more complex code.

Moreover, if this is a bottleneck then it seems likely that the dictionary lookups in results for every single element in the source will be slower than the overhead of foreach, so you could start by replacing results with a List<(string Label, Func<T, K> Getter, IDictionary<K, ISet<T>> Groups)> and just convert it to a dictionary after the loop.

      foreach ((var label, var func) in groupers)

var (label, func) saves the repetition.

After my proposed refactors and some minor tidying of whitespace, I get

public static IDictionary<string, IDictionary<K, ISet<T>>> MultiGroupBy<T, K>(this IEnumerable<T> source, params (string Label, Func<T, K> Getter)[] groupers)
{
  if (source == null) throw new ArgumentNullException(nameof(source));
  if (groupers == null) throw new ArgumentNullException(nameof(groupers));

  var results = groupers.ToDictionary(grouper => grouper.Item1, _ => (IDictionary<K, ISet<T>>)new Dictionary<K, ISet<T>>());

  foreach (var elt in source)
  {
    foreach (var (label, func) in groupers)
    {
      var dict = results[label];
      var key = func(elt);
      if (!dict.TryGetValue(key, out var set))
      {
        set = new HashSet<T>();
        dict[key] = set;
      }

      set.Add(elt);
    }
  }

  return results;
}


Refactoring method to make it unit testing friendly

Following on what Magnus said in comments can you not inject the necessary dependencies.

For example:

public class UserManagementService : IUserManagementService
{
    private readonly IUserDao userDao ;
    private readonly ILog log;

    public UserManagementService(IUserDao userDao, ILog logger)
    {
       this.userDao = userDao;
       this.log = logger;
    }

    public LoginResponse Login(LoginRequest request)
    {
       // etc
    }
}

Now the class has no dependencies on concrete implementations and you can mock the interfaces however you feel.  For example, the ILog interface you might want to mock so it logs to the console only.  The IUserDao interface might be mocked to a internal list implementation or you might use a mocking framework such as Moq.


I'm afraid this is not fully immutable becasue I am able to change the Name with a simple cast:

altTypes.Dump();
((SoilType)altTypes.SensitiveFines).Name = "foo";
altTypes.Dump();

The underlying data type is still SoilType so the interface does not protect the data from being overriden.

Consider a user that writes a function like this one because he doesn't like interfaces :-)

public static void foo(SoilType bar)
{
    bar.Name = "new name";
}

and calls it

foo((SoilType)altTypes.SensitiveFines);
altTypes.Dump();

Name changed. Unfortunatelly I have no idea how to prevent it yet.


For a first script, this is great, and I am impressed.

your structure is neat
you are using loops properly
you are using variable substitution which is 'advanced'

The script appears that it will work for all the standard cases, and, I have seen much worse in 'production' code.

So, as a beginner, well done.

What's next?

the edge cases are going to kill this script - spaces in file names.
the logging and error handling could be better
I recommend basename and dirname instead of the variable regexes you use:

dirname: http://linux.die.net/man/1/dirname
basename: http://linux.die.net/man/1/basename (note that basename path/to/file.pdf .pdf returns file)

consistency on for->do loop - you have do on the next line once, and then for ... ; do the next time. Either is fine, but be consistent.

All of the error-handling, logging, and the spaces-in-files can be solved easily by using a function for running commands. Also, the "$@" construct in bash is 'special'

Consider the bash function:

function runcmd {
    echo "$@"
    # Fail if the command fails...
    "$@" || exit 1
}

So, this function will print the command, and then will run it, and exit the script if the command fails.

Now, instead of structures like:

            echo cp $working_directory/$folder_name/$f $new_filename
            cp $working_directory/$folder_name/$f $new_filename

you can do:

            runcmd cp "$working_directory/$folder_name/$f" $new_filename

and you will still get the echo, you will get the new error handling, and you will handle spaces in names just fine.


If you write this by hand you should pay attention to consistent
indentation and such as well because it makes things much easier to
read.

The IDs "tekst" and "prah" are a bit opaque, I assume that the first
one should really be "text" instead.

The major complaint I have is the repetition of the style for each and
every line of text.  That should be moved to the surrounding div so
that it applies to all subelements instead.  Also, you should probably
make sure that you supply some fallback fonts in case this one can't be
loaded.

The <br>s at the end of some lines shouldn't be necessary.  If you
want a force empty line maybe move each block of paragraphs into their
own div and control it via that.  The fact that you're manually doing
line breaks is obviously a problem.  It would be much better in terms of
organisation if you just have five or six paragraphs with all the text
and then control text flow by setting the boundaries of the
surrounding box.  You don't have any hyphenation, so that too is no
excuse.  N.b. take a look at how the formatting looks in different
screen sizes as well as on mobile screens (i.e. using the inspector
and emulating a smaller screen).

Having additional divs for the images is maybe not needed?  But then
again, it's really up to the CSS how that works out in the end.


Generic callback object, but I need the type parameter inside methods

One thing that bothers me is, that I have both the type parameter for the class and I am passing in the class to the constructor. It seems like I should not need to pass in the same info in two different ways.

The reason for why you have to do that is because of Type Erasure. Simply put, the generic class is only known during compile-time.

This call is unnecessary in your constructor: super();
All your fields should be marked with final.
Class mType; should be Class<T> mType;
I believe the mType.cast is unnecessary here:

mBus.post(mType.cast(response));

simply mBus.post(response); is enough. The eventbus will automatically detect the class by calling obj.getClass() and invoke the appropriate listeners.

In fact, your response variable is already declared as T response; so I don't see what good casting it will do.


It's always good to use guard conditions.  Instead of wrapping all of your logic in a code block, check for conditions when you don't have to execute and return early.  Like so:

public int recursivesearch(int[] array,int startindex,int endindex,int key) {
    if (endindex<=0){
       return -1;
    }

    // everything else here
}

It's much easier to read if you structure your code like this: also much less error-prone.

Next, you are missing some guards.  What happens if you array is empty?  What happens if the value you are looking for is larger or smaller than any values in the array?  You have to check for these conditions and handle them individually.  You are also trusting that the user has passed a proper index in.

Also, I would make it easier to use by having the public method not require start and end index, calculating them from the length, and then passing it into the actual search method which is protected.

Finally, you were not properly detecting a missing value.  You were returning -1 if endIndex<=0, but the proper condition is endIndex<startIndex.  Yours ends in an infinite loop for items such as:

recusivesearch([1,2,3,4,6], 0, 4, 5)

Keep in mind that java is not my language of choice, so this might be best viewed as pseudo-code:

public int search(int[] array, int key) {
    if (array.length == 0){
        return -1;
    }

    if (key < array[0] || key > array[array.length-1]){
        return -1;
    }

    return this.recursiveSearch(array, key, 0, array.length-1);
}

protected int recursiveSearch(int[] array, int key, int startIndex, int endIndex){
    if (endIndex<startIndex){
        return -1;
    }

    int middleIndex = startIndex + (endIndex-startIndex)/2;
    if (array[middleIndex] == key){
        return middleIndex;
    }
    if (key < array[middleIndex]){
        return recursiveSearch(array, key, startIndex, middleIndex-1);
    }
    return recursiveSearch(array, key, middleIndex+1, endIndex);
}

Nitpicks

Your definition of middle was prone to integer overflow.  I adjusted the definition to fix that issue.

Watch out for your use of whitespace.  In the long run, consistent whitespace makes code maintenance much easier.  Java problem has some general standards, which I'm guessing at.

Same with capitalization.  I believe Java prefers camelCase.  Some people prefer snake_case.  Pick one and stick to it: you don't do either, and it makes it harder to read your variable names.

Naming variables is also important.  You have startindex and endindex, and then middle.  You should at least go for consistency:

startIndex, endIndex, middleIndex

Or

start, end, middle

Since these variables contain indexes, I would probably go for the former, but for shorter names I would also consider the latter acceptable.  Either way, Keep your names consistent.


Looks good as a proof of concept. I recommend to modularize python code, that is

Make socket interface into a function
Make GPIO interface into a function
Have a

if __name__ == '__main__'

clause to call them (directly or via a main) function.

I would also handle failures to connect (retry maybe?); a total fun is to implement service discovery via pybonjour or zeroconf.


From a once over:

Magic constants should go on top ( 5000 and 12000
You use this construct .html($('#slide-content-'+id).html()); 4 times, a helper functions might be in order.
You don't need e in the event handling function, so you can just drop that
Image and video carousel use pretty much the same code, that could be a helper function as well.

So something like this potentially:

var imageCarouselSpeed = 5000,
    videoCarouselSpeed = 12000;

startCarousel( '#image-gallery-carousel', '#carousel-caption-text', imageCarouselSpeed );
startCarousel( '#video-gallery-carousel', '#carousel-caption-video-text', videoCarouselSpeed );

function startCarousel( carouselSelector, textSelector, speed ){
  //Start bootstrap carousel
  $( carouselSelector ).carousel({
    interval: speed
  });
  //Set the first caption
  $(textSelector).html($('#slide-content-0').html());
  // When the carousel slides, auto update the caption
  $(carouselSelector).on('slid.bs.carousel', function () {
    var id = $(this).find('.item.active').data('slide-number');
    $(textSelector).html($('#slide-content-'+id).html());
  });
}

I would agree with Larz a jsfiddle or jsbin would have gotten you a code review much sooner.


Enable Jquery Containment without using position: relative

In Firefox Dev edition your original code worked fine unless I a) resized the dialog or b) the body was too small for the dialog. The fix for each is to set the containment on the resizable widget too and don't let the dialog start out larger than the body to begin with, respectively.

var maxWidth = $('body').width() - 20;
var maxHeight = $('body').height() - 20;
$("#dialog").dialog({
  autoOpen: false,
  height: maxHeight > 300 ? 300 : maxHeight,
  width: maxWidth > 830 ? 830 : maxWidth,
  dialogClass: 'myTitleClass',
  modal: true,
  draggable: true,
  title: "Carpe Diem. Nunca Acredito Posteiro",
  closeOnEscape: false,
  open: function(event, ui) {
    $('.ui-dialog-titlebar-close', ui.dialog | ui);
  },
  buttons: {
    "Save": function() {
      $(this).trigger(updateKeyword());
    }
  }
}).draggable({
  containment: 'body'
}).resizable({
  containment: 'body'
});

Here's the updated fiddle.


Before making this more efficient I'd suggest making it more readable:

in your switch statement you have break in both the true and else parts of your if statement.

if(checkmove(pos.x, pos.y-2)) {
    pos.y -= 2;
    break;
} else {
    break;
}

It would be much easier to read if you just move the break out of the if statement.

if(checkmove(pos.x, pos.y-2)) {
    pos.y -= 2;
}
break;

In another question I had suggested a bit shaving optimisation that might help here. Math.floor(number) is equivalent to number >> 0 this bit shifts the number by 0 bits and converts it to an integer.

Math.floor(x/20)

becomes

(x / 20) >> 0

similarly adding almost 1 (+ 1 - Number.EPSILON) and then flooring will give you the ceiling. (number + 1 - Number.EPSILON) >> 0

The checkmove() function calculates this multiple times on the one line. I'd rewrite it to calculate once.

function checkmove(x, y) {
  var floorX = (x/20) >> 0;
  var floorY = (y/20) >> 0;
  var ceilX = ((x/20) + 1 - Number.EPSILON) >> 0;
  var ceilY = ((y/20) + 1 - Number.EPSILON) >> 0;

  return level[floorX][floorY] == 1 ||
      level[ceilX][floorY] == 1 ||
      level[floorX][ceilY] == 1 ||
      level[ceilX][ceilY] == 1;
}


One thing is that the way you're calling the events is not thread-safe:

if (OnStop != null) {
    OnStop(this, new EventArgs());
}

If the only subscriber to the event unsubscribes between the null check and the invoke, you will get a NullReferenceException. The correct way is like this:

var onStop = OnStop;
if (onStop != null) {
    onStop(this, new EventArgs());
}

Or, alternatively, you can make sure that the events are never null by adding a subscriber that does nothing:

public event EventHandler OnStart = delegate { };

That way, you don't have to check for null at all. This could hurt performance a bit, but it shouldn't be noticeable (especially since the events most likely won't be invoked more frequently than once every few milliseconds).

Another thing is that your finalizer is completely useless, since you don't have any unmanaged resources. It could make sense if some of the children of this class did have some unmanaged resources, but I think those could have their own fianlizer.

Also, in the usual Dispose() pattern, the parameterless Dispose() method is not virtual. I don't see any reason for it here, having virtual Dispose(bool) should be enough.


Interfaces vs implementations

Always use interfaces in declarations, not implementations. Instead of:

 private static HashMap<Integer,String> products = new HashMap<Integer, String>();

Do like this:

private static Map<Integer,String> products = new HashMap<Integer, String>();

doSessionStuff

The httpServletResponse parameter is unused, so drop it.

No need to initialize cartMap to null, as you will assign to it anyway. Actually you don't need that local variable at all, you could simplify the method without it:

@SuppressWarnings("unchecked")
private Map<String, Integer> doSessionStuff(HttpServletRequest httpServletRequest) {
    HttpSession session = httpServletRequest.getSession();
    if (session.getAttribute("cart") == null) {
        session.setAttribute("cart", new HashMap<String, Integer>());
    }
    return (Map<String, Integer>) session.getAttribute("cart");
}

doGet

You only use the cart variable if addProductbyName != null, so it would be better to move it inside the if block.

It's a bit awkward to do cart.put(addProductbyName, 0); and then again cart.put(addProductbyName, cart.get(addProductbyName) + 1);. And you are doing cart.get(addProductbyName) multiple times.

The @SuppressWarnings("unchecked") is also unnecessary for this method, as there are no unchecked casts.

The method would be cleaner like this:

@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {
    String addProductbyName = httpServletRequest.getParameter("addProductbyName");
    if (addProductbyName != null) {
        Map<String, Integer> cart = doSessionStuff(httpServletRequest);
        Integer count = cart.get(addProductbyName);
        if (count == null) {
            cart.put(addProductbyName, 1);
        } else {
            cart.put(addProductbyName, count + 1);
        }
    }

    httpServletResponse.sendRedirect(getServletContext().getContextPath()+"/shopping.jsp");
}


Check syntax (string and character comparison)

I suggest making the code more expressive by encapsulating the conditions as lambdas before the loop.

You should avoid magic numbers and for the mode create constants or an enum.

In the following example the {} stand for a block and [] for an attribute.

private static bool CheckIfSyntaxIsValid(string input)
{
    var mode = 1;
    var last = ' ';

    var isEndOfEmptyBlock = new Func<char, bool>(c => last == '{' && c == '}');
    var isBeginOfNestedBlock = new Func<char, bool>(c => last == '{' && c == '{');
    var isEndOfEmptyAttribute = new Func<char, bool>(c => last == '[' && c == ']');
    var isNotDigitInsideAttribute = new Func<char, bool>(c => last == '[' && !Char.IsDigit(c));
    var isAttributeBegin = new Func<char, bool>(c => c == '[');
    var isAttributeEnd = new Func<char, bool>(c => c == ']');
    var isBlockBegin = new Func<char, bool>(c => c == '{');
    var isBlockEnd = new Func<char, bool>(c => c == '}');

    foreach (char c in input)
    {
        if (isEndOfEmptyBlock(c))
        {
            last = ' ';
            mode = 1;
            continue;
        }

        if (isBeginOfNestedBlock(c))
        {
            return false;
        }

        if (isEndOfEmptyAttribute(c))
        {
            last = ' ';
            mode = 2;
            continue;
        }

        if (isNotDigitInsideAttribute(c))
        {
            return false;
        }

        if (isAttributeBegin(c))
        {
            if (mode == 2)
            {
                return false;
            }
            last = c;
            mode = 1;
        }

        if (isBlockBegin(c))
        {
            if (mode == 1)
            {
                return false;
            }

            last = c;
            mode = 2;
        }

        if (isAttributeEnd(c) || isBlockEnd(c))
        {
            return false;
        }
    }

    if (last != ' ')
    {
        return false;
    }

    return true;
}


I like my implementation as it's much more succinct

Which isn't necessarily a good thing: we care about readable code, not about oneliners. It means we don't use 5 lines to write what can be written in 1 line but it also means we don't cram 5 lines in 1 line just for the sake of it.

That being said: your implementation does the same as the example. I would also prefer your example since it keeps the equality logic in one method Equals(T) rather than duplicating it.

Some comments however:

There's no point in doing this cast: (object)p != null
You might as well implement IEquatable<T> MSDN
There should be no performance difference unless you have an unusual amount of null arguments to Equals(object) that will now go through the as statement before being caught by the null check
Equals(T) will probably be inlined anyway


How to name a method that sets some values in a javabean?

I agree you should not use setXXX() as this sounds like a classic setter. I would say go with what you think sounds nice and conveys the meaning well. prepareXXX() sound nice to me. If it is default values you are setting, you could use something along populateWithDefaultValues().

Just make sure you use the same naming strategy throughout your application.


Plotting many images at once in matplotlib

Try using matplotlib's LineCollection class. Here's an example.

In your case, you might do:

from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection

ax = plt.gca()
pts = myPath.reshape((-1,2))  # make a matrix of (x,y) pairs
edges = LineCollection(pts)
ax.add_collection(edges)
plt.show()


Parsing NuGet packages.config with Parallel.ForEach

If you want to do it this way then you need a lock but since the rest of your code is using Linq I would suggest you convert it over to PLINQ instead of using Parallel.ForEach,

Also you are iterating over the enumerable versionGroups twice. In your specific case it shouldn't cause an issue but that's not best practices with an IEnumerable.

First I'm going to change the GetPackagesForFile to return an array of Packages instead of using the static _packages field.

private static Package[] GetPackagesForFile(string filepath)
{
    return XDocument.Load(filepath).Root?.Elements("package").Select(GetPackageFromElement).ToArray() ??
           new Package[0];
}

I also changed it so to not throw a NullException if root not defined.  That's up to you if you want the exception there to tell you something was wrong or not.  So you might want to remove the ? and the ?? part if you want the exception to be thrown.

Now if you want to use PLINQ we just need to use the AsParallel() extension method. I'm going to use an anonymous class but you could create one if that's what you prefer.  Since I'm using an anonymous class I can't specify the type so going to use the var keyword, which doesn't match your coding style.

static void Main(string[] args)
{

    string[] files = Directory.GetFiles(Directory.GetCurrentDirectory(), "packages.config",
        SearchOption.AllDirectories);

    var idGroups = files.AsParallel()
        .SelectMany(GetPackagesForFile)
        .GroupBy(p => p.Id)
        .Select(g => new
        {
            Id = g.Key,
            Version = new HashSet<string>(g.Select(p => p.Version))
        }).OrderBy(p => p.Id);

    foreach (var idGroup in idGroups)
    {
        Console.WriteLine($"{idGroup.Id} ({idGroup.Version.Count})");

        foreach (string version in idGroup.Version)
            Console.WriteLine($"\t{version}");
    }
}

Since in your code all you care about is the distinct list of versions for each ID and the count I put them in a hashset instead of doing the grouping.  I could have used the g.Select(p => p.Version).Distinct().ToList() but just adding them to a hashset seems simpler code.

And in closing like you already stating making this parallel might be overkill.  If you want to test it compared to not being paralleled then you just need to remove the AsParallel() and the rest of the code can stay the same.


Don't ignore errors
You are just skipping any file that cannot be read correctly. But probably, if the user tried to process the images in a given target directory, it wants all of them to be watermarked, and if something cannot be watermarked, the user probably wants to hear about it. So you should not just continue after loading an image failed, you should stop and report an error. There are several ways to do this, for example:
Consider throwing exceptions
I would recommend throwing exceptions here. I assume that not being able to open a file or parsing it correctly is an exceptional event for your program. The advantage of throwing an exception is that the caller of a function that throws doesn't have to handle the exception, it can just let it propagate up the stack until something does handle it, or if nothing handles the exception, the program will abort with an error. The latter can even be desirable. Here is an example of how to throw exceptions:
#include <stdexcept>

cv::Mat Watermarker::loadImage(const std::string& path)
{
    cv::Mat image = cv::imread(path, cv::IMREAD_UNCHANGED);

    if (!image.data)
        throw std::runtime_error("Failed to read image");

    return image;
}

I have removed the check for path being valid as well, since if it isn't valid, trying to call cv::imread() on it will fail as well.
Inside Watermarker::mark(), you can now assume that when loadImage() returns, image.data is always non-NULL, so you don't need a check there. If you really want to continue parsing images, then you can catch the exception, and perhaps print a warning so the user does get to know what was wrong:
try {
    cv::Mat image = loadImage(path.string());
    cv.resize(...);
    ...
} catch (std::runtime_error &e) {
    std::cerr << "Could not load " << path << ": " << e.what() << "\n";
}

Write error messages to std::cerr
Don't write warnings, errors and debug messages to std::cout, but use std::cerr. This is especially important if the program is printing normal output to std::cout, so that if standard output is redirect to a file for example, it will not contain error messages, and the error messages will still be printed to the console.
Avoid converting std::filesystem::paths to std::strings too early
Use std::filesystem::path as the type to pass paths in consistently. Only convert them to/from std::strings when really necessary. You can also make use of implicit conversions between std::string and std::filesystem::path. So for example:
cv::Mat Watermarker::loadImage(const std::filesystem::path& path)
{
    cv::Mat image = cv::imread(path, cv::IMREAD_UNCHANGED);
    ...
}

And:
void Watermarker::mark(const std::fileystem::path& targetDirectory, const std::filesystem::path& watermarkPath)
{
    auto watermarkImage = loadImage(watermarkPath);

    for (auth& path : std::filesystem::directory_iterator(targetDirectory))
    {
        auto image = loadImage(path);
        cv::resize(watermarkImage, watermarkImage, image.size());
        ...
        saveImage(targetDirectory / "watermarked_images" / path.filename(), image);
    }
}


Representing a property with a non-nullable getter & a nullable setter

I'm thinking you should probably change your Post class as follows:
public class Post
{
    public string Title { get; }
    public string Slug { get; set; }
    public Post(string title)
    {
        Title = title;
        Slug = title.Slugify();
    }
}

Now you have a slugified title by default. However, if a user of the Post class wants to provide an alternative slug, they can still do that:
var post = new Post("foo bar") { Slug = altSlug };

The explanation for the user should be that they can either provide a slug explicitly, or have one auto-created by omitting it from the initializer. The only thing you cannot do with this code is set Slug to null explicitly. But I think it would not be good design to allow that.
On a side note, you might even want to make the Slug property getter-only, creating an immutable class, and providing a second constructor that takes the alternative slug. This makes reasoning easier:
public class Post
{
    public string Title { get; }
    public string Slug { get; }
    public Post(string title) : Post(title, title.Slugify()) {}
    public Post(string title, string slug)
    {
        Title = title;
        Slug = slug;
    }
}


Find the 2 distinct highest values in an array

Here's a simple implementation which will return the max (first index in return array) and second distinct max (second index in return array) value as an array.  If the list is size zero or there is no distinct max value, then Integer.MIN_VALUE is returned.

/**
 * @param integer array
 * @return an array comprising the highest distinct value (index 0) and second highest distinct
 *         value (index 1), or Integer.MIN_VALUE if there is no value.
 */
public int[] findTwoHighestDistinctValues(int[] array)
{
    int max = Integer.MIN_VALUE;
    int secondMax = Integer.MIN_VALUE;

    for (int value:array)
    {
        if (value > max)
        {
            secondMax = max;
            max = value;
        }
        else if (value > secondMax && value < max)
        {
            secondMax = value;
        }
    }
    return new int[] { max, secondMax };
}


Alternate solution

First off, I want to provide an alternate solution.

Let's analyze the sample inputs and outputs provided:

  Input:

(()(()(

  Output:

3

Now, let's count how many of each character there is:

(: 5 occurrences
): 2 occurrences

Well, if ( is the "up" character and ) is the down character, subtracting their occurrences gives you the floor number.

Don't believe me? Here's another example:

  Input:

))(((((

  Output:

3

(: 5 occurrences
): 2 occurrences

5 - 2 = 3; again, the floor number is revealed.

Basically, it doesn't matter the order of characters; you are always going to end up on the same floor. Now your implementation can be simplified: count up the occurrences of each character and subtract them for your result.

var upOccurrences = floors.match(new RegExp(upFloorSymbol, "g")).length;
var downOccurrences = floors.match(new RegExp(downFloorSymbol, "g")).length;

return upOccurrences - downOccurrences;

Note that JavaScript may yell at you for using the above code depending on the character passed in. For example, if you use parentheses, you will get an error even if they are escaped in the argument list. Here is how to fix that:

  If you want to fix that regex error then just provide the parentheses
  as "\\(" and "\\)". That will change the regex to be /\(/g and /\)/g
  :)

  -tkellehe

An alternative solution for finding the amount of characters in a string would be this:

var occurrences = string.split(character).length - 1;

However, I am unsure if this is good practice in JavaScript (I know it's not in Java).

Review

Now, for a review on your code.

Splitting an array into the same array

var chars = floors.split('');

In JavaScript, strings are just like arrays with the exception that strings are immutable. Since you are not modifying this chars array as you loop through it, it is unnecessary to split it as you can just treat the string like an array.

Stop throwing strings at me! I can't trace them!

throw 'parameter 1 is expected to be a string';

This is bad practice. When an error is thrown like this, there is no way to search the stack trace for where the problem occurred. Also, you get a pretty weird console message:

  Uncaught parameter 1 is expected to be a string

That doesn't even make sense (grammatically).

You should be throwing an instance of an Error, like this:

throw new Error(...);

Now, when this error is thrown, a better message and a stack trace are provided. This makes tracking down where the error occurred a lot more easy:

  Uncaught Error: message (stack trace)

Even better, you can be more specific and JavaScript's built-in errors like TypeError, especially since you are dealing with the types of the arguments.

Half the size for twice the conditionals

  if(chars[i] === upFloorSymbol || chars[i] === downFloorSymbol)
      count += (chars[i] === upFloorSymbol ? 1 : -1);

I see what you are trying to do here. You are trying to make your code shorter by first squishing two conditionals into one, and then using a ternary.

This is a bad idea. With how you did it, you are now forced to create two more conditions (creating a total of 4, or something like that) to check when you really only need two. These extra conditions unnecessarily slow down your code.

Instead of combining two conditionals here:

  if(chars[i] === upFloorSymbol || chars[i] === downFloorSymbol)

Split it up like this:

if(chars[i] === upFloorSymbol) {
    count += 1;
} else if(chars[i] === downFloorSymbol) {
    count -= 1;
}

Now you don't need that extra ternary.

Braces keep your code straight

Always use braces with conditionals, loops, etc.


Asynchronous JavaScript to fetch remote JSON data with promises and generators

Why do not use async / await functions? Its just syntactic sugar for promises / generators. Check this vanilla JS snippet, is live:

var url1 = 'https://jsonplaceholder.typicode.com/posts/2'
var url2 = 'https://jsonplaceholder.typicode.com/posts/3'

async function mimicSyncInside () {
  console.log('Before')
  console.log(await fetch(url1).then(resp => resp.json()))
  console.log(await fetch(url2).then(resp => resp.json()))
  console.log('After')
}

mimicSyncInside()


You can use the new utilities in the comparator class. Unfortunately you'll have to help the compiler a bit with the generic type induction.

Assuming, that the value class is "Whatever", this can be done like this:

    map.entrySet().stream()
        .sorted(Comparator.comparing((Map.Entry<String, Whatever> e) -> e.getValue().hasPriority())
                          .thenComparing(Map.Entry::getKey))
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());


Use parent class to declare a child object or how compiler allocates memory

Kind of a strange question for CodeReview as I see nothing wrong with your code itself. Answering your questions:

... is that a problem?

  No.

Does the compiler allocate memory when I declare a variable?

  Here's a good answer from Eric Lippert on storage location when declaring variables.

The only thing you could change about your code is make it a switch statement (although this change has nothing to do with the memory question):

private void ShowControlForBatchStatus(BatchStatus batchStatus)
{
    MyControl control = null;
    panelContainer.Controls.Clear();

    switch(batchStatus)
    {
        case BatchStatus.NoBatch: control = new InicializeLevel(); break;
        case BatchStatus.BatchRunning:
        case BatchStatus.BatchPaused: control = new Stadistics(); break;
        case BatchStatus.BatchFinish: control = new FinishBatch(); break;
    }

    panelContainer.Controls.Add(control);
}


Find list of valid continuing positions in a game

Disclaimer: this is not a code review, but a suggestion for an alternative implementation.

First, there is not that many terminating positions (just num_players), so it seems easier to enumerate all positions, and filter the terminating ones out.

Second, given a position it is easy to generate lexicographically next one. In pseudocode,

    find the leftmost player holding non-zero amount of chips
    if it is the last player,
        we are done
    otherwise
        pass one chip to the next player, and
        give her remaining chips (if any) to player 0


My Calendar generation code is slow. How do I improve it?

I just read somewhere that AppendFormat() can be slower than simple Append() calls. Being shocked by reading this, I decided to investigate.

For 1,000,000 empty events the times required are:

With AppendFormat: 9297 ticks
Without AppendFormat: 8268 ticks

That is a considerable difference of 11%!

I'm guessing this is due to the lookup of the arguments and such. It would be nice if AppendFormat() would be recompiled to Append() calls only by default.

This is the code:

    /// <summary>
    /// Creates a calendar json string.
    /// </summary>
    /// <returns></returns>
    public string ToFullCalendarJsonStringFaster()
    {
        StringBuilder sb = new StringBuilder();

        sb.Append( "[" );

        int count = Events.Count;
        int i = 0;

        foreach ( Event eventItem in Events )
        {
            sb.Append( "{" );

            sb.Append("\"title\":\"");
            sb.Append(eventItem.Title);
            sb.Append("\",");
            sb.Append("\"allDay\":\"");
            sb.Append(eventItem.AllDay);
            sb.Append("\",");

            if ( eventItem.AllDay )
            {
                // My test never comes here, so I left it out.
            }
            else
            {
                sb.Append("\"start\":\"");
                sb.Append(eventItem.Start.ToString("yyyy-MM-dd"));
                sb.Append("T");
                sb.Append(eventItem.Start.ToString("HH:mm:ss"));
                sb.Append("\",");

                sb.Append("\"end\":\"");
                sb.Append(eventItem.End.ToString("yyyy-MM-dd"));
                sb.Append("T");
                sb.Append(eventItem.End.ToString("HH:mm:ss"));
                sb.Append("\",");
            }
            sb.Append("\"url\":\"");
            sb.Append(eventItem.URL);
            sb.Append("\"");
            sb.Append( "}" );

            i++;

            if ( i < count )
            {
                sb.Append( "," );
            }
        }

        sb.Append( "]" );

        return sb.ToString();
    }

By also applying Snowbear's earlier replies:

Using yyyy-MM-ddTHH:mm:ss as format strings, gives an extra speed difference of 5%
Preallocating StringBuilder size, gives an extra speed difference of 6%

In total, after applying all changes, the code is 22% faster. :)

Bottomline is, there probably isn't a 'magic' solution which can make it go instant with so many events, but you can improve the speed considerably. I suggest you run the processing on a BackgroundWorker.

... this is getting even more ridiculous. Changing the date formatting to the following:

//sb.Append(eventItem.Start.ToString( "yyyy-MM-ddTHH:mm:ss" ) );
sb.Append(eventItem.Start.Year);
sb.Append("-");
sb.Append(eventItem.Start.Month);
sb.Append("-");
sb.Append(eventItem.Start.Day);
sb.Append("T");
sb.Append(eventItem.Start.Hour);
sb.Append(":");
sb.Append(eventItem.Start.Minute);
sb.Append(":");
sb.Append(eventItem.Start.Second);
sb.Append("\",");

... gives another speed increase and makes it 34% faster in total. Might slow down
again if you need more specific formatting.

Beware: this last update is probably erronous. I asked a question about proper usage of PLINQ.

I haven't used Parallel LINQ (PLINQ) yet. But this seemed a nice use for it. After replacing the for by:

Events.AsParallel().AsOrdered().ForAll( eventItem =>
{
    ...
} );

I get a total speed increase of 43%, again 9% faster. :) This is on a dual core processor. PC's with more cores should perform better. I don't know how PLINQ works exactly, but I would think it could work even faster if one iteration doesn't need to wait on another. The StringBuilder and i are exposed as closures. Anyone got any better approaches than ForAll()?


I'm no big fan of using partial classes because I find it less readable. Like the other commenter I think you should look at the repository pattern for a cleaner solution.
It seems a bit odd that you give Student the responsibility to save itself to the context.

Something in the same neighbourhood is the UnitOfWorkPattern. That said the DbContext is an implementation of UnitOfWork and Repository Pattern. You could use the DbContext directly or with a wrapper of your own, but if your wrapper doesn't add value to the DbContext you could skip it.

You are initializing your DbContext multiple times which seems redundant. Most likely you get the same instance since it implements the UnitOfWork pattern, but the "new" and private variables combined with static methods will make it very hard to write unit-tests. For testability you should avoid having MyDbContext in a private variable. You can use constructor injection to make it available to the class, or keep it in a property that you can substitute in tests later.


I think you will be able to implement this in a cleaner way by representing the key codes as data instead of control flow. Not only will the resulting code be shorter, but it will be more abstract. If you need to add new sequences or support multiple sets of sequences, you will be able to use the same basic logic.
More specifically, a trie data structure is a good match for your problem. The mapping process is simple: start at the root, input a character, and follow the corresponding branch. If there is no branch, fail. This must be modified slightly to output the original character if it is the sequence does not start with 27.
There is no trie in the Java collections framework, so you will have to build your own. The signature should be something like
class AsciiTrie {
  AsciiTrie[] children;
  int data;
}

Given this data structure, your new algorithm is the following
private static int readInputKey(AsciiTrie t) {
  if (System.in.available() == 0) {
    return 0;
  }

  int c;
  int depth = 0;
  while (t != null) {
    try {
      c = System.in.read();
    } catch {
      // handle error properly
    }

    t = t.children[c];
    depth += 1;

    if (t.data != 0) {
      return t.data;
    }
  }

  if (depth == 1) {
    return c;
  } else {
    return 0;
  }
}

I have not included code to build or populate the trie. But it is quite similar to traversal.


I am trying to calculate sum of two angles theta1 and theta2. These angles are being calculated by subtracting the inverse of cosine of an expression from a constant angle (theta0 or 180). The expression mentioned in the last line involves a division. The dividend is something like:
(square of sum of two numbers) +/- (square of a number - square of another number)
The divisor is something like:
(2 * a number * (sum of two numbers))

Don't tell us, tell the maintainer of your codebase!
float length_angle(float length = 0)
{
    auto square = [](auto x) { return x*x; };

    auto dividend1 = square(constlength_link1 + length) + square(length_base_end) - square(length_link2);
    auto divisor1 = 2 * length_base_end * (constlength_link1 + length);

    float theta1 = theta0 - acos(dividend1 / divisor1) * 180 / M_PI;

    auto dividend2 = square(constlength_link1 + length) - square(length_base_end) + square(length_link2);
    auto divisor2 = 2 * length_link2 * (constlength_link1 + length);

    float theta2 = 180 - acos(dividend2 / divisor2) * 180 / M_PI;

    return theta1 + theta2;
}

Three optimizations I'd make to this code for better API design: First, don't use default function arguments. If I meant to write length_angle(1) but fat-fingered length_angle() instead, give me an error! If I meant to write length_angle(0), trust me to write it. You're hurting more than you're helping when you try to save your caller that one extra character of typing.
Second, use radians. Radians are the right answer for trig in the same way that UTF-8 is the right answer for character encoding. Trust the past couple millennia of mathematicians when they tell you that angles should be measured in radians. This will save you some repetition here, and some unnecessary rounding errors as well.
Third, optionally, use double; it'll give you more accuracy and be no slower — maybe even faster — than float if you're targeting a normal desktop computer. Obviously if you're targeting a 32-bit microprocessor with hardware float and software-emulated double, don't use double. :)
In your real code, the above will be super readable because you'll be using real names for the variables instead of long placeholders like constlength_link1. You can also say sqr or sq instead of square. So:
double length_angle(double length)
{
    auto sq = [](auto x) { return x*x; };

    auto a1 = sq(L1 + length) + sq(L3) - sq(L2);
    auto b1 = 2 * L3 * (L1 + length);

    auto theta1 = theta0 - acos(a1 / b1);

    auto a2 = sq(L1 + length) + sq(L2) - sq(L3);
    auto b2 = 2 * L2 * (L1 + length);

    auto theta2 = M_PI - acos(a2 / b2);

    return theta1 + theta2;
}

Lastly, perhaps notice that theta1 + theta2 is theta0 + M_PI - (acos(a1/b1) + acos(a2/b2)); and perhaps deal with the possibility of division-by-zero when b1 or b2 is zero. Or even factor out the repeated code, now that it's been made blatantly obvious by our renamings:
double length_angle(double length)
{
    auto sq = [](auto x) { return x*x; };

    auto f = [&](auto start, auto a, auto b) {
        auto y = sq(L1 + length) + sq(b) - sq(a);
        auto x = 2 * b * (L1 + length);
        return start - acos(y / x);
    };

    return f(theta0, L2, L3) + f(M_PI, L3, L2);
}


Your original problem

  that pattern matching wont work anymore if I decide to add any fields to the Human or Bot constructors later, so I would have to adjust this every time I change the constructors.

can be easily solved by matching data constructors without their fields:

nextMessage :: User -> Message -> IO Message
nextMessage Human{} msg = putStr ("New Message: " ++ msg ++ " \n> ") >> getLine
nextMessage Bot{} msg = return $ msg + "is an interesting question!"

In this case changing fields in Human or Bot won't break nextMessage.

You can enable NamedFieldPuns extension to get only specified fields :

{-# LANGUAGE NamedFieldPuns #-}

nextMessage :: User -> Message -> IO Message
nextMessage Human{humanName} msg = putStr ("New Message: " ++ msg ++ " \n> ") >> getLine
nextMessage Bot{botName} msg = return $ msg + " is an interesting question!"

Haskell also allows different datatypes to have common field names, so the code could look like this:

{-# LANGUAGE NamedFieldPuns #-}

data User = Human { name :: String, age :: Int }
          | Bot   { name :: String, age :: Int }
            deriving (Show, Eq)

nextMessage Human{name} msg = putStr ("New Message: " ++ msg ++ " \n> ") >> getLine
nextMessage Bot{name} msg = return $ msg ++ " is an interesting question!"


Send and receive data code using OpenSSL

Looks good. No buffering problems anymore. Endianness is handled correctly. Reading and writing size is duly factored out.

The only suggestion is not rely on the native unsigned type to represent the size. Notice that htonl takes uint32_t as a parameter. It is a strong hint to pass size as uint32_t as well. This guarantees that the size is 4 byte long no matter which platform it is running on. Don't forget to #include <cstdint>.


Singleton manager/service classes with mockable dependencies in swift

Your singleton pattern leaves a lot to be desired.

It is not thread safe.
It makes use of the crash operator (!)
The class can be initialized any number of times--this isn't a true singleton
The fact that defaultInstance is a function which can be passed a parameter can lead to misleading results.

Thread-safety
The simplest way to make singletons thread safe in Swift is pretty straight-foward.
class MySingleton {
    private init(){}
    static let sharedInstance = MySingleton()
}

But given we want our singleton to potentially have different types, we need a slightly more complicated pattern.
Without account for any of the other points I want to address, the simplest solution looks like this:
static func defaultInstance(apiFacade apiFacade: MyApiFacade = RestApiImplementation.defaultInstance) -> MyManager {

    struct Static {
        static var onceToken: dispatch_once_t = 0
        static var instance: MyManagerImplementation?
    }

    dispatch_once(&Static.onceToken) {
        Static.instance = MyManagerImplementation(networkFacade: apiFacade)
    }

    return Static.instance!
}

The Crash Operator
Force unwrapping optional variables always leaves us with the potential to crash.  Even in a case like this where crashing probably is the correct behavior (because for the variable to be nil is presumably impossible), we still deserve better diagnostic information in the case of the crash.
By simply changing the last line from return Static.instance! to this:
guard let instance = Static.instance else {
    fatalError("Unable to obtain reference to MyManager singleton instance.")
}

return instance

We're doing the exact same thing, but in the case of a crash, we get better diagnostic information.
Importantly, if for some reason in the future, the MyManagerImplementation(networkFacade:) constructor were ever turned into a failable initializer, your app is all of the sudden going to start crashing without Xcode providing any warnings here.
And if left unchanged, you'll have no diagnostic information beyond:

fatal error: Unexpectedly found nil while unwrapping an optional

So... a few extra lines can be very helpful.

Not a true singleton
Because your initializer is perfectly accessible outside of the file, this is not a true singleton.  You do have a shared instance available, but other instances can be instantiated.
And perhaps importantly, if you compare your original implementation to the one posted above with the nested struct, even though your instance property is private, it has to be declared as a var (let wouldn't work), and that means it is possible to change the reference.
This is important to note because you can't stop users from capturing a reference to the original instance and continuing to make calls on it even after you've changed the value the singleton returns.

Misleading Results
Your defaultInstance function accepts and argument, and that argument has a default value of RestApiImplementation.defaultInstance.  This works for allowing your first time instantiation to choose how the singleton is set up.
But... we're going to get misleading results if the first time we called it we passed one sort of implementation, and then later we tried calling it with the other type of implementation.  Your code doesn't change the implementation, and despite me calling it requesting it be set up with Foo, you return me a Bar.
Perhaps better would be a method to initialize the singleton with a particular value?  And then you have to decide what happens if initialize is called more than once.  On the second and later calls, you must either reinitialize with the new value or you should do something to indicate that the action the user requested wasn't able to be performed.  So perhaps, you should throw an error here.


Your hardcoded letters is easier to take from string (just in case the alphabet ever changes or to save you some typing in some future code you might write):

from string import ascii_uppercase as letters

I don't see the advantage of

class BookingClass:
    ECONOMY = 'Economy'
    BUSINESS = 'Business'
...
    self.seating_areas = {
            BookingClass.ECONOMY: economy_seats,
            BookingClass.BUSINESS: business_seats}

over

self.seating_areas = {
        "economy": economy_seats,
        "business: business_seats}

The __str__ of Seat could be slightly simplified:

def __str__(self):
    return '{0.row_number}{0.letter}'.format(self)

In the constructor of SeatingArea you don't need the intermediate variable:

    for row_number in range(start_row, row_count + start_row):
        for seat_number in range(seats_per_row):
            self.seats_remaining.append(Seat(row_number, letters[seat_number]))

Assigning the booking ID like this:

self.booking_id = random.Random().randrange(1000, 10000)

will mean a roughly a 1:9000 chance of a collision. I don't know how many customers this is supposed to deal with, but that does not seem too unrealistic for e.g. a year of running. Maybe give the Flight a name and date/time like this and use that together with the seat and hash it with md5 to get a more unique id:

from datetime import datetime
from hashlib import md5
...

class Flight:
    def __init__(self,
                 path: str,
                 date: datetime,
                 economy_seats: SeatingArea,
                 business_seats: SeatingArea):
        ...
        self.path = path
        self.date = date

...

class Passenger:
    ...
    def book(self, flight: Flight, booking_class: str):
        ...
        id_str = "{0.path}{0.date}{1.seat}".format(flight, self)
        self.booking_id = md5(id_str.encode()).hexdigest()

...

    flight_time = datetime.strptime("2016-08-12 8:00:00 -0800" "%Y-%m-%d %H:%M:%S %z")
    flight = Flight("LAX->JFK", flight_time, economy, business)

This way every seat on every flight between two airports for every different starting time has a different id (at least the chance of collisions for md5 are a lot less than 1:9000).

In reality you would probably also have a Plane class, which has the SeatingArea's as parameters and just pass that on to Flight as the plane servicing that particular flight.


No need for an empty constructor in C++11:

Array()
{
}

You can just use a default constructor:

Array() = default;

It's a little confusing to have multiple public/private sections.  Here, you can just put all the public code under the same keyword.
You could make your structure more useful by providing iterators.  This will, for instance, allow you to use range based for-loops instead of plain ones for iterating through this structure.
You don't need std::endl if you just need newlines.  Just output "\n" instead for this.  More info about this can be found here.
It's unnecessary to have your own return 0 at the end of main() in C++.  The compiler will provide this return for you.


Usability

Your addCombinations(String input, int index, List<String> output) is harder to use than necessary.  The user must:

create the storage for the result
pass in a mysterious 0 value

It would be better to add a "helper" function, to do these tasks for the user:

  public static void main(String[] args) {
    List<String> output = combinations("0?1?");
    System.out.println(output);
  }

  public static List<String> combinations(String input) {
      List<String> output = new ArrayList<>();
      addCombinations(input, 0, output);
      return output;
  }

Flexibility

Will '?' always be the replacement target?  Will the replacements only be the characters '0' and '1'?  It wasn't asked by the interviewer, but you could make the function more flexible.  Or at least mention the possibility to the interviewer.

Code Style

This screams "hacky":

    for (int i = index; i < input.length(); ++i) {
      if (input.charAt(i) == '?') {
        // Do work
        return;
      }
    }
    output.add(input);

You are looping ... but only execute the "real" body of the loop exactly once -- and return if you do -- and if you get to the end without doing work, you do some different work.  As an interviewer, unless you've impressed me elsewhere, I'd be moving on to the next candidate.

What you are doing - what you intend to do - is find the first '?', replace that with '0' and '1', and recursing to find other occurrences for replacement.  Make that clearer.

    int position = input.indexOf('?', index);
    if (position >= 0) {
        addCombinations( ... );
        addCombinations( ... );
    } else {
        output.add(input);
    }

You've got two cases: found and not found.  Recursive and leaf.  No embedded return.  Pretty clear.

Premature Optimization?

You've got an optimization which may be unnecessary.  You pass in index to indicate where to start searching for the next '?'.  But you've replaced the '?', so if you omitted this, and simply started searching from the start of the string, it would still work.  Yes, you will be doing some unnecessary searching of the beginning of the string over and over again, but you've also removed passing the extra argument on the stack, which complicates the addCombinations(...) call.

To be fair, I've used String.indexOf() to do the searching, which is very fast, where as your code did the search itself, with a loop, a String.charAt() and a comparison, which would be significantly slower, so the optimization definitely makes sense in the original code.

The Better Way

As metioned by @greybeard, StringBuffer.setCharAt() would be much simpler to the string manipulation currently being done.  But it is still the wrong choice.  StringBuilder.setCharAt() is what you want.  (StringBuilder is StringBuffer, but without the synchronization overhead).

Instead of creating and throwing away multiple StringBuilder objects, it would be possible to reuse one StringBuilder object for all recursive calls.  Create the StringBuilder in the helper method I introduced, and pass it (instead of input) into the addCombinations() method.  When a ? is found, replace it with a 0 and recurse, then a 1 and recurse, and then change it back to a ? before returning to ensure subsequent processing still works.

public static List<String> combinations(String input) {
    StringBuilder workspace = new StringBuilder(input);
    List<String> output = new ArrayList<>();
    addCombinations(workspace, output);
    return output;
}

private static void addCombination(StringBuilder workspace, List<String> output) {
    int position = workspace.indexOf('?');
    if (position >= 0) {
        workspace.setCharAt(position, '0');
        addCombination(workspace, output);
        workspace.setCharAt(position, '1');
        addCombination(workspace, output);
        workspace.setCharAt(position, '?');
    } else {
        output.add(workspace.toString());
    }
}

There is still a lot of repeated work going on.  With 4 question marks, the first question mark is found once, the second is found twice, the third is found 4 times, and the fourth is found 8 times.  You could count the number of question marks, create an int positions[] array, and locate all the question marks only once.  You could also create an int state[] array, and use that to turn the recursion into a loop.  Finally, once each execution of the loop generates one new combination, you could extract the body of the loop into its own Supplier<String>, and use Stream::generate(Supplier<? extends T>) to create a stream of combinations on demand, instead of filling in a list, but we've ran way beyond reasonable expectations for an interview question.


Recognizing number representation (and convert to decimal) from the base prefixes

I see a number of things which may help you improve your code.

Be aware of what the standard doesn't say

Your use of unget() is not portable and will not work reliably.  The standard does not guarantee that an infinite number of characters will be buffered, and that's if the stream is buffered at all.  See this question for more details.

Use standard library functions where available

There is already a function std::stoi() which does the conversion you seek.  That is, it converts a std::string into an integer, applying the base conversions as specified.

Create functions to clarify your code

One thing that the code must do is to identify which base is specified by the source string.  Since what you need is a string identifying the base, such as "hexadecimal", given an input number as a string, we can write something simple like this:

const std::string& baseid(const std::string& str)
{
    static const std::string bases[]{
        "decimal", "octal", "hexadecimal"
    };
    enum baseid { DEC, OCT, HEX };
    if ((str.length() < 2) || (str[0] != '0'))
        return bases[DEC];
    return str[1] == 'x' ? bases[HEX] : bases[OCT];
}

Don't abuse using namespace std

Putting using namespace std at the top of every program is a bad habit that you'd do well to avoid.  Know when to use it and when not to (as when writing include headers).

Eliminate return 0 at the end of main

When a C++ program reaches the end of main the compiler will automatically generate code to return 0, so there is no reason to put return 0; explicitly at the end of main.

Don't wrap entire programs in a try clause

Rather than take the lazy way out and have a single massive block of code within the try clause, it's generally better to isolate specific things that might fail and deal with them individually and intelligently.  If you're not going to do anything useful with the output, it's probably better not to even have a try ... catch construct.

Use the appropriate #includes

This code uses a number of things that are in specific #include files but the code (as posted) does not show them.  Generally, reviewers have an easier time if you post an entire compilable program instead of just a non-compilable extract.

An alternative approach

Using the baseid function shown above, here's a much simpler program to accomplish this this:

numbase.cpp

#include <iostream>
#include <string>
#include <vector>

const std::string& baseid(const std::string& str)
{
    static const std::string bases[]{
        "decimal", "octal", "hexadecimal"
    };
    enum baseid { DEC, OCT, HEX };
    if ((str.length() < 2) || (str[0] != '0'))
        return bases[DEC];
    return str[1] == 'x' ? bases[HEX] : bases[OCT];
}

int main(){
    const std::string info ("This program recognizes multiple base prefixed numbers  dec:none, hex:0, oct:0x\nand converts them into decimals.\n");
    std::cout << info;
    std::string num;
    std::vector<std::string> inputNumbers;

    while (std::cin >> num)
        inputNumbers.push_back(num);
    for (const auto &n : inputNumbers)
        std::cout << n << " " << baseid(n) <<" converts to "
                << stoi(n,0,0) <<" decimal\n";
}


Determining if a word is an anagram of another

You need to check if each letter occurs the name number of times in both strings.

One method would be to sort the letters and compare the lists of letters for equality.

Here is my approach:

def is_anagram(test, original):
  return sorted(list(test.lower())) == sorted(list(original.lower()))

This algorithm is far from optimal runtime O(n*logn), but I have chosen it because of its simplicity.
For an Efficient algorithm see the comment of @corsiKa for a quite simple O(n) algorithm.


Decoding and Encoding packet layers using decorator pattern

I don't know about the decorator pattern, but there are things you can improve anyway:

Identifiers that begin with an underscore followed by a capital letter are reserved identifiers in C++. Therefore, _DECODER_H_ is not a valid identifier; that name is reserved to the implementation. You should change it to DECODER_H_.
You never modify the string that you pass to Decode. Therefore, you should pass it a const reference instead of a simple non-const one:

virtual void Decode(const std::string &packet) = 0;

All of your class members are public. Therefore, you could simply change them to structs instead and remove all the public qualifications. The only difference between class and struct is that all is public by default (even inheritance) while all is private by default within a class.
You don't seem to need pointers in main, regular automatic variables would be enough. Actually, try to use pointers only when you have to in C++, only where it makes sense. Otherwise, try to always use value and/or reference semantics. That way, you may avoid many problems.
DecoderBase is probably meant to be a base class to be used for some polymorphic behaviour. Give it a virtual destructor. Otherwise, deleting a derived instance through a base pointer will be undefined behaviour.
Try to use constructor initialization lists whenever possible:

Level2::Level2(DecoderBase *innerLayer, const std::string &data):
    mInnerLayer(InnerLayer),
    mData(data)
{}

There are several functions that could be const-qualified (try to do so whenever a function does not modify the members of the class). The Encode methods look like they should be const-qualified everywhere:

std::string Header::Encode() const
{
    return mData;
}


Parsing argument list specifying a player to be added

First of all, don't ever write code like this... you know it can be done better, so don't waste your time.

Moreover, you can be sure, you'll make some errors there, e.g., this looks wrong:

Player p = player.getServer().getPlayer(args[2].split(":")[1]);
String r = args[2].split(":")[1];

as you're using args[2] twice.

It's actually very trivial:

String[] inputs = {args[1], args[2], args[3]);
Arrays.sort(inputs);
if (inputs[0].startsWith("l:") && inputs[1].startsWith("r:") && inputs[2].startsWith("u:")) {
    Player p = player.getServer().getPlayer(inputs[2].split(":")[1]);
    String r = inputs[1].split(":")[1];
    String l = inputs[0].split(":")[1];
    Config.addPlayer(p, r, l, player);
    return true;
} else {
    return false;
}

A possibly even simpler alternative would be to go through the args and always fill the appropriate data slot (p, r, and l). After processing all three args, all slots must be filled, otherwise the input is wrong.

There's much more to say... e.g., your repetitive

args[2].split(":")[1]

should be replaced by a method. You also most probably don't want to allow args like l:12:34:567 (or you don't want to lose the part after the second colon), so don't use split.

Actually, I guess, you need some command line parser... there are at least 10 such things in Java freely available.


Use functions

It's generally a good idea to sort your functionality into functions. Allows you for nice reuse and stuff like that.

string.split()

So how will we parse? Of course, you can parse every single input like you do, or even upgrade it to a tokenizer engine if you got a lot of spare time and effort. There's really 2 ways to go about there here. The simple one is string.split(). The complicated one is regexes, but you probably won't need these unless you're planning big.

Map to functions, not precomputed results

You'll notice I import functions from the operator builtin module. These do the exact same thing as the +, -, /, * and **(power) symbols, but we can use them as functions. This lets us put them in a dict we can create before we ask for user input. It also means we don't have to calculate all the operations, and can stick to only calculating the one we actually are interested in. Do note that this also obsoletes your power function, much as you could have done using ** yourself.

from operator import pow, sub, mul, add, truediv

def calculate():
    operators = {
        "+": add,
        "-": sub,
        "/": truediv,  # floordiv also exists, which is integer division
        "*": mul,
        "^": pow
    }
    val = input("Calculate: ")  # Do note that it's already a string, so you don't need to cast to one.
    for symbol, operator in operators.items():
        if symbol in val:  # Check if the symbol is in the string
            a, b = val.split(symbol)
            return operator(float(a), float(b))  # Cast them to floats - all builtin operators can handle them.

if __name__ == "__main__":
    print(calculate())

Last thing I added was what we call a guard. It makes you able to import this function from another script and use it, without having to run it.

If you want to go for bonus points, you can also switch to regexes for your input parsing.

Bonus info: Iterators

Python does a lot of smart things with iterators. For example, we're iterating over a dictionary here. A dictionary looks like this:

my_dict = {
    "key1": "value1",
    "key2": "value2",
    # etc...
}

It's a hashtable for the keys, and under the hood these are linked to pointers to the values. We can iterate over a dictionary in three ways: Over the keys, over the values, and over key: value pairs.

Keys

for key in my_dict:
    # "key1", "key2"....
# OR:
for key in my_dict.keys():
    # "key1", "key2"....

Values

for value in my_dict.values():
    # "value1", "value2"....

key/value pairs

for key, value in my_dict.items():
    # ("key1", "value1"), ("key2", "value2")....

In case of items(), the iterator gives a tuple of length 2 for every iteration. By assigning that tuple to key, value, we unpack it. This works the same as in the line:

a, b = 1, 2

On the RHS, we construct a 2-length tuple (1, 2), which is passed to the LHS, where it is unpacked to a, b. Since tuples enforce ordering, that's how python decides which value to put where.

See also: Python Docs Dictionary Looping Techniques


Trying to Find a Loop to use for a specific MySQL query

Saving lines of code in search of elegance is not always (in fact hardly ever in my experience) a worthwhile exercise if it comes at the expense of clarity and maintainability. Your current code is better than any solution that iterates over table columns because it is clear and easy to change. For example, combining the data of two columns into one or changing column order are both trivial.

You might consider moving this display logic to a template. Here is an example of a twig template:

{% if results %}

HERE ARE SOME RESULTS

    {% for row in results %}

        {{ row.subject }}
        {{ row.description }}
        {% if row.user == user %}
        You can delete this
        {% else %}
        Code didn't work
        {% endif %}

    {% endfor %}

{% else %}

No results

{% endif %}

The PHP becomes very simple:

$bindings = array(
    'results' => $mysqli->query('SELECT...'),
    'user' => $_SESSION['firstname'] . ' ' . $_SESSION['lastname']
);
$twig->render('template.html', $bindings);


Managing user defined and default values for instance attributes

Some minor comments on the code:

Class definition should be separated from the line with import by two spaces.
My personal preference is to have key-value pairs in dictionaries separated with a space after colon as shown in PEP 8:

defaults = {'A': None, 'B': 0, 'C': 0}

Comparing to None should be done by is instead of ==:

required = [key for key, value in defaults.items() if value is None]

Note that I also removed redundant brackets around key, value.  There are several other lines where brackets are not needed around them.
PEP 8 also discourages aligning several lines with assignments by =, so instead of, for example:

results        = None
keys, values   = zip(*setup.items())

it should be

results = None
keys, values = zip(*setup.items())

There is no need to specify object in class O(object), class O will work fine.
Here:

for key, value in kwargs.items():
    if key in setup:
        setup[key] = kwargs[key]  # user specified overrides default

you don't use value, but you could:

for key, value in kwargs.items():
    if key in setup:
        setup[key] = value

Here:

  keys, values   = zip(*setup.items())

you don't need values as you overwrite them later. So, I'd just remove this line altogether.
set((1,)) can be replaced with {1}, and set.difference can be replaced with just -. BTW, I like how you combined two conditions from my previous review in one!
Don't forget to use np.can_cast instead of checking the dtypes against np.int64. The current version failed for me until I changed it.
[array.astype(float) for array in arrays] can be written as list(map(np.float64, arrays)) but both versions are fine.
The overall design looks quite unusual to me. If it would be me, I'd separate validating data from the container that will keep it. In other words, I'd not keep it in one class. BTW, if a class has just two methods and one of them is __init__ then it shouldn't be a class. Another thing you could try is pydantic library. Never had a chance to try it myself though, but with this problem of data validation I'd give it a shot.


Recursive merge-sort inversion count algorithm very slow

There's a bug in merge_count_split_inversions.

    for i in range(n):
        if j == len(X):
            add len(Y)-k elements to X_Y
        elif k == len(Y):
            add len(X)-j elements to X_Y
        elif X[j] < Y[k]:
            add 1 element to X_Y
            j += 1
        else:
            add 1 element to X_Y
            k += 1

This should have the invariant that after the ith time round the loop it has added i elements to X_Y. Either the first two cases need to add a single element, or they need to break.


Calculating the distance squared between all vertex-pairs of a number of 2D polygons

It would be helpful to have a simple test harness for the code.

In reviewing your code I can see some possible bottlenecks, in Cython there can be quite a large overhead in passing arrays (views) to functions, also the array operations may be convenient but when performing them on very small arrays of only a few values performance will tend to suffer considerably compared with doing the arithmetic directly — Cython can make some optimizations when it comes to calling functions into python-space and a few numpy array operations bypass python-space — but arithmetic on basic types in Cython is guaranteed to be at the speed of c as it translates directly to c code, as does array indexing.

Hence you would probably gain some performance benefits by passing floats directly instead of arrays.

cdef double calculate_2D_dist_squared(self, np.float64_t x1, np.float64_t y1,
                                      np.float64_t x2, np.float64_t y2):
    return (x1 - x2) ** 2 + (y1 - y2) ** 2

As noted previously, indexing is very very fast in Cython, but intermediate views can result in performance losses, hence my instinct would be to call the function in this way:

dist_squared = self.calculate_2D_dist_squared(
    polygons_vertex_coords[pi_focus, vi_focus, 0],
    polygons_vertex_coords[pi_focus, vi_focus, 1],
    polygons_vertex_coords[pi, vi, 0],
    polygons_vertex_coords[pi, vi, 1])

Instead of the other possible way which would involve creating a variable to hold polygons_vertex_coords[pi_focus, vi_focus] (etc).


How can this  be set up to maximize inheritance if additional classes will be passed in from a JSON file?

Some quick notes:

You can use list-style: none; instead of list-style-type: none; – Just a bit shorter
You mention in a comment /* only for tablet */, but there are no media queries in sight.

@media screen and (max-width: 480px) {
    .international {
        max-width: 240px;
    }
}

It's common practise to use dash-delimited class names in CSS, not CamelCase. This completely personal and you can do whatever you want.
Omit the units on zero values: background-position: 0 0; instead of background-position: 0px 0px;
I recommend writing single-line CSS: Every property declaration on a new line. There is no reason to write rule declarations with only one property declaration on one line. Also I don't find it helpful writing top, right, bottom and left on one line.

If you want to save file size and improve performance, you should minimize your CSS. That's so much more efficient plus you keep the legibility and maintainability in your CSS file.

That's it for the moment. Feel free to add a comment to discuss something or visit our great chat.


To address your immediate concerns, it is a tail recursion indeed. OTOH, there is no need to be that terse. You may want to be a little more explicit:

    if (i == n) {
        return a;
    }
    return fib(n, i + 1, b, a + b);

Now the tail-recursiveness is obvious.

The error message "Argument 2 must be the Nth term." is misleading. The Nth term definitely refers to the Nth Fibonacci number, rather than the index of the number to be computed.

Besides that, traditionally such message is formatted as

    "Usage: " << argv[0] << " index\n";


Never use get method on option. In this case you could use case Some(a) instead.
You don't need curly braces in case branches

oa match {
  case None => G.unit(None)
  case Some(a) =>
    val x: G[B] = f(a)
    G.map(x)(Some(_))
}

I don't know if variable x makes any sense in this case. I'd just use this:

case Some(a) => G.map(f(a))(Some(_))

You could also use methods of Option like fold of map + getOrElse, but I guess pattern matching is the best solution in this case.


Actually, I do believe you are quite good as you are. The simple inversion listed in this similar question (from comments) does not work when you want to split up the set values of your first dict. You could try something like a dict comprehension with a double for loop, but that doesn't work either as the second time you get a fruit it will overwrite the first one.

The only thing I would like to change in your answer is to use the plural of fruit, fruits, so that you don't do the for fruit in fruit which looks kind of hairy, and has the potential for code breaking as you're overwriting a variable with the same variable. Not good. In other words:

people_by_fruit = defaultdict(set)
for person, fruits in favorite_fruits.items():
    for fruit in fruits:
        people_by_fruit[fruit].add(person)


Check if a record already exists and update if it exists

When working within a Rails environment you can use try

occurrence.try(:touch_with_version)
occurrence.present?

Ruby also provides tap so you could also write:

occurrence.tap({|o| o.try(:touch_with_version)}).present?

You could even dig into the libraries to see that touch_with_version returns the result of ActiveRecord's save! which in turn returns the result of create_or_update which returns a boolean and so you can write:

occurrence.try(:touch_with_version).present?

If you're happy returning true, false, or nil you could shorten it to:

occurrence.try(:touch_with_version)

Very nice but also more fragile if either of those libraries decide to change their return values in a future release.


Turn On/Off Functions to speed things up

You should save the initial state of the Application.* variables before you mess with them, then reset them when you're done. Not all of your users will have the same settings and it's rude to assume they do.

A simple way to do it would be to implement a class like this:

'@Folder("Classes")
Option Explicit

Private Type ApplicationSettings
  ScreenUpdating As Boolean
  DisplayStatusBar As Boolean
  CalculationMethod As Excel.XlCalculation
  EnableEvents As Boolean
End Type

Private this As ApplicationSettings

Public Property Get ScreenUpdating() As Boolean
  ScreenUpdating = this.ScreenUpdating
End Property

Public Property Get DisplayStatusBar() As Boolean
  DisplayStatusBar = this.DisplayStatusBar
End Property

Public Property Get CalculationMethod() As Excel.XlCalculation
  CalculationMethod = this.CalculationMethod
End Property

Public Function DisableExcelDisplayUpdates()

  SetScreenUpdating False
  SetDisplayStatusBar False
  SetCalculationMethod Excel.xlCalculationManual
  SetEnableEvents False

End Function

Public Function EnableExcelDisplayUpdates()

  Application.ScreenUpdating = this.ScreenUpdating
  Application.DisplayStatusBar = this.DisplayStatusBar
  Application.Calculation = this.CalculationMethod
  Application.EnableEvents = this.EnableEvents

End Function

Private Function SetScreenUpdating(ByVal value As Boolean)
  this.ScreenUpdating = Application.ScreenUpdating
  Application.ScreenUpdating = value
End Function

Private Function SetDisplayStatusBar(ByVal value As Boolean)
  this.DisplayStatusBar = Application.DisplayStatusBar
  Application.DisplayStatusBar = value
End Function

Private Function SetCalculationMethod(ByVal value As Excel.XlCalculation)
  this.CalculationMethod = Application.Calculation
  Application.Calculation = value
End Function

Private Function SetEnableEvents(ByVal value As Boolean)
  this.EnableEvents = Application.EnableEvents
  Application.EnableEvents = value
End Function

Then test it out like this:

Option Explicit
`@Folder("Tests")

Public Sub testIt()

  Dim ExcelValues As Class1
  Set ExcelValues = New Class1

  Debug.Print "Before "
  Debug.Print "ScreenUpdating: " & Application.ScreenUpdating
  Debug.Print "DisplayStatusBar: " & Application.DisplayStatusBar
  Debug.Print "Calculation: " & Application.Calculation
  Debug.Print "EnableEvents: " & Application.EnableEvents

  ExcelValues.DisableExcelDisplayUpdates

  Debug.Print "During "
  Debug.Print "ScreenUpdating: " & Application.ScreenUpdating
  Debug.Print "DisplayStatusBar: " & Application.DisplayStatusBar
  Debug.Print "Calculation: " & Application.Calculation
  Debug.Print "EnableEvents: " & Application.EnableEvents

  MsgBox "Do your long running process here"

  ExcelValues.EnableExcelDisplayUpdates

  Debug.Print "After "
  Debug.Print "ScreenUpdating: " & Application.ScreenUpdating
  Debug.Print "DisplayStatusBar: " & Application.DisplayStatusBar
  Debug.Print "Calculation: " & Application.Calculation
  Debug.Print "EnableEvents: " & Application.EnableEvents

End Sub

*Note that the '@Folder("<something>") annotation is a feature of Rubberduck which is a great tool for helping to improve your VBA code. I'm an avid user and occasional contributor to the OSS project.


This is not vastly different but you might think its a little easier to read and follow and probably therefore debug.

With this code everything can be done within a single loop rather than the more complex multiple loop while/do that you originally used.

This also makes use of the stdClass provided by PHP to generate an array of objects as per your requirement, where your code was creating an array of arrays.

// get all the posts and their photos
$st = $db->prepare ('SELECT * FROM `posts` ' .
                    'LEFT JOIN `photos` ON `photo_post` = `post_id`');
$st->execute ();

// init our results array
$posts = array ();

$lastPostId = NULL;

// get the first post (plus it's JOINed photo)
while ( $post = $st->fetch (PDO::FETCH_OBJ) ) {

    if ( $lastPostId != $post->id ) {
        if ( $lastPostId !== NULL ) {
            // add this obj to the post array
            $posts[] = $tPost;
        }
        // start a new temp object
        $tPost          = stdClass();
        $tPost->id      = $post->id;
        $tPost->content = $post->content;
        $tPost->photos  = array();
    }

    // Add photo_id to current tPost obj
    $tPost->photos[] = $post->photo_id;

    $lastPostId = $post->id;
}

// and send it back
echo json_encode($posts);