text:
void pr6884_abort() __attribute__((noreturn));

struct pr6884_abort_struct {
  pr6884_abort_struct() {}
  ~pr6884_abort_struct() __attribute__((noreturn)) { pr6884_abort(); }
};

struct other { ~other() {} };

// Ensure that destructors from objects are properly modeled in the CFG despite
// the presence of switches, case statements, labels, and blocks. These tests
// try to cover bugs reported in both PR6884 and PR10063.
namespace abort_struct_complex_cfgs {
  int basic(int x) {
    switch (x) { default: pr6884_abort(); }
  }
  int f1(int x) {
    switch (x) default: pr6884_abort_struct();
  }
  int f2(int x) {
    switch (x) { default: pr6884_abort_struct(); }
  }
  int f2_positive(int x) {
    switch (x) { default: ; }
  } // expected-warning {{control reaches end of non-void function}}
  int f3(int x) {
    switch (x) { default: { pr6884_abort_struct(); } }
  }
  int f4(int x) {
    switch (x) default: L1: L2: case 4: pr6884_abort_struct();
  }
  int f5(int x) {
    switch (x) default: L1: { L2: case 4: pr6884_abort_struct(); }
  }
  int f6(int x) {
    switch (x) default: L1: L2: case 4: { pr6884_abort_struct(); }
  }

  // FIXME: detect noreturn destructors triggered by calls to delete.
  int f7(int x) {
    switch (x) default: L1: L2: case 4: {
      pr6884_abort_struct *p = new pr6884_abort_struct();
      delete p;
    }
  } // expected-warning {{control reaches end of non-void function}}

  // Test that these constructs work even when extraneous blocks are created
  // before and after the switch due to implicit destructors.
  int g1(int x) {
    other o;
    switch (x) default: pr6884_abort_struct();
  }
  int g2(int x) {
    other o;
    switch (x) { default: pr6884_abort_struct(); }
  }
  int g2_positive(int x) {
    other o;
    switch (x) { default: ; }
  } // expected-warning {{control reaches end of non-void function}}
  int g3(int x) {
    other o;
    switch (x) { default: { pr6884_abort_struct(); } }
  }
  int g4(int x) {
    other o;
    switch (x) default: L1: L2: case 4: pr6884_abort_struct();
  }
  int g5(int x) {
    other o;
    switch (x) default: L1: { L2: case 4: pr6884_abort_struct(); }
  }
  int g6(int x) {
    other o;
    switch (x) default: L1: L2: case 4: { pr6884_abort_struct(); }
  }

  // Test that these constructs work even with variables carrying the no-return
  // destructor instead of temporaries.
  int h1(int x) {
    other o;
    switch (x) default: pr6884_abort_struct a;
  }
  int h2(int x) {
    other o;
    switch (x) { default: pr6884_abort_struct a; }
  }
  int h3(int x) {
    other o;
    switch (x) { default: { pr6884_abort_struct a; } }
  }
  int h4(int x) {
    other o;
    switch (x) default: L1: L2: case 4: pr6884_abort_struct a;
  }
  int h5(int x) {
    other o;
    switch (x) default: L1: { L2: case 4: pr6884_abort_struct a; }
  }
  int h6(int x) {
    other o;
    switch (x) default: L1: L2: case 4: { pr6884_abort_struct a; }
  }
}

// PR9380
struct PR9380 {
  ~PR9380();
};
struct PR9380_B : public PR9380 {
  PR9380_B( const PR9380& str );
};
void test_PR9380(const PR9380& aKey) {
  const PR9380& flatKey = PR9380_B(aKey);
}

// Array of objects with destructors.  This is purely a coverage test case.
void test_array() {
  PR9380 a[2];
}

// Test classes wrapped in typedefs.  This is purely a coverage test case
// for CFGImplictDtor::getDestructorDecl().
void test_typedefs() {
  typedef PR9380 PR9380_Ty;
  PR9380_Ty test;
  PR9380_Ty test2[20];
}

// PR9412 - Handle CFG traversal with null successors.
enum PR9412_MatchType { PR9412_Exact };

template <PR9412_MatchType type> int PR9412_t() {
  switch (type) {
    case PR9412_Exact:
    default:
        break;
  }
} // expected-warning {{control reaches end of non-void function}}

void PR9412_f() {
    PR9412_t<PR9412_Exact>(); // expected-note {{in instantiation of function template specialization 'PR9412_t<PR9412_Exact>' requested here}}
}

struct NoReturn {
  ~NoReturn() __attribute__((noreturn));
  operator bool() const;
};
struct Return {
  ~Return();
  operator bool() const;
};

int testTernaryUnconditionalNoreturn() {
  true ? NoReturn() : NoReturn();
}

int testTernaryStaticallyConditionalNoretrunOnTrue() {
  true ? NoReturn() : Return();
}

int testTernaryStaticallyConditionalRetrunOnTrue() {
  true ? Return() : NoReturn();
} // expected-warning {{control reaches end of non-void function}}

int testTernaryStaticallyConditionalNoretrunOnFalse() {
  false ? Return() : NoReturn();
}

int testTernaryStaticallyConditionalRetrunOnFalse() {
  false ? NoReturn() : Return();
} // expected-warning {{control reaches end of non-void function}}

int testTernaryConditionalNoreturnTrueBranch(bool value) {
  value ? (NoReturn() || NoReturn()) : Return();
} // expected-warning {{control may reach end of non-void function}}

int testTernaryConditionalNoreturnFalseBranch(bool value) {
  value ? Return() : (NoReturn() || NoReturn());
} // expected-warning {{control may reach end of non-void function}}

int testConditionallyExecutedComplexTernaryTrueBranch(bool value) {
  value || (true ? NoReturn() : true);
} // expected-warning {{control may reach end of non-void function}}

int testConditionallyExecutedComplexTernaryFalseBranch(bool value) {
  value || (false ? true : NoReturn());
} // expected-warning {{control may reach end of non-void function}}

int testStaticallyExecutedLogicalOrBranch() {
  false || NoReturn();
}

int testStaticallyExecutedLogicalAndBranch() {
  true && NoReturn();
}

int testStaticallySkippedLogicalOrBranch() {
  true || NoReturn();
} // expected-warning {{control reaches end of non-void function}}

int testStaticallySkppedLogicalAndBranch() {
  false && NoReturn();
} // expected-warning {{control reaches end of non-void function}}

int testConditionallyExecutedComplexLogicalBranch(bool value) {
  value || (true && NoReturn());
} // expected-warning {{control may reach end of non-void function}}

int testConditionallyExecutedComplexLogicalBranch2(bool value) {
  (true && value) || (true && NoReturn());
} // expected-warning {{control may reach end of non-void function}}

int testConditionallyExecutedComplexLogicalBranch3(bool value) {
  (false && (Return() || true)) || (true && NoReturn());
}

int testConditionallyExecutedComplexLogicalBranch4(bool value) {
  false || ((Return() || true) && (true && NoReturn()));
}

#if __cplusplus >= 201103L
namespace LambdaVsTemporaryDtor {
  struct Y { ~Y(); };
  struct X { template<typename T> X(T, Y = Y()) {} };

  struct Fatal { ~Fatal() __attribute__((noreturn)); };
  struct FatalCopy { FatalCopy(); FatalCopy(const FatalCopy&, Fatal F = Fatal()); };

  void foo();

  int bar() {
    X work([](){ Fatal(); });
    foo();
  } // expected-warning {{control reaches end of non-void function}}

  int baz() {
    FatalCopy fc;
    X work([fc](){});
    foo();
  } // ok, initialization of lambda does not return
}
#endif

// Ensure that function-try-blocks also check for return values properly.
int functionTryBlock1(int s) try {
  return 0;
} catch (...) {
} // expected-warning {{control may reach end of non-void function}}

int functionTryBlock2(int s) try {
} catch (...) {
  return 0;
} // expected-warning {{control may reach end of non-void function}}

int functionTryBlock3(int s) try {
  return 0;
} catch (...) {
  return 0;
} // ok, both paths return.


text:
var getSetIconHandler = require('setIcon').getSetIconHandler;

apiBridge.registerCustomHook(function(bindingsAPI) {
  var apiFunctions = bindingsAPI.apiFunctions;

  apiFunctions.setHandleRequest(
      'setIcon', getSetIconHandler('pageAction.setIcon'));
});

redpajama_set_name: RedPajamaGithub


text:
package secure

import (
	"fmt"
	"net/http"
	"strings"
)

const (
	stsHeader           = "Strict-Transport-Security"
	stsSubdomainString  = "; includeSubdomains"
	stsPreloadString    = "; preload"
	frameOptionsHeader  = "X-Frame-Options"
	frameOptionsValue   = "DENY"
	contentTypeHeader   = "X-Content-Type-Options"
	contentTypeValue    = "nosniff"
	xssProtectionHeader = "X-XSS-Protection"
	xssProtectionValue  = "1; mode=block"
	cspHeader           = "Content-Security-Policy"
	hpkpHeader          = "Public-Key-Pins"
)

func defaultBadHostHandler(w http.ResponseWriter, r *http.Request) {
	http.Error(w, "Bad Host", http.StatusInternalServerError)
}

// Options is a struct for specifying configuration options for the secure.Secure middleware.
type Options struct {
	// AllowedHosts is a list of fully qualified domain names that are allowed. Default is empty list, which allows any and all host names.
	AllowedHosts []string
	// If SSLRedirect is set to true, then only allow https requests. Default is false.
	SSLRedirect bool
	// If SSLTemporaryRedirect is true, the a 302 will be used while redirecting. Default is false (301).
	SSLTemporaryRedirect bool
	// SSLHost is the host name that is used to redirect http requests to https. Default is "", which indicates to use the same host.
	SSLHost string
	// SSLProxyHeaders is set of header keys with associated values that would indicate a valid https request. Useful when using Nginx: `map[string]string{"X-Forwarded-Proto": "https"}`. Default is blank map.
	SSLProxyHeaders map[string]string
	// STSSeconds is the max-age of the Strict-Transport-Security header. Default is 0, which would NOT include the header.
	STSSeconds int64
	// If STSIncludeSubdomains is set to true, the `includeSubdomains` will be appended to the Strict-Transport-Security header. Default is false.
	STSIncludeSubdomains bool
	// If STSPreload is set to true, the `preload` flag will be appended to the Strict-Transport-Security header. Default is false.
	STSPreload bool
	// If ForceSTSHeader is set to true, the STS header will be added even when the connection is HTTP. Default is false.
	ForceSTSHeader bool
	// If FrameDeny is set to true, adds the X-Frame-Options header with the value of `DENY`. Default is false.
	FrameDeny bool
	// CustomFrameOptionsValue allows the X-Frame-Options header value to be set with a custom value. This overrides the FrameDeny option.
	CustomFrameOptionsValue string
	// If ContentTypeNosniff is true, adds the X-Content-Type-Options header with the value `nosniff`. Default is false.
	ContentTypeNosniff bool
	// If BrowserXssFilter is true, adds the X-XSS-Protection header with the value `1; mode=block`. Default is false.
	BrowserXssFilter bool
	// ContentSecurityPolicy allows the Content-Security-Policy header value to be set with a custom value. Default is "".
	ContentSecurityPolicy string
	// PublicKey implements HPKP to prevent MITM attacks with forged certificates. Default is "".
	PublicKey string
	// When developing, the AllowedHosts, SSL, and STS options can cause some unwanted effects. Usually testing happens on http, not https, and on localhost, not your production domain... so set this to true for dev environment.
	// If you would like your development environment to mimic production with complete Host blocking, SSL redirects, and STS headers, leave this as false. Default if false.
	IsDevelopment bool
}

// Secure is a middleware that helps setup a few basic security features. A single secure.Options struct can be
// provided to configure which features should be enabled, and the ability to override a few of the default values.
type Secure struct {
	// Customize Secure with an Options struct.
	opt Options

	// Handlers for when an error occurs (ie bad host).
	badHostHandler http.Handler
}

// New constructs a new Secure instance with supplied options.
func New(options ...Options) *Secure {
	var o Options
	if len(options) == 0 {
		o = Options{}
	} else {
		o = options[0]
	}

	return &Secure{
		opt:            o,
		badHostHandler: http.HandlerFunc(defaultBadHostHandler),
	}
}

// SetBadHostHandler sets the handler to call when secure rejects the host name.
func (s *Secure) SetBadHostHandler(handler http.Handler) {
	s.badHostHandler = handler
}

// Handler implements the http.HandlerFunc for integration with the standard net/http lib.
func (s *Secure) Handler(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Let secure process the request. If it returns an error,
		// that indicates the request should not continue.
		err := s.Process(w, r)

		// If there was an error, do not continue.
		if err != nil {
			return
		}

		h.ServeHTTP(w, r)
	})
}

// HandlerFuncWithNext is a special implementation for Negroni, but could be used elsewhere.
func (s *Secure) HandlerFuncWithNext(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
	err := s.Process(w, r)

	// If there was an error, do not call next.
	if err == nil && next != nil {
		next(w, r)
	}
}

// Process runs the actual checks and returns an error if the middleware chain should stop.
func (s *Secure) Process(w http.ResponseWriter, r *http.Request) error {
	// Allowed hosts check.
	if len(s.opt.AllowedHosts) > 0 && !s.opt.IsDevelopment {
		isGoodHost := false
		for _, allowedHost := range s.opt.AllowedHosts {
			if strings.EqualFold(allowedHost, r.Host) {
				isGoodHost = true
				break
			}
		}

		if !isGoodHost {
			s.badHostHandler.ServeHTTP(w, r)
			return fmt.Errorf("Bad host name: %s", r.Host)
		}
	}

	// Determine if we are on HTTPS.
	isSSL := strings.EqualFold(r.URL.Scheme, "https") || r.TLS != nil
	if !isSSL {
		for k, v := range s.opt.SSLProxyHeaders {
			if r.Header.Get(k) == v {
				isSSL = true
				break
			}
		}
	}

	// SSL check.
	if s.opt.SSLRedirect && !isSSL && !s.opt.IsDevelopment {
		url := r.URL
		url.Scheme = "https"
		url.Host = r.Host

		if len(s.opt.SSLHost) > 0 {
			url.Host = s.opt.SSLHost
		}

		status := http.StatusMovedPermanently
		if s.opt.SSLTemporaryRedirect {
			status = http.StatusTemporaryRedirect
		}

		http.Redirect(w, r, url.String(), status)
		return fmt.Errorf("Redirecting to HTTPS")
	}

	// Strict Transport Security header. Only add header when we know it's an SSL connection.
	// See https://tools.ietf.org/html/rfc6797#section-7.2 for details.
	if s.opt.STSSeconds != 0 && (isSSL || s.opt.ForceSTSHeader) && !s.opt.IsDevelopment {
		stsSub := ""
		if s.opt.STSIncludeSubdomains {
			stsSub = stsSubdomainString
		}

		if s.opt.STSPreload {
			stsSub += stsPreloadString
		}

		w.Header().Add(stsHeader, fmt.Sprintf("max-age=%d%s", s.opt.STSSeconds, stsSub))
	}

	// Frame Options header.
	if len(s.opt.CustomFrameOptionsValue) > 0 {
		w.Header().Add(frameOptionsHeader, s.opt.CustomFrameOptionsValue)
	} else if s.opt.FrameDeny {
		w.Header().Add(frameOptionsHeader, frameOptionsValue)
	}

	// Content Type Options header.
	if s.opt.ContentTypeNosniff {
		w.Header().Add(contentTypeHeader, contentTypeValue)
	}

	// XSS Protection header.
	if s.opt.BrowserXssFilter {
		w.Header().Add(xssProtectionHeader, xssProtectionValue)
	}

	// HPKP header.
	if len(s.opt.PublicKey) > 0 && isSSL && !s.opt.IsDevelopment {
		w.Header().Add(hpkpHeader, s.opt.PublicKey)
	}

	// Content Security Policy header.
	if len(s.opt.ContentSecurityPolicy) > 0 {
		w.Header().Add(cspHeader, s.opt.ContentSecurityPolicy)
	}

	return nil
}


text:
define(function () {
  return function (ParsleyValidator) {
    describe('ParsleyValidator', function () {
      var parsleyValidator = new ParsleyValidator(window.ParsleyConfig.validators || {}, window.ParsleyConfig.i18n || {});

      it('should be a function', function () {
        expect(ParsleyValidator).to.be.a('function');
      });
      it('should bind global config validators if given in constructor', function () {
        window.ParsleyConfig = {
          i18n : window.ParsleyConfig.i18n,
          validators: $.extend(window.ParsleyConfig.validators, {
            foo: { fn: function () {}, priority: 42 },
            bar: { fn: function () {}, priority: 12 }
          })
        };
        var parsleyValidator = new ParsleyValidator(window.ParsleyConfig.validators);
        expect(parsleyValidator.validators).to.have.key('foo');
        expect(parsleyValidator.validators).to.have.key('bar');
        delete window.ParsleyConfig.validators.foo;
        delete window.ParsleyConfig.validators.bar;
      });
      it('should have a required validator', function () {
        expect(parsleyValidator.validate('', parsleyValidator.validators.required())).not.to.be(true);
        expect(parsleyValidator.validate('foo', parsleyValidator.validators.required())).to.be(true);
      });
      it('should have a notblank validator', function () {
        expect(parsleyValidator.validate(' ', parsleyValidator.validators.notblank())).not.to.be(true);
        expect(parsleyValidator.validate('foo', parsleyValidator.validators.notblank())).to.be(true);
      });
      it('should have a type="email" validator', function () {
        expect(parsleyValidator.validate('', parsleyValidator.validators.type('email'))).not.to.be(true);
        expect(parsleyValidator.validate('foo', parsleyValidator.validators.type('email'))).not.to.be(true);
        expect(parsleyValidator.validate('foo@bar.baz', parsleyValidator.validators.type('email'))).to.be(true);
        expect(parsleyValidator.validate('foo+bar@bar.baz', parsleyValidator.validators.type('email'))).to.be(true);
        expect(parsleyValidator.validate('foo.bar@bar.baz', parsleyValidator.validators.type('email'))).to.be(true);
        expect(parsleyValidator.validate('foo.bar@bar.com.ext', parsleyValidator.validators.type('email'))).to.be(true);
      });
      it('should have a min validator', function () {
        expect(parsleyValidator.validate('', parsleyValidator.validators.min(6))).not.to.be(true);
        expect(parsleyValidator.validate('foo', parsleyValidator.validators.min(6))).not.to.be(true);
        expect(parsleyValidator.validate('1', parsleyValidator.validators.min(6))).not.to.be(true);
        expect(parsleyValidator.validate('6', parsleyValidator.validators.min(6))).to.be(true);
        expect(parsleyValidator.validate('10', parsleyValidator.validators.min(6))).to.be(true);
      });
      it('should have a max validator', function () {
        expect(parsleyValidator.validate('', parsleyValidator.validators.max(10))).not.to.be(true);
        expect(parsleyValidator.validate('foo', parsleyValidator.validators.max(10))).not.to.be(true);
        expect(parsleyValidator.validate('1', parsleyValidator.validators.max(10))).to.be(true);
        expect(parsleyValidator.validate('10', parsleyValidator.validators.max(10))).to.be(true);
        expect(parsleyValidator.validate('17', parsleyValidator.validators.max(10))).not.to.be(true);
      });
      it('should have a range validator', function () {
        expect(parsleyValidator.validate('1', parsleyValidator.validators.range([5, 10]))).not.to.be(true);
        expect(parsleyValidator.validate('7', parsleyValidator.validators.range([5, 10]))).to.be(true);
        expect(parsleyValidator.validate('17', parsleyValidator.validators.range([5, 10]))).not.to.be(true);
      });
      it('should have a type="number" validator', function () {
        expect(parsleyValidator.validate('foo', parsleyValidator.validators.type('number'))).not.to.be(true);
        expect(parsleyValidator.validate('1', parsleyValidator.validators.type('number'))).to.be(true);
        expect(parsleyValidator.validate('1.5', parsleyValidator.validators.type('number'))).to.be(true);
        expect(parsleyValidator.validate('-1.5', parsleyValidator.validators.type('number'))).to.be(true);
        expect(parsleyValidator.validate('1,500.642', parsleyValidator.validators.type('number'))).to.be(true);
      });
      it('should have a type="digits" validator', function () {
        expect(parsleyValidator.validate('foo', parsleyValidator.validators.type('digits'))).not.to.be(true);
        expect(parsleyValidator.validate('1', parsleyValidator.validators.type('digits'))).to.be(true);
        expect(parsleyValidator.validate('-1', parsleyValidator.validators.type('digits'))).not.to.be(true);
        expect(parsleyValidator.validate('1.5', parsleyValidator.validators.type('digits'))).not.to.be(true);
        expect(parsleyValidator.validate('-1.5', parsleyValidator.validators.type('digits'))).not.to.be(true);
        expect(parsleyValidator.validate('1,500.642', parsleyValidator.validators.type('digits'))).not.to.be(true);
      });
      it('should have a type="integer" validator', function () {
        expect(parsleyValidator.validate('foo', parsleyValidator.validators.type('integer'))).not.to.be(true);
        expect(parsleyValidator.validate('1', parsleyValidator.validators.type('integer'))).to.be(true);
        expect(parsleyValidator.validate('-1', parsleyValidator.validators.type('integer'))).to.be(true);
        expect(parsleyValidator.validate('1.5', parsleyValidator.validators.type('integer'))).not.to.be(true);
        expect(parsleyValidator.validate('-1.5', parsleyValidator.validators.type('integer'))).not.to.be(true);
      });
      it('should have a type="alphanum" validator', function () {
        expect(parsleyValidator.validate('foo', parsleyValidator.validators.type('alphanum'))).to.be(true);
        expect(parsleyValidator.validate('foo bar', parsleyValidator.validators.type('alphanum'))).not.to.be(true);
        expect(parsleyValidator.validate('foo$', parsleyValidator.validators.type('alphanum'))).not.to.be(true);
      });
      it('should have a type="url" validator', function () {
        expect(parsleyValidator.validate('foo', parsleyValidator.validators.type('url'))).not.to.be(true);
        expect(parsleyValidator.validate('foo bar', parsleyValidator.validators.type('url'))).not.to.be(true);
        expect(parsleyValidator.validate('http://', parsleyValidator.validators.type('url'))).not.to.be(true);
        expect(parsleyValidator.validate('foo.bar', parsleyValidator.validators.type('url'))).to.be(true);
        expect(parsleyValidator.validate('www.foo.bar', parsleyValidator.validators.type('url'))).to.be(true);
        expect(parsleyValidator.validate('http://www.foo.bar', parsleyValidator.validators.type('url'))).to.be(true);
        expect(parsleyValidator.validate('https://www.foo.bar', parsleyValidator.validators.type('url'))).to.be(true);
        expect(parsleyValidator.validate('https://www.foobarbaz.barbazbar.bazbar', parsleyValidator.validators.type('url'))).not.to.be(true);
      });
      it('should have a pattern validator', function () {
        expect(parsleyValidator.validate('a', parsleyValidator.validators.pattern('[a-z]+'))).to.be(true);
        expect(parsleyValidator.validate('A', parsleyValidator.validators.pattern('[a-z]+'))).not.to.be(true);
      });
      it('should have a length validator', function () {
        expect(parsleyValidator.validate('foobar', parsleyValidator.validators.length([3, 9]))).to.be(true);
        expect(parsleyValidator.validate('foo', parsleyValidator.validators.length([4, 9]))).not.to.be(true);
        expect(parsleyValidator.validate('foobarbaz', parsleyValidator.validators.length([3, 8]))).not.to.be(true);
      });
      it('should have a minlength validator', function () {
        expect(parsleyValidator.validate('foo', parsleyValidator.validators.minlength(3))).to.be(true);
        expect(parsleyValidator.validate('fo', parsleyValidator.validators.minlength(3))).not.to.be(true);
      });
      it('should have a maxlength validator', function () {
        expect(parsleyValidator.validate('foo', parsleyValidator.validators.maxlength(3))).to.be(true);
        expect(parsleyValidator.validate('foobar', parsleyValidator.validators.maxlength(3))).not.to.be(true);
      });
      it('should have a check validator', function () {
        expect(parsleyValidator.validate(['foo', 'bar', 'baz'], parsleyValidator.validators.check([3, 5]))).to.be(true);
        expect(parsleyValidator.validate(['foo', 'bar', 'baz', 'qux', 'bux'], parsleyValidator.validators.check([3, 4]))).not.to.be(true);
        expect(parsleyValidator.validate(['foo', 'bar'], parsleyValidator.validators.check([3, 5]))).not.to.be(true);
      });
      it('should have a mincheck validator', function () {
        expect(parsleyValidator.validate(['foo', 'bar', 'baz'], parsleyValidator.validators.mincheck(3))).to.be(true);
        expect(parsleyValidator.validate(['foo', 'bar'], parsleyValidator.validators.mincheck(3))).not.to.be(true);
      });
      it('should have a maxcheck validator', function () {
        expect(parsleyValidator.validate(['foo', 'bar', 'baz'], parsleyValidator.validators.maxcheck(3))).to.be(true);
        expect(parsleyValidator.validate(['foo', 'bar', 'baz', 'qux'], parsleyValidator.validators.maxcheck(3))).not.to.be(true);
      });
      it('should have an equalto validator', function () {
        $('body').append('<input type="text" id="element" value="foo" />');
        expect(parsleyValidator.validate('', parsleyValidator.validators.equalto('#element'))).not.to.be(true);
        expect(parsleyValidator.validate('bar', parsleyValidator.validators.equalto('#element'))).not.to.be(true);
        expect(parsleyValidator.validate('foo', parsleyValidator.validators.equalto('#element'))).to.be(true);
      });
      it('should handle proper error message for validators', function () {
        expect(parsleyValidator.getErrorMessage({ name: 'length', requirements: [3, 6] })).to.be('This value length is invalid. It should be between 3 and 6 characters long.');
        expect(parsleyValidator.getErrorMessage({ name: 'notexisting' })).to.be('This value seems to be invalid.');
      });
      it('should handle proper error message for validators in various languages', function () {
        parsleyValidator.setLocale('fr');
        expect(parsleyValidator.getErrorMessage({ name: 'length', requirements: [3, 6] })).to.be('Cette valeur doit contenir entre 3 et 6 caractères.');
        expect(parsleyValidator.getErrorMessage({ name: 'notexisting' })).to.be('Cette valeur semble non valide.');
      });
      afterEach(function () {
        window.ParsleyConfig = { i18n: window.ParsleyConfig.i18n, validators: window.ParsleyConfig.validators };

        if ($('#element').length)
          $('#element').remove();
      });
    });
  };
});


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one
  ~ or more contributor license agreements.  See the NOTICE file
  ~ distributed with this work for additional information
  ~ regarding copyright ownership.  The ASF licenses this file
  ~ to you under the Apache License, Version 2.0 (the
  ~ "License"); you may not use this file except in compliance
  ~ with the License.  You may obtain a copy of the License at
  ~
  ~ http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing,
  ~ software distributed under the License is distributed on an
  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  ~ KIND, either express or implied.  See the License for the
  ~ specific language governing permissions and limitations
  ~ under the License.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.molecule</groupId>
    <artifactId>molecule-parent</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>molecule-examples</artifactId>
  <name>Molecule CodeSet Examples ${project.version}</name>

  <properties>
    <symbolicName>${project.groupId}.examples</symbolicName>
    <exportedPackage>${project.groupId}</exportedPackage>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-slf4j-impl</artifactId>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>${version.log4j}</version>
    </dependency>

    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>molecule-application</artifactId>
      <version>${project.version}</version>
    </dependency>

    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>molecule-packet-api</artifactId>
      <version>${project.version}</version>
    </dependency>

    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>molecule-server</artifactId>
      <version>${project.version}</version>
    </dependency>

  </dependencies>

</project>


text:
import styled from 'styled-components';

const DashboardMain = styled.div`
  flex-direction: column;
  width: 100%;
  height: 100%;
  min-height: 100%;
`;

export default DashboardMain;


text:
package com.github.eirslett.maven.plugins.frontend.lib;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class YarnInstaller {

    public static final String INSTALL_PATH = "/node/yarn";

    public static final String DEFAULT_YARN_DOWNLOAD_ROOT =
        "https://github.com/yarnpkg/yarn/releases/download/";

    private static final Object LOCK = new Object();

    private String yarnVersion, yarnDownloadRoot, userName, password;

    private final Logger logger;

    private final InstallConfig config;

    private final ArchiveExtractor archiveExtractor;

    private final FileDownloader fileDownloader;

    YarnInstaller(InstallConfig config, ArchiveExtractor archiveExtractor, FileDownloader fileDownloader) {
        logger = LoggerFactory.getLogger(getClass());
        this.config = config;
        this.archiveExtractor = archiveExtractor;
        this.fileDownloader = fileDownloader;
    }

    public YarnInstaller setYarnVersion(String yarnVersion) {
        this.yarnVersion = yarnVersion;
        return this;
    }

    public YarnInstaller setYarnDownloadRoot(String yarnDownloadRoot) {
        this.yarnDownloadRoot = yarnDownloadRoot;
        return this;
    }

    public YarnInstaller setUserName(String userName) {
        this.userName = userName;
        return this;
    }

    public YarnInstaller setPassword(String password) {
        this.password = password;
        return this;
    }

    public void install() throws InstallationException {
        // use static lock object for a synchronized block
        synchronized (LOCK) {
            if (yarnDownloadRoot == null || yarnDownloadRoot.isEmpty()) {
                yarnDownloadRoot = DEFAULT_YARN_DOWNLOAD_ROOT;
            }
            if (!yarnIsAlreadyInstalled()) {
                if (!yarnVersion.startsWith("v")) {
                    throw new InstallationException("Yarn version has to start with prefix 'v'.");
                }
                installYarn();
            }
        }
    }

    private boolean yarnIsAlreadyInstalled() {
        try {
            YarnExecutorConfig executorConfig = new InstallYarnExecutorConfig(config);
            File nodeFile = executorConfig.getYarnPath();
            if (nodeFile.exists()) {
                final String version =
                    new YarnExecutor(executorConfig, Arrays.asList("--version"), null).executeAndGetResult(logger).trim();

                if (version.equals(yarnVersion.replaceFirst("^v", ""))) {
                    logger.info("Yarn {} is already installed.", version);
                    return true;
                } else {
                    logger.info("Yarn {} was installed, but we need version {}", version, yarnVersion);
                    return false;
                }
            } else {
                return false;
            }
        } catch (ProcessExecutionException e) {
            return false;
        }
    }

    private void installYarn() throws InstallationException {
        try {
            logger.info("Installing Yarn version {}", yarnVersion);
            String downloadUrl = yarnDownloadRoot + yarnVersion;
            String fileending = "/yarn-" + yarnVersion + ".tar.gz";

            downloadUrl += fileending;

            CacheDescriptor cacheDescriptor = new CacheDescriptor("yarn", yarnVersion, fileending);

            File archive = config.getCacheResolver().resolve(cacheDescriptor);

            downloadFileIfMissing(downloadUrl, archive, userName, password);

            File installDirectory = getInstallDirectory();

            // We need to delete the existing yarn directory first so we clean out any old files, and
            // so we can rename the package directory below.
            try {
                if (installDirectory.isDirectory()) {
                    FileUtils.deleteDirectory(installDirectory);
                }
            } catch (IOException e) {
                logger.warn("Failed to delete existing Yarn installation.");
            }

            extractFile(archive, installDirectory);

            logger.info("Installed Yarn locally.");
        } catch (DownloadException e) {
            throw new InstallationException("Could not download Yarn", e);
        } catch (ArchiveExtractionException e) {
            throw new InstallationException("Could not extract the Yarn archive", e);
        }
    }

    private File getInstallDirectory() {
        File installDirectory = new File(config.getInstallDirectory(), INSTALL_PATH);
        if (!installDirectory.exists()) {
            logger.debug("Creating install directory {}", installDirectory);
            installDirectory.mkdirs();
        }
        return installDirectory;
    }

    private void extractFile(File archive, File destinationDirectory) throws ArchiveExtractionException {
        logger.info("Unpacking {} into {}", archive, destinationDirectory);
        archiveExtractor.extract(archive.getPath(), destinationDirectory.getPath());
    }

    private void downloadFileIfMissing(String downloadUrl, File destination, String userName, String password)
        throws DownloadException {
        if (!destination.exists()) {
            downloadFile(downloadUrl, destination, userName, password);
        }
    }

    private void downloadFile(String downloadUrl, File destination, String userName, String password)
        throws DownloadException {
        logger.info("Downloading {} to {}", downloadUrl, destination);
        fileDownloader.download(downloadUrl, destination.getPath(), userName, password);
    }
}


text:
@implementation NSString(SURNSString)

-(NSString *)removeUnderlineInVariable
{
    NSArray *paraArray = [self componentsSeparatedByString:@"_"];
    NSMutableString *result = [[NSMutableString alloc] init];
    for (int i = 0; i < paraArray.count; i++)
    {
        NSString *str = paraArray[i];
        if (i == 0)
        {
            [result appendString:str];
        }else
        {
            [result appendString:str.capitalizedString];
        }
    }
    return result;
}

-(NSString *)firstCapitalLetter{

    char firstChar = [self characterAtIndex:0];

    NSString *firstStr = [NSString stringWithFormat:@"%c",firstChar];

    firstStr = firstStr.uppercaseString;

    NSMutableString *mutableStr = [[NSMutableString alloc] init];

    [mutableStr appendString:firstStr];
    [mutableStr appendString:[self substringFromIndex:1]];

    return [mutableStr copy];
}

-(NSString *)handleKeyWord
{
    char firstChar = [self characterAtIndex:0];

    NSString *firstStr = [NSString stringWithFormat:@"%c",firstChar];

    if ([firstStr isEqualToString:@"_"])
    {
        return [self substringFromIndex:1];
    }
    return self;
}

@end


text:
package org.hibernate.transaction;
import java.util.Properties;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;

import org.hibernate.HibernateException;

/**
 * Contract for locating the JTA {@link TransactionManager} on given platform.
 *

 * NOTE: this contract has expanded over time, and basically is a platform
 * abstraction contract for JTA-related information.
 *
 * @author Gavin King
 */
public interface TransactionManagerLookup {

	/**
	 * Obtain the JTA {@link TransactionManager}.
	 *
	 * @param props The configuration properties.
	 * @return The JTA {@link TransactionManager}.
	 *
	 * @throws HibernateException Indicates problem locating {@link TransactionManager}.
	 */
	public TransactionManager getTransactionManager(Properties props) throws HibernateException;

	/**
	 * Return the JNDI namespace of the JTA
	 * {@link javax.transaction.UserTransaction} for this platform or <tt>null</tt>;
	 * optional operation.
	 *
	 * @return The JNDI namespace where we can locate the
	 * {@link javax.transaction.UserTransaction} for this platform.
	 */
	public String getUserTransactionName();

	/**
	 * Determine an identifier for the given transaction appropriate for use in caching/lookup usages.
	 *

	 * Generally speaking the transaction itself will be returned here.  This method was added specifically
	 * for use in WebSphere and other unfriendly JEE containers (although WebSphere is still the only known
	 * such brain-dead, sales-driven impl).
	 *
	 * @param transaction The transaction to be identified.
	 * @return An appropropriate identifier
	 */
	public Object getTransactionIdentifier(Transaction transaction);
}


text:
{% extends "dialog.html" %}
{% load i18n %}

{% block page_header %}
    {% if object.upcoming_meeting_started %}
      {% trans "Summary draft" %}
    {% else %}
      {% trans "Publish" %}
    {% endif %}
{% endblock %}

{% block nofooter %}

	<button type="button" class="btn btn-info hidden-print pull-left" data-toggle="collapse" data-target="#protocolPreview">
		{% if object.upcoming_meeting_started %}
			{% if LANGUAGE_CODE == 'he' and community.no_meetings_community %}
            {% trans "Preview details" %}
            {% else %}
            {% trans "Preview protocol" %}
            {% endif %}
		{% else %}
			{% trans "Preview draft" %}
		{% endif %}
	</button>
    <button type="button" class="btn btn-default" data-dismiss="modal">{% trans "Close" %}</button>
    <input type="submit" class="btn btn-oc" value="{% trans "Publish" %}">

		<button type="button" class="btn btn-default hidden-print protocol-print-btn" onclick="printProtocol();">

			{% if object.upcoming_meeting_started %}
				{% if LANGUAGE_CODE == 'he' and community.no_meetings_community %}
                {% trans "Print details" %}
                {% else %}
                {% trans "Print protocol" %}
                {% endif %}
			{% else %}
				{% trans "Print draft" %}
			{% endif %}
		</button>

{% endblock %}

{% block page_scripts %}
{% if object.upcoming_meeting_started %}

{% else %}

{% endif %}
{% endblock %}


text:
// Copyright © 2011 - Present RealDimensions Software, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace chocolatey.infrastructure.app.configuration
{
    using System;
    using System.Collections.Generic;
    using System.Reflection;
    using System.Text;
    using domain;
    using logging;
    using platforms;

    /// <summary>
    ///   The chocolatey configuration.
    /// </summary>
    [Serializable]
    public class ChocolateyConfiguration
    {
        public ChocolateyConfiguration()
        {
            RegularOutput = true;
            PromptForConfirmation = true;
            Information = new InformationCommandConfiguration();
            Features = new FeaturesConfiguration();
            NewCommand = new NewCommandConfiguration();
            ListCommand = new ListCommandConfiguration();
            UpgradeCommand = new UpgradeCommandConfiguration();
            SourceCommand = new SourcesCommandConfiguration();
            FeatureCommand = new FeatureCommandConfiguration();
            ApiKeyCommand = new ApiKeyCommandConfiguration();
            PushCommand = new PushCommandConfiguration();
            PinCommand = new PinCommandConfiguration();
#if DEBUG
            AllowUnofficialBuild = true;
#endif
        }

        // overrides
        public override string ToString()
        {
            var properties = new StringBuilder();

            this.Log().Debug(ChocolateyLoggers.Important,@"
NOTE: Hiding sensitive configuration data! Please double and triple
 check to be sure no sensitive data is shown, especially if copying
 output to a gist for review.");
            output_tostring(properties, GetType().GetProperties(), this, "");
            return properties.ToString();

        }

        private void output_tostring(StringBuilder propertyValues, IEnumerable<PropertyInfo> properties, object obj, string prepend)
        {
            foreach (var propertyInfo in properties.or_empty_list_if_null())
            {
                // skip sensitive data info
                if (propertyInfo.Name == "Password" || propertyInfo.Name == "Key")
                {
                    continue;
                }

                var objectValue = propertyInfo.GetValue(obj, null);
                if (propertyInfo.PropertyType.is_built_in_system_type())
                {
                    if (!string.IsNullOrWhiteSpace(objectValue.to_string()))
                    {
                        var output = "{0}{1}='{2}'|".format_with(
                            string.IsNullOrWhiteSpace(prepend) ? "" : prepend + ".",
                            propertyInfo.Name,
                            objectValue.to_string());

                        append_output(propertyValues, output);
                    }
                }
                else if (propertyInfo.PropertyType.is_collections_type())
                {
                    var list = objectValue as IDictionary<string, string>;
                    foreach (var item in list.or_empty_list_if_null())
                    {
                        var output = "{0}{1}.{2}='{3}'|".format_with(
                            string.IsNullOrWhiteSpace(prepend) ? "" : prepend + ".",
                            propertyInfo.Name,
                            item.Key,
                            item.Value);

                        append_output(propertyValues, output);
                    }
                }
                else
                {
                    output_tostring(propertyValues, propertyInfo.PropertyType.GetProperties(), objectValue, propertyInfo.Name);
                }
            }
        }

        private const int MAX_CONSOLE_LINE_LENGTH = 72;
        private int _currentLineLength = 0;

        private void append_output(StringBuilder propertyValues, string append)
        {
            _currentLineLength += append.Length;

            propertyValues.AppendFormat("{0}{1}{2}",
                   _currentLineLength < MAX_CONSOLE_LINE_LENGTH ? string.Empty : Environment.NewLine,
                   append,
                   append.Length < MAX_CONSOLE_LINE_LENGTH ? string.Empty : Environment.NewLine);

            if (_currentLineLength > MAX_CONSOLE_LINE_LENGTH)
            {
                _currentLineLength = append.Length;
            }
        }

        /// <summary>
        ///   Gets or sets the name of the command.
        ///   This is the command that choco runs.
        /// </summary>
        /// <value>
        ///   The name of the command.
        /// </value>
        public string CommandName { get; set; }

        // configuration set variables
        public string CacheLocation { get; set; }
        public bool ContainsLegacyPackageInstalls { get; set; }
        public int CommandExecutionTimeoutSeconds { get; set; }

        /// <summary>
        ///   One or more source locations set by configuration or by command line. Separated by semi-colon
        /// </summary>
        public string Sources { get; set; }

        // top level commands

        public bool Debug { get; set; }
        public bool Verbose { get; set; }
        public bool Force { get; set; }
        public bool Noop { get; set; }
        public bool HelpRequested { get; set; }
        public bool RegularOutput { get; set; }
        public bool PromptForConfirmation { get; set; }
        public bool AcceptLicense { get; set; }
        public bool AllowUnofficialBuild { get; set; }

        /// <summary>
        ///   Usually related to unparsed arguments.
        /// </summary>
        public string Input { get; set; }

        // command level options
        public string Version { get; set; }
        public bool AllVersions { get; set; }
        public bool SkipPackageInstallProvider { get; set; }

        // install/update
        /// <summary>
        ///   Gets or sets the package names. Space separated
        /// </summary>
        /// <value>
        ///   Space separated package names.
        /// </value>
        public string PackageNames { get; set; }

        public bool Prerelease { get; set; }
        public bool ForceX86 { get; set; }
        public string InstallArguments { get; set; }
        public bool OverrideArguments { get; set; }
        public bool NotSilent { get; set; }
        public string PackageParameters { get; set; }
        public bool IgnoreDependencies { get; set; }
        public bool AllowMultipleVersions { get; set; }
        public bool ForceDependencies { get; set; }

        /// <summary>
        ///   Configuration values provided by choco.
        /// </summary>
        /// <remarks>
        ///   On .NET 4.0, get error CS0200 when private set - see http://stackoverflow.com/a/23809226/18475
        /// </remarks>
        public InformationCommandConfiguration Information { get;  set; }

        /// <summary>
        ///   Configuration related to features and whether they are enabled.
        /// </summary>
        /// <remarks>
        ///   On .NET 4.0, get error CS0200 when private set - see http://stackoverflow.com/a/23809226/18475
        /// </remarks>
        public FeaturesConfiguration Features { get;  set; }

        /// <summary>
        ///   Configuration related specifically to List command
        /// </summary>
        /// <remarks>
        ///   On .NET 4.0, get error CS0200 when private set - see http://stackoverflow.com/a/23809226/18475
        /// </remarks>
        public ListCommandConfiguration ListCommand { get;  set; }

        /// <summary>
        ///   Configuration related specifically to Upgrade command
        /// </summary>
        /// <remarks>
        ///   On .NET 4.0, get error CS0200 when private set - see http://stackoverflow.com/a/23809226/18475
        /// </remarks>
        public UpgradeCommandConfiguration UpgradeCommand { get;  set; }

        /// <summary>
        ///   Configuration related specifically to New command
        /// </summary>
        /// <remarks>
        ///   On .NET 4.0, get error CS0200 when private set - see http://stackoverflow.com/a/23809226/18475
        /// </remarks>
        public NewCommandConfiguration NewCommand { get;  set; }

        /// <summary>
        ///   Configuration related specifically to Source command
        /// </summary>
        /// <remarks>
        ///   On .NET 4.0, get error CS0200 when private set - see http://stackoverflow.com/a/23809226/18475
        /// </remarks>
        public SourcesCommandConfiguration SourceCommand { get;  set; }

        /// <summary>
        /// Configuration related specifically to the Feature command
        /// </summary>
        /// <remarks>
        ///   On .NET 4.0, get error CS0200 when private set - see http://stackoverflow.com/a/23809226/18475
        /// </remarks>
        public FeatureCommandConfiguration FeatureCommand { get;  set; }

        /// <summary>
        ///   Configuration related specifically to ApiKey command
        /// </summary>
        /// <remarks>
        ///   On .NET 4.0, get error CS0200 when private set - see http://stackoverflow.com/a/23809226/18475
        /// </remarks>
        public ApiKeyCommandConfiguration ApiKeyCommand { get;  set; }

        /// <summary>
        ///   Configuration related specifically to Push command
        /// </summary>
        /// <remarks>
        ///   On .NET 4.0, get error CS0200 when private set - see http://stackoverflow.com/a/23809226/18475
        /// </remarks>
        public PushCommandConfiguration PushCommand { get;  set; }

        /// <summary>
        /// Configuration related specifically to Pin command
        /// </summary>
        /// <remarks>
        ///   On .NET 4.0, get error CS0200 when private set - see http://stackoverflow.com/a/23809226/18475
        /// </remarks>
        public PinCommandConfiguration PinCommand { get;  set; }
    }

    [Serializable]
    public sealed class InformationCommandConfiguration
    {
        // application set variables
        public PlatformType PlatformType { get; set; }
        public Version PlatformVersion { get; set; }
        public string PlatformName { get; set; }
        public string ChocolateyVersion { get; set; }
        public string ChocolateyProductVersion { get; set; }
        public string FullName { get; set; }
        public bool Is64Bit { get; set; }
        public bool IsInteractive { get; set; }
        public bool IsUserAdministrator { get; set; }
        public bool IsProcessElevated { get; set; }

    }

    [Serializable]
    public sealed class FeaturesConfiguration
    {
        public bool AutoUninstaller { get; set; }
        public bool CheckSumFiles { get; set; }
    }

    //todo: retrofit other command configs this way

    [Serializable]
    public sealed class ListCommandConfiguration
    {
        // list
        public bool LocalOnly { get; set; }
        public bool IncludeRegistryPrograms { get; set; }
    }

    [Serializable]
    public sealed class UpgradeCommandConfiguration
    {
        public bool FailOnUnfound { get; set; }
    }

    [Serializable]
    public sealed class NewCommandConfiguration
    {
        public NewCommandConfiguration()
        {
            TemplateProperties = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
        }

        public string Name { get; set; }
        public bool AutomaticPackage { get; set; }
        public IDictionary<string, string> TemplateProperties { get; private set; }
    }

    [Serializable]
    public sealed class SourcesCommandConfiguration
    {
        public string Name { get; set; }
        public SourceCommandType Command { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
    }

    [Serializable]
    public sealed class FeatureCommandConfiguration
    {
        public string Name { get; set; }
        public FeatureCommandType Command { get; set; }
    }

    [Serializable]
    public sealed class PinCommandConfiguration
    {
        public string Name { get; set; }
        public PinCommandType Command { get; set; }
    }

    [Serializable]
    public sealed class ApiKeyCommandConfiguration
    {
        public string Key { get; set; }
    }

    [Serializable]
    public sealed class PushCommandConfiguration
    {
        public string Key { get; set; }
        public int TimeoutInSeconds { get; set; }
        //DisableBuffering?
    }
}


text:
module MemoryTracker
  class Request
    include Sys

    attr_reader :start_gcstat, :end_gcstat
    attr_reader :gcstat_delta
    attr_reader :rss, :vsize

    extend Forwardable
    def_delegators :@env, :path, :controller, :action

    def initialize(env)
      @env          = env
      @start_gcstat = GcStat.new(self.class.rss, self.class.vsize)
    end

    def close
      @end_gcstat   = GcStat.new(self.class.rss, self.class.vsize)
      @gcstat_delta = GcStatDelta.new(@start_gcstat, @end_gcstat)
      self
    end

    private

    def self.rss
      rss = ProcTable.ps(Process.pid).rss * 0.004096
    end

    def self.vsize
      vsize = ProcTable.ps(Process.pid).vsize * 0.000001
    end
  end
end


text:
package io.searchbox.core.search.aggregation;

import com.google.gson.JsonObject;

import java.util.Objects;

import static io.searchbox.core.search.aggregation.AggregationField.*;

/**
 * @author cfstout
 */
public class GeoBoundsAggregation extends MetricAggregation {

    public static final String TYPE = "geo_bounds";

    private Double topLeftLat;
    private Double topLeftLon;
    private Double bottomRightLat;
    private Double bottomRightLon;

    public GeoBoundsAggregation(String name, JsonObject geoBoundsAggregation) {
        super(name, geoBoundsAggregation);
        if (geoBoundsAggregation.has(String.valueOf(BOUNDS))) {
            JsonObject bounds = geoBoundsAggregation.getAsJsonObject(String.valueOf(BOUNDS));
            JsonObject topLeft = bounds.getAsJsonObject(String.valueOf(TOP_LEFT));
            JsonObject bottomRight = bounds.getAsJsonObject(String.valueOf(BOTTOM_RIGHT));

            topLeftLat = topLeft.get(String.valueOf(LAT)).getAsDouble();
            topLeftLon = topLeft.get(String.valueOf(LON)).getAsDouble();
            bottomRightLat = bottomRight.get(String.valueOf(LAT)).getAsDouble();
            bottomRightLon = bottomRight.get(String.valueOf(LON)).getAsDouble();
        }
    }

    /**
     * @return Top left latitude if bounds exist, null otherwise
     */
    public Double getTopLeftLat() {
        return topLeftLat;
    }

    /**
     * @return Top left longitude if bounds exist, null otherwise
     */
    public Double getTopLeftLon() {
        return topLeftLon;
    }

    /**
     * @return Bottom right latitude if bounds exist, null otherwise
     */
    public Double getBottomRightLat() {
        return bottomRightLat;
    }

    /**
     * @return Bottom right longitude if bounds exist, null otherwise
     */
    public Double getBottomRightLon() {
        return bottomRightLon;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj == this) {
            return true;
        }
        if (obj.getClass() != getClass()) {
            return false;
        }

        GeoBoundsAggregation rhs = (GeoBoundsAggregation) obj;
        return super.equals(obj)
                && Objects.equals(topLeftLat, rhs.topLeftLat)
                && Objects.equals(topLeftLon, rhs.topLeftLon)
                && Objects.equals(bottomRightLat, rhs.bottomRightLat)
                && Objects.equals(bottomRightLon, rhs.bottomRightLon);
    }

    @Override
    public int hashCode() {
        return Objects.hash(super.hashCode(),
                bottomRightLat,
                bottomRightLon,
                topLeftLat,
                topLeftLon);
    }
}


text:
package info.noname.moviehub;

import android.app.Application;
import android.content.ContextWrapper;

import com.orm.SugarContext;
import com.orm.SugarDb;

import java.io.File;

import info.noname.moviehub.models.Actor;
import info.noname.moviehub.models.Category;
import info.noname.moviehub.models.Movie;
import info.noname.moviehub.models.MovieActors;
import info.noname.moviehub.models.MovieCategories;
import info.noname.moviehub.models.MovieComments;
import info.noname.moviehub.models.User;
import info.noname.moviehub.models.UserListMovies;
import info.noname.moviehub.models.UserVotes;

/**
 * Created by AKamenov on 10/9/2016.
 */

public class MainApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        // Delete the database if exist
        if (doesDatabaseExist(this, "movie_hub.db")) {
            SugarDb sugarDb = new SugarDb(getApplicationContext());

            new File(sugarDb.getDB().getPath()).delete();
        }

        // Create and fill the database
        SugarContext.init(getApplicationContext());
        boolean doesDbExist = doesDatabaseExist(this, "movie_hub.db");
        if (!doesDbExist){

            Category.findById(Category.class, (long) 1);
            Movie.findById(Movie.class, (long) 1);

            initDb();
        }
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }

    private void initDb() {
        User user1 = new User("John", "7815696ecbf1c96e6894b779456d33e", "john@snow.bg", "http://cdn.tvweb.com/img.news.tops/NEaMHVFvWpoJeh_2_b.jpg");

        Category categoryAction = new Category("Action", "http://i279.photobucket.com/albums/kk143/pasqkpo/Chucknorris.png", "#997300");
        Category categoryDrama = new Category("Drama", "http://www.bamangharhs.edu.bd/images/staffs/drama-icon.png", "#0066cc");
        Category categoryComedy = new Category("Comedy", "https://moviefiednyc.files.wordpress.com/2013/11/e0006-ace-ventura-pet-detective-512c7fac5d838.png", "#2eb82e");

        Movie movie1 = new Movie("The Matrix", categoryAction, 1999, 136, "Thomas A. Anderson is a man living two lives. By day he is an average computer programmer and by night a hacker known as Neo. Neo has always questioned his reality, but the truth is far beyond his imagination. Neo finds himself targeted by the police when he is contacted by Morpheus, a legendary computer hacker branded a terrorist by the government. Morpheus awakens Neo to the real world, a ravaged wasteland where most of humanity have been captured by a race of machines that live off of the humans' body heat and electrochemical energy and who imprison their minds within an artificial reality known as the Matrix. As a rebel against the machines, Neo must return to the Matrix and confront the agents: super-powerful computer programs devoted to snuffing out Neo and the entire human rebellion.","http://www.impawards.com/1999/posters/matrix_ver1.jpg", "https://www.youtube.com/watch?v=Q8g9zL-JL8E");
        Movie movie2 = new Movie("American History X ", categoryDrama, 1998, 119, "Derek Vineyard is paroled after serving 3 years in prison for killing two thugs who tried to break into/steal his truck. Through his brother, Danny Vineyard's narration, we learn that before going to prison, Derek was a skinhead and the leader of a violent white supremacist gang that committed acts of racial crime throughout L.A. and his actions greatly influenced Danny. Reformed and fresh out of prison, Derek severs contact with the gang and becomes determined to keep Danny from going down the same violent path as he did.", "https://www.cinematerial.com/media/posters/md/zj/zjjeldsq.jpg", "https://www.youtube.com/watch?v=JsPW6Fj3BUI");
        Movie movie3 = new Movie("The God of Gamblers", categoryAction, 1989, 126, "The God of Gamblers is a legendary gambler helped by his supernatural abilities. He undertakes to help a friend pay a debt by beating his friend's advisory at the card table. Despite being assigned a bodyguard Do San has a freak accident which leaves him with partial memory loss and at a mental stage of a child. The small time hustler Knife, his side-kick and his girl friend, being responsible for the accident takes care of the retarded Do San. After some time they discover that he has not lost all of his powers and takes him on a round at the local gambling halls. After being chased by both Knife's loan-shark and enemies closer to the home of Do San, a final showdown at the card tables may take place.", "http://moviescounter.com/wp-content/uploads/2016/04/God-of-Gamblers.jpg", "https://www.youtube.com/watch?v=mibGBsWF4E0" );
        Movie movie4 = new Movie("Borat", categoryComedy, 2006, 86, "Borat Sagdiyev is a TV reporter of a popular show in Kazakhstan as Kazakhstan's sixth most famous man and a leading journalist. He is sent from his home to America by his government to make a documentary about American society and culture. Borat takes a course in New York City to understand American humor. While watching Baywatch on TV, Borat discovers how beautiful their women are in the form of C. J. Parker, who was played by actress Pamela Anderson who hails from Malibu, California. He decides to go on a cross-country road trip to California in a quest to make her his wife and take her back to his country. On his journey Borat and his producer encounter a country full of strange and wonderful Americans, real people in real chaotic situations with hysterical consequences.", "https://upload.wikimedia.org/wikipedia/en/3/39/Borat_ver2.jpg","https://www.youtube.com/watch?v=vlnUa_dNsRQ" );

        MovieComments comment1 = new MovieComments("I absolutely love this movie!", movie1, user1);
        MovieComments comment2 = new MovieComments("I absolutely love this movie, yeaahh!", movie2, user1);
        MovieComments comment3 = new MovieComments("love this movie it's awseome", movie4, user1);

        Actor kevinHart = new Actor("Keanu", "Reeves");

        MovieActors movieActors = new MovieActors(movie1, kevinHart);

        MovieCategories movieCategories1 = new MovieCategories(movie1, categoryAction);
        MovieCategories movieCategories2 = new MovieCategories(movie2, categoryDrama);
        MovieCategories movieCategories3 = new MovieCategories(movie3, categoryAction);
        MovieCategories movieCategories4 = new MovieCategories(movie4, categoryComedy);

        UserVotes userVotes = new UserVotes(movie1, user1, 1);

        UserListMovies userListMovies = new UserListMovies(movie1, user1);

        user1.save();
        categoryAction.save();
        categoryDrama.save();
        categoryComedy.save();
        movie1.save();
        movie2.save();
        movie3.save();
        movie4.save();
        comment1.save();
        comment2.save();
        comment3.save();
        kevinHart.save();
        movieActors.save();
        movieCategories1.save();
        movieCategories2.save();
        movieCategories3.save();
        movieCategories4.save();
        userVotes.save();
        userListMovies.save();
    }

    private boolean doesDatabaseExist(ContextWrapper context, String dbName) {
        File dbFile = context.getDatabasePath(dbName);

        return dbFile.exists();
    }
}


text:
from O365 import *

# User's credentials
e = 'email_address'
p = 'password'

# Create Schedule object, get calendars, and create empty dict
schedule = Schedule((e, p))
result = schedule.getCalendars()

# Funciton to invoke getName() and bind to var result
def cal_name():
    result = cal.getName() # This will get the name of a calendar
    return result

# Show name of each calendar
print('\nHere are your calendars:\n')
for cal in schedule.calendars:
    print(cal_name())

# Get events for each calendar
print('\nHere are all your upcoming events:\n')
for cal in schedule.calendars:
    result = cal_name()
    events = cal.getEvents() # This will create an Event object
    for x in cal.events:
        contents = x.getSubject() # This will get the subject
        date = x.getStart() # This will get the start time and we'll parse it below
        print('{}-{} | {} : {}'.format(date.tm_mon, date.tm_mday, result, contents))


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <title>OkHttp源码初探 — FSilence's Blog</title>
    <link rel="stylesheet" href="/assets/vendor/primer-css/css/primer.css">
    <link rel="stylesheet" href="/assets/vendor/primer-markdown/dist/user-content.min.css">
    <link rel="stylesheet" href="/assets/vendor/octicons/octicons/octicons.css">
    <link rel="stylesheet" href="/assets/css/components/collection.css">
    <link rel="stylesheet" href="/assets/css/components/repo-card.css">
    <link rel="stylesheet" href="/assets/css/sections/repo-list.css">
    <link rel="stylesheet" href="/assets/css/sections/mini-repo-list.css">
    <link rel="stylesheet" href="/assets/css/components/boxed-group.css">
    <link rel="stylesheet" href="/assets/css/globals/common.css">
    <link rel="stylesheet" href="/assets/vendor/share.js/dist/css/share.min.css">
    <link rel="stylesheet" href="/assets/css/globals/responsive.css">
    <link rel="stylesheet" href="/assets/css/posts/index.css">

    <link rel="canonical" href="http://localhost:4000/2017/06/13/okhttp-client-simple/">
    <link rel="alternate" type="application/atom+xml" title="FSilence's Blog" href="">
    <link rel="shortcut icon" href="/favicon.ico">

    <meta property="og:title" content="OkHttp源码初探">

    <meta name="keywords" content="java, okhttp, okhttpclient, call, realcall, asynccall">
    <meta name="og:keywords" content="java, okhttp, okhttpclient, call, realcall, asynccall">

    <meta name="description" content="在之前的文章我中我们介绍了OkHttp的基本使用方法并简单说明了源码下各个module的功能作用,从这篇开始我们将要开始分析okHttp的源码。">
    <meta name="og:description" content="在之前的文章我中我们介绍了OkHttp的基本使用方法并简单说明了源码下各个module的功能作用,从这篇开始我们将要开始分析okHttp的源码。">

    <meta property="og:url" content="http://localhost:4000/2017/06/13/okhttp-client-simple/">
    <meta property="og:site_name" content="FSilence's Blog">
    <meta property="og:type" content="article">
    <meta property="og:locale" content="zh_CN" />

    <meta property="article:published_time" content="2017-06-13">

 FSilence's Blog

            <button class="collapsed mobile-visible" type="button" onclick="toggleMenu();">

            </button>

                首页

                分类

                维基

                链接

                关于

OkHttp源码初探

             2017/06/13

            java

在之前的文章我中我们介绍了OkHttp的基本使用方法并简单说明了源码下各个module的功能作用,从这篇开始我们将要开始分析okHttp的源码。

首先,我们先来回忆一下OkHttp的使用过程:
1.创建一个OkHttpClient对象

2.创建一个Request对象

3.调用OkHttpClient的newCall方法创建request的Call实例

4.调用Call的execute 或 enqeue方法分别启动同步异步请求获取Response

上述我们涉及到几个概念OkHttpClient, Request, Call, Response 我们将分别来分析一下这些内容。

Request

一个Request是一次请求的抽象,我们先简单看下里面的参数:

  final HttpUrl url;
  final String method;
  final Headers headers;
  final @Nullable RequestBody body;
  final Object tag;

可以看到一个Request 基本包含一个请求的url 请求的方法, Headers 和 请求的body,还有一个tag。

关于Request的具体内容,我们会在后面的系列文章中来进行分析。

OkHttpClient

我们可以看到OkHttpClient基本上是和okHttp打交道的门户,我们先来看一下OkHttpClient的定义:

public class OkHttpClient implements Cloneable, Call.Factory, WebSocket.Factory

可以看到OkHttpClient实现了接口Call.Factory 和 WebSocket,Factory顾名思义,OkHttpClient将负责创建Call 和 WebSocket的实例,在这里我们先对WebSocket不做考虑,我们讲桌布分析Http的请求。

OkHttpClient使用了创建者模式,使用一个Builder对象来控制构建一个OkHttpClient所需的各项配置,我们来看一下Builder中的参数:

  final Dispatcher dispatcher;
  final @Nullable Proxy proxy;
  final List<Protocol> protocols;
  final List<ConnectionSpec> connectionSpecs;
  final List<Interceptor> interceptors;
  final List<Interceptor> networkInterceptors;
  final EventListener.Factory eventListenerFactory;
  final ProxySelector proxySelector;
  final CookieJar cookieJar;
  final @Nullable Cache cache;
  final @Nullable InternalCache internalCache;
  final SocketFactory socketFactory;
  final @Nullable SSLSocketFactory sslSocketFactory;
  final @Nullable CertificateChainCleaner certificateChainCleaner;
  final HostnameVerifier hostnameVerifier;
  final CertificatePinner certificatePinner;
  final Authenticator proxyAuthenticator;
  final Authenticator authenticator;
  final ConnectionPool connectionPool;
  final Dns dns;
  final boolean followSslRedirects;
  final boolean followRedirects;
  final boolean retryOnConnectionFailure;
  final int connectTimeout;
  final int readTimeout;
  final int writeTimeout;
  final int pingInterval;

除了一些Http的配置外,我们可以看到3个特殊的概念配置,分别是EventListener.Factory Dispatcher 和 Interceptor

我们先来看一下EventListener 至于Dispatcher 和 interceptor我们会在系列文章的后续部分看到详细的分析,其中Dispatcher是来管理分发请求任务的,Interceptor是拦截器。

abstract class EventListener {
  public static final EventListener NONE = new EventListener() {
  };

  static EventListener.Factory factory(final EventListener listener) {
    return new EventListener.Factory() {
      public EventListener create(Call call) {
        return listener;
      }
    };
  }

  public void fetchStart(Call call) {
  }

  public void dnsStart(Call call, String domainName) {
  }

  public void dnsEnd(Call call, String domainName, List<InetAddress> inetAddressList,
      Throwable throwable) {
  }

  public void connectStart(Call call, InetAddress address, int port) {
  }

  public void secureConnectStart(Call call) {
  }

  public void secureConnectEnd(Call call, Handshake handshake,
      Throwable throwable) {
  }

  public void connectEnd(Call call,  InetAddress address, int port, String protocol,
      Throwable throwable) {
  }

  public void requestHeadersStart(Call call) {
  }

  public void requestHeadersEnd(Call call, Throwable throwable) {
  }

  ...

  public interface Factory {
    EventListener create(Call call);

我们可以看到EventListener是对请求过程中各个步骤的事件监听.

Call

一次具体的请求, OkHttpClient通过newCall创建了call对象,通过call对象的execute 或 enqeue来发起请求

Response

网络返回的结果,我们将在后续文章中进行详细的解析。

现在我们已经了解了在okHttp启动中的几个概念 其中有入口 OkHttpClient, 请求的实例Request 请求的抽象Call 拦截器Interceptor 分发管理Call的Dispatcher http的返回响应 Response, 我们还阅读了OkHttpClient的源码, 在下一篇中我们将要详细分析Call的体系结构。

Search

    <input type="text" id="search_box" placeholder="Search">
    <button class="btn btn-default" id="site_search_do"></button>

<link rel="stylesheet" type="text/css" href="/assets/css/modules/sidebar-search.css">

Post Directory

                    © 2015
                    FSilence
                    TOP

                    TOP

                    首页

                    分类

                    维基

                    链接

                    关于

    <link rel="stylesheet" href="/assets/css/globals/prism.css">


text:
<!DOCTYPE html>

This test passes if the div below is a blue 100px square when the deviceScaleFactor is 1.
    It simply ensures that when both src and srcset are specified for the same DPR, srcset wins.


text:
namespace Slim {
    class Exception : public Poco::Exception {
    }
}
#endif


text:
layout: page
title: About
permalink: /about/
---

Free macOS Guides, Articles and Tutorials from the Apple experts.


text:
FROM centos:centos7
MAINTAINER Philip Vacca <phil.vacca@gmail.com>
LABEL vendor="LCC" \
  version="0.1" \
  description="The Loose Confederation of Chums presents: expiralink"

ENV ELWEB_HOME /var/elweb

RUN yum makecache \
 && yum install -y epel-release \
 && yum install -y nodejs npm \
 && yum clean all

RUN groupadd elweb \
 && useradd -m -d $ELWEB_HOME -g elweb elweb \
 && mkdir $ELWEB_HOME/bin \
 && mkdir $ELWEB_HOME/public \
 && mkdir $ELWEB_HOME/routes \
 && mkdir $ELWEB_HOME/views

COPY elweb/package.json $ELWEB_HOME/package.json
WORKDIR $ELWEB_HOME
RUN chown -P elweb:elweb $ELWEB_HOME \
 && npm install

COPY entrypoint.sh $ELWEB_HOME/entrypoint.sh
COPY elweb/app.js $ELWEB_HOME/app.js
COPY elweb/bin/www $ELWEB_HOME/bin/www

COPY elweb/public/* $ELWEB_HOME/public/
COPY elweb/routes/* $ELWEB_HOME/routes/
COPY elweb/views/* $ELWEB_HOME/views/

RUN chown -P elweb:elweb $ELWEB_HOME

EXPOSE 3000

ENTRYPOINT ["./entrypoint.sh"]

CMD ["start"]


text:
double findCorrelation(int U1, int U2, int NUM_MOVIES, int *matrixUI);
int* findBests(int NUM_USERS, int NUM_MOVIES, int NUM_BEST,
               int U1, int *matrixUI);


text:
TinyGame.Scene = function(game, width, height, parent_id, bg_color){
	this._Game = game;

	this.Canvas = null;
	this.Context = null;

	this.Width = width;
	this.Height = height;
	this.Parent = parent_id;
	this.bgColor = bg_color || 'white';
};
TinyGame.Scene.prototype._Boot = function(){
	this.Canvas = TinyGame.Canvas(this.Width, this.Height, this.Parent);
	this.Context = this.Canvas.getContext('2d');
};
TinyGame.Scene.prototype._Update = function(){
	//	Clears Scene, DUH DUMBSHIT READ IT
	this._ClearScene();

	//	Draw objects
	for(var i=0, len=this._Game.Objects._Objects.length; i<len; i++){
		var obj = this._Game.Objects._Objects[i];

	//	Check if object is off-canvas before drawing..
	// if(){ };

		obj._Draw(this.Context);
	}
};
TinyGame.Scene.prototype._ClearScene = function(){
	this.Context.fillStyle = this.bgColor;
	this.Context.fillRect(0, 0, this.Width, this.Height);
};

// Add method for sorting objects based on z_index for layering

//  Add a method for drawing the last state to a off-screen canvas when the state changes
//  	then redraw that last-state scene every draw while in the new state?
//  	Maybe an option when creating a new state?


text:
package Google::Ads::GoogleAds::V10::Resources::ThirdPartyAppAnalyticsLink;

use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseEntity);

use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;

sub new {
  my ($class, $args) = @_;
  my $self = {
    resourceName    => $args->{resourceName},
    shareableLinkId => $args->{shareableLinkId}};

  # Delete the unassigned fields in this object for a more concise JSON payload
  remove_unassigned_fields($self, $args);

  bless $self, $class;
  return $self;
}

1;


text:
from .. util import *

class ReportTestSettings:
	def __init__(self, imageDifferenceTolerance = 0.0):
		self.imageDifferenceTolerance = imageDifferenceTolerance

class ReportTest:
	def __init__(self, key, testfun, message):
		self.key = key
		self.testfun = testfun
		self.message = message

	def test(self, report):
		return self.testfun(report[self.key])

	def failures(self):
		return {self.key : [self.message]}

class ReportImageTest(ReportTest):
	def __init__(self, key, differenceTolerance = 0.0):
		self.key = key
		self.message = {}
		self.differenceTolerance = differenceTolerance

	def test(self, report):
		imgs = report[self.key]
		for img in imgs:
			tol = safeget(report, "config", "image_test", "differenceTolerance", img["image"], failure = self.differenceTolerance)
			tol = max(tol, self.differenceTolerance)

			if img['test_mode'] != img['ref_mode']:
				self.message[img['image']] = \
					("Image {image} has different modes, " +
					"Test: {test_mode} vs Reference:{ref_mode}").format(**img)
			elif img['test_size'] != img['ref_size']:
				self.message[img['image']] = \
					("Image {image} has different sizes, " +
					"Test: {test_size} vs Reference:{ref_size}").format(**img)
			elif img["difference"] > tol:
				self.message[img['image']] = \
					("Image {image} has difference greater then the allowd tolerance ({difference}% > {tol})  " +
					"difference, {different_pixels} different pixels, " +
					"largest difference {max_difference}").format(tol=tol, **img)

		return len(self.message) == 0

	def failures(self):
		return {self.key : self.message}

class ReportLogTest(ReportTest):
	def __init__(self):
		self.key = 'log'
		self.message = []

	def test(self, report):
		try:
			with open(toPath(report['outputdir'], report['log']), 'r') as f:
				lines = f.readlines()
				for line in lines:
					if "Error:" in line:
						self.message.append(line)
		except FileNotFoundError:
			self.message.append("Missing Log")

		return len(self.message) == 0

	def failures(self):
		return {"log" : self.message}

class ReportTestSuite:
	def __init__(self, settings = ReportTestSettings()):
		self.settings = settings
		self.tests = [
			ReportTest('returncode', lambda x : x == 0, "Non zero retuncode"),
			ReportTest('timeout', lambda x : x == False, "Inviwo ran out of time"),
			ReportTest('missing_refs', lambda x : len(x) == 0, "Missing refecence image"),
			ReportTest('missing_imgs', lambda x : len(x) == 0, "Missing test image"),
			ReportImageTest('image_tests', settings.imageDifferenceTolerance),
			ReportLogTest()
		]

	def checkReport(self, report):
		failures = {}
		successes = []
		for t in self.tests:
			if not t.test(report):
				failures.update(t.failures())
			else:
				successes.append(t.key)
		report['failures'] = failures
		report['successes'] = successes
		return report


text:
This Visual Studio .NET/C# project shows you how to use [Microsoft.VisualStudio.TestTools.UnitTesting](https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.aspx) tools for unit testing of PowerShell code.

You can write a simple [TestMethod](https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.testmethodattribute.aspx) like this that tests the addition of two numbers via PowerShell (rather advanced ...):

	[TestMethod]
	public void doAddNumbersReturns7()
	{
		var x = 3;
		var y = 4;
		var testResult = 7;

		PowerShell ps = PowerShell.Create();
		var results = ps.AddScript( String.Format("return {0} + {1}", x, y) )
			.Invoke();
		var result = results[0];
		Assert.AreEqual(testResult, Convert.ToInt32(result.ToString()));
	}

Here you `Assert` that the `testResult` (which is `7`) equals the actual return from PowerShell. As PowerShell returns its contents as `PSObject` you have to convert it to an `int` first.

The project is built with [log4net](http://logging.apache.org/log4net/) support (you need the assembly/DLL in the same directory as the UnitTest assembly or have it installed in the GAC). So you can direct the (test) output to any device you like (such as File, SYSLOG, etc). In addition the project contains a special `Run` methdo you can call directly from PowerShell to execute all tests (even without Visual Studio installed):

	Add-Type -Path $PWD\UnitTest01.dll
	$ut = New-Object biz.dfch.CS.PowerShellUnitTestSample.UnitTest1
	$ut.Run();

Running the tests will output its results like this:

	2015-04-02 02:42::50.703+02:00|biz.dfch.CS.PowerShellUnitTestSample:UnitTest1.Run: Running tests ...
	2015-04-02 02:42::50.500+02:00|Invoking 'doConvertRandomMultiVarFromBase64ReturnsTrue' ...
	2015-04-02 02:42::50.500+02:00|Invoking 'doConvertRandomMultiVarFromBase64ReturnsTrue' SUCCEEDED.
	2015-04-02 02:42::50.500+02:00|Invoking 'doWriteHostReturnsTrue' ...
	2015-04-02 02:42::50.500+02:00|biz.dfch.CS.PowerShellUnitTestSample:UnitTest1.doWriteHostReturnsTrue
	2015-04-02 02:42::50.578+02:00|Invoking 'doWriteHostReturnsTrue' SUCCEEDED.
	2015-04-02 02:42::50.578+02:00|Invoking 'doWriteHostThrowsCmdletInvocationException' ...
	2015-04-02 02:42::50.578+02:00|biz.dfch.CS.PowerShellUnitTestSample:UnitTest1.doWriteHostThrowsCmdletInvocationException
	2015-04-02 02:42::50.703+02:00|Invoking 'doWriteHostThrowsCmdletInvocationException' SUCCEEDED.
	2015-04-02 02:42::50.703+02:00|biz.dfch.CS.PowerShellUnitTestSample:UnitTest1.Run: Running tests COMPLETED.

If you want to run the tests with the original [MSTest](https://msdn.microsoft.com/en-us/library/jj155804.aspx) agent, you can download and install [Agents for Microsoft Visual Studio 2013](https://www.microsoft.com/en-us/download/confirmation.aspx?id=40750).

## Notes regarding the PowerShell Host in Visual Studio

There are some things to keep in mind when running PowerShell scripts or Cmdlets from a .NET/C# programme:

1. You have to import all modules manually before executing scripts.

2. You have no STDOUT, so functions like `Write-Host` will not work and throw an exception. You can workaround this by implementing a *fake* function for this like `ps.AddScript("function Write-Host {}")`

3. If you are reusing the same `System.Automation.PowerShell` object you have to `Clear()` the comannds before performing a subsequent `Invoke()` otherwise you will re-execute the previous commands again.

4. As written above, PowerShell returns its contents as `PSObject` so you have to make an explicit conversion before comparing a result via `Assert`.

5. The result is always returned as an array (even if only one item is returned, in which case you extract the actual result via `results[0]`)

6. Properties of an `PSObject` can be accessed via `Properties` which is a `PSMemberInfoCollection`. You extract actual properties via `Match(key)[0]` (with corresponding `Name` and `Value` properties).


text:
package lc.houserubber;

public class Solution {
    // it is actually a DP problem. Time complexity: O(n) Space complexity: O(n)
    public int rob(int[] nums) {

        // corner case
        if(nums == null || nums.length == 0) return 0;
        else if(nums.length == 1) return nums[0];

        // profit[i] stores the MAX profit we can earn when we
        // taken house 0...i into consideration
        int [] profit = new int[nums.length + 1];    // the extra slot will facilitate the DP process

        for(int i = 1; i < profit.length; i ++) {
            // for each house we have two choice: rob or not
            if(i == 1) profit[i] = nums[i - 1];    // for initial case. rob is always better than don't
            else {
                // need to take two scenarios into account
                profit[i] = Math.max(nums[i - 1] + profit[i - 2],    // the case you rob the i-th house
                        profit[i - 1]);   // the case you don't, thus the profit is equal to old profit
            }
        }

        // finally return profit[n], which is the max profit we can get
        return profit[nums.length];
    }

    public static void main(String [] args) {

        Solution sol = new Solution();

        int [] nums = {7, 8, 9, 11, 10, 6, 5};

        System.out.println("max profit: " + sol.rob(nums));
    }
}