Calculator for the price of a team of ninjas and samurai

The main problem is to mix javascript objects with DOM elements. It's conceptual wrong to do this. However this has some advantages, first of all the execution speed.

The alternative, indeed, is to calculate everything with pure javascript and, when something change, rewrite all the DOM elements. This solution, when the data are very large and the elements change too frequently, could be not optimal.

Said this, according with your approach, I try to separate as much possible the DOM with the Javascript with some class/method bridge between them.

First rule: works always with data-* when search values on DOM. Because the css class could be change during a refactory by other developers (after several years maybe). It's also possibile that what you want see don't match what you want manipulate. For example: the quantity of Ninjas could be "1000" and you would write "1k". So it's better to store this value in a data-attribute.

Premise: This is only a point to start.

Here we go.

For link a DOM element with a Javascript Object I've added a data attribute data-object

and of course here

and here

Now we have the object Player

function Player(id, name, value) {
    this.id = id;
    this.name = name;
    this.value = value;
}

We need a Factory of players starting from DOM. Because, if something change on your HTML you should modify only this method:

Player.getPlayerFromDOM = function (domElement) {
    var $dom = $(domElement);
    var playerType = $dom.attr("data-player-type-id");
    var player = {
        id    : +$dom.attr("data-player-type-id"),
        value : +$dom.attr("data-player-value"),
        name  : $dom.find('.heading').text()
    }
    return new Player(player.id, player.name, player.value);
}

Another thing to do is to write a function that fetch the schema of players (how much cost a ninja? How much a samurai?) I think that the better solution is to inject a json with this values, but I don't know if you want/can. So fetching it by DOM.

Player.getSchema= function() {
    var players = {};
    $('[data-object="player"]').each(function() {
        var player =  Player.getPlayerFromDOM(this);
        players[player.id] = player;
    });
    return players;
}

For players we have all.
There is now the player list:

function PlayersList($table) {
    var $tbody = $table.find("totalPlayers");
    // be sure if there is the totalPlayers class
    if($tbody.length == 0) {
        $tbody = $table.append($('
').addClass("totalPlayers"));
    }
    this.$playersContainer = $tbody;
    this.$table = $table;
}

PlayersList.prototype.addRow = function(cells) {
    var $tr = $('
');
    for(var i = 0, clen = cells.length; i < clen; i++) {
        var $td = $('');
        if(cells[i].hasOwnProperty('className')) {
            $td.addClass(cells[i].className);
        }
        if(cells[i].hasOwnProperty('data')) {
            for(var dataAttr in cells[i].data) {
                $td.attr("data-"+dataAttr, cells[i].data[dataAttr]);
            }
        }
        $tr.append($td.html(cells[i].value))
    }
    this.$playersContainer.append($tr);
    return $tr;
}

It's for a simple table managment. Method AddRow add a row with some class or some data-attribute. It could be a simple method of a superclass more generic for table management.
So, when a player is added, the table must be updated with new values.

PlayersList.prototype.addPlayer = function(player) {
    var $table = this.$table;
    var $row = $table.find("tr[data-player-type-id='"+player.id+"']");
    if($row.length === 0) {
        $row = this.addRow(
            [
                {value: player.name},
                {value: 1, className: 'quantity', data:{quantity:1}}
            ]
        ).attr("data-player-type-id", player.id);
    }else {
        var newValue = +$row.find("[data-quantity]").attr("data-quantity")+1;
        $row.find("[data-quantity]").attr("data-quantity", newValue).text(newValue);
    }
    this.$table.trigger('ninja.table-updated')
}

Nothing of special. Just note the trigger of custom event ninja.table-updated that notice the listeners that something is changed (in this case, we will add a listener for total calculation).

For totalcalculation, let's create a method with compute the total with a given schema (maybe the schema could change, or could depends by other things)

PlayersList.prototype.calcTotal = function(schema) {
    var total = 0;
    this.$table.find('tbody').find("tr").each(function() {
        var playerId = $(this).attr("data-player-type-id")
        total += schema[playerId].value*$(this).find("[data-quantity]").text();
    });
    return total;
}

So we have all that we need:

var playersSchema = Player.getSchema();
var $teams = $('.teams');
var playerTable = new PlayersList($teams);

$('body').on('click', '.addToTeam', function() {
    var player = Player.getPlayerFromDOM($(this).parents('[data-player-type-id]'));
    playerTable.addPlayer(player);
});

$teams.on('ninja.table-updated', function() {
    $('#totalvalue').text(playerTable.calcTotal(playersSchema));
});

function Player(id, name, value) {
 this.id = id;
 this.name = name;
 this.value = value;
}

Player.getPlayerFromDOM = function (domElement) {

 var $dom = $(domElement);
 var playerType = $dom.attr("data-player-type-id");
 var player = {
  id    : +$dom.attr("data-player-type-id"),
  value : +$dom.attr("data-player-value"),
  name  : $dom.find('.heading').text()
 }
 return new Player(player.id, player.name, player.value);
}

Player.getSchema= function() {
 var players = {};
 $('[data-object="player"]').each(function() {

  var player =  Player.getPlayerFromDOM(this);
  players[player.id] = player;
 });
 return players;
}
function PlayersList($table) {
 var $tbody = $table.find("totalPlayers");
 // be sure if there is the totalPlayers class
 if($tbody.length == 0) {
  $tbody = $table.append($('
').addClass("totalPlayers"));
 }
 this.$playersContainer = $tbody;
 this.$table = $table;
}

PlayersList.prototype.addPlayer = function(player) {
 var $table = this.$table;
 var $row = $table.find("tr[data-player-type-id='"+player.id+"']");
 if($row.length === 0) {
  $row = this.addRow(
   [
    {value: player.name},
    {value: 1, className: 'quantity', data:{quantity:1}}
   ]
  ).attr("data-player-type-id", player.id);
 }else {
  var newValue = +$row.find("[data-quantity]").attr("data-quantity")+1;
  $row.find("[data-quantity]").attr("data-quantity", newValue).text(newValue);
 }
 this.$table.trigger('ninja.table-updated')
}

PlayersList.prototype.addRow = function(cells) {
 var $tr = $('
');
 for(var i = 0, clen = cells.length; i < clen; i++) {
  var $td = $('');
  if(cells[i].hasOwnProperty('className')) {
   $td.addClass(cells[i].className);
  }
  if(cells[i].hasOwnProperty('data')) {
   for(var dataAttr in cells[i].data) {
    $td.attr("data-"+dataAttr, cells[i].data[dataAttr]);
   }
  }
  $tr.append($td.html(cells[i].value))
 }
 this.$playersContainer.append($tr);
 return $tr;
}

PlayersList.prototype.calcTotal = function(schema) {
 var total = 0;
 this.$table.find('tbody').find("tr").each(function() {
  var playerId = $(this).attr("data-player-type-id")
  total += schema[playerId].value*$(this).find("[data-quantity]").text();
 });
 return total;
}
var playersSchema = Player.getSchema();
var $teams = $('.teams');
var playerTable = new PlayersList($teams);

$('body').on('click', '.addToTeam', function() {
 var player = Player.getPlayerFromDOM($(this).parents('[data-player-type-id]'));
 playerTable.addPlayer(player);
});

$teams.on('ninja.table-updated', function() {
 $('#totalvalue').text(playerTable.calcTotal(playersSchema));
});

Ninja

$10
 Add player

Samurai

$20.25
 Add player

            Players
            Quantity

 Total: $
 0.00


Presenting a boolean as an int for XMLSerialization in C#

I'd implement it like this:

public struct Bit : IEquatable<Bit>, IXmlSerializable
{
    private int value;
    public Bit(bool value) { this.value = value ? 1 : 0; }
    public Bit(int value) : this(value != 0) { }

    public bool Equals(Bit other) { return this.value == other.value; }
    public override bool Equals(object obj) { return obj is Bit && this.Equals((Bit)obj); }
    public override int GetHashCode() { return value.GetHashCode(); }
    public override string ToString() { return this.value.ToString(); }

    public static implicit operator int(Bit value)  { return value.value; }
    public static explicit operator bool(Bit value) { return value.value != 0; }

    System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema() { throw new NotImplementedException(); }
    void IXmlSerializable.ReadXml(XmlReader reader)  { this.value = reader.ReadElementContentAsInt(); }
    void IXmlSerializable.WriteXml(XmlWriter writer) { writer.WriteValue(this.value); }
}

It would be better to store your value as an integer as that is the "true" value that you're interested in.  It's value is normalized using C semantics (i.e., false if 0, true otherwise as opposed to true if 1, false otherwise).  That would feel more natural to me but it's up to you.

I'd be careful with the operator overloading.  Don't do it just because you can, do it because it makes sense.  I'd stop at implementing casting operators from the type explicitly (since that's the only way to get at the value), use the constructors otherwise.  And make only one of them an implicit cast, otherwise you will run into ambiguity errors if you use this a lot in your code.

Consider implementing the IEquatable<T> interface and other appropriate overrides.  If you intend to use this in your code, this could be invaluable.

Consider implementing the IXmlSerializable interface explicitly.  If you intend to use this type as you would any other in your code, you probably wouldn't want to see the serialization methods all the time.  Otherwise if you are only using this for serialization, implement it implicitly.


The starting point in plugin creation is most likely the official documentation here: http://learn.jquery.com/plugins/basic-plugin-creation/

You can start from the very simple plugin that actually contain the function stick as follows:

$.fn.holder = function (options) { /* ... stick's code goes here ... */ return this; };

and this will be the base for your plugin.

Then later you can call

$('#control').holder({ ... some options ... });

And the defined method should be called.

This approach will probably change and below is the review of the code you actually posted, assuming that later you will change it anyway.

The coding style of the presented code is good. I only recommend to remove /***********variables*****************/ and /*************functions***************/ because they are usually become inconsistent with the code blocks below them. Even now the variables are mixed with expressions.

The logic here is unclear:

$('#textButton').click(function () {
    var options = {
        button: '#textButton',
        textBox: '#textBox',
        catcher: '#catcher'
    };
    stick($(options.textBox), options.catcher);
});

this in click handler is the clicked object - $(this) === $(options.textBox) so it it makes sense to move options outside of the click handler and use options.button in $('#textButton').

Also in strip it is not necessary to use $(textBox) because textBox is a jQuery object already.

It is not clear why you have added the functions addStrip and clearTextbox - they are used only once so their code can be just inlined.

$(textBox).val('');
$(textBox).focus();

The power of jQuery allows you to chain the methods (and textBox is already a jQuery object):

textBox.focus().val('');

And the main logic issue - currently the code on the halfway between pure jQuery implementation without model at all and model-driven approach (the code recreates model-like construction on every click). So it is better to select one of the ways and make a step:

remove holderArray and just use $(''.holder .strip'').filter(function () { return $(this).text() === text; }) instead of the array routines
or (and what is better) move holderArray and add code that keeps it consistent with the list. You can check my article on JavaScript MVC for more info on this approach: http://alexatnet.com/articles/model-view-controller-mvc-javascript


Best way to get two columns from a table

There is no telling how the database will optimize the query plan for this, but I would expect that the best query plan would involve applying the predicates to the tables before the union is done. Doing a UNION of multiple small result sets would be more efficient than doing a union on large sets and then filtering the results.

The UNION operation requires a lot of scanning because UNION is also a DISTINCT process (you only have one record of each value in the result).

So, two things.

If you are sure that the values in in a column-pair will not also be in any of the other column-pairs, then you can replace the UNION with the faster UNION ALL.

If you are sure that a column-pair is unique, or empty, then you can avoid the DISTINCT process completely.

I would write the query as:

    SELECT VIDEOURL,
           VIDEOTITLE
    FROM [VincentV5].[dbo].[MARCMSITEMPRESENTATION]
    WHERE [VIDEOURL] != ''
      AND [VIDEOTITLE] != ''
  UNION ALL
    SELECT [COUKVIDEO1URL] AS VIDEOURL,
           [COUKVIDEO1TITLE] AS VIDEOTITLE
    FROM [VincentV5].[dbo].[MARCMSITEMPRESENTATION]
    WHERE [COUKVIDEO1URL] != ''
      AND [COUKVIDEO1TITLE] != ''
  UNION ALL
    SELECT [COUKVIDEO2URL] AS VIDEOURL,
           [COUKVIDEO2TITLE] AS VIDEOTITLE
    FROM [VincentV5].[dbo].[MARCMSITEMPRESENTATION]
    WHERE [COUKVIDEO2URL] != ''
      AND [COUKVIDEO2TITLE] != ''
  UNION ALL
    SELECT [COUKVIDEO3URL] AS VIDEOURL,
           [COUKVIDEO3TITLE] AS VIDEOTITLE
    FROM [VincentV5].[dbo].[MARCMSITEMPRESENTATION]
    WHERE [COUKVIDEO3URL] != ''
      AND [COUKVIDEO3TITLE] != ''
  UNION ALL
    SELECT [COUKVIDEO4URL] AS VIDEOURL,
           [COUKVIDEO4TITLE] AS VIDEOTITLE
    FROM [VincentV5].[dbo].[MARCMSITEMPRESENTATION]
    WHERE [COUKVIDEO4URL] != ''
      AND [COUKVIDEO4TITLE] != ''

If values in one column-pair can appear in other column pairs, then change the UNION to UNION ALL.

If the values can be duplicated in a column-pair, then add DISTINCT to each SELECT.

Do both DISTINCT and UNION ALL if you need to.

The idea is to make the data as small as possible before you start doing the big merging processes.


Nothing wrong with these:

template<typename Iterator>
using ItVType  = typename std::iterator_traits<Iterator>::value_type;

template<typename Iterator>
using StdEqual= typename std::equal_to<ItVType<Iterator>>;

But I find them a bit disturbing being so unbound (they are in the global namespace). Maybe just a feeling. I personally would put them in an anonymous namespace.

I also prefer

template<typename BidirectionalIterator,
         typename Compare=StdEqual<BidirectionalIterator>>
bool is_palindrome(BidirectionalIterator first,
                   BidirectionalIterator last,
                   Compare               comp=Compare())

Over

template<typename BidirectionalIterator,
         typename Compare>
bool alt_is_palindrome(BidirectionalIterator first,
                       BidirectionalIterator last,
                       Compare               comp)

template<typename BidirectionalIterator>
inline bool alt_is_palindrome(BidirectionalIterator first,
                              BidirectionalIterator last)

Putting it all in one function does not reduce readability.
But the huge template type names do bother me slightly. Template names are usually short (because they are not real type).

template<typename I,typename Compare=StdEqual<I>>
  // requires BindirectionalIterator<I>()
bool is_palindrome(I first, I last,Compare comp=Compare())

I change my mind this is fine.

for(; first != last && first != --last; ++first)
    if(not comp(*first,*last))
        return false;

But you may want to look at some algorithms.

return std::equal(first, last, std::reverse_iterator(last), comp);

Admittedly I now compare twice as many elements (so not an improvement in this case (informational only)). But if you are using random access elements you can reduce this by calculating the mid point manually.

auto dist    = std::distance(first, last);
auto halfway = first;
std::advance(halfway, dist/2);
return std::equal(first, halfway, std::reverse_iterator(last), comp);

Looks like this should not compile:

 is_palindrome(begin(s),end(s))

That should be std::begin() and std::end() so it looks like you have a hidden using namespace std; somewhere.

If you are going to declare your lambda like this:

auto my_comp = [](auto const& lhs, auto const& rhs)
{
    return tolower(lhs) == std::tolower(rhs);
};

You may as well put it in a separate function. The point of lambdas is you can see them in place.

is_palindrome(begin(s),end(s),
              [](auto const& lhs, auto const& rhs) {return tolower(lhs) == std::tolower(rhs);}
             );


Improving time it takes to insert thousands of records using Entity Framework

Since you're not making any changes to existing objects, you might set the AutoDetectChangesEnabledproperty of your context to false.

From MSDN:

  Gets or sets a value indicating whether the DetectChanges method is called automatically by methods of DbContext and related classes. The default value is true.

Calling the Add calls the DetectChanges method every time and is expensive. Turn it off and at the end, turn it on again.

Example:

using (var db = new DbContext)
{
    try
    {
        db.Configuration.AutoDetectChangesEnabled = false;
        //logic
    }
    finally
    {
        db.Configuration.AutoDetectChangesEnabled  = true;
    }
}

More reading on this: Secrets of DetectChanges Part 3

Also, you call the SaveChanges method every iteration in your loop. This means you make a call to your DB every iteration to persist that entity and is intensive and time consuming. Place that line of code outside your loop.

foreach (var taskCode in taskCodes)
{
    //logic
    db.TaskCodes.Add(newTaskCode);
}

db.SaveChanges();

It's much more performant to make 1 call for many items than many calls for 1 item!

Here's an example question on StackOverflow about this: Any difference between calling SaveChanges() inside and outside a foreach loop?


Recovering permutation from its image sequence

Exactly like the bookshelf problem

This problem is exactly the same problem as the bookshelf problem that I previously reviewed.  If you work from the end of the inversion sequence, each number is like a book that you remove from the right end of the shelf.  For example, if the inversion sequence were:

Inversion sequence = 0 1 0 2 2 1 2 0

Then starting with the last entry 0, this means that book #8 is the rightmost book on the shelf.  So we can place it there:

Original sequence = ? ? ? ? ? ? ? 8

Next in the inversion sequence is 2.  This means that we book #7 is the 3rd remaining book from the right of the shelf (3rd because 0, 1, 2).

Original sequence = ? ? ? ? 7 ? ? 8

Next is 1, so book #6 is the 2nd from the right:

Original sequence = ? ? ? ? 7 6 ? 8

And you keep going until you fill in the full sequence: 2 4 5 1 7 6 3 8.

\$O(\log ^2(n))\$ solution

Just like with the bookshelf problem, this can be done in \$O(\log ^2*(n))\$ time using a binary indexed tree and a binary search of that tree.  I took the exact code I wrote for the bookshelf problem and adapted it to this one:

#include <iostream>
#include <vector>

static inline int BIT_GET(const std::vector<int> &BIT, int i)
{
    int ret = 0;
    i++;
    while (i > 0) {
        ret += BIT[i-1];
        i -= (i & -i);
    }
    return ret;
}

static inline void BIT_ADD(std::vector<int> &BIT, int i, int val)
{
    int max = BIT.size();
    i++;
    while (i < max)
    {
        BIT[i-1] += val;
        i += (i & -i);
    }
}

int bsearch(const std::vector<int> &BIT, int index)
{
    int low  = 0;
    int high = BIT.size()-1;

    while (low <= high) {
        int mid    = low + ((high-low)>>1);
        int midVal = mid + BIT_GET(BIT, mid);

        if (midVal >= index)
            high = mid - 1;
        else
            low = mid + 1;
    }
    return low;
}

int main(void)
{
    int n;
    std::cin >> n;
    std::vector<int>inv(n);
    std::vector<int>original(n);
    std::vector<int>BIT(n);

    for (int i=0;i<n;i++)
        std::cin >> inv[i];

    for (int i=n-1;i>=0;i--) {
        int index = bsearch(BIT, inv[i]);
        original[n - 1 - index] = i + 1;
        BIT_ADD(BIT, index, -1);
    }

    for (int i=0;i<n;i++)
        std::cout << original[i] << " ";

    return 0;
}

As you can see, only main() changed.  The only tricky thing is that the BIT can only track books being removed and the books on the right shifting left by one.  The problem calls for removing books from the right and the books on the left shifting to the right by one.  So the BIT actually tracks the bookshelf in reverse order.  That is why we when we retrieve index from the BIT, we reverse it to n - 1 - index in order to determine where to place the current value in the original array.


Dynamically display relevant form elements

Comments:

The idea of splitting your data-values with different isolation characters seems silly, just using a comma seems much better, as @76484 suggested, and removing the Regular Expression altogether.

However stepping around that, I can see a few things you could fix up:

Yes and No buttons:

You use yes and no for testing the input, why not use true and false, that way instead of $('input[value="yes"],input[value="true"]'), you can just use $('input[value]').

<input type="button" value="true" data-value="foo" />
<input type="button" value="false" />

Regular Expression declaration:

Assuming entire removal of the regular expression isn't possible: you only use rx once, meaning you can just place the expression in the loop:

if (patt = next_id.match(/[^a-z|^0-9]/g)) {

While loops:

while loops are notorious for causing recursion to occur, so you ought to replace it with a for loop.

It also removes the need for two extra lines for declaring the variable and incrementing the variable.

for (var i = 0; matches[i]; i++) {
  $('#' + matches[i]).slideDown('fast');
}


$(document.createElement('div')). ...

is the same as:

$('

'). ....

you can just build uppon your previus jQuery statements:

$('

')
    .attr('id','lol')
    .html('hey hey')
    .appendTo("#div_selection_section");

$("#cornercases").change(function () {
        CORNER_CASE_LOADING();
    });

is the same as:

$("#cornercases").change(CORNER_CASE_LOADING);

and you can bind 2 events in one with jQuery so:

$("#cornercases").bind("change ready",CORNER_CASE_LOADING)

you might want to
parsInt topvalue in the line with te var

var topvalue = parseInt($('#cornercases').val());

you will not need to repeat pareInt in each 'if' if you do that.

Also, I see that
OLD_CASE_NUMBER is an integer (and if you do what is mesioned above), you won't need to parse that either

as far as I see the second line of your function var counter = 0; is useless, because everywhere you use counter you first set it to something else


Managing inherited dependency properties in WPF

Well, this looks like a really bad idea.

To begin with... what's the point? I mean what is so bad about having a dependency on standard .Net assembly? It is already installed on the machine as part of .Net installation, so this dependency does not affect the size of your app. Am I missing something?
This design works under fairly naive assumption, that the app will not change in any way as the time goes on. And it might be the case for your particular app, but it is not the case in general. Imagine I am using your library, and I want to subscribe to ContentToggle.Loaded event. What should I do? Should I call you at 3AM and ask you to also override this event with new keyword? Will you do the same thing for every single event (or property) found on FrameworkElement? Will you then test every single interaction, to make sure you did not break standard behavior? If you are not willing to take this all the way - don't do it at all.
I don't even want to begin imagining all the potential pitfalls. What will happen if someone sets e.Handled = true; for your new Click event? Will your base event keep going? What will happen, if I have a style for regular button that uses <EventSetter Event="Click" .../> and I want to override this setter for your button's style? How is it going to work, will I have two event handlers as a result or just one? Etc, etc.


Though it is character-building to transform a recursive algorithm into an iterative form (and vice versa) I would not worry too much about iterative vs recursive.

There are several ways you could improve this code.

As I said in your previous post: why an array? You could be much more general and sort an IList<int>.  And why ints?  You can sort any collection of things that can be compared consistently which would make your sorting algorithm more useful.
start and end are very clear. i, j and num are not.  How is the reader of this code supposed to understand what it does?  Rename num to what it is: the pivot.
Recursive quicksort has four basic steps: (1) decide if we're already sorted, (2) choose a pivot, (3) partition and (4) recurse. The considerable majority of your algorithm is devoted to (3). Consider putting the partition logic in a helper method that can be clearly shown to be correct.
Consider showing us your test cases.
There is no error handling; what if the array is null?  What if the start and end are out of bounds?  And so on.
Consider adding postcondition assertions.  A postcondition assertion is a Debug.Assert that documents what the method ensures is true just before it returns. In your case the postcondition is "the array is sorted from start to end". So assert that; write a little "is sorted" predicate and verify that it works. This will help you find bugs, if there are any. This will help future readers of the code understand it. And it will help people who change the code in the future understand what needs to not break when they modify the code.
The partition step also has a postcondition; after the partition the array is partitioned into three parts: the values before the pivot are smaller or equal to it, the pivot, and the values after the pivot are greater than it. Assert that these conditions are met.


Classical model for database connection provider

Like in Spring where you have not defined lazy loading of bean, the singleton beans are created when the context is started up.

3.3.4. Lazily-instantiated beans

  By default, ApplicationContext implementations eagerly create and
  configure all singleton beans as part of the initialization process.
  Generally, this pre-instantiation is desirable, because errors in the
  configuration or surrounding environment are discovered immediately,
  as opposed to hours or even days later.

So assuming you have some entrypoint like main() method - there is the best place where you can create singletons etc. main() is basically the beginning of your application and since this method is called you should be able to use DatabaseService.

In my opinion DatabaseService is something like DataSource in spring so it should not be configured as lazy loading.

I would change getInstane to singleton pattern:

public static DatabaseService getInstance() {
    if(instance == null) {
        instance = new DatabaseService();
    }
    return instance;
}

So I will go for:

public static void main(String... args){
    DatabaseService.getInstance() != null ? LOG.info("DatabaseService initialized!") : throw new SystemException("Failed DatabaseService initilization");
    ...
}

or you can use your init method but it would be better to change void to DatabaseService and check whether instance was created successfully.


Document your code in the code. If trying to stick to all pertaining PEPs gets too much, have a look at Code Documentation Advice.

If you don't want to go with bisect
(noteworthy simplifications/improvements (esp. over/of VersionWrap), anyone? Please edit.)

from bisect import bisect
from functools import total_ordering

class NoBadVersion(Exception):
    """Home brewed exception to diferentiate from other
    kind of exceptions and avoid too generic except clauses.
    """

@total_ordering
class VersionWrap:
    """Support version designator comparison"""
    __slots__ = 'version', 'bad'
    def __init__(self, v, b = None):
        self.version = v
        self.bad = b
    def is_bad(self):
        if self.bad is None:
            self.bad = is_bad_version(self.version)
        return self.bad
    def __eq__(self, other):
        return other.is_bad() == self.is_bad()
    def __lt__(self, other):
        return not self.is_bad() and other.is_bad()

def find_first_bad_index(numbers):
    """Find the first bad version

    Assumes is_bad_version(numbers[i]) implies
     is_bad_version(numbers[i+n]) for every natural number n.
    numbers is a sequence of version designators,
    suitable as parameters to is_bad_version().

    Returns the lowest b such that is_bad_version(numbers[b])
    """
    firstNonGood = bisect([VersionWrap(vd) for vd in numbers],
                          VersionWrap(None, False))
    if firstNonGood == len(numbers):
        raise NoBadVersion('none bad!')

    return firstNonGood

, stay with

"""Find the first bad version

Keep number of calls to is_bad_version() at minimum.
"""

class NoBadVersion(Exception):
    """Home brewed exception to diferentiate from other
    kind of exceptions and avoid too generic except clauses.
    """

def is_bad_version(number):
    """dummy for an external predicate costly to evaluate"""
    return number

def find_first_bad_index(numbers):
    """Find the index of the first bad version

    Assumes is_bad_version(numbers[i]) implies
    is_bad_version(numbers[i+n]) for every natural number n.
    numbers is a sequence of version designators,
    suitable as parameters to is_bad_version().

    Returns the lowest b such that is_bad_version(numbers[b])
    """
    start = 0
    end = len(numbers)

    while start < end:
        mid = start + (end - start) // 2
        if is_bad_version(numbers[mid]):
            end = mid
        else:
            start = mid + 1

    if start == len(numbers):
        raise NoBadVersion('none bad!')
    return start

if __name__ == "__main__":
    numbers = [1] * 7
    for good in range(len(numbers)+1):
        print(find_first_bad_index(numbers))
        numbers[good] = 0


Creating comma-separated '?' placeholders for SQL query parameters

The ? array can be filled using array_fill:

implode(', ', array_fill(0, sizeof($arr), '?'))


Looks pretty good. Some notes:

(Time.now - 1.day) -> 1.day.ago
"08/08/2013".to_time: I'd be in doubt "is that day/month or month/day?". An alternative to avoid problems with the parsing format: Time.new(2013, 8, 8)
Net::HTTP: IMO this module is a pain to use for common tasks. I prefer something higher-level like the rest-client gem. It does a lot of boring things for you.
response.response['set-cookie'].split('; ')[0]. I wouldn't rely on this space after the semi-colon. Safer: response.response['set-cookie'].split(';')[0].strip
Use do/end for multiline blocks.
JSON.parse res.body Be consistent, use parentheses like you did in the rest of the code.
stats = stats['data']['links.created']: don't reuse variables: links_created = stats['data']['links.created']
request and later req, response and later res: Use more declarative names.


Showing links to Contributor Breakdown on Stackoverflow Docs

You're using 'use strict'; in all functions except the top one. Why not declare it at the top of your file?

You seem to have thought about readability. You're declaring variables for just that purpose here:

    let currentLink = exampleLinks[i];
    let currentMenuContainer = exampleMenus[i];

So why oh why do I see magic numbers in your code?

setTimeout(addLinks, 2000);
let topicLink = document.querySelectorAll("a.doc-topic-link")[0];
topicLink.href.split('/')[5]
currentLink.href.split('/')[7]
menu.insertBefore(elem, menu.children[0]);

Of those 5, arguably the first and latter are acceptable. The 3rd and 4th are the most magical of the lot. You explained the first in a comment, but I'd personally move it to a variable.


Markov chain-based random text generator in Perl

The only thing that comes to mind is the way you open the file.

You could do this instead:

open(my $file, "<", "$ARGV[0]") or die;
$data = do { local $/; <$file> };
close $file;

Which is a well known Perl idiom to read an entire file in one go.

For more info see these links

https://perlmaven.com/open-files-in-the-old-way

https://perlmaven.com/slurp

http://www.perlmonks.org/?node_id=20235


Check that an image is available to be served

To make this more efficient, you need to break down this problem into smaller pieces. From your description you are:

Testing the image to see if it exists
Testing the image to see if it is corrupted

The first test is pretty easy, and can be optimized by issuing a HEAD request to the server. The second test is where things get inefficient because you need to download the image and parse it.

Something like a remote image verifier that has methods to test for the image existence and corruption would be beneficial:

class RemoteImageVerifier
  def image_exists?(uri)
    Net::HTTP.start(uri.host, uri.port) do |http|
      begin
        response = http.request_head uri.path
        # check response["header-name"] if need be
        true
      rescue Net::HTTPNotFound
        # Image URL is no longer valid
        false
      rescue Exception
        # Another unknown error happened
        false
      end
    end
  end

  def image_corrupted?(uri)
    Net::HTTP.start(uri.host, uri.port) do |http|
      begin
        response = http.request_get uri.path
        # parse response.body as a JPEG
        false
      rescue Exception
        # Another unknown error happened
        true
      end
    end
  end
end

And to use it:

verifier = RemoteImageVerifier.new

verifier.image_exists? 'http://some_image_cdn.com/images/image.jpg'
verifier.image_corrupted? 'http://some_image_cdn.com/images/image.jpg'


Python script to test music sight reading

Warning for other reviewers : input and input are different depending on the version of Python you are using. This is about Python 3.

Instead of defining the notes of a clef as a dictionnary mapping consecutive integers from 0 to n to names, you could use a list.

You'll have the much more natural :

TREBLE_CLEF_NOTES = [ 'F', 'E', 'D', 'C', 'B', 'A', 'G', 'F', 'E' ]
BASS_CLEF_NOTES = [ 'A', 'G', 'F', 'E', 'D', 'C', 'B', 'A', 'G' ]

and you just need to change :

def random_note(self):
    return random.choice(range(len(self.notes)))

add_note = i == note_index does not seem useful : get rid of it.

The way you are playing with string slicing to display a note or a line doesn't need to be that complicated. Also, defining values as class members was a nice touch but the fact that you hardcode indices in the logic with the string slicing kind of removes the all point. As for me, I'll keep things simple and not so well organised for the time being as these values are unlikely to be useful for anything else than displaying.

Here's my suggestion :

def display(note_index):
    for i in range(9):
        line_element = '-' if i%2 else ' '
        print(line_element * 4 + ('O' if i == note_index else line_element) + line_element*5)

I have to go, I'll try to add more details later. In the meantime, if you are interested in Python and music theory, you might be interested by this github project.


Mapping the differences between JavaScript objects

The existing suggestions are good for trimming down your current code, but, as always, the most important thing to optimize is the algorithm itself. I took a crack at your problem, as I understand it, and here's the result:

function difference(o1, o2) {
    var k, kDiff,
        diff = {};
    for (k in o1) {
        if (!o1.hasOwnProperty(k)) {
        } else if (typeof o1[k] != 'object' || typeof o2[k] != 'object') {
            if (!(k in o2) || o1[k] !== o2[k]) {
                diff[k] = o2[k];
            }
        } else if (kDiff = difference(o1[k], o2[k])) {
            diff[k] = kDiff;
        }
    }
    for (k in o2) {
        if (o2.hasOwnProperty(k) && !(k in o1)) {
            diff[k] = o2[k];
        }
    }
    for (k in diff) {
        if (diff.hasOwnProperty(k)) {
            return diff;
        }
    }
    return false;
}

Note that I didn't try to mimic your code exactly:

Arrays are compared thoroughly, not just on numbered properties.
Difference map contains new values themselves, not their types.
If there are no differences then the function returns false, not {}.


In a Lisp dialect (Scheme, Racket, or anything else), indentation is rather important.  It doesn't determine anything about how the code works, but being able to visually parse the code is necessary, because the alternative is to count parentheses.

With this indentation, you can visually see that the 2 lines after the if are part of the if statement:

(define (coffee cup)
  (if (is-empty? cup)
      (coffee (refill cup))
      (drink cup)))

I just copy-pasted the code into Emacs, told it to switch to scheme mode, and then told it to reindent.  You don't have to use Emacs, but you should use an editor that understands the Lisp dialect you're using.  If you mess up the parentheses, the editor will indent things oddly, and you can visually see that it's wrong without having to count parentheses.


Javascript 5 Module Pattern internal name

Because of the scoping inside a closure you will not run into a problem.

The Revealing Module Pattern

I want to introduce this type of module pattern because it does not need the helper object module. Instead of collecting all public functions inside an object called module return directly an object with all public functions. This will reduce code and result in a better to reading code.

var module = function () {
    var config = {
        css: {
            classes: {
                heading: 'h1',
                navbar: 'nav-bar'
            },
            ids: {
                widget: 'widget',
                block: 'block'
            }
        },
        userName: 'user',
        token: 'UUID'
    };

    function _moduleMethod() {
        console.log(config.userName);
    }

    function init() {
        _moduleMethod();
    }

    // Return an object as public API
    return {
        init: init
    }
}();


My comment is that you can write your desired method with far more generality, no recursion, and far less realization into lists. For example:

using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    public static IEnumerable<R> Zipper<A, R>(IEnumerable<IEnumerable<A>> sequences, Func<IEnumerable<A>, R> f)
    {
        var enumtors = sequences.Select(seq => seq.GetEnumerator()).ToList();
        while(true)
        {
            // Not quite kosher, as we are using Select to cause a side effect!
            var hasValues = enumtors.Select(e => e.MoveNext());
            if (hasValues.Any(v => !v))
                break;
            yield return f(enumtors.Select(e => e.Current));
        }
        foreach(var enumtor in enumtors)
          enumtor.Dispose();
    }

    public static void Main()
    {
        foreach(var s in Zipper(
            new[] {
              new[] {1, 2},
              new[] {3, 4},
              new[] {5, 6, 7} },
            x => string.Join("-", x)))
          Console.WriteLine(s);
    }
}

Produces output

1-3-5
2-4-6

Note that my version works on infinite lists provided that there are finitely many of them.  Note also that my method is "lazy"; it only makes computations when the caller "pulls" something.


Iterating pattern (1-10 then 10-1) with only 1 loop

I don't see any compelling reason for doing this in one loop, but it's certainly possible in a simpler way.  First, though let's look at some other aspects of the code.

Declare one variable per line

Generally, it's better for readability if we declare just one variable per line instead of cramming them all together on a single line.

Use more whitespace

Lines like this

while(i!=0 && lines<3){

Are rendered much more readable if we use more whitespace:

while (i != 0 && lines < 3) {

Use braces consistently

I'd recommend using braces around the else clause statement, even though it isn't technically required.  In addition to making things more readable (there's that word again!) it helps to prevent bugs.

Use better variable names

In the current code, lines is a good variable name because it suggests the purpose of the variable, but flag is not a very good name.  It would be better to make it bool and call it reverse.

Use named constants

Named constants make it easier for readers of the program to understand what's being done and why.

Simplify your code

Essentially, what the program is intended to do is make three traversals from 1 to 10 and back.  I'd write it like this:

int main(void) {
    const int lowerlimit = 1;
    const int upperlimit = 10;
    int i = lowerlimit;
    int delta = +1;  // start counting up
    for (int traversals=3; traversals; ) {
        printf("%d ", i);
        i += delta;
        if (i > upperlimit || i < lowerlimit) {
            printf("\n");
            delta *= -1;   // change direction
            i += delta;    // come back in bounds
            --traversals;
        }
    }
}

Omit return 0

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

Note: when I make this suggestion, it's almost invariably followed by one of two kinds of comments:  "I didn't know that." or "That's bad advice!"  My rationale is that it's safe and useful to rely on compiler behavior explicitly supported by the standard.  For C, since C99; see ISO/IEC 9899:1999 section 5.1.2.2.3:

  [...] a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0.

For C++, since the first standard in 1998; see ISO/IEC 14882:1998 section 3.6.1:

  If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;

All versions of both standards since then (C99 and C++98) have maintained the same idea.  We rely on automatically generated member functions in C++, and few people write explicit return; statements at the end of a void function.  Reasons against omitting seem to boil down to "it looks weird".  If, like me, you're curious about the rationale for the change to the C standard read this question.  Also note that in the early 1990s this was considered "sloppy practice" because it was undefined behavior (although widely supported) at the time.

So I advocate omitting it; others disagree (often vehemently!)  In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means.


Library to verify GTINs of various lengths

I assume the variety of GTIN's are a bounded set.  If so, I see no use
in the inheritance.  Go with Option #2. And on that option I would recommend a
few changes

Pre-build your formats into a dict based on length:

This pre-builds and compiles the format regex's

formats = {l: re.compile(r'^[0-9]{{{}}}[0-9?]{{1}}$'.format(l - 1))
           for l in (8, 12, 13, 14)}

Add a __str__ method for easier debugging:

This makes it easier to see what is going on in the debugger.

def __str__(self):
    return self.gtin if self.gtin is not None else 'invalid'

If you have an early return, put it in the if, not else:

I would generally code something like this:

if len(gtin) in cls.ALLOWED_LENGTHS:
    self.length = len(gtin)
else:
    return False

as this:

if len(gtin) not in cls.formats:
    return False
....

Define a __len__ method if needed:

I removed the self.length as it was not used internally, and a better way to publish the length is with a __len__.

def __len__(self):
    return len(self.gtin) if self.gtin is not None else 0

Consume bool evaluations directly:

If you need a bool and are performing a test to determine the bool state, you rarely need an if.  I redid this:

if re.match(format, gtin):
    return True
return False

as this (with some other changes also incorporated):

return cls.formats[len(gtin)].match(gtin) is not None

So there is no reason for the if, the result of the test can be returned (or assigned to a variable) directly.

Entire Class:

import re

class GTIN:
    formats = {l: re.compile(r'^[0-9]{{{}}}[0-9?]{{1}}$'.format(l - 1))
               for l in (8, 12, 13, 14)}

    def __init__(self, gtin):
        self.gtin = self.parse(gtin)

    def __str__(self):
        return self.gtin if self.gtin is not None else 'invalid'

    def __len__(self):
        return len(self.gtin) if self.gtin is not None else 0

    @classmethod
    def parse(cls, gtin):
        parsed_gtin = cls.sanitize(gtin)
        if not cls.check_format(parsed_gtin):
            return None
        return parsed_gtin

    @classmethod
    def sanitize(cls, gtin):
        return re.sub(r'[\s\-]+', '', gtin)

    @classmethod
    def check_format(cls, gtin):
        if len(gtin) not in cls.formats:
            return False
        return cls.formats[len(gtin)].match(gtin) is not None


Trying to convert imperetive code to functional -Haskell

Why are you reimplementing length O_o?

dft_resolve_nested :: Double -> Int -> [((Double, Double), Double)] -> [(Double, Double)]
dft_resolve_nested _ _ [] = []
dft_resolve_nested k n (((x, y), t) : xs) = do
  let angle = 2.0 * pi * t * k / fromIntegral n
  let sumreal = x * cos angle + y * sin angle
  let sumimag = - x * sin angle + y * cos angle
  (sumreal, sumimag) : dft_resolve_nested k n xs

tuples_sum :: [(Double, Double)] -> (Double, Double)
tuples_sum [] = (0, 0)
tuples_sum ((x1, y1) : xs) = do
  let (x2, y2) = tuples_sum xs
  (x1 + x2, y1 + y2)

dft_resolve ::  [((Double, Double), Double)] -> [(Double, Double)]
dft_resolve [] = []
dft_resolve ls@((_, k) : xs) = do
  let (xr, yr) = tuples_sum $ dft_resolve_nested ls k $ length ls
  (xr, yr) : dft_resolve xs

-- Main driver
main = print $ dft_resolve $ zip [(1,2), (3,4)] [0..]

The explicit recursion can be done by library functions.

dft_resolve_nested :: Double -> Int -> ((Double, Double), Double) -> (Double, Double)
dft_resolve_nested k n ((x, y), t) = do
  let angle = 2.0 * pi * t * k / fromIntegral n
      sumreal = x * cos angle + y * sin angle
      sumimag = - x * sin angle + y * cos angle
  in (sumreal, sumimag)

tuples_sum :: (Double, Double) -> (Double, Double) -> (Double, Double)
tuples_sum (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)

dft_resolve ::  [((Double, Double), Double)] -> (Double, Double)
dft_resolve ls@((_, k) : _) = foldr tuples_sum (0,0) $
  map (dft_resolve_nested k $ length ls) ls

-- Main driver
main = print $ map dft_resolve $ tails $ zip [(1,2), (3,4)] [0..]

Many of these names can be removed. You were also only ever restricted to Double by your own type signatures :). (You may want to tell it what Floating instance to use somewhere, though.)

import Data.NumInstances.Tuple

main :: IO ()
main = print
  [ sum
    [ (  x * cos angle + y * sin angle
      , -x * sin angle + y * cos angle
      )
    | (t, (x, y)) <- ls
    , let angle = 2 * pi * t * k / genericLength ls
    ]
  | (k, ls) <- zip [0..] $ tails [(1,2), (3,4)]
  ]

Edit: Data.Complex specializes in this sort of math:

import Data.Complex

main :: IO ()
main = print
  [ sum [z / cis angle ** t | (t, z) <- ls]
  | (k, ls) <- zip [0..] $ tails [1:+2, 3:+4]
  , let angle = 2 * pi * k / genericLength ls
  ]


- (NSMutableArray *) quickSort: (NSMutableArray *)toSort{
    for(NSNumber *arrayMember in toSort){
        if(![arrayMember respondsToSelector:@selector(doubleValue)]){
                NSLog(@"incorrect types in input array, returning nil");
                return nil;
            }
    }

    /* stuff */
}

There is a lot to comment on in just this part of your code, so that's where my focus will lie.

First of all, given that we're working with a mutable array, we should simply sort it in place--and we should make the method a category of NSMutableArray itself.

@interface NSMutableArray(QuickSort)

- (void)quickSort;

@end

So it can be used as such:

NSMutableArray *myArray = /* array instantiation */

[myArray quickSort];

I'd make a similar category for the immutable NSArray class which returns the sorted array:

@interface NSArray(QuickSort)

- (NSArray *)quickSortedArray;

@end

And that'd be used as such:

NSArray *unsorted = /* array instantiation */

NSArray *sorted = [unsorted quickSortedArray];

This makes our method signature make more sense.  Of course, NSMutableArray is a subclass of NSArray, so we can always apply the quickSortedArray method to an NSMutableArray as well, while the first recommendation (the simple quickSort method) simply sorts it in place and returns nothing.

So, that cleans up our method signature.  It makes it nice, and closer to what we'd expect to see with normal Objective-C methods.

But we've got a bigger problem.

Without documenting it, your method only works for objects which responds to the doubleValue selector, and inexplicably returns nil if anything else exists in the method.

Moreover, it can only sort the array in a single direction: ascending.

Rather than the zero argument quickSort or quickSortedArray methods I recommended, what we actually need is to accept some argument that tells us by what logic to sort the array.

We need a NSComparator argument.  This is what NSComparator is:

typedef NSComparisonResult (^NSComparator)(id obj1, id obj2);

In plain English, NSComparator is a block which takes two arguments (of any object type) and returns an NSComparisonResult (which describes how these two objects should be sorted).

So we want our quickSort method to take one of these and use this for the logic to sort the array.  Let the caller specify how they should be sorted.

So, if as a caller of the quickSort method, I know my array contains only NSNumber objects, I can pass a comparator that treats the two inputs as strictly NSNumber, and it doesn't impact your implementation of the sorting logic.


If you want to match by the same pattern as rename,
then it's probably best to use perl.
To be really pedantic and support filenames with embedded newlines,
you could use -print0 of find,
and then in perl split the output by \0 characters and filter with the grep function:

find . -maxdepth 1 -print0 | perl -ne "print scalar grep /$search/, split /\0/"

Putting in your script:

 while true; do
     echo "Please enter token to be replaced: "
     read -e -r search
     match=$(find . -maxdepth 1 -print0 | perl -ne "print scalar grep /$search/, split /\0/")
     if [ "${match}" -gt 0 ]; then
         echo "${match} file(s) found"
         break
     else
         echo "no matches found!"
         echo
     fi
 done


This looks very well crafted. I don't know f# and I'm not really into functional programming, but I can enumerate everything I like about this code:

Type parameter names are descriptive: TValue and TResult are perfect.
The interface for Optional<TValue> is segregated; it's very focused and specialized, which makes it highly reusable... which is a nice feature for an abstract class.
Usage of this qualifier is consistent.

Well as I enumerated these points I did find a few minor nitpicks:

Usage of this qualifier is redundant.
Usage of String could be replaced with C# language alias string (but then again usage of String is beautifully consistent).

And as I enumerated these minor nitpicks I did find one tiny little thing that could be improved: the Message property in the derived types is only assigned through the constructor, using the private setter. I'd make it readonly and change the auto-property for a get-only property:

public None(String message)
{
    _message = message;
}

private readonly String _message;
public String Message { get { return _message; } }

...and this is where I'm clashing with this - I prefer prefixing private fields with an underscore and avoid this altogether, you might have it like this instead:

public None(String message)
{
    this.message = message;
}

private readonly String message;
public String Message { get { return this.message; } }


Functions that build a path to the model and command files for some tests

Your code is fine and contains documentation, so there's not much to say at that point. That being said, your TestType problem can be tackled by transforming the type class to a data type:

data TestType = BenchTest | IntegrationTest

dataDir :: TestType -> FilePath

However, that just removes the constraint and makes your program less flexible in the long run. So let us go back to the drawing board. The data directory is part of the test configuration. That sounds like a valid new data type:

data TestConfiguration = TestConfiguration
                       { dataDir :: FilePath
                       , ...
                       }

defaultConfiguration :: TestConfiguration
defaultConfiguration = TestConfiguration
                     { dataDir = "data" </> "test"
                     , ...
                     }

Your two functions can now use TestConfiguration as first parameter instead of a TestType. This lets your user define adhoc configurations easily:

myConfiguration = defaultConfiguration
                { dataDir = "data" </> "my" </> "tuesday"
                , verbosity = VerboseLow
                , logFormat = TimeStamps
                , ... -- you get it
                }

Whether you want to allow record syntax, lenses or setters is left to you.


Implementing a binary tree in C++ using "std::unique_ptr"

On raw and smart pointers

First, I'll address your specific question, about using a raw pointer to refer to nodes in the tree.  I believe you're doing exactly the right thing here, because smart pointers convey information about ownership of the resource.

We are looking at nodes that are owned by the tree (actually, each node is owned by its parent), and it's entirely appropriate that that ownership is encoded as a std::unique_ptr; that says that this is the only place that's responsible for deleting the node when it's no longer required.

Our Delete method walks nodes from the root downwards; it needs to refer to the nodes, but only during the execution of the method (it doesn't store pointers anywhere).  A raw pointer is perfectly suitable here.

General review

Is <iostream> used anywhere?  I think it can be omitted.

If this is a header file, avoid bringing std::make_unique and std::unique_ptr into the global namespace, as that will affect every file that includes the header.  It's reasonably to do so inside the function bodies, but at that point it's likely better to simply use the qualified names.  Including them within the scope of the type is a middle ground where opinions will differ.

We should include <utility> for std::move (and the same comments apply to importing that name into ::).

Consider turning tests around to test a positive first, which slightly reduces cognitive load.  Instead of:

if (not node) {
  node = make_unique<Node>(value);
}
else {
  value < node->value
    ? Insert(node->left, value)
    : Insert(node->right, value);
}

This is easier to reason about:

if (node) {
  value < node->value
    ? Insert(node->left, value)
    : Insert(node->right, value);
}
else {
  node = make_unique<Node>(value);
}

Actually, that ternary can be narrowed to within the argument list (you can add more parens according to taste):

if (node) {
  Insert(value < node->value ? node->left : node->right, value);
}
else {
  node = make_unique<Node>(value);
}

On a related note, if we return early from within if, we can just flow into the next code without else:

if (not node) {
  return false;
}
else if (node->value == value) {
  return true;
}
else {
  return value < node->value
    ? Contains(node->left, value)
    : Contains(node->right, value);
}

That can become

if (not node) {
  return false;
}
if (node->value == value) {
  return true;
}

return Contains(value < node->value ? node->left : node->right, value);

We might be able to remove some repetition by adding a method to find the insertion point for a value - Contains() can return true if that insertion point has a value that compares equal, and Delete() can start from that point in removing the value.

If the tree could be large, then perhaps iteration may be better than recursion for walking the tree.  That means we'll need pointers in some places where we currently have references, and some things may have to lose const qualification, but may give a performance improvement and save on stack usage (or may not, depending on how your compiler manages to optimise the recursive call - always check these things!).

Further directions

Try to evolve the public interface to supporting standard container operations.  This probably begins with creating iterators and the member functions that return them.

Consider maintaining a balanced tree - you'll want to read up on the theory if you're not already familiar with the techniques to do this.

You haven't shown your unit tests here, but it's worthwhile occasionally running them with a memory checker such as Valgrind.  As well as ensuring we don't leak memory, that will also help identify any uses of dangling pointers or uninitialized values, which an ordinary run might not.


Python generator for "barely obtuse" triangles (Project Euler 224)

It seems like you want to find a solution for a²+b²=c²-1 with some added constraints, like a<=b<=c, a+b+c<=n, etc. by trying all possible combinations of a, b, and c and testing whether they satisfy all your conditions at once. This is pretty wasteful.

Instead of itertools.product, you can use a generator expression with three regular for loops. This has several advantages:

you could move some of the if clauses up after the first or second loop, i.e. you don't have to run the other loops if those conditions already fail at this point, e.g.

 for x in ... if test(x) for y in ... if test(y) ...

you can use the values of your previous variables in the lower and upper bounds for the later variables (in your case this replaces most of your if conditions)
you can basically calculate the value for c from a and b without testing all possible values

This is how I'd do it:

gen = ((a, b, int(c))
       for a in range(2, v_max_n + 1, 2)
       for b in range(a, min(v_max + 1, n - a - a), 2) # use a for lower and upper bounds
       for c in [(a ** 2 + b ** 2 + 1)**0.5]           # just a single candidate for c
       if  c % 1 == 0)                                 # whole-numbered c found?

Note that the calculation of c using very_large_number**0.5 might be imprecise with float; using decimal might work, though. However, even with those optimizations, testing much fewer values than your original loop (on the order of O(n²) instead of O(n³)), it might not be feasible to find solution for large values of a, b and c.

Also note that I did not thoroughly test this for off-by-one errors, since performance was the main concern.

Another thing that you might try: Invert the loops for a and for b, i.e. instead of testing all b for each a, no matter how large the difference, test all a up to b first. This does not decrease the number of combinations to test, but it seems to yield much more valid combinations in the "smaller" number much faster. Like this (upper bound for b can probably be reduced):

       for b in range(2, v_max + 1, 2)
       for a in range(2, b+1, 2)


If I understand the rules correctly, the last rule "Otherwise return the state of the most advanced non-ready module." isn't met by your method. Having states {ParserState.LoadingReference, ParserState.Parsed, ParserState.Parsing, ParserState.Ready} I would expect the returned state equals to ParserState.Parsed but your method results in ParserState.Parsing.
The rules 3 and 4 are superflous because they are satisfied by rule 1.
Because any error state takes precedence over every other state you should chewck this first. If all states are of the same error state it will result in the same result, but checking first the error states will be faster.
this

if (result == ParserState.Ready && moduleStates.Any(item => item != ParserState.Ready))
{
    result = moduleStates.Except(new[] {ParserState.Ready}).Max();
}

looks strange. result equals to the Min() of the modulStates, so let us assume it would equal to ParserState.Ready then it is garanteed that the second condition will result in true because you already checked if all states are the same.  Because of the the check of the same values the second condition of Debug.Assert(result != ParserState.Ready || moduleStates.All(item => item == ParserState.Ready)); is superflous as well.
You should use the same variables name for the same type when using lambdas. One time you have ps => ps == value and the other times you use ms => ms == ParserState.Error.
The method relies on a class variable which I would change. Add a parameter to that method declaration so it can stand on its own.

Implementing the mentioned points will lead to

private ParserState EvaluateParserState(IList<ParserState> moduleStates)
{
    // error state takes precedence over every other state
    if (moduleStates.Any(ms => ms == ParserState.Error))
    {
        Debug.WriteLine("ParserState evaluates to '{0}' (thread {1})", ParserState.Error,
        Thread.CurrentThread.ManagedThreadId);
        return ParserState.Error;
    }
    if (moduleStates.Any(ms => ms == ParserState.ResolverError))
    {
        Debug.WriteLine("ParserState evaluates to '{0}' (thread {1})", ParserState.ResolverError,
        Thread.CurrentThread.ManagedThreadId);
        return ParserState.ResolverError;
    }

    var state = States.SingleOrDefault(value => moduleStates.All(ms => ms == value));

    if (state != default(ParserState))
    {
        // if all modules are in the same state, we have our result.
        Debug.WriteLine("ParserState evaluates to '{0}' (thread {1})", state, Thread.CurrentThread.ManagedThreadId);
        return state;
    }

    var result = moduleStates.Except(new[] { ParserState.Ready }).Max();

    Debug.Assert(result != ParserState.Ready);

    Debug.WriteLine("ParserState evaluates to '{0}' (thread {1})", result,
    Thread.CurrentThread.ManagedThreadId);
    return result;
}


Finding consecutive primes matching p, p + 4, p + 6, p + 10, p + 12, p + 16

Overall, good first question!
The first obvious improvement is to factor out the code that generates the primes

def prime_sieve(n):
    grid = [None for _ in range(n+1)]
    i = 2
    while i < n+1:
        if grid[i] is None:
            grid[i] = True
            for p in range(i*i, n+1, i):
                grid[p] = False
        else:
            i += 1
    return (index for index, b in enumerate(grid) if b)

Note that for p in range(i*i, n+1, i): starts later than the for p in range(2*i, n+1, i): which you used. This is safe because anything less than the current prime squared will have already been crossed out. This difference alone makes the code about 2x faster for n = 4000000.

By separating the sieve, it makes things like profiling much easier, and you can see that most of the time this method takes is still in the sieve. Using some tricks from Find primes using Sieve of Eratosthenes with Python, we can focus our efforts on speeding this part up.

def prime_sieve(n):
    is_prime = [False] * 2 + [True] * (n - 1)
    for i in range(int(n**0.5 + 1.5)): # stop at ``sqrt(limit)``
        if is_prime[i]:
            is_prime[i*i::i] = [False] * ((n - i*i)//i + 1)
    return (i for i, prime in enumerate(is_prime) if prime)

This prime sieve works pretty similarly, but is shorter, and about 4x faster. If that isn't enough, numpy and https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n/3035188#3035188 can come to the rescue with this beauty which is another 12x faster.

import numpy
def prime_sieve(n):
    """ Input n>=6, Returns a array of primes, 2 <= p < n """
    sieve = numpy.ones(n//3 + (n%6==2), dtype=numpy.bool)
    for i in range(1,int(n**0.5)//3+1):
        if sieve[i]:
            k=3*i+1|1
            sieve[       k*k//3     ::2*k] = False
            sieve[k*(k-2*(i&1)+4)//3::2*k] = False
    return numpy.r_[2,3,((3*numpy.nonzero(sieve)[0][1:]+1)|1)]

At this point, further speedup would need to come from fancy number theory, but I'll leave that for someone else.


A program for fun to see how red and blue appears blended to purple due to resolution

I actually ran this. Good thing I don't have epilepsy, because wow. The flashing is intense.

There are many ways to improve this, depending on how technical you want to get. Move to a more advanced graphics library that's able to draw circles in an off-screen memory buffer before showing them in tkinter, your current windowing framework. This will speed up the rendering significantly and won't create that flashing (unless that's part of your art?).

There's a bug where moving your window creates even more flashing - this time, instead of being due to the concentric circles being rendered from the outside in, I suspect it's from the circles being re-rendered by graphics.py rather than flattening the representation of the image to a rasterized buffer. Rendering to an off-screen buffer will fix this, too.

There's another bug: closing the window produces this stack trace -

  File "/opt/pycharm-community-2019.2.1/helpers/pydev/pydevd.py", line 2060, in <module>
    main()
  File "/opt/pycharm-community-2019.2.1/helpers/pydev/pydevd.py", line 2054, in main
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/opt/pycharm-community-2019.2.1/helpers/pydev/pydevd.py", line 1405, in run
    return self._exec(is_module, entry_point_fn, module_name, file, globals, locals)
  File "/opt/pycharm-community-2019.2.1/helpers/pydev/pydevd.py", line 1412, in _exec
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/opt/pycharm-community-2019.2.1/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/home/gtoombs/PycharmProjects/zelles/zelles.py", line 25, in <module>
    win.getMouse() # Pause to view result
  File "/home/gtoombs/.virtualenvs/zelles/lib/python3.7/site-packages/graphics/__init__.py", line 316, in getMouse
    if self.isClosed(): raise GraphicsError("getMouse in closed window")
graphics.GraphicsError: getMouse in closed window

which means that you're not handling shut-down gracefully. See if you can change your exit condition to be either when the mouse event is received or the window is closed.


Convert IEnumerable to HTML table string

I can use reflection to solve it:

void Main()
{
    var datas = new[] { new {Name="Test1",Value="Test2"} };
    var array = datas.ToArray().ToHtmlTable(); //Run Success
    var set = datas.ToHashSet().ToHtmlTable();//Run Succes
    var list = datas.ToList().ToHtmlTable(); //Run Succes
    var enums = datas.AsEnumerable().ToHtmlTable(); //Run Succes
}

public static class HTMLTableHelper
{
    public static string ToHtmlTable<T>(this IEnumerable<T> enums)
    {
        var type = typeof(T);
        var props = type.GetProperties();
        var html = new StringBuilder("
");

        //Header
        html.Append("

");
        foreach (var p in props)
            html.Append("" + p.Name + "	");
        html.Append("

");

        //Body
        html.Append("
");
        foreach (var e in enums)
        {
            html.Append("
");
            props.Select(s => s.GetValue(e)).ToList().ForEach(p => {
                html.Append("" + p + "	");
            });
            html.Append("
");
        }

        html.Append("
");
        html.Append("
");
        return html.ToString();
    }
}

Name	Value

Test1	Test2


You don't need invalidchoice() as it just prints a statement and nothing else.  Just put the printf() under default.
Consider receiving all user input in main() and having the functions only do the calculations.  It's best to have a function do one (useful) thing.

In this form, the functions could also return the values to main() and displayed.  With the user input eliminated, they should now take the original temperature as an argument.
Optionally, you can return EXIT_SUCCESS or EXIT_FAILURE instead of 0 or 1, respectively.  It's especially important to return a failure value if the conversion was not successful.

You could then have something like this:

#include <stdio.h>
#include <stdlib.h>

double fahconv(double fah)
{
    return (fah - 32) * 5 / 9;
}

double celsconv(double cels)
{
    return (cels * 9 / 5) + 32;
}

int main()
{
    double originalTemp;
    double convertedTemp;
    char choice;

    scanf("%lf", originalTemp);

    puts("Enter (F or f) to convert from Fahrenheit to Celsius\n");
    puts("Enter (C or c) to convert from Celsius to Fahrenheit\n");
    scanf("%c", &choice);

    switch (choice)
    {
        case 'c':
        case 'C':
              convertedTemp = celsconv(originalTemp);
              printf("Converted temperature from F to C: %lf", convertedTemp);
              break;
        case 'f':
        case 'F':
              convertedTemp = fahconv(originalTemp);
              printf("Converted temperature from F to C: %lf", convertedTemp);
              break;
        default:
              printf("Invalid choice..exiting");
              return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}


Multithreaded number printer in ordered manner

Here are some things that may help you improve your program.
If it has private members, it should be a class
The OrderNumberPrinter struct really should be a class because it has private member data.  See C.8
Use std::size_t rather than int
The values m_len and m_current should both probably be std::size_t rather than int, not least because they are compared to num and initialized with list.size() which are both explicitly std::size_t.
Exercise all functions
There is no way that the destructor ever gets called in the current code because there is no exit condition in the code.  For that reason, how do you know if it works?  I'd ask that for an interview.  I'd also ask why w.joinable() is tested before calling w.join().  Is there a circumstance in which w.joinable() will return false?
Think about further derivation
What would happen if a user derived from this class?  I'd recommend either declaring the destructor as virtual or declaring the class final to prevent derivation.
Be clear about what each mutex is locking
The name m_printLock suggests that the shared resource being protected is std::cout.  If we used std::basic_osyncstream as suggested in a comment, would you still need a mutex?  If so, what would it then be locking?  Generally, I like to have each mutex just lock one thing because it simplifies maintenance and clarifies the intent to other programmers.


When I see this question, I immediately understand what you are trying to do as a bitwise rotation (also known as a circular shift). You need to either rotate the bits in the value left by 24 or right by 8 (they yield equivalent results). As the bits are shifted off one end, they're inserted back in the other end.

Ironically, this is one of those rare cases where the code is conceptually simpler in assembly language (!) than it is in C#. The x86 processor family has two very simple instructions that accomplish precisely this feat—ROL and ROR—which rotate left and right, respectively. That means the code in assembly language is almost as simple as:

rol  value, 24

Whereas it is actually more work—and less obvious what is being done—when writing the code in C or C#. You have to explicitly notate both parts of the circular shift. The canonical form is:

public static UInt32 RotateLeft(UInt32 value, UInt32 amount)
{
    Debug.Assert(amount < 32, "Attempted to rotate by more bits than are in the value.");
    return (value << amount) | (value >> (32 - amount));
}

public static UInt32 RotateRight(UInt32 value, UInt32 amount)
{
    Debug.Assert(amount < 32, "Attempted to rotate by more bits than are in the value.");
    return (value >> amount) | (value << (32 - amount));
}

Note that I've explicitly used the UInt32 type here, instead of the short name uint. This is because I've hard-coded assumptions about the type's width, and I like things to be obvious. UInt32 is obviously always a 32-bit type. At least for me, since I bounce back and forth between languages, that's not always so obvious with uint.

I've also thrown in an assertion to check that we're rotating by a reasonable amount. That's just an assertion, though, not an exception, because the C# language standard guarantees that the shift amount will be masked, such that only the lower 5 bits will be used (resulting in a value from 0 to 31). This means that the language protects you from the undefined behavior you would get in C by trying to shift by too many places. (Again, ironically, so does x86 assembly language.)

So this is basically the generalized form of the code that you have. A call like:

argb = RotateLeft(rgba, 24);

would essentially inline to:

argb = (rgba << 24) | (rgba >> 8);

There is one major difference, though. I've written the code to work with unsigned types, rather than signed types. In fact, bitwise operations should always be done on unsigned types because when you do bitwise operations, you are essentially treating the value as a field of bits, rather than as a number. Using an unsigned type is not only conceptually more correct, but also saves you from bugs.

C# automatically differentiates between signed and unsigned shifts (based on the type of the value you're shifting), which is why you found that your code needed that extra mask. The result was being padded with the most significant bit of the number being shifted because that's how a signed shift works—in effect, it does a signed extension, where the sign bit (the most significant bit) is repeated to preserve the sign of the value. (Note that this distinction is only relevant for right shifts; signed and unsigned left shifts are exactly the same.)

But that's something you don't want to have to think about, and something that you wouldn't have to think about if you just follow the rule that bitwise operations imply unsigned types.

So the correct code is precisely what pgs already suggested:

public static UInt32 ToARGB(UInt32 rgba)
{
    return (rgba << (3*8)) | (rgba >> 8);
}

But you might also want to consider Eric Lippert's advice about logical representations. It is merely an implementation detail that these color values are stored as unsigned 32-bit integers. Therefore, it would make sense to wrap that implementation detail up inside of a structure, so that the client never has to deal with the messiness.

Unfortunately, the C# JIT compiler doesn't seem to be able to produce as efficient of code here as a C compiler would. In C or C++, your function would be transformed directly into that assembly-language instruction I mentioned above. In C#, you get 4 instructions instead of that one:

mov  ecx, eax    // make extra copy of value
shl  ecx, 8      // shift that copy left by 8
shr  eax, 24     // shift original right by 24
or   eax, ecx    // combine the two

Oh well. That's still as efficient as you're going to get.


It seems that you are storing the data with double links (article -> category AND category -> articles).

I assume that you need to report on articles for a category.  I would simple create an index on Category like this:

var articleSchema = mongoose.Schema({
    category: { type: mongoose.Schema.Types.ObjectId, ref: 'Category', index: true },
    title: String
});

This way you can simplify your code a ton by keeping it KISS:

function seedArticle(categoryTitle, articleTitle) {
  CategoryModel.findOne({ title: categoryTitle }).exec()
    .then(function (category) {
      return ArticleModel.create({ title: articleTitle, category: category._id });
    });
}

Other than that, I like your code.


First of all, this should be obvious, but when you have performance issues in code that involves a tight inner loop, you want to simplify that loop as much as you can.  If you can save one cycle in the loop by spending a dozen or a hundred cycles somewhere else, do it, because every cycle in the loop gets multiplied by 5000².

Also, what you really want to minimize in the inner loop are memory accesses.  Accessing local variables is fast, since they're typically cached and the JVM knows that their values cannot change unless the code in the method itself changes them.  In comparison, pulling a random element from a large array is relatively slow, since it requires a full RAM access, as is, typically, accessing a member variable or calling an uncached method.

I've done something like this before,* so, rather than listing every improvement I might make to your code, let me start by sketching how I might rewrite your core update loop:

// assume these arrays are (height + 2) by (width + 2)
boolean[][] oldBuffer = universeDoubleBuffer[flipFlopIndex],
            newBuffer = universeDoubleBuffer[newFlipFlopIndex];

for (int y = 1; y <= height; y++) {
    int environment
        = (oldBuffer[y-1][0] ? 32 : 0) + (oldBuffer[y-1][1] ?  4 : 0)
        + (oldBuffer[y  ][0] ? 16 : 0) + (oldBuffer[y  ][1] ?  2 : 0)
        + (oldBuffer[y+1][0] ?  8 : 0) + (oldBuffer[y+1][1] ?  1 : 0);

    for (int x = 1; x <= width; x++) {
        environment = ((environment % 64) * 8)
            + (oldBuffer[y-1][x+1] ? 4 : 0)
            + (oldBuffer[y  ][x+1] ? 2 : 0)
            + (oldBuffer[y+1][x+1] ? 1 : 0);

        newBuffer[y][x] = lookupTable[ environment ];
    }
}

A few things to note about this code:

There is no countLiveNeightbors() method; in fact, the code does not explicitly count live neighbors at all.  Instead, the pattern of the nine cells including and surrounding the cell at (x, y) is maintained in the variable environment, which is used as an index to a 512-element lookup table.

For example, if the surroundings of the current cell look like this (# = live cell, _ = dead cell):

# # _
_ # #
# _ _

then the value of the environment variable will be:

(1 * 256) + (1 * 32) + (0 * 4) +
(0 * 128) + (1 * 16) + (1 * 2) +
(1 *  64) + (0 *  8) + (0 * 1) = 370

Of course, you'll have to set up this lookup table before using it, but that is something you can do outside the core loop (e.g. in your constructor), so it's not performance-critical.

(In fact, while I haven't benchmarked this, I'd at least consider making lookupTable a local variable and rebuilding it every time the update method is called, as the extra cost of rebuilding the table might be balanced out by extra optimization opportunities available to the compiler / JVM if it knows that no other code can modify the table.  You may want to test it both ways and see which one is faster.)

One additional advantage of such a lookup table based implementation is that, by changing the lookup table, it can simulate any two-state cellular automaton using the Moore neighborhood, not just Conway's Game of Life specifically.
By reusing the parts of the environment pattern that are shared between adjacent cells, the code only needs to do three reads from the oldBuffer array per cell, as opposed to nine in your version.  Uncached array access is expensive, so this is likely to provide a significant speedup.  (Also, like your code, mine also makes sure to access the buffers as close to sequentially as possible, iterating first by rows and then by columns.  This is also important for CPU cache locality.)
The code above doesn't update the cells at the edges of the array, which means it doesn't have to worry about (literal) edge cases such as array indices being out of bounds.  (Hopefully, the compiler / JVM may notice this too, and may omit some of its internal array bounds checks.)

If you want your grid to be surrounded by dead cells, you can just initially mark these border cells as dead and leave them untouched in your update method.  Alternatively, if, say, you want the grid to wrap around, you can update the edge cells in a separate loop (which can be less efficient, since it only runs for a tiny fraction of all the cells).

Actually, there are a few ways in which the code I suggested above could be optimized further.  For example, an obvious optimization is to get rid of the two-dimensional array accesses in the inner loop, since they require two array lookups each.

There are (at least) two ways you could do this:

a) In the outer loop, save the previous, current, and next rows of oldBuffer in local variables, like this:

boolean[] prevRow = oldBuffer[y-1],
          currRow = oldBuffer[y],
          nextRow = oldBuffer[y+1];

b) Make the buffers themselves one-dimensional arrays, and adjust the indexing so that, instead of buffer[y][x], you use buffer[ y * (width+2) + x ].  You can precalculate the offset y * (width+2), and possibly also (y ± 1) * (width+2), in the outer loop to save a bit of arithmetic, or you could rely on the compiler / JVM to do this for you.  Again, you could try it both ways and see if there's any difference.

Also, for cellular automata like the Game of Life, where only a small fraction of the cells typically change in each time step, there are much faster algorithms available than even the generic table lookup method described above.

As a first step, ChrisW's suggestion of caching the live neighbor count is likely to be faster whenever the environment of each cell changes relatively infrequently.
An even greater speedup may be obtained by storing a list of active cells, i.e. cells that changed or had at least one of their neighbors change state during the previous update step, and only iterating through those cells on the next update.  (Since the total number of active cells is bounded above by the size of the grid, you can use a simple array as a circular buffer to efficiently store this list.)

Effectively combining active cell lists with double buffering can be somewhat tricky.  An alternative solution is to use a single buffer, but divide your update method into two phases:

In the first phase, you iterate through the list, calculate the new state for each active cell, and store it in the list.
In the second phase, you iterate through the list again and update the grid buffer to match the new states calculated in the first phase.

(That said, using both activity lists and double buffering does have one advantage: it allows you to treat cells that oscillate with a period of two, which are quite common in the Game of Life, as inactive.  This does require you to maintain separate active cell lists for each buffer.)
Finally, if you want a really fast algorithm for simulating Conway's Game of Life, look up Hashlife.  It's literally orders of magnitude faster than any "naïve" simulation algorithm, especially for sparse and highly repetitive patterns like many constructed ones.

*) Please don't take that code as an example of good coding style.  It is pretty fast, though.

Addendum: Here's a basic implementation of the activity list method, using a single buffer, and with the Conway's Game of Life rules hardcoded.

It uses a byte-packed cell state buffer, where the lowest bit of the byte indicates whether the cell is currently in the activity list, the second bit stores the actual state of the cell, and the following (four) bits store the number of surrounding live cells (to avoid having to recalculate it whenever the cell is examined):

// assume that buffer is a (height) by (width) byte array, and that
// xQueue and yQueue are (height * width) int arrays, of which the
// first (activeCells) elements contain the current active cell coords

// loop over active cells, and find those whose state will change
int changedCells = 0;
for (int i = 0; i < activeCells; i++) {
    int x = xQueue[i], y = yQueue[i];
    byte packedState = buffer[y][x];  // = 4*neighbors + 2*state + active
    boolean wasAlive = (oldState & 2 == 2);

    // quickly check if cell will live under the Game of Life rules
    // (10-11 = alive, 2 neighbors; 12-13 = dead, 3 neighbors; 14-15 = alive, 3 neighbors)
    boolean isAlive = (10 <= packedState && packedState <= 15);

    // add cell to queue if it died or was born
    // we know that changedCells <= i, so it's safe to reuse the same queue space
    if (wasAlive != isAlive) {
        xQueue[changedCells] = x;
        yQueue[changedCells] = y;
        changedCells++;
        // assume active bit is already 1, so no need to change
    }
    else {
        buffer[y][x] = packedState - (byte)1;  // unset active bit
    }
}

// carry out deferred state updates
activeCells = changedCells;
for (int i = 0; i < changedCells; i++) {
    int x = xQueue[i], y = yQueue[i];
    boolean wasAlive = (buffer[y][x] & 2 == 2);
    byte delta = (byte)(wasAlive ? -4 : +4);  // change in neighbor count * 4

    // update neighbor counts of adjacent cells, and mark them as active
    int yMin = (y > 0 ? y-1 : 0), yMax = (y < height-1 ? y+1 : height-1);
    int xMin = (x > 0 ? x-1 : 0), xMax = (x < width-1 ? x+1 : width-1);
    for (int ny = yMin; ny <= yMax; ny++) {
        for (int nx = xMin; nx <= xMax; nx++) {
            byte newState = buffer[ny][nx] + delta;
            // if this cell is not yet active, add it to the queue for next time step
            if (newState & 1 == 0) {
                xQueue[activeCells] = nx;
                yQueue[activeCells] = ny;
                activeCells++;
                newState += (byte)1;
            }
            buffer[ny][nx] = newState;
        }
    }
    // the middle cell only needs to adjusted by +/-2
    buffer[y][x] -= (byte)(delta / 2);
}

Before the first pass, all cells should be initialized to have the correct neighbor counts, have the active bit set and be added to the active cell queue.  I've omitted this part of the code, since it's not performance-critical.

Note that this method does not use any padding cells along the edges of the state array.  Alternatively, we could add the padding and permanently set the active bit for those cells, but not include them in the queue, allowing the min/max coords calculations to be simplified.  I suspect this would not make much difference, but there's no way to be sure without trying it.


An array is perfectly fine, it's what I'd prefer as well. But there are some improvements you can make:

When you have an array and you want to create a new array by transforming every item of an old array, it's most appropriate to use Array#map:
// I'd call it `filenames` and `audios`, not `sources` and `sounds`;
// `audios` is plural of Audio and is a bit more precise
const audios = filenames.map(filename => new Audio(filename));

If your sound files are really numeric-indexed, it would be even easier to just iterate over the numbers 1 to 4, rather than having to list sound1.ogg, sound2.ogg, etc.

Always declare variables with const when possible - only use let when you must reassign the variable name. Using const makes code easier to read, when a reader can determine that the variable name won't ever be reassigned at a glance.

At the moment, if playRandomSound is called multiple times in a row, multiple sounds may be active at once, which may sound very discordant and not be desirable. In such a case, you may wish to save the randomNumber in a persistent outer variable so that you can call .stop() on the prior Audio before .play()ing another. (Or, if you want to have playing sounds overlap, your current approach is just fine)

If your sources array's length changes, you'll also need to change this section: Math.floor(Math.random() * 6); Better to put the array's length there instead of the 6.

const audios = Array.from(
  { length: 6 },
  (_, i) => new Audio(`sound${i + 1}.ogg`)
);
function playRandomSound() {
    const randomNumber = Math.floor(Math.random() * audios.length);
    sounds[randomNumber].play();
}


Fading in while scrolling - is this an elegant solution?

The onScroll event is generally very performance hungry, since it is called quite often, while scrolling. Looping through all "ajax_block_product" elements on every singel call, even if most of them might be outside of the viewport, makes it even worse. But you can use some specialities of JS to optimize it. As a short intro: In JS you can set an array element at a defined index, leaving the ones in between undefined while having the length of the array set to the highest index defined.

a[100] = 'one';
a[1000] = 'two';
for (var i = 0; i < a.length; i++) {
    console.log('iterate'); // called 1000 times
}
for (var elm in a) {
    console.log('iterate'); // called two times
}

Now if you loop through the array with a typical for(var i = 0; i < a.length; i++) you will have 1000 iterations BUT since an array is also an object in JS a for(elm in a) would only iterate 2 times. We can now use this to store all Y-positions of "ajax_block_product" elements as indexes of an array, than determine the dimension of the current viewport and cut out only those element who are inside that range.

$(document).ready(function () {
    var tiles = $('.ajax_block_product'),
        winHeight = $(window).height(),
        posArr = [];

    tiles.each(function () {
        var pos = $(this).offset().top;
        posArr[pos] = $(this);
    });

    $(window).scroll((function fadeIn() {
        var sTop = $(window).scrollTop(),
            range = posArr.slice(sTop, sTop + winHeight);
        range.forEach(function (elm) {
            elm.css('opacity', 1);
        });
        return fadeIn;
    }()));
});

In this example I've used CSS3: transition: opacity .5s ease-in; for the fade in. You need to check out how to do this with jQuery's fadeIn, if needed...

Last but not least, the onScroll event callback is somehow special. It a self-executing, self-referencing function. It is called once, when it's defined, to initially show all elements already in the viewport and then returns a reference to itself for later onScroll event calls.

Hope this could help you, even if it's some time ago, you asked this question...


Search for the biggest amplitude in an array

Some key points:

No need to sort the array to find min/max value
No need to copy the array, can search in the original array using an offset count * N

Have a look at this:

public String solution(int[] T) {
    final int count = T.length / 4;
    int indx = 0;
    int last = Integer.MIN_VALUE;
    for (int i = 0; i < 4; ++i) {
        int diff = IntStream.of(T).skip(count * i).limit(count).max().getAsInt()
                 - IntStream.of(T).skip(count * i).limit(count).min().getAsInt();
        if (diff > last) {
            indx = i;
            last = diff;
        }
    }
    final String[] seasons = { "WINTER", "SPRING", "SUMMER", "AUTUMN" };
    return seasons[indx];
}


A double search function that looks in a list for one value and then the other alternatively

Python has this wonderful module called itertools. Whenever you need to iterate over some data in a specific way, check if there isn't a function or recipe that could help you.

For this problem, I’m thinking about itertools.cycle: being an iterator, you can easily call next on it whenever you need to grab the "other" value. e.g.:

input_list = [1, 2, 3, 2, 4, 2, 3]
values = itertools.cycle(('First', 'Second'))
for element input_list:
    if element == 2:
        print(next(values))
    else:
        print('None')

will print:

None
First
None
Second
None
First
None

So you can easily compare elements to the current condition.

The only thing missing, then, is associating the value to store in the output list to the condition to check. You have two choices: either you use zip with a second itertools.cycle, or you use a single itertools.cycle but you define it with a couple of couples like so: itertools.cycle(((cond1, 'First'), (cond2, 'Second'))). I’ll go with the former as I feel it is cleaner, but both are equally valid:

import itertools

def double_search(iterable, condition1, condition2):
    output = []
    conditions = itertools.cycle((condition1, condition2))
    results = itertools.cycle(('First', 'Second'))
    iterator = zip(conditions, results)

    # Initialize the current value to search for
    condition, value = next(iterator)

    for element in iterable:
        if element == condition:
            output.append(value)
            condition, value = next(iterator)
        else:
            output.append('None')
    return output

It is however considered bad practice to use the pattern empty list + append in a loop. But the use of next makes it hard to use a list-comprehension instead.

You can, however, turn your function into a generator instead

import itertools

def double_search(iterable, condition1, condition2):
    conditions = itertools.cycle((condition1, condition2))
    results = itertools.cycle(('First', 'Second'))
    iterator = zip(conditions, results)

    # Initialize the current value to search for
    condition, value = next(iterator)

    for element in iterable:
        if element == condition:
            yield value
            condition, value = next(iterator)
        else:
            yield 'None'

and call it like:

input_list = list(range(5))
result = list(double_search(input_list, 2, 3))


use Identity value in entity after insert in Database

I would suggest you change your database design.

Option 1)

Have SQL Server set a column to the current date/time when you insert a row  See https://stackoverflow.com/q/6594589 for how to do it.  Then have that column mapped on your Tracking entity but mark the property as [DatabaseGenerated(DatabaseGeneratedOption.Computed)]

Assuming you call the field AddDate

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public datetime AddDate {get;set;}

Now you can create your get only TrackingCode property in code and use the [NotMapped] on it and define it as

[NotMapped]
public int TrackingCode
{
     get { return Convert.ToInt32(AddDate.ToString("yyyyMMdd") + tracking;
}

Option 2:

Create an after insert tigger and have SQL Server update the TrackingCode.  Again I would mark the property as DatabaseGenerated

In a nut shell it's better to offload this to the SQL Server


Authorization checks for editing attributes of a task

Just like you say, you are hiding dependencies if you have new or call a non-pure function with the x::y($z) syntax.

One way to go around this, is to acknowledge the dependency and take it as a constructor argument, so that the current object doesn't care where it gets its user from, but it knows that it can call isCreator() or such. Some would advice you to take dependencies through setUser(User $u)-like methods, but that would make the object useless between its constructor is called, and until the setUser() method is called, because getEditableStateForMessage() and friends will fail in the meantime.

You should consider attacking problems like this from a TDD point of view: how do I test the current code without having to resort to real data?


Avoid unnecessary math

        for (long i = 0; i < entry.getValue() + 1; i++) {

As you noted in your comment, this should start at 1.

        for (long i = 1; i < entry.getValue() + 1; i++) {

But we can also simplify the end.

        for (int i = 1; i <= entry.getValue(); i++) {

We want to process entry.getValue() and then stop, so do that.  No need to determine the next place where we don't want to be.  The other way works, but this is easier to read.

We also don't need to use long here.  Because Java arrays can't be indexed past the range of an int, we can be sure that none of the counts will exceed the capacity of an int.  Of course, if we change to int here, we should change everywhere else as well.

Use a helper

    consecutiveCharacterCounts.put(startingCharacter, consecutiveCharacterCount);

    for (int i = 1; i < chars.length; i++) {
      char currentCharacter = chars[i];

      if (currentCharacter == startingCharacter) {
        consecutiveCharacterCount++;
      }

      if (currentCharacter != startingCharacter || i == chars.length - 1) {
        Long characterCount = consecutiveCharacterCounts.get(startingCharacter);
        if (characterCount == null || consecutiveCharacterCount > characterCount) {
          consecutiveCharacterCounts.put(startingCharacter, consecutiveCharacterCount);
        }
      }

      // Doing this logical check twice feels weird
      if (currentCharacter != startingCharacter) {
        startingCharacter = currentCharacter;
        consecutiveCharacterCount = 1;
        Long characterCount = consecutiveCharacterCounts.get(startingCharacter);
        if (characterCount == null || consecutiveCharacterCount > characterCount) {
          consecutiveCharacterCounts.put(startingCharacter, consecutiveCharacterCount);
        }
      }
    }

You can simplify this with a helper method:

public static void update(Map<Character, Long> counts, char c, int count) {
    Long oldCount = counts.get(c);
    if (oldCount == null || count > oldCount) {
        counts.put(c, count);
    }
}

Then we can change the bounds of the for loop.

    for (int i = 1, n = chars.length - 1; i < n; i++) {
      if (chars[i] == startingCharacter) {
        consecutiveCharacterCount++;
        continue;
      }

      update(consecutiveCharacterCounts, startingCharacter, consecutiveCharacterCount);
      startingCharacter = chars[i];
      consecutiveCharacterCount = 1;
    }

    if (chars[chars.length - 1] == startingCharacter) {
      consecutiveCharacterCount++;
    } else {
      update(consecutiveCharacterCounts, startingCharacter, consecutiveCharacterCount);
      consecutiveCharacterCount = 1;
    }

    update(consecutiveCharacterCounts, chars[chars.length - 1], consecutiveCharacterCount);

Now we do one fewer iteration and on exiting the loop we do different processing.  This saves us having to do the extra check on every iteration of the loop.

Now we don't have to compare currentCharacter and startingCharacter three times.  Once is enough.

Using the continue saves us a level of indent over using an else.

We don't need to update the Map for the first one of each letter.  The logic works without that.


Displaying styled validation messages to user

Why wait until the data has gone to the server before you inform the user that their name is empty?  You should be doing any processing up front that you can for performance reasons (though you'll still need to do validating from the server side for security reasons).  I recommend the addition of the required attribute:

<input type="text" name="first_name" required />

You can even use CSS to inform the user that the field contains invalid data.

input:invalid {
    border: 1px solid red;
}

Learn more: http://www.html5rocks.com/en/tutorials/forms/html5forms/