There are some formatting and code clarity points I will mention a bit further down, but for now there are some places I think the performance could be improved, at a glance. You should definitively consider posting your EXPLAIN and table definitions, as was suggested in a comment, for this and future SQL questions, as those can make a huge difference, often more so than the queries themselves.

Bottlenecks

This JOIN is perplexing:

FROM documents AS d
    LEFT JOIN inventory AS i
        ON (CASE
            WHEN d.document_type = 'Invoice'
                THEN i.skunumber = d.skunumber
            WHEN d.document_type = 'Purchase Order'
                THEN i.originalskunumber = d.skunumber
        END)

There is a fundamental problem if you are using a case expression like this as a joining condition. Why are your Invoice and Purchase Order documents not normalized into their own tables? I would suggest to take another look at the architecture there, especially if you find yourself having to do this kind of join often.
Parsing strings in SQL is expensive. At the very least, I hope your document_type column is indexed. If it isn't, then that's a choke point, because it has to scan the documents table (instead of an index) just to be able to join. If you find yourself making joins on non-index columns more than just very seldom, you need to look to do some serious indexing, and consider normalizing.
You are using a LEFT JOIN so I am assuming you are expecting null values... but the way you wrote the expression does not make that clear. Consider at the very least adding a comment to explain where you are expecting nulls and how it handles it.

I had to notice further down what the left join is actually for, with this bit...

WHEN d.document_type = 'Invoice' AND d.skunumber IS NOT NULL

How many other kinds of documents are stored like this? I see at least one more, Quote. Good question to ask yourself, I think. It's much easier to re-architect databases earlier on, if you have that luxury, than after you've written all your application around a sub-par architecture.

This is a bit weird:

WHERE d.document_type <> 'Quote'
    AND d.header_item = '0'
    AND d.active_document = '1'
    AND d.active_item = '1'

What are those '0' and '1'supposed to mean? Why are they characters instead of say, a BIT if they are meant to be true/false, or a TINYINT or INT if that is just a key that represents some value?

This part (and the 2 after it) in your where clause is formatted in such a way that as a one-liner you don't really see what is going on. Once you format it like the rest of your query is, it becomes clear that it's a very inefficient operation:

WHERE ...
...
AND (CASE
    WHEN d.document_type = 'Invoice' AND d.skunumber IS NOT NULL
        THEN (d.document_id, LEFT(d.skunumber, 3)) NOT IN (
            SELECT
                trailing_doc,
                LPAD(vendor_code, 3, '0') AS vendor_code
            FROM documents
            WHERE active_document = '1'
                AND active_item = '1'
                AND trailing_doc IS NOT NULL
                AND vendor_code IS NOT NULL
        )
    WHEN d.document_type = 'Purchase Order'
        THEN 1
    ELSE 1
END)

Wow, this is complex.

This condition is redundant: WHEN d.document_type = 'Purchase Order' THEN 1 ELSE 1. If a value doesn't fall in your first case, it will be 1 either way, so just keep the ELSE 1 by itself.
Again, I hope this document_type column is indexed, otherwise here we go again parsing those strings!
Now at first glance, this subquery seems really odd. You are verifying that your document_id (primary key, I'm assuming) is not contained in trailing_doc column (why?) and, perhaps even more strangely to an outsider, that the left-most 3 characters of your skunumber (why is it called a number if it has characters?) are not the same as the vendor_code padded to 3 characters with 0s to the left. So presumably, a skunumber could look something like 011999999 where 011 is the vendor code, and 999999 is the actual unit number. Did I guess right? That, to me, would be deserving of at the very least a small explanation as code comment, so the next maintainer doesn't have to do this kind of mental gymnastics as well.
Again, if performance is a concern, I really hope you have indexes on skunumber, vendor_code and trailing_doc. If you don't, then there's another bottleneck.

All the same points apply on your other subqueries to payments table. (except maybe point 3 that's pretty specific to this one).

Split into multiple, more specialized queries?

Consider splitting this logic into at least 2 queries, one for invoices and one for purchase orders, since they are really not the same thing. If need be, you could always bring them together using UNION, or combine them some other way (maybe in your application?), or altogether just keep them separated.

Code style

A few things:

All those back-ticks are really distracting, and really not needed. I realize they are added there by a PHP tool, but a quick find & delete in a text editor, or using a regex, is all that's needed to remove them.
Some line breaks make the first part of a SELECT easier to read, like

SELECT
    u.first,
    u.last,
    i.id,
    IFNULL(i.vendor, d.unattached_vendor) AS vendor,
    IFNULL(i.originalskunumber, d.skunumber) AS skunumber,
    ....
It's tempting to use 1-letter aliases for tables, but in bigger queries it can make things very hard to follow, once you start joining in 6, 9, 12 tables, to keep track of all those d, u and i names. Naming things is hard, but reading unclear code is harder.

I made a pastebin of how I reformatted your query here.


C++ is statically typed programming language. Due to this overhead for allocation of class members is very small.
Using of global variables is not a good idea. Such vars like NUM_NPC makes your application non-scalable.
Each domain object (like a player or an item) must be described by a same-named class.

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

typedef int Hearts;
typedef bool Gender;

struct Date
{
      Date(int month,int day) : month(month), day(day) {}
      int month;
      int day;
};

class Item
{
    // TODO: implement
};

class Player
{
public:
      Player(std::string name, Hearts hearts, Date birthday, Gender gender)
            : name(name), hearts(hearts), birthday(birthday), gender(gender) {}

      Hearts getHearts() const
      {
            return hearts;
      }

      const std::vector<Item>& getItems()
      {
            return items;
      }

      Date getBirthday() const
      {
            return birthday;
      }

      std::string getName() const
      {
            return name;
      }
private:
      std::vector<Item> items;
      Hearts hearts;
      Date birthday;
      std::string name;
      Gender gender;
};

int main()
{
      using namespace std;

      vector<Player> players;
      players.push_back(Player("Ace", 0, Date(3,5), 0));
      players.push_back(Player("Amber", 0, Date(9,20), 1));
      players.push_back(Player("Benny", 0, Date(1,10), 0));
      players.push_back(Player("Ethan", 0, Date(12,30), 0));

      Player& p = players[1];
      cout << "Player 1 Details:" << endl;
      cout << "Name: " << p.getName() << endl;
      cout << "Hearts: " << p.getHearts() << endl;
      cout << "Birthday: " << p.getBirthday().month << "/" << p.getBirthday().day << endl;
      cout << "Item count: " << p.getItems().size() << endl;
}


Inserting a node to a given position in a linked list

I see a lot of checks here, how can I reduce those and make my code more readable and covering all the edge cases?

Using a dummy node that points to the head can help reduce many of the checks:

Node insertNth(Node head, int data, int position) {
    Node dummy = new Node();
    dummy.next = head;

    Node runner = dummy;
    for (int i = 0; i < position; ++i) {
        runner = runner.next;
    }

    Node node = new Node();
    node.data = data;
    node.next = runner.next;
    runner.next = node;

    return dummy.next;
}

  Also, is there any recursive version possible for the given code because list is a recursive data structure hence, there should be some recursive way, right?

Naturally, a recursive solution is also possible:

Node insertNthRecursive(Node head, int data, int position) {
    if (position == 0) {
        Node node = new Node();
        node.data = data;
        node.next = head;
        return node;
    }
    head.next = insertNthRecursive(head.next, data, position - 1);
    return head;
}

Update

As @PeterCordes pointed out, the above implementation is a bit dirty,
as it rewrites the links unnecessarily.
Here's a variant replacing the head.next = ... line above to make it cleaner.

    Node next = insertNthRecursive(head.next, data, position - 1);
    if (position == 1) {
        head.next = next;
    }

Input validation

I intentionally omitted input validation from these example implementations:
they won't work with position values outside the range \$[0, n]\$.
I leave that fun up to you.


Invert-range operation in a circular vector

Bug

Your previous() function doesn't wrap around well:

int previous(const int i) {
    return (i - 1) % vec.size();
}

When i reaches 0, this function will return -1, not vec.size() - 1 as you might be expecting.  You could either go with:

int previous(const int i) {
    return (i - 1 + vec.size()) % vec.size();
}

or perhaps:

int previous(const int i) {
    if (i == 0)
        return vec.size() - 1;
    return i - 1;
}

Unnecessary use of float

The Floating Point Police™ disapprove of your unnecessary use of floating point here:

if(j < i ){
    segment_size = std::ceil(((vec.size() - i) + j) / 2.0);
} else {
    segment_size = std::ceil(std::abs(j - i) / 2.0);
}

All you are doing is rounding up, so you could just do:

if(j < i ){
    segment_size = (vec.size() - i) + j;
} else {
    segment_size = j - i;
}
segment_size = (segment_size + 1) / 2;

Technically, there could be a problem with the above if your segment size can be INT_MAX.  If this is possible, then replace that last line with this instead:

segment_size = (segment_size / 2) + (segment_size & 1);

But if your segment size could be INT_MAX, then your next() function would need to be fixed as well.


Removing characters from end of string from character to character

You could simply take advantage of the string.LastIndexOf() method together with the string.Substring() method like so

private static string Clean(string value)
{
    return value.EndsWith(")") ? value.Substring(0, value.LastIndexOf('(')).TrimEnd() : value;
}

and use it like so

foreach(var i in methodResponse.Response.Data.Results.Where(x => x.CategoryFriendlyName == platform))
{
    i.BoxName = Clean(i.BoxName);
}

Some side notes about the posted code:

Don't use abbreviations when naming stuff e.g var arr
You shouldn't check like while(exit != true) but rather like so while(!exit)


Searching has_and_belongs_to_many relations for article categories

Generally you'll want to make sure this always gets passed an array so I'd choose to set the argument to an empty array rather than nil. Since in the successful case the method receives an array, you should treat it as such. If you ever expect to get a nil passed in (like you might from params), you can also catch if it is blank or empty to handle all cases safely.

If you get rid of the ternary, you can simply put a guard as the first line and that clarifies the method a lot more. You'll see the use of guards throughout the Rails source itself.

def self.in_categories(category_ids=[])
  return all if category_ids.blank? || category_ids.empty?
  includes(:categories).where(categories: { id: category_ids })
end

Alternatively you could always cast the parameter to an array and only handle that case.

def self.in_categories(category_ids=nil)
  category_ids = category_ids.to_a
  return all if category_ids.empty?
  includes(:categories).where(categories: { id: category_ids })
end

I've run into this "undocumented feature" on several occasions with Rails and it trips me up every time. Hopefully someone has a better solution so that Rails, but it is also good to just be explicit on the results if you can't consolidate.

Looks like there are quite a few discussions about this https://github.com/rails/arel/pull/245


More efficient way to make a Twitter status in a string of just words

(subject to further changes)

In your simple example, how are the hashtags and usernames actually derived from the tweet?

My suggestion is to tokenize the tweet by whitespaces first, then look at the individual words to determine if they must be stored ("Vote") or discarded ("#LittleMonsters").

    // Delete all RT (retweets flags)
    text = text.replaceAll("RT", "");

You do realize that this will turn text like "ART!" into just "A!" right? Tokenizing first should remedy this issue.

On a related note, Apache Incubator Storm's tutorials usually use tweets as an example to demonstrate the Big Data approach. I'm not suggesting that you need such a set-up in your context, but perhaps you can give those a quick read-through to pick up some tips.


Sum of all multiples of 3 or 5 below 1000 (Project Euler #1 - typical)

Minor

Paren placement

Hanging parens are an eyesore.

Global var

Use defvar instead of setq to create global variables.

Sharp-quote for functions

You should do (apply #'+ ...) instead of (apply '+ ...).

Unnecessary allocation

Since your range returns a fresh list, you can use nunion instead of union.

Major

Sum

Your sum function is broken - it will not work on long lists, see CALL-ARGUMENTS-LIMIT.

Here are better ways to do this:

(defun sum (list)
  (reduce #'+ list))

(defun sum (list)
  (loop for x in list sum x))

Performance

union is probably quadratic in your implementation, so you might want to consider another approach for larger values of 1000 :-)


How to remove redundancy in code when alternating between methods?

Rethink your function

Instead of using if statements you can store the points in an array and then the current player variable could be an index for the array (so not a string value, use and integer instead).

Try to think in numbers instead of strings.

Code example:

int[2] pointsArray;
int currentPlayer = 0;
pointsArray[currentPlayer] = roolDiceFunction();

If you really want to use strings though you could use a map but I think it will just make your code more complicated.

Coin:

Just do the coin check at the start of your function by setting the start index for current player. For example if you want the user to start if the coin lands on heads which you can represent as 0, you then just set the current player index to a random value between 0 & 1.

Example:

int[2] pointsArray;
int currentPlayer = (int)Math.random(); //Random value between 0 & 1
pointsArray[currentPlayer] = roolDiceFunction();

I'm guessing there's more to your function than this, but you probably want to have it in a loop of some kind and then ask at the end of the function if the user wants to keep rolling, if they don't want to keep rolling you can change the current player index.

More about your functions

Make the rool2Dice function simpler, does it really need that many parameters, you are passing the exact same most of the time.

If you have any more questions just ask away, good luck.


I'm not familiar with that framework, but if there is more than one school and you are going to use Python to access those values (such as the school's address), I'd use a class. Think of it this way: Classes are usually meant to be instantiated, or at least to be a group of functions for a specific purpose.

Instead of creating a dict for each school you simply instantiate the class:

MIT=School(1,'Cambridge','university')
Harvard=School(2,'Cambridge','university')
>>> MIT.address
'Cambridge'
>>> Harvard.s_type
'university'

Or whatever pattern you are using.

This way you can also add functions to it:

class School:
    def __init__(self, name, num, addr, s_type):
        self.num = num
        self.name = name
        self.addr = addr
        self.s_type = s_type
    def describe(self):
        print "%s is a %s located at %s." % (self.name, self.s_type, self.address)
    def request(self,arg):
        request[arg] # I'm not sure if that's what you want, I copied it from the dict you had there

>>> MIT.describe()
MIT is a university located at Cambridge.
>>> MIT.request('name')
# Whatever that thing does


Displaying a certain element among inputted numbers

You can definitely improve it, by replacing the array of pointers with a std::vector<int>.

If you must track usage, I suggest using a map instead, where the keys are 0...9 and the values exist only if the respective index was added.


Comparing an active record result with an array of object in a rspec test

Provided you sort the active record results (as you have done), comparing to an array works fine.  I'm not sure what you mean by 'flexible', but the test you've written looks pretty good (without knowing the internals of your 'sort' function).

I'd only suggest adding some more tests to cover reverse sorting, sorting by author.nickname (if that's part of the default scope, or pulled in via delegation), and passing invalid values to the sort function.

Being a little pedantic, you don't need to repeat the word "it" in the spec declaration.
The word "it" will be prepended to the message in the case of failures.

  describe "self.sort" do
    before(:each) do
      @tee = FactoryGirl.create :author, nickname: "tee jia hen", user: FactoryGirl.create(:user)
      @jon = FactoryGirl.create :author, nickname: "jon", user: FactoryGirl.create(:user)
      @tee_article1 = FactoryGirl.create :article, author: @tee, title: "3diablo"
      @tee_article2 = FactoryGirl.create :article, author: @tee, title: "1people"
      @jon_article = FactoryGirl.create :article, author:@jon, title: "2game"
    end

    it "should sort articles base on title" do
      Article.sort("title", "asc").should == [@tee_article2, @jon_article, @tee_article1]
    end

    it "should reverse-sort articles base on title" do
      Article.sort("title", "desc").should == [@tee_article1, @jon_article, @tee_article2]
    end
  end


Entity Framework 7 In Memory Database - Unit Testing using xUnit

I don't know xUnit, but in other testing frameworks you can reuse a single in-memory database in multiple test cases, by annotating the text cases (or rather, the entire test class) transactional. That is, the database manipulations within the test cases will be automatically rolled back after leaving the scope of the methods. That way tests can run faster, thanks to not recreating a full text database repeatedly. I would hope a similar concept exists in xUnit too, and research that.

If no such feature exists, your approach seems fine, but Initialize is a bit too generic of a name, I would call it RecreateDatabase instead to make it more clear what it does. Or, actually, other frameworks use annotation like @Before for this kind of purpose, instead of an explicit method call.

Lastly, the test in the second example is a bit weak. You only get that the first item is what you inserted. I suggest to either add a test to verify that there is only 1 item, or require it using GetAll like you did in the other test case.


I have managed to get it down to this. It had been a while since I had encountered this scenario so I had to rack my brain for a bit and do some research. I basically followed this principle. Let me know if you have any suggestions for further improvements. Cheers.

interface iUpdateArea {
    _areasList: Array<string>;
    _areas: KnockoutObservableArray<string>;
    _selectedArea: KnockoutObservable<string>;
    updateSubArea(geonameId: string);
}

class Area implements iUpdateArea  {
    _areasList = [];
    _areas = ko.observableArray([]);
    _selectedArea = ko.observable('');

    updateSubArea(geonameId){
        var self = this;
        self._areasList = [];
        $.ajax({
            url: `http://api.geonames.org/children?geonameId=${geonameId}&username=elion`
        }).then(function(allRegionsXML) {
            var allRegionsJSON = xml2json(allRegionsXML);
            var allRegions = JSON.parse(allRegionsJSON);
            if(allRegions.geonames.length) {
                for (var index = 1; index < allRegions.geonames.length - 1; index++) {
                self._areasList.push(allRegions.geonames[index].geoname);
                }
            } else {
                if(allRegions.geonames) {
                    self._areasList.push(allRegions.geonames.geoname);
                }
            }
            self._areas(self._areasList);
        });
    }
}

class SearchFilterViewModel {
    _region: Area;
    _town: Area;

    constructor() {
        this._region = new Area();
        this._town = new Area();
        this._region.updateSubArea("2186224");
        this._region._selectedArea.subscribe(this._town.updateSubArea.bind(this._region));
    }
}

$(document).ready(function() {
    var _searchFilterViewModel: SearchFilterViewModel = new SearchFilterViewModel();
    var _searchFilterForm = $("#find-vegan-products-page").find("form")[0];
    ko.applyBindings(_searchFilterViewModel, _searchFilterForm);
    $('.select-multiple').each(function(i, obj) {
        //obj[i] gets each element inside the div
        $(this).multiselect({
            noneSelectedText: "CATEGORIES"
        });
    })
});


Compare Sheet1 and Sheet2 for every match and then write them on Sheet3

Shouldn't this:

For k = 1 To 5
    sheet3.Cells(lr3, k).Value = sheet1.Cells(lr3, k).Value
Next k

be this (you're not copying from row i on Sheet1) ?

For k = 1 To 5
    sheet3.Cells(lr3, k).Value = sheet1.Cells(i, k).Value
Next k

Would be faster as:

sheet3.Cells(lr3, 1).Resize(1, 5).Value = sheet1.Cells(i, 1).Resize(1, 5).Value

EDIT: this should be faster overall. Removes the nested loop and instead uses a dictionary to create a lookup on the sheet2 values.

Sub checkdata()

    Application.Calculation = xlCalculationManual
    Dim sheet1 As Worksheet, sheet2 As Worksheet, sheet3 As Worksheet
    Dim dict As Object, v

    Set sheet1 = Sheets(1)
    Set sheet2 = Sheets(2)
    Set sheet3 = Sheets(3)

    lr1 = sheet1.Cells(Rows.Count, 1).End(xlUp).Row
    lr2 = sheet2.Cells(Rows.Count, 1).End(xlUp).Row
    lr3 = sheet3.Cells(Rows.Count, 1).End(xlUp).Row

    'Map all values+rows in Sheet2 ColD
    Set dict = CreateObject("scripting.dictionary")
    For j = 1 To lr2
        If sheet2.Cells(j, 5).Value = vbNullString Then
            v = jsheet2.Cells(j, 4).Value
            If Not dict.Exists(v) Then dict.Add v, j '<< capture value (first instance only) and row
        End If
    Next

    For i = 1 To lr1

        check = sheet1.Cells(i, 1).Value
        lr3 = lr3 + 1
        sheet3.Cells(lr3, 1).Resize(1, 5).Value = _
                sheet1.Cells(i, 1).Resize(1, 5).Value

        'does check exist on Sheet2 (with empty ColE value)?
        If dict.Exists(check) Then

            sheet2.Cells(dict(check), 9).Value = "x" '<<< not Col 5 ?
            lr3 = lr3 + 1 '<<< needed?
            sheet3.Cells(lr3, 6).Resize(1, 5).Value = _
                    sheet2.Cells(dict(check), 1).Resize(1, 5).Value
            Exit For
        End If

        lr3 = lr3 + 1 '<<< needed?
    Next i

    Application.Calculation = xlCalculationAutomatic

End Sub


Given your requirements, it seems you would be best using String.StartsWith and a StringComparison value which ignores case (i.e., CurrentCultureIgnoreCase, InvariantCultureIgnoreCase, or OrdinalIgnoreCase).  This should be a little cleaner and faster than doing case conversions.

Expression<Func<SearchVehicleVariant, bool>> expression =
   c => SearchTerms.All (
      (c.ManufacturerName ?? string.Empty).StartsWith (s, StringComparison.InvariantCultureIgnoreCase)
      || (c.ModelName ?? string.Empty).StartsWith (s, StringComparison.InvariantCultureIgnoreCase)
      || (c.Name ?? string.Empty).StartsWith (s, StringComparison.InvariantCultureIgnoreCase));


Summing values in a vector using threads

Firstly, it's a good first attempt at writing some threaded code. The major sticking point is that you're passing in an int & and returning void. Of course, std::thread will just run some code and won't return you a result. However, within the C++11 threading library, there are a number of things you can use that will allow you to return results, instead of having to use std::ref and reference parameters.

Before tackling that, let's look at the adder function itself. I'm going to go through a sequence of improvements that can be made to it. Firstly, you should try and use the correct type to index into a std::vector:

using size_type = std::vector<int>::size_type;

int adder( const std::vector<int> & v, size_type begin, size_type end)
{
    for( ; begin < end; ++begin )
    {
        result = result + v.at( begin );
    }
}

This is ok, but it could be a lot more generic: What if the values aren't stored in a std::vector? Instead, template this so that it can use anything that supports an iterator concept:

template <typename Iterator>
int adder(Iterator begin, Iterator end)
{
    int result = 0;
    for(auto it = begin; it != end; ++it) {
        result += *it;
    }
    return result;
}

Ok, getting there, but we can still improve this quite a bit: what if we want to sum any kind of numeric type? (Note this will require an #include <iterator>):

template <typename Iterator>
std::iterator_traits<Iterator>::value_type
adder(Iterator begin, Iterator end)
{
    std::iterator_traits<Iterator>::value_type result;
    for(auto it = begin; it != end; ++it) {
        result += *it;
    }
    return result;
}

Ok, so we're not locked into a vector or an int type anymore. However, this pattern of summing up a bunch of values is really common, and there is library functionality that takes care of it for us: std::accumulate (note that this needs an #include <algorithm>):

template <typename Iterator>
typename std::iterator_traits<Iterator>::value_type
adder(Iterator begin, Iterator end)
{
    using T = typename std::iterator_traits<Iterator>::value_type;
    return std::accumulate(begin, end, T());
}

Now for the threading part.

The C++11 threading library has a really handy function called std::async. This allows you to run some piece of code in a thread, and retrieve a result from it. It will give you back what is known as a std::future (note that this needs an #include <future>):

template <typename Iterator>
typename std::iterator_traits<Iterator>::value_type
parallel_sum(Iterator begin, Iterator end)
{
    using T = typename std::iterator_traits<Iterator>::value_type;
    auto midpoint = begin + std::distance(begin, end) / 2;
    std::future<T> f1 = std::async(std::launch::async, adder<Iterator>, begin, midpoint);
    std::future<T> f2 = std::async(std::launch::async, adder<Iterator>, midpoint, end);
    return f1.get() + f2.get();
}

We then use this as follows:

int main()
{
    std::vector<int> v;
    for(int i = 0; i < 100000; ++i) {
        v.push_back(i);
    }
    int total = parallel_sum(v.begin(), v.end());
    std::cout << total << "\n";
}

There's probably too much to absorb here in one go, but I'll break down the main points:

Try and make your functions work with the facilities provided by the standard library. Iterators permeate the container/algorithm side of it - if you can, try and work with iterators instead of directly with containers.
Look for functionality in the standard library that can help you with common tasks, such as std::accumulate.
With threading, if you want to get results back, prefer to use std::async instead of passing parameters by reference to store results.


Multiple 'using' statements in method implementation

There is nothing inherently wrong with having multiple using statements. It keeps the lifetime of objects to the minimum which is not a bad thing to do.

Another point is that I'd possibly re-factor the error raising: You always prepare the error message with the same parameters except for the actual message. This could easily be encapsulated in a little helper function. So the refactored code could look like this:

private Response GetUnauthorizedResponse(string message)
{
    using (var responseManager = new ResponseManager())
    {
        return responseManager.PrepareMessage(
            HttpStatusCode.Unauthorized,
            message,
            null,
            ResponseManager.ResponseType.InterfacePlainText
        );
    }
}

[HttpPost]
[ExpiredCookieCheck]
public IHttpActionResult Auth([FromBody]AuthenticationData authenticationData)
{
    try
    {
        if (authenticationData == null)
        {
            return GetUnauthorizedResponse("No authentication model was provided in request body.");
        }

        using (var authenticationHandler = new AuthenticationHandler())
        {
            var validationData = authenticationHandler.CheckAuthenticationDataFromWeb(authenticationData);
            if (!validationData.Key)
            {
                return GetUnauthorizedResponse("Incorrect credentials for authentication.");
            }

            using (var cookieManager = new CookieManager())
            using (var responseManager = new ResponseManager())
            {
                var authenticationCookie = cookieManager.CreateAuthenticationCookieHeader(Request.RequestUri.Host);
                cookieManager.SaveAuthenticationCookie(validationData.Value.Id, authenticationCookie);

                return responseManager.PrepareMessage(
                    HttpStatusCode.OK,
                    null,
                    authenticationCookie,
                    ResponseManager.ResponseType.InterfacePlainText
                );
            }
        }
    }
    catch (Exception exception)
    {
        return GetUnauthorizedResponse(exception.ToString());
    }
}

This removed some distracting clutter and lets the reader focus better on the actual functionality of the method.


From a set of words, output all words that fit a string of random letters (like Scrabble)

The way you handle the file is not ideal. It's not apparent in such a small program, but you are not .close()-ing the file after opening it. Of course, Python will close the file once the program is done running, but in a bigger application, using your method would get clunky since you would have to remember to call .close() each time you open a file. Python's with keyword can take care of that for you, though.

with open('wordlist.txt','r') as file:
    wordlist=list(line.strip('\n') for line in file
    # more file handling code...

# file will be automagically closed after `with` block exits

I think your wordFinder function does too much (also per PEP8 convention it should be named word_finder). I would expect a function named like that to just find and return words, but it also handles user input, which I think should be a separate function.

Speaking of handling input, your program does not seem to handle non-letter characters at all. What happens when a user enters abc_123 as input? I'm guessing it will just use ABC_123 to look in your file, and return results for ABC after it finds nothing for _123. My suggestion would be to get input in a while loop, and exit the loop only after validating it:

input_is_only_letters = False
while not input_is_only_letters:
    letters = str.upper(input('enter up to 7 letters:'))
    if letters.isalpha():
        input_is_only_letters = True
    else:
        print('Please enter only letters A-Z (not case sensitive)')

I would also wrap this logic into its own function that returns the input.

A few small things:

Since you are using Python 3, you can (and IMO should) use type hints, which I did in the below code.
Get in the habit of making a separate function for each "action" or separate type of thing. This makes debugging and testing code much easier.
When you assign values, use a space on each side of the equal sign, e.g., my_value = 42.
Use snake_case naming for functions, variables, etc.
You don't need to check for if my_var == True: or if my_var == False:, you can simply write if my_var: and if not my_var:
Try to get in the habit of writing docstring for your functions, you will thank yourself later when you or others have to revisit your code.
Get in the habit of executing your self-contained calls in if __name__ == '__main__', so that if you were to import this into another module it wouldn't execute the file itself when it's loaded. See this article on thepythonguru.com for more information.
I haven't looked at your list comprehension code, maybe someone else will think of a way to do it that way.

My refactored code.

Note that I don't have a way to test it, to the best of my knowledge it should work fine but please let me know if I made an error.

from typing import List

def get_7_letters_input() -> str:
    """Captures up to 7 letters from stdin"""
    input_is_only_letters = False
    while not input_is_only_letters:
        letters = str.upper(input('enter up to 7 letters:'))
        if letters.isalpha():
            if len(letters) <= 7:
                input_is_only_letters = True
            else:
                print('Please enter no more than 7 letters')
        else:
            print('Please enter only letters A-Z (not case sensitive)')
    return letters

def get_words_from_file(filename: str) -> List:
    """Opens a file and splits it into a list for each new line"""
    with open(filename, 'r') as file:
        return list(line.strip('\n') for line in file

def find_words_matching_letters(letters: str) -> List:
    """Find words that match the letters provided"""
    words = []
    word_list = get_words_from_file('wordlist.txt')

    for word in word_list:
        candidate = True
        letterlist = list(letters)
        for letter in word:
            if letter not in letterlist:
                candidate = False
                break
            else:
                letterlist.remove(letter)
        if candidate:
            words.append(word)
    return words

if __name__ == '__main__':
    find_words_matching_letters(get_7_letters_input())


Formatting

The indenting and placement of braces is inconsistent in the program,
and it hurts readability. Instead of this:

    for(int i = first_i ; i< list.Count; i++)
    {
        for(int j=second_i; j<list.Count; j++)
        {
                    if(i != list.Count)
                        {
                            global_sum += list[i] + list[j];

                            if(global_sum == sum)
                                {
                                     var tuple1 = Tuple.Create(i,j);
                                  return tuple1;
                                }
                            global_sum = 0;
                        }
                    else
                        {
                            break;
                        }

        }
    }

This would be have been much better:

    for (int i = first_i; i < list.Count; i++)
    {
        for (int j = second_i; j < list.Count; j++)
        {
            if (i != list.Count)
            {
                global_sum += list[i] + list[j];

                if (global_sum == sum)
                {
                    var tuple1 = Tuple.Create(i, j);
                    return tuple1;
                }

                global_sum = 0;
            }
            else
            {
                break;
            }
        }
    }

Strange condition in loop body

The conditional in the body of the nested loop is pointless,
as it can never be true. You can simply remove it:

for (int i = first_i; i < list.Count; i++)
{
    for (int j = second_i; j < list.Count; j++)
    {
        global_sum += list[i] + list[j];

        if (global_sum == sum)
        {
            var tuple1 = Tuple.Create(i, j);
            return tuple1;
        }

        global_sum = 0;
    }
}

Unnecessary variables

The name global_sum is not great. There's nothing "global" about that sum. It's just sum. And you don't need it a variable for it anyway.
You could change this code:

        global_sum += list[i] + list[j];

        if (global_sum == sum)
        {
            var tuple1 = Tuple.Create(i, j);
            return tuple1;
        }

        global_sum = 0;

Like this:

        var global_sum = list[i] + list[j];

        if (global_sum == sum)
        {
            var tuple1 = Tuple.Create(i, j);
            return tuple1;
        }

At this point, notice that you don't really need this variable at all,
you could write the expression directly in the if statement.
The tuple1 variable is also pointless.
The code can be reduced to:

        if (list[i] + list[j] == sum)
        {
            return Tuple.Create(i, j);
        }

first_i and second_i are also rather useless,
and would have been to use their values directly inside the loop statements.

Also keep in mind that declaring variables at the top of their scope,
when they are not used until much later,
is not a recommended practice.
It's best to declare a variable right before you need it.

Correctness

As @RiskyMartin hinted, given an input list 1, 6, 9, the output will be incorrectly (6, 6). In other words, you need to make sure that i and j indexes are not equal.

Performance

Of course, none of the above help with the performance.
The algorithm is \$O(n^2)\$: you try all permutation of pairs.

To make this faster, you can sort the input list, and then form pairs using two pointers, one going from the start and one going from the end.
Move the pointers closer when the sum of the pointed values is above the target sum.
The performance of this algorithm will be \$O(n\log(n))\$:
the sorting step is \$O(n\log(n))\$,
the search step with two pointers is \$O(n)\$.

For example, given 1, 2, 5, 7, 9, the first pointer starts at 1, the second at 9. 1 + 9 is less than 12, so you advance the first pointer. 2 + 9 is less than 12, so you advance the first pointer. 5 + 9 is greater than 12, so you move the second pointer. 5 + 7 is a match, you return it.

Just like in the original program, make sure the two pointers don't point to the same element, because that could produce an invalid match, potentially using the same element twice to make the sum.


Since b_int is limited to bytes we can change your code a little to remove the formatting.

The left_shift can only have two states, if b_int & 1 is 1 or 0. And so is the same as ((b_int & 1) << 7). (b_int >> 1) is as simple as it gets, and so this can stay the same.

And so I changed it to:

def shift_bits(b_int):
    return (b_int >> 1) | (int('{0:08b}'.format(b_int << 7)[-8:], 2))

def p_shift_bits(b_int):
    return ((b_int & 1) << 7) | (b_int >> 1)

Which works as intended:

for i in range(1 << 9):
    if shift_bits(i) != p_shift_bits(i):
        print(i)
        break

However, you can still speed it up if you used functools.lru_cache:

@functools.lru_cache(None)
def pc_shift_bits(b_int):
    return ((b_int & 1) << 7) | (b_int >> 1)

These gave the following timings:

>>> timeit.timeit('shift_bits(i)', 'from __main__ import shift_bits; i=183')
1.9397294419024576
>>> timeit.timeit('p_shift_bits(i)', 'from __main__ import p_shift_bits; i=183')
0.4003988483403518
# Yes heavily biased, but if the length of data is greater than 256, it comes into play.
>>> timeit.timeit('pc_shift_bits(i)', 'from __main__ import pc_shift_bits; i=183')
0.15648568020111497


Key Points

I would not use local variables to hold recordset values, because you'd need one for every field of every returned row... which is just wrong.
As already pointed out, good variable names are readable variable names (which can be pronounced!).
You're not showing it, but make sure you close that connection once you're done.

"Entities"

Here's an [perhaps less appealing] alternative to Dictionary. Since I learned about C# and started using Entity Framework, I like wrapping each record in an object - given a class called MyEntity (which does nothing more than exposing getters and setters for all properties):

Private Type ThisEntity
    SomeProperty As String
    AnotherProperty As String
End Type

Private this As ThisEntity
Option Explicit

Public Property Get SomeProperty() As String
    SomeProperty = this.SomeProperty
End Property

Public Property Let SomeProperty(value As String)
    this.SomeProperty = value
End Property

Public Property Get AnotherProperty() As String
    AnotherProperty = this.AnotherProperty
End Property

Public Property Let AnotherProperty(value As String)
    this.AnotherProperty = value
End Property

You define this object only once, and then you instantiate it as many times as you have records in your recordset. With a dictionary you get easier loading (each "entity" is a dictionary where you identify each field by their names to retrieve the corresponding value), but with this object you completely avoid referring to your properties using strings - the only hard-coded strings involved are the field names.

Reading the recordset

All you need to do is exactly as you said, loop through the recordset:

Dim entity As MyEntity
Dim entities As New Collection
While Not rs.EOF And Not rs.BOF 'BOF check if result has 0 rows

    Set entity = New MyEntity
    With entity
        .SomeProperty = rs.Fields("SomeField").Value 'or rs!SomeField
        .AnotherProperty = rs.Fields("AnotherField").Value 'or rs!AnotherField
    End With

    entities.Add entity ', entity.Id /PK property if you want to use a key here
    rs.MoveNext 'don't forget this, or your loop will be endless!
Wend

rs.Close
Set rs = Nothing
'at this point you have your entire recordset's content in the "entities" collection

About rs!FieldName notation (little "Gotcha!")

For what it's worth, I've recently fixed a bug in our codebase that was caused by the rs!FieldName notation in a specific circumstance: rs!FieldName was being added to a collection, and the recordset was left open. When I found that out, I added rs.Close and all of a sudden the collection, although non-empty, could no longer be read. This is because adding rs!FieldName to the collection (or, if you take the dictionary road) was actually adding a reference to the Field object, and the original programmer was left with the impression it worked fine because he could retrieve any entry in the collection and see the field's value - when he was actually retrieving a Field object and through the default property was fetching the value from the recordset: that stopped working when I added code to close the recordset after all records were read.

That bug was fixed by explicitly adding rs.Fields("FieldName").Value to the collection instead.


CLRS Exercise 2.3-4: Recursive Insertion Sort

The implementation looks fine to me, but writing the recurrence with a big theta isn't right. The problem is that the time taken to insert item \$n\$ into the right place among items 1 to \$n-1\$ depends on the values of the items — if item \$n\$ is bigger than all of items 1 to \$n-1\$ then it takes constant time to "insert" it. What we can say is that in the worst case it takes time proportional to \$n\$ to insert the item.

Let's go back and try again from first principles. If you look at the analysis of the iterative version of the insertion sort algorithm (on pages 25–6 of CLRS) you'll see that the approach the authors take is to annotate each line of code with a cost and number of times it is executed. So let's do that for the code in the post:

                                        COST    TIMES
--------------------------------------  ------  ------
def recursive_insertion_sort(A, n):
    if n < 1:                           c1      1
        return A
    recursive_insertion_sort(A, n - 1)  T(n-1)  1
    key = A[n]                          c2      1
    while n > 0 and key < A[n - 1]:     c3      t(n) + 1
        A[n] = A[n - 1]                 c4      t(n)
        n -= 1                          c5      t(n)
    A[n] = key                          c6      1
    return A                            c7      1

Here \$t(n)\$ is the number of times that the while loop needs to be iterated when the function is called with the value \$n\$. This depends on the input A, so we might need to make separate worst-case and best-case analyses (as you can see the authors do for the iterative version on page 26).

So we have $$ T(n) = T(n-1) + c_1 + c_2 + c_3 + c_6 + c_7 + (c_3 + c_4 + c_5)t(n) $$ Now, in the best case, the input is already sorted, and so the while loop is never executed, and so \$t(n) = 0\$, hence $$ T(n) \ge T(n-1) + c_1 + c_2 + c_3 + c_6 + c_7 $$ and following similar analysis to page 26, we find $$ T(n) \ge (c_1 + c_2 + c_3 + c_6 + c_7)n $$ and so \$T(n) = \Omega(n)\$.

In the worst case, the input is sorted in reverse order, and so \$t(n) = n-1\$, hence  $$ T(n) \le T(n-1) + c_1 + c_2 + c_3 + c_6 + c_7 + (n-1)(c_3 + c_4 + c_5) $$ and again following similar analysis to page 27, we find $$ \eqalign{ T(n) &\le (c_1 + c_2 + c_3 + c_6 + c_7)n + {c_3 + c_4 + c_5\over2}n(n-1) \\ &= {c_3 + c_4 + c_5\over2}n^2 + \left(c_1 + c_2 + c_3 + c_6 + c_7 - {c_3\over2} - {c_4\over2} - {c_5\over2}\right)n} $$ and so \$T(n) = O(n^2)\$.

So this is an algorithm for which we can't find a big-Theta expression for the runtime — it's bounded below by \$ \Omega(n) \$ and above by \$O(n^2)\$ and these do not meet in the middle.

(There are various ways to take shortcuts in this kind of analysis, especially if you are only interested in the asymptotic result, but when you are starting out, it's good to go through all the details so that you have confidence you're not missing anything.)


Google's Python exercise about lists very different from the given solution

In a nutshell, yours is better, for two reasons.

First, Python isn't designed for speed. It's decently fast, but the goal is code like yours: so clear, concise, obvious, and readable that anyone can glance at it and immediately see what it does. You can then spend the rest of the project's development time working on the difficult problems (like attending meetings).

Second, the "answer" code doesn't really answer the exercise, as it notes. It looks right in theory, but popping elements from the beginning of a list is not the most performant operation in most languages, including Python. It would be a more reasonable solution with a linked list, which is a type that was probably omitted from Python precisely because its utility is mostly limited to fixing the micro-optimizations in bloated code. This is like optimizing a recursive function by making it tail-recursive, and then admitting that it doesn't make any difference because Python doesn't have tail call optimization.

If you were using this code in a real program and determined through actual testing that this linear_merge function was taking too much time due to the extra sorting, you might then be justified in optimizing it.

For fun, here's something with indexing instead of pop():

def linear_merge(list1, list2):
    result = []
    c1 = c2 = 0
    while c1<len(list1) and c2<len(list2):
        if list1[c1] <= list2[c2]:
            result.append(list1[c1])
            c1 += 1
        else:
            result.append(list2[c2])
            c2 += 1
    result.extend(list2[c1:])
    result.extend(list1[c2:])
    return result

This might be faster due to not pop()ing items from the beginning of each list, but it also might be slower (or possibly more memory-intensive) due to having to slice a list at the end. I leave it as an exercise to you to time these approaches... but remember that the most important time to conserve is usually your own, not your computer's.


Replacing removed secure empty trash feature

Your description appears to suggest you're reimplementing wipe; I recommend you read its sources to see what an effective implementation looks like.  I'll note that the concept could well be flawed if you're writing to a log-structured filesystem or to wear-levelling media - both of those need specific actions to erase data, because overwriting will simply create new data blocks elsewhere.
The "PascalCase" naming convention makes this code surprisingly hard to read (and not just because capital I looks a lot like 1, and Int sounds a lot like int).  I would prefer to see more conventional identifiers, so that variables look like variables.
This include looks pointless:

 #include <unistd.h>

As we're using only Standard Library, prefer to omit this, for a portable program.

    if (!File || fseek(File, 0, SEEK_END) || (FileSize = ftell(File)) < 0) {
        perror(Path);
        continue;
    }

I approve of error checking, but there's a problem here.  If we open a file but fail to seek (because it's a non-regular file, perhaps), then we fail to close it.

    RandBuf = realloc(RandBuf, IntCount<<2);

What happens when realloc() returns a null pointer?  We have a leak and we have undefined behaviour when we dereference RandBuf.  It seems risky to need that much memory, given that files can often be larger than address space.  We'd probably prefer to write in sensible size chunks too, given the copying that's involved.

    const unsigned long IntCount = (FileSize+3)>>2;
    RandBuf = realloc(RandBuf, IntCount<<2);

Where do those magic numbers 2 and 3 originate?  I'm guessing that perhaps that sizeof (int) is 4 on your platform, and the constants derive from that.  But it would be better to calculate from the actual size of int and to name the constants more appropriately.

    for (unsigned char Write = 0; Write < WriteCount; Write++) {

This loop serves no purpose.  We write a variety of values several times, but it's unlikely any of these values go all the way to the disk, given we never fflush() the stream.


I'm not really into networking, but I can say a little about your coding style:

Missing return

if (socket_desc == -1) {
    printf("Could not create socket");
}
puts("Socket created");

If socket_desc is equal to -1. Could not create socket will be printed as well as Socket created, which is misleading. I think:

if (socket_desc == -1) {
    printf("Could not create socket");
    return -1;                           /* or some other error code */
}
puts("Socket created");

is appropriate and the code doesn't proceeds.

Outsource
I'm also not sure if it would be better to outsource this part (as void prepareServer(sockaddr_in *server):

server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 8888 );

Unnecessary comments
I don't know who else will read this code but comments like //print the error message followed by this perror("bind failed. Error");

will just make the code more obscure, since the goal of the error message is pretty obvious.

Calling strlen for no reason
Also it's not really clear to me, why you need to call strlen(client_message) here

write(sock , client_message , strlen(client_message));

when you store assign read_size a few lines above in the while-condition. strlen will just search for a '\0', which you assign by yourself with read_size...

Besides these points I can't see any major mistakes. You should just think about your comments a little more (Do I really need this information? Is this self explaining? Is a single line comment enough here?).
As I already said: I can't say much about the networking part, maybe someone else will jump here.


I would suggest having the 2D implementation call the 1D implementation, rather than duplicating the "any" logic in both implementations, e.g.

bool any(bool** array, const int nRow, const int nCol){
    // mimics the behavior of Matlab's any() function. Returns true if any element of the array is true
    bool val = false;

    for (int i = 0; i < nRow && val == false; ++i)
    {
        val = any(array[i], nCol); // call 1D version of any
    )
    return val;
}


Guessing game - am I using the concept of objects in Java properly?

To start with, spot the inconsistency. For the name you create it in your main loop and then use a setter; for the number you have a method in the Player object to acquire the guess. The latter is more in line with the message-passing philosophy of OO. (Many people seem to think that using getters and setters is being OO. They're often - not always - a sign of non-OO thinking). However, it doesn't take it as far as it could. The number guessed isn't a property of the player - it's a property of the guess.

Guessing a number isn't the same thing as displaying it - either rename the method or, probably better - a method should do one thing - move that out.

Next up, the flagWinner is a big red flag. Its sole purpose is to identify one of the objects p1, p2, p3, or none of the above. What's the OO way to do that? Use the object to identify itself.

I'd be inclined to factor out the IO as an object too, to be a bit less procedural. So without going into a full over-patterned architecture we have

public class IO {
    public void output(String msg) {
        JOptionPane.showMessageDialog(null, msg);
    }

    public String input(String prompt) {
        return JOptionPane.showInputDialog(prompt)
    }

    public int inputInt(String prompt) {
        return Integer.parseInt(input(prompt));
    }
}

public class Player {
    private String playerName;

    private Player(String name) {
        playerName = name;
    }

    public static Player createPlayer(IO io, String prompt) {
        String name = io.input("Enter " + prompt + " Name: ");
        return new Player(name);
    }

    public String getPlayerName() {
        return playerName;
    }

    public int guessNumber(IO io) {
        return io.inputInt(playerName +"'s Turn\nGuess the Number"));
    }
}

public class GuessGame {

    private final IO io;
    private final int numPlayers;
    private int numberToGuess;
    private List<Player> players = new LinkedList<Player>();

    public GuessGame(IO io, int numPlayers) {
        this.io = io;
        this.numPlayers = numPlayers;
    }

    public void init() {
        numberToGuess = (int) (Math.random()*10);
        for (int i = 0; i < numPlayers; i++) {
            players.add(Player.createPlayer(io, "Player " + (i+1)));
        }
    }

    public void runGame(){
        init();

        Player winner = null;
        Iterator<Player> it = players.iterator();
        while (winner == null) {
            if (!it.hasNext()) {
                it = players.iterator();
            }

            Player turnPlayer = it.next();
            String playerName = turnPlayer.getPlayerName();

            int guess = turnPlayer.guessNumber(io);
            io.output(playerName+ "'s GUESS is " + number);

            if (guess == numberToGuess) {
                winner = turnPlayer;
            }
            else {
                io.output(playerName + "'s Guess is Wrong!");
            }
        }

        io.output(winner.getPlayerName()+ " Wins!");
    }
}


If the objective is to avoid duplicating information in memory, the code you have given won't archive it.

The new keyword hides the original value. It doesn't replace it. You should try another approximations, like the Decorator pattern: https://en.wikipedia.org/wiki/Decorator_pattern

The MasterData inherits from the GlobalData class and stores internally the reference to that class. Whenever someone accesses to a property of the GlobalData class, you redirect the request to the instance stored internally.

The MasterData class stores only the values of the newly added properties.

The tricky part would be preventing other parts of your MasterApplication app calling to the GlobalData class and thus creating another instance.

Singletons are always a nightmare...


How about leveraging Enum.ToString()?

Given these two enums:

public enum Win32OperatingSystem
{
    FreePhysicalMemory,
    TotalVirtualMemorySize,
    FreeVirtualMemory
}

public enum Win32ComputerSystem
{
    Name,
    Manufacturer,
    Model
}

Now you can have a simple method:

    public ulong SelectWin32Property(Win32OperatingSystem property)
    {
        var propertyName = property.ToString();
        var moSearcher = new ManagementObjectSearcher
            ("SELECT " + propertyName + " FROM Win32_OperatingSystem");
        using (var enu = moSearcher.Get().GetEnumerator())
        {
            if (!enu.MoveNext()) return 0;
            return BytesToMegaBytes((ulong)enu.Current[propertyName]);
        }
    }

If you wanted an overload that takes a Win32ComputerSystem parameter, you'd have to deal with the different return value:

    public string SelectWin32Property(Win32ComputerSystem property)
    {
        var propertyName = property.ToString();
        var moSearcher = new ManagementObjectSearcher
            ("SELECT " + propertyName + " FROM Win32_ComputerSystem");
        using (var enu = moSearcher.Get().GetEnumerator())
        {
            if (!enu.MoveNext()) return "Unable to retrieve " + propertyName + " from Win32_ComputerSystem!";
            return enu.Current[propertyName].ToString();
        }
    }

The easiest would probably be to box the numeric types into a string, so all overloads would return a string representation of their values. This might not be practical, but at least you don't need to write a new method nor to change your interface to support a new property.

Alternatively you could box results in an object, but that wouldn't be pretty, I'd much prefer dealing with a string than exposing object.

The ideal would be to avoid boxing the numeric return types altogether, so the methods have to live in separate classes - this is where generics come handy:

public abstract class Win32QueryBase<TResult, TProperty>
{
    public abstract TResult SelectWin32Property(TProperty property);
}

This can be implemented by this class:

public class Win32OperatingSystemQuery : Win32QueryBase<ulong, Win32OperatingSystem>
{
    public override ulong SelectWin32Property(Win32OperatingSystem property)
    {
        // ...
    }
}

And this class:

public class Win32ComputerSystemQuery : Win32QueryBase<string, Win32ComputerSystem>
{
    public override string SelectWin32Property(Win32ComputerSystem property)
    {
        // ...
    }
}


Test if two nodes in a binary search tree are cousins

The logic seems sane to me in general.

If the caller has the values to seek instead of node pointers, then you could change the function parameters to the value types and drop the a == nullptr || b == nullptr checks. But if the caller has node pointers that you cannot know for sure if null or not, then indeed you don't have a choice.

I find these statements more readable without the line breaks and unnecessary parentheses:

a_seek = a->value < a_seek->value ? a_seek->left : a_seek->right;
b_seek = b->value < b_seek->value ? b_seek->left : b_seek->right;


Testing a Collatz Conjecture Conjecture (Python)

def key(value, dct):
    for key in dct.keys():
        if dct[key] == value:
            return key
    return None

This is really inefficient and not how dictionaries should be used.

The point of a dict is O(1) lookup, this is essentially O(n) and it doesn't make sense
You should remove your blockcomments, and create a nice docstring. That will make the purpose of the code clearer
You don't close the file, a nice addition is using the with statement to automatically open/close files PEP343


Read JSON as a dictionary of country codes and names

There's nothing wrong with what you currently have. However, a plist is another option, if this JSON is just static file.

The nice thing about the property list format is that Xcode has built-in support for editing it and Foundation has built-in support for reading it.

fileprivate func loadNames() {
    if let filePath = Bundle.main.path(forResource: "countryNames", ofType: "plist") {
        countryNames = NSDictionary(contentsOfFile: filePath)!
    }
}


The test

if (fib.doubleValue() % 2 == 0)

does not produce the correct result for numbers with more than 17 digits, because
that exceeds the precision of a double. Actually it returns true for 8944394323791464 and all subsequent Fibonacci numbers.
That is not relevant for the concrete problem here (see below), but if you want to work with BigInteger then you should replace this with

if (fib.remainder(bigTwo).equals(BigInteger.ZERO))

where bigTwo is defined as

BigInteger bigTwo = new BigInteger("2");

Project Euler Problem #2
asks for the sum of all even-valued Fibonacci values not exceeding 4 million,
so using BigInteger is not really necessary. All numbers fit into the range
of int, and the above test simplifies to

if (fib % 2 == 0)

(I also planned to tell that using int instead of BigInteger makes the
program more efficient, but it turned out that the difference in running
time is not significant.)


I was wondering if there is a better approach to this?

Yes. Use a library. Using what's already done is always better than doing it yourself. ;)

The next best thing you could do is convert minutes into milliseconds and instantiate a Date object from it. From there, JS does most of the heavy lifting for you. Here's an example (not extensively tested, but you get the idea):

const pad = n => `0${n}`.slice(-2)

const convertMinsToHrsMin = mins => {
  const date = new Date(mins * 60 * 1000)

  // Need to be UTC since timestamps are universal
  // but normal time methods operate based on local time.
  const hours = date.getUTCHours()
  const minutes = date.getUTCMinutes()

  // If 0, as in 00:00 or 12:00, default to 12.
  const hours12 = hours % 12 || 12
  const period = hours >= 12 ? 'PM' : 'AM'

  return `${pad(hours12)}:${pad(minutes)}${period}`
}

startTime = convertMinsToHrsMin(720);
endTime = convertMinsToHrsMin(1080);

alert(startTime);
alert(endTime);

As for your code:

Use console.log instead of alert. I know alert is a quick way to visualize values, but getting the habit of using console.log will do wonders for your skin.
Avoid very deep and branchy conditionals. if statements don't do anything on its own and has to be mutating some variable. That means you define variables up top. There is a chance that you might miss a branch and leave that variable empty or contain an unwanted value.
Use a ternary for short conditionals, like determining AM and PM. It's short, and gets you into not mutating variables.
Use template literals to construct strings. This way, you don't need to break out strings and you always get a string (not a NaN should your expression fail you due to coercion).
And lastly, get familiar with the native APIs. They do lots of heavy lifting for you so you don't have to write it yourself.


Inserting large amounts data into Excel spreadsheet

public class ReportData
{
    public ReportData(IEnumerable<ReportColumn> columns)
    {
        Columns = columns ?? throw new ArgumentNullException("No valid columns available");
    }

    public IEnumerable<ReportColumn> Columns { get; set; }
}

The Columns property should be get-only.

public string ColumnName { get; set; }
public object[] ColumnData { get; set; }

Same with these two: it makes no sense to set them in the constructor, even throw an exception if it's null, if you can legally construct the object and then merrily do this:

var data = new ReportData(Enumerable.Empty<ReportColumn>()) { Columns = null };

Note that IEnumerable<T> things should indeed never be null, but any IEnumerable<T> can still be empty without being null. As such, the guard clause is insufficient, since it appears to be there to protect against creating a new ReportData that wouldn't have any columns - Enumerable.Empty<T>() is a perfectly valid input that should be guarded against.

public class ReportData
{
    public reportData(IEnumerable<ReportColumn> columns)
    {
        var reportColumns = columns ?? throw new ArgumentNullException(...);
        if (!reportColumns.Any())
        {
            throw new ArgumentException(...);
        }

        Columns = reportColumns;
    }

    public IEnumerable<ReportColumns> Columns { get; }
}

Now there's no way a ReportData object can have 0 columns, be it during or after construction.

These two could be expression-bodied auto-properties:

private Worksheet Worksheet { get { return Globals.ThisAddIn.Application.ActiveSheet; } }
private Range Cells { get { return Globals.ThisAddIn.Application.ActiveSheet.Cells; } }

Like this:

private Worksheet Worksheet => Globals.ThisAddIn.Application.ActiveSheet;
private Range Cells => Globals.ThisAddIn.Application.ActiveSheet.Cells;

This is a serious problem:

// NOTE: Excel uses indexing that starts at 1
if (columnIndex == 0)
    columnIndex = 1;

if (rowIndex == 0)
    rowIndex = 1;

Consider consistently using { } braces to avoid such implicit scopes.

If the columnIndex or rowIndex supplied was 0, then the calling code is off-by-one and this silent one-upping is literally hiding that bug, and there's a very very very high chance that the next call is going to pass a 1 that you're not going to offset, which will produce a result, but very unlikely the expected result.

Consider:

Throwing an ArgumentOutOfRangeException given 0 for column or row index.
Adding XML docs to document that the index parameters are 1-based - OR document them as 0-based, and abstract away the fact that Excel's object model is 1-based by offsetting every provided value, not just 0. In any case, you need XML docs to say this.

My experience with VSTO is that if you don't properly release all the COM objects you ever access, then when your program exits you'll be left with a ghost EXCEL.EXE process in Task Manager, because .NET will be holding on to RCW objects wrapping COM/unmanaged objects that won't be garbage-collected like managed objects would be.

Hence, avoid double-dots like this:

Globals.ThisAddIn.Application.ActiveSheet

That's essentially leaking ThisAddIn, Application, and ActiveSheet objects.

Every single access to Cells is re-dereferencing the same ActiveSheet over and over and over, every time. That makes a lot of redundant member access.

var addin = Globals.ThisAddIn;
var application = addin.Application;
var activeSheet = application.ActiveSheet;

var allCells = activeSheet.Cells;
var cell = allCells[columnIndex][rowIndex];
cell.Value = column.ColumnName;

var cellFont = cell.Font;
cellFont.Bold = true;

...and then each of these objects need to be released... in the reverse order they were accessed:

Marshal.ReleaseCOMObject(cellFont);
Marshal.ReleaseCOMObject(cell);
Marshal.ReleaseCOMObject(allCells);
...

Miss one single COM object, and the EXCEL.EXE process won't be able to shut down correctly.

That makes it a pretty good reason to avoid writing to individual cells, ...regardless of the performance hit ;-)


Increasing performance and accuracy in multithreaded loop

So your first question.

  no thread function call will be skipped.

You seem to be lost on what the WaitAll(Task[]) function does. This function is essentially a while loop that only exits when all threads it is called upon have finished executing. In this case, your program  will always execute all threads in your 'tasks' list. If you were to call something like WaitAll(Task[], Int32) instead, like: Task.WaitAll(tasks, 500); then your code would wait 500 milliseconds for your threads to join, and then continue on. It would give you an undesirable affect of not guaranteeing the execution of all threads.

  Also is there any way to improve the threaded loop? ...I was hoping to find a way to get them in order.

You have to understand that threads do not guarantee execution in order of insertion, or when they were started. Imagine you have a 5 gallon bucket that is half filled with bouncy balls. Each ball has a number on it from [0, n], and was placed in the bucket in order from 0 -> n. Now, if we put a lid on the bucket, shake the bucket, pull the lid off, put a blind fold on and then try to pull out the balls in order of n - 0 we have a close idea of what happens when trying to get an ordered execution of threads.

Edit:

Due to the comments from @ErnieL I realized that there is another aspect of multithreading which needs to be addressed about scope. We are not talking about scope as in my object exists between braces, but rather the scope of who has control over my object.

The point was brought up about doing StackLoopPoints.Pop().ToString(). Prima facie this is an easy thing to do and results in the data that we want, but there is actually a tricky situation happening behind the scenes. We have to ask ourselves: What happens in the time span between when Pop() and ToString() being called?

   The answer is we do not know. The reason is because Pop() and ToString() are two separate instructions, which in multithreading allows for a context switch (a.k.a. change in thread being executed) to occur. Since there is no way to force a context switch to not occur*** we have to code against the situation of a context switch occurring, this is what @ErnieL's comments are saying.

We can actually improve DoStuffStack(int ctr) by protecting it a little bit.

Method 1

private static string DoStuffStack(int ctr)
{
    thread.Sleep(TimeSpan.FromSeconds(1d));
    // Pick which method you want to use. I realized the variable ctr is not being used,
    // and wanted to give it a chance to do something.
    const int value = StackLoopPoints[ctr];  // This way we always grab the intended item.
    const int value = StackLoopPoints.Pop(); // This way we grab an item in the list as long as the list has items.
    return " " + value.ToString();
}

Method 2

There are better ways of dealing with thread safety than this, but this is a basic technique for dealing with safely removing an item from StackLoopPoints.

static int currentLock = 0;
private static string DoStuffStack(int ctr)
{
    while(currentLock != ctr)
    {
        thread.Sleep(TimeSpan.FromSeconds(1d));
        // This may fail to work correctly.
        // So please, do not break out of the loop in the if block.
        if(currentLock != -1)
        {
            currentLock = ctr;
        }
    }

    int value = StackLoopPoints.Pop(); // We can't return without clearing our variable.
    currentLock = -1; // We have the value we need, and no longer require the lock.

    return " " + value.ToString();
}

*** There are cases where you can force a context switch to not occur, but that is a conversation for another time.


Basics

Aliases

PowerShell is meant to be both shell and programming language. As such, it has a concept of Aliases. An Alias is another name for a command. An alias can resolve to a cmdlet, a function, or even a native application. You can create your own aliases, but there are already many built in.

Aliases are great for quickly typing out commands in the shell or prototyping, but I and many others strongly believe you should avoid using them in scripts.

Try to use the full name of each command, as this can reduce ambiguity and increase code clarity.

In your script you only use one: select

This is an alias to Select-Object.

Parameters

Many (most) PowerShell commands accept parameters both as named parameters (MyCommand -ParamName ParamValue) and positional parameters (MyCommand ParamValue).

Similarly to the preference for using full command names, it is recommended to always use named parameters. In your script for example, so you are doing select logname, providername, timecreated (truncating the rest).

What you may not realize is that you are passing an array to a single parameter, and that parameter does in fact have a name: Property (the same is true for your first parameter to Get-WinEvent, whose first parameter in your case is called FilterHashTable).

Expanded out:

$events | Select-Object -Property logname,providername,timecreated

Although not in use in your script, you should be aware of the following:

Parameter names can also have aliases. So for example Get-WinEvent -ComputerName $comp could also be written Get-WinEvent -cn $comp. Aliases have to be defined; they aren't automatic.
Parameter names accept any unambiguous stub of the name. So, you can use a partial name, like Get-WinEvent -FilterH @{}. In this example, you can't use Get-WinEvent -Filter because there are also -FilterXml and -FilterXPath parameters, but you can do down to a single character as long as it's unambiguous for that command.

Both of these are good to know, but again should be avoided in scripts.

Format- commands

PowerShell makes heavy use of pipelines, but unlike most shells, PowerShell sends complete objects throughout its pipeline.

This is a great thing, and it's what allows you to do complex filtering and manipulation.

But when you see the output on the screen and it shows you a table or list of information, it's easy to think just think of it as formatted text.

PowerShell has Format- cmdlets that let you display information explicitly the way you want (since normally the host chooses a format based on the data types or amount of information).

Here's the really important thing to remember: Format- cmdlets are for end-result, final display only.

Once you send an object through a Format- cmdlet, it is no longer the original object; you've lost the original.

In almost all cases, it's best to send the original object, then let the caller or use decide what they want to do with it (whether it's format it, convert it to another data type, save is as a CSV, or whatever).

It's hard to tell what you want to do with the data in your script, but since you use Format-Table you've already excluded all of your other options.

Backtick ` as line continuation character

The backtick ` is the escape character in PowerShell. The standard backslash \ used in most languages is not used here because backslash is also the path separator on Windows, and since PowerShell is supposed to work as a shell and was born on Windows, this would be inconvenient. The backtick was chosen instead.

When you use backtick at the end of a line, you are in essence "escaping" the newline for the purposes of the parser.

The unfortunate thing is that the backtick is very small, and very difficult to see, so it can make things confusing.

I highly recommend that you avoid the backtick for line continuation at all costs.

Luckily, you do have some other options, as there are other points in commands and statements where you can start a newline without the need for any special character.

Pipe |

Since pipes are so common in PowerShell and you may be doing a pipeline that includes several statements, it's very useful to know that you can use a newline after a pipe (but not before). So the following works without any line continuation:

$events |
    Select-Object -Property logname,providername |
    Sort-Object -Property logname

(indentation after the first pipe is a stylistic choice, not at all required)

Operators

You can use a newline directly after an operator:

if ($var -gt 5 -and
    $var -lt 100) {
    # code
}

For long conditionals, this is essential.

ScriptBlocks {}

Any scriptblock is essentially a whole script, so you can use newlines liberally inside it, even if you were passing the scriptblock as a parameter. As soon as the scriptblock is opened, go for it!

Invoke-Command -ScriptBlock {
    # A whole new script here
    Get-Service |
        Get-Random |
        Stop-Service -Verbose -WhatIf
}

In grouping expressions () and sub-expressions $()

Using Grouping and Sub expressions even where not necessary can help if you feel the code needs better formatting. You can use newlines inside them as needed:

Get-Service -Name (
    'Win*'
)

Get-Service -Name (
    "Win$(
        '*'
    )"
)

Those examples are convoluted, but you get the idea.

In array/hashtable definitions @()/@{}

I use these a lot. Format as needed within these. Note that in a hashtable definition, if you are used to using semicolons ; to separate items on a single line (like @{ Key1 = 'val1' ; Key2 = 'val2' } the newlines take the place of the semicolon.

# Hashtable
@{
    Key1 = 'val1'
    Key2 = 'val2'
}

# Array
@(
    1,2,3
)

@(
    1,
    2,
    3
)

@(
    1 ,
    2
    ,3
) # why oh why

# my preferred (long) array style:
@(
     1
    ,2
    ,3
)

Combined:

@{
    Set1 = @{
        Arr1 = @(
             'A'
            ,'B'
            ,'C'
        )

        Arr2 = @(
             1
            ,2
            ,3
        )
    }

    Set2 = @{
        Scalar = 10
    }
}

In a command:

Get-WinEvent -FilterHashTable @{
    logname = $logs
    starttime = $yesterday
    level = @(
         2
        ,3
    ) # I wouldn't expand the array like this for 2 elements, just an examples
} -ComputerName $comp

Errors and Exceptions

PowerShell has a concept of terminating vs. non-terminating errors. Different commands and different code determine whether an error stops execution or whether it just reports an error and keeps going. Most commands allow you to override whatever their default is with the -ErrorAction common parameter.

In your code, you are using try/catch, but you've added -ErrorAction Ignore to Get-WinEvent.

Errors that are non-terminating, which includes an error you've told PowerShell to ignore or ContinueSilently, will not trigger a try/catch, so I believe your catch block will never run even if there is an error.

Instead, you probably want -ErrorAction Stop, which is supposed to force all errors to become terminating errors, so that they do trigger the exception handling.

Truthiness and Falsiness

PowerShell tries pretty hard to convert or coerce values into the type that is required. In the case of a boolean value, like that used in an if statement, almost anything can be interpreted as true or false.

The following all evaluate to $false with no additional action or conversion needed:

$false
0
$null
Empty string
Empty array
Uninitialized variable (not the same as one containing $null)

Just about everything else, including, confusingly, an empty hashtable, is interpreted as $true.

So what does this mean for you?

if ($events.count -gt 0)

Can be reduced to:

if ($events.count)

Which could even further be reduced to:

if ($events)

This is useful to check for lots of things; return values of course, but also whether a parameter contains a value or is otherwise available.

Pipeline Output

When you do something like this:

"Some thing"

You're used to it showing up on the screen, so it's easy to think that this is the same as a sort of print statement (which in PowerShell would be Write-Host).

But that isn't what's happening; it's actually implicitly calling Write-Output, which sends that to the output stream.

If the output stream makes its way back to the host, then the host decides what to do with it; in the case of powershell.exe (or ISE) it decides to display it, but in the case of a function for example, this becomes part of the return value. In the case of a status message that's not really what you want.

Here's an example:

function Test-Output1 {
    "I'm returning 5"
    5
}

function Test-Output2 {
    Write-Host -Object "I'm returning 5"
    5
}

Now, if you run these directly:

Test-Output1
Test-Output2

You will see the exact same output. They are indistinguishable that way.

But try to assign the result to a variable instead:

$v1 = Test-Output1
$v2 = Test-Output2

Now, you will see the difference. Test-Output1 shows nothing on the screen. If you check the value of $v1, it will be an array, with 2 elements. The first element is a string (your message), the second element is the number.

Test-Output2 on the other hand showed a message anyway, and the value of $v2 is only the number.

That's the critical difference.

So even if you're in a situation where you can't see the difference, you should always be thinking about it. "Am I trying to show a message to a person on the screen, or am I trying to return a value to somewhere else in the program?"

Details

Ok, so now some stuff that actually has to do with the task you're trying to achieve!

Parameters

This is something of a general language element thing too, but instead of hardcoding variables at the top of your script, consider adding parameters to the script so that as a caller you can specify the values you want.

Let's look at replacing the first 3 lines of your script:

$computers = 'COMP1','COMP2','COMP3','COMP4'
$logs = 'Log1','Log2','Log3','Log4'
$yesterday = (Get-Date).AddDays(-1)

With this:

[CmdletBinding()]
param(
    $Computers,
    $Logs,
    $StartTime
)

Now, I renamed $yesterday to $StartTime so that you can specify the date you want when calling, so that variable would have to change, but the entire rest of your script would work the same. If your script is named Get-MyLogs.ps1 then you can call it like this:

.\Get-MyLogs.ps1 -Computers 'COMP1','COMP3' -Logs 'Log1','Log9999' -StartTime (Get-Date).AddDays(-1)

But maybe you almost always want to use "yesterday" and it's too annoying to enter that value every time. You can provide your parameter with a default value instead:

[CmdletBinding()]
param(
    $Computers,
    $Logs,
    $StartTime = $((Get-Date).AddDays(-1))
)

Now you can leave that parameter off, and it will use the default, but you can still explicitly set a value to override it. This gives you a great amount of flexibility, without having to edit the script, and it required almost no effort.

I didn't even go into adding data types to the parameters, validation, etc.

I will only add that there are some naming conventions you should follow for parameters.

Typically plural is not used, so even if you want to accept multiple logs, you would probably name that parameter $Log and not $Logs.

Accepting a computer name is common and the parameter is pretty much always called $ComputerName (again, even if multiple names are accepted). It's good to follow these conventions. You can add aliases to your parameters if you want to support non-standard additional names, but real name should generally follow convention when possible.

Parallelization

Right now, you go through the list of computers sequentially. For more than a few computers, this is going to be slow. If any of the computers are not available, and have to time out, it's going to be really slow.

Before going further, I'll just say this: if it's ok that it's slow, then stop here. Let it be slow. Sequential, non-parallelized code is easy to write, easy to understand. If this just runs as a background task or whatever, don't complicate it.

But if you want to check multiple computers at once, you can.

PowerShell sucks at this, but there are options.

The built-in ways on Windows are Workflows and Jobs.

Workflows are weird. They're a bit complicated, difficult to understand all the implications, and hard to find good help on, because nobody uses them. They are also not going to be included in PowerShell core since they only work on Windows so I don't recommend this. For very simple things, it might be a good way to go.

Jobs are supported through the *-Job* cmdlets, and the -AsJob parameter that's available on some commands.

Jobs actually run as separate PowerShell processes so they are a bit expensive in terms of start time and resource usage (especially with large numbers of them). Also because they are not in-process, any objects passed between them are serialized/deserialzed so some functionality may be lost.

If you start a scriptblock in a job, you then have a job object which you can wait on, check the progress on, and then when ready receive its output.

There are more advanced ways to do parallel workflows like runspaces, which you can do yourself, or use a library like Boe Prox's excellent PoshRsJob module.

I'm not going to get any deeper on this since I don't even know your intention and there's so much to write. If you try to parallelize this, try some stuff, try different methods, and use Stack Overflow as needed.

Conclusion

Despite my novel, your code is pretty straightforward. Without knowing how you intend to use the data it's hard to be opinionated on any deeper design changes, so clearly most of my suggestions are general language stuff.


Checking for required text fields for login

In my opinion the issue here is not the repetition of if else but the repetition of similar alert message code.

For example, you could continue using if else but without these repetitions:

guard let correoText = correoTextField.text, let contrasenaText = contrasenaTextField.text else {
    fatalError("The outlets are not properly connected")
}
var msg: String? = nil
if correoText.isEmpty && contrasenaText.isEmpty {
    msg = "CORREO Y CONTRASEÑA"
} else if correoText.isEmpty {
    msg = "CORREO"
} else if contrasenaText.isEmpty {
    msg = "CONTRASEÑA"
}
if let msg = msg {
    let alertMessage = UIAlertController(title: "Datos requeridos", message: "Favor de llenar todos los datos requeridos (\(msg)) antes de continuar", preferredStyle: .alert)
    alertMessage.addAction(UIAlertAction(title: "Aceptar", style: .default, handler: nil))
    self.present(alertMessage, animated: true, completion: nil)
}

But if you want to use switch, you can switch on a tuple representing the two booleans:

guard let correoText = correoTextField.text, let contrasenaText = contrasenaTextField.text else {
    fatalError("The outlets are not properly connected")
}
let msg: String?
switch (correoText.isEmpty, contrasenaText.isEmpty)  {
case (true, true):
    msg = "CORREO Y CONTRASEÑA"
case (true, false):
    msg = "CORREO"
case (false, true):
    msg = "CONTRASEÑA"
default:
    msg = nil
    // implement additional behavior, or add more cases
}
let alertMessage = UIAlertController(title: "Datos requeridos", message: "Favor de llenar todos los datos requeridos (\(msg)) antes de continuar", preferredStyle: .alert)
alertMessage.addAction(UIAlertAction(title: "Aceptar", style: .default, handler: nil))
self.present(alertMessage, animated: true, completion: nil)


Merge sort implementation weirdly faster than system sort

That's because your implementation is not correct. You have

private static void merge(Comparable[] a, Comparable[] aux, int low, int mid, int high) {
    int i = low;
    int j = mid;
    for (int k = low; k <= high; k++) {
        aux[k] = a[i];
    }
    for (int k = low; k <= high; k++) {
        ...

yet I believe you need:

private static void merge(Comparable[] a, Comparable[] aux, int low, int mid, int high) {
    int i = low;
    int j = mid;
    for (int k = low; k <= high; k++) {
        aux[k] = a[i++]; // <--- INCREMENT i
    }
    i = low; // <--- RESET i
    ...

The demonstration program is here.

The output is

Good Sort.
Time taken: 29846 for 10000000 elements.
Good.
Arrays.sort in 25226 ms.
true

Hope that helps.


I'm working on an RPG so of course I have to have some dungeons. I've got the dungeon generation working, with the output being a DungeonTileType[][].

Well there's your problem. To simplify eliminate the search, you should return something like this:

class Dungeon {
    DungeonTileType[][] tiles;
    MapPoint start;
    MapPoint end;
}

Think about it, you currently have some code that generates a map that you then search through the entire map to find out where you placed that one exit and that one start tile.

When you place the start and end tiles, you should save the position that you placed them at.

As for general two dimensional looping, I wrote a Iterator for looping through 2D arrays a while ago that you can use if you'd like.


I see that not specifying function parameters - which made it easier to deal with variable lengths of arguments

But it didn't really make it easier to deal with variable length args, as underscore's code demonstrates. It's true, though, that it makes it a lot easier to write the function definition without worrying about whether you should write function (start), function (start, end), or function (start, end, step)- but that's about it.

But regardless of how you write it in code document it.

Since JS doesn't really care too much about what you put in the args list, docs are the what you have to rely on.

Anyway, you can basically put whatever you want in the args list. But I'd lean toward following underscore's example, and write out the full list of arguments. Worst case scenario is that someone skips the docs, looks at the args list, and sees 3 arguments. So he/she writes calls the function with all of those argument, even though 1 or 2 would have achieved the same thing. But that's just fine. But if you don't write anything in the args list and don't provide docs, whomever wants to use your code (e.g. you yourself in 2 months) suddenly has to play JavaScript interpreter and read the code itself to figure it out. While that shouldn't take more than a couple of seconds it's still an annoyance.

Alternatively, you can do something like

function (start /*, [stop, [end]] */)

to clue a developer in on what the function expects. But that's still not a substitute for just documenting it well. Because even if you are looking at the function's code itself and figuring it out, you have no idea what arguments[1] might be, because there's nothing to indicate there even is a 2nd argument. You have to work backwards to understand it. Underscore has named arguments, that, even if they're undefined, just make the code itself a lot more readable right off the bat.

  underscore declares an Array literal with length. Is that necessary?

Necessary? No. A good idea? Yes.

By declaring the length right away, you save the computer the trouble of keeping up with a growing array. When you declare the length, the computer can start allocating the necessary memory right away, whereas if you build it up, it may have to allocate more memory for each push(), and copy chunks of memory around and similar busywork.

Will you ever notice the difference? Depends on what you're doing, but I'd say wager that no, you won't ever notice. But it's a pretty simple optimization to make, so why not? Not that this is something you have to always do when building arrays (and sometimes you just can't know ahead of time how big the array will get), but for a low-level function like this with potentially heavy usage? Yeah, might as well. It's still very readable, so it's a win-win, really.

Next up: Variables. Just declare your variables in one place - with sensible default values, if possible. You declare the same 4 vars in two different places. While it doesn't matter much, it's just basic code cleanliness to not repeat yourself.

Next up: The loop. You loop basically does this:

declare and initialize i
call comparisonTest with a couple of arguments

compare those arguments
return boolean

if returned value is false, exit the loop
if returned value is true:

append i to the array
increment i  by step

repeat

Whereas underscore's does this:

compare idx and length
if false, exit the loop
if true:

insert start at index idx
increment idx
increment start by step

repeat

Your way seems to save a variable (underscore has both idx and start), but it's a losing battle: underscore's way saves an entire function call for every iteration of the loop.

Calling that comparison function means duplicating 2 variables (the arguments) plus the whole rigamarole of setting up return address, switching to the function's context, setting up caller and callee, arguments and all the other stuff a JS runtime does when you shove something onto the stack. Then it does the same sort of thing again when calling push. Since push is a native function, the calling overhead is no doubt lower,  but there's still the aforementioned overhead of (potentially) having to reallocate memory for a bigger array and all that.

Oh, and the engine also has to create those comparison functions when you call range() (I'd wager this is also pretty well optimized, but worst case scenario is a lot of extra work on every call just to do a simple comparison)

It's naturally more efficient to just not do any of that, as in underscore's solution.

Now, let me just make it clear that you rarely need to care about all of this. Once you start micro-optimizing your code, it's a deep, deep rabbit hole to go down, and most of the time it really doesn't matter. You're just spinning your wheels. All of this stuff is worth being aware of, but don't go overboard. "Premature optimization is the root of all evil" as the saying goes.

So in the end, there's nothing really terribly wrong with your code at all, and I'm sure it can serve you well without any changes (except maybe some documentation). But it's of course hard to improve upon a battle-tested, built-for-speed library like underscore.


It looks like a nice implementation, but I don't think that using immutable.js is terribly necessary. JS already has a Map, which, while not immutable, could work too. However, a plain object might also be enough.

The slightly ironic bit is that despite choosing to use immutable data structures, your function actually has side-effects: sort modifies the receiver in-place, meaning that the d argument is mutated as a side-effect.

Inside the function itself, i.e. for local variables, I'd be less concerned about mutability. So for instance, a vanilla-JS solution using a plain object (since Map's API of get/set gets tiresome in a hurry) could be:

const coinChanger = (denominations, amount) => {
  return denominations
    .slice() // copy array before sorting
    .sort((a, b) => b - a)
    .reduce((result, value) => {
      result.coins[value] = (result.remainder / value) | 0; // bitwise trick to floor the result
      result.remainder %= value;
      return result;
    }, { remainder: amount, coins: {} });
};

Edit/sidenote: The | 0 trick, while neat, does have some very notable limitations. See the comments for a discussion (thanks, Thriggle!). Essentially, all numbers in JS are 64-bit floats, but behind the scenes, bitwise operations are performed on 32-bit ints. So the trick causes an unsafe cast to int, performs a pointless OR'ing with zero, and casts the result back to a float. So again: It's a trick. Here, given a large enough  amount value, you will get weird results. So use with caution.

I've simplified it somewhat (removed the coinCounter function), and yes, the memo object for reduce is mutated. The effects are however contained within the reduce call, so... eh. The coin denominations are also coerced to strings when used as keys in the object, which a proper Map wouldn't do, but the coercion works both ways, so the keys can transparently be used as numbers later.

Of course, once the object is returned, only the caller holds a reference, and then it's the caller's responsibility – so that's where an immutable data structure might be better. But for the purposes of a quick alternative implementation, I'll leave things as-is.

Style-wise, your code looks fine. You're missing a semi-colon after sort (JS mostly works without semi-colons, but it looks like you're using them elsewhere, so stay consistent), and you could do with a little more whitespace here and there, but otherwise it's pretty good.

The only thing to wag a finger at, which Fanis Despoudis pointed out in a comment, is that d and m should be spelt out, rather than be explained in a comment. Especially because they're arguments, and they form the interface of the function, they should be readable. In general, all names should of course be clear and descriptive, but parameter and function names should be especially easy to parse, as that's what others will see first and make use of.


Fastest way to extract n bytes from uint8_t buffer

Since you want low level operations, I'd suggest memmove

#include <time.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>

static uint32_t get_data(uint8_t *buf, size_t off)
{
    return ((uint32_t)(buf[off + 0]) << 24) +
                  ((uint32_t)(buf[off + 1]) << 16) +
                  ((uint32_t)(buf[off + 2])  <<  8) +
                  ((uint32_t)(buf[off + 3]));
}

int main(int argc, char **argv)
{
    uint8_t buf[128];

    /* get some example data */
    for (uint8_t i = 0; i < 128; ++i)
        buf[i] = i;

    clock_t t = clock();
    uint32_t res;
    for(int i=0; i<10000; i++)
        memmove(&res, buf+10, sizeof(uint32_t));
    t = clock() -t;
    printf("Time %lf\n", (double)t/CLOCKS_PER_SEC);

    t = clock();
    for(int i=0; i<10000; i++)
     res = get_data(buf, 10);
    t = clock() -t;
    printf("Time %lf\n", (double)t/CLOCKS_PER_SEC);
}

Because a single copy doesn't show any difference I tried with 10.000 and my results were:

Time 0.000049
Time 0.000090

Almost double the speedup

EDIT 1: As mentioned in the comments, memcpy is a viable alternative
to memmove.
EDIT 2: The speed difference in this example cannot be
observed with -O flag as the compiler executes the loop only one
time.