Using jQuery 1.7 .on() and event.stopPropagation to close boxes when clicking in document body

It did work in my Chrome. However, I felt your code was confusing with all those handlers. Let me suggest the following:

$('html').on('click', '.poster', function(e) {

  var target = $(e.target);
  var poster = $(this);

  if (!poster.hasClass('active')) {
    closeQuickView();
    poster.addClass('active').find('.quick-view').fadeIn(200);
  }
  if (target.hasClass('quick-view') || target.hasClass('image-effect')) e.stopPropagation(); // prevent bubbling and thus closeClickView call below
});

$('html').on('click', closeQuickView);

This way, it's more concise and hopefully clearer what's handling what.

PS: I threw out the conditional '.close' appendage here, nothing wrong with having it in the vanilla HTML I'd say.


My simple implementation of a DI container

What you're actually doing is implementing Service Locator which is quite opposite to dependency injection. Please refer to [THIS] discussion about it.

Please use already existing solution.

Few points from my side, just to point out why I think that's wrong for your case:

Why do you think you need more lightweight DI container? Have you performed benchmarks and they proved that your bottle neck is DI injection?
Why have you choosen struct for DIReference? Struct is not good choice for a field, because you're unintenionally (I presume) allocating it on heap. Please refer to [THIS] discussion.
Why would you need DIReference anyway? It's only complicating your code. You don't need to store it as field anywhere - instances that you need are already kept in _references in DIContainer.
Just to point out, as your _references is static readonly field, then this Dictionary is singleton. It causes few potential problems, to name two:

Is it guaranteed that every time you install bindings there won't be any other threads that trying to do same thing?
Every instance in this dictionary is also singleton-ish. What I mean by that - as soon as first class will install PlayerController into your _references in DIContainer then it'll be available for all classes that uses your DIContainer class. Yet you can still overwrite it. Why would that be a problem? It could cause huge GC pressure, because you'll constantly overwriting PlayerController in your dictionary and GC will have to clean that up which could lead to stopping all threads from running. You definitely want to avoid that especially in games.

I want to strongly suggest to use already existing solution for DI. If you're worried about performance please refer to [THIS] benchamrks.


Handling parsing failure in Scala without exceptions

Having monads in your data structures is not messy, they allow you always to flatten their content during nested calculation steps. A simple definition of them can be:

trait Monad[A] {
  def map[B](f: A => B): Monad[B]
  def flatMap[B](f: A => Monad[B]): Monad[B]
}

Because Option is a monad you do not have to work with nested types:

scala> def inc(i: Int) = Option(i+1)
inc: (i: Int)Option[Int]

scala> val opt = inc(0)
opt: Option[Int] = Some(1)

scala> val nested = opt map inc
nested: Option[Option[Int]] = Some(Some(2))

scala> val flattened = opt flatMap inc
flattened: Option[Int] = Some(2)

Thus, there should never be a reason to nest monads deeply. Scala also has the for-comprehension which automatically  decomposes monads:

scala> :paste
// Entering paste mode (ctrl-D to finish)

val none = for {
  o1 <- inc(0)
  o2 <- inc(o1)
  o3 <- inc(o2)
} yield o3

val some = for {
  o1 <- inc(0)
  o2 <- inc(o1)
  o3 <- inc(o2-1)
} yield o3

// Exiting paste mode, now interpreting.

none: Option[Int] = None
some: Option[Int] = Some(2)

In order to work with exceptions scala.util.Try is introduced in 2.10:

scala> import scala.util.{Try, Success, Failure}
import scala.util.{Try, Success, Failure}

scala> def err: Int = throw new RuntimeException
err: Int

scala> val fail = Try{err} map (_+1)
fail: scala.util.Try[Int] = Failure(java.lang.RuntimeException)

scala> val succ = Try{0} map (_+1)
succ: scala.util.Try[Int] = Success(1)

Nevertheless, Try should only used when you have to work with exceptions. When there is no special reason, exceptions should be avoided - they are not here to control the control flow but to tell us that an error occurred which normally can not be handled. They are some runtime thing - and why to use runtime things in a statically typed language? When you use monads the compiler always enforces you to write correct code:

scala> def countLen(xs: List[String]) = Option(xs) collect { case List(str) => str } map (_.length)
countLen: (xs: List[String])Option[Int]

scala> countLen(List("hello"))
res8: Option[Int] = Some(5)

scala> countLen(Nil)
res9: Option[Int] = None

scala> countLen(null) // please, never use null in Scala
res13: Option[Int] = None

With collect you ensure that you don't throw an exception during matching the contents. After that with map one can operate on the String and doesn't care anymore if an empty or a full list is passed to countLen.

Now, look at the documentation of Option, there are more useful methods which allow safe error handling. The only thing to keep in mind is not to use method get or a pattern match on the monad during calculation:

scala> Some(3).get
res10: Int = 3

scala> None.get // this throws an exception
java.util.NoSuchElementException: None.get

// this looks ugly and does not safe you from anything because it is equal
// to a null check
anyOption match {
  case Some(e) => // no error
  case None => // error
}

Now you may ask how to get the contents of a monad? That is a good question and the answer is: you won't. When you use a monad you say something like: Hey, I'm not interested if my code threw an error or if all worked fine. I want that my code works up to end and then I will look what's happened. Pattern matching on the content of a monad (means: accessing their content explicitly) is the last thing which should be done and only if there is no other way any more to go further with control flow.

There a lot of monads available in Scala and you have the possibility to easily create your own. Option allows only to get a notification if something happened wrong. If you wanna have the exact error message you can use Try (for exceptions) or Either (for all other things). Because Either is not really a monad (it has a Left- and a RightProjection which are the monads) it is unhandy to use. Thus, if you want to effectively work with error messages or even stack them you should take a look at scalaz.Validation.

EDIT

To address your edit, it seems that you never know the type you can get. This will complicate things a lot since you have to check the type of each element explicitly. I don't think it is possible to do this in a clean way without the use of a library which can do the typechecks for you. I suggest to take a look at some Scalaz or Shapeless code.

Nevertheless is is far easier to do such type checks in the parser and not in the AST traverser. Thus, I suggest using a JSON parser which can handle a type format given by the user and returns an error if it finds some unexpected content. I don't know if Play! can parse things like the following (which can be done in lift-json):

val json = """{ "foo": [1, 2, 3], "bar": [2, 5] }"""
class Content(foo: List[Double], bar: List[Double])
parse(json).extract[Content]


Create database connection and run the insert, delete, update queries class-Update

You won't gain any advantage by using abbreviations for your parameter/variable names but you will loose readability. Therefor I would like to suggest to use more descriptive names. Otherwise you will come back in a couple of weeks/months and you will be wondering what e.g int _rc; should represent.

This

if (String.IsNullOrWhiteSpace(dbCmd))
{
    throw new ArgumentException("Invalid Connection String");
}

in your ExecuteCmd() method shows why copy&pasta should be done in a wise way.

In addition you never check if the passed in SqlParameter para is null. In a public method you should always validate all passed in parameters.

As DbConnection is implementing IDisposable you should enclose its usage into a using block. This would also remove the need to have a CloseConnection() method. Hence this would result in removing the IDbConSetup interface.

Instead of having a public OpenConnection method you could pass the connection string to the constructor and make the method private. In addition you won't really need the class level field private SqlConnection _dbconnect;.

Methodlevel variables shouldn't be prefixed with an underscore. This is usually only done for class level variables.

A sample of a simplified DAL which still needs to be expanded.

Note this isn't tested

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;

public class SimplifiedDal
{
    private readonly DbProviderFactory dbFactory;
    private readonly string connectionString;
    public SimplifiedDal(string connectionString, string providerFactory)
    {
        if (string.IsNullOrWhiteSpace(connectionString))
        {
            throw new ArgumentException("Value may not be null or whitespace", "connectionString");
        }
        if (string.IsNullOrWhiteSpace(providerFactory))
        {
            throw new ArgumentException("Value may not be null or whitespace", "providerFactory");
        }
        dbFactory = DbProviderFactories.GetFactory(providerFactory);
        this.connectionString = connectionString;
    }
    public int ExecuteNonQuery(string sql, CommandType commandType, Dictionary<string, object> parameters)
    {
        if (string.IsNullOrWhiteSpace(sql))
        {
            throw new ArgumentException("Value may not be null or whitespace", "sql");
        }

        using (var connection = dbFactory.CreateConnection())
        {
            connection.ConnectionString = connectionString;
            connection.Open();
            using (var command = connection.CreateCommand())
            {
                AddParameters(command, parameters);
                return command.ExecuteNonQuery();
            }
        }
    }
    private void AddParameters(DbCommand command, Dictionary<string, object> parameters)
    {
        if (parameters == null || parameters.Count == 0) { return; }
        string dbFactoryName = dbFactory.GetType().Name;
        if (dbFactoryName == "OleDbFactory" || dbFactoryName == "OdbcFactory")
        {
            AddOleDbOdbcParameters(command, parameters);
            return;
        }

        string parameterPrefix = GetPrefixByFactoryName(dbFactoryName);
        foreach (var kvp in parameters)
        {
            var parameter = command.CreateParameter();
            parameter.ParameterName = parameterPrefix + kvp.Key;
            parameter.Value = kvp.Value;
            command.Parameters.Add(parameter);
        }
    }
    private string GetPrefixByFactoryName(string factoryName)
    {

        switch (factoryName)
        {
            case "SqlClientFactory":
                return "@";
            case "OracleClientFactory":
                return ":";
            case "MySqlClientFactory":
                return "?";
        }
        throw new NotImplementedException();
    }
    private void AddOleDbOdbcParameters(DbCommand command, Dictionary<string, object> parameters)
    {
        foreach (var kvp in parameters)
        {
            var parameter = command.CreateParameter();
            parameter.ParameterName = "?";
            parameter.Value = kvp.Value;
            command.Parameters.Add(parameter);
        }

    }

}

which can be used like so

//MS Access
var msConnectionString = "A MS Access connection string";
var msDal = new SimplifiedDal(msConnectionString, "System.Data.OleDb");

//MySql
var mysqlConnectionString = "A MySQL connection string";
var mysqlDal = new SimplifiedDal(mysqlConnectionString, "System.Data.OleDb");

//MS Sql
var sqlConnectionString = @"A Sql connection string";
var sqlDal = new SimplifiedDal(sqlConnectionString, "System.Data.SqlClient");

you can easily check which factories are installed by using

DataTable table = DbProviderFactories.GetFactoryClasses();


Is_prime check in Python: can this be more pythonic?

Your code looks nice, seems to follow PEP 8 and has docstrings. I don't have much to say about it but here are a few changes to make it look more pythonic.

The while loop can be rewritten using a for loop with range (or xrange).

for divisor in xrange(5, 1+int(math.sqrt(n)), 6):
    if n % divisor == 0 or n % (divisor + 2) == 0:
        return False
return True

Then, this looks like a scenario where we could use all/any. The obvious way to convert the code above is :

return not any(n % divisor == 0 or n % (divisor + 2) == 0 for divisor in xrange(5, int(math.sqrt(n))+1, 6))

but it looks better (and makes more sense) to use all with reversed conditions :

return all(n % divisor != 0 and n % (divisor + 2) != 0 for divisor in xrange(5, int(math.sqrt(n))+1, 6))

then, you can use the fact that non-zero numbers evaluates to True in a boolean context (and zero evaluates to False) :

return all(n % divisor and n % (divisor + 2) for divisor in xrange(5, int(math.sqrt(n))+1, 6))

Then, you could use the same kind of idea in the previous if then merge duplicated code :

return n % 2 and n % 3 and all(n % divisor and n % (divisor + 2) for divisor in xrange(5, int(math.sqrt(n))+1, 6))

This is pretty much all I have to say about the code. Now, I think it might be worth commenting the algorithm a bit more.

def is_prime(n):
    """ Check if n (assumed to be an int) is a prime number. """
    # Handle values up to 3
    if n < 2:
        return False
    if n in (2, 3):
        return True
    # Handles bigger values : divisors for n have to be
    # * multiples of 2
    # * multiples of 3
    # * of the form 5 + 6*i or 5 + 6*i + 2 (other cases already handled)
    return n % 2 and n % 3 and all(n % divisor and n % (divisor + 2) for divisor in xrange(5, int(math.sqrt(n))+1, 6))


I think you have over complicated things and I don't think it works for the generic tree (as your create_mirror_for_[left|right]_subtree() only recurse down one side of the tree.

Why the test before a swap?

tree_node* temp = 0;
if(root->left)
    temp = root->left;    // If left is NULL you can still assign it
                          // to temp and get the same result.
root->left = root->right;
if(temp)
    root->right = temp;
else
    root->right = NULL;   // If temp is null you could just assign
                          // it to right then both sides of the branch
                          // are identical and they collapse into a
                          // single statement.

// Much easier to write as:
tree_node* temp = root->left;
root->left      = root->right;
root->right     = temp;

// Which of course can be replaced by std::swap
std::swap(root->left, root->right);

I assume you want to swap all nodes in the tree (otherwise it's not a mirror).

class Tree
{
    public:
        void mirrorTree()
        {
            root.mirrorTree(root);
        }
    private:
        void mirrorTree(Node* node)
        {
            if (node == nullptr) {
                return;
            }
            using std::swap;
            swap(node->left, node->right);
            mirrorTree(node->left);
            mirrorTree(node->right);
        }
};


Collecting files from a particular directory

README:
First off, I'll just focus on making this one class a tad more generic, and expandable and maintainable and... well, generally more OO. Then, though I'm not going to go into too much detail on the matter, I'll just list a few quick tips of how you could go about separating concerns even more and create an entire File namespace.
Code-review can be harsh, but I do not intend to be hurtful or patronizing. My intentions are simply to convey, to the best of my abilities my views on what might be a preferable approach. I base this on experience, as well as personal preference and. While I try to be as objective as possible, I'm only human, so it stands to reason that the code I suggest might not be to your liking. But the code listed here is untested, written off the top of my head and only serves to illustrate my point.

This class/method definitely could do with a couple of additional methods. For example: I might want to set a path, and then -at various points in time- want to get reflection classes for a given "gateway namespace".
Your code, as it now stands would imply calling the collect method with the same $path argument, which will create an all-new RecursiveDirectoryIterator instance, only to get those files I'm after.

If, however, your class would look like this:

class Collector
{
    protected $iterator = null;
    public function __construct($path = null)
    {
        if ($path) $this->setPath($path);
    }
    public function setPath($path)
    {
        $this->iterator = new \RecursiveDirectoryIterator(
            dirname(__FILE__) . $path
        );
        return $this;
    }
    public function collect($namespace, $path = null)
    {
        $return = array();
        if ($path !== null) $this->setPath($path);
        foreach(new \RecursiveIteratorIterator($this->iterator) as $file)
        {
            $class = str_replace('.php','', basename($file));
        }
    }
}

You allow users to set the base-path when creating the instance, and then use that instance to get whatever reflection classes they will be needing at any given moment.
Moreover, you can expand on this "theme" even more, by allowing them to set a property that you can use instead of using dirname(__FILE__), which -if we're honest- isn't really improving the reusability of your current code.

I also struggle to see the point in a method that only allows reflection on abstract classes only:

if((new \ReflectionClass($constructedClass))->isAbstract())

Why not create reflection classes for all matched files, and assign them to a property, so you can then use a getter where the user can specify which classes he/she needs?

class Collector
{
    const COLLECT_ABSTRACT = 0;
    const COLLECT_REGULAR = 1;
    const COLLECT_BOTH = 2;
    //properties:
    $iterator = null;
    $collection = array();
    public function getCollection($gatewayNS, $which = self::COLLECT_ABSTRACT)
    {
        if (!isset($this->collection[$gatewayNS]))
            $this->getNS($gatewayNS);
        if (!isset($this->collection[$gatewayNS][$which]))
            throw new \InvalidArgumentException('invalid offset (0,1,2 are allowed)');
        return $this->collection[$gatewayNS][$which];
    }

    private function getNS($ns)
    {
        $this->collection[$ns] = array(
            self::COLLECT_ABSTRACT => array(),
            self::COLLECT_REGULAR  => array(),
            self::COLLECT_BOTH     => array()
        );
        foreach(new \RecursiveIteratorIterator($this->iterator) as $file)
        {
            $class = $ns.str_replace('.php','', basename($file));
            if (class_exists($class))
            {
                $class = new \ReflectionClass($class);
                $this->collections[$ns][self::COLLECT_BOTH] = $class;
                if ($class->isAbstract())
                    $this->collection[$ns][self::COLLECT_ABSTRACT] = $class;
                else
                    $this->collection[$ns][self::COLLECT_REGULAR] = $class;
            }
        }
        return $this->collections[$ns];
    }
}

That should help you on your way to turn this one-method-function-in-OOP-drag thing into a bona-fide class, that you can use in future projects, as well as your current one.
This is, of course, just a start. This class still needs some more work, and actually, could do with some helper classes, too. As I said, I'm not going to deal with this in great detail, but just as a primer/list of suggestions. The first one, though, is not a suggestion, but an appeal:

Code should document itself
Looking at your code, I'm not at all aware of all the other classes you're using, lest I browse through the actual code. Namespaced class files should start with a series of use statements, that tell me what other classes they depend upon. That way, I can get a rough Idea of what classes I can expect to see in the return values, and which objects are going to be valid as arguments, too.
That, and of course: nobody likes to see all those backslashes throughout the code.

Clear Interface is not optional
A clear-cut, consistent interface isn't just a nice-to-have thing. It's vital. If you want to churn out code you can pass on to others, or re-use without having to refactor half of it, you need to stop and think about what data is likely to be passed to your classes
You're iterating directories, in search of files. So yes, strings are likely candidates for arguments. As are SplFileInfo instances, don't you think?

Now, to add support for these instances, you have 2 choices: Either check the type of the argument that is passed ($arg instanceof \SplFileInfo) or create a wrapper.
IMO, the wrapper is the way to go, as it normalizes your API, allows for type-hints and centralizes all code concerning how you deal with file-paths in a couple of classes. If ever the SplFileInfo class changes, you can update those classes and be done with it all, certain that all other code will work fine.

Read up on what the SplFileInfo class can do for you. If you're interested, write a constructor that accepts either an instance of this class or a string, and -if you receive a string- use that to construct an SplFileObject asap.

Collector is a container
If you do set about writing a File-managing lib, this Collector shouldn't contain anything but processed files. It's a data-container, not a data processor.
You should consider writing some file-parsers (or "Adapters"), that each deal with a specific type of file. They can implement various interfaces, like the ParserInterface for the (and I'm just making these names up as I type) DOMFile, PHPFile and YamlFile classes). This signals users that these classes can process a files content.
Another interface could then be CompressorInterface, which might be useful when dealing with gzipped text files.
Of course, all these classes can extend from a generic abstract class FileAdapter or something, that specifies generic read-write methods, and perhaps allows the user to change the mode to binary, read-only, or even stream... Just go wild here :)

Remember, remember: files are files
After all this talk and suggestions of what you can do, it's important to stress that, while you can do a lot, you can take things to far: these are files, and files mean I/O. If you build an API that lends itself to file usage a bit too well, you could end up with people using files as a replacement for DB storage. Don't.
If people might use your API as an alternative to caching, or simple DB's, then you might have over-done it.

Copy with pride, but credit
A lot of open-source projects do offer some classes to read/process files already. There's nothing wrong with looking at those for inspiration. Copy what you need, provided the license permits it. And of course, feel free to contribute, too :)


Check if all lotto numbers are covered in input

First, this will not work with the input 99.  Arrays are 0-indexed, but when you create one, you need to specify the value you wish .length to have, which is 100.

This part is also erroneous:

while (ticketNumber != 0) {
    for (int i = 1; i <= neededNumbers.length; i++) {
        neededNumbers[i] = true;
    }
    ticketNumber = input.nextInt();
}

Here, you input the values until the input equals 0, but you loop from 1 through needeNumbers.length and set the values to true.  First off, this will crash when you run it because the value neededNumbers[neededNumbers.length] does not exist.  Additionally, your logic is wrong as you do not want all the values of neededNumbers to be set to  true, just the input ones:

while (ticketNumber != 0) {
    neededNumbers[ticketNumber] = true;
    ticketNumber = input.nextInt();
}

This loop is almost right, but you check the value an index 0, which you did not set to true because 0 was the value to exit the loop:

for (int i = 0; i < neededNumbers.length; i++) {
    if (neededNumbers[i] == false) {
        System.out.println("You do not have all the numbers.");
        System.exit(0);
    }
}

You can solve this problem in one of two ways - starting with i = 1, or changing your while loop to use neededNumbers[ticketNumber - 1] = true; and intializing it to new boolean[99], like you currently do.  This will have value 1 be stored in the 0 index of the array, so all values will be set to true once all the numbers in the range of 1 - 99 have been entered.


Classifying lexemes in a given C program

Remove all these literals from the stack and place them in the .rodata/.const section of the executable image:

const char keywords[32][20]={"auto","break","case","char",
                            "const","continue","default","do","double",
                            "else","enum","extern","float",
                            "for","goto","if","int","long",
                            "register","return","short","signed",
                            "sizeof","static","struct","switch",
                            "typedef","union","unsigned",
                            "void","volatile","while"};

One very good way to do that would be to make it an array of pointers:

const char *keywords[]=
{
    "auto","break","case","char",
    "const","continue","default","do","double",
    "else","enum","extern","float",
    "for","goto","if","int","long",
    "register","return","short","signed",
    "sizeof","static","struct","switch",
    "typedef","union","unsigned",
    "void","volatile","while"
};

Similar considerations should be applied to the literal array in the isOperator() function.

Regarding this line:

for(int i=0;i<32;i++)

Do not use 'magic' numbers (other than 0 and 1) in the code as they are a maintenance nightmare. I suggest:

for(size_t i=0; i<(sizeof(keywords)/sizeof(char*)); i++)

Regarding this line:

for(int i=0;token[i]!=(char)NULL;i++)

This will not work quite correctly, as NULL is the size of a pointer and I think the code is looking for '\0', not NULL.

I suggest:

Note, no need to make any comparison as the contents of token[i] is either in the range 0x01...0xFF or 0x00 - and 0x00 will be seen as false.

for(int i=0; token[i];i++)

When #defineing a numeric value, always wrap the value in parens to avoid any possibility of 'text replacement' errors.

Regarding these lines:

fgets(string,sizeof string, fp);
while(string!=(char *)NULL || (strcmp(string,"\n"))==0)

string will NEVER be NULL because string is not a pointer
there is never a need to cast NULL

I suggest:

while( fgets(string,sizeof string, fp) )

To get the actual reason that a call to fopen() fails, change this:

FILE *fp = fopen(param2[1],"r");

if(!fp)
{
    fprintf(stderr,"File access denied on read. \n");
    exit(1);
}

to: (perror() will output the system message for the current value of 'errno')

FILE *fp = NULL;
if( NULL ==( fp = fopen(param2[1],"r") ) )
{ // then fopen failed:
    perror( "fopen for input file failed" );
    exit( EXIT_FAILURE );
}

I suggest that main() check the number of parameters and if not correct, then output a 'USAGE' statement and exit.  This would greatly simplify the readfile() function, which is not actually reading a file, but rather just opening a file.

There are plenty of other details that could be improved, but the above should get you started.


Firstly, we cannot rely on arguments that the "compiler isn't smart enough to do that" because that may change tomorrow. We need to base our assessment of the code on what the compiler is and isn't allowed to do.

Given two input strings and a yes/no return if the string match, any program performing the function can be transformed into the trivial short-circuited for-loop. Provided that there isn't anything prohibiting the compiler from doing the transform.

Will writing the sum of xor differences to a volatile prevent the transform? Maybe, it depends on the execution model and guarantees of volatile in Java. In C++ under the as-if rule all writes and reads to/from volatile memory regions must occur in the same order as-if the program was executed according to the wording in the standard (somewhat simplified but that's the gist of it). So for C++ this would work; However I'm unsure if Java has the same guarantee. For C++ this limitation is natural because it must be able to interface with device drivers and bus addresses where writes and reads cannot be re-ordered or omitted. But Java does none of the kind and as such I wouldn't be terribly surprised if volatile has a more lax meaning in Java.

What about SecureRandom? Well it is really just volatile reads from /dev/urand in disguise to get the seed, the rest is deterministic which the compiler that compiled the JVM isn't allowed to reorder or remove, but what the JIT is allowed to do in this context is beyond me. It is conceivable that the JIT can deduce that the read from /dev/urand will not affect the program in an observable way and it will remove the code all together.

If the volatile keyword doesn't have the same meaning in Java as in C++ I believe that doing this kind of processing in Java in a reliable and guaranteed way is difficult. I would consider a hand written loop in assembler in a JNI library, this is guaranteed by your C/C++/assembler to not be fudged in any way.

I'm sorry this isn't an authoritative yes/no answer on correctness, but I hope that it is of some help any way.


Advent of code 2017 Day 1 (1) in Functional Programming

As far as functional programming goes, this looks pretty nice to me,
clear and readable.

One performance drawback is the splitting to a string array.
The size of the array will be similar to the input,
and it can be much smaller if you apply a filter directly on the input.
Although strings don't have a filter method like arrays,
since the selectTwins function would work on strings,
you could apply the filter method of arrays on the input directly:

[].filter.apply(parsedInput, [selectTwins])

Another performance drawback is that the input is scanned twice:
once to replace whitespace characters, and once more for splitting.
We could use the same technique as earlier to apply a filter on the input directly instead of using a regex replacement.

Putting the above suggestions together:

const isDigit = x => /\d/.test(x);
const solution = [].filter.apply(INPUT, [isDigit])
  .filter(selectTwins)
  .map(toNumber)
  .reduce(sum, 0);


You could cache $("#eventurl") and $("#js-skipbutton") so jQuery won't search those elements multiple times, that's a little speed up.

var eventulr = $(document.getElementById("eventurl"));
var js_skipbutton = $(document.getElementById("js-skipbutton"))

It's not necessary to check for focus or focusout events in an input element (specially the focusout event, that is used for event bubbling).

Instead, only check for keypress event. This way you won't be checking if the input element is empty every 200 milliseconds whether the user is pressing a key or not

eventurl.on("keypress", Change);

Edit

Since keypress event is not triggered when text is pasted into the input element you can listen for keyup event instead; Which is triggered whenever a key is released (Including Ctrl, Shift, etc.). Or rely on jQuery's change() method which works with input, select, textarea elements.

eventurl.change(Change);


Key / Value store with type classes for formatting / parsing

I don't see how to understand the KeyValueStore without understanding the ValueFormat implementation you reference. You don't have any substantial comments in either implementation, including "why". Their mutual dependency makes it very difficult to review either of them.

Readability issues:

You use ValueReader[S,T] in the KeyValueStore and ValueReader[T] in the ValueFormat -- this caused many minutes of confusion and blind paths.
Similarly, you define trait ValueReader[S,T] and then you immediately turn around and use ValueReader[T,S] in the body of KeyValueStore. Swapping the parameters causes more confusion.


Conditional logic to determine if popup menu should be visible

You may not need another if else to setEnabled. The expression within if returns a boolean. Just set the inverse of it to setEnabled. You can pull it into a variable in case of better readability.

Updated:

if (attentionSignalAction != null) {
  bool isActiveRowSelected = (Framework.getInstance().getActiveSubjectOfCare().id == null||!getAcuteListTable().getTableDataByRow(getAcuteListTable().getSelectedRow()).socId.equals(Framework.getInstance().getActiveSubjectOfCare().id));
  attentionSignalAction.setEnabled(!isActiveRowSelected);
}

Update 2

if(selectedOperations != null && selectedOperations.length > 1){
    listRegistraionOpenMenuItem.setEnabled(false);
}else{
    listRegistraionOpenMenuItem.setEnabled(true);
}

can also be reduced to

bool operationsSelected = (selectedOperations != null && selectedOperations.length > 1);
listRegistraionOpenMenuItem.setEnabled(!operationsSelected);


Vigenere Cipher - Haskell Implementation

Do you think the implementation is efficient

No, sorry. You're heading in the right direction, but !! makes your algorithm \$\mathcal O(n^2)\$, and if it wasn't for !!, appending c' to the cipherText would also lead to \$\mathcal O(n^2)\$ due to ++. Or taking the length all the time. Well, basically any function that you use in each iteration that needs to (possibly) traverse the complete list makes your function non-efficient.

But let us start at the top. I suggest you to put your documentation before the type signature. That way, the type and the names are still close, which makes your function easier to understand if height is limited:

-- shift applies a arithmetic function to given characters
-- after converting it from ASCII value to Int
-- This can be used to Encrypt or Decrypt the character
shift :: (Int -> Int -> Int) -> Char -> Char -> Char
shift f i k = let i' = ord i - 65
                  k' = ord k - 65
              in  chr $ ((f i' k') `mod` 26) + 65

Next, you seem to use a very specific interpretation of Char as Int, namely the position in the alphabet. This is fine, but if you use - 65 and + 65 all the time, it's going to be hard to update it to a larger alphabet. A pair of additional functions and values can help:

toInt :: Char -> Int
toInt c = ord c - 65

fromInt :: Int -> Char
fromInt i = chr i + 65

alphabetSize :: Int
alphabetSize = 26

-- feel free to add your documentation here
shift :: (Int -> Int -> Int) -> Char -> Char -> Char
shift f i k = let i' = toInt i
                  k' = toInt k
              in  fromInt $ f i' k' `mod` alphabetSize

By the way, with on from Data.Function one could write

shift :: (Int -> Int -> Int) -> Char -> Char -> Char
shift f i k = let f' = f `on` toInt
              in  fromInt $ f i k `mod` alphabetSize

but that's just a remark (Exercise: try to guess on's type. How would a valid implementation look like?).

Next, we head over to crypt. Let us assume for a second that the key is longer than the text we want to encrypt. We want to encrypt each character on its own. So if we have a string, we can pattern match. We start with the easier case:

crypt' :: (Int -> Int -> Int) -> String -> String -> String
crypt' _ [] _ = []

If there's nothing to encrypt, there's nothing to return. Now, what should we do if there is at least one character? Well, we check whether it is a space. If it is a space, we add a space to our result and continue on the rest:

crypt' f (' ':ws) ks = ' ' : crypt f ws ks

A space goes in, a space goes out. We do not change the key. So now there is only one case missing: the one where we have a character that's not a space:

crypt' f (w:ws) (k:ks) = shift f w k : crypt f ws ks

A character goes in, a character from the key goes in, we use the function to shift and create the result, and then we continue on our other words and keys.

Here's crypt' at once:

crypt' :: (Int -> Int -> Int) -> String -> String -> String
crypt' _ []       _      = []
crypt' f (' ':ws) ks     = ' '         : crypt' f ws ks
crypt' f (w:ws)   (k:ks) = shift f w k : crypt' f ws ks

However, this does only work if the key is longer than the text. How do we write crypt, which may take a smaller key? We use cycle:

crypt :: (Int -> Int -> Int) -> String -> String -> String
crypt f w k = crypt' f w (cycle k)

That's not necessary by the way, you could have defined a function inside of crypt, check whether the "local" key is [] and then start over:

crypt f w k = go w k
  where
    go ...

but that's left as another exercise.

Further remarks

  Do you think the implementation is … [an] obvious way to do it?

It's an obvious way in imperative languages, which have a string as an array or similar data structure, since index-wise accessing is fast, and .push_back or other "append-single-character-at-end" functions are usually (amortized) constant.

So if you're coming from an imperative language, yes, that would be the obvious way to implement it there (well, aside from the recursiveness).

But in Haskell keep in mind that lists are, well, lists. If you want to access the 20th element, you have to skip the first 19. !! isn't a care-free operation like a vector access in several other operations. Neither is length. That's why it's usually a good idea to pattern match (or use higher-order-functions) and create the list with :.

Exercises

Adjust encrypt and decrypt to crypt's new type.
What is the type signature of cycle? Can you implement it yourself?
(*) Instead of (Int -> Int -> Int), have crypt use (Char -> Char -> Char). (Why?)
(*) Make it possible to use both upper and lower characters in your text.
(*) Keep unsupported characters
(**) Instead of (Char -> Char -> Char), have crypt use (a -> a -> a). (Is this possible? What do you have to change to make it possible? Why?)
(***) Make it possible to encrypt/decrypt arbitrary alphabets, if given "nice" toInt and fromInt functions.


There isn't much to review in 6 lines of code. But oh well.

Native methods return error codes, so it is good practice to handle those codes somehow, not just ignore them. For example, if method reports, that there is no sound driver or no sound card or w/e, it makes sense to notify user somehow. Write warning in the status bar of your window or something.
It is meaningless to initialize CurrVol, since its value will be overriden anyway, wont it? And, if its your real code, you dont have to recieve current volume in order to set it to begin with.
Convert.ToString should be refactored to String.Format("Volume: {0}%", trackBar1.Value);. More complex example:

var status = String.Format("Current Buffer: {0} Clear: {1} Ping: {2} Buffer: {3}", waveProvider.BufferedDuration.Milliseconds, TimesBufferClear, PingReply, SendStream.BufferMilliseconds);


Calculating the Collatz conjecture of a number

Single Responsibility Principle

The CollatzConjecture method is the so called god-method. What does this mean? It does everything. But what exactly? I has three responsibilities:

read the number from the console
calculate the Collatz Conjecture
print the results

Each of those features should be encapsulated in their own method. But why? So that you can better test it. Currently you cannot write a unit test to validate whether the calculation is correct because it's bound to the console so you need to extract the math first:

public static IEnumerable<int> CollatzConjecture(int value)
{
    while (value > 1)
    {
        value =
            (value % 2) == 0
            ? value / 2
            : value * 3 + 1;

        yield return value;
    }
}

Now you have a deferred method that does the math. Notice the yield return.

You could already use it but you want to see the output so you need another method that can print it. Here it is:

public static void PrintCollatzConjecture(int number, IEnumerable<int> collatzConjecture, int delayInMilliseconds = 100)
{
    var counter = 0;
    foreach (var value in collatzConjecture)
    {
        Console.WriteLine("Element {0} of the {1}'s collatz sequence is: {2}", ++counter, number, value);
        Thread.Sleep(delayInMilliseconds);
    }
    Console.WriteLine("The Collatz Conjecture sequence for the number {0} contains {1} numbers", number, counter);
    Console.WriteLine("The Collatz Conjecture sequence has been calculated, press enter key to exit");
    Console.ReadLine();
}

No magic here. Just an ordinary loop that prints each element. Additionally you can specify a different delay.

To make it interactive you need to create the third method that will read the number from the user:

public static int ReadNumber()
{
    Console.WriteLine("Enter an integer number into the program to calculate its Collatz Conjecture sequence:");

    var result = 0;
    var input = (string)null;

    var isValidNumber = true;
    do
    {
        if (!isValidNumber)
        {
            Console.WriteLine("Please insert an integer number:");
        }
        input = Console.ReadLine();
        isValidNumber = int.TryParse(input, out result);
    } while (!isValidNumber);

    Console.WriteLine("The entered number is {0}, calculating Collatz's sequence:", result);

    return result;
}

All three features are now encapsulated. You are free to modify and optimize any of them without breaking the other two. This is what we always strive for. One module/class/method does only one thing at a time.

If you assemble everything your Main will be nice and short:

void Main()
{
    var number = ReadNumber();
    var collatzConjecture = CollatzConjecture(number);
    PrintCollatzConjecture(number, collatzConjecture);
}

C# 6

With the latest C# there is an easier way to build string. You can put the variables inside them. In order to do this you need to prefix it with the $ e.g.:

Console.WriteLine($"The entered number is {result}, calculating Collatz's sequence:");


You can also chain the Comparators using thenComparing

CASE_INSENSITIVE_COMPARATOR = Comparator.comparing((Function<String, String>) String::toLowerCase)
                                        .thenComparing(o -> o);

Official Java docs on thenComparing.


Your use of the boolean return value of the Set.add() call is a clever way to check for your duplicates. The concept you have is good, and I can't think of a faster way.

Additionally, I like how you have used Interface-based types on the left-side of assignments Set<String> and the concrete classes on the right new HashSet<>() .... people often put the concrete type on the left too, and it's good to see that you did not.

In terms of the Java streaming API, though, I can't help but feel that you missed out on an opportunity to improve the process by streaming the split.... The Pattern class has a splitAsStream method which would reduce your latency on the first words....

As an aside, a word should probably be on a contiguous whitespace, not just a single space (i.e. "\\s+" instead of " ").

Here's your code done differently:

private static final Pattern SPACE = Pattern.compile("\\s+");

public static Set<String> findDuplicateWordsInText(String text) {
    Set<String> duplicatesRemovedSet = new HashSet<>();
    return SPACE.splitAsStream(text)
            .filter(string -> !duplicatesRemovedSet.add(string))
            .collect(Collectors.toSet());
}


public void Resize(string filePath, string dropLocation, List<Size> sizes)

Why List<>? Following the principle of coding to the interface rather than the implementation, this should probably be IList<> or even IReadOnlyList<>.

        Parallel.ForEach(sizes, async (size) =>
        {
            var fileName = Path.GetFileName(filePath);
            var result = await Resize(filePath, dropLocation, size);
            Console.WriteLine($"Done {result} Resizing {fileName} to {size}");
        });

Why async/await inside Parallel.ForEach? If each size is handled on a different thread, there's nothing to be gained by using await.

            var newFilePath = $"{dropLocation}{newFileName}";

Path.Combine exists for a reason: using that rather than manual concatenation will give more robust code.

            await Task.Run(() =>
            {
                image.Resize(magickSize);
                image.Write(newFilePath);
            });

Pretend for a moment that we're not using Parallel.ForEach. The benefit of async/await with something like image processing is that you can keep the CPU busy even when one of the coroutines is blocked on I/O. But half of the I/O has already happened (maybe more if you're always scaling down rather than up). If you want to make an async version, the image load should be async.


Well, to me it looks pretty good. I've made a few minor tweaks, mainly renaming variables, removing unneeded temp variables and renaming the class and methods, to make the code a little more self documenting.

There was one thing that struct me as odd. Your class only works with charSets which contain unique chars. "ppen" will output "p" ten times.

I would definitely add a pruning feature to remove any duplicates, that would make it a more robust class. Something like this first snippet below.

const CharStitcher = (function(){

    class CharStitcher {

        constructor (string) {
            string = CharStitcher.pruneChars(string);
            this._str = string;
            this._1st = string[0];
            this._last = string[ string.length -1 ];
            return this;
        }

        next (char) {
            return this._str[ ( this._str.indexOf(char) + 1 ) % this._str.length ];
        }

        genString (str) {

            let lastChar = str.slice(-1);
            let otherChars = str.slice(0, str.length - 1);

            if (lastChar === this._last) {
                let charAt = 1;
                let upTo = otherChars.length;
                while ( otherChars[upTo] === this._last && --upTo ) ++charAt;
                if ( upTo === -1 ) return this._1st.repeat( charAt + 1 );
                return otherChars.slice( 0, upTo ) + this.next( otherChars[upTo] ) + this._1st.repeat( charAt );
            }

            return otherChars + this.next(lastChar);
        }

        *stitch (str, newStr) {
            newStr = this.genString(str);
            yield newStr, yield* this.stitch(newStr);
        }

    }

    CharStitcher.pruneChars = function (source, pruned){
      pruned = {}
      source.split('').forEach(function(char){
        if(!Object.prototype.hasOwnProperty.call(pruned, char)){
          pruned[char] = undefined;
        }
      })
      return Object.keys(pruned).join('');
    }

    return CharStitcher;

})();

Otherwise, I've removed all the comments, I feel it remains just as readable as your initial version.

class CharStitcher {

    constructor (string) {
        this._str = string;
        this._1st = string[0];
        this._last = string[ string.length -1 ];
        return this;
    }

    next (char) {
        return this._str[ ( this._str.indexOf(char) + 1 ) % this._str.length ];
    }

    genString (str) {

        let lastChar = str.slice(-1);
        let otherChars = str.slice(0, str.length - 1);

        if (lastChar === this._last) {
            let charAt = 1;
            let upTo = otherChars.length;
            while ( otherChars[upTo] === this._last && --upTo ) ++charAt;
            if ( upTo === -1 ) return this._1st.repeat( charAt + 1 );
            return otherChars.slice( 0, upTo ) + this.next( otherChars[upTo] ) + this._1st.repeat( charAt );
        }

        return otherChars + this.next(lastChar);
    }

    *stitch (str, newStr) {
        newStr = this.genString(str);
        yield newStr;
        yield* this.stitch(newStr);
    }

}

I've also rewritten your test a little bit, also just minor tweaks.

function test (charSet, startStr, times = 10) {
    let progress = new CharStitcher(charSet).stitch(startStr);
    while ( times-- ) console.log(progress.next().value);
}

test("pen", "p", 10);

class CharStitcher {

    constructor (string) {
        this._str = string;
        this._1st = string[0];
        this._last = string[ string.length -1 ];
        return this;
    }

    next (char) {
        return this._str[ ( this._str.indexOf(char) + 1 ) % this._str.length ];
    }

    genString (str) {

        let lastChar = str.slice(-1);
        let otherChars = str.slice(0, str.length - 1);

        if (lastChar === this._last) {

            let charAt = 1;
            let upTo = otherChars.length;

            while ( otherChars[upTo] === this._last && upTo-- && ++charAt);

            if ( upTo === -1 ) return this._1st.repeat( charAt + 1 );

            return otherChars.slice( 0, upTo ) + this.next( otherChars[upTo] ) + this._1st.repeat( charAt );

        }

        return otherChars + this.next(lastChar);

    }

    *stitch (str, newStr) {

        newStr = this.genString(str);

        yield newStr;

        yield* this.stitch(newStr);

    }

}

function test (charSet, startStr, times = 10) {
    let progress = new CharStitcher(charSet).stitch(startStr);
    while ( times-- ) console.log(progress.next().value);
}

test("pen", "p", 10);

Again, nothing major, hope my comments are helpful.


Code for calculating number of trailing zeroes after factorial

Code Review
All return paths from a function must return  value. Leaving a function that has a non void type without a return is undefined behavior (google nasal dragons).
int getZeroes(long long n){
    if(n>0){
       // STUFF
       return stuff;
    }
    // BUT HERE there is no return.
    // Any negative value or zero causes undefined behavior.
}

This while loop seems overly cumbersome with a break;
        while(a%5){
            if(a%5 == 0){  // will this ever be true.
                // STUFF   // Since it is just after a test that checks the opposite?
            }else{
                break;
            }
            a = a/5;
        }

This looks exactly the same both sides of the else:
        return (b+getZeroes(n-1));
    }else{
        return (getZeroes(n-1));

The only difference is b (which just needs to be made zero for the second case then) you can yank it out of the conditional.
Why store the results?
x.push_back(getZeroes(cases));

The only thing you do with them is print them. May as well just print them as you generate them!


Find the longest unique string in the input list

I'm on my phone so can only give pointers.

In the first loop you can use Map.get and switch on its value:

null: put True and add to wordsByLength
True: put False and remove from wordsByLength
False: do nothing

Map<Integer, Set<String>> wordsByLength tracks unique word sets, one per word length. It maps word length to a set of unique words. Whenever a new word appears in 1 above, add it to the set. When it is seen again for the first time in 2, remove it.

Next sort those entries by their keys (word length) in reverse and pull the first word from the first set.

Note that you may end up with ties of same-length words. The standard set will return an undefined "first" word. That may be okay.


Using an IDE, some changes are suggested automatically. For example:
Runnable and ActionListener can be replaced with Lambdas,

        if(circle.contains(e.getPoint()))
            hover = true;
        else
            hover = false;

can be simplified to

hover = circle.contains(e.getPoint());

Also, is it really intended that in Ellipse2D.Double(randomPositionY, randomPositionX, randomSize, randomSize) the first parameter is Y?

Usually if/else statements are used with braces.

In such small classes, the distinction between UI logic and business logic may not seem important, but as programs grow, it also gets more important. The Methods in your MouseListener seem to contain logic which could be extracted to a class or method. Although I am not a Swing expert, IIRC the repaint() method has to be called from the Event-dispatching thread, and could be therefore moved from generateRandom() into the Listener-methods where they are guaranteed to be called from the Event-dispatching thread.

The logic for generating a new circle could be refactored into an own class like this:

class CircleGenerator{
    public final static int MAX_SIZE = 100;
    public final static int MIN_SIZE = 10;
    private Random rand = new Random();

    public Ellipse2D.Double generateRandomCircle() {

        int randomSize = MIN_SIZE + (rand.nextInt(MAX_SIZE - MIN_SIZE) + 1);

        int randomPositionX = rand.nextInt(WIDTH - randomSize);
        int randomPositionY = rand.nextInt(HEIGHT - randomSize);
        return new Ellipse2D.Double(randomPositionX, randomPositionY, randomSize, randomSize);
    }
}


Possible antipattern: looping until a search condition is met

I know it's not the easiest to read - but is there any reason why I should not be doing it this way?

You answered your own question already. It's not easy to read, which is a very good reason not to do it this way.

In addition to the readability, your code will (probably, I didn't profile it) also perform worse than the simple solution (because of the extra function call).

So you have two points against this pattern. What are the advantages?

Two other points: if (exp === true) adds extra complexity. I would just write if (exp), and let the function return false. And you should assign i right were you need it, inside the loop.

If you consider all those points, your code might look like this:

var length = myArr.length,
    fe = null;

for (var i = 0; i < length; i++) {
    if (myArr[i].searchCondition) {
        fe = myArr[i];
        break;
    }
}

return fe;

If you don't like that the array is accessed twice, save the value in a temporary variable. Or just return directly like @dusky did:

var length = myArr.length;

for (var i = 0; i < length; i++) {
    if (myArr[i].searchCondition) {
        return myArr[i];
    }
}


To answer your questions:

It's hard to say.  If you expect a large number of values or moderate number of large values, you could potentially overflow an int.  Otherwise, you may be fine using int instead of long.
Yes, it's overkill, since dividing the total by the count would yield the correct answer anyways.
Unfortunately, no.  You need to lock anything which can be mutated by other threads, and you're doing precisely that.

I would do a few things:

Use a different naming format for fields than you do for local variables.  The most common format I have seen with .NET code is an underscore prefix, though the naming guidelines do not have any particular rule for private fields.  Once that is done, you can drop all the this references.
Constants should use different casing from fields.  SCREAMING CASE is the one I follow and see most often, but the framework isn't really consistent.  There appears to be a mix of PascalCase and SCREAMING_CASE, depending on which class you look at in ILDASM, even just within mscorlib.dll.
Avoid unnecessary casting.  .NET performs implicit casting in many cases, so there is no need to use most of the casts.  The only exception is casting the calculated average to int (from long).
Use proper exceptions.  The exception in the constructor should instead be ArgumentOutOfRangeException, as it more clearly states what the problem was.
Returning from within a lock works, so there is no need to define local variables for the total in the CurrentAverage property

public sealed class RollingAverage
{
    public RollingAverage()
        : this(DEFAULT_MAX_CAPACITY)
    {
    }

    public RollingAverage(int maxCapacity)
    {
        if (maxCapacity <= 0)
        {
            throw new ArgumentOutOfRangeException("maxRememberedNumbersmust be greater than 0.",
                                                    "maxRememberedNumbers");
        }

        _counts = new Queue<int>(maxCapacity);
        _maxSize = maxCapacity;
        _currentTotal = 0L;
        _padLock = new Object();
    }

    private const int DEFAULT_MAX_CAPACITY = 10;

    private readonly Queue<int> _counts;
    private readonly int _maxSize;

    private long _currentTotal;
    private object _padLock;

    public void Add(int value)
    {
        lock (_padLock)
        {
            if (_counts.Count == _maxSize)
            {
                _currentTotal -= _counts.Dequeue();
            }

            _counts.Enqueue(value);
            _currentTotal += value;
        }
    }

    public int CurrentAverage
    {
        get
        {
            lock (_padLock)
            {
                var lenCounts = _counts.Count;
                if (lenCounts == 0)
                {
                    throw new InvalidOperationException("No counts to average.");
                }

                return (int)(_currentTotal / lenCounts);
            }
        }
    }

    public void Clear()
    {
        lock (_padLock)
        {
            _currentTotal = 0L;
            _counts.Clear();
        }
    }
}

Other things to consider

Consider using a float or double type for the CurrentAverage property.  It is better to preserve the correct decimal answer in case you need a more exact average.  You can always truncate the answer back down to an int or float in the caller if you really want.
If the ratio of reads/writes heavily favors reads, consider using a ReaderWriterLockSlim.  This will allow multiple readers to retrieve the average without blocking one another.  Just remember to differentiate between obtaining the lock in reader mode versus writer or upgrade mode.


Getting multiple keys' values from nested object in JSON (w/out jQuery)

{ "dates & times":
    {
        "dates": [ "date01", "date02", "date03" ],
        "times": [ "150", "165", "180" ]
    }
}

No, don't do that. You take an explicit relationship in one data structure and make it implicit between two data structures. Instead, do:

{ "dates & times": [
    { "date": "2014-08-24", "time": "150" },
    { "date": "2014-08-24", "time": "165" },
    { "date": "2014-08-24", "time": "180" },
] }

Now the relationship is explicit, and you can iterate over the array more simply and safely than iterating over the keys. (Safely because, if a property is added to Object.prototype, it will show up as a key.)

for (var key in myObj){
    if (key == selUser){
        for (var date in myObj[key]["dates & times"]){
            console.log("Date: " + date + "; " + "weight: " + myObj[key]["dates & times"][date]);
            var dtTag = "
Date: " + date + "
";
            var ddTag = "
Time: " + myObj[key]["dates & times"][date] + "
";
            output.innerHTML += dtTag;
            output.innerHTML += ddTag;
        }
    } // if
} // loop

This has a bit more going on than is totally necessary. The outer loop is superfluous, since we only actually do something for one key. The inner loop changes with our new data structure. Also, we can do a bit of reorganization to help performance a bit. We will also change the if statement into a guard clause to clarify the code path.

// Is this key in the object, and does it have the right property?
if(!myObj[selUser] || !myObj[selUser]["dates & times"]) { // return, throw error, whatever }

output.innerHTML += myObj[selUser]["dates & times"].map(function(el){
    console.log("Date: " + el.date + "; Time: " + el.time);
    var dtTag = "
Date: " + el.date + "
";
    var ddTag = "
Time: " + el.time + "
";

    return dtTag + ddTag;
}).join("");

This relies on a newer ES5 feature, so polyfill or replace with equivalent loops if you need to support older browsers (see below). Also, this code does not exactly give the output you specified, FYI.

Without Array#map:

// Is this key in the object, and does it have the right property?
if(!myObj[selUser] || !myObj[selUser]["dates & times"]) { // return, throw error, whatever }

var i, el, dtTag, ddTag;

var listItems = [];
var datesAndTimes = myObj[selUser]["dates & times"];
var datesAndTimesLength = datesAndTimes.length;

for(i = 0; i < datesAndTimesLength; i++) {
    el = datesAndTimes[i];
    console.log("Date: " + el.date + "; Time: " + el.time);
    dtTag = "
Date: " + el.date + "
";
    ddTag = "
Time: " + el.time + "
";

    listItems.push(dtTag + ddTag);
}

output.innerHTML += listItems.join("");


Making sure all elements are processed in a JQuery call

There is absolutely no need for the synch part - JavaScript is synchronous, and you should not get into a situation where the processing of that function (the one you're showing) will not be completed before the next line runs.

(By the way, that function you have there can be rewritten for greater efficiency)

var indexArray = $('.views').map(function(){
    return this.value;
}).get();

Let's assume that you are doing something async in that each loop, for instance, ajax calls. Your best bet is to keep a count of how many of the calls are completed in the callback function, then execute the rest of your code when the last callback function is called:

var views = $('.views'),
    completed = 0,
    total = views.length;

views.each(function(){
    someAsyncFunction (function(){
        // Process data
        if(++completed === total) {
            // We're done! Let's move on..
        }
    });
});

This can be abstracted away into another function, though doing that is left as an exercise for the reader.


Disclaimer: my Lisp is extremely rusty.

same-parity must have at least one argument, so the proper declaration would be (same-parity arg . rest).
A more natural predicate for determining same parity of x,y is (even? (- x y))
A more natural helper is (same-parity-helper arg lst). Notice the absence of dot: it can recurse.
Putting it all together,

    (define (same-parity-helper arg lst)
        (if (null? lst) '()
            (cons
                (if (even? (- arg (car lst))
                    (car lst))
                    '())
                (same-parity-helper arg (cdr lst)))))

    (define (same-parity arg . rest)
        (same-parity-helper arg rest))


You need to enlarge tape because your initialization zeroes 101 bytes.

 section .bss
 tape resb 101

When in graphics mode, the teletype function uses the BL and BH registers as arguments.

 mov  bx,0007h ;Display page 0 and Color 7
 mov  ah, 0Eh
 mov  al, byte [tape +di]
 int  10h

When in text mode, the teletype function uses the BH register as an argument.

 mov  bh,0     ;Display page 0
 mov  ah, 0Eh
 mov  al, byte [tape +di]
 int  10h

You can optimize the setup code by iterating backwards. It shaves off 2 instructions! It too will leave DI=0.

 mov  di, 101
setup_loop:
 sub di,1
 mov  byte [tape + di], 0
 jnz  setup_loop

I don't know if you would care but the code for [ ] by itself produces an infinite loop if the byte at [tape + di] is anything but zero.


There are several remarks I could tell on your singleton implementation but since there's a far more better expert than me on these things, I'll reference his work. His name is Jon Skeet and he has an article on the singleton pattern which can be found here. Here are several points from the article that can help:

Characteristics:

A single constructor, which is private and parameterless. This prevents other classes from instantiating it (which would be a violation of the pattern). Note that it also prevents subclassing - if a singleton can be subclassed once, it can be subclassed twice, and if each of those subclasses can create an instance, the pattern is violated.
The class is sealed. This is unnecessary, strictly speaking, due to the above point, but may help the JIT to optimise things more.
A static variable which holds a reference to the single created instance, if any.
A public static means of getting the reference to the single created instance, creating one if necessary.

Basically your implementation of the pattern boils down to his first example:
public sealed class Singleton
{
    private static Singleton instance=null;

    private Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (instance==null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
}

And this example is bad code. I stringly suggest you read the article to understand all this and implement the correct way of the singleton pattern.

Other points:
Take your following code:
public Cart UserCart
{
    get
    {
        if (HttpContext.Current.Session["Cart"] != null)
        {
            return HttpContext.Current.Session["Cart"] as Cart;
        }
        return new Cart();
    }
    set
    {
        HttpContext.Current.Session["Cart"] = value;
    }
}

This is wrong, the setter should be used to set the value of a Cart instance, certainly not to save a value in the HttpSessionState object. Also since this has all to do with Cart and not with the SessionFactory, maybe this belongs in the Cart class.

Why mix fieldnaming with and without the underscore and capitalize some and do not so with other? Prefixing them with an underscore is personal choice but fieldnames have camelCase, according to the capitalization conventions of Microsoft.


Much of your code can be made shorter and more clear with LINQ:

string[] tempnames = { hand[0].Face, hand[1].Face, hand[2].Face, hand[3].Face, hand[4].Face };

vs

var faces = hand.Select(c => c.Face).ToArray();

But we actually don't need this at all, because your main algorithm can be made more clear with LINQ as well. What do you want?  To divide the cards up into groups based on their face value.  So do that!

var cardCounts = (from card in hand         // We're processing each card
                 group card by card.Face    // make a sequence of groups of cards with the same face
                 into g                     // process each group
                 let count = g.Count()      // get the size of each group
                 orderby descending count   // sort the groups by size, big to small
                 select count).Take(2).ToList();  // get the top two sizes

Before you read on: Why did I only take the highest two counts?

And now you can just read off the results:

switch(cardCounts[0])
{
  case 1: return "nothing";
  case 2: return cardCounts[1] == 1 ? "one pair" : "two pair";
  case 3: return cardCounts[1] == 1 ? "three of a kind" : "full house";
  case 4: return "four of a kind";
  default: Debug.Fail("How'd we get here?"); return "";
}

LINQ make the code read more like its meaning rather than a bunch of loops and counters that seem completely disconnected from the domain at hand. What are you doing logically?  Grouping the cards by face value and counting how many cards are in each group.  So make the code actually do that.

Remember, your goal here is to correctly implement the rules. The rules do not say "consider all ordered pairs of cards; assign one point for each identical card in that set of pairs. If the point total is 12 then..." and so on, but that's what you wrote.  Which is more likely to be correct, code that resembles the logic of the rules, or code that does some completely other thing that you hope is equivalent to the rules? Which do you suppose will be easier to maintain?

Exercise: Now add flushes, straights, and straight flushes. Can you use LINQ?

Exercise: Come up with a better representation for the value of a hand other than a string describing it

Exercise: Make a class for hands. What operations do you need to perform on hands?

Exercise: Cards don't change their kind, but you've modeled them as having setters. Make the card type an immutable struct, not a mutable class.

Exercise: Implement IComparable<Card> on cards.

Exercise: Given two hands, which, if either, is the winning hand?  Implement IComparable<Hand> on Hand. Note that you'll need more than just the kind of hand it is! Suppose there are two hands, both are two pair, and both are pair of kings, pair of queens. One of them still could win.  Read the rules of poker carefully; that's your specification. Again, try to make the code read like the rules.

Exercise: Given a sequence of cards, generate all possible five-card hands.  The signature of your method should be static IEnumerable<Hand> AllHands(IEnumerable<Card> cards).  If there are fewer than 5 cards in the sequence then clearly the resulting sequence should be empty.  If there are exactly 5 then you should get exactly one hand.  If there are 6 cards then you should get 5 hands. If there are 7 cards then how many hands should you get?

Exercise: given a sequence of 7 cards, find the highest 5-card hand in it.

Exercise: given n two-card hands and five community cards, describe how to divide the pot. Note that you have to represent ties somehow.  Again, remember, you are implementing the rules of poker, and those include ties.

Exercise: What if there are multiple pots, due to an all-in situation? Now how to divide the pots?

Exercise: Implement the rest of the rules of poker: ante, betting, raising, etc.

Exercise: Write an AI that plays poker, and a user interface that lets humans play against the AI.


Use std::vector<std::string> instead C-style array for possibleAnswers and then pass a reference to the vector into the checkInput function.
If you will use std::vector you can use just std::find to check if the input appears in the possibleAnswers.
Consider making possibleAnswers constant1. It is never change, is not it?
The sizeof operator returns a value of type std::size_t but you use int length to hold it. You should use std::size_t instead of int for the loop counters i inside the checkInput fucntion as well. Note that int is not guaranted to be large enough to hold a size of any object type (an array of std::string in your case).
It is a good habit to prefer pre-increment over post-increment all things being equal in C++ since the first usually is faster.
Do not comment your code too much. Anyone perfectly knows that * means dereference:

// dereference possibleAnswers pointer to the
//ith position of the array
if (input == *pointerPossibleAnswers)

Make it a rule: "Comments shouldn't say what happens in code, they should say why this is happens".
You can easily restructure your code to get rid of the isAsking flag variable. All you have to do is explicitly return input when it equals to one of the possible answer.

1 As mentioned @πάντα ῥεῖ in the comments if you'll decide to use to make possibleAnswers constant you may want to use std::array. But in this case you have to use templates to pass different sized arrays to the possibleAnswers function.


Some general notes:

Global variables are usually a bad idea; state that can be accessed from everywhere is hard to read and debug because you have no idea what random function might modify it.  It's extra difficult here because your globals are declared in different places.
The standard way of handling errors in Python is to raise an exception that can be caught and handled.
Long sequences of if/elif are usually an indication that your logic can either be simplified or split up.

Here's how I might suggest writing your start and register functions, using exceptions to handle errors, a lookup table to handle dispatching your different functions, and a single state object that collects all the random global variables:

from typing import NamedTuple

class LoginState(NamedTuple):
    admin: str
    adminpass: str
    user: str
    pass: str

def start() -> None:
    state = LoginState("Max", "Luo", "", "")
    print("Welcome, please choose what to do")
    menu = {
        'register': register
        'login': username
        'admin': username
    }
    choice = input('register/login ')
    try:
        menu[choice](state)
    except:
        problems()

def register(state: LoginState) -> None:
    state.user = input('Please register your username : ')
    state.pass = input('Please register your password : ')
    menu = {
        "Y": register
        "N": username
    }
    choice = input('Do you want to register another account? Y/N : ')
    menu[choice](state)

Defining your state as a type means that it's easier to refactor -- for example, suppose you realize that your register logic overwrites the username and what you actually want to do is be able to have more than one!  You could change user and pass into a collection (like a Dict, say), and use mypy to tell you all the places in your program that those attributes are used so you can make the appropriate updates.  If they're defined as globals, it's a lot more difficult to make sure you've updated all the places where they're used.

The menu dict is IMO a little easier to expand (and read) than the big chain of if/elif, by providing a single obvious place where the menu options are defined.

Having problems() be an exception handler means that not only does it catch the case where the user inputs an invalid command (this will cause menu[choice] to raise an IndexError), but it will also catch any unhandled exceptions raised by your other functions, so those functions don't need to call problems() themselves; all they have to do is raise an exception and the control flow will end up right here.  In the case of register() I didn't have to do anything with the error case, because if an exception is raised there I know that it will be caught in start().

Since the "present menu, make selection" pattern is probably going to be repeated a few times in this program, I might want to make that into a function as well:

def menu_prompt(
    menu: Dict[Text, Callable[[State], None]],
    prompt: str,
    state: LoginState
) -> None:
    choice = input(prompt)
    menu[choice](state)

and now this:

    menu = {
        'register': register
        'login': username
        'admin': username
    }
    choice = input('register/login ')
    try:
        menu[choice](state)
    except:
        problems()

becomes:

try:
    menu_prompt({
        'register': register
        'login': username
        'admin': username
    }, 'register/login ', state)
except:
    problems()


Implementing joinWithSeparator on a Character array

There are two problems with your method:

Problem #1: The method takes a separator: String parameter, but actually it is
expected that a single character string is passed, and it crashes
at Character(separator) if a multi-character string is passed:

let myChars: [Character] = ["a", "b", "c"]
let joined = myChars.joinWithSeparator("==")
print(joined)
// fatal error: Can't form a Character from a String containing more than one extended grapheme cluster

The solution is easy: change the parameter to separator: Character.
Btw, this makes the method faster.

Problem #2: The method is an extension of SequenceType, but it
actually works only for Arrays. For arbitrary sequences of characters,
the optional cast as? [Character] fails. This is silently ignored
and the separator not inserted:

let charSeq = Repeat(count: 4, repeatedValue: Character("x"))
let joined = charSeq.joinWithSeparator(",")
print(joined) // Output: xxxx

Two more remarks before I suggest possible solutions:

The name of the local variable var str = "" is quite non-descriptive.
I would call it result or joinedString (but that may be
opinion based).
Your loop

self.enumerate().forEach {
    /* do something with `$0` (index) and `$1` (char)
}

is correct, but I would write it as

for (index, char) in self.enumerate() {
    /* do something with `index` and `char`
}

So how can problem #2 be solved? You cast the sequence to an array in
order to get the index of the last element, so that you can insert the
separator after all elements but the last.

It becomes simpler if you think the other way around: Insert the
separator before all elements but the first. No need to determine
the endIndex anymore:

public func joinWithSeparator(separator: Character) -> String {

    var result = ""
    for (idx, char) in self.enumerate() {
        if idx > 0 {
            result.append(separator)
        }
        result.append(char)
    }
    return result
}

This has about the same speed as your method when applied to an
array, but works for arbitrary character sequence.

You asked:

  Would it be possible to replace the forEach loop with flatMap?

and the answer is "yes":

public func joinWithSeparator(separator: Character) -> String {

    let joinedChars = self.enumerate().flatMap {
        (idx, char) in
        idx == 0 ? [ char ] : [ separator, char ]
    }
    return String(joinedChars)
}

The shorted implementation (but not the fastest) would be to convert all characters
to strings, and use the existing method to join strings:

public func joinWithSeparator(separator: Character) -> String {

    return self.map { String($0) }.joinWithSeparator(String(separator))
}

Performance comparison

Here is my test code (compiled in Release
mode on a 3.5Ghz iMac):

let myChars = Array(Repeat(count: 1_000_000, repeatedValue: Character("x")))
let d1 = NSDate()
let j = myChars.joinWithSeparator(",")
let d2 = NSDate()
print(d2.timeIntervalSinceDate(d1))

Results:

Your original code: 0.163 sec.
Your code, with the separator parameter changed to Character: 0.104 sec.
My first suggestion: 0.095 sec.
Using flatMap: 0.276 sec.
Convert all characters to strings: 0.305 sec.


You could make count a field, then have a function to determineFirstResult().  Then the setPageNumber block can be separated out.

if (pageData.isLastPage()) {
    count = getCountFromDb();
    if (count > 0) {
        boolean isFinalPageFull = (count % maxResults) == 0;
        int pageNum = count / maxResults;
        pageData.setPageNumber((isFinalPage) ? pageNum - 1 : pageNum;
    }
}
firstResult = determineFirstResult();

...

int determineFirstResult(int maxResults) {
    if (pageData.isLastPage()) return getFirstResult(count, maxResults);
    return maxResults * pageNumber;
}

But now you've got a dependency; count has to be determined before calling determineFirstResult() as written.  So maybe make count a lazy-loaded field; if it's requested and null, then (and only then) do you getCountFromDb.


Abstract Factory + Strategy pattern for parsing log files in multiple formats — improvement suggestions?

Few thoughts about your code:

your case resembles more Abstract Factory pattern more than Strategy pattern. ILogFactory is your Abstract Factory while SmithsLogFactory, VividFactory etc are yours Concrete Factories. ISessionLog, ITipLog and IStatisticsLog are Abstract Products and, for example, TipLog with L3TipStrategy inside is your Product.
Because I see this case as Abstract Factory, I would add derived versions of ISessionLog, ITipLog and IStatisticsLog for each manufacturer. Constructor of each of those classes should take care of details - like creating proper version of Parser subclass.
When using Abstract Factory I always like to provide * construction parameters* to the methods, which can be used to control concrete products creation - and here is the place where I would handle issue with different versions of the logs from the same manufacturer.

Draft summarizing my thoughts:

    public class LogFactoryParameters
    {
       // ... for example, Version
    }

    public class L3LogFactory : ILogFactory
    {
        public ISessionLog CreateSessionLog(LogFactoryParameters parameters)
        {
            return new L3SessionLog(parameters);
        }

        public ITipLog CreateTipLog(LogFactoryParameters parameters)
        {
           return new L3TipLog(parameters);
        }

        public IStatisticsLog CreateStatisticsLog(LogFactoryParameters parameters)
        {
           return new L3StatisticsLog(parameters);
        }
    }


Finding the node with the smallest maximum distance to all the other nodes

It's not about constant optimizations. It's all about a more efficient algorithm. Here is a simple observation: the given graph is always a tree(because it has exactly n - 1 edges)(if it is not a tree, it is not connected and it is not clear what the answer is(maybe +infinity), so I will assume that it is a tree). That's why we can use the following algorithm:

Pick an arbitrary vertex v.
Find the furthest vertex from v(let's call it u).
Find the furthest vertex from u(let's call it t).
The distance between u and t is the answer.

This solution requires only two breadth-first searches so it has a linear time complexity. Why is it correct? I will not post a formal proof here, but drawing several trees on paper should help you to understand it. It is important that a given graph is a tree(this algorithm does not work for arbitrary graphs).

This algorithm actually finds a diameter of a tree, but it is easy to solve the original problem when a diameter is found. We can just pick the center of the diameter. To do it, we can find the path from u to t(it requires a small modification in bfs: we also need to keep track of a parent for each vertex) and store in a list. After that we just need to get the middle element of the list. If the number of elements in the list is even, we can pick any of two middle elements.


Advent of Code 2017, Day 1: Sum of digits matching the next digit (circular list)

I think std::rotate can lead to a somewhat simpler approach:

get the input
create a copy
rotate the copy by one element
Accumulate the sum of elements that match between the two

Code might look something on this general order:

int sum_matching(std::vector<int> const &digits) {
    std::vector<int> copy{digits};

    std::rotate(copy.begin(), copy.begin()+1, copy.end());

    int sum = 0;
    for (int i=0; i<digits.size(); i++)
        if (digits[i] == copy[i])
            sum += digits[i];
    return sum;
}

I'm pretty sure you could hijack std::inner_product to do that final loop, but given its name, that would be misleading, so probably better avoided. On the other hand, if your compiler includes all the latest C++17 goodness, you could use std::transform_reduce though:

int main() {
    std::vector<int> inputs{1, 2, 3, 3, 1};

    std::vector<int> copy{inputs};
    std::rotate(copy.begin(), copy.begin()+1, copy.end());

    int result = std::transform_reduce(inputs.begin(), inputs.end(),
                    copy.begin(),
                    0,
                    [](int a, int b) { return a + b; },
                    [](int a, int b) { return a==b ? a : 0; });

    std::cout << result << "\n";
}

If you'd like to play with that using a (strictly prototype) implementation of transform_reduce, it's not terribly complex--something on this order:

template<class InputIterator1,
         class InputIterator2,
         class T,
         class BinaryOperation1,
         class BinaryOperation2>
T transform_reduce(InputIterator1 first1, InputIterator1 last1,
                    InputIterator2 first2,
                    T init,
                    BinaryOperation1 binary_op1,
                    BinaryOperation2 binary_op2)
{
    for ( ; first1 != last1; ++first1, ++first2) {
        init = binary_op1(init, binary_op2(*first1, *first2));
    }
    return init;
}

Note, however, that this is a purely serial implementation--part of the intent of transform_reduce is that it will support parallel implementation, which this doesn't (but that's mostly a restriction that binary_op1 and binary_op2 must be commutative and associative, not a requirement on the implementation). Note that the standard includes a number of overloads of std::transform_reduce--I've included an implementation of the one used in the preceding code.


I'll add some remarks (adding to what Miguel Avila already said) and then focus on the performance aspect.

Use consistent naming: you mix camel case (FactorsSum) and snake case (sum_of_factors).
Use consistent spacing (after keywords like if and around operators).
Declare variables and the narrowest possible scope. As an example, sum_of_factors is only needed inside the for-loop.
Use proper exit codes. A non-zero exit code indicates the failure of a program. You'll want to return 0; or return EXIT_SUCCESS;. In fact you can simply omit the return statement: Reaching the end of main() does an implicit return 0; in C++.

If you care about portability: C++ does not specify the size of int, only its minimum range (which is -32767 to 32767). You should use long (with a minimum range -2147483647 to 2147483647) or one of the fixed-size types (int32_t or int64_t) depending on the needed range.
Performance improvement #1
Computing the sum of all (proper) divisors of a number can be significantly improved by observing that if \$ i \$ divides \$ n \$ then both \$ i \$ and \$ n/i \$ are divisors of \$ n\$. Therefore it suffices to test all \$ i \le \sqrt n\$. See for example Sum of all proper divisors of a natural number. A possible implementation is
// Returns the sum of all proper divisors of `n`.
int divisor_sum(int n) {
    if (n <= 1) {
        return 0;
    }

    int count = 1; // 1 is always a divisor.
    int sqrt_n = (int)sqrt(n); // Upper bound for the loop.
    for (int i = 2; i <= sqrt_n; i++) {
        if (n % i == 0) {
            // `i` and `n / i` are divisors of `n`.
            count += i;
            if (i !=  n / i) {
                count += n / i;
            }
        }
    }
    return count;
}

Performance improvement #2
In your main loop, you compute the divisor sum of sum_of_factors even if that is larger than num:
if (GetSumOfFactors(sum_of_factors) == num && num > sum_of_factors)

A simple improvement would be to change the order of the expressions:
if (num > sum_of_factors && GetSumOfFactors(sum_of_factors) == num)

Another option is to remember the divisor sums of numbers which are possible candidates of  an amicable pair, so that they need not be computed again. This can for example be done with a
std::unordered_map<int, int> abundant_divsums;

which holds all abundant numbers with their divisor sums encountered so far. A number is abundant if its proper divisor sum is larger than the number. These are candidates for an amicable pair with higher numbers.
A possible implementation is
#include <unordered_map>

int main()
{
    std::unordered_map<int, int> abundant_divsums;

    int num = 1;
    for (int counter = 0; counter < 10; num++) {
        int divsum = divisor_sum(num);
        if (divsum > num) {
            abundant_divsums[num] = divsum;
        } else if (divsum < num) {
            if (abundant_divsums.find(divsum) != abundant_divsums.end() && abundant_divsums[divsum] == num) {
                std::cout << "Pair: " << num << ' ' << divsum << '\n';
                counter++;
            }
        }
    }
}

Benchmarks
The tests were done on a MacBook Air (1.1 GHz Quad-Core Intel Core i5), with the code compiled with optimizations (“Release” configuration).
I measured the time for computing the first 10/20/50 amicable pairs. All times are in seconds.

# of amicable pairs
10
20
50

Original code:
3.8
24

After improvement #1:
0.08
0.2
3.8

After improvement #2:
0.05
0.15
2.5


Overall, this is a pretty straightforward program. See the bottom of my answer for an Extreme Makeover: Code Edition of the program.

You have a hard-coded "magic number" in your for loop.  It would be better to use a variable.

for (int i = 1; i < 101; i++) // not the best

int num = 101;
for (int i = 1; i < num; i++); // better

Your if test conditions can be shortened a bit.

if (Integer.toString(i).indexOf("3") != -1)

Your logic is a bit off.  You should actually have fewer else if conditions (this is rarely the case, but here it is applicable).  For example, when i reaches "15", is should print "FizzBuzzFuzz", but your program only prints "FizzFuzz".

Final code:

public class Test
{
    public static void main(String... args)
    {
        int num = 101;
        for (int i = 1; i < num; i++)
        {
            boolean printed = false;

            if (i % 3 == 0)
            {
                printed = true;
                System.out.print("Fizz");
            }
            if (i % 5 == 0)
            {
                printed = true;
                System.out.print("Buzz");
            }

            if (Integer.toString(i).indexOf("3") != -1)
            {
                printed = true;
                System.out.print("Bizz");
            }
            if (Integer.toString(i).indexOf("5") != -1)
            {
                printed = true;
                System.out.print("Fuzz");
            }

            if (printed == false) System.out.print(i);
            System.out.println();
        }
    }
}

Extreme Makeover: Code Edition

Let's use a StringBuilder and some ternary operators.  And let's get rid of that boolean.

public class Test
{
    public static void main(String... args)
    {
        int num = 101;
        for (int i = 1; i < num; i++)
        {
            StringBuilder sb = new StringBuilder();
            if(i % 3 == 0) sb.append("Fizz");
            if(i % 5 == 0) sb.append("Buzz");

            if(Integer.toString(i).indexOf("3") != -1) sb.append("Bizz");
            if(Integer.toString(i).indexOf("5") != -1) sb.append("Fuzz");

            if (sb.length() == 0) System.out.print(i);
            else System.out.print(sb);
            System.out.println();
        }
    }
}


It seems to me that you understand the concept correctly, but your implementation is horrible. That's because you don't need the whole _possibleAnswers list at all, you should just keep two numbers: the lower bound and the upper bound, you can compute everything you need from that.

There are also some smaller issues:

Don't use Max() if you know that the maximum number will be always the last one. You can instead use Last(), that will be much faster. And a something similar applies to the way you compute count in the else branch: you already know that FindIndex() will return the index of the last item in the list, you don't need to walk the list twice for that.
C# is not Java, you should use == to compare strings instead of Equals(), it's much more readable.
You won't need _isCorrectNumber, if you use break instead of continue. That would make your code shorter and less confusing. (I thought something like “wait, why does he continue when he wants to end iterating?” when I read that part of the code.)

Binary search should take only O(log n) time, but your code is O(n2 log n), which is really bad. The n2 part is caused by using Max() inside of the FindIndex() lambda, if you fixed that by simply computing the Max() once before calling FindIndex() (which is still horrible, see #1 above), it would make your code O(n log n), although that is still bad.


Rearranging array elements depending on their indexes

The trick you are missing here is a simple swap.

All you need to do is keep a "fast" and a "slow" index in the array. The "fast" index scans forwards looking for 0 values. The "slow" index is an insert-point for where the next 0 would belong.

Consider this loop:

public int[] zeroFront(int[] nums){

    int slow = 0; // next zero inserted here
    for (int fast = 0; fast < nums.length; fast++) {
        if (nums[fast] == 0) {
            nums[fast] = nums[slow];
            nums[slow] = 0;
            slow++;
        }
    }
    return nums;
}

That loop finds all zero values and then swaps non-zero values with them from the beginning of the loop, ending with a situation where the zeros are all at the front.

Sometimes, tricks like these are really hard to spot, but, when pointed out, make you think: Neat!


Find if items in a list of list matches to another list

Extract this into functions

You are doing one well defined thing (finding fuzzy matches), so this should be at least one function, but I suggest more because you are returning two results.

Write automatic tests

Re-factoring is very hard without tests, re-running and checking the input manually is very time consuming, an automatic test runs in milliseconds.

Use the list comprehensions and zip

You are basically checking the single-dimensional list (xs) against each row of the two-dimensional list (matrix) and seeing which elements are contained and which are not. This can be expressed very easily in code.

def fuzzy_matches(xs, matrix):
    """
    >>> list(fuzzy_matches(["a","b","c"], [["a", "b43", "x"], ["w", "b", "5cfg"]]))
    [[True, True, False], [False, True, True]]
    """
    return ([i in j for i, j in zip(xs, line)] for line in matrix)


Build an index and use it to map the second array:

const index = new Map(source.map(el => [el.id, el]));
const result = picks.map(el => (index.get(el.id) || el));

The larger the arrays, the more effective the index becomes.
If this code is a bottleneck, it can be rewritten to build the index on-the-go (memoization).

P.S. source stands for preprocessed_array and picks for new_array in the original code.