Adding a mix of strings and string arrays to an array

Naming Conventions

As the Naming Guidelines states:

  The goal of this chapter is to provide a consistent set of naming
  conventions that results in names that make immediate sense to
  developers.

In that sense, the creatively defined method name Add and the parameter names ogarr and toadd will not do.

The General Naming Conventions states:

  Avoid using identifiers that conflict with keywords of widely used
  programming languages.

  Do not use abbreviations or contractions as part of identifier names.

  Do favor readability over brevity.

Method name Add is a common method name used by collection types to add a new element to the collection. An Add method with source as the first parameter and the items to be added as the second parameter does not make sense.

ogarr and toadd are bad names for parameters and should be changed at least to sourceArray and itemsToAdd or similar.

And in Capitalization Conventions

  Do use camelCasing for parameter names.

I'm not suggesting to change ogarr to ogArr and toadd to toAdd of course. The parameters should have descriptive names in the first place. You can consider sourceArray and itemsToAdd or similar.

Possible Improvements

Being consistent with code formatting is important. Consider using curly brackets, always:

if (toadd[i].GetType() == typeof(string[]))
{
    results.AddRange((string[])toadd[i]);
}
else
{
    results.Add((string)toadd[i]);
}

You say

  restrictions are not allowed.

Then, why restricting the second method parameter to object[]? Let's get that as an IEnumerable. This way, your method can also operate on string[] or List<T> instances

public string[] Add(string[] sourceArray, IEnumerable itemsToAdd)

You can also change the method to be an extension method of string[]. This will clearly state the purpose of the method if declared with a good name:

public static string[] AddItemsOrRanges(this string[] sourceArray, IEnumerable itemsOrRangesToAdd)

You should always check if the parameters are passed in as null. Your code would fail with a null refererence exception at toadd.Length if toadd is passed as null.

if (toadd == null)
{
    // throw ArgumentException() ?
    return ogarr;
}

You should also check the items of the passed in collection for null references. If any of the items of the object[] toadd would be null, your code would fail with a null refererence exception at x.GetType()

if (toadd[i] == null)
{
    // throw ArgumentException() ?
    continue;
}

Finally, the implementation, with all the naming convention violations and functional confusions fixed, might look like the following:

public static string[] AddItemsOrRanges(this string[] sourceArray, IEnumerable itemsOrRangesToAdd)
{
    if (itemsOrRangesToAdd == null)
    {
        // throw ArgumentException() ?
        return sourceArray;
    }

    // It is possible with extension methods to have the self instance this as null
    // because extension methods are actually static methods and can be invoked
    // on a null reference (interesting?)
    // string[] myStringArray = null;
    // string[] finalStringArray = myStringArray.AddItemsOrRanges(new object[] { "Test" });
    // will work!
    if (sourceArray == null)
    {
        // throw ArgumentException() ?
        return sourceArray;
    }

    var results = new System.Collections.Generic.List<string>(sourceArray);

    foreach (var itemOrRangeToAdd in itemsOrRangesToAdd)
    {
        if (itemOrRangeToAdd != null)
        {
            if (itemOrRangeToAdd.GetType() == typeof(string[]))
            {
                results.AddRange(itemOrRangeToAdd as string[]);
            }
            else if (itemOrRangeToAdd.GetType() == typeof(string))
            {
                results.Add(itemOrRangeToAdd as string);
            }
            else
            {
                // What to do if the element is neither a string nor a string[]?
                // The (string) cast in the else block would fail in your source code
                // throw ArgumentException() ?
            }
        }
        else
        {
            // How would you determine if the element is to be added or not?
            // is it a null string instance, or is it a null string[] instance?
            // throw ArgumentException() ?
            continue;
        }
    }

    return results.ToArray();
}

And calling it would be like:

string[] temp = new string[] { "123", "456", "789" };

string[] thing1 = new string[] { "abc", "def" };
string thing2 = "ghi";

object[] toadd = new object[] { thing1, thing2 };

temp = temp.AddItemsOrRanges(toadd);


Loading files or directories based on type

I don't see glaring performance issues that should make this "sluggish".

But you could improve performance by extracting specialized logic to specialized functions:

add_file
add_dir
add_array
add_json

Because,
in the current implementation,
for example,
when you scan a directory and call $this->add for each file,
the recursive call will do unnecessary is_string, is_dir, is_file checks on it.
Those checks don't need to be in the specialized add_file.

The same goes for the other input types,
when you separate to multiple functions,
there should be fewer unnecessary conditions to go through.

Users of the class,
when they know that the input is JSON data,
it will make sense that they should call add_json directly.
In the end,
I don't know what legitimate cases will be left for calling the generic add function.
At that point, you can delete the function.

The return statement is pointless here:

throw new \RuntimeException('Provided data could not be parsed ("' . substr($input, 0, 20) . '...").');
return;

Instead of this:

    case 'php':
      $content = require($input);
    break;

The common practice is to align the break statement with the content of the case, like this:

    case 'php':
      $content = require($input);
      break;

It's recommended to use braces { ... } with single-statement blocks too,
even they aren't strictly necessary.


Fade-in / fade-out effects for several buttons

I have no problem setting this up in html - it makes sense in this case.

home

work

cms

contact

Set a target on each one

$(function() {
    $('li a', '.menu').click(function(e) {
      e.preventDefault();
      var target = $($(this).attr('href'));
      $($(this).data('fadeOut')).fadeOut(function(){
        target.fadeIn();
      });
    })
    $('.panel').hide();
    $('.home_button').click(function(){
        $('.panel:visible').fadeOut();
    });
})

You get the nifty coincidental benefit here of this working ok even without javascript since  also happens to be the the syntax for 'scroll-to element'

Also, you should not name functions with an uppercase capital. Because javascript has no native way of determining which functions are meant to be run in a functional style and which are meant to be used as constructors with the new keyword, it is a very well known convention to use upper case names only for functions which are meant to be invoked with the new keyword. Learn more about javascript capitalization conventions here.

Edit: Totally misread your code. I believe my rewrite now reflects what you're trying to do


You don't use weekdays.
You can have two return statements. (Shown below).

This keeps the same logic, it just removes the need for so meany return statements.

def alarm_clock(day, vacation):
    weekend = "06"
    if vacation:
        return "off" if str(day) in weekend else "10:00"
    else:
        return "10:00" if str(day) in weekend else "7:00"

I would improve it further by adding a check, that you enter a number 0-6.

if not (0 <= day <= 6):
    return "-:--"


Return most recent DateTime C# Entity Framework

This frequently used pattern...

entities.First().Property

... is hardly ever an economical way to do querying. It fetches a complete entity from the database of which subsequently all but one property is discarded. Or, when Property is a lazy loaded collection, everything is discarded.

In general a better way is...

entities.Where(e => e.Id == id).Select(e => e.Property).First()

... because this only gets the single property from the database.

Or, if Property is a collection,...

entities.Where(e => e.Id == id)
        .SelectMany(e => e.Property)
        .Select(p => p.Property1)

Applying this would turn the first statement into...

IEnumerable<Guid> logLists = dbContext.Jobs
                                      .Where(j => j.Guid == jobGuid)
                                      .SelectMany(j => j.Quotes)
                                      .Where(q => q.EmailLogListGuid != null)
                                      .Select(q => q.EmailLogListGuid.Value);

The second part is OK. Getting the most recent item from a collection always requires some ordering that defines "most recent".

Note that using the improved form, EF will translate this into one query, because logList isn't materialized yet. It is an expression tree1 that can be merged with the second expression. If you want, you can create one statement in LINQ as well:

return dbContext.Jobs
                .Where(j => j.Guid == jobGuid)
                .SelectMany(j => j.Quotes)
                .SelectMany(q => dbContext.EmailLogs
                    .Where(e => q.EmailLogListGuid == e.EmailLogListGuid))
                .OrderByDescending(e => e.CreatedDate)
                .Select(e => e.CreatedDate)
                .FirstOrDefault();

Or, if Quote has a navigation property EmailLogs (recommended):

return dbContext.Jobs
                .Where(j => j.Guid == jobGuid)
                .SelectMany(j => j.Quotes)
                .SelectMany(q => EmailLogs)
                .OrderByDescending(e => e.CreatedDate)
                .Select(e => e.CreatedDate)
                .FirstOrDefault();

1 Even though you cast the expression tree to IEnumerable, it's still an IQueryable containing an expression.


Node.js Is this a great way to show pages in a minimal way as possible?

Good question,
made me learn some more about dirty.

Some observations:

1 var block is good, having the commas not at the end of each line looks odd
I wonder if it is faster to get the extension of the requested resource and compare to js and css instead of executing 2 regexes
Your 3 if blocks contain the same statement: response.writeHead(200, {'Content-Type': 'text/html'}); you should extract that statement into 1 place.
'80' should be in a var which you then use for your last console.log statement
Similarly, hard coding the ip address in your log statement does not make sense, you should get that info from node.
Always calculating 4*1024 and creating an options object seems like a lot work, that ought to get done only once
*

I would counter propose something like this:

var http = require('http'),
    db = require('dirty')('pages.db'),
    url = require('url'),
    fs = require('fs'),
    port = 80,
    streamOptions = { 'bufferSize': 4 * 1024 },
    htmlHeader = {'Content-Type': 'text/html'};

http.createServer(function (request, response)
{
  var pathname = url.parse(request.url).pathname;
  var html = db.get(pathname);

  //First check if the requsted file is css or js
  if (/\.(css)$/.test(pathname) || /\.(js)$/.test(pathname))
  {
    fs.createReadStream(__dirname + pathname,streamOptions).pipe(response);
  }
  else
  {
    response.writeHead(200, htmlHeader );
    if (!!html && pathname !== '/admin' )
    { //Pages from our Dirty DB
      response.end(html);
    }
    else if (pathname === '/admin')
    { //Display Admin page
      response.end('Admin!');
    }
    else
    { //Not found..
      response.end(db.get('404'));
    }
  }
 }).listen(port);

console.log('Server running on port' , port );

If you absolutely want to show the IP address, then you should check out this excellent question.

Finally, any hacker can access your admin pages with /./admin tricks unless either dirty or url is smarter than I give it credit for.


In regards to your question:

  I feel as though there could be a way to refactor this code so that
  Request.CreateErrorResponse only occurs in the code once, but I cannot
  see how at the moment.

I would consider reducing the nesting (Arrow code) of the If statements and perform follow the return early mantra.

public HttpResponseMessage Post(LongUrlModel model)
{
    if (!ModelState.IsValid)
    {
        return BadRequest();
    }

    var baseAddress = Request.RequestUri.ToString().TrimEnd('/');
    if (model.LongUrl.StartsWith(baseAddress))
    {
        ModelState.AddModelError("", "You cant shorten a URL that belongs to this domain");
        return BadRequest();
    }

    // Perform the valid code logic here
}

private HttpResponseMessage BadRequest()
{
    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}

In regards to your other question

  I am not at all fond of the conditional logic here

There's a few things I can think of you could try.

Create a custom validation attribute and decorate the LongUrl property.

  public class UrlLengthAttribute: ValidationAttribute
  {
      public UrlLengthAttribute()
      {
      }

      protected override ValidationResult IsValid(object value, ValidationContext validationContext)
      {
        var httpContext = new HttpContextWrapper(HttpContext.Current);
        var url = value as string;

        if(string.isNullOrWhiteSpace())
        {
          return base.IsValid(value, validationContext);
        }

        // I'm not 100% on this code but you get the general idea
        var baseAddress = httpContext.RequestUri.ToString().TrimEnd('/');

        if(url.StartsWith(baseAddress))
        {
          return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
        }

        return null;
      }
  }

You can then use this to decorate your model:

    public class LongUrlModel
    {
        [UrlLength(ErrorMessage = "You cant shorten a URL that belongs to this   domain")]
        public string LongUrl { get; set; }
    }

You could the extract the model validation out into a separate Validator class and use that in the controller instead.  At the very least it might be moving towards the lines of creating a unit testable module.

  public class LongUrlModelValidator
  {
     public LongUrlModelValidator(HttpContextBase httpContext)
     {
      // store and use
     }

     public bool Validate(LongUrlModel model)
     {
      // perform validation logic here
     }
  }


Removing duplication in AngularJS Factory

You can extract the whole ajax to a function.

myAppServices.factory('apiService', function ($http, $q) {
    var get = function(endpoint) {
        return $http.get(endpoint)
                .then(function (response) {
                    if (typeof response.data == 'object') {
                        return response.data;
                    } else {
                        // invalid response
                        return $q.reject(response.data);
                    }
                }, function (response) {
                    // something went wrong
                    return $q.reject(response.data);
            });
    }
    return {
        getDocuments: function () {
            return get('/api/autodeskdocuments/1');
        },

        getSharePoint: function () {
            return get('/api/sharepointheaderdata/1');
        }
    };
});


PropertyInfo GetValue and Expression Cache GetValue

Problems

Both the reflection and expression-based approach fail to take null values into account (NullReferenceException).
They also fail to take types with indexers into account (TargetParameterCountException).
Hash-codes are not unique identifiers. Different properties (and objects in general) can have the same hash code - that just means that they might be equal. Use prop.MetadataToken in combination with the module they're declared in (prop.Module.ModuleVersionId).
Compiling expressions asynchronously makes this a lot more complex than it needs to be, and that complexity is not properly taken care of:

There's no guarantee that compilation will be finished when the next object is processed. This can result in multiple compilations for the same property. That's a waste of work.
The results of these compilations are added to a Dictionary, which is not thread-safe. In the best case, adding a key that already exists will throw an exception. In the worst case, the dictionary's internal state will become corrupted.
Those exceptions are not being caught. Before .NET Framework 4.5, that would've caused a crash, and in 4.5 and higher it may still do so, depending on certain settings.

Other improvements

Why does Execute take a sequence of items, instead of a single item? Flattening results is easy (data.SelectMany(service.Execute)), 'unflattening' is not - the caller would have to figure out the number of properties, and you'd have to write a method to split up a single sequence into sub-sequences.
Instead of doing ExpressionCache.ContainsKey(key), followed by ExpressionCache[key], use TryGetValue. This lets you check the presence of a key and get its associated value with a single lookup.
There's no point in making AddExpressionCacheAsync async. It's not doing any asynchronous work (that await Task.Yield() is useless). You're already calling this method from within a Task.Run call, so it'll be executed asynchronously anyway.
In GetValueGetter, use nameof(object.ToString) instead of "ToString".

Readability issues

Some names are not very descriptive: Execute -> GetPropertyValues, enums -> items, func -> compiledExpression, GetValueGetter -> CompileGetValueExpression.
There are several abbreviations that do not improve readability: e -> item, props -> properties, p -> property.


You have three problems that I can see. Two performance, and one logic. In least-to-most significant order:

Performance: You should no use the NOT LIKE 'NOT FOUND' statement, it should be  <> 'NOT FOUND'
Potential logic problem: You should have an order-by clause on the inner select for the TOP 5 ... otherwise, what TOP 5 are you getting?
Performance: Using declare @table... syntax has different performacne to create table #table ... For example, this blog entry shows some real differences. I recommend trying the same query with a #temp table instead.

Also, read up on this SO Answer: SQL Server tables: what is the difference between @, # and ##?
Edit:
It was almost too obvious to ask... but, you have done the two most basic items... right?

an index on the [PartNumber].[PatternCode]
updated all table statistics

... right?


First off, there is an error: You have the part [b- duplicated at the beginning.

The first section matches five successive consonants, which is possbile. Examples for German words (although not names) with up to eight successive consonants: http://www.duden.de/sprachwissen/sprachratgeber/die-woerter-mit-den-meisten-aufeinanderfolgenden-konsonanten

The same goes for four successive vowels. Again examples in German with up to five: http://www.duden.de/sprachwissen/sprachratgeber/die-woerter-mit-den-meisten-aufeinanderfolgenden-vokalen

Then the next one basically matches when a specific letter is repeated three times anywhere in the name and that can't be terribly rare.

And finally one that only allows two spaces, thus names consisting of three words. And I've come across plenty of names in my live with more than three words.

Finally a technical note: If you really want to do this, you need to do it server side. JavaScript validation is trivially easy to circumvent.


A good option is to use the Objects utility class (available since Java 7)

Note also, that instead of doing if-conditions and returning true, or false, you can do a direct return of the condition... For example, the part == null is common to these two expressions:

if (part == null && newName == null) {
    return false;
}
if (part == null || newName == null) {
    return true;
}

And those can be simplified to just:

if (part == null) {
    return newName != null;
}

Note also, that your code runs the risk of a NullPointerException if part.getName() returns null. Is that possible?

Your code:

private boolean isThingChanged(String newName, Thing thing) {
    final Part part = thing.getPart();
    if (part == null && newName == null) {
        return false;
    }
    if (part == null || newName == null) {
        return true;
    }
    return !part.getName().equals(newName);
}

Could be:

private boolean isThingChanged(String newName, Thing thing) {
    if (thing.getPart() == null) {
        return newName != null;
    }
    return !Objects.equal(thing.getPart().getName(), newName);
}

Writing that as a ternary is an option:

private boolean isThingChanged(String newName, Thing thing) {
    return thing.getPart() == null ? newName != null : !Objects.equal(thing.getPart().getName(), newName);
}


Which way is better for converting number to string?

I would recommend

String.valueOf(myNumber)

This allows you to to change myNumber to another primitive type - or a Number - later.

"" + myNumber

should be avoided since :

it produces clutter bytecode (instanciating a new StringBuffer)
it does not convey what you wanted to do with myNumber


For one, you don't want to pass a string to setInterval(); better to use a function. You can bind that function to the object's context, so it'll call the right thing.

For another, aim for less ambiguous names. rotation should probably be updateRotation, since that's what it does. And rotate should likely be startRotating (and they you could have an equivalent stopRotating).

That be something like:

this.startRotating = function () {
  var self = this; // to maintain the object's context
  setInterval(function () {
    self.updateRotation();
  }, 100);
};

However, if you're planning to add more planets etc., it would probably be nicer to have one central timer that calls an update function on all your objects.

And I'd also define a "proper" prototype for all this, and extract some general logic/avoid repetition:

// extract this logic, since it's generally useful
function getElement(element) {
  if (typeof element == "string") {
    return document.getElementById(element);
  }
  return element;
}

function Mass(element, angularVelocity) { // added the rotation speed as an arg
  var computedStyle;

  this.element = getElement(element);

  // fetch this once
  computedStyle = window.getComputedStyle(this.element);

  this.width  = parseInt(computedStyle.width, 10);
  this.height = parseInt(computedStyle.height, 10);
  this.top    = parseInt(computedStyle.top, 10);
  this.left   = parseInt(computedStyle.left, 10);
  this.radius = this.width / 2;

  this.origin = {
    x: this.left + this.radius, // you just calculated the radius; might as well use it here
    y: this.top + this.radius
  };

  this.angularVelocity = angularVelocity;
  this.rotation = 0;
}

// make nice prototype
Mass.prototype = {
  update: function () {
    this.rotation = (this.rotation + this.angularVelocity) % 360;
    this.element.style.webkitTransform = "rotate(" + this.rotation + "deg)";
  }
};

// do the timer magic outside the object
var moon = new Mass("moon", 1.0),
    timer;

timer = setInterval(function () {
  moon.update();
}, 100);

fiddle


General Observations
Good job creating functions and the naming of the functions. The naming of the variables could probably be improved, for instance n could be renamed to item_count or array_element_count.
The indentation is inconsistent. This could lead issues during maintenance of the code.
Missing Function
As stated above you did a pretty good job of creating functions, but you missed one, the input of the array should be a function as well.
Logical Order of Printing
Put printf("SORTING...\n"); before the call to the sort() function.
Comments
Since you did a good job of naming the functions most of your comments are unnecessary. For instance //Swaps The Value Of Index i With The Value Of Index j In The Array really doesn't add anything.
Arguments for Swap Function
Rather than passing in 2 pointers to values and swapping the values I might pass in the array and the 2 indexes and use array notation in the swap function to relocate the values.
Missing Error Check
The code to input the array properly checks to see that the value of the size of the array is greater than 0, but it doesn't check that the size of the array is less than than the maximum size.


This part is pretty odd:

    // Calculate dynamic values
    scrollTop = $(this).scrollTop(),
    elHeight = wrap.outerHeight(),
    fixed = wrap.hasClass('fixed'),
    staticFlag = wrap.hasClass('static'),
    stopMovingPos = article.outerHeight() + article.offset().top;

The 5 assignments are separated by commas, instead of semi-colons.
It would be better to end each of the first 4 lines with a semi-colon.

This is even worse, using assignment in the right-hand sides of a ternary operator:

    (scrollTop < fixedPosTrigger) ? stopMovingPosTrigger = scrollTop : stopMovingPosTrigger = scrollTop + elHeight;

It would be shorter and better to move stopMovingPosTrigger to the left, and use the ternary at the right-hand side of the assignment:

    stopMovingPosTrigger = scrollTop < fixedPosTrigger ? scrollTop : scrollTop + elHeight;

Inside the scroll function, these conditions and their negated values appear multiple times:

scrollTop > fixedPosTrigger
stopMovingPosTrigger > stopMovingPos

To reduce the duplication which may lead to errors,
I suggest giving these conditions a name by storing them in variables, like this:

var fixedPositionArea = scrollTop > fixedPosTrigger;
var staticPositionArea = stopMovingPosTrigger > stopMovingPos;

This way, instead of re-typing scrollTop > fixedPosTrigger multiple times,
you could use fixedPositionArea and !fixedPositionArea in your conditions.
Of course, !fixedPositionArea is not exactly the same as scrollTop < fixedPosTrigger,
but it seems to me this small discrepancy won't break your script.

Using these variables the code becomes:

if (fixedPositionArea && !staticFlag) {
    wrap
        .addClass('fixed')
        .css({ 'padding-top': topPadding + 'px' });
}

// Fixed positioned area, setting paddings and margins, and transition scrolling from the static area
if (fixedPositionArea && !staticPositionArea) {
    wrap
        .removeClass('static')
        .addClass('fixed')
        .css({ 'margin-top': 0 });
}

// Static positioned area, setting dynamically the margin-top for the element
else if (staticPositionArea && fixed) {
    // Calculate top margin to be added to the static element
    staticMarginTop = stopMovingPos - startingPos - elHeight;

    wrap
        .removeClass('fixed')
        .addClass('static')
        .css({ 'margin-top': staticMarginTop });
}

// Original area before the fixed position area
else if (!fixedPositionArea) {
    wrap
        .removeClass('fixed static')
        .css({ 'padding-top': 0 });
}

Some blocks are not indented well, for example:

var Plugin = function ( element, options ) {
this.element = element;
this.options = $.extend( {}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}

It would be better to indent the body inside a { ... } block, like this:

var Plugin = function ( element, options ) {
    this.element = element;
    this.options = $.extend( {}, defaults, options);
    this._defaults = defaults;
    this._name = pluginName;
    this.init();
};

Also, since this is an assignment, the right-hand side should be terminted with a semi-colon.

Review the rest of the code and correct all the under-indented blocks.

It would be also good to use consistent amount of indents.
In most places you seem to use 4 spaces, while in others only 2.
I suggest to pick one width and use it consistently everywhere.


It might be slightly cleaner and more performant to keep self.mask as a list, and just join it before printing:

# Basically what you had before, without the space
# Just "list multiplication" instead of "string multiplication"
self.mask = ['_'] * len(word)

. . .

if w == letter:
    mask[i] = letter

. . .

if '_' not in self.mask:
    self.show_board()
    print('You won!')

. . .

print(' '.join(self.mask))

Now there's less converting back and forth between strings and lists. This also saves you from needing to do i * 2. The spaces can just be added in using join before being printed, so you don't need to worry about them.

print(self.mistakes) currently prints out a normal list representation to the end user without any context. I'd probably prefix a message to that, and format it a bit before printing:

print(f"Already tried: {', '.join(self.mistakes)}")
# Already tried: R, Q

I'd probably get rid of self.winner and change how you're checking for winning. Notice what you're using it for: you assign it in check_winner, then return that same value that you just assigned, but never use the return value. I'd have check_winner just return the value, move the call to check_winner to after the call to make_move, and use the return value:

def check_winner(self):
    if '_' not in self.mask:
        self.show_board()
        print('You won!')
        return True

    return False

. . .

def play(self):
    won = False  # Just track this locally instead

    while not won:
        self.show_board()

        letter_input = input('Choose a letter: ').upper()
        self.make_move(letter_input)

        won = self.check_winner()  # And assign it here
        self.check_loser()

I'd also probably change check_loser (As a heads up, it's spelled "loser". "Looser" means that one thing is "less tight" than something else). I'd maybe have it return a bool saying whether or not the player lost, and just return from that function instead. As I noted in a previous review (at the bottom), quit can cause problems when testing code. Just returning from the main loop to allow control to pass back to the REPL is much cleaner.


Some grist for the mill:

When variables will not be reassigned, it's helpful to declare them as final to reduce cognitive load on the reader.

When using the Collections API, it's preferable to declare interface types rather than implementations (List instead of ArrayList) unless you need functionality specific to the implementation type.

Declare variables as closely to where they're first used as is possible.

When you return in the if clause, you don't need an else clause.

Calling inputAlphabet().contains() once for every character in the input is very inefficient, especially given that inputAlphabet() is running a loop to create the list. Call inputAlphabet() once and keep a local variable to hold it. And have inputAlphabet() return a Set instead of a List, which gets you contains() at O(1) instead of O(n).

input.toCharArray() is easy to read, which makes it probably correct in this case, but be aware that it's marginally less efficient than using an indexed loop and calling input.charAt(i) because it creates a new char[].

You don't need to keep a Tape instance variable. Just create a new one in run(). It might be nice if the Tape constructor accepted a list of cells.

Probably not relevant, but your code is not thread-safe. It will break if multiple threads call run at the same time.

Don't reuse a variable (pT) for different things in the same method. It makes it hard for the reader to keep track of what it contains.

pT is a poor variable name. I think it means possibleTransitions? Variables should clearly indicate what they're referencing. Another example is t instead of transition.

The loop building the transitions could be extracted into a method.

It's traditional in looping constructs to check <=, instead of != to avoid a possible infinite loop if a bug puts you past the exact value you want to terminate on.

You can localize i and use a for loop, because you know is has to be tape.getCells().size() when you're done looping.

Your code might be easier to read with a guard clause if (.. != .. ) { continue; rather than nesting.

Rather than setting the value of j to break the loop, just use break. Then you can use an enhanced for loop rather than indexing on j.

Your temp dancing is not meaningful. Since Tape is returning an unsafe copy from getCells(), you could just do tape.getCells().set(i, ..). Even better would be changing the API of Tape to have the methods to access the cells (tape.getCellAt(int), tape.setCellAt(int, Character) instead of returning the array for you to mess around with. While you're at it, add a method like size() or length() to tape and get rid of getCells altogether. Let Tape hide the fact that it's using a List under the covers, and you can change the implementation later without breaking other code.

It's unclear why a Transition's direction and the current state are treated as Strings when they're only ever one character long.

It also be nice if Transition could be changed so you could do something like i = possibleTransition.applyDirection(i), and the Transition determines whether to add one, subtract one, or do nothing. Then that if .. else if .. block reduces to i = possibleTransition.applyDirection(i); tape.setHeadPosition(i);

Your second for loop with the k index has the same break; issue as the first. You can again use the enhanced for loop.

It's unclear what this loop is doing with Tape, since you're making changes that effectively vanish once the method exists. It looks like that code can just go. In fact, since getHeadPosition is never called in your codebase, I'm not sure why you're tracking it at all.

If you were to make all of these modifications, your code might look something like the code below. This is untested, so I might very well have broken something.

public boolean run(final String input) {
    final List<Character> chars = new ArrayList<>();
    final Set<Character> inputAlphabet = inputAlphabet();
    for (final char c : input.toCharArray()) {
        if (!inputAlphabet.contains(c)) {
            return false;
        }
        chars.add(c);
    }

    String currentState = startState;

    final Tape tape = new Tape(chars);
    for (int i = 0; i < tape.size(); i++) {

        for (final Transition transition : this.possibleTransitions(currentState)) {
            if (tape.getCellAt(i) != transition.getInputSymbol()) {
                continue;
            }

            if (transition.getWriteSymbol() != EMPTY_SYMBOL) {
                tape.setCellAt(i, transition.getWriteSymbol());
            }

            i = transition.applyDirection(i);
            currentState = transition.getToState();
            break;
        }

        if (this.rejectStates.contains(currentState)) {
            return false;
        }
    }

    for (final Transition transition : possibleTransitions(currentState)) {
        if (transition.getInputSymbol() == EMPTY_SYMBOL) {
            currentState = transition.getToState();
            break;
        }
    }
    return acceptStates.contains(currentState);
}

private List<Transition> possibleTransitions(final String state) {
    final List<Transition> possibleTransitions = new ArrayList<>();
    for (final Transition transition : transitions) {
        if (transition.getFromState().equals(state)) {
            possibleTransitions.add(transition);
        }
    }
    return possibleTransitions;
}


Positioning link boxes & managing backgrounds

I edited your fiddle jsFIddle. Basically what I have done is removed position:relative and added float:left and then added some margin to the elements. Then with the last-child selector I removed margin from the last item.


What you've got is pretty readable, but there are a few points to make:

Your sub-query is written with a different indentation style from the main query.
I prefer to see the keywords in upper-case.
Personally, I dislike spaces before commas intensely (and you aren't 100% consistent about adding them).  However, I loathe even more the style where the comma is put at the start of the next line:

     item1
   , item2
   , item3

I'd use explicit AS to introduce table aliases.  At least on the DBMS I use mainly, using AS gives a degree of future-proofing against aliases that become keywords in a later version of the product.  That is, writing FROM SomeTable st runs into a problem later if st becomes a keyword, but writing FROM SomeTable AS st avoids that problem.  Whether this helps in other DBMS is open to debate.

For your query, I'd probably write:

SELECT lp.period_id,
       lp.building_id,
       lp.suite_id,
       lp.lease_id,
       lp.tenant_trading_name,
       lp.suite_status,
       lp.suite_name,
       lp.suite_area,
       lp.lease_status,
       lp.lease_current_start_date,
       lp.lease_current_stop_date,
       lp.lease_current_term,
       lp.lease_occupancy_date,
       lp.lease_vacated_date
  FROM property.lease_period AS lp
 WHERE lp.lease_current_stop_date < @truncateddate
   AND (UPPER(lp.lease_status) = 'ACTIVE' OR UPPER(lp.lease_status) = 'OVERHOLDING')
   AND lp.building_id = @building_id
   AND NOT EXISTS
       (SELECT *
          FROM lease_deal.lease AS l
         WHERE lp.building_id = l.building_id
           AND lp.lease_id = l.lease_id
       )
   AND (@section_name = 'ALL'
        OR (@section_name <> 'ALL' AND UPPER(section_name) = UPPER(@section_name)))
   AND lp.lease_current_stop_date BETWEEN @truncateddate AND
                        DATEADD(MONTH, @lease_expiry_period, @truncateddate)
 ORDER BY period_id DESC;

Sometimes, I'd indent the sub-query more than I did here, occasionally even placing it after the EXISTS:

   AND NOT EXISTS (SELECT *
                     FROM lease_deal.lease AS l
                    WHERE lp.building_id = l.building_id
                      AND lp.lease_id = l.lease_id
                  )

That has a tendency to run off the right-hand edge of the screen, though.


Making code elegant, clean and optimized

The inelegance lies in the way you're storing your data.  You haven't normalized it, so you have to check multiple places for what should be the same information.
Why are golden albums in a different list?  The fact that you need to check that list too, should be an indication that those two lists should be the same.  Just like the artists, producers, and other information about the album, whether or not it's golden (and indeed, how many times, if I understand golden album status correctly) is an attribute of the data.
You don't spend much time justifying why GoldenAlbum and Album are different types. Without knowing much about the data you're modeling, it's hard to be sure exactly what your data attempts to describe.  So maybe I'm misunderstanding what 'golden' means for an 'album'.  But if you have only one Album object and it has a is_golden attribute, you can avoid continuing to implement checks for both types of album in any code that interacts with the data by album name.


I'm confused why you're using a named tuple for PosixPermission. To me an Enum would be a better choice:

class PosixPermission(Flag):
    READ = 4
    WRITE = 2
    EXECUTE = 1
    NONE = 0

    @property
    def perms(self):
        return ''.join(
            name if self & val else '-'
            for name, val in zip('rwx', PosixPermission)
        )

>>> PosixPermission(0)
<PosixPermission.NONE: 0>
>>> PosixPermission(7)
<PosixPermission.READ|WRITE|EXECUTE: 7>
>>> PosixPermission(5)
<PosixPermission.READ|EXECUTE: 5>
>>> PosixPermission(5).perms
'r-x'
>>> PosixPermission(5) & PosixPermission.READ
<PosixPermission.READ: 4>
>>> PosixPermission(5) & PosixPermission.WRITE
<PosixPermission.NONE: 0>
>>> PosixPermission(8)
Traceback (most recent call last):
ValueError: 8 is not a valid PosixPermission

Honestly PosixMode looks pretty good, I think it's reasonable to assume it to be a namedtuple, rather than an object with __slots__. I however wouldn't use __int__ and __str__, and would instead use properties for these.


Doing #ifdef DEBUG and #define func() right?

Perhaps use NDEBUG (as used in assert.h) instead of making up your own.  Also note that unless you put an ifdef around the two functions you might get a linkage warning (as one of the functions might be unused).  A warning is undesirable, but so is putting the ifdef around the functions, which will result in one of the functions not being compiled and in time the function may rot.

Note that you might achieve the same end using the tool-chain to modify the symbol table.

Another alternative would be to name the two functions the same in two separate files and link one or the other as required - that would be a cleaner solution, but would need documenting.

Also...

Perhaps make ptrLinks and ptrValuesEtc the same type so that a cast is unnecessary.

Consider whether ptrLinks and ptrValuesEtc are correctly named:

they appear to the uninitiated (me) to mean different things;
also, one is a function and the other a pointer but their form is the same.


Using a radix tree to find case-insensitive matches in large files

time complexity

There is one troubling call in processCurrent that jumps out at me - the downcasing. I get the sense that sb becomes "big", so the nested inner loop for the linear scan seems like trouble. It's the sort of thing that can easily turn e.g. a linear algorithm into a quadratic one. I understand that case matters for correctness, but just humor me for a moment. Imagine  an alternate implementation that calls toLowerCase at file read time, destroying valuable information but allowing processCurrent to happen quicker. With such results in hand as a valuable hint, could you coax the current implementation to report results faster? As a simpler alternative, could we replace all comparisons in the current implementation with case-insensitive comparisons? Maybe downcase data when handing it to the radix tree library. The point is to avoid repeatedly downcasing a given character many thousands of times - we want to do localized work on our current focus rather than doing (ignored) global work.

memory complexity

There are a few large memory consumers such as storing Match hexOffsets, and storing charAndIndex tuples rather than generating them. Their cost is "just" linear with filesize, so maybe it's an acceptable tradeoff in the name of clarity, but you might think about what the code would look like if you deleted a large ancillary object (or made it smaller). Perhaps code that depended on the large object could get by within a smaller footprint? You're memory constrained and you want parallelism, so reducing memory by 2x would let you keep twice as many cores busy.

varying file sizes, and stragglers

The parallel mapping that invokes FileProcessor is very nice, it is simple and clear. But you complain about memory pressure, and I think your input files are of diverse sizes. This leads to two suggestions: consider viewing files as a series of fixed-length subproblems to work on, and consider throwing lots of tasks into a queue that a fixed number of worker bees draw from. Then you can size it so there's about N workers for N cores, each using about 1 / Nth of memory (either 1 / Nth of heap or 1 / Nth of cache, whichever matter more to your elapsed times). If the current code encounters a mix of files where the largest is, say, double the size of the smallest, then it's likely to be a straggler that impacts elapsed time while most of memory and most of cores are idle.

style

Instead of trie, it would have been helpful to me if you had written private val targetTrie, parallel with targetFile which is a nice informative identifier. It would be very helpful to write down pre- & post-conditions that processCurrent maintains.


Use $(...) instead of `...`

`...` is archaic, error-prone, and harder to read than $(...).

For example, instead of date=`(date +%Y%m%d%H%M)`, write date=$(date +%Y%m%d%H%M).
Note that the extra (...) around the date command was unnecessary.

Double-quote variables used in command arguments

For example instead of for user in ${!users[@]},
write for user in "${!users[@]}".

This way, if the users array has keys with spaces in it,
the program will still work correctly.
In the current example none of the keys contain spaces (they are user1 and user2),
so you don't strictly need it,
but it's a good habit to build.

Don't parse the output of find

This line shows a very bad practice:

directories=`find /var/www/$directory -maxdepth 1 -mindepth 1 -type d`

Let's first correct the form:

directories=$(find "/var/www/$directory" -maxdepth 1 -mindepth 1 -type d)

The problem here is that if any of the files printed by the command contain a newline character, then it will be impossible to tell complete filenames from partial filenames in $directories. If any of the filenames contain whitespace, then parsing the value of $directories will be complicated.

It's best to avoid parsing the output of find when possible.
Even if this code works in your example because you know that the filenames will be strictly alphanumeric, it's good to avoid such bad practices if possible.

In this case there's a fairly simple alternative:

for directory in "/var/www/$directory"/*/

This is basically a simple glob expansion,
with the small trick that the trailing / will make it match only directories.

Notice that */ is outside the double-quoted part. This is because * would not be expanded within double-quotes. For the record, this is an equivalent way to write the above:

for directory in /var/www/"$directory"/*/

Finally, there is a small caveat: this is not exactly equivalent to the find command, because that would also find directories whose name starts with .,
and the glob expansion won't, by default.
If you need to support such filenames, then write shopt -s dotglob before the loop statement. That will enable matching filenames starting with . in glob expansions.

Avoid changing the working directory (with cd) in scripts

Changing directories with cd in scripts is error-prone:

It may become confusing what is the current working directory, at any point in the script
The cd command may fail, for example due to permission issues or filesystem errors. If such failures are not handled (as in the posted script), the program may happily continue executing the rest of the commands, which can have serious consequences. Consider for example what will happen to cd "$foo"; rm -fr * if the cd command fails: important stuff could get deleted!

In the posted code, instead of this:

cd $directory

if [ ! -d backups ]
then
    mkdir backups
fi

tar --exclude ./backups -czf backups/$date.tar.gz .

You could write without using cd like this:

mkdir -p "$directory/backups"
tar -C "$directory" --exclude ./backups -czf "backups/$date.tar.gz" .

That is, use the -C flag of tar to specify its effective directory,
and use the correct paths in other commands appropriately.
Keep in mind that the rest of the commands in the loop body that rely on the path of backups will also need to be adjusted accordingly.
For example change gzip > backups/$date.sql.gz to gzip > "$directory/backups/$date.sql.gz".

Notice that I double-quoted the parameters using the $date variable,
as explained earlier in this posted.
And I replaced a conditional statement by taking advantage of the -p flag of mkdir.

Don't give permissions willy-nilly

Using chmod with unnecessarily relaxed permissions is a very bad practice.
Question every permission bit if it's really needed and why.

Let's take a closer look at this:

chmod 770 backups -R
chown $user:$user backups -R

The chmod gives read-write-execute permission to the user and the group of files and directories under backups, recursively.
Why? The loop body creates .gz files under backups.
These files don't need to be executable.
Only the backups directory needs to be executable, so that the user can access its contents.

It would be better to set an appropriate umask before the loop.
You will be able to drop the chmod command,
because the umask, combined with the chown will be enough to ensure correct permissions.

Strictly speaking, the chown is only necessary for the newly created files and directories, instead of a blanket chown -R on the parent directory.
But this level of laziness is probably acceptable in a Bash script,
so until the chown -R becomes a practical concern (for example due to an excessively large number of files in the directory tree), I wouldn't complicate the script with more precise treatment.

Test your backup solutions

Can you spot the bug in this code?

for database in $databases
do
    if [ $database = ${directory##*/} ]
    then
        mysqldump -u $user -p$password $database | gzip > backups/$date.sql.gz
    fi
done

The $database variable is not used in the output filename.
If there are multiple databases,
only the last one will be saved.
A few months later, if you try to fix a corrupted database by recovering from backups,
you would be in for a terrible surprise,
discovering that some database backups are completely missing.

Be sure to test thoroughly your backup solution, accounting for the most complex supported scenarios.

(And as pointed out multiple times earlier, double-quote variables used in command arguments.)


Calculating binary tree height as asked in the interview

There is no input/output handling in your code.

Even though it is fine to implement the algorithm in isolation, and also to base your unit tests on the backing implementation, handling input and output was part of the problem specification.

If this was for an interview, you would have missed to fulfill the specification.

  Having said that I would like to adhere to the problem specification in past I saw people arguing about the best practices which doesn't match with the problem statement and hence becomes immaterial.

Even if the problem specification gives you guarantees about the input being well formatted, you still should take care to handle invalid inputs gracefully.

Both of your implementations e.g. get caught in an infinite loop, should the input contain a directed graph with loops instead of a tree. Your second implementation will even exhaust the call stack eventually.

Simply limiting the recursion depth / iteration count to the number of input elements would have protected you against that.

Verifying that there is only a single root node, or that all indexes are valid would have easily fit within the budget as well. Even though your algorithms would just throw an exception / yield nonsensical results in that case, so it's not as critical as the loop case.

As it stands, your code is a potential vector for a DoS attack and should therefor not be used in any publicly accessible environment.

function recur(parent, i, depth) {
  if (depth[i] !== 0) return;

  if (parent[i] === -1) {
    depth[i] = 1;
    return;
  }

  // Find the depth of parent
  if (depth[parent[i]] === 0) recur(parent, parent[i], depth);

  // We have depth of the parent now
  depth[i] = depth[parent[i]] + 1;
}

Recursions are nasty in JavaScript, because the maximum recursion depth is pretty low on some platforms: https://stackoverflow.com/a/7828803/2879325

You should try to express this in iterative form if possible, especially since the problem specification does not provide you with an upper bound!

// O(N^2)
console.log(heightSlow([4, -1, 4, 1, 1])); // 3
console.log(heightSlow([-1, 0, 4, 0, 3])); // 4

// Theta(N)
console.log(heightFast([4, -1, 4, 1, 1])); // 3
console.log(heightFast([-1, 0, 4, 0, 3])); // 4

That's an usage example, but it's not a unit test. If you don't want to use a fully fleshed testing framework, the least you can do is something this:

function test(functor, expected) {
  var result;
  try {
    result = functor();
  } catch(e) {
    console.error(Function.prototype.toString.call(functor), e, expected);
  }
  // Object comparison hack
  if (JSON.stringify(result) !== JSON.stringify(expected)) {
    console.error(Function.prototype.toString.call(functor), result, expected);
  }
}

// O(N^2)
test(function (){return heightSlow([4, -1, 4, 1, 1])}, 3);
test(function (){return heightSlow([-1, 0, 4, 0, 3])}, 4);

// Theta(N)
test(function (){return heightFast([4, -1, 4, 1, 1])}, 3);
test(function (){return heightFast([-1, 0, 4, 0, 3])}, 4);

That provides you with simple unit tests which are both machine checked and easy to comprehend in case of an error.

Just beware that this is not exactly robust with regard to run time errors, such as exhausting the recursion limit!

As for your choice of test cases, you didn't test anything but trivial cases.

The most bugs however usually hide in edge cases, such as:

Minimal input
Degenerated input (sequential list or all nodes are children of root)
Malformed input (duplicate root, no root, loops)
Large inputs (long sequential list, exhausting the recursion limit!)

// find depth of each node
// recursion would be called for each node but
// it would return immidiately hence we can ignore that call?
// if yes then recur would be called N times exactly. Hence,
// Theta(N)

The conclusion is correct, but the argumentation is incoherent.

Your argument is that you are calculating the height of each node exactly once, plus a total of \$n\$ comparisons to verify that each node has either been computed yet, which amounts to a total of \$2n\$ calls to recur().


Your computer will get bored, too, dividing (over?) by count over and again. Use
avg_count = sum / count / count - or
scale = something / sum


It would be helpful to know how textSurface is created. There may be a performance win to be had by using, say, a hardware surface instead of a software surface.

If you are using a surface that supports double buffering I would reccomend using SDL_FLip rather than flipping the buffers yourself using 2 surfaces.

E.g:

SDL_Surface* textSurface;
if(!(textSurface = SDL_SetVideoMode(600, 400, 32, SDL_HWSURFACE)))
    SDL_Quit();

SDL_SetColorKey(textSurface, SDL_SRCCOLORKEY, SDL_MapRGB(textSurface->format, 255, 0, 255)); //typically we use magenta
for(auto i=0; i<256; i++){
    auto col = SDL_MapRGB(textSurface->format, i, i, i);
    std::cout << col << "," << SDL_FillRect(textSurface, 0, col) << std::endl;
    SDL_Flip(textSurface);
}

Note that for your current goal, there is no need to reset the ColorKey each time around the loop.

If you want to run faster than "a few seconds" you certainly won't need to display all 256 intermediate colours to achieve the desired effect.

SDL_Surface* textSurface;
if(!(textSurface = SDL_SetVideoMode(600, 400, 32, SDL_HWSURFACE)))
    SDL_Quit();

SDL_SetColorKey(textSurface, SDL_SRCCOLORKEY, SDL_MapRGB(textSurface->format, 255, 0, 255)); //typically we use magenta
auto frame_increment = 4;
for(auto i=0; i<256; i += frame_increment){
    auto col = SDL_MapRGB(textSurface->format, i, i, i);
    std::cout << col << "," << SDL_FillRect(textSurface, 0, col) << std::endl;
    SDL_Flip(textSurface);
}

You should determine frame_increment based on your desired time and hardware capabilities.


While this task can be written as a single loop over your data, it would involve unnecessarily convoluted conditionals and temporary variables which will likely be an irritation to future developers (that person might actually be you) that may need to read your code.

I respect your desire to keep things terse, but great code isn't just brief, it is easily comprehensible.  I feel that two loops will be the smartest approach.  In the first loop, create a grouping array with the street name as keys and push each number into its respective street's subarray.

Then filter the group array for qualifying data (2 or more numbers in a group), extract the highest and lowest number, then append the bookend numbers to the street name.

Code: (Demo)

$array = [
    ['apn' => 345345353, 'sqft' => 1121, 'address' => '12 Lincoln Ave.'],
    ['apn' => 345345351, 'sqft' => 1643, 'address' => '13 Lincoln Ave.'],
    ['apn' => 345345352, 'sqft' => 1222, 'address' => '14 Lincoln Ave.'],
    ['apn' => 345345358, 'sqft' => 1226, 'address' => '6 Olark Ave.'],
    ['apn' => 345345345, 'sqft' => 1200, 'address' => '323 Pacific Ave.'],
    ['apn' => 345345342, 'sqft' => 1421, 'address' => '324 Pacific Ave.'],
    ['apn' => 345345347, 'sqft' => 1093, 'address' => '328 Pacific Ave.'],
];

foreach ($array as $row) {
    [$number, $street] = explode(' ', $row['address'], 2);
    $group[$street][] = $number;
}

$result = [];
foreach ($group as $street => $numbers) {
    if (sizeof($numbers) > 1) {
        array_push($result, min($numbers) . ' ' . $street, max($numbers) . ' ' . $street);
    }
}

var_export($result);

Output:

array (
  0 => '12 Lincoln Ave.',
  1 => '14 Lincoln Ave.',
  2 => '323 Pacific Ave.',
  3 => '328 Pacific Ave.',
)


The first, obvious, issue is that generating the set in memory uses a lot of memory. However, making a lazy version is a bit more advanced, so don't worry about it for now.

1. Code to the interface, not the implementation

public static HashSet<HashSet<Integer>> generateAllSubsets(Set<Integer> original) {

is bad.

public static Set<Set<Integer>> generateAllSubsets(Set<Integer> original) {

is better.

2. Generics reduce repetition

public static <T> Set<Set<T>> generateAllSubsets(Set<T> original) {

is better still, because you can use it to find power sets of any set.

3. Generics remove the necessity to do most casts

    Iterator it = original.iterator();
    while(it.hasNext()) {
        Integer element = (Integer) it.next();

and

        Iterator it2 = tempClone.iterator();
        while(it2.hasNext()) {
            Set<Integer> s = (HashSet<Integer>) it2.next();

have wholly unnecessary explicit casts (which in the second case generates a warning) because you're using the raw type Iterator. Both can also be simplified using the same foreach syntax which you use when making the copy of the power set so far.

4. KISS

You have three loops (including the one hidden behind allSubsets.addAll), which seems to me to be unnecessarily complicated. If you make a shallow copy first then you can combine the deep copy with the adding an element.

public static <T> Set<Set<T>> generateAllSubsets(Set<T> original) {
    Set<Set<T>> allSubsets = new HashSet<Set<T>>();

    allSubsets.add(new HashSet<T>()); //Add empty set.

    for (T element : original) {
        // Copy subsets so we can iterate over them without ConcurrentModificationException
        Set<Set<T>> tempClone = new HashSet<Set<T>>(allSubsets);

        // All element to all subsets of the current power set.
        for (Set<T> subset : tempClone) {
            Set<T> extended = new HashSet<T>(subset);
            extended.add(element);
            allSubsets.add(extended);
        }
    }

    return allSubsets;
}

You'll note that I'm using the copy-constructor rather than clone(). That's a matter of taste: fundamentally there's no real difference, because they're both special-cased.


Find group of available stalls in an aisle

There are no docstrings. What does an object belonging to the Stall class represent? What do the methods do? How should I call them?
The get_available_adjacents method relies on the adjacents attribute. But there is no method on the class that sets this attribute. This makes it hard to reason about the behaviour of this method.

Update: I recognize that you can't supply the adjacent stalls at initialization time (because maybe they haven't been created yet), so I recommend initializing the adjacents attribute to an empty collection in the __init__ method, and providing a method to extend the collection.

Alternatively (as suggested by Sjoerd Job Postmus in comments), since aisles have a standard layout, it might make sense to move the adjacency computation to the aisle class. If you do the latter then you'll find that the Stall class becomes redundant — all it represents is whether there is an occupant or not, and that could be represented by an Occupant object, or None if there is no occupant. (Assuming that no occupant can occupy more than one stall.)
I don't like the way that get_available_adjacents has been implemented as a method on the Stall class. That's because finding an available set of stalls in an aisle is an operation on an aisle, not an operation on an individual stall. Methods should be placed where they make logical sense, not just attached to any old class.
The algorithm you have implemented is known as flood fill. If you read the Wikipedia article, you'll see a couple of approaches for making it faster: (i) use a queue instead of a stack, to avoid function call overhead; (ii) run as far as you can along horizontal rows to reduce the amount of queue management. (But neither of these approaches improves the efficiency: all algorithms take time proportional to the size of the flooded region.)


Integer to binary using an old-school way

Functional extraction

Your method does not do toBinary, it does:

read input from user
convert to binary
print back for user

When you have methods that do multiple things it becomes hard to isolate and reuse the logic. Your code should be split in to parts, and the toBinary method should take the int input and return a String

Complicated end-of-loop handling

The while condition while (num >= 2) { is a complicated construct, that needs a comment. That logic is key to the process, and guarantees that you are left with a "dangling" 1 for the high-bit, and also handles the 0 input case. It took me a number of minutes to figure out how that code works, and that's not useful for your readers... (or yourself, a year in the future).

As it happens, a do-while loop is the structure you want, and it simplifies the logic a whole bunch....

valueOf(...) mystery

I assume you have done a static import of the String class? Otherwise the valueOf method is not defined. Doesn't this defeat some of your "old-school" desire? Also, why not just use a simple 2-value lookup table. The digits are either 0 or 1, so it's simply:

char[] digits = new char[]{'0', '1'};

and then your valueOf can be replaced with:

digits[num % 2]

implicit type conversion

You do an implicit type conversion in the output num + newS which is not "old-school" either. Adding a number to a string is... complicated.

Unnecessary reversals

Why do the reverse mechanism? Why not just build the digit string up backwards to start with? Instead of:

s = s + valueOf(num % 2);

have:

s = valueOf(num % 2) + s;

String concatenation

String concatenation with the + operator is often frowned on... in this instance, it makes the code cleaner, and I am leaving it in. The alternative is to use a StringBuilder, but that has other issues in this use-case. Like you, I would use string concatenation...

Conclusion

All told, I would recommend something like:

private static final char[] digits = "01".toCharArray();

private static String toBinaryRL(int num) {
    if (num < 0) {
        throw new IllegalArgumentException("toBinary can only handle positive integers, not " + num);
    }
    String binary = "";
    do {
        binary = digits[num % 2] + binary;
        num /= 2;
    } while (num > 0);
    return binary;
}

Further, this process can be easily extended in to any "base", by extending the digits, and adding a parameter to the function:

private static final char[] digits = "0123456789abcdefghijklmnopqrstuvwxyz".toCharArray();

private static String toBase(int num, int base) {
    if (num < 0) {
        throw new IllegalArgumentException("toBase can only handle positive integers, not " + num);
    }
    if (base <= 1 || base >= digits.length) {
        throw new IllegalArgumentException("Cannot convert to base " + base);
    }
    String result = "";
    do {
        result = digits[num % base] + result;
        num /= base;
    } while (num > 0);
    return result;
}

private static String toBinaryB(int num) {
    return toBase(num, 2);
}


Idiomatic Django conditional filter queryset

It's fine.
As this function doesn't have a default value for parameters,
you would have to use a dictionary if you want to make it more DRY.
I'd do something like:

kwargs = {
    'pk': pk,
    'user': user_pk
}
if not kwargs['user']:
    del kwargs['user']
queryset = Comment.objects.filter(**kwargs)


Python script to demonstrate Fermat's Last Theorem, with option to restart

Mathematics

Fermat's Last Theorem states:

  No three positive integers a, b, and c satisfy the equation an + bn = cn for any integer value of n greater than 2.

That's not what your code does.  Why are you requiring that a, b, and c be greater than 2, when they only need to be greater than 0?  Why does your prompt for n only say Give a positive number for the exponent "n" when it should say Give an integer greater than 2 for the exponent "n"?

And who is "Fermet"?

Flow control

Function calls should not be used as gotos.  Functions should accept parameters and return a result.  Your calls to user_input() and program_restart(), on the other hand, expect the execution to never return to the caller.  To see the problem with that, say "yes" a few times to retry the calculation, then hit CtrlC to abort.  You'll see the stack trace, which indicates that the ever-deepening stack is keeping track of all the calls, in anticipation for the opportunity to return control to the caller.  Since control never returns, the stack grows deeper and would eventually overflow.

Suggested solution

def prompt_yesno(prompt):
    return input(prompt) in 'Yy'

def prompt_int(prompt, min=None):
    while True:
        try:
            ans = int(input(prompt))
            if min is None or min <= ans:
                return ans
        except ValueError:
            print("Input must be an integer.")

def is_fermat_counterexample(a, b, c, n):
    return n > 2 and a**n + b**n == c**n

def fermat_demo():
    print("Let's see if Fermat was right.")
    print("He claims that a^n + b^n = c^n cannot be true for any n > 2.")
    a = prompt_int('Give a positive integer for "a": ', 1)
    b = prompt_int('Give a positive integer for "b": ', 1)
    c = prompt_int('Give a positive integer for "c": ', 1)
    n = prompt_int('Give an integer bigger than 2 for exponent "n": ', 3)
    print("Holy smokes, Fermat was wrong!"
          if is_fermat_counterexample(a, b, c, n) else
          "No, that does not work!")

while True:
    fermat_demo()
    if not prompt_yesno("Would you like to try again?\n"
                        "Type 'Y' to continue and 'N' to exit: "):
        break

A more interesting demonstration

It would be a more satisfying demonstration if the computer asked the user for a, b, and n, then solved for c, showing that c is not an integer.


Handling Circular References Without Recursion

Correctness
Following testcase breaks your code:
const o={};
o.x = o.y = {};

This is due to objectTracker tracks all seen values not all parent values.
Interface Design

initialPathValue looks strange to me. The parameter has no meaning to this function as far as I can tell.
Dot separated path won't work if any .s in keys. For example: { "a.b": {}, "a": { "b": {} } }. To avoid any confusion, I would suggest use string[] instead.

Implementation

objectStack is named as Stack, but you are using it as a Queue. I believe there should be a mistake here. Maybe you want pop() instead of shift().
parentValue is a WeakSet. But I cannot find a reason why any objects in it will be garbage collected during the functions life cycle. So maybe a simple Set would fint your requirement.


Monge Array - leftmost minimum for each row

Read compiler warnings and fix them:

src/main.rs:7:11: 7:27 warning: unnecessary parentheses around `if` condition, #[warn(unused_parens)] on by default
src/main.rs:7         if(monge[i] < min){
                        ^~~~~~~~~~~~~~~~

Spaces before braces

fn min(...) -> usize{ // No
fn min(...) -> usize { // Yes

Be consistent about brace indentation

// No
if {
    1
} else { 2 }

// Yes
if {
    1
} else {
    2
}

mut is stuck to the &

& mut Vec<usize> // No
&mut Vec<usize> // Yes

else lives on the same line as the previous curly brace

// No
if true {
    1
}
else {
    2
}

// Yes
if true {
    1
} else {
    2
}

No need to leave blank space at the beginning of a block

// No
fn foo() {

    let a = 1;

// Yes
fn foo() {
    let a = 1;

Keep the macro braces attached to the macro name, and indent the body if it's going to be multiline. Leave a trailing comma, and use spaces after the comma

let x = vec![
    10, 17, 13, 28, 23,
    17, 22, 16, 29, 23,
    24, 28, 22, 34, 24,
    11, 13,  6, 17,  7,
    45, 44, 32, 37, 23,
    36, 33, 19, 21,  6,
    75, 66, 51, 53, 34,
];

Leave spaces after commas in function calls as well, but not before

// No
get(row ,leftmost[row - factor]),

// Yes
get(row, leftmost[row - factor]),

A single space around =

leftmost[row] =  min(...); // No
leftmost[row] = min(...); // Yes

Never take a &Vec<T> as an argument, use a &[T] instead. This allows more types to be provided
Your min function is poorly named. The name seems to suggest it will return the minimum value, when it actually returns the index of the minimum value. Rename it to something intention-revealing. Maybe index_of_minimum
Space after a ; in an array or vector

vec![0;row]; // No
vec![0; row]; // Yes

Instead of having multiple lines in a for x in y clause, create a variable to store that in.

// Poor name because I'm not sure what it really is
let x_rows = (0..)
    .map(|x| factor * (2 * x + 1))
    .take_while(|&x| x < (rows - 1));

for row in x_rows {

Eventually, min_by will be stabilized, and you can use it:

// May be off-by-one errors here
let (min_index, _) =
    monge.iter()
    .enumerate()
    .skip(from)
    .take(to - from)
    .min_by(|&(_, v)| v)
    .unwrap();
min_index

I'm sure there's more that can be suggested, but my brain is tired for now ^_^.

fn index_of_minimum(monge: &[i32], from: usize, to: usize) -> usize {
    let mut min = monge[from];

    (from + 1..to).fold(from, |m,i| {
        if monge[i] < min {
            min = monge[i];
            i
        } else {
            m
        }
    })
}

fn minimums(monge: &[i32], leftmost: &mut Vec<usize>, rows: usize, columns: usize, factor: usize) {
    if rows == 1 {
        leftmost[0] = index_of_minimum(monge, 0, columns) % columns;
    } else {
        let mid = rows - (rows / 2);
        minimums(monge, leftmost, mid, columns, 2 * factor);

        let get = |i, j| (i * columns) + j;

        let x_rows = (0..)
            .map(|x| factor * (2 * x + 1))
            .take_while(|&x| x < (rows - 1));

        for row in x_rows {
            leftmost[row] = index_of_minimum(monge,
                                get(row, leftmost[row - factor]),
                                get(row, leftmost[row + factor] + 1)) % columns;
        }

        if rows % 2 == 0 {
            let row = factor * (rows - 1);
            leftmost[row] = index_of_minimum(monge,
                                get(row, leftmost[row - factor]),
                                get(row, columns)) % columns;
        }
    }
}

fn main() {
    let row = 7;
    let x = vec![
        10, 17, 13, 28, 23,
        17, 22, 16, 29, 23,
        24, 28, 22, 34, 24,
        11, 13,  6, 17,  7,
        45, 44, 32, 37, 23,
        36, 33, 19, 21,  6,
        75, 66, 51, 53, 34,
    ];

    let mut leftmost = vec![0; row];

    minimums(&x, &mut leftmost, row, 5, 1);

    for x in leftmost {
        println!("{}", x);
    }
}


Finding a common prefix/suffix in a list/tuple of strings

common_suffix can be written as return common_prefix(string[::-1])[::-1] because the operations are just the simmetric of one another, and this way will prevent duplication.

Also I think you should not handle max or min inside the common_prefix function because it feels like the function has double responsabilty: finding prefixes + length interval check.

Why are you limiting yourself to strings? Python allows general functions very easily.

Why do you build all the result and then return it? You should yield the result item by item:

Why do you write so much yourself? Using the itertools module is much more efficient and simple:

def common_prefix(its):
    yield from itertools.takewhile(all_equal, zip(*its))

PS: common_suffix will now need to use reversed(list instead of [::-1]


Task.Run(async () =>
{
    await SendRequests(cookie, request1, request2);
})

is a very long-winded way of writing

SendRequests(cookie, request1, request2)

.GetAwaiter().GetResult() is also a long-winded way of writing .Result, but since you're ignoring the return value it's probably necessary.

  Can the SendRequests method ever return before the requests finish / get resolved?

Of course. Otherwise it would return List<HttpResponseMessage> rather than Task<List<HttpResponseMessage>>. However, assuming that wasn't the question you actually intended to ask...

The doc for SendAsync says

  The returned task object will complete once the entire response including content is read.

Since you await both of the tasks, the responses must finish before the SendRequests task will finish. (Of course, if the first one throws an exception then the second won't even be sent).

It's not clear to me whether the intention was for the requests to be made in parallel. That seems to be implied by

  to 2 different endpoints (not related to or dependent on each other).

In that case you would want to create the tasks and then wait for them both:

var responseTask1 = httpClient.SendAsync(request1);
var responseTask2 = httpClient.SendAsync(request2);
await Task.WhenAll(responseTask1, responseTask2);

responseMessages.AddRange(new [] { responseTask1.Result, responseTask2.Result });

return responseMessages;

Although I have to say that I don't understand the purpose of creating responseMessages in the outer scope.


You did many things right. Great! =)

Readability and complexity reduction

Your

private String rank;

is nice and readable, but what is a rnk in

public Card(String rnk, String sut)

?

I would not suggest to compromise on the readability of publicly visible variable names. (And I would neither suggest doing so on any other variable of any access level.)

If there's no good alternative name for parameter names, use this to differentiate the readable (and equal) variable and parameter names:

public Card(String rank, String suit) {
    this.rank = rank;
    this.suit = suit;
}

A common alternative solution is to add an underscore character to the variable name like so:

private String _rank;
private String _suit;

Speaking of those two variables, it might make sense to make them final. After all, the suit of a card should never be changed. This reduces complexity, because you can only ever set the value once.

Top-Down design (refactoring)

  a randomly selected card from a deck of 52 cards.

You are not doing that at all. You pick some random rank and some other random suit and construct a card from that. The concept of a "deck" doesn't exist at all in your code. You merely have it implicitely defined just by how your random number generation works.

From top-down design code, I'd expect to see some object representing the deck of cards and some mechanism to get a random card from it. E.g.

Deck cardDeck = new Deck();
Card randomCard = cardDeck.getRandomCard();

Documentation

The public documentation of the constructor parameters

* @param rnk The rank of the card
* @param sut The suit of the card

is not adding any new information, while the hidden comments of the variables do:

/* The card rank : Ace,2,3,4,5,6,7,8,9,10,Jack,Queen,King */
/* The card suit : Clubs, Diamonds, Hearts, Spades */

I wish I could see those when being clueless about how to invoke the constructor.

My personal opinion is that comments like

/* Instance variables */

and

/* Constructor */

do not add any value. If you want them or if you are forced to add them, you should be consistent though and also add

/* Public methods*/

to your classes.

Object oriented

rank and suit should be Enum Types. One part of object oriented philosophy is to create types in a way that they are helpful. A string is a string, but a Suit is not a Rank. Among many others, this has the benefit of preventing mistakes like the following from even compiling:

private Card selectCardFromDeckRandomly() {
    String rank = selectRandomCardSuit();
    String suit = selectRanomCardRank();
    return (new Card(rank, suit));
}

  Note: still not in a position to use arrays.

You actually are in exactly that position.
In you case, limiting your code to not use arrays is what reduces your ability to improve it the most.

The use of enums leads to the use of their values() method (which returns an array), which allows you to get rid of the switches, resulting in more generic code.

Oh, and btw. isn't String [] args an array?


Designing a sorting algorithm from scratch

Congrats of making your own sorting algorithm!
Speed/Efficiency
There are plenty of sorts on Wikipedia that are more efficient, if you want to take a look at them. I added rough speed (given random data) and difficulty estimates:

Bubble sort (very slow, very easy)
Selection sort (slow, easiest)
Insertion sort (also slow, but harder)
Merge sort (fast, hard)
Quicksort (faster, also hard)

Output
Typically it is bad practice to put a print statement inside a function, because you don't want your console flooded with text if you are calling that function a bunch of times. Instead, you can do return numSort inside your function and print(sortFunc(myList)) outside.
Naming
Now, I'm sure you will also get answers pertaining to variable names, but I'm not a stickler for that, plus your variables and functions seem good already.
Happy coding!


Design of genetic algorithm which would allow TDD

You have already written the API of your implementation. Being strict: That's not how tdd works.

Write one failing test
Make the test pass
Refactor

Your test case should not only test your implementation, but also document the behaviour of your implementation - without having written the implementation. And if you're at the first point, your test case describes the expected behaviour of your implementation. And it guides the design of your implementation.

And what's very important, too: Know when to stop. If you have code which is not covered by your test cases - and should be covered by a test case - at the end of an iteration, you did it wrong.

And in my opinion: A code review does help, but not too much. Because with tdd, an application grows iteration by iteration. And the thoughts which have to be thought during those steps have to be learned and practiced.


In object-oriented design, the key to modelling is to figure out how your application will respond to messages. Messages can be requests for information, requests to do something, or notifications that something has happened.

In your example, the application could receive a message, "what is the next question?" After giving it some thought, you might decide that a Quiz object would be responsible for providing that information, in which case you would need Quiz class with a method to respond to the message.

function Quiz() {
...
}

Quiz.prototype.nextQuestion = function () {
...
};

Now, you don't really have any questions yet, so another obvious message that your application will have to handle is, "add this question with these answer choices and correct answer."

DO NOT simply rush and add a new method to Quiz to handle the new message; instead, you need to repeat the thought process and decide which object is best suited to respond. In this case, again it is a Quiz object because questions are needed to answer the previous message of, "what is the next question?" So, you update your Quiz class accordingly. (Along the way you create a structure to represent a question and an index to track the current question, thus enabling you to find the next question.)

function Quiz() {
    this.questions = [];
    this.index = 0;
}

Quiz.prototype.addQuestion = function (text, choices, answer) {
   this.questions.push(new Question(text, choices, answer));
};

Quiz.prototype.nextQuestion = function () {
    if (this.index < this.questions.length)
        return this.questions[this.index++];
    return null;
};

function Question(text, choices, answer) {
    this.text = text;
    this.choices = choices;
    this.answer = answer;
}

I will skip messages that your application might have to handle in relation to player management and get to those that will require your objects to collaborate.

Say, your application receives a message, "the player has answered to this question with this answer." Going through the same thought process as before, you decide that the Quiz object will handle that, and you add a new method.

Quiz.prototype.answer = function (player, question, answer) {
...
};

However, this time, you need to check if the answer is correct as part of responding to that message. But which object can do that? Of course, the Question structure has the knowledge of correct answer, so it becomes its responsibility. Question has just been promoted from a simple structure to a full-blown class that can also respond to messages; in this case, "is this answer correct?" Therefore--

Question.prototype.isCorrect = function (answer) {
    return this.answer === answer;
};

And--

Quiz.prototype.answer = function (player, question, answer) {
    if (question.isCorrect(answer)) {
         // score some points for player
    }
}

As you can see, object-oriented design is not just finding classes and adding methods to them. You need to think about the messages and how they are handled; in other words, messages are key--NOT classes, NOT methods.

Good luck!


In the innermost for loop,
you have a condition to check in every cycle if k is the square root.
But most of the time it's not equal to the square root.
It would be more optimal to rework that,
and add a special treatment for square numbers once, after the loop:

for (int k = 2; k < lim; k++) {
    if (testcase % k == 0) {
        sum += k + testcase / k;
    }
}
int intLim = (int) lim;
if (intLim * intLim == testcase) {
    sum += lim;
}

You don't need the reader.nextLine() calls in this code,
you can safely remove them.
You can also remove the reader.close(),
no need to close System.in.

int testcases = reader.nextInt();
//reader.nextLine();
List<Integer> values = new ArrayList<>();
for (int i = 0; i < testcases; i++) {
    values.add(reader.nextInt());
    //reader.nextLine();
}
//reader.close();

Is it really important to not print a newline at the end?
If it's not important, then you can rewrite the loop as a for-each loop:

for (int testcase : values) {
    // ...
    System.out.println(sum);
}

Minor things:

It's better to declare variables with interface types when possible, so instead of ArrayList<Integer> values = ..., use List<Integer> values = ...
As of Java 7, use the diamond operator <> when creating parameterized types, for example List<Integer> values = new ArrayList<>()
Always use braces even with single-statement if/else/for
Put spaces around operators and parentheses, for example instead of if(testcase%k==0){ write as if (testcase % k == 0) {


Project Euler 7: 10001 Prime in Functional Programming (FP)

You shouldn't be doing things in a loop that don't depend on things changing in the loop. n < 2, n === 2, and  n === 3 all depend on n, which is constant throughout your loop. Also, if you store your primes, you just have to loop through the primes until you get to sqrt(n), rather than checking every number. There are further tricks to speed up the algorithm, such as checking n only if n mod 60 is in [7,11,13,17,23,29,31,37,41,43,47,49,53,59]; that reduces the number of n to check by more than 3/4.

Is tail recursion an option?

How large is your stack size? You can break recursion into subrecursion. For instance, suppose you have a function that recursively finds the nth to n+100th primes. Then you can have a recursive function than, when asked to find k primes, calls itself on k-101, then appends the k-100 to kth primes. You can then add another layer, and have something that does 10 primes at a time. Do this in binary rather than base 10, and you'll need 14 layers to get 10001 primes.


You are putting your server_name to be $domain and www.$domain. What if, someone puts in www.example.com for the script argument? You will thne be serving www.example.com and www.www.example.com. Instead; replace possible www. from the domain variable.

domain="${domain#www\.}"

Each of your location section has a different indentation. Keep it consistent. Since server section is the root level, you do not need to indent it out. I understand that you are flushing the left indentation from the conf, but I would suggest keeping it, since one might want to peek at them in future, and would like to tweak it?

#!/bin/bash
domain="$1" && test -z "$domain" && exit 2
domain="${domain#www\.}"
drt="/var/www/html"

cat <<EOF > "$s_a/$domain.conf"
server {
    root "${drt}/${domain}";
    server_name ${domain} www.${domain};
    index index.php index.html index.htm;
    location / {
        try_files $uri $uri/ /index.php?q=$uri&$args;
    }
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }
    location ~* \.(jpe?g|png|gif|ico|css|js|ttf|woff|pdf)$ {
        expires 365d;
    }
}

EOF


The Report#gpas method is utilizing the tap method. This feels like too much magic for something so simple (Related: Should I Tap That Hash). It took me a bit to unravel what that method does, which is essentially:

def gpas
  {
    average: student_terms.average :term_gpa,
    minimum: student_terms.minimum :term_gpa,
    maximum: student_terms.maximum :term_gpa
  }
end

This looks much cleaner and immediately easy to understand -- and it's the same number of lines of code.

I haven't dealt with Ruby much in a few years, but prior to Ruby 2.2 the String#to_sym method was a source of memory leaks, because symbol objects never get garbage collected, and the to_sym method always returned a new Symbol object. The symbolize_hash method could be just such a memory leak. I'm actually wondering why you aren't using classes here instead of a Hash. You are creating these Hashes and then manipulating their data. This feels like you need some additional classes to push this behavior into.

There's also no benefit to checking for @year_term_ids.empty? before adding the "where" condition in load_year_terms. Just a simple:

def load_year_terms
  YearTerm.includes(student_year_terms: [ :student ]).where(id: @year_term_ids)
end

will suffice. In fact this feels like it should be a static method on the YearTerm class itself:

class YearTerm < ActiveRecord::Base
  def self.including_student_for(year_term_ids)
    YearTerm.includes(student_year_terms: [ :student ]).where(id: @year_term_ids)
  end
end

Then just call YearTerm.including_student_for(@year_term_ids) in your Report class.


Exercism assignment for word-count in Clojure

I would format it like this:

(ns phrase
  (:require [clojure.string :as s]))

(defn word-array [phrase]
  (s/split (s/lower-case phrase) #"\W+"))

(defn word-count [phrase]
  (frequencies (word-array phrase)))

Notice that I included the require statement as part of the ns definition.

Whether or not you use threading macros (->, ->>) is generally a matter of personal preference, and there's nothing wrong with using them here, but I think in this case since you're only using 2 functions, I find the above easier to read. You might also consider using comp:

(def word-array (comp #(s/split % #"\W+") s/lower-case)
(def word-count (comp frequencies word-array))


Give more sensible names

ALPHABET = {'0000': 'A',
            '0001': 'B',

This is plain wrong, that variable really is not only an alphabet. I usually call dicts x_to_y and I think it is a sensible idea to do so, my suggestion is BINARY_TO_LETTER

Just reverse the dict

def reverse_dict(d):
    return {d[i]:i for i in d}

LETTER_TO_BINARY = reverse_dict(BINARY_TO_LETTER)


Group list items into pages, rows and columns

You're closing tags only when a row or table is full. Is data always going to fit the table size?

if (i % labelsPerRow == (labelsPerRow - 1)) {
    @Html.Raw("
")
}

if (i % labelsPerPage == (labelsPerPage - 1)) {
    @Html.Raw("
")
}

You could make a functional helper and use that instead. Notice that after the loop, the row and table are ensured to be closed. The purpose is to allow the consumer to pick how to build a TAggregate from TSource items and observer methods. We're observing every item, table start/end and row start/end.

public static class GridRenderer
{
    public static TAggregate Render<TSource, TAggregate>(IEnumerable<TSource> source, TAggregate seed, int pageSize, int rowSize,
        Func<TSource, TAggregate, TAggregate> itemObserver,
        Func<TAggregate, TAggregate> beginPageObserver,
        Func<TAggregate, TAggregate> endPageObserver,
        Func<TAggregate, TAggregate> beginRowObserver,
        Func<TAggregate, TAggregate> endRowObserver)
    {
        if (source == null) throw new ArgumentNullException(nameof(source));
        if (pageSize <= 0) throw new ArgumentOutOfRangeException(nameof(pageSize));
        if (rowSize > pageSize) throw new ArgumentOutOfRangeException(nameof(rowSize));
        // .. check observers for null

        var items = source.ToList();
        var result = seed;

        if (!items.Any()) return result;

        for (var i = 0; i < items.Count; i++)
        {
            if (i % pageSize == 0)
            {
                result = beginPageObserver(result);
            }

            if (i % rowSize == 0)
            {
                result = beginRowObserver(result);
            }

            result = itemObserver(items[i], result);

            if ((i + 1) % rowSize == 0)
            {
                result = endRowObserver(result);
            }

            if ((i + 1) % pageSize == 0)
            {
                result = endPageObserver(result);
            }
        }

        if (items.Count % rowSize != 0)
        {
            result = endRowObserver(result);
        }

        if (items.Count % pageSize != 0)
        {
            result = endPageObserver(result);
        }

        return result;
    }
}

Let's say your data does not fit the table size and row size.

var renderer = new StringBuilder();
GridRenderer.Render(new[] {1, 2, 3, 4, 5}, renderer, 4, 2,
    (item, cur) => cur.AppendLine($"    {item}	"),
    cur => cur.AppendLine("
"),
    cur => cur.AppendLine("
"),
    cur => cur.AppendLine("
"),
    cur => cur.AppendLine("
"));
var layout = renderer.ToString();

The grid still gets created correctly.

    1
    2

    3
    4

    5

Note I've used a StringBuilder, but you could also use any other class to render the output. You could also change the flow a bit if you want an empty table when no data is available.


Determining orthogonal polygons in a 3D integer lattice

Type Hints
+1 for using type hints.  But they could be a little more informative.
def polygonise(pts: list) -> list:
Ok.  The function takes a list of pts, but what are pts?  It returns a list, but a list of what?
from typing import Sequence

Point = Sequence[int]
Polygon = list[Point]

def polygonise(points: list[Point]) -> list[Polygon]:
    ...

Now we're giving the reader a lot of information.  A point is a sequence of integers.  Could be a tuple, could be a list.  Not important.  Instead of pts, we're a bit more explicit and say points.  Finally, the function returns a specific kind of list: a Polygon list.
You can help the reader out even more by including a nice """docstring""" for the function.
Axes
axes = {i:set(c) for i,c in enumerate(zip(*pts)) if len(set(c))!=1}
I really, really hate this statement.  It takes the list of points, and explodes each point as an argument for zip.  Then, it takes the first coordinate of each of those points, and returns it as a tuple.  enumerate adds an index to this, to keep track of which coordinate axis we are processing.  Then, we assign those to things to i, c ... really opaque variable names.  axis, coordinates might be clearer.  Then we turn the coordinates into a set, determine the len of the set, and if that is not 1, we turn the coordinates into a set again, for construction the dictionary.
Yikes!  That's a lot to unpack.
Then we take the axes, and assign it into to variables a and b, hoping there are exactly 2 axis.
Perhaps we should add some error checking.
    num_coord = len(points[0])
    if any(len(pt) != num_coord for pt in points):
        raise ValueError("All points should have the same number of coordinates")

    axes = ...

    if len(axes) != 2:
        raise ValueError("All coordinates must be in an orthogonal 2D plane")

    a, b = axes.keys()

That gives me a lot more confidence in the code.
I still don't like the axes = ... statement.  I would re-write it, and maybe use the walrus operator (:=) to avoid creating the set twice, but I'm about to significantly change it.
Useless code
edges[tuple((axis,v1))] = other, v2
Here, (axis, v1) is creating a tuple, to pass to the tuple(...) function.  That seems ... odd.  You could simplify it to:
edges[axis, v1] = other, v2
Alternate implementation
Axes
Instead of a dictionary, let's just extract a list of axis which have varying coordinate data.  A simple comparison of each coordinate of all points with the coordinate of the first point, for each coordinate, will tell us if that axis is important or not.
    axes = [axis for axis, first in enumerate(points[0])
            if any(pt[axis] != first for pt in points)]

    if len(axes) != 2:
        raise ValueError("All coordinates must be in an orthogonal 2D plane")

    a, b = axes

This is a much simpler concept.  No sets are being created (twice).  No dictionaries.
Sorted Edges
The pts_by_axis is very complex, a dictionary of dictionaries of arrays.
Let's rework this, by simply sorting the points list.  We'll sort it two ways, first by the (a, b) coordinate, then by the (b, a) coordinate.  We'll use a helper function to generate the sort keys:
def point_key(first: int, second: int):
    def key(pt):
        return pt[first], pt[second]
    return key

Now we can say sorted(points, key=point_key(a, b)), and we'll have the points sorted in one direction.  sorted(points, key=point_key(b, a)) will sort it in the other direction.
Since the points always come in pairs, to form edges, let's add another helper function, to extract pairs of points from the sorted array.
def in_pairs(iterable):
    it = iter(iterable)
    return zip(it, it)

With these, we can build our sorted edge structure.  But instead of keying the edges dictionary with a tuple to encoding the axis of the edge, let's just use two dictionaries:
    a_edge = {}
    for v1, v2 in in_pairs(sorted(points, key=point_key(a, b))):
        a_edge[v1] = v2
        a_edge[v2] = v1

    b_edge = {}
    for v1, v2 in in_pairs(sorted(points, key=point_key(b, a))):
        b_edge[v1] = v2
        b_edge[v2] = v1

The loop at the end does some check to close a polygon and start the next one.  Really, you have two loops.  Loop while there are still edges.  Inside that loop, loop until you've made a polygon.  With that structure, the code reads much better:
    result = []
    while a_edge:
        v1 = next(iter(a_edge.keys()))
        poly = []

        while v1 in a_edge:
            v2 = a_edge.pop(v1)
            v3 = b_edge.pop(v2)
            a_edge.pop(v2)
            b_edge.pop(v1)
            poly.extend((v1, v2))
            v1 = v3

        result.append(poly)

    return result

Note that I use poly = [] instead of poly = [v1], which means no slice is required at the end to remove the extra point.
Also, I'm popping v2 out of the a_edge dictionary, not a edge, since what is popped out is just a vertex.  I find that much clearer.