For improved readability, this writing style is generally recommended:

if (elements.constructor !== Array) {
    elements = [elements];
}

In conditions with range checks, it's a good practice to organize the elements of the condition by increasing numerical order. So instead of this:

bounds.top+margin < window.innerHeight && bounds.bottom-margin > 0

This is better:

0 < bounds.bottom - margin && bounds.top + margin < window.innerHeight


I would try a sequence of case statements:

class ApiError < StandardError
  def initialize(response)
    message = case
      when response.is_a?(String)
          response
      when !(response.respond_to? 'body')
        'Error'
      when response.body.is_a?(Hash)
        response.body['message']
      else
        response.body.to_s
      end
    super(message)
  end
end

###test code
class XX
  attr_accessor :body
end

p ApiError.new('string')
p ApiError.new(:x)

xx = XX.new()
p ApiError.new(xx)
xx.body={'message' => 'my message'}
p ApiError.new(xx)

I hope I understood your code correct.
Actually there is no check, if a given Hash has a 'message'-key.

You can also omit the message variable:

class ApiError < StandardError
  def initialize(response)
    super case
      when response.is_a?(String)
          response
      when !(response.respond_to? 'body')
        'Error'
      when response.body.is_a?(Hash)
        response.body['message']
      else
        response.body.to_s
      end
  end
end


Playing different audio files based on video keyframe

You want to play a certain audio at a certain time? Well, you're in luck. I recently did this in a demo. It wasn't playing audio with video though. It was triggering animations at certain points of the audio, but it should be the same idea.

<audio> and <video> elements are HTMLMediaElements and have media events.

If you want to play your mapped audio in real time, there is the timeupdate event which is triggered when the current time of the element has changed.
If you want to play it during pause, then there is the paused event.

You can use these events to check the currentTime of your element, which in this case is your video. currentTime is in seconds. If you want to stick to your hh:mm:ss format, you'd need your own converter.

Instead of urls, you should have preloaded audio elements there so that they will play instantly when we need them.

Anyways, here's a sample structure with seconds and audio elements

var samples = [
  [5,HTMLAudioElement],
  [10,HTMLAudioElement],
  [15,HTMLAudioElement],
  ...
];

Then, hook to the timeupdate event of the video, check the current time, and compare with the indicated item in the array. You can use a counter to indicate your current position.

var i = 0
//get first audio as current audio and play
var currentAudio = samples[i][1].play();

video.addEventListener('timeupdate',function(){

  //if video time is greater than current audio end time
  if(this.currentTime > samples[i][0]){
    if(currentAudio) currentAudio.pause(); //pause existing audio (maybe do a "seek to zero" to reset)
    currentAudio = samples[++i][1];        //reference next audio as current
    currentAudio.play();                   //play the current audio
  }
});


Check if a string is a permutation of a palindrome using Python

Some suggestions:

You strip out spaces, then on the next line check if each character is a space.  The second part is redundant.
The only possible values for freq % 2 are 0 and 1, so num_odd = sum(1 for char, freq in Counter(data).items() if char != ' ' and freq % 2 == 1) can be simplified as num_odd = sum(freq % 2 for Counter(data).values())
If num_odd is 0, then there must be an even number of elements. If num_odd is 1, then there must be an odd number of elements.  So really all you care about is if there is more than 1 odd count.
You can return the results of expressions directly.  So something like return x < y is simpler than using an if test and manually returning True or False depending on the outcome.
I would put the replace first since that reduces the number of characters that lower has to operate over (although this is probably a silly negligible micro optimization).

So the code can be simplified to:

from collections import Counter

def is_palindrome_permutation(data: str) -> bool:
    """Given a string, check if it is a permutation of a palindrome."""
    data = data.replace(' ', '').lower()
    return sum(freq%2 for freq in Counter(data).values()) < 2

One more thing you could do is put the Counter on the first line.  I think this hurts readability a bit, but does mean that your modified data can be garbage collected right away.  There is no point doing this with .values(), though, since this is just a view into the Counter object, so the Counter object has to be kept in memory.

from collections import Counter

def is_palindrome_permutation(data: str) -> bool:
    """Given a string, check if it is a permutation of a palindrome."""
    data = Counter(data.replace(' ', '').lower())
    return sum(freq%2 for freq in data.values()) < 2


Improving performance hacker rank Median

There are a lot of stylistic changes I'd normally suggest, but I'm going to forgo that to mention three very simple optimizations:

remove new Char[] { ' ', '\t', '\n' } from within the loop. No need to recreate this object every time as it's an invariant.
you know the maximum size of the a list, so create it with that capacity in mind to prevent resizing as it's being accessed: List<double> a= new List<double>(N);
Repeated code in both the if and else branches pulled out (no performance optimization, but basic tenet of DRY (Don't Repeat Yourself)): int index= a.BinarySearch(x[i]);

Resulting code looks like this:

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
class Solution {

   static void Main(String[] args) {
      int N;
      StringBuilder st= new StringBuilder();

      N = Convert.ToInt32(Console.ReadLine());
      int[] x = new int[N];
       List<double> a= new List<double>(N);
      string[] s = new string[N];

      Char[] splitChars = new Char[] { ' ', '\t', '\n' };

      for(int i=0; i<N ;i++){

         string tmp = Console.ReadLine();
         string[] split = tmp.Split(splitChars);

         s[i] = split[0].Trim();
         x[i] = Convert.ToInt32(split[1].Trim());
          bool r=true;

          int index= a.BinarySearch(x[i]);
          if(s[i]=="r"){
              if(index>=0){
                  a.RemoveAt(a.LastIndexOf(x[i]));
              }
              else{
              r=false;
              }

          }else{
                if (index < 0) index = ~index;
                  a.Insert(index,x[i]);
          }
          if(!r || a.Count==0){
              st.AppendLine("Wrong!");

          }
          else{
          st.AppendLine(calcularModa(a).ToString());
          }
      }
       Console.WriteLine(st.ToString());

   }
   static double calcularModa(List<double> a){

   int i= a.Count/2;
       if(a.Count % 2 !=0){
           return a[i];
       }else{
           return ((a[i - 1] + a[i]))/2;
       }

    }
}


Using inheritance and polymorphism in Java

In your code, two classes differently extend a base class ClassificationRule.
Objects of these classes are added to a list, cast as the base class.
They are retrieved from the list and a method, apply(), which is present in the base class but overridden in the child classes.
As you intend, the apply() method as present in the child class will run, not the apply() method from the base class.

In the case of your code, the child class does not actually gain functionality from the base class. You are inheriting solely in order manipulate objects of different types as if they were of one homogenous type, because you know they provide certain functionality.

In software engineering terms, you would say 'the classes implement an interface'.
An interface looks very much like an empty base class, like the one you wrote, and it is a Java language feature different from a base class. Implementing an interface (i.e. providing some agreed functionality) is different from inheriting functionality.

And the code for it is different, you would write public interface ClassificationRule {, and public class RuleFirstOccrnc implements ClassificationRule {.

In Java, you can only inherit from one class (thought that class may itself have a parent). But you can implement as many interfaces as you like. A typical java object will implement interfaces that let it be sorted (comparable), serialized to transmissable data (serializable), etc, but can only ever inherit from a single base class.
C++ lets you inherit multiple base classes. Things go horribly wrong when you do. Or at least when I do.


Critique My Codeigniter Custom CMS Pages Model

I don't know Codeigniter so i can't comment on "is this a propper model". For my answer i'm just going to assume it is.

It's not much code so i'm going to focus on some details:

  public function __construct()
  {
      parent::__construct();
  }

Those 5 lines do absolutely nothing. I'd remove them. If you need a constructor later, add it later.

  public function fetch_navigation()
  {
    $result = $this->db->order_by("nav_order", "asc")->where('published', 1)->get('navigation')->result_array();
    return $result;
  }

This is a pretty hard to read (113 Chars in that line). I'd go for something like this (to say with your formatting from above)

  public function fetch_navigation()
  {
      return $this->db
          ->order_by("nav_order", "asc")
          ->where('published', 1)
          ->get('navigation')
          ->result_array();
  }

$db = $this->db;

Seems unnecessary to create a local variable, those 6 extra chars shoudn't hurt. I needed to look twice to see where that variable is from and if its local because changes are made to it.

So far those are really minor notes.

Unreachable code ?

if ($query) {
  return $query;
} else {
  return false;
}

you are setting $query['modules'] = ... so even if that is null $query will at least contain

array("modules" => null);

and that will always be true.


Converting string array to string (and vice-versa) for storing via XML

My first reaction is: don't do this.

By creating your own encoding for an array of strings, your XML is not going to be (easily) consumable by other programs. By Base64 encoding your strings, your XML is not going to be human-readable.

These are two major benefits of XML, and if you're willing to sacrifice them, maybe XML is not the right format. If the serialized data is only going to be consumed by the same program, binary serialization would be a better option.

That said, if you want to serialize a list of strings to XML, this is what I would recommend:

public class Email
{
    private static readonly XmlSerializer Serializer = new XmlSerializer(typeof(Email));

    [XmlArrayItem("Attachment")]
    public List<string> Attachments { get; set; }

    public XDocument ToXDocument()
    {
        var document = new XDocument();
        using (var writer = document.CreateWriter())
        {
            Serializer.Serialize(writer, this);
        }

        return document;
    }
}

And some sample client code:

var email = new Email
{
    Attachments = new List<string> { "<hello></hello>", "asdf" }
};
var xml = email.ToXDocument().ToString();
Console.WriteLine(xml);

This will output

<Email xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Attachments>
    <Attachment>&lt;hello&gt;&lt;/hello&gt;</Attachment>
    <Attachment>asdf</Attachment>
  </Attachments>
</Email>

Now, this chokes if the strings contain a null-byte, which you mentioned was a possibility. It's hard to say what to do about this without knowing more about your problem domain. Hopefully, stripping null-bytes is an option for you.

Serializing a byte[] as a Base64-encoded string can be done using a surrogate property:

[XmlIgnore]
public byte[] Bytes { get; set; }

public string BytesBase64
{
    get { return Convert.ToBase64String(this.Bytes); }
    set { this.Bytes = Convert.FromBase64String(value); }
}


Don't make it possible for your container to contain nothing. It can be wrapped in a std::optional for that. Drop the _init_ type and parameterless constructor.
Use val consistently. The parentheses around this->val are unnecessary anyway, but since you're already using val in some places, just use it everywhere.
Don't allow construction or assignment with values of bad types. That fails silently right now, which is not a good way to fail. Luckily, you can do even better and keep the static typing with overloading:

TripleType(A x) { val._e = _tA; val.__a = x; }
TripleType(B x) { val._e = _tB; val.__b = x; }
TripleType(C x) { val._e = _tC; val.__c = x; }

TripleType& operator=(A x) { val._e = _tA; val.__a = x; return *this; }
TripleType& operator=(B x) { val._e = _tB; val.__b = x; return *this; }
TripleType& operator=(C x) { val._e = _tC; val.__c = x; return *this; }

Mark methods that don't modify their object – get() and current_type() – as const.
Don't allow fetching values of the wrong type. I'm not a C++ expert by any means, so there might be a better way of restricting T to A, B, or C while keeping the same .get<T> calling convention (I sure hope so), but:

private:
    A get_(A const*) const {
        if (val._e != _tA) {
            throw bad_multitype_access(typeid(A), current_type());
        }

        return val.__a;
    }

    B get_(B const*) const {
        if (val._e != _tB) {
            throw bad_multitype_access(typeid(B), current_type());
        }

        return val.__b;
    }

    C get_(C const*) const {
        if (val._e != _tC) {
            throw bad_multitype_access(typeid(C), current_type());
        }

        return val.__c;
    }

public:
    template <class T> T get() const {
        return get_(static_cast<T const*>(nullptr));
    }

where bad_multitype_access would be something along the lines of:

class bad_multitype_access : std::logic_error {
public:
    bad_multitype_access(std::type_info const& expected, std::type_info const& actual) :
        std::logic_error(std::string("Attempted to get ") + expected.name() + " from multitype containing " + actual.name()) {}
};

That's all verbose and a bit hacky, but prevents getting types outside of the expected set statically and values of the wrong type dynamically. Again, I would love to hear a better way of accomplishing the same thing from someone who actually knows the language. You can also drop the vp_t typedef at this point, which was never really a good idea, as well as is_same_type.
Use a switch for current_type().

std::type_info const& current_type() const {
    switch (val._e) {
    case _tA: return typeid(A);
    case _tB: return typeid(B);
    case _tC: return typeid(C);
    }
}

Stop it with the underscores already! =)

private:
    enum contained_type {
        tA,
        tB,
        tC,
    };

    struct {
        A a;
        B b;
        C c;
        contained_type type;
    } val;

It feels like creating a TripleType shouldn't create an instance of each of its possible types, and that writing a new value of a different type should destroy a previously existing one. unique_ptrs could work here.

private:
    ⋮
    struct {
        std::unique_ptr<A> a;
        std::unique_ptr<B> b;
        std::unique_ptr<C> c;
        contained_type type;
    } val;
    ⋮
        return *val.a;
    ⋮
        return *val.b;
    ⋮
        return *val.c;

public:
    TripleType(A x) { val.type = tA; val.a = std::make_unique<A>(x); }
    TripleType(B x) { val.type = tB; val.b = std::make_unique<B>(x); }
    TripleType(C x) { val.type = tC; val.c = std::make_unique<C>(x); }

    TripleType& operator=(A x) {
        val.type = tA;
        val.a = std::make_unique<A>(x);
        val.b.reset(nullptr);
        val.c.reset(nullptr);
        return *this;
    }

    TripleType& operator=(B x) {
        val.type = tB;
        val.a.reset(nullptr);
        val.b = std::make_unique<B>(x);
        val.c.reset(nullptr);
        return *this;
    }

    TripleType& operator=(C x) {
        val.type = tC;
        val.a.reset(nullptr);
        val.b.reset(nullptr);
        val.c = std::make_unique<C>(x);
        return *this;
    }

Avoid the double-copy-construct by accepting T const& instead of T in the constructors and operator=s.
Since TripleType is managing everything about val, move val's members into it; it's just doing namespacing right now and not representing an actual object.
Give TripleType some copy and move constructors.

TripleType(TripleType<A, B, C> const& o) {
    type = o.type;

    switch (type) {
    case tA: a = std::make_unique<A>(*o.a); break;
    case tB: b = std::make_unique<B>(*o.b); break;
    case tC: c = std::make_unique<C>(*o.c); break;
    }
}

TripleType(TripleType<A, B, C>&& o) = default;

All told, it looks like this now:

#ifndef MULTITYPE_HPP
#define MULTITYPE_HPP

#include <memory>
#include <stdexcept>

class bad_multitype_access : std::logic_error {
public:
    bad_multitype_access(std::type_info const& expected, std::type_info const& actual) :
        std::logic_error(std::string("Attempted to get ") + expected.name() + " from multitype containing " + actual.name()) {}
};

template <class A, class B, class C>
class TripleType {
private:
    enum contained_type {
        tA,
        tB,
        tC,
    };

    std::unique_ptr<A> a;
    std::unique_ptr<B> b;
    std::unique_ptr<C> c;
    contained_type type;

    A get_(A const*) const {
        if (type != tA) {
            throw bad_multitype_access(typeid(A), current_type());
        }

        return *a;
    }

    B get_(B const*) const {
        if (type != tB) {
            throw bad_multitype_access(typeid(B), current_type());
        }

        return *b;
    }

    C get_(C const*) const {
        if (type != tC) {
            throw bad_multitype_access(typeid(C), current_type());
        }

        return *c;
    }

public:
    TripleType(TripleType<A, B, C> const& o) {
        type = o.type;

        switch (type) {
        case tA: a = std::make_unique<A>(*o.a); break;
        case tB: b = std::make_unique<B>(*o.b); break;
        case tC: c = std::make_unique<C>(*o.c); break;
        }
    }

    TripleType(TripleType<A, B, C>&& o) = default;

    TripleType(A const& x) { type = tA; a = std::make_unique<A>(x); }
    TripleType(B const& x) { type = tB; b = std::make_unique<B>(x); }
    TripleType(C const& x) { type = tC; c = std::make_unique<C>(x); }

    TripleType& operator=(A const& x) {
        type = tA;
        a = std::make_unique<A>(x);
        b.reset(nullptr);
        c.reset(nullptr);
        return *this;
    }

    TripleType& operator=(B const& x) {
        type = tB;
        a.reset(nullptr);
        b = std::make_unique<B>(x);
        c.reset(nullptr);
        return *this;
    }

    TripleType& operator=(C const& x) {
        type = tC;
        a.reset(nullptr);
        b.reset(nullptr);
        c = std::make_unique<C>(x);
        return *this;
    }

    template <class T> T get() const {
        return get_(static_cast<T const*>(nullptr));
    }

    std::type_info const& current_type() const noexcept {
        switch (type) {
        case tA: return typeid(A);
        case tB: return typeid(B);
        case tC: return typeid(C);
        }
    }
};
#endif

And now there's more type safety. (I hope this isn't actually egregiously bad advice!)

Also, here are some moving constructors and operator=s you can add.

TripleType(A&& x) { type = tA; a = std::make_unique<A>(std::move(x)); }
TripleType(B&& x) { type = tB; b = std::make_unique<B>(std::move(x)); }
TripleType(C&& x) { type = tC; c = std::make_unique<C>(std::move(x)); }

TripleType& operator=(A&& x) {
    type = tA;
    a = std::make_unique<A>(std::move(x));
    b.reset(nullptr);
    c.reset(nullptr);
    return *this;
}

TripleType& operator=(B&& x) {
    type = tB;
    a.reset(nullptr);
    b = std::make_unique<B>(std::move(x));
    c.reset(nullptr);
    return *this;
}

TripleType& operator=(C&& x) {
    type = tC;
    a.reset(nullptr);
    b.reset(nullptr);
    c = std::make_unique<C>(std::move(x));
    return *this;
}


Google Custom Search placeholder function in JavaScript

So after testing it,  you don't really need to define it in your javascript. You can simply add it in your HTML before all your other scripts.

That's what s.parentNode.insertBefore(gcse, s); does. It finds the first occurence of a script tag in your HTML (which is kind of funny as it won't work if there are no script tags in your HTML), and adds your new script before it.

So if the first occurence of a script tag appears in the HEAD, then it'll be placed in the head'

<script src="https://cse.google.com/cse.js?cx=017643444788069204610:4gvhea_mvga" async type="text/javascript"></script>
<gcse:search></gcse:search>

Making your javascript more efficient will be difficult as 1. there isn't much happening and 2. it's already very short.

But you could do something like this (which doesn't change much)...

// google search placeholder
(function(cx) {
    const gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = true;
    gcse.src = `https://cse.google.com/cse.js?cx=${cx}`;
    const s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(gcse, s);
})('!!!!!!!!!!!!!!!!!!!');


Performance tuning on a text file to object conversion

If you use regular expressions for parsing, then I would recommend using them for everything.  Here's a solution that proceeds line by line, using capturing parentheses to see what the line contained.

function parse(data) {
    var re = /(#start)|(#end)|#p\s+(\S+)\s+(\S+)/ig;
    var results = [], match, obj;
    while (match = re.exec(data)) {
        if (match[1]) {           // #start
            obj = {};

        } else if (match[2]) {    // #end
            results.push(obj);
            obj = null;           // ← Prevent accidental reuse if input is malformed

        } else {                  // #p something something
            obj[match[3]] = match[4];
        }
    }
    return results;
}


Generate mask for non zero (or inverse) nibbles in integer

Intrinsics from bmi and similar are okay, but I haven't found anything that seems useful.

They're not very useful for this. pdep and pext let you do this in a different way, but it's not better (especially not on AMD Zen1), you shouldn't use this (but maybe it's interesting to think about):
uint64_t m = 0x1111111111111111;
uint64_t stacked = _pext_u64(b, m) | _pext_u64(b, m << 1) |
                   _pext_u64(b, m << 2) | _pext_u64(b, m << 3);
return _pdep_u64(stacked, m) * 15;

There is a slightly different way to write the original logic in a way that may be easier to read, of course that's subjective but it will be as a straight-line composition of common bitwise idioms, it shouldn't make any difference for a compiler. It's the same thing really, but instead of being a single expression it's linearized into discrete steps, which also creates the opportunity for in-line comments to explain the steps:
uint64_t getNonZeroMask( uint64_t b )
{
    // horizontal OR of nibbles in log(bits) steps
    b |= b >> 2;
    b |= b >> 1;
    // remove polluted bits, leaving the results in the lsb of every nibble
    b &= 0x1111111111111111;
    // spread single bit flags into full nibbles
    return b * 15;
}


Function to generate an Int from a series of bits

Improving the code

Your code computes
$$
 a_0 2^{n-1} + a_1 2^{n-2} + \ldots a_{n-2} 2 + a_{n-1} \, ,
$$
that is the polynomial
$$
 P(x) = a_0 x^{n-1} + a_1 x^{n-2} + \ldots a_{n-2} x + a_{n-1} \,
$$
evaluated at \$ x=2 \$. A well-known, efficient method to evaluate polynomials is Horner's method:
$$
 P(x) = (\ldots ((a_0 x + a_1) x + a_2) x + \ldots ) x + a_0 \, .
$$

Applied to your task that gives

func genInt(fromBitArray array: [Int]) -> Int {
    var n = 0
    for i in 0...array.count - 1 {
        n = 2 * n + array[i]
    }
    return n
}

Instead of the bit shift (by a variable amount) we have now multiplications by the fixed factor \$ 2 \$. But this can be simplified further. Inside the loop we need now only the array element at the current index, but not the index itself. Therefore we can enumerate the array instead:

func genInt(fromBitArray array: [Int]) -> Int {
    var n = 0
    for digit in array {
        n = 2 * n + digit
    }
    return n
}

And for this kind of combining array (or more general: sequence) elements there is a dedicated method in the Swift standard library, reduce():

func genInt(fromBitArray array: [Int]) -> Int {
    return array.reduce(0) { (accum, digit) in
        return 2 * accum + digit
    }
}

Naming

The “official” Swift naming conventions are describe in the API Design Guidelines, e.g.

Name variables, parameters, and associated types according to their roles, rather than their type constraints.
Begin names of factory methods with “make”, e.g. x.makeIterator().
Avoid abbreviations.

With these rules in mind I would suggest something like

func makeInteger(fromBits array: [Int]) -> Int

Or if one sees this as a way to construct an integer then a custom initializer would be appropriate

extension Int {
    init(bits array: [Int]) {
        self = array.reduce(0) { (accum, digit) in
            return 2 * accum + digit
        }
    }
}

// Example:
let value = Int(bits: [1, 1, 0])

Miscellaneous

It is expected that the array contains only the values zero and one. With an assertion this can be verified during the test phase, without performance impact on the released code:

extension Int {
    init(bits array: [Int]) {
        self = array.reduce(0) { (accum, digit) in
            assert(digit == 0 || digit == 1, "invalid binary digit")
            return 2 * accum + digit
        }
    }
}

If you want to create other integer types from a bit array in the same manner then you can defined the initializer on the BinaryInteger protocol instead:

extension BinaryInteger {
    init(bits array: [Int]) {
        self = array.reduce(0) { (accum, digit) in
            assert(digit == 0 || digit == 1, "invalid binary digit")
            return 2 * accum + Self(digit)
        }
    }
}

// Example:
let value = Int16(bits: [1, 1, 0])


Convert three functions into a single function

I think your code would be cleanest if you wrote the program as a composition of a minimum-absolute-value-of-array function and a filter.

Assuming that performance in the face of large data sets is not a concern, you could have, for example:

function isNumber(val) {
    return typeof val == "number";
}

getClosestToZero(myNumbersToSort.filter(isNumber));

Alternatively, getClosestToZero() could directly support an optional second argument that servers as a filtering callback if it is provided.

Please pay attention to the consistency of the indentation.


Normally it would disgust me, but you appear to have a valid reason to use it, which stems from the pre-existing disgusting situation that you have to cope with these data objects that use ints.

The only thing I would ask is, why can these data objects not use enums? What is it about their auto-generation that precludes enums from being used?  I do not think that enums receive any special handling at the IL level, they are handled just like primitive types are.


I think you are too concerned with the implementation right now.

The last part of the question

  ... recommended ... for scalability and unit-testability?

is the most important one.

Let's imaging you were to write the test for this feature. You would start off by designing the API that the user of the functionality would ultimately consume. Secondly as far as the tests go ... they could careless how it is implemented 'under the hood' it only cares that it meets the requirements performance just being on possible requirement. Many times asymptotic complexity doesn't even play a critical role unless n is large. Take for example Strassen matrix multiplication it is only practical for larger matrices.

For scalability I'm assuming you mean maintainability and extensibility. The best way to achieve that is to use the dependency inversion principle (DIP) so that you are not depending on either a list or a dict but instead on the correct abstraction.

One possible abstraction is that the rules represent a validation.

interface IValidator<T>
{
   bool IsValid(T item);
}

Your test would look as follows.

[Test]
void NoRulesEverythingIsFalse()
{
    var rules = new Rules();
    Assert.False(rules.IsValid(""));
}

[Test]
void SingleRule()
{
    var rules = new Rules(new[]
    {
        new LinkedRule("abc", "Only abc is allowed.")
    });
    Assert.True(rules.IsValid("abc"));
    Assert.AreEqual(
        rules.GetLinkForRule("abc"),
        "Only abc is allowed.");
    Assert.False(rules.IsValid("123"));
}

Now with this you can implement it however you want as long as your test pass. Feel free to add a performance test if it is required.

// LinkedRule.cs
struct LinkedRule {
    string Rule { get; set; }
    string Link { get; set; }
}

// Rules.cs
class Rules : IValidator<string>
{
    private Dictionary<string, LinkedRule> RulesToLinks { get; }

    public RuleValidator(IEnumerable<LinkedRule> linkedRules)
    {
        RulesToLinks = linkedRules.ToDictionary(
            x => x.Rule);
    }

    public bool IsValid(string rule) =>
        RulesToLinks.Keys.Contains(rule);

    public string GetLinkForRule(string rule) => RulesToLinks[rule];

    // ...
}


Helper Method for Generating Stubbed ICommand in Rhino Mocks

It looks fine to me, although I would personally prefer to have method chaining rather than optional parameters just for semantic purposes. Are your arguments meant to be weakly typed (using object)? If I could, I would change that to something strongly typed, but that is out of scope for this question.


You have the scroll always on because you set the overflow-x:scroll; in the first div. Change it to hidden and it should never show itself again.

<div style="width:100%;height:75px;overflow:hidden;">

You have to remember that if you will hide it in some cases the content may not be visible (too small browser window width or to many elements if you plan to add more). I don't know what you want to do with it but you should consider some kind of dynamic scrolling or width adjustment.


Proper way to cancel WebClient in BackgroundWorker

Is this approach poor form?

I think yes

  Is passing in a reset event better than having a loop within the function that tests the DoWorkEventArgs::Cancel property every tenth of a second?

Both are wrong. Event is a kernel object! Using a kernel object for this type task is wasteful. It would be better if you used something like this:

webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCallback2);
client.DownloadStringAsync (uri);

In this case, you don't need to block any thread with a loop. When your request completes, you will take the control in passed method (DownloadStringCallback2).

  Also, is there a way to delay the call to RunWorkerAsync until the background worker isn't busy, without blocking the thread?

At first glance - yes, you can pass in worker method CancellationToken. When the user inputs a new value, you simply cancel the token and start a new task. When the cancelled request takes the control in DownloadStringCallback2 it should check the token and return. If it wasn't cancelled, it may continue work. On each user request you should simply cancel the old token and create a new one, then start a new request.

  Or should I just create a new background worker every time?

I think it's OK at first glance. On each user request create a new BackgroundWorker and pass the cancellation token. The BackgroundWorker will use ThreadPool behind the scenes anyway.


The assignment

Write a program to find out how often a streak of six heads or a streak of six tails comes up in a randomly generated list of heads and tails.

Now this requirement you didn't match, so your program doesn't contain the required functionality, even if it does match the required result.
Note that there is a bit of a problem with the assignment, as you might see a streak of 7 as two streaks of 6, or a streak of 12 as two streaks of 6. I presume, given the assignment, that you may use any streak of 6 or more. This is not what your program currently does, by the way; I presume from the code that a streak of 12 will be seen as two streaks of 6.
[EDIT] Rereading the question, it seems that you do match the assignment, if you assume that the "often" part depends on how often the streak of 6 comes up in the randomly generated distributions, instead of in one distribution. That seems to be the case if I take the rest of the context in, but the assignment isn't stated very clearly.

our program breaks up the experiment into two parts: the first part generates a list of randomly selected 'heads' and 'tails' values, and the second part checks if there is a streak in it.

You fail to meet this requirement: you haven't specified two methods, which is generally the way you would split things up in programming.

Put all of this code in a loop that repeats the experiment 10,000 times so we can find out what percentage of the coin flips contains a streak of six heads or tails in a row.

So if you'd create the method that counts the streaks, and the streak count is higher than 0 then you would increase the counter. You do that perfectly :)
As indicated, you haven't separated it from the main functionality. Worse, you update global variables from a function.
If this course is about structured programming then you might fail even though your application is likely to generate the right answer.
Code review
totalRuns = 0
streakScore = 0

This is fine, but in that case you need to update them from global code. If not the variables should be local to a function.
def coinFips():

This method name is misspelled. Does the method really only perform coin flips? If so, shouldn't there be a parameter that indicates how many? And return an array of results?
global streakScore,totalRuns

Every time you type global, you should wonder if it really helps design / readability, and refrain from using globals if it does not. I would add a space before totalRuns, but that's kind of personal.
results = ''

Why not use a (character) array instead? That way you can assign it the right size from the start and then fill it by indexing the coin flip...
for i in range(100):

100 is a literal, a so called "magic value". Here you should use a parameter (or, in other cases, a constant).
# Use regular expressions to check results sting

Another spelling mistake. Spelling mistakes are not terrible, but if you make too many they act as red flags to a reviewer. They are more likely to take a deeper look.
match = re.findall(r'(HHHHHH|TTTTTT)', results)

It will probably not be terribly performant, but it is a nice way to test and easy to program. But note the problem indicated in the first section of the review.
Instead you probably want to use something like ([H]{6,}|[T]{6,}). Also, you'll find that regular expressions are hard to parameterize (what if you want to use 7 or any other number instead of 6?). Some kind of state machine would impress me (even) more.
print("The Chance of a streak is: {}%".format(round(streakScore/totalRuns * 100)))

Here too much is happening for me. The calculation should be on it's own line. If your function ends with ))) then your application is getting too much LISP like if you ask me. You can also see that it is getting too cramped because you suddenly don't use spacing around the operator / anymore.

The other lines seem fine to me. There isn't too much happening on them except for the last line - which is good. And the variable naming seems fine too. Spacing and readability are fine. The application code is concise too.
Conclusion: you are well on your way, but the part where you "divide-and-conquer" is lacking. This is not much of a problem in the above code of course, but it may become a problem for larger, more complex systems.


The comments have got it right - you're vulnerable to an SQL injection. If I navigate to your page with the id parameter set to something like this:

http://yoursite.com/database-operation?id=0;DROP%20TABLE%20%`Students`;--

then your SQL query will end up looking like this:

SELECT * FROM document_0;
DROP TABLE `Students`;

If you have a table called Students, that's about to get totally deleted.

Instead, you should be looking at using prepared statements. Both the mysqli and PDO extensions for PHP have this functionality; a quick Google search will turn up plenty of tutorials on it.

You can also help prevent this via user privileges: if all you're ever doing is SELECTs, then the MySQL user that takes these queries doesn't need the privilege to DROP tables. Use the principle of least privilege: give users (and any other entity) only the privileges they need to perform their task, nothing more.


primes.rs:11:13: 11:25 warning: value assigned to `is_prime` is never read, #[warn(unused_assignments)] on by default
primes.rs:11         let mut is_prime = 0;
                         ^~~~~~~~~~~~

You don't have to initialize a variable when you declare it. That is, you can write

let mut is_prime;

You just have to initialize it before reading from it; if the compiler cannot guarantee that the variable will be initialized at that point, it will raise an error.

primes.rs:14:17: 14:25 warning: value assigned to `is_prime` is never read, #[warn(unused_assignments)] on by default
primes.rs:14                 is_prime = 1;
                             ^~~~~~~~

That warning comes from this block:

if n < 4 {
    is_prime = 1;
}

This block is useless, because you are unconditionally setting is_prime to 1 after a couple of other if blocks, and you don't read back the variable between these assignments.

is_prime should be a boolean instead of an integer. Rust has a built-in boolean type, bool, and the keywords true and false, which you can use instead of 1 and 0.

Instead of having a mutable is_prime variable, I'd factor out the code that decides if a number is prime in a separate function. We can use early returns to avoid defining a mutable variable.

use std::io;

fn is_prime(n: u64) -> bool {
    if n < 4 {
        // Skip all the following checks, we know it's a prime!
        return true;
    }

    // We don't need to check if n is 2 or 3 anymore,
    // since if n is one of these values, we won't reach here.
    if n % 2 == 0 {
        return false;
    }

    if n % 3 == 0 {
        return false;
    }

    let mut m = 5;
    while m <= (n as f64).sqrt() as u64 {
        if n % m == 0 {
            return false;
        }

        if n % (m + 2) == 0 {
            return false;
        }

        m += 6;
    }

    // Implicit return
    true
}

fn main() {
    println!("Enter a number: ");
    let mut limit = String::new();
    io::stdin().read_line(&mut limit).expect("failed to read line");
    let limit: u64 = limit.trim().parse().expect("Please enter a number.");
    if limit <= 0 {
        println!("Number must be greater than or equal to 0.");
    } else {
        for n in 2..limit + 1 {
            if is_prime(n) {
                println!("{}", n);
            }
        }
    }
}


Good for you for resisting the temptations of Automapper.

My answer to your question is to design around it.

I often write my viewmodels generically so I don't have to copy properties.  This does not work in every case but works in more cases than you might think.  Your viewmodel might become something like this:

public class BaseViewModel<T>
{
    public T Model {get; set;}

    public BaseViewModel( T model)
    {
        this.Model = model;
    }
}

public class DogViewModel : BaseViewModel<Dog>
{
    public DogViewModel(Dog dog) : base(dog)
    {

    }

    public void DoSomething()
    {
        // do something with Dog object...
        Model.Weight = 10;
    }

}

I wrote a little about it on my site:
http://www.samwheat.com/Post/The-function-of-ViewModels-in-MVC-web-development


Filtering and processing computers listed in a CSV file

As far as performance goes there are a few places to make changes.

Make better use of the pipeline

You read in the csv to a variable then process. Convert the script to process these records directly. There would be performance increases this way. Insanely brief example...

Import-Csv 'U:\Local Group Members.csv' |
   Where-Object {($_.Name0 -eq "administrators")}
   Select-Object "Netbios_name0", "Name0" |
   ForEach-Object {
       # Something happens.
} | Export-Csv ....

Wasted console output

I cannot imagine you are checking ~1000's of lines of console output. You are wasting processing time but putting that data to console. Remove the write-host lines. Even if you have this running as a task.

Where-Object is slow

This is really easy to use but is not very performance friendly. I can tell you have at least PowerShell 3.0 but if you have at least v4 then you have access to the where and foreach methods of collections. The syntax as you will see is very similar but there should be performance boons here as well. Example:

(Import-Csv -Path C:\temp\devices.csv).where({$_.DeviceType -ne "BlackBerry"})

I think you are already doing this but order your conditions in order of least likely to most likely. PowerShell will not evaluate the RHS of -and if the LHS is already false.

I tried to improve the logic in your regex but it was at a cost of performance everytime. As redundant as that string is it seems to be a faster choice given other options.


Pythonic indenting `with` statement blocks

Yes, ideally, you close the with block as soon as possible, that way the file gets closed quickly - which means you are not (potentially) blocking access to it, having less file handles in use, etc...

Python does have scoping, it just doesn't make new scopes very often - only for functions and classes (and some other smaller cases, like list comprehensions and cousins in 3.x and above).

Unlike in Java, Python doesn't take the approach that every block is a scope, therefore loops, as you say in your question, don't introduce a new one.


Calculating primes until a user-given value

So this is a curious writeup, because primes can be calculated in many, many ways.

That said, there's one huge optimization we can use to cut your search pattern in half, and it starts here:

for (ulong i = 4; i<inputnumber; i++)
{

Fun fact: the only prime even number is 2, so we can actually rewrite this very quickly to remove half of the numbers you need to search:

for (ulong i = 5; i<inputnumber; i += 2)
{

Bam. Cut our search grid in half.

The next thing I would do is remove 2 from the List<ulong> of results, and we'll insert it later, because that will never match any of the values we're searching now:

var primes = new List<ulong>();
primes.Add(3);
...
primes.Insert(0, 2);

That way we get another speed boost, without sacrificing any of the rest of our code. (Are there better ways to do this? Sure.)

Next, we need to talk about some "best practices" and such:

Console.WriteLine("The Range from 0 to " + inputvar + " has " + Convert.ToString(numberofprimes) + " primes.");

This is something we call "string concatenation", basically, string1 + string2. It's frowned upon, and we recommend not doing it. Instead, use a formatted string, in one of two ways:

Console.WriteLine("The Range from 0 to {0} has {1} primes.", inputvar, numberofprimes);
Console.WriteLine($"The Range from 0 to {inputvar} has {numberofprimes} primes.");

Either will work, though the second is only supported in C# 6.0.

Next, there's one more huge optimization to make, and it's at this line:

double result = 0;

You don't realize it, but there's a boatload of casting/conversions here that shouldn't exist. Replace double with ulong and it goes away.

What's happening, is i % prime is a ulong, that is being casted to a double when assigned to result. This is an expensive operation, because the two types are stored in memory in completely different formats. Change the type, and you should get a 50%+ speed boost. (At least, I did.)

Additionally, you don't really need result, you don't use it for anything. So, I recommend removing it, and rewriting the foreach as follows:

for (ulong i = 5; i < inputnumber; i += 2)
{
    isprime = true;
    foreach (ulong prime in primes)
    {
        if (i % prime == 0UL)
        {
            isprime = false;
            break;
        }
    }
    if (isprime == true)
    {
        primes.Add(i);
    }
}

This gives you another speed boost, surprisingly.

Lastly, I recommend initializing the List with a default buffer. This should help avoid "resizing" that happens throughout the lifetime of the program. I used 500000, but as long as you use something reasonable (even 10000 is fine) it will give you a decent performance boost. (1-2%)

Overall, when we're done, the algorithm should look something like:

var primes = new List<ulong>(10000);
primes.Add(3);
bool isprime = false;
for (ulong i = 5; i < inputnumber; i += 2)
{
    isprime = true;
    foreach (ulong prime in primes)
    {
        if (i % prime == 0UL)
        {
            isprime = false;
            break;
        }
    }
    if (isprime == true)
    {
        primes.Add(i);
    }
}
primes.Insert(0, 2);
int numberofprimes = primes.Count;


Simple color flooding game in Javascript/HTML5 canvas area

This would be so much easier with the use of a table or divs. You could then create an array of objects (one object per square). Ex:

[
    {
        "className": "orange",
        "x": 0,
        "y": 0
    }
];

By doing this, you can match the class of the surrounding objects, rather than changing the color directly. Hope this helps.


I want to create a js MVVM framework

Oh no... not again. No, seriously. If this is for learning purposes or personal stuff, that's fine. If you plan to use this in real projects and production, you might consider picking up an existing framework or help improve an existing one.

  my problem is input update always late, not like angular every type will update model.

That's because during a keydown event, the value of the input hasn't been changed yet. Frameworks usually use a combination of different events (which differ across elements as well as browsers) to consistently get values whenever the UI state changes. For instance, radio buttons in older IE don't fire some event on selection (I think it was change) and frameworks work around it by detecting click instead.

  angular every type will update model

The approach of each framework is different. Angular uses "dirty checking", which is a periodic check of data changes, and re-rendering once necessary. Frameworks like Ember and Backbone rely on setters which, aside from setting values, recompute dependent entities like computed props, and the DOM.

var elems = document.getElementsByTagName('*');
for (var ii = 0; ii < elems.length; ii++) {
  if (elems[ii].getAttribute('mk')) {

This is a bad idea. It's fast in small cases, terrible when your page is huge. Consider narrowing down the initial set of elements instead of getting every single one of them and filtering.

<input type="text" mk="value=test" value="test" />

Your markup is also... too much. All we needed is to know where this input binds to. You'd only need to assign the binding. Additionally, when using frameworks, you seldom actually touch the values. Values come straight from the view-model. In this case, "test" shouldn't be necessary. The following should be fine:

<input type="text" data-mk="test" />

You should also consider when your data starts to contain objects and arrays. You'd then have to deal with data contexts, key path resolution, parsing the expressions, scoping. Your example works fine when your DOM only has one model to bind to. In real life, you could have a dozen of data sources and elements nesting each other.

elems[ii].onkeydown = function (e) {
    e = e || window.event;
    var charCode = e.charCode || e.keyCode,
        character = String.fromCharCode(charCode),
        value = this.value;

    var cmk = this.getAttribute('mk').split(';');
    for (var cc = 0; cc < cmk.length; cc++) {
        var dd = cmk[cc].split('=');
        Mark.set(dd[1], value);
    }
}

Like I said earlier, listening to events require combinations of events and may differ across elements and browsers. You could move this logic out of your main framework logic (maybe in a separate function, or an entirely separate module) that you could simply pull in and call.


Some quick remarks:

Naming is important. I don't consider dt, conString, con, etc. proper names since they don't tell me enough. There's no need to abbreviate. selectcmd doesn't follow Microsoft's rules about compound words, and dttemp even contains the dreaded "temp".
You haven't encapsulated the MySqlCommand which creates the table in a using.
MySqlCommandBuilder inherits from a class that implements IDisposable, so perhaps that too should be used in a using statement?


SQL Server 'Execute As'/Revert pattern in a 'Try/Catch' Block

One thing to be wary of is if you grant execute permissions on a schema in sql server, then no matter what's in the Stored Procedure, the user is granted rights to execute that stored procedure and whatever it entails.

So I think that, even if you change user contexts, that SP will work no matter what.


I feel you on the "My reasons are more due to preference than need." comment but the inheritance from PickOrder and public new ERPListBase<TPickOrderLine> Lines { get; protected set; }  will confuse somebody best case and really mess things up worst case. While it may still give you that feeling of impending doom here are some suggestions to make this safer while keeping the look and feel you prefer.

Consider implementing the property like so (also for Header)

public new ERPListBase<TPickOrderLine> Lines {
    get {
        // note that you can't control base.Lines so some values may not be of TPickOrderLine
        return new ERPListBase<TPickOrderLine>(base.Lines.OfType<TPickOrderLine>());
    }
    protected set { base.Lines = new new ERPListBase<IPickOrderLine>(value.Cast<IPickOrderLine>()); }
}

Consider not reusing the base class and using explicit interface implementation:

public class PickOrder<TPickOrderHeader, TPickOrderLine> :
    IPickOrder<TPickOrderHeader, TPickOrderLine>
    where TPickOrderHeader : class, IPickOrderHeader, new()
    where TPickOrderLine : class, IPickOrderLine, new()
{
    public TPickOrderHeader Header { get; protected set; }

    IPickOrderHeader IPickOrder.Header { get { return Header; } }

    public ERPListBase<TPickOrderLine> Lines { get; protected set; }

    ERPListBase<IPickOrderLine> IPickOrder.Lines { get { return new ERPListBase<IPickOrderLine>(Lines.Cast<IPickOrderLine>()); } }
}

Whatever you do, avoid storing the same data twice as you may be doing (depending on use) in your current code.


High-level issues:

  making a copy in zero or more files

It appears the code only handles zero or one file.

  The output is unbuffered.

The code is very much buffering the input. Check out read_to_string:

  Read all bytes until EOF in this source, placing them into buf.

That means that the program has to wait for the entire input string to exist before it writes a single byte. That input could be gigabytes!
The code assumes that all input is a UTF-8 encoded string. This cat cannot be used with images or zipfiles any any kind of binary data.

More tactical issues:

Don't use single items from a prelude. The point of a prelude is to be a glob import of all the things you might want.
Check out all the methods that exist on Option or Result. For example, unwrap_or_else encapsulates the default value case.
Hardcoding /dev/null ties the implementation to a specific OS (maybe OK because you are making cat) but also to a filesystem layout. This cat can't be used when /dev/ isn't available, which would likely be during a nasty system emergency. Would be better for the program to not write anything instead of writing to /dev/null.
Printing out the errors description shows less information than printing out the error:

  other os error

vs.

  Is a directory (os error 21)

expect may be more compact than a match or unwrap_or_else, depending on the desired error format.
I don't believe the loop will ever loop, since the entire input is read into the string as discussed above.
If the loop did loop, reallocating the entire string for each iteration is inefficient. Better to just clear it and reuse the memory.
There's no need to pass a reference when using println!; that macro automatically references all the arguments.
Don't ignore errors! let _ is a really big red flag. cat has few responsibilities, but writing output correctly is fairly critical! The program should exit when writing fails, such as when a pipe is closed.
The exit code isn't well defined in all cases. What is it when panicking?
Standard in and out would be repeatedly locked in each iteration. Not as efficient as a single lock.

use std::env;
use std::io::{self, Read, Write};
use std::fs::File;

fn main() {
    let fname = env::args().nth(1).unwrap_or_else(|| String::from("/dev/null"));

    let mut outfile = File::create(&fname).expect("Unable to create file");
    let mut line = String::new();

    loop {
        line.clear();

        io::stdin().read_to_string(&mut line).unwrap_or_else(|_| {
            std::process::exit(0)
        });

        if line.is_empty() {
            std::process::exit(0);
        }

        println!("{}", line);

        outfile.write(line.as_bytes()).expect("Unable to write!");
    }
}

Sorry for going a bit off the deep end, but the problem was interesting. I'd probably write it a little like this:

use std::env;
use std::io::{self, Read, Write};
use std::fs::File;

const BUFFER_SIZE: usize = 8 * 1024;

fn main() {
    let mut buf = vec![0; BUFFER_SIZE];

    let stdin = io::stdin();
    let mut stdin = stdin.lock();

    let stdout = io::stdout();
    let stdout = stdout.lock();

    let mut outputs: Vec<_> = env::args().skip(1).map(|fname| {
        let f = File::create(&fname).unwrap_or_else(|e| {
            panic!("Unable to create file {}: {}", fname, e);
        });

        Box::new(f) as Box<Write>
    }).collect();

    outputs.push(Box::new(stdout));

    loop {
        let bytes = stdin.read(&mut buf).expect("Unable to read input");

        if bytes == 0 { break }

        // **Very important**, otherwise you can end up with
        // Heartbleed-esque bugs! I'm chosing to shadow `buf` to
        // deliberately prevent using it again in this loop.
        let buf = &buf[..bytes];

        for output in &mut outputs {
            output.write_all(buf).expect("Unable to write output");
        }
    }
}


Secure CURL to & handle response from Payment Gateway

Well, security from what type of threat? You need to figure out what you want to protect against before you can protect against it! Since I'm unsure of what you're protecting against, I'll point out relevant setopt flags.

CURLOPT_VERBOSE - This is fine for a developer, but make sure the client doesn't see this returned information. It could lead to a possible exploit. More on the output later on.
CURLOPT_POST - You're using this incorrectly. The value should be true or an alternate HTTP POST.
CURLOPT_RETURNTRANSFER - Using 1 does result in TRUE, but it's easier to read if the explicit boolean is used.

Here are some flags you may way to consider in order to help secure this connection even more. Each can be found in the docs.

bool CURLOPT_FAILONERROR - Just in case the page you fetch is "out of order".
bool CURLOPT_FORBID_REUSE - Force the connection to close on finish, and prevent the reuse of a connection. Also see bool CURLOPT_FRESH_CONNECT.
Make sure you keep bool CURLOPT_SSL_VERIFYPEER set to TRUE.
int CURLOPT_TIMEOUT - Timeout if the connection takes too long.


I'm unsure of your SCSS, because it doesn't seem to use media-queries, and isn't small-screen-first: but here are my HTML suggestions:

The columns would likely stack on small screens, and aren't really columns semantically in general. You can note that they are smaller pieces inside a container by calling them blocks or something, and then use floats in combination with @media queries. Giving them static classes like bootstrap does, describes style in HTML – when it should stay in the styles. You can use an inner .inner-w or something to emulate a 'main column' like most web pages.

        some block

        some other block

If you have an actual grid, it is a list, and should be described that way. Then you can style the list without adding classes to every li.

            grid item 1

            grid item 2

            grid item 3

            grid item 4

            grid item 5

            grid item 6


Testing whether characters of a string are unique

@Wayne Conrad has made some good points.  I just have a few additional ones:

I'm not sure about checking against a maximum value, but I'll address it anyway.

In case you'd like to change the default 256, consider having a template parameter.  That way, the value can be changed at just one location.  It'll also give more meaning to that value.

template <std::size_t maxChars = 256>
bool unique_chars(std::string &s) {
    if (s.length() > maxChars) return false;
    std::bitset<maxChars> bs;

    // ...
}

To slightly add on to Wayne's point about const, make sure the argument is const& so that no unnecessary copying is done.  In addition, declaring the string argument as const will allow it to be passed in while avoiding casting.
Consider renaming the function to something like areUniqueChars().  Otherwise, it may sound like it's returning the number of unique chars.
In C++, prefer to put unary operators (such as & and *) next to the type:

std::string& s;

for (auto& c : s) {}


Set discounted ticket price, with a floor of 0

Use the built-in max() function:

discounted_price = max(0, original_ticket_price - discount_value)


Do write and writef automatically buffer writes? If not I bet that's your problem.

One suggestion I do have that you could try is using a final switch statement. It would require an enum containing all the possible values of a ubyte, but in return your switch would essentially be a jump table and a bit faster.
If you're worried about this making your switch look huge you could just mixin the boring portion, generating a string within a loop and adding that string to compilation.

You could also try using a char[128] to store all conversions from ubyte to char, skipping the to! call which might be a bit slower. Making the conversion an array lookup instead of a method call.

This code doesn't use the buffered writes I mentioned, I'll leave that to someone else since I'm unsure about it.

import std.stdio;
import std.conv;

//This enum is so you can use final switch, use a proper ascii order
enum MyEnum {
    J0, J1, J2, ... //Using J because you can't start identifiers with a number, so I just picked something
    Ja, Jb, Jc, ...
    JA, ...
    ...
}

//a lookup table to make conversion possible in this direction.
static MyEnum[128] reverseMyEnum = {
    J0, J1, J2, ... //in proper ascii order, I know this is wrong
}

//replaces your use of to!
static char[128] ascii = {
    //just put the ascii chars here
}

void main()
{
  foreach (ubyte[] mybuff; chunks(stdin, 4096)) {
    encodebuff (mybuff);
  }
}

@pure string generateBoring() {
    string code;
    for (char value; a .. z, A .. Z, 0 .. 9)
        code ~= "case MyEnum.J'"~value~"': writeChar(b); break;\n";
    for (char value; any other uncaught cases)
        code ~= "case MyEnum.J'"~value~"': writeOctal(b); break;\n";
    return code;
}

@safe void encodebuff (ubyte[] mybuff) {
  foreach (ubyte i; mybuff) {
    char b = ascii[i]; //integer promotion lets you use a ubyte where int is expected
    final switch (reverseJB[i]) {
        mixin(generateBoring());
        case 0: writeChar ('\n'); break;
        case MyEnum.JBackBack: writeString(`\\`); break;
        case MyEnum.JBackT: writeString(`\t`); break;
        case MyEnum.JBackN: writeString(`\n`); break;
        case MyEnum.JBackR: writeString(`\r`); break;
        case MyEnum.JBackF: writeString(`\f`); break;
        case MyEnum.JBackV: writeString(`\v`); break;
        case MyEnum.JBackA: writeString(`\a`); break;
        case MyEnum.JBackB: writeString(`\b`); break;
    }
  }
}

@trusted void writeString (string a)
{
  write (a);
}

@trusted void writeOctal (int a)
{
  writef ("\\%.4o", a); // leading 0 needed for for zsh printf '%b'
}

@trusted void writeChar (char a)
{
  write (a);
}


Codility Frog Jump - Count minimal number of jumps from position X to Y

You don't need a loop for this, there is a mathematical solution:

If y - x is divisible by d, then it takes (y - x) / d jumps
If y - x is not divisible by d, then it takes (y - x) / d + 1 jumps

In other words:

if ((y - x) % d == 0) {
    return (y - x) / d;
}
return (y - x) / d + 1;

Or the somewhat less readable but more compact:

return (y - x) / d + ((y - x) % d == 0 ? 0 : 1);


Join and pivot multiple tables of securities data in MySQL

DB Design

Your tables are not correctly normalized:

codes.description depends on codes.code → requires a table with codes.code as primary key

You are also missing constraints:

ISIN.id primary key
ISIN.name unique key
additionalCredit.id, additionalCredit.code primary key
codes.codeId, codes.code primary key

Query Optimization

mysql does not come with a pivot, so we need to use an aggregate function - in this case min(..) - instead. This way we can avoid the union of redundant quasi code duplication.

Fiddle

query..

select isin
    , min(if(codeId = 8, description, null)) Type8
    , min(if(codeId = 9, description, null)) Type9
from (
    select codeId, code, description, ifnull(name1, name2) isin from (
        select codes.codeId, codes.code, codes.description, ISIN1.isin name1, ISIN2.isin name2
        from codes
        left join ISIN ISIN1 on ISIN1.code = codes.code
        left join additionalCredit on additionalCredit.code = codes.code
        left join ISIN ISIN2 on ISIN2.id = additionalCredit.id
    ) q1
) p1
group by isin
order by isin
;

yielding..

name              Type8                 Type9
AU0000XVGZA3      No Redemption         ETM - Waiting Close
GB0002634946      Partial Prerefunded
US0378331005                            ETM - Principal Only


Deleting rows from a spreadsheet where Column C is blank

Things I like:

Going last row to first, so as to avoid messiness with row numbers that occur when deleting whole rows.
Good use of With
Good function naming of GetTickCount (at least, assuming it does what it says it does)

And now that that's done:

Option Explicit

This should be at the top of every code module you ever create in VBA. Go to Tools --> Options --> Require Variable Declaration and it will automatically insert it for you from now on.

This is important because without it, VBA will interpret any new variable names (including mis-spellings) as entirely new variables, instead of what you intended.

It also forces you to declare your variables. So you must explicitly give them a type (Long, String, Variant etc.) and a scope (Procedure Dim var As, Module Private Var As, Project Public Var As).

This will then automatically catch all sorts of unintended situations (such as accidentally setting a number equal to an object) which would not be caught if VBA has to assume that all your variables are Variant because you never explicitly declared them.

Naming

Good Variable naming is one of the most important skills you can develop as a developer. Variable names (including values, objects, functions, even whole projects) should be Clear, Concise and, above all, Unambiguous.

Your variable names here are good. Your function name is not. Longer bears absolutely no relation to "Deleting Rows".

A function name like RemoveRowsWithEmptyCellsInRange would be far better.

Re-usability

Rather than hard-coding this function for column C of the active sheet, why not create a function to do it for any column at all?

Perhaps something like this?

Private Sub DescriptiveNameHere()

    Dim columnIndex As Long
    columnIndex = 3 '/ Column "C"

    Dim firstRow As Long, lastRow As Long
    firstRow = 20
    lastRow = Cells(Rows.Count, columnIndex).End(xlUp).row

    RemoveRowsWithEmptyCellsInColumn ActiveSheet, columnIndex, firstRow, lastRow

End Sub

Public Sub RemoveRowsWithEmptyCellsInColumn(ByRef targetSheet as Worksheet, ByVal columnIndex As Long, ByVal firstRow As Long, ByVal lastRow As Long)

    Dim ws as Worksheet
    Set ws = targetSheet
    ws.Activate

    Dim row As Long, col As Long
    Dim checkCell As Range

    col = columnIndex
    For row = lastRow To firstRow Step -1
        Set checkCell = ws.Cells(row, col)
        If IsEmpty(checkCell) Then Rows(row).Delete
        '/ You might also want to check for cells that appear empty but contain E.G. a formula that is currently displaying no value, like so:
        ' If checkCell.Text = "" Then Rows(row).Delete
    Next row

End Sub

Speed

Very low-hanging standard VBA fruit here:

Public Sub DisableApplicationSettings()

    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual

End Sub

Public Sub ResetApplicationSettings()

    Application.ScreenUpdating = True
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic

End Sub

Put that at the start and end of any VBA program and it will run inordinantly faster.

However, it doesn't take into account how the spreadsheet was before your program started (what if your user already had calculation set to manual?).

So, these, coupled with some public variables and some error handling so premature ending of the code execution still restores the settings, is even better:

Public VarScreenUpdating    As Boolean
Public VarEnableEvents      As Boolean
Public VarCalculation       As XlCalculation

Public Sub StoreApplicationSettings()

    VarScreenUpdating = Application.ScreenUpdating
    VarEnableEvents = Application.EnableEvents
    VarCalculation = Application.Calculation

End Sub

Public Sub DisableApplicationSettings()

    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual

End Sub

Public Sub RestoreApplicationSettings()

    Application.ScreenUpdating = VarScreenUpdating
    Application.EnableEvents = VarEnableEvents
    Application.Calculation = VarCalculation

End Sub


Placing all the input and output in a separate function would improve the structure of program.
Computing the bill follows the exact same logic for both types of connection; they are just using a different price list. You could use a data structure to represent the price list, and pass it to the billing function as a parameter.


use trie data structure to solve the problem of clustering anagrams

#include <cstring>

Avoid including C headers when programming C++.

struct Index_node_base
{
    Index_node_base* next;
    Index_node_base():next(NULL){}
};

struct Index_node : public Index_node_base
{
    int index;
    Index_node(int i):index(i), Index_node_base(){}
};

void insert_index_node(Index_node** head, int i)
{
     Index_node* node = new Index_node(i);
     node->next = (*head);
     *head = node;
}

This is overkill as you are just re-implementing a list of numbers / characters.

const char*

This is C code, consider using the C++ std::string instead.

const char* word_arr[]

For example, this one should be a std::list<std::string> (a.k.a. list<string>)

 printf("%s\n", word_arr[h->index]);

Again C, use the C++ iostreams instead. This should be like cout << ... << endl;

while(*w)
{
    int i = *w - 'a';
    if(r->child[i] == NULL)
    {
        r->child[i] = new Trie_node(r->num_of_child);
    }
    r = (Trie_node*)r->child[i];
    ++w;
}

You can use iterators and STL algorithms to do this in one line.

for(i = 0; i < r->num_of_child; ++i)
{
    if(r->child[i] != NULL)
        traversal_trie(word_arr, (Trie_node*)r->child[i]);
}

This would also be one line using for_each on iterators and passing traversal_trie.

void Trie::destroy(Trie_node* root)

You won't need destory anymore as a result; also, there's a chance you might not need pointers.

static int comp_char(const void* x, const void* y)
{
    const char* c1 = (const char*)x;
    const char* c2 = (const char*)y;

    return *(c1) - *(c2);
}

This is messsy, you are doing useless C style voids and casts and not using C++ overloading. This body would have been something along the line of just the line return c1 < c2;

for(i = 0; i < size; ++i)
{
    int len = strlen(word_arr[i]);
    buffer = new char [len+1];
    memcpy(buffer, word_arr[i], len+1);
    qsort(buffer, strlen(buffer), 1, comp_char);
    trie->insert_trie_node(buffer, i);
    delete buffer;
}

memcpy? Not necessary, std::string allows you to copy the string and not mess with memory.


Abstracting getter and setter method references for testing

I had no issues, but I'm not sure if "easy to understand" is actually answerable.

There's still room for improvement, though: Your areEqual method can be replaced by Objects.equals.

private static <T> boolean isSetConsistentToGet(T input, Consumer<T> setter, Supplier<T> getter) {
    setter.accept(input);
    T getValue = getter.get();
    return Objects.equals(input, getValue);
}

Let me also throw in two frameworks that might make your life easier:

Project Lombok. Lombok can generate getters and setters for your fields, (IMHO) removing the necessity for writing any explicit tests completely.
OpenPojo. I haven't used that one yet, but it claims to do getter/setter validation automagically and has been suggested on Stack Overflow.


Simple Duration calculator using es6 class syntax

NOTE     I'll only be taking a look at your Duration class, not the UI-specific code.

Regex as a constant

You don't need to re-instantiate a new RegExp instance every time a Duration is instantiated.
Move the regex initialization to the global context, or maybe as a static field of the class.
This saves memory as it's not allocated for the same regex over and over whenever you call new Duration.

Also, let's be more descriptive in its naming.
Since it's used for validation, let's name it exactly that.

class Duration {
  static VALIDATION = /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/;
  constructor(start, end) {
    // ...
  }
  // ...
}

You also don't need to instantiate it with the RegExp function; you can just place it there as a literal as it's known run-time.

Helper methods

...shouldn't be methods at all, but functions instead.
The _seconds and _round do not belong in the Duration class.
They are pure utility functions that don't touch this at all: give them something as input, and something comes out as output.

If you put them in a separate file, they also become more reusable.
Your round function, for example, has nothing to do with Duration and thus you could re-use it in any math-based code -- like a renderer in a 3D engine!

function seconds(time = "00:00") { /* ... */ }
function round(float) { /* ... */ }

class Duration {
  static VALIDATION = /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/;
  constructor(start, end) { /* ... */ }
  get difference() { /* ... */ }
}

A good rule of thumb that a method should be a util function is that it doesn't use this.
If you feel that the util function is still semantically tied to the class, you should place it as a static method.

This also make the get difference part simpler:

get difference() {
  const { start, end } = this;
  return round((seconds(end) - seconds(start)) / 60);
}

Validation

Constructor is a good place for validation in this case.
If someone passes in some junk instead of valid timestamps, you'd want to catch that immediately as no operation would make sense if the start and end are not valid timestamps.

However, your handling of validation only hides errors under the rug.
Say that someone, by mistake, tries to create a Duration like this:

new Duration("12:00", "1300")

Your validation will successfully test that 12:00 is fine, and assign that to start, but the 1300 will be silently treated as 00:00.
And now my duration is actually (12:00, 00:00), but I wanted (12:00, 13:00).
A silent bug.
No error in console, but my results are weird.
Difficult to debug!

That's why you should throw an exception if the validation fails.
Feel free to scream at me, I want to know that I've messed up.

Here's the idea:

constructor(start, end) {
  if (!Duration.VALIDATION.test(start)) {
    throw new Error(`The "start" argument (${start}) is in wrong format.`)
  } else {
    this.start = start
  }
}

Notice what makes a good error message: it tells me exactly what I've screwed up.
It would be even better if it went on and explained what is a valid argument, but I'll go ahead and assume that it's obvious in this case for brevity.

In order to avoid repeating, you can extract the validation as a method.
The method would act as a no-op function in case everything is OK, but throw if something's wrong.
It's a good candidate for a static method, since it's clearly tightly coupled with the Duration class.

static throwIfError(arg, argName) {
  if (!Duration.VALIDATION.test(arg)) {
    throw new Error(`The "${argName}" argument (${arg}) is in wrong format.`);
  }
  return arg;
}

constructor(start, end) {
  this.start = Duration.throwIfError(start, 'start');
  this.end = Duration.throwIfError(end, 'end');
}

The second argument is just for a prettier message.
Now, when I try my example, new Date("12:00", "1300"), I get an error message saying this:

  Error: The "end" argument (1300) is in wrong format.

Complete code

My full refactored version of the original code is below, along with an example of usage.

function seconds(time = "00:00") {
  const split = time.split(':');
  return Number(split[0]) * 60 + Number(split[1]);
}

// See: https://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-only-if-necessary
function round(float) {
  return Math.round((float + 0.0001) * 100) / 100;
}

class Duration {
  static VALIDATION = /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/;

  static throwIfError(arg, argName) {
    if (!Duration.VALIDATION.test(arg)) {
      throw new Error(`The "${argName}" argument (${arg}) is in wrong format.`);
    }
    return arg;
  }

  constructor(start, end) {
    this.start = Duration.throwIfError(start, 'start');
    this.end = Duration.throwIfError(end, 'end');
  }

  get difference() {
    const { start, end } = this;
    return round((seconds(end) - seconds(start)) / 60);
  }

}

console.log("From 12:00 to 13:00 => ");
console.log(new Duration("12:00", "13:00").difference);
console.log("From 12:00 to 1300 (!) => ");
console.log(new Duration("12:00", "1300").difference);


Using Comparator with 3 conditions at the same time

The shortest way to do this is using the Java 8 Comparator building api :

Comparator<Dto> myComparator = Comparator.comparing(Dto::getName)
    .thenComparing(Dto::Number)
    .thenComparing(Dto::Other);

And this is even a lot more readable.

Btw : your method names do not follow Java coding conventions, and the posted code doesn't actually compile.


What is the use case and rationale for this module? I can see what it does, but I'm struggling to understand why I'd want to do it.
The fact that you have three almost identical case statements to drive the behaviour is a 'code smell'. In most other OO languages you'd use inheritance or an interface and a factory method to determine which subclass of an object to create (with a single case statement). In that case, the objective is to abstract away the differences between connecting to the databases behind an interface (which is what you seem to be trying to do in method database_authentication_success?). But the metaprogramming code generates explicitly-named methods for connecting to each type of database, which seems to do the opposite and makes it harder to use.


A tiny command-line program that prints a sum of numbers

You have a compiler warning. One of the points of using a statically typed language is to have the compiler watching your back. If you ignore what the compiler says, you lose out.

warning: unused variable: `n`, #[warn(unused_variables)] on by default
  --> main.rs:14:17
   |
14 |             Err(n) => {
   |                 ^

If you don't care about the value, use an underscore (_).
Learn and love Rustfmt.

There are no braces on one-line match arms.
Always use trailing commas on multiple line items.
Use spaces inside braces ({ break }).

If the current code encounters an error while reading input, it continues processing. That seems unintuitive.
The current code uses trim when parsing, but only trim_right when showing the error to the user. This seems like a way of confusing the user when the error occurs.
It's potentially inefficient to reallocate the string in each iteration. Moving it outside the loop would mean you are responsible for clearing it each iteration. Failing to clear it would be a bug and potential security hole.
However, the code to process each line is already implemented for you.
There's duplicate error handling code. I'd extract a method to be able to use Result. I love using quick_error to construct error enumerations. This lets you use try! or ?.

#[macro_use]
extern crate quick_error;

use std::io::{self, BufRead};
use std::process;

use quick_error::ResultExt;

quick_error! {
    #[derive(Debug)]
    enum Error {
        Io(err: io::Error) {
            from()
            description("unable to read line")
            display("Unable to read line: {}", err)
            cause(err)
        }
        Parse(err: std::num::ParseIntError, num: String) {
            description("unable to parse number")
            display("Unable to parse '{}': {}", num, err)
            cause(err)
            context(num: &'a str, err: std::num::ParseIntError) -> (err, num.into())
        }
    }
}

fn inner_main() -> Result<i32, Error> {
    let mut sum = 0;

    let stdin = io::stdin();
    for line in stdin.lock().lines() {
        let line = line?;
        let line = line.trim();
        sum += line.parse().context(line)?;
    }

    Ok(sum)
}

fn main() {
    match inner_main() {
        Ok(sum) => println!("{}", sum),
        Err(e) => {
            println!("ERROR: {}", e);
            process::exit(1);
        }
    }
}


Here is my analysis:

Well formatted
Both backwards and forwards compatible
Has both block and inline comments

The only thing would be wary of is the margin: 0 on the html, body selector may not work as expected on newer iPhones to Safari's new behavior:
Out of the box, Safari displays your existing websites beautifully on the edge-to-edge display of the new iPhone X. Content is automatically inset within the display’s safe area so it is not obscured by the rounded corners, or the device’s sensor housing.
The inset area is filled with the page's background-color (as specified on the <body> or <html> elements) to blend in with the rest of the page. For many websites, this is enough. If your page has only text and images above a solid background color, the default insets will look great.
The first new feature is an extension to the existing viewport meta tag called viewport-fit, which provides control over the insetting behavior. viewport-fit is available in iOS 11.
The default value of viewport-fit is auto, which results in the automatic insetting behavior seen above. In order to disable that behavior and cause the page to lay out to the full size of the screen, you can set viewport-fit to cover. After doing so, our viewport meta tag now looks like this:

<meta name='viewport' content='initial-scale=1, viewport-fit=cover'>


Microsoft OA | Longest Substring Without 3 Contiguous Occurrences of Letter

After some tests, the code does look correct, but the logic takes some time to parse and understand, which is a significant disadvantage; when writing good, maintainable code, readability is usually the most important factor to consider.
If a script is running too slowly for your liking, you can run a performance test to identify the bottleneck(s) and then fix those bottlenecks (possibly with hard-to-read code like this), but before then, better to write easy-to-write, easy-to-understand code first.
If it were me, I'd use a regular expression. It'll have many fewer "moving parts" than going through the string manually and counting up lengths, and REs are quite widely used for general string matching and manipulation across most programming languages; it's something a programmer will probably already be familiar with, so hopefully using them won't present a problem.
The one complication with a regular expression is that when there may be overlapping matches, the code can get somewhat ugly, see here for examples. Here, with a string of abbba, you'd have to consider both abb and bba, where the middle b is contained in both. Rather than deal with overlapping matches, I'll replace all 3+-contiguous-occurrences with 4-contiguous-occurrences beforehand. Then it's trivial to use .split to split along the middle of each 4-contiguous section, and then return the longest string in the resulting array:

const maxLenSubStr = s => s
  // Expand 3 or more contiguous occurrences to 4 contiguous occurrences
  // eg 'abbba' -> 'abbbba'
  .replace(/(.)\1{2,}/g, '$&$1')
  // Split along the middle of each 4-contiguous subsequence
  // eg 'abbbba' -> ['abb', 'bba']
  .split(/(?<=\1(.))(?=\1{2})/)
  .reduce((a, b) => a.length > b.length ? a : b);

console.log(maxLenSubStr("aabbaaaaabb")); //  => "aabbaa"
console.log(maxLenSubStr("aabbaabbaabbaa")); //  => "aabbaabbaabbaa"
console.log(maxLenSubStr("baaa")); //  => "baa"

For the regular expressions, the same technique is being used in both. Capture a character in a group, then backreference that group to match the same character again as many times as needed.

(.)\1{2,} - (.) captures the character, \1{2,} matches it again 2 or more times, then replaces with 4 occurrences of the character.
(?<=\1(.))(?=\1{2}) - (.) captures the character in the lookbehind, preceded by \1, another occurrence of the character. Then (?=\1{2}) looks ahead for 2 more occurrences of the character.

I'd consider this an order of magnitude easier to understand than your original code. It's much easier to see at a glance that it'll carry out the desired logic properly, at least for those with a bit of experience with regular expressions. Whether it's worth replacing your original code with it would depend on you and your team's familiarity with REs.
If you had to do it without lookbehind (which is not supported on out-of-date browsers), then split with another capturing group around the whole left match, or use .match instead, to match characters until encountering 3 in a row:

const maxLenSubStr = s => s
  // Expand 3 or more contiguous occurrences to 4 contiguous occurrences
  // eg 'abbba' -> 'abbbba'
  .replace(/(.)\1{2,}/g, '$&$1')
  // Split along the middle of each 4-contiguous subsequence
  // eg 'abbbba' -> ['abb', 'bba']
  // Lazily match characters until encountering the end of the string
  // or until 3 of the same character are in a row
  .match(/.*?(?:$|(.)\1(?=\1))/g)
  .reduce((a, b) => a.length > b.length ? a : b);

console.log(maxLenSubStr("aabbaaaaabb")); //  => "aabbaa"
console.log(maxLenSubStr("aabbaabbaabbaa")); //  => "aabbaabbaabbaa"
console.log(maxLenSubStr("baaa")); //  => "baa"
console.log(maxLenSubStr("aaab")); //  => "aab"

If you were to keep using your original code, I'd suggest:

Use strict comparison === instead of sloppy comparison == (which has weird coercion rules a reader of the code shouldn't have to worry about)

Use spaces between non-unary operators and operands, for readability, eg end - start > res.length instead of end-start > res.length

Rather than numOfConsecutiveChars--;, since the new consecutive count will always be 2, better to assign 2 to it directly: numOfConsecutiveChars = 2

Increment numOfConsecutiveChars only when a subsequent consecutive character is found, and not unconditionally. (Your current logic works, it's just confusing)


I'd criticize:

Extension methods on "object" should be avoided because of the broad scope, except for special cases (which such a "ToBool" method is not one). It also feels like an overuse of extension methods.
The first one takes an "object", but really wants a string, and will blow up with an InvalidCastException at runtime.
The second one does not check for null (which wouldn't be a problem in itself, but having overloads for default values with differing behavior is bad).


Should a Factory ever be generated per request?

Just got one thing to say on your code:

Your Comments add close to no value!

your code is littered with comments and empty lines

//Create the Container Builder
var containerBuilder = new ContainerBuilder();

The comment is in fact almost exactly the same as the code below. And it's not only there, it's the same with every comment in the AutofacRegistrations you posted.

Other than that, if your factory has a dependency on Session you maybe did something wrong. Instead you could try to pass the Session to the already instantiated singleton factory, when calling the GetErrorDao() Function.

That would instead look something like that:

public IErrorDao GetErrorDao(Session session)
{
     return ErrorDao ?? (ErrorDao = new ErrorDao(session));
}

this would decouple both your NHibernateDaoFactory and your ManagerFactory and let them be free to use a singleton pattern instead. Which in turn greatly reduces the stress your application puts on the system.

You'd need to cascade this up the Dependency Chain, but that's a small price to pay to have a decoupled Factory Instance for all Requests / Sessions instead of one for each Session.
You'd thus need to modify your GetErrorManager too:

public IErrorManager GetErrorManager(Session session)
{
    return ErrorManager ?? (ErrorManager = new ErrorManager(Logger, DaoFactory.GetErrorDao(session)));
}


Waiting for a file to be accessible with Thread.Sleep() and exception catching

How about making this an asynchrounous operation that only returns if the stream has successfully been opened. you can get rid of the while(true) and the thread sleep plus the new mthod call cn have a retry count.

Here is what it might look like if you use C# 4.0 (not tested).

Task<FileStream> OpenStreamAsync(String filename, FileAccess fileAccess, FileShare fileShare,int retryCount){

    if (retryCount < 1)
        throw new Exception("maximum retry reached");

    return
        Task.Factory.StartNew(() => new FileStream(filename, FileMode.OpenOrCreate, fileAccess, fileShare))
        .ContinueWithTask( task => {
            if (task.IsCompleted)
                return task;

            Logger.LogError(ex); // Information purposes only
            return TaskExtenstion2.Wait(TimeSpan.FromMilliseconds(250))
                .ContinueWithTask(t => OpenStreamAsync(filename, fileAccess, fileShare,retryCount--) );
        });
}

public static class TaskExtenstion2 {

    /// Set the completionSource to the same values as the task
    public static void SetCompletionSource<TResult>(this Task<TResult> task, TaskCompletionSource<TResult> completionSource){
        if (task.IsCompleted){
            completionSource.SetResult(task.Result);
        }else if (task.IsCanceled){
            completionSource.SetCanceled();
        }else if (task.IsFaulted){
            completionSource.SetException(task.Exception);
        }
    }

    /// Continues a task with another task genrated by the specified function
    public static Task<U> ContinueWithTask<T,U>(this Task<T> sourceTask, Func<Task<T>,Task<U>> continuation){
        var completionSource = new TaskCompletionSource<U>();
        sourceTask.ContinueWith(firstTask => {
            var secondTask = continuation(firstTask);
            secondTask.ContinueWith(task => task.SetCompletionSource(completionSource));
        });
        return completionSource.Task;
    }

     /// returns true after a certain amount of time
     public static Task<bool> Wait(TimeSpan span){
         var completionSource = new TaskCompletionSource<bool>();
         Timer timer = null;
         timer = new Timer(_ => {
             using(timer) {
               completionSource.SetResult(true);
             }
         },null,span,TimeSpan.MaxValue);
         return completionSource.Task;
     }
}

if you still want to block the main thread, getting the Result property of the returning task will make sure of that

var stream = OpenStreamAsync("myFile", FileAccess.ReadWrite, FileShare.None,20).Result;