Am I over-reacting with my page SESSIONS security?

1) Overreacting is a question of how valueable your protected information is. My personal oppinion is that by the nature of digital computers and of the internet there is no such thing as overreacting in security. You either want something to be public or you do not, and in the latter case there is quite a bit of work and knowledge involved to counter all the different attacks. On the other hand, a lot of other people will say that if your protected information is not really valueable enough to hackers, then probably no hardcore hacker will invest enough time so your protection might not worth your programming efforts.

2) In the code above you build your fingerprint by hashing a concatenation of different information about the remote user and the token is used as a kind of salt (in addition to 'SECRET-SALT') to make that hash unique. So the answer depends on how secure is your session storage.

If you are alone on the server or you have a secure session storage for $_SESSION (like a password-protected database), then you do not need to worry about someone reading the contents of your session variables. This also means that protecting your fingerprint by hashing it is absolutely useless, in which case you can just remove the token and hashing from your code completely. In this case you also do not need a fingerprint, you can just store the user variables separately and compare them separately.

If there is a way for your $_SESSION contents to leak, then you want to protect private information in it. In this case you will want to keep your token private and do not send it to the user, put it into login.php instead. Normally, you do not have to worry about protecting a salt because even if it is known it will increase the time considerably for a hacker to crack a password, not just because of the longer password string but also because precomputed rainbow tables become useless. But in your case you do not have a password, all you have is the user_agent and the IP, both of which are easily predictable or sniffable. This means that the concatenated information is basically no variable to the hacker, so the only thing keeping him from cracking your fingerprint are your salts. So if you reveal them, the hash becomes useless.

To sum it up: If you want maximum securty in all situations, keep fingerprinting and hashing, but since your protected string is easily guessable, keep your token private this time. Theoretically even if your token is compromised 'SECRET-SALT' will still provide protection, but only as long as your code is safe. If your filesystem is hacked or the sources for the website your are building are public you cannot rely on 'SECRET-SALT' alone. Do not depend on hiding it, 'security by obscurity' is a bad practice.

3) Generally you should not depend on the IP to stay consistent across a session. This is because for a lot of legitimate users the IP can keep changing constantly, this can be because they are behind corporate load balancing, they are using AOL or some other proxy network. A possible solution is to observe the IP of a session and if it is consistent for, say, 10 pages, then it is reasonable to assume that it will stay consistent in the future. So only then will you start making checks on it. However, storing it temporarily in a DB can still be of use, eg. for logging so that it can be analyzed what happened if there is an attack or so.


Optimizing PowerShell string hasher method

In general I don't really see the value in not defining an XSD or DTD and validating against that when loading it with an XmlReader, which feels most correct. You should be able to instance one XmlSchemaSet and compile it. Then that can be repeatedly used to validate the documents without reloading the schema, and that should perform well. That feels like the most correct solution. If you want valid data the most correct thing to do is to validate it. That covers every situation where your goal is to have valid data.
What you're doing here just feels like a home grown XML digital signature, so your method just raises conceptual concerns to me. If I were to look at what you're doing, I'd be confused by what you were trying to accomplish.
If you just want to be able to verify what files you've previously validated, I'd prefer just maintaining a CSV file or database with the output of Get-FileHash and some file metadata. That seems much less complicated and doesn't require modifying the XML files.

However, taking the code as face value, you may see some performance improvement like this on the first method:
static [String] GetHash ([Xml.XmlDocument]$xmlDocument) {
    $stringBuilder = [System.Text.StringBuilder]::new(32)

    $hashBuilder = [System.Security.Cryptography.HashAlgorithm]::Create('md5')
    $xmlToHash = [Xml.XmlDocument]::new()
    $xmlToHash.AppendChild($xmlToHash.ImportNode($xmlDocument.DocumentElement, $true))
    $hashBuilder.ComputeHash([System.Text.StringBuilder]::UTF8.GetBytes([pxXML]::ToString($xmlToHash))).ForEach({
        $stringBuilder.Append($_.ToString('x2'))
    })

    return $stringBuilder.ToString()
}

When you know the length of the StringBuilder you can instance it with that initial capacity. MD5s are always 32 characters. That saves having to expand capacity.
The ComputeHash() method is an inherited method from the HashAlgorithm class. You don't gain anything by instancing a more complex child class because you don't use it for anything else. You're just calling a hash function; there's nothing inherently cryptographic about what you're doing.
The .ForEach({}) collection method is somewhat higher performant in most cases, although it makes for less readable code and is more obscure.
Eliminating variables that are only used once also tends to improve performance. Indeed, you could also just call [System.Security.Cryptography.HashAlgorithm]::Create('md5').ComputeHash(...), but it's getting a bit hard to read on StackOverflow.
Offhand, I'm not sure if $stringBuilder.AppendFormat('{0:x2}',$_) is better or worse than $stringBuilder.Append($_.ToString('x2')), but I believe the latter is better here.


Prevent recursive calls in WinForm event handlers

You can improve the EventHelper by reusing the sender argument so that you have only a single instance of the helper. The helper maintains a HashSet<object> that stores senders that are currently handled. This will allow you to use the return value of the Add method which is false if the sender already has been added an thus acts like your skip variable. Finally you Remove the sender from the set as if you were setting skip to false.

public class EventHelper
{
    private readonly ISet<object> _senders = new HashSet<object>();

    public void ExecuteOnce(object sender, Action action)
    {
        if (!_senders.Add(sender))
        {
            return;
        }

        action();
        _senders.Remove(sender);
    }
}

You would now call it with one more parameter:

eventHelper.ExecuteOnce(s, () =>

As far as the code is concerned you should always use {} and perhaps parameter names longer then a single letter f.


Unit Testing Express Middleware That Verifies Auth Tokens

I only looked at the tests briefly, but they look good and I like your approach

The following changes will help the readability of your main code:

Prefer early returning guard clauses over if/else.  It's easier to follow, uses less code, and avoids a level of indentation.
Name concepts clearly and move them to helper functions, so that your main body expresses its intent better: see notAuthorized()
Arguably a personal preference, but consider it: For short, one-line if statements, don't use brackets and put them on a single line.

Rewrite (note this hasn't been tested, so it's possible there are trivial errors):

module.exports = {
  ensureAuthenticated: function(req, res) {
    return new Promise(function(resolve, reject) {

      // Use guard clause rather if / else
      const token = req.query.token;
      if (!token) return notAuthorized();

      jwt.verify(token, "secret", function(err, decoded) {

        if (err) return notAuthorized();
        req.user = decoded;
        resolve();
      });

    });
    function notAuthorized() { return reject({ status: 401}) }
  }
};


It looks ok at first glance (proper use of camelCase and PascalCase, proper indentation, etc.), but there are some issues when you dig a little deeper.

You have a bug: Because you define a book's ID as simply books.length, and because you set the ID in the constructor, you're assuming/relying on every book instance to either be added ("saved") immediately after instantiation or discarded forever.

If I were to do this:

book1 = new Book({ ... });
book2 = new Book({ ... });

I get two books with the same ID. Of course, id is just another property, but in this case, I think it's safe to assume that it's supposed to be a unique ID.

For now, you could simply move the assignment of a book's ID to the save method, so it only gets assigned there.

However, if you ever add the ability to delete books, you'll run into trouble again, since removing something from the array would change its length, and you'd end up with multiple books sharing the same ID.

Perhaps the simplest thing would be to declare yet another closure variable (aka a private, static variable) simply called nextId or something. Then, whenever a book is saved, give it that value as its ID, and increment nextId. Same basic principle as auto-incrementing IDs in a database.

Of course there's still the caveat that anyone can just change a book's id property to "monkey" after the fact, but one step at a time.
How can anyone change the ID after the fact even with the extra precautions I mentioned? Well, if I call Book.find with no conditions, I get a reference to an otherwise private variable: books. Then I can do whatever I want with its contents. If I call it with some conditions, I don't get the books array itself, which is good, but I still get some of the same book objects that books holds. So again, I'm free to do what I want.

More simply, though, I can just alter the instance I created after it was saved since save just does books.push(this). So I can do this:

var book = new Book({title: "War and Peace", author: "Leo Tolstoy", genre: "novel"});
book.save();
book.id = "monkey"; // cue mischievous snickering

The book instance I changed after saving is the same instance the books array holds a reference to, so the damage is done.

Of course, right now, I could also just set book.id before saving, and achieve the same, since save doesn't care what it's stuffing in the array.

Also, if I do this:

var book = new Book({title: "War and Peace", author: "Leo Tolstoy", genre: "novel"});
book.id = "monkey";
book.save();
book.save();
book.save();

I end up with three identical books in the books array, all of which have the ID "monkey". It's not even that it's three copies; it's the same exact object appearing three times. Hmm....
You have another bug: Book.findById assumes it always finds something. When it doesn't, the script breaks because it calls cloneBook(undefined).
The description is fixed once defined, so changing, say, the title doesn't update the description. Description would be better off as a method.
The assert module isn't really necessary. I'd rather see the constructor throw a more specific exception of some kind (you can throw anything in JavaScript, so the "exception" can just be a string to start with). Also, your message says "cannot be undefined", but assert.ok just checks for general thruthiness, not undefined specifically. So it'll balk at false, 0, NaN, "", and null as well as undefined. Most of those are fine to complain about in this case, except maybe the empty string (maybe you don't want to put a genre in there, but still want a book instance). Besides, checking for thruthiness still doesn't check for type. So the title could be an array, the genre could be a Date object, author could be Number.NEGATIVE_INFINITY etc... However, that's simply the nature of dynamic typing, so it's up to you how far you want to go.

Still, it might be more beneficial to move the validity checks to the save method. Right now, you can't make a "blank" book by saying new Book; you have to know most of its details ahead of time.

... which begs the question: If you have all the details in an object already, do you need to make a Book out of em? Eh, this is an exercise, so I'll just go with it.
Why the callbacks? None of what you're doing is asynchronous, and JavaScript is single-threaded. So you can just return. It'd make the API a lot simpler. I suppose it's because you're mimicking Mongoose and its functions are asynchronous, but still. It's a little too cargo cult'y. (Note that using callbacks allows for really neat stuff, and learning to work with asynchronous JavaScript is a worthy goal; in this case, however, it complicates matters.)
The idea of returning a clone from findById to keep some properties "safe" is fine in and of itself. However, because you've hardcoded which properties are editable, it's not great for maintainability.
Why bother with the areNoConditions function? For one, it's a really odd name, but it also just wraps a single condition you might as well do inline.
Why not use filter in find?

Long story short, there are some issues here, but for a learning exercise it's not too shabby! You just have to decide how far you want to go with it, because a large portion of this seems to be about controlling access to properties. But that's kinda hard to do really well in JavaScript. Mongoose is forced to do all those things, but it's not the "path of least resistance" in JavaScript. Hence, it may not be the best thing to mimic.

You can "sort of" do strictly typed, access-controlled stuff in JavaScript. But unless you really need to, why bother? It's going against the grain, and often just encourages headaches.

By the way:

  // private static variable (why this exhibits static behaviour, I have no clue)

Because it's a closure. All the functions defined while it's in-scope will retain a reference to it. So while you return the constructor function, that function still has access to books.


Here's my thoughts.
Profile Model
I'm not sure that the separate profile is pulling enough weight to justify its existence. It seems that a lot of this code could be avoided by collapsing it into the User model. I appreciate that the User and Profile can be two separate entities but it looks like it'll be much easier to keep them in one model until they grow too large to be viable, or there comes a time when a Profile has a separate lifecycle from a User.
Which then avoids your question around SRP altogether :)
But if we were to keep them separate, I don't think it would be a practical violation of SRP because your application likely depends on a profile always existing for a user. So having asserted that User should always have a Profile, you are then faced with the choice of leaving the creation in the hands of the controller, or the model. I favour leaving it in the hands of the model because the model is responsible for modelling the relationships between different business objects.
Finding the Profile and Validating Access
You could replace the find methods with a before_action that uses the user's relationship with the profile like so:
before_action :get_profile, only: [:edit, :update]

def get_profile
   @profile = current_user.profile
end

This will both reduce the amount of code required to select the profile, and ensure that the user can only access their profile to edit/update it.
However, at that point it doesn't make sense to have the profile edit and update actions available with a user ID. They're essentially now singular resources and should be handled accordingly in your routes.
You ask whether find by user_id or not is a good choice. It depends on whether the person accessing that route will be accessing it from the context of its User, or the Profile owner.
current_user?
I don't believe this code will work. You are passing it only Profile objects, and comparing it to the current_user method which returns a User object (or null if not logged in, if memory serves). This should always return false. You either need to call profile.user before passing it to the method, or have that method make the call.


C# calculate total time worked with TimeSpan

Why does your code pointlessly reinvent the wheel? Microsoft provides methods to convert strings to DateTimes; why not use those instead of your own clunky GetNumberOfMinutes? Or perhaps even better: convert the string directly to a TimeSpan.

On the subject of GetNumberOfMinutes: why even do string sh = result[0].ToString();? The result of spring.Split is an array of strings, why then the need to convert a string to a string? And that's just one of the things that are wrong with that method, there are several more.

The whole flow of your code is IMHO needlessly complex. Why not simply convert each time to a TimeSpan, thus getting a List<TimeSpan>, then calculate the amount of minutes, add those up, and then convert those to a "readable" format?

I don't even understand why you do this: ((int)ts.TotalHours).ToString() + ts.ToString(@"\:mm");. Surely this can be expressed much more elegantly and readable.

On a general note: use proper, self-explanatory names for your variables, and not ts or sh etc.


Read hex from file and convert to decimal

Python 3

The script currently does not work in Python 3. For example, print "converted =" + str(converted) is invalid syntax in Python 3, use print() instead (as a function).

Comments

It's great that you document the code. Some comments however don't add any value for future reading: #this took me a few hour to figure out a bug. Thanks to stackoverflow. I have no idea what the bug is, and what the answer from StackOverflow was.

Try to use docstrings as well. For instance in the hex2dec function:

def hex2dec(hex):
    """Convert a hexadecimal string to a decimal number"""
    result_dec = int(hex, 0)
    return result_dec

Some other things about the above function:

Rather than hex2dec, perhaps use hex_to_decimal. In this case it's not too big of a deal though.
You're storing the result in a variable and then returning the variable without doing anything else to it. This means you could also return result immediately: return int(hex, 0)
Since it's using a built in function without any other operation, is the function necessary?

Running it!

As said above, using Python 3 failed to run it. Changing the print statements to functions fixed this issue. Python 2 also supports the print() function, so it should have no issue running on Python 2 as well.

The program ran as expected with a correct file, and produced an output file with the converted values.

Running it with an invalid file, or no arguments at all, crashes the program with either a FileNotFoundError or ValueError respectively. If a file was given which exists but has an invalid hexadecimal value in it (for instance a random string), the program also crashes:

Traceback (most recent call last):
  File "hex2dec.py", line 22, in <module>
    converted = str(hex2dec (i))
  File "hex2dec.py", line 7, in hex2dec
    result_dec = int(hex, 0)
ValueError: invalid literal for int() with base 0: 'random word'

The above errors tells us we need some error checking.

The first error to solve would be the ValueError of not giving a filename as argument when running the program. This can be solved by using a CLI module such as argparse, click, or perhaps another one you like. I personally use argparse, since it's pretty simple and it's part of the standard library.

The arguments:

import argparse

def get_cli_parser():
    parser = argparse.ArgumentParser(description='Describe what your program does')
    parser.add_argument('input_file', type=str,
                        help='The file to read the hexadecimal values from'
    return parser

if __name__ == '__main__':
    parser = get_cli_parser()
    args = vars(parser.parse_args())

At this point you can access the command line arguments args as a dictionary.

The if __name__ == '__main__': part of the code is only applicable if it's run as a script. This means that if the file is imported as a module, this will not run. See also this answer for more info.

When we run the above code without any arguments, we get the following:

usage: hex2dec2.py [-h] input_file
hex2dec2.py: error: the following arguments are required: input_file

Next up is the FileNotFoundError. This one is quite easy to solve: before opening the file, check if it exists using the already imported os module:

if not os.path.exists(args['input_file']):
    print('Input file does not exist, please try again')
    return

The last ValueError can be solved in a number of ways. One would be to use regex on the current line of the file to find any hexadecimal values. Assuming only the hexadecimal values should be on a line, it becomes a lot simpler though. We could just check if the line starts with 0x (e.g. a hexadecimal value).

Reading the file should also be done line by line as an iterator, to prevent huge files from crashing your program by too high memory consumption. Right now the program reads all the text in the file into memory. This can be done as described in the following question:

with open(input_file) as input_file:
    for line in input_file:
        # rest of code here.

Placing this in a function of its own also prevents you from opening the file continuously.

The final product

import argparse
import os

def write_and_print_result(args, result):
    """Write every result to the output file
    and print each converted value
    """
    out_file = args['input_file'][:-4] + "_1.txt"
    with open(out_file, 'a+') as output:
        for converted in result:
            output.write(converted + "\n")
            print('Converted: {}'.format(converted))

def read_and_convert_file(args):
    """Read the given input file and convert each hexadecimal value
    to decimal value
    """
    result = []
    with open(args['input_file']) as input_file:
        for line in input_file:
            if (line.startswith('0x')):
                result.append(str(int(line, 0)))
    write_and_print_result(args, result)

def get_cli_parser():
    parser = argparse.ArgumentParser(description="Describe program here")
    parser.add_argument('input_file', type=str,
                        help='The file to read the hexadecimal values from')
    return parser

def cli_runner():
    parser = get_cli_parser()
    args = vars(parser.parse_args())

    if not os.path.exists(args['input_file']):
        print('Input file does not exist, please try again.')
        return

    read_and_convert_file(args)

if __name__ == '__main__':
    cli_runner()

As you can see, most of it is either error checking or command line arguments. The actual conversion is only one line of code.

What's next

One issue I still found:

If the input file is anything but *.txt, the output file might have a weird name. For example, a file called hex would simply become _1.txt, which isn't very descriptive. To fix this, as pointed out by @Mathias Ettinger, you could use os.path.splitext. It is used as such:

filename, extension = os.path.splitext(args['input_file'])
outfile = filename + "_1.txt"


How to improve code structure and architecture?

Three suggestions...

1. Recognize your code's logical concepts and do so as idiomatically as possible.

For example, the make_block and make_genesis_block seem to both be making a block. Here making-the-block is the concept.

You can more idiomatically recognize this make block concept via parametric polymorphism. 200_success suggests this via renaming make_genesis_block so it has the same name as the other block making function: make_block. And then having the genesis making block function take no arguments.

Now you have two make_block functions which the compiler distinguishes by the parameters (ADL):

Block make_block();
Block make_block(std::string const& data, sha_t const& prevBlockHash);

2. Recognize your code's structural invariants, and then enforce those using encapsulation.

Take the Block class for instance. I'd guess that the hash field is dependent on the data field. If correct, then make these inter-dependent fields private. Provide accessor methods for these values and a mutator method for the data field which updates the hash.

If nothing else depends on the data or hash fields, then I'd suggest making this tuple of info its own class and put the encapsulation within it. Then compositionally incorporate this new class into your block class. This way Block can still be a struct with its members publicly accessible.

Use Non-Member functions unless the function needs direct access to the representation of a class (C.4). For my favorite explanation of what I'm suggesting here, please see Scott Meyer's article: How Non-Member Functions Improve Encapsulation.

3. Prefer value semantics over reference semantics.

You haven't shown any code which exemplifies reference semantics but for the sake of C++ developers everywhere (or at least for my preference), please keep with value semantics as long as you can: don't expose to your API any classes that inherit from other class (see inheritance is the base class of evil).

How to improve performance? Use constexpr or something else?

Setup a benchmarking system for your code for the platforms you need the performance on.
Make sure to compile your code with the highest available optimization settings turned.
If your compiler will take profiling data for optimizing code, give it that too.
Understand the difference between return value optimization (RVO) and named return value optimization (NRVO).
Understand how RVO and NRVO fits in with copy elision and when you're guaranteed copy elision (not until C++17).

As an example of NRVO vs. RVO, your first make_block definition does:

Block block{timestamp, d, prevBlockHash, sha_t(), 0};
return block;

Here block is a named return value. This can be rewritten instead as:

return Block{timestamp, d, prevBlockHash, sha_t(), 0};

Which is an anonymous/unnamed return value.

While your question is tagged C++11, I'll opine that it's a nice practice still to be aware of the newer standards and that with C++17 you're guaranteed copy elision. I suspect that compilers of earlier standard implementation are also likely more able to support copy elision when using unnamed return values. Copy elision tends to help with performance.

Moreover, returning output through return values encourages value semantics, aids with constness, and I find it makes it easier for people to reason about the code.

As to constexpr, I haven't seen it increase performance much of code I've used it with. OTOH, I love what recognizing code as constexpr means — computable at compile time — and I agree with Scott Meyers recommendation: use constexpr whenever possible (from Item 15 of his Effective Modern C++ book). A related nicety IMO is that types having constexpr constructors can then satisfy the LiteralType concept.

How to store the data that all are byte arrays, but some of arrays have fixed length (such as SHA256 hashes), and some have dynamic size (such as data)?

I like how you've already done this — you're using std::array for the fixed length types, and std::vector for the dynamic types. It's a preferable starting point so long as these types' access don't allow your data invariants to be violated.

Prior to C++17, you may just want to update the type you're using in the std::array and std::vector containers to std::uint8_t. Since C++17, we can use std::byte for this type as one of the commentators suggests.

Deeper in, you may need to answer whether speed is more important or data correctness is. A structure of arrays (SOA) often lends itself better to speed, while an array of structures (AOS) can lend itself better IMO to correctness.

How to pass empty byte array? sha_t() is ok?

It's not clear what you're asking with this question. Sounds like you may want to read about value initialization (introduced in C++03).

How to deal with time and make code short and fast?

Seems like this question is asking again about how to improve performance. If so, please see my response in that section.

What SHA256 library should I use?

The code from the most recent OpenSSL library is what I'd go with just simply because I suspect it's had the most eyes on it. If your code is license compatible, you may find it easier to just copy the OpenSSL code for SHA256 into your code instead of trying to build the entire OpenSSL library and then linking with it.


It depends if this is for OOP or procedural code.  I am assuming OOP as you use class in some of your file names.

Procedural

If this is for procedural code then it should be renamed to load as there is nothing auto about it (see the OOP review).

OOP

If this is for OOP then it is not a good option. spl_autoload_register to register a standard autoload function is better.

Your Solution

There is a hardcoded entry that needs to be maintained for each class that you want to include.  This does not scale well with hundreds or thousands of entries to look through.
If the value is not recognized you ignore it silently because you don't have a default entry in your switch statement.
You have to manually autoload the classes that you want (this takes the auto out of autoload).

Advantages of spl_autoload_register

spl_autoload_register is a true automatic loader.

// We just need one call to register an autoload function, this registers the
// autoloading for the lifetime of the program.
spl_autoload_register();
$exampleObject = new Example_Object;

// In the file autoloaded for class Example_Object:
class Example_Object
{
    // Type hinting works to load the class for Another_Object.
    public exampleMethod(Another_Object $another)
    {
        // Autoloading works here too.
        $lastObject = new Last_Object;
    }
}

The autoloader only needs to be registered once and continues to load files for classes right throughout the program.

A stack of autoload functions can be provided allowing for flexibility in the logic used to load classes.
Because files are loaded lazily only what is required is loaded no matter how much you edit the other files.
Using logic to load your class files helps you to organize them logically.  It makes your logic simpler if you name your class files logically. This helps when you have hundreds or thousands of files that have been named in a consistent manner.

What not to use an autoloader for

An autoloader is for loading the file needed to define a class. You should not use it to load functions or templates.  These should still be included manually.


Concatenate function arguments with "AND" string if they're not None.

Concatenating strings with a common connector (such as ' AND ' here) is most idiomatically done using join. So the idea should be to:

return ' AND '.join(<some list with the right `text:value` formatting>)

The easiest way to get such list should be to pair the text part and the associated value using zip and then use a list comprehension to filter out undesired variables:

parameters = zip(
    ('host', 'app_name', 'instance', 'config_source', 'config_name'),
    (host, app_name, instance, config_source, config_name)
)
query = ['{}:{}'.format(text, value) for text, value in parameters if value is not None]
return ' AND '.join(query)

You can also simplify a bit by turning the list-comprehension into a generator expression and feeding it directly to join.

Lastly, the self parameter suggest that you are using this as a method of a class. But since you are not using self in the method, you should either make it a regular function or a saticmethod:

@staticmethod
def _get_query_string_for_get_config(host, app_name, instance, config_source, config_name):
    parameters = zip(
        ('host', 'app_name', 'instance', 'config_source', 'config_name'),
        (host, app_name, instance, config_source, config_name)
    )
    return ' AND '.join(
        '{}:{}'.format(text, value)
        for text, value in parameters
        if value is not None)


I would improve on handling class attributes. They are multi-valued attributes per definition and your way of checking the class values in the XPath expressions can potentially cause problems.

For instance, @class='productPreview  ' check would fail if there will be one space less at the end of the value. Or, you would also match an element with class="showImageDescription" with the contains(@class,'showImage') check.

One way of dealing with that is to use this workaround which involves using concat().

I would though simply switch to CSS selectors which are generally faster, more concise and handle class attributes naturally:

Set posts = driver.FindElementsByCss("li.productPreview")
On Error Resume Next
For Each post In posts
    i = i + 1
    Cells(i, 1) = post.FindElementByCss("h4 > a").Text
    Cells(i, 2) = post.FindElementByCss("span[class^=ProductPrice__price]").Text
    Cells(i, 3) = post.FindElementByCss("img.showImage").Attribute("src")
Next post

Note the span[class^=ProductPrice__price] selector - I don't think the ___3BmxE part of the class matters much and provides any relevant information - plus, it sounds like a good subject for a change. That's why I've switched to a partial match with "starts with" (^=).


Seems to be swatting a fly with a Buick to me. The first form seems pretty concise and the variable names are quite descriptive. The second form creates a new object (the array) which will eventually have to be GC'd and introduces a new lambda variable, c which doesn't seem descriptive any more.


Find the shortest whole repetitive substring

Why not use a regular expression?

>>> import re
>>> len(re.match(r'(.+?)\1*$', 'catcatcat').group(1))
3

This has runtime \$Θ(n^2)\$, same as the code in the post, but it's a lot shorter.


Binary heap (priority queue) implementation in JavaScript

Big f...reakin' bug:

GZKM.Heap.prototype.pop = function() {
    if(!this.arr.length) return undefined
    this._swapNodes(this.arr[0], this.arr[this.arr.length-1])
    var ret = this.arr.pop()
    this._moveDown(this.arr[0])
    return ret
}

After this.arr.pop() the array may very well be empty, and _moveDown is not prepared to being called with undefined, so we will get an exception here. I really thought the tests would cover this...well, they didn't.

Fixing this seems simple though:

if(this.arr.length)
    this._moveDown(this.arr[0])


This is an ugly old pattern. Why don't just try the newer async/await? You already use Task in your tests anyway.

In order to implement it the awaitable way you just need to use a different API, in this case AcceptTcpClientAsync and build everything on top of it. With the CancellationToken you can now better control the server.

public class TcpServer : IDisposable
{
    private readonly TcpListener _listener;
    private CancellationTokenSource _tokenSource;
    private bool _listening;
    private CancellationToken _token;

    public event EventHandler<DataReceivedEventArgs> OnDataReceived;

    public TcpServer(IPAddress address, int port)
    {
        _listener = new TcpListener(address, port);
    }

    public bool Listening => _listening;

    public async Task StartAsync(CancellationToken? token = null)
    {
        _tokenSource = CancellationTokenSource.CreateLinkedTokenSource(token ?? new CancellationToken());
        _token = _tokenSource.Token;
        _listener.Start();
        _listening = true;

        try
        {
            while (!_token.IsCancellationRequested)
            {
                await Task.Run(async () =>
                {
                    var tcpClientTask = _listener.AcceptTcpClientAsync();
                    var result = await tcpClientTask;
                    OnDataReceived?.Invoke(this, new DataReceivedEventArgs(result.GetStream()));
                }, _token);
            }
        }
        finally
        {
            _listener.Stop();
            _listening = false;
        }
    }

    public void Stop()
    {
        _tokenSource?.Cancel();
    }

    public void Dispose()
    {
        Stop();
    }
}

EventArgs as a nested class, no no no ;-)

Test

The old test won't work anymore as now you need to make everything async/await.

the event handler now becomes async (sender, e)
Thread.Sleep is now await Task.Delay(3000);
the server needs to run async so you need a Task.Run(async () => {..}
at the end you wait for the server with await serverTask;

I used the console for output as I run this in LINQPad and added the thread-id so to see where it runs.

using (var server = new TcpServer(IPAddress.Any, 54001))
{
    server.OnDataReceived += async (sender, e) =>
    {
        var bytesRead = 0;
        do
        {
            // Read buffer, discarding data
            bytesRead = e.Stream.Read(new byte[1024], 0, 1024);
        }
        while (bytesRead > 0 && e.Stream.DataAvailable);

        // Simulate long running task
        Console.WriteLine($"Doing some heavy response processing now. [{Thread.CurrentThread.ManagedThreadId}]");
        await Task.Delay(3000);
        Console.WriteLine($"Finished processing. [{Thread.CurrentThread.ManagedThreadId}]");

        var response = Encoding.ASCII.GetBytes("Who's there?");
        e.Stream.Write(response, 0, response.Length);
    };

    Task.Run(async () =>
    {
        var serverTask = server.StartAsync();

        var tasks = new List<Task>();

        for (var i = 0; i < 5; ++i)
        {
            tasks.Add(Task.Run(() =>
            {
                var response = new byte[1024];

                using (var client = new TcpClient())
                {
                    client.Connect("127.0.0.1", 54001);

                    using (var stream = client.GetStream())
                    {
                        var request = Encoding.ASCII.GetBytes("Knock, knock...");
                        stream.Write(request, 0, request.Length);
                        stream.Read(response, 0, response.Length);

                        //Assert.AreEqual("Who's there?", Encoding.ASCII.GetString(response).TrimEnd('\0'));
                        Console.WriteLine($"Who's there? Echo: " + Encoding.ASCII.GetString(response).TrimEnd('\0') + $" [{Thread.CurrentThread.ManagedThreadId}]");
                    }
                }
            }));
        }

        //Assert.IsTrue(Task.WaitAll(tasks.ToArray(), 10000));
        Console.WriteLine($"IsTrue: " + Task.WaitAll(tasks.ToArray(), 10000));

        await serverTask;
    });

}


As others have commented, it's not clear what your performance issue is currently and what your performance target is, but the function could certainly be rewritten to be more concise and use only a single "loop", like this:

func split<T>(array:[T])->(real:[T], imag:[T]) {
    // I didn't include your guard because it wasn't necessary for safety in this implementation, but you could include it here if you wished.
    return array.enumerated().reduce(([T](), [T]())) {
        (result:(real:[T], imag:[T]), input:(index:Int, element:T)) in
        input.index % 2 == 0 ? (result.real + [input.element], result.imag) : (result.real, result.imag + [input.element])
    }
}

This implementation uses reduce to loop through the source array once, and accumulate a tuple of two arrays as a result.  The reduce is use on the enumerated() source array, so that the closure received both the element, and the index of that element in the original array.  This way, by checking the mod 2 of the index, we can see if the element was in an even or an odd position and add it to the correct resulting array accordingly.

Lastly, since we don't really need to know what the specific type of the array's element is for this behavior, this implementation is generic and will split any array of anything into two new arrays: one with all the even-indexed elements, and one with all the odd-indexed elements.


Convert IP address to its binary representation

I don't have access to your test file, but try:

private static final String[] PAD_ZEROS=
    new String[] {
        "00000000",
        "0000000",
        "000000",
        "00000",
        "0000",
        "000",
        "00",
        "0",
        ""
    };

   public static String fast(final String ip) {
        final StringBuilder result = new StringBuilder();
        final String octals[] = ip.split("\\.");
        for (final String octal: octals) {
            final String binaryString = Integer.toBinaryString(Integer.parseInt(octal));
            result.append(PAD_ZEROS[binaryString.length()]);
            result.append(binaryString);
        }
        return result.toString();
    }

In general, I'd suggest avoiding hungarian notation (bStringBuilder), unnecessary abbreviations(binString), and magic numbers (if you keep the 8, it should be in a private static final class-level variable).

Note that your performance testing is flawed. The problem is the VM performs internal optimizations as it runs which can improve the performance of the system. You should test either fast or slow, but not both, in one execution. Don't test the same string over and over again, but pull in your routing file. Then, unless your whole application is to run this one method on the file and then stop, you should run for a while, throw out that data, then start measuring. Maybe do 2 executions of the file, but only time the second one. That imitates the method being called from a live system that's been running a while, instead of a cold system.

Two more things: as @rofl said, presize the StringBuilder. Also pull the System.out.println() out of your method - it's an artificial drag on the performance.

-- Working off of @rofl's other suggestion, this is 25% faster on my machine than your fast method, including the time to populate the map. It does consume more memory, and it eagerly maps numbers which may not be used. It is less elegant than @rofl's suggestion, and possibly slower, but I find it easier to read.

private static final String[] PAD_ZEROS =
        new String[] {
            "00000000",
            "0000000",
            "000000",
            "00000",
            "0000",
            "000",
            "00",
            "0",
            ""
        };

private static final Map<String, String> MAP =
        new HashMap<String, String>(256);

private static void populateMap() {
    for (int i = 0; i < 256; i++) {
        final String binaryString = Integer.toBinaryString(i);
        MAP.put(
            Integer.toString(i),
            PAD_ZEROS[binaryString.length()] + binaryString);
    }
}

public static String faster(final String ip) {
    final StringBuilder result = new StringBuilder(32);
    final String octals[] = ip.split("\\.");
    for (final String octal: octals) {
        result.append(MAP.get(octal));
    }
    return result.toString();
}


Extract incomplete weeks from a DateTime collection

Naming:

Names of methods in C# use PascalCasing. Your method name would become ExtractIncompleteWeeks. Although the naming convention is now correct, the name is ambiguous. Extract incomplete weeks means you want to fetch only the dates of the weeks which are incomplete. Instead rename it to ChopIncompleteWeeks or ExtractCompleteWeeks. This makes clear that you want to eliminate the incomplete weeks or want to extract the complete weeks.

Return type:

The return type of the method is an IEnumerable<DateTime> yet you return a List<DateTime>. Either make the return type also List<DateTime> but preferably return one element at a time by using yield.

private IEnumerable<DateTime> ExtractCompleteWeeks(IEnumerable<DateTime> dates)
{
    ...

    foreach (var monday in mondays)
    {
        ...

        if (fullWeek.Last().Date == monday.AddDays(6).Date)
        {
            foreach(var day in fullWeek)
            {
                yield return day;
            }
        }
    }
}

Here are some questions from StackOverflow and Programmers.SE regarding yield:

Proper Use of yield return
A practical use of “yield” keyword in C#

I really like this answer from the first question to get a very basic understanding of using yield instead of a temporary list:

  Populating a temporary list is like downloading the whole video, whereas using yield is like streaming that video.

HashSet:

Is there a specific reason why you create a HashSet<DateTime> only to take the last element and compare it against monday.AddDays(6).Date? You can replace that line by following:

var fullWeek = dates.SkipWhile(d => d < monday).Take(7).Select(d => d.Date);

Complete code:

private IEnumerable<DateTime> ExtractCompleteWeeks(IEnumerable<DateTime> dates)
{
    var mondays = dates.Where(d => d.DayOfWeek == DayOfWeek.Monday)
                       .Select(d => d.Date);

    foreach (var monday in mondays)
    {
        var fullWeek = dates.SkipWhile(d => d < monday).Take(7).Select(d => d.Date);

        if (fullWeek.Last().Date == monday.AddDays(6).Date)
        {
            foreach(var day in fullWeek)
            {
                yield return day;
            }
        }
    }
}


Calculate the rates at which users get stuck at each stage

you should define float failureRate = 0; inside the for (int i = 1; i <= N; ++i) loop, because you are not using it outside the loop. See this for more info.
When you calculate failureRate, just cast one of usersOnStage.get(i) or total to float. You don't need to cast both.
else {failureRate = 0 / total;} is redundant because you'll always set failureRate to 0, which is its default value.

As for optimization to make it faster, since this piece of code is likely to be used in a video game, stages should be a small list, where efficiency of the algorithm doesn't matter much. You'd probably want to use simpler data structures, for a smaller overhead.


Google CodeJam 2016 - Ruby - Counting Sheep

In no particular order:

I'd prefer .zero? rather than == 0
You could use a hash instead of an array and remove the need to call uniq. That method quickly gets pretty expensive, especially since you're calling it on an ever-growing array
I'd like the solve method to return either an integer or nil, instead of mixing string and number return types.

As for getting digits from a number, I'd suggest using #divmod. Coverting to a string and splitting always irks me a little, even if it is a pretty straightforward solution. But like the return type from solve, I see no reason to involve strings when trying to get numbers from a number.

Basically, you can do something like this:

require 'set'

def unique_digits(number)
  digits = Set.new
  remainder = number
  while remainder > 0
    remainder, digit = remainder.divmod(10)
    digits << digit
  end
  digits
end

This is using a Set (part of the stdlib) since it guarantees uniqueness - no need to call uniq on an array.

As for the core of the task:

def count_sheep(n)
  return nil if n.zero?
  digits = Set.new
  current = 0
  while digits.size < 10
    current += n
    digits += unique_digits(current)
  end
  current
end

All you need then is the method to run it. I'd suggest something like:

def read_input(io)
  cases = io.gets.strip.to_i
  cases.times do |i|
    n = io.gets.strip.to_i
    puts "Case ##{i+1}: #{count_sheep(n) || "INSOMNIA"}"
  end
end

Where io is a file handle or stdin. That way you can run your script in two ways; piping things to stdin, or reading from a file. All it needs is an IO object. E.g.:

read_input(ARGV[0] ? File.open(ARGV[0]) : STDIN)

should let run either $ ruby sheep.rb <file> or $ cat <file> | ruby sheep.rb

In all:

require 'set'

def unique_digits(number)
  digits = Set.new
  remainder = number
  while remainder > 0
    remainder, digit = remainder.divmod(10)
    digits << digit
  end
  digits
end

def count_sheep(n)
  return nil if n.zero?
  digits = Set.new
  current = 0
  while digits.size < 10
    current += n
    digits += unique_digits(current)
  end
  current
end

def read_input(io)
  cases = io.gets.strip.to_i
  cases.times do |i|
    n = io.gets.strip.to_i
    puts "Case ##{i+1}: #{count_sheep(n) || "INSOMNIA"}"
  end
end

read_input(ARGV[0] ? File.open(ARGV[0]) : STDIN)


Return array of objects with matching keys

Better readability could be achieved using array.filter, since it creates the array for you and all you have to do is return true or false. No need to create an array, do the comparison and push yourself.

In the same way when checking for the values, Object.keys can be used with array.every to iterate through your constraints and see if each of the current item's keys match the constraint.

Also, I wouldn't call it source. It's not a source of anything. It's more of a "constraint" for your collection. So I'd call it that way instead.

In terms of performance, array iteration functions are slower than your average for loop (older APIs will tend to be more optimized). However, in terms of readability, these array APIs really shorten your code.

function where(collection, constraint){
  // filter creates an array of items whose callback returns true for them
  return collection.filter(function(collectionItem){
    // every returns true when every item's callback returns true
    return Object.keys(constraint).every(function(key){
      return collectionItem.hasOwnProperty(key) && constraint[key] === collectionItem[key];
    });
  });
}

var a = where([{ "a": 1 }, { "a": 1 }, { "a": 1, "b": 3 }], { "a": 1});
var b = where([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 })

document.write(JSON.stringify(a));
document.write('
');
document.write(JSON.stringify(b));

The code can further be simplified by taking advantage of ES6 arrow functions. This removes the brackets (with one arg, the parens are optional), and the body can be an expression which would then be an implicit return value, eliminating return.

function where(collection, constraint){
  return collection.filter(collectionItem =>
    Object.keys(constraint).every(key =>
      collectionItem.hasOwnProperty(key) && constraint[key] === collectionItem[key]));
}

var a = where([{ "a": 1 }, { "a": 1 }, { "a": 1, "b": 3 }], { "a": 1});
var b = where([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 })

document.write(JSON.stringify(a));
document.write('
');
document.write(JSON.stringify(b));


What is the best practice for working with a project as nested modules?

I use the version with double indent and I think it is the common usage:

module ProjectName
    module SubModule
        # Double indent for all the code in the file!?
    end
end

If you don't like the double indention, just don't do it.

It is best practice to indent each code level (module, class, def, loops...), but no must.
In Python it is part of the syntax, but not in Ruby.

See also https://stackoverflow.com/questions/3833641/is-there-an-acceptable-way-of-putting-multiple-module-declarations-on-the-same-l


Extracting distinct HTML list items into a JavaScript array

As already noticed by previous comments, don't mind about global variables if they're declared by var inside of a function.
And you can do the same for commonArray and str, unless they're used elsewhere (obviously, I don't think so).

In the other hand, you can dramatically reduce your code!

First because you don't have to wait for onload event, since your

Here is a working example.


Generating a list of unique random longs

I doubt that algorithmic efficiency can be improved but you may consider an implementation similar to this which leverages idiomatic LINQ.
public IEnumerable<long> GenerateRandomNumbers()
{
    var f = new Faker();

    return
        Enumerable.Range(0, int.MaxValue)
        .Select(
            _ => f.Random.Long(5000000000, 8000000000))
        .Distinct();
}


Check existence of user identification number

One of:

Only take a string or a number.
Use str either way.
Work against a bespoke class.

Yes. But I find it better to just use Iterator[str], unless you're using the coroutine aspects of it.
Yeah that's fine. But:

You can just use in rather than any(...).
You don't need the function get_ids you can just use any, like you are now.

Don't use type(...) == int, use isinstance.
Validating user_id should probably happen somewhere else.

I'll make a class as an example to show this.

class UserId:
    __slots__ = ('id',)
    id: int

    def __init__(self, id: int) -> None:
        if not self.valid_id(id):
            raise ValueError("ID should be 9 characters long and all digits.")
        self.id = id

    @staticmethod
    def valid_id(id: int) -> bool:
        if not isinstance(id, int):
            return False
        str_id = str(id)
        return (
            len(str_id) == 9
            and str_id.isdigit()
        )

    def exists(self) -> bool:
        user_id = str(self.id)
        with open('ids.txt') as f:
            return any(user_id == line.strip() for line in f)

print(UserId(123456789).exists())


Yep, go for it. Adding more detail to error messages is helpful.

Also, depending on which style you prefer you could avoid explicitly checking the count by catching the exception thrown by Single().

try
{
    return objects.Single();
}
catch (InvalidOperationException ex)
{
    throw new InvalidOperationException(
        "%Collection% should contain one %element%, but now it's: " + objects.Count,
        ex
    );
}


Print 2 double arrrays, the second one should be cumulative totals of the elements of the first array

About the only thing I would change is this loop

for (x = 0,index2 = 0,index = 0; x < ASIZE; x++, index2++)//adding the second array the elements
{
    cal += array1[index++];
    array2[index2] = cal;
}

You don't need x (its really index1. As all the variables are tracking each other you don't need index2 as index1 is the same value each iteration (and allways do the increment in the for() loop.

The only bug I see is the cal is not initialized to zero and can thus have an indeterminate value.

I would have written it like this:

cal = 0.0;
for (index = 0; index < ASIZE; index++)//adding the second array the elements
{
    cal += array1[index];
    array2[index] = cal;
}

A minor note:

As the code may be changed to have bigger arrays by modifying ASIZE. I would make the user instructions reflect this automaically.

printf("Please enter 8 numbers:\n");

// Try:

printf("Please enter %d numbers:\n", ASIZE);


Chain Responsibility Pattern to filtering messages

Chain of Responsibility

Rather than building the chain on instantiation, make the creation of the chain a function.
This can allow you to chain the creation, which is easier to read and nicer to look at.

I'd also make the chain return, rather than mutate a foreign object.
This removes side effects, which lead to hard to understand code, and potential bugs.

has_successor is a poor function, it's simpler to read and understand using if self._next is not None, rather than using that abstraction.
And so I'd remove it, I'd favour writing out the non-function way anyway.

And so I'd come to:
class Filter(object):
    _next = None
    def add_filter(self, next_filter):
        self._next = next_filter
        return next_filter

    def filter_message(self, message):
        if self._next is None:
            return True
        return self._next.filter_message(message)

class SlangFilter(Filter):
    def filter_message(self, message):
        for word in message.content:
            for bad_word in bad_words:
                if bad_word == word.lower():
                    return False

        if self._next is None:
            return True
        return self._next.filter_message(message)

class Website_Filter(Filter):
    def filter_message(self, message):
        if re.findall(urlmarker.URL_REGEX, message.content) is not None:
            return False

        if self._next is None:
            return True
        return self._next.filter_message(message)

This then lets you create the chain as:
def main():
    new_message = Message("This is full of fucking shit www.google.com")
    filter = WebsiteFilter()
        .add_filter(SlangFilter())
    print filter.filter_message(new_message)

Going forward, you'd want to change your classes in a couple of other ways too.

Rather than relying on a global bad words variable, SlangFilter should be passed these words on instantiation.
Rather than manually re-creating in, you can use it to reduce code complexity, and for a performance boost, if you were to change the list of words to a set.
Your code shouldn't rely on an unneeded model, as a string is good enough for this.

And so I'd use:
import urlmarker
import re

class Filter(object):
    _next = None
    def add_filter(self, next_filter):
        self._next = next_filter
        return next_filter

    def filter_message(self, message):
        if self._next is None:
            return True
        return self._next.filter_message(message)

class SlangFilter(Filter):
    def __init__(self, bad_words):
        self._bad_words = {word.lower() for word in bad_words}

    def filter_message(self, message):
        for word in message.lower().split():
            if word in self._bad_words:
                return False

        if self._next is None:
            return True
        return self._next.filter_message(message)

class Website_Filter(Filter):
    def filter_message(self, message):
        if re.findall(urlmarker.URL_REGEX, message) is not None:
            return False

        if self._next is None:
            return True
        return self._next.filter_message(message)

def main():
    with open("bad-words.txt") as file:
        bad_words = [word.strip() for word in file]

    message = "This is full of fucking shit www.google.com"
    filter = WebsiteFilter()
        .add_filter(SlangFilter(bad_words))
    print filter.filter_message(message)

if __name__ == '__main__':
    main()


The way sequence is used guarantees that the results will be wrong for the majority of inputs. It's clearly intended that sequence should be a continuous range starting at 0. So rather than require the range as input, it would make more sense to require the limit as input.

        numbers.append(0)
        if i == 0 or i == 1:
            numbers[i] = 1
            continue
        numbers[i] = numbers[i-1] + numbers[i-2]

This confused me briefly until I figured out that it appends 0 as a placeholder and then overwrites it with the appropriate Fibonacci number. Following the principle of KISS (keep it simple), it would make more sense to append the Fibonacci number directly.

IMO the expression is short enough to use a ternary:

        numbers.append(numbers[i-1] + numbers[i-2] if i > 1 else 1)

Those two changes give

def spiral(n):
    numbers = []
    for i in range(n):
        numbers.append(numbers[i-1] + numbers[i-2] if i > 1 else 1)
    return numbers
times = int(input("How many times do you want to go through? "))
fibonacci = spiral(times)
print(fibonacci)

The names seem quite opaque. Why spiral? Why times? They both seem to assume some context which isn't documented in the code.

It would be more Pythonic to write a generator, but since you say you're a beginner this may be a concept which you haven't encountered yet.


The Vector type is not related to graphics, so importing
CoreGraphics seems "unnatural" here. If you replace CGFloat
by Float or Double

extension DigitType {
    static func value(place place: Int) -> Int {
        return count * Int(pow(10, Double(place)))
    }
}

then it suffices to import Foundation (or Swift + Darwin).

But I would get rid of the floating point conversion and implement it as (taking the hundreds as an example):

enum ___<H: DigitType, T: DigitType, U: DigitType> : CountType {
    static var count: Int {
        return H.count * 100 + T.count * 10  + U.count
    }
}

This is simple and straightforward, and easy to read. This makes the
value(place place:) with its floating point conversion, and the
the math library call to the pow() function obsolete.

As a consequence, the entire code compiles with a pure

import Swift

without additional imports.

(This is my major point.) The boxing of the array elements into
a class seems problematic to me.

First, struct Vector is a value type, but its elements are
mutable even for a constant:

let vecA = Vector<_3, Int>(0)
vecA[0].value = 111 // This should not compile!

Second, copying a vector copies references to the elements,
which is not to be expected for a value type:

let vecA = Vector<_3, Int>(0)
vecA[0].value = 111

let vecB = vecA
vecB[0].value = 222

print(vecA[0].value) // Output: 222. Expected output: 111.

Here, modifying the elements of vecB modifies the elements of
vecA as well.

I would simply omit the boxing and store the elements just as an
array. Modifying the elements is then done via a subscript setter:

struct Vector<Dimension: CountType, Element> {

    private var array: [Element]

    init(_ repeatedValue: Element) {
        array = [Element](count: Dimension.count, repeatedValue: repeatedValue)
    }

    var elements: [Element] {
        return array
    }

    subscript(index: Int) -> Element {
        get {
            return array[index]
        }
        set(newValue) {
            array[index] = newValue
        }
    }

    func generate() -> Array<Element>.Generator {
        return array.generate()
    }
}

Using a private var array for the element storage and a
computed elements property still makes sense for encapsulation.

Now Vector behaves like a proper value type:

var vecA = Vector<_3, Int>(0)
vecA[0] = 111

var vecB = vecA
vecB[0] = 222

print(vecA[0]) // Output: 111

By adopting the CustomStringConvertible protocol,

extension Vector : CustomStringConvertible {
    var description: String {
        return "<" + (array.map { String($0) }).joinWithSeparator(", ") + ">"
    }
}

printing a vector produces nicer output (the angle brackets are just
an example to disambiguate the output from an array):

print(vecA)
// Output: <111, 0, 0>
// instead of Vector<_3, Int>(array: [111, 0, 0])

To create (constant) vectors, an init method taking a "index to
element mapping" might be useful:

extension Vector {
    init(elementForIndex: Int -> Element) {
        array = (0 ..< Dimension.count).map(elementForIndex)
    }
}

Example:

let vecC = Vector<_5, Int>(elementForIndex: { 2 * $0 })
print(vecC) // <0, 2, 4, 6, 8>

This would also come in handy when you start to define operations
on the vector type, e.g. an addition of integer vectors:

func + <Dimension, Element: IntegerArithmeticType>
    (lhs: Vector<Dimension, Element>, rhs: Vector<Dimension, Element>)
    -> Vector<Dimension, Element> {
        return Vector(elementForIndex: { lhs[$0] + rhs[$0]})
}

Initialization from an array or array literal might also be
convenient:

extension Vector {
    init(elements: [Element]) {
        precondition(elements.count == Dimension.count)
        array = elements
    }
}

extension Vector: ArrayLiteralConvertible {
    init(arrayLiteral elements: Element...) {
        self.init(elements: elements)
    }
}

Example:

let vecD: Vector<_5, Double> = [ 1.0, 2.0, 3.0, 4.0, 5.0 ]
print(vecD) // <1.0, 2.0, 3.0, 4.0, 5.0>

The disadvantage here is that the compiler cannot check the
dimension.


The latter would be my preferred method. It enhances readability, and allows you to use that object more than once without casting it every time (more efficient).

Though, if you are only casting to use one function inside the object, then there's no point in doing the latter (you would just be creating needless variables to only set one value in it once).


dequeue() in Queue implememtation that uses a circular linked list

dequeue2

This method works because, when there's just one remaining item in the queue, the line:

Node first = last.next;

sets first to be the same as last (because, for a 1-sized queue last.next is a pointer to last).

In the other dequeue() you set last to be null when there's nothing left, but this does not make a difference, really (other than Garbage Collection) because the enqueue function checks the empty queue using n == 0 and not last == null

static inner class

Your Node class does not have any need for a back-reference to the Queue. It should be a static inner class private static class Node....... To do that, though, you need to make it generic too. Use a letter other than T to represent the generic class...

 private static class Node<U> {
    U value;
    Node<U> next;
    Node(U val, Node<U> n) {
        value = val;
        next = n;
    }
}

This saves a small amount of memory, but it is good practice. When you create the Node instances now, the code will change from:

private Node last;

to

private Node<T> last;

and you will add the <> diamond operator here:

Node<T> tmp = new Node<>(item, last.next);

Constructor:

Your constructor:

public Queue() {
    last = null;
    n = 0;
}

should just be:

public Queue() {
}

as you don't need to explicitly supply the default values.

General

Your code is neat, your variable names are not bad, and the use of generics is good.

As a learning exercise you should spend some time seeing if you can make it implement java.util.Queue interface (it's not easy - fair warning) because that will teach you a bit about what the actual Java Collections API offers.


Selecting function overload based on a type match with return value of passed callable

Higher level overview:
Personally I think the architecture has limited use cases. It was quite hard to implement, and even then doesn't match the specification.
From what I understood, this is the problem definition:

Given a container with element type T, and a callable which has return type U, create a new container with element type U and populate it by calling callable on each element of the first container. If T and U are the same, take the container by copy and transform it, otherwise use back inserter to populate it.

Although it is already good, in realm of template metaprogramming this is insufficient.
Implementation overview:
The solution places superficial limits (as per the problem definition). There are two problems in C++ template metaprogramming: assuming too much and assuming too little. Both of those happened in this case. Most of the time it is hard to tell if too little is assumed or too much, so they are mostly interchangeable.
The most obvious superficial assumptions are made here:
Container<A, std::allocator<A>>

Very few hand-rolled containers will have allocator type, or even any types at all. Remapping from one type to another is quite hard, and is the most significant problem in this case.
Somewhere the other stuff except the element type is left out:
if constexpr(std::is_same<ContainerOfB, std::vector<B>>::value) {
   result.reserve(xs.size());
}

A vector which has non-standard allocator will probably benefit from reserving too.
I don't think the code itself is unreadable. After some time on codereview and around a year of template metaprogramming this code is still readable. Although I would note that the comments in the center of the template parameter declaration got me really confused. I would put that above or below parameter declaration part.
Another solution:
I gave it a shot. I believe I covered more cases, at the expense of code size, although I think readability increased a bit:
namespace detail
{
    template <typename Container>
    using value_type = typename Container::value_type;

    template <typename Callable, typename Container>
    using invoke_result = std::result_of_t<Callable(value_type<Container>)>;
}

template <typename Container, typename Callable>
struct mutable_in_place :
        public std::bool_constant<std::is_same_v<detail::value_type<Container>,
                                  detail::invoke_result<Callable, Container>>>
{};

namespace detail
{
    template <template <typename ...> typename Container, typename T, typename ... TArgs, typename Callable>
    auto realfmap(Container<T, TArgs...> container, Callable&& callable, std::true_type)
    {
        std::transform(container.begin(), container.end(),
                       container.begin(), std::forward<Callable>(callable));
        return container;
    }

    template <template <typename ...> typename Container, typename T, typename ... TArgs, typename Callable>
    auto realfmap(Container<T, TArgs...>&& container, Callable&& callable, std::false_type)
    {
        using parameter_type = decltype(*container.begin());
        using invoke_result = std::result_of_t<Callable(parameter_type)>;
        Container<invoke_result> mapped_container;

        if constexpr(std::is_same_v<decltype(mapped_container), std::vector<invoke_result>>)
        {
            mapped_container.reserve(container.size());
        }

        std::transform(container.begin(), container.end(), std::back_inserter(mapped_container),
                       std::forward<Callable>(callable));
        return mapped_container;
    }
}

template <typename Container, typename Callable>
auto realfmap(Callable&& callable, Container&& container)
{
    return detail::realfmap(std::forward<Container>(container),
                            std::forward<Callable>(callable),
                            mutable_in_place<std::decay_t<Container>, Callable>{});
}

Although it grabs the other template arguments, it cannot use them. For example, consider the case when container=std::vector<int> and callable=std::string(int). The allocator which should get instantiated for the returning vector is std::allocator<std::string>, but the grabbed one is std::allocator<int>, so static assert will fire or some other library error notification facility, since std::vector<T>::value_type and std::vector<T>::allocator::value_type must match.
The reasoning behind not putting mutable_in_place is to expose this to the user. Some people could do template metaprogramming on top of this, and sometimes people might run into template bugs, and exposing the variable template should aid them.
About using std::result_of_t<>, the reason is that it is much easier to convert the type trait compared to hand rolled version with decltype() and stuff. It might even be possible to write a python script or something similar to convert throughout the code base, since the syntax is trivial.
Don't get me wrong, but plain transform has clear advantage here, both semantics and implementation wise.
Change the problem:
It seems like solving the current problem will have a very big engineering cost, thus I propose the following problem definition:

An StdContainer: type which exactly matches declaration template <typename ElemType, typename Allocator = std::allocator<ElemType>> class container except identifier names (type parameters and class name itself) and is allocator-aware. Given an StdContainer and Callable, create and populate another StdContainer with return type of the Callable as element type. Creating and populating depends on the equality of element type of the original container and return type of the callable. If they match, a copy is taken and std::transform() is called. Otherwise, the original container is taken by reference, new one is default constructed and it is populated though calling std::transform() with std::back_inserter() as output iterator.

Your solution will solve the new problem and won't have any bugs. Also, for me it would be sufficient to pass into code base, with some cosmetic tweaking.


Implementation of a threshold detection function in Python

If y will always be a sine wave, then you're going about this the wrong way. Rather than calculating trigger_marker based on whether y exceeds tr, you should be calling asin(tr) to see where in the cycle the trigger will be crossed. You would then avoid the need for most of your lists and loops.


Printing 1,000,000 numbers in 1 sec. in Python

Nice solution, few suggestions:

Printing the numbers one by one might be the issue. Generate the list of numbers first and then call print only once.
The case n==1 is already handled, so the first elif can be removed.

Applying the suggestions:
n = int(input())
if n == 2 or n == 3:
    print("NO SOLUTION")
elif n == 4:
    print("3 1 4 2")
else:
    beautiful_perm = [*range(1, n + 1, 2), *range(2, n + 1, 2)]
    print(' '.join(map(str, beautiful_perm)))

By inverting the ranges we don't need to check for n==4:
n = int(input())
if n == 2 or n == 3:
    print("NO SOLUTION")
else:
    beautiful_perm = [*range(2, n + 1, 2), *range(1, n + 1, 2)]
    print(' '.join(map(str, beautiful_perm)))

Runtime on CSES:
n = 906819 (CPython3)
Original: 0.92 s
Improved: 0.26 s

n = 1000000 (CPython3)
Original: timeout
Improved: 0.28 s

n = 1000000 (PyPy3)
Original: 0.61 s
Improved: 0.15 s


Sheet display in function of date and time on open and save

selectiondequartauto() defines night shift to determine whether to select either the night shift or day shift sheet.  If none of the worksheets meet the criteria of Night Shift or Day Shift then the Friday worksheet is selected.  This all works fine but consider the advantages of my refactored code which separates these tasks into their own methods.
• isNightShift: Using a function that determines what is Night Shift and what is Day Shift means that you can update the hours of Night Shift in one spot and not have to look over every procedure that is dependent on on the Night Shift.
• NightShiftSheet() and DayShiftSheet():  Having these functions will prevent you from having to repeat the logic to find the sheets in the future.  They also make  selectiondequartauto() easier to read
Public Sub selectiondequartauto()
    Dim ws As Worksheet

    If isNightShift(Now) Then
        Set ws = NightShiftSheet
    Else
        Set ws = DayShiftSheet
    End If

    If ws Is Nothing Then
        Sheets("Vendredi jour").Activate
    Else
        ws.Activate
    End If
End Sub

Public Function DayShiftSheet() As Worksheet
    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets
        With ws.Range("B4")
            If IsDate(.Value) Then
                If Not isNightShift(.Value) Then
                    Set DayShiftSheet = ws
                    Exit Function
                End If
            End If
        End With
    Next

End Function

Public Function NightShiftSheet() As Worksheet
    Dim ws As Worksheet
    For Each ws In ThisWorkbook.Worksheets
        With ws.Range("B4")
            If IsDate(.Value) Then
                If isNightShift(.Value) Then
                    Set NightShiftSheet = ws
                    Exit Function
                End If
            End If
        End With
    Next
End Function

Public Function isNightShift(DateTime As Date) As Boolean
    isNightShift = TimeValue(DateTime) > TimeValue("3:00:00") And TimeValue(DateTime) < TimeValue("16:15:00")
End Function


Dependency Inversion Principle and Dependency Injection in C#

The new code seems OK to me.

One way to know if you're on the right way is trying to unit test your code. In the old code you couldn't unit test the higher class, as you needed to create real instances of the lower classes inside the code, so you needed to test both the higher and the lower classes at the same time.

In the new code you can test the lower classes and the higher class separately, as now you can inject a mock of the ISex interface into the higher class and test that the proper methods of the lower classes are invoked.

Note that you have two options to inject the lower class. If the lower class is only going to help in one method of the higher class, maybe it will be better to inject the lower class as a parameter of that method. If the lower class is going to help all along the higher class, then pass it as a parameter of the constructor, as you have it now.


Number of Google search results over a period of time, saved to database

If you just need the number of search results, you can surely use what you're using now and grep the total result number, otherwise you may use Google Search API, or find an open source scrawling tool like Scrappy.


I think I personally like the set by constructor method in general.  I think it provides a means by which you can better allow for TDD and also implicitly implies the contract all inheriting classes must obey in providing a Entity object if they wish to inherit from the base class.

I think if I were going make Entity a requirement of the second method I would make the protected method abstract which would also enforce this constraint.  However that doesn't allow for the easy of use in using dependency injection which I think would suit this approach nicely.

I'm not sure why there would be a huge increase in the size of the Entity object itself.  I would assume the size increase would only be as large as the size of the memory register holding the location of the Entity object itself.  As for performance, I can't comment explicitly but I would assume you would still need to make visible the EntityData object to it's children so you would probably do that via a property accessor or method anyway so performance impacts to me would be low on the priority list unless profiling the code suggested otherwise.

So assuming the Entity is required in inherited classes I would consider something like:

abstract class Entity
{
    protected EntityData Data { get; private set; }

    protected Entity(EntityData data)
    {
        this.Data = data;
    }
}


Find the single smallest IP network with the given IP addresses

You don't have to look at all the IPs to catch 'em all. Just looking at the lowest and highest does the trick. This realisation comes in handy when you consider that ipaddr does have a (private) function that gives you the common prefix length between two IP addresses. The code can then be simplified to:

#with many thanks to gfalcon
def _GetOneNetmaskForAllTheseIPs(ips):
  """Get the one IP network that covers all IPs in input.

  ipaddr.collapse_address_list is a little bit TOO smart and gives you the LIST
  of networks that describe a number of IP addreses. Ceph just wants one
  netmask. This function tries to get that one netmask.

  >>> _GetOneNetmaskForAllTheseIPs(("10.0.0.1", "10.0.0.2",
  ...   "10.0.0.251","10.0.0.255"))
  10.0.0.0/24
  """

  #Look at larger and smaller IP addresses
  ips = [ipaddr.IPAddress(ip) for ip in ips]
  lowest_ip, highest_ip = min(ips), max(ips)

  mask_length = ipaddr._get_prefix_length(
    int(lowest_ip), int(highest_ip), lowest_ip.max_prefixlen)

  #Return the network
  network_ip = ipaddr.IPNetwork("%s/%d" % (lowest_ip, mask_length)).network
  network = ipaddr.IPNetwork("%s/%d" % (network_ip, mask_length), strict = True)
  return str(network)

You still can't use public functions like ipaddr.summarize_address_range, because the library will still painstakingly try to avoid any IP address ever so slightly off range.

>>> ipaddr.summarize_address_range(IPv4Address('10.0.0.1'), IPv4Address('10.0.0.255'))
[IPv4Network('10.0.0.1/32'),
 IPv4Network('10.0.0.2/31'),
 IPv4Network('10.0.0.4/30'),
 IPv4Network('10.0.0.8/29'),
 IPv4Network('10.0.0.16/28'),
 IPv4Network('10.0.0.32/27'),
 IPv4Network('10.0.0.64/26'),
 IPv4Network('10.0.0.128/25')]


Is there a way to simple Haskell class instance?

Above all, such an instance doesn't make any sense. A composite entity can't have much in common with a number, which the fact that your instance consists of just partial and undefined functions is only the evidence of.

With regards to your concern about the verbosity of the instance declaration, it was caused by you choosing an incorrect approach to type declaration.

Pixels of different bit-depths are appropriately described as different types, and not different constructors of the same type. The analogy is right before you: Word8 and Word16 are different types, not constructors.

Taking the said above into account I recommend you to reapproach your problem the following way:

-- The separate datatypes. Note the absense of `Empty` constructors, as there
-- is no such thing as empty pixel. There are black and transparent pixels,
-- which should be described as `PixelRGB8 0 0 0` or `PixelRGBA8 0 0 0 0`,
-- but not empty. And for dealing with missing pixels we have a `Maybe` type.
data PixelRGB8 = PixelRGB8 Word8 Word8 Word8
-- ...
data PixelRGBA16 = PixelRGBA16 Word16 Word16 Word16 Word16

-- We're taking an analogous approach to Num/Integral typeclasses, while
-- combining both the "to" and "from" functionality in a single typeclass.
class Pixel a where
  -- whether its toPixelRGBA16 or possibly toRGBA64Pixel should depend on
  -- the highest precision type you want to be dealing with
  toPixelRGBA16 :: a -> PixelRGBA16
  fromPixelRGBA16 :: PixelRGBA16 -> a
  -- And here's addition for pixels of same type:
  addPixel :: a -> a -> a

instance Pixel PixelRGB8 where
  toPixelRGBA16 = error "TODO"
  fromPixelRGBA16 = error "TODO"
  addPixel = error "TODO"

instance Pixel PixelRGBA16 where
  toPixelRGBA16 = id
  fromPixelRGBA16 = id
  addPixel = error "TODO"

-- Here's addition for pixels of differing types:
addArbitraryPixel :: (Pixel a, Pixel b) => a -> b -> PixelRGBA16
addArbitraryPixel a b = addPixel (toPixelRGBA16 a) (toPixelRGBA16 b)


There's no sense in creating a dynamic array for a fixed set of checks. Just put them in a single boolean expression.

public function isProfileComplete()
{
    return $this->isAddressGiven()
        && $this->isGenderSelected()
        && null !== $this->getFirstName()
        && null !== $this->getLastName()
        && null !== $this->getJobTitle()
        && null !== $this->getAboutMe()
        ;
}


Manipulating a .csv file to look for two common values to create a key, then summing up values

Overall, your code is pretty clean.

Here are some points for improvement:

Use the if __name__ == '__main__' idiom if this file is to be executed directly. https://docs.python.org/2/library/main.html
Structure your code so that no code is executed before the name clause or upon import. In other words, don't have any code blocks which start at the left-hand margin. Instead, place code within a few functions which are called by a main run() function.
Use an enum or constants to represent the index values for things like nd_amount.

EDIT

ND_AMT = 14
...

nd_amt = row[ND_AMT]


Correct usage of MVVM and object for method

Minor note:

Here in your validation class there's this comment.

// Temporarily 0 = success, 1 = error

Which is fine. You don't want to use a boolean because you'll be adding more status codes in the future. Cool! But you shouldn't be hard coding the error code numbers. This is what enums are for.

enum ValidationStatus {Success,GenericError}

// Check if user input was empty
public object inputNullCheck(string input)
{
    if (input != "")
    {
        this.ErrorCode = ValidationStatus.Success;

At this point, it would be better to remove this code

       this.ErrorName = "Success";
       this.ErrorMessage = "Valid input received";

And create a class that manages what Message to return based off of the value of the ValidationStatus passed into its constructor.

Reducing the above code to

    if (input != "")
    {
        return new ValidationResult(ValidationStatus.Success);


Calculate percentage of values in an array with a certain condition

Naming

Kill the Hungarian Notation. Kill it with fire. Don't bother taking it out back to bury it.

Hungarian notation can be done right, but using it to tell yourself what datatype a variable is is not doing it right. Even if you must just insist on using hungarian notation this would not be right.

Dim intAge( , ) As Integer = {{0, 2, 5, 10}

intAge is not an integer. It is an array of arrays of integers.

Functions/Subs should have Verb-Noun style names. They should also be PascalCased.

Indentation

It's important. Like, really really important. Proper indentation makes it orders of magnitude easier to read code. Considering code will be read many more times than it will be written, it's important to make sure people can read it.

Everything inside of Function...End Function should be indented one level. Everything inside of For...Next should be indented one more level. Same goes for If...End If blocks.

Getting Down to Business

A percentage is a double, not an integer.

Public Function intPercentage As Integer

If you want an integer representation of the percentage, you should probably leave a comment explaining why.
A function isn't much good if it will return the same results every time. This one will because you've hardcoded the array of arrays into the function. It would be much more useful to accept a 2-dimensional array as an argument instead.
I'm not personally a fan of declaring multiple variables on a single line, but there's technically nothing wrong with it.

Dim intRow, intCol As Integer

Since we're now going to accept an array as an argument, we'll no longer be able to hardcode For row = 0 to 3. You'll need to call GetLength on the internal array and Length on the outer one. (Example will be below.)
You never declared intTotal. (Which you're going to call totalAge now, right?)
Don't skimp on the End Ifs. Always be sure to close the If block unless you really write a one liner. (I don't recommend one liners by the way.)
Prefer the Return keyword over assigning values to the function name.
You can't just divide a number by 100 and call it a percentage.

intPercentage = intTotal / 100

In order to get the results you're really after, you need to divide the count of ages 2 or older by the count of all ages, then multiply by 100.

I took the liberty of re-writing the code.

Public Function GetPercentage(ages(,) As Integer) As Double

    Dim row As Integer
    Dim col As Integer
    Dim overTwo As Integer
    Dim total As Integer

    For row = 0 to ages.Length - 1
        total = total + ages.GetLength(row)

        For col = 0 to ages.GetLength(row) - 1
            If ages(row, col) >= 2 Then
                overTwo = overTwo + 1
            End If
        Next col
    Next row

    Return (overTwo / total) * 100
End Function


Query URL parameters in downloading pictures from network cameras

Is my code readable enough?

Unfortunatelly there is no objective answer to this question. Whether code is readable is mainly a personal opinion. I think you code isn't readable because it calls a lot of methods one after anthoer in a single line. I find it's hard to tell where one ends and the other starts.

So I suggest adding a few line breaks to clearly separate all calls:

var userName =
    query
        .Split('&')
        .SkipWhile(x => !x.StartsWith("username"))
        .First()
        .Split('=')
        .Last();

If you wrote it like this from the beginning it would also make your code much longer because you use very similar code in several places. This would probaly make you think does it have to be this way? and make you look for a different solution. This new solution is called encapsulation.

You don't want to have anything more the once. But more about this under the next question.

  Is it the best approach? if not how could i have made this better?

You need to define what best means to you.

Is the code best when it's short or when it's testable?
Is it best when it is quick&dirty written or is it best when it's maintainable?
Is it best when it's everything in one place or is is it best if you have dedicated modules for everything and use a lot of dependency injection?

My No. 1 definition of best (production) code is: testable + maintainable (this does not necessarily mean short and/or simple). To achieve this two goals you code needs to be at least DRY and it should satisfy the  Single Responsibility Principle.

This will make sure you can test each algorithm only once and if you find a bug you need to fix it in only one place.

Currently your code is not DRY. It repeats the same logic several times (parsing). It's also does not satisfy the SRP because it parses the query string and fills the cache by the same method.

You should encapsulate the parsing either by a helper method if this is the only place you need it or write a dedicated class and use it as a service with Dependency Incjection.

If you have everything already properly encapsulated you can always upgrade the code to a service if you need it later somewhere else. Why should you implement it again? I wouldn't, I'm lazy :-)

Your code could e.g. parse the query string into a dictionary which is much easier to use then always run through the entire string (worst case scenario) with Contains. Parse it once and reuse the results. I would, I'm lazy - but lazy is a good thing - it makes you write DRY code.

var query =
    uri
        .Query
        .TrimStart('?')
        .Split('&')
        .Select(x => x.Split('='))
        .ToDictionary(
            x => x[0],
            x => x.ElementAtOrDefault(1)
        );

I don't know if you always have pairs but in case you don't, the ElementAtOrDefault will make this not crash if a value is missing.

  Should i be worried with performance in this implementation?

This question can be answered only by you. You need to know how often it's called and whether it might become a potential bottleneck. But I'm pretty sure you won't see it in any benchmarks. There are parts in your code that are with certainty much slower. The best way to tell whether your code needs optimization and where, is to use a profiler.


Anytime that you check a count then do something on that you have to assume another thread did something in between.

for example this code

while (q.Count > m_poolSize)
{
    TValue localValue;
    q.TryDequeue(out localValue);
}

Because no locking is happening two threads could read the count and see it's over and both could remove an item.  Since you are using ConcurrentQueue both will remove different items.  This would cause your pool to drop below max size.  Maybe that's ok in your situation.

Same issue is applied when having the Keys being a ConcurrentQueue.  In theory if you had your max pool size lower than the processor count times 2 and each thread hit that line at the same time you could get an exception, since you would try to dequeue when the queue has no items in it.  Granted this is an extreme example and one not likely to hit but at a min you would want to catch that exception.

If you want to have the max stored in the pool you will need to do locking on an object and if we are going to do then both the ConcurrentQueue can go away.  The Keys I would replace as a list since that will do the array manipulation for us and change the ConcurrentDictionary values to just be a normal Queue.

private readonly ConcurrentDictionary<TKey, Queue<TValue>> m_pool;
private IList<TKey> m_keys;
private readonly object m_lock = new object();

We can simplify the Count method to use the concurrentDictionary GetOrAdd method

public int Count(TKey key)
{
    if (key == null)
        return 0;

    var q = m_pool.GetOrAdd(key, _ => new Queue<TValue>());
    return q.Count;
}

The Queue class implements ICollection and ICollection has a SyncRoot object.  To make it easy I would create a helper method so I don't have to cast to the Icollection each time I wanted the SyncRoot

private object SyncLock(ICollection collection)
{
    return collection.SyncRoot;
}

For the Request Method I would use the GetOrAdd again and lock on the return queue to know the count hasn't changed when Dequeued

public TValue Request(TKey key, Func<TValue> creator = null)
{
    if (key == null)
       return default(TValue);

    var q = m_pool.GetOrAdd(key, _ => new Queue<TValue>());
    lock (SyncLock(q))
    {
        if (q.Count > 0)
        {
            return q.Dequeue();
        }
    }
    if (creator != null)
    {
        return creator();
    }
    return default(TValue);

}

TryAdd method now needs locking as well.  Plus we will use the ConcurrentDictionary GetOrAdd method and pass in the value to add so we can tell if it added to the dictionary or if it returned back an existing value.

public bool TryAdd(TKey key, TValue value)
{
    if (key == null)
       return false;

    var addedQueue = new Queue<TValue>();
    var q = m_pool.GetOrAdd(key, addedQueue);

    lock (SyncLock(q))
    {
        q.Enqueue(value);
        if (q.Count > m_poolSize)
        {
            q.Dequeue();
        }
    }

    // If these are the same then we added to the concurrent dictionary
    if (q == addedQueue)
    {
        lock (m_lock)
        {
            m_keys.Add(key);
            if (m_keys.Count > m_poolSize)
            {
                var ejected = m_keys[0];
                m_keys.RemoveAt(0);
                TryRemove(ejected);
            }
        }
    }

    return true;
}

Since we add to both the keys and concurrentdictionary then check to see if over we should init them with plus one of the max count

public PooledDictionary(byte maxPoolSize)
{
    if (maxPoolSize <= 0)
        maxPoolSize = (byte)Math.Min(Environment.ProcessorCount, byte.MaxValue);

    m_poolSize = maxPoolSize;
    m_keys = new List<TKey>(maxPoolSize + 1);

    m_pool = new ConcurrentDictionary<TKey, Queue<TValue>>(Environment.ProcessorCount * 2, m_poolSize + 1);
}

In this implementation there is no need for while(q.Count > m_poolsize) as we controlling the adding an could only ever be one over the size.  Which is our trigger to remove one.


Off by one error

This loop goes over by 1 and writes past the last array element:

  for (int i = 0; i < maxLength; i++ ) {
    placer[ i + 1 ] += placer[i];
  }

You could either stop the loop at maxLength - 1, or rewrite the loop to start at 1 like this:

  for (int i = 1; i < maxLength; i++ ) {
    placer[i] += placer[i-1];
  }

Uninitialized variable causes crash

When I ran your program, it crashed due to an uninitialized variable, here:

int placer[maxLength];

Later on, you do placer[values[i]] += 1 without ever having cleared the placer array to zeros, so you can get garbage values in the array.  You can fix this by clearing the array like this:

memset(placer, 0, sizeof(placer));

However, I recommend not using variable length arrays.  One reason is that they are only optionally supported in the latest C standard.  The other reason is that sometimes you can overflow your stack if you allocate a large variable length array.  I would use calloc() here to allocate the counting array.

Simplify the function

It looks like you are using a version of counting sort that is used for radix sort, which needs to move elements around in the array.  For a simple counting sort, you don't need to do that.  After the counting pass, you can just fill in the original array with values from the counts, like this:

// Uses counting sort to sort an array which contains values in the
// range [0..65535].  The counting array is allocated using calloc() in
// order to avoid putting a large array on the stack.
void sort(int values[], int n)
{
    const int maxLength = 65536;
    int      *counts    = calloc(maxLength, sizeof(*counts));

    if (counts == NULL) {
        return;
    }

    for (int i = 0; i < n; i++) {
        counts[values[i]]++;
    }

    int outIndex = 0;
    for (int i = 0; i < maxLength; i++) {
        for (int j = 0; j < counts[i]; j++) {
            values[outIndex++] = i;
        }
    }

    free(counts);
}