text:
@implementation BRACellFill

- (instancetype)initWithForegroundColor:(BRANativeColor *)foregroundColor backgroundColor:(BRANativeColor *)backgroundColor andPatternType:(BRACellFillPatternType)patternType inStyles:(BRAStyles *)styles {
    NSDictionary *dictionaryRepresentation = @{
                                               @"patternFill": @{
                                                       @"_patternType": patternType,
                                                       @"bgColor": [styles openXmlAttributesWithColor:backgroundColor],
                                                       @"fgColor": [styles openXmlAttributesWithColor:foregroundColor]
                                                       }
                                               };

    if (self = [super initWithOpenXmlAttributes:dictionaryRepresentation inStyles:styles]) {
    }

    return self;
}

- (void)loadAttributes {
    NSDictionary *dictionaryRepresentation = [super dictionaryRepresentation];
    _patternType = [dictionaryRepresentation valueForKeyPath:@"patternFill._patternType"];

    if ([_patternType isEqual:kBRACellFillPatternTypeNone]) {
        _backgroundColor = [BRANativeColor clearColor];
        _foregroundColor = [BRANativeColor clearColor];
    } else {
        _backgroundColor = [_styles colorWithOpenXmlAttributes:[dictionaryRepresentation valueForKeyPath:@"patternFill.bgColor"]];
        _foregroundColor = [_styles colorWithOpenXmlAttributes:[dictionaryRepresentation valueForKeyPath:@"patternFill.fgColor"]];
    }
}

- (NSDictionary *)dictionaryRepresentation {
    NSMutableDictionary *dictionaryRepresentation = [super dictionaryRepresentation].mutableDeepCopy;

    [dictionaryRepresentation setValue:_patternType forKeyPath:@"patternFill._patternType"];
    [dictionaryRepresentation setValue:[_styles openXmlAttributesWithColor:_backgroundColor] forKeyPath:@"patternFill.bgColor"];
    [dictionaryRepresentation setValue:[_styles openXmlAttributesWithColor:_foregroundColor] forKeyPath:@"patternFill.fgColor"];

    [super setDictionaryRepresentation:dictionaryRepresentation];

    return dictionaryRepresentation;
}

#pragma mark - Pattern

- (BRANativeColor *)patternedColor {
    if ([_patternType isEqual:kBRACellFillPatternTypeNone]) {
        return [BRANativeColor clearColor];
    } else if ([_patternType isEqual:kBRACellFillPatternTypeSolid]) {
        return [self _solidPatternedColor];
    } else if ([_patternType isEqual:kBRACellFillPatternTypeDarkGray]) {
        return [self _darkGrayPatternedColor];
    } else if ([_patternType isEqual:kBRACellFillPatternTypeMediumGray]) {
        return [self _mediumGrayPatternedColor];
    } else if ([_patternType isEqual:kBRACellFillPatternTypeLightGray]) {
        return [self _lightGrayPatternedColor];
    } else if ([_patternType isEqual:kBRACellFillPatternTypeGray125]) {
        return [self _gray125PatternedColor];
    } else if ([_patternType isEqual:kBRACellFillPatternTypeGray0625]) {
        return [self _gray0625PatternedColor];
    } else if ([_patternType isEqual:kBRACellFillPatternTypeDarkHorizontal]) {
        return [self _darkHorizontalPatternedColor];
    } else if ([_patternType isEqual:kBRACellFillPatternTypeDarkVertical]) {
        return [self _darkVerticalPatternedColor];
    } else if ([_patternType isEqual:kBRACellFillPatternTypeDarkDown]) {
        return [self _darkDownPatternedColor];
    } else if ([_patternType isEqual:kBRACellFillPatternTypeDarkUp]) {
        return [self _darkUpPatternedColor];
    } else if ([_patternType isEqual:kBRACellFillPatternTypeDarkGrid]) {
        return [self _darkGridPatternedColor];
    } else if ([_patternType isEqual:kBRACellFillPatternTypeDarkTrellis]) {
        return [self _darkTrellisPatternedColor];
    } else if ([_patternType isEqual:kBRACellFillPatternTypeLightHorizontal]) {
        return [self _lightHorizontalPatternedColor];
    } else if ([_patternType isEqual:kBRACellFillPatternTypeLightVertical]) {
        return [self _lightVerticalPatternedColor];
    } else if ([_patternType isEqual:kBRACellFillPatternTypeLightDown]) {
        return [self _lightDownPatternedColor];
    } else if ([_patternType isEqual:kBRACellFillPatternTypeLightUp]) {
        return [self _lightUpPatternedColor];
    } else if ([_patternType isEqual:kBRACellFillPatternTypeLightGrid]) {
        return [self _lightGridPatternedColor];
    } else if ([_patternType isEqual:kBRACellFillPatternTypeLightTrellis]) {
        return [self _lightTrellisPatternedColor];
    }

    return nil;
}

#pragma mark - Patterned color makers

- (BRANativeColor *)_solidPatternedColor {
    return _foregroundColor ? _foregroundColor : [BRANativeColor clearColor];
}

- (BRANativeColor *)_darkGrayPatternedColor {
    return [self __grayPatternedColorWithGrayLevel:.75];
}

- (BRANativeColor *)_mediumGrayPatternedColor {
    return [self __grayPatternedColorWithGrayLevel:.5];
}

- (BRANativeColor *)_lightGrayPatternedColor {
    return [self __grayPatternedColorWithGrayLevel:.25];
}

- (BRANativeColor *)_gray125PatternedColor {
    return [self __grayPatternedColorWithGrayLevel:.125];
}

- (BRANativeColor *)_gray0625PatternedColor {
    return [self __grayPatternedColorWithGrayLevel:.0625];
}

- (BRANativeColor *)nativeColorWithSize:(CGSize)drawingSize drawingOperations:(void (^)(CGContextRef context))drawingOps {
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL, drawingSize.width, drawingSize.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);

    drawingOps(context);

    BRANativeImage *patternImage = BRANativeGraphicsGetImageFromContext(context);

    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);

    return [BRANativeColor colorWithPatternImage:patternImage];
}

- (BRANativeColor *)_darkHorizontalPatternedColor {

   return [self nativeColorWithSize:CGSizeMake(4, 4) drawingOperations:^(CGContextRef context){
     CGContextSetFillColorWithColor(context, _foregroundColor.CGColor);
     CGContextFillRect(context, CGRectMake(0., 0., 4., 4.));

     CGContextSetFillColorWithColor(context, _backgroundColor.CGColor);
     CGContextFillRect(context, CGRectMake(0., 0., 4., 2.));
   }];
}

- (BRANativeColor *)_darkVerticalPatternedColor {

  return [self nativeColorWithSize:CGSizeMake(4, 4) drawingOperations:^(CGContextRef context){
      CGContextSetFillColorWithColor(context, _foregroundColor.CGColor);
      CGContextFillRect(context, CGRectMake(0., 0., 4., 4.));

      CGContextSetFillColorWithColor(context, _backgroundColor.CGColor);
      CGContextFillRect(context, CGRectMake(0., 0., 2., 4.));
    }];
}

- (BRANativeColor *)_darkDownPatternedColor {

  return [self nativeColorWithSize:CGSizeMake(6, 6) drawingOperations:^(CGContextRef context){
    CGContextSetFillColorWithColor(context, _foregroundColor.CGColor);
    CGContextFillRect(context, CGRectMake(0., 0., 6., 6.));

    CGContextSetStrokeColorWithColor(context, _backgroundColor.CGColor);
    CGContextSetLineWidth(context, 2.);
    CGContextMoveToPoint(context, -2., -1.);
    CGContextAddLineToPoint(context, 6., 7.);
    CGContextMoveToPoint(context, 4., -1.);
    CGContextAddLineToPoint(context, 7., 2.);
    CGContextMoveToPoint(context, -2., 5.);
    CGContextAddLineToPoint(context, 0., 7.);
    CGContextStrokePath(context);
  }];
}

- (BRANativeColor *)_darkUpPatternedColor {

  return [self nativeColorWithSize:CGSizeMake(6, 6) drawingOperations:^(CGContextRef context){
    CGContextSetFillColorWithColor(context, _foregroundColor.CGColor);
    CGContextFillRect(context, CGRectMake(0., 0., 6., 6.));

    CGContextSetStrokeColorWithColor(context, _backgroundColor.CGColor);
    CGContextSetLineWidth(context, 2.);
    CGContextMoveToPoint(context, 6., -2.);
    CGContextAddLineToPoint(context, -2., 6.);
    CGContextMoveToPoint(context, 7., 3.);
    CGContextAddLineToPoint(context, 3., 7.);
    CGContextMoveToPoint(context, -2., 0.);
    CGContextAddLineToPoint(context, 0., -2.);
    CGContextStrokePath(context);
  }];
}

- (BRANativeColor *)_darkGridPatternedColor {
  return [self nativeColorWithSize:CGSizeMake(4, 4) drawingOperations:^(CGContextRef context){
    CGContextSetFillColorWithColor(context, _foregroundColor.CGColor);
    CGContextFillRect(context, CGRectMake(0., 0., 4., 4.));

    CGContextSetFillColorWithColor(context, _backgroundColor.CGColor);
    CGContextFillRect(context, CGRectMake(0., 0., 2., 2.));
    CGContextFillRect(context, CGRectMake(2., 2., 2., 2.));
  }];
}

- (BRANativeColor *)_darkTrellisPatternedColor {
  return [self nativeColorWithSize:CGSizeMake(6, 6) drawingOperations:^(CGContextRef context){
    CGContextSetFillColorWithColor(context, _foregroundColor.CGColor);
    CGContextFillRect(context, CGRectMake(0., 0., 6., 6.));

    CGContextSetStrokeColorWithColor(context, _backgroundColor.CGColor);
    CGContextSetLineWidth(context, 2.);
    CGContextMoveToPoint(context, 6., -2.);
    CGContextAddLineToPoint(context, -2., 6.);
    CGContextMoveToPoint(context, 7., 3.);
    CGContextAddLineToPoint(context, 3., 7.);
    CGContextMoveToPoint(context, -2., 0.);
    CGContextAddLineToPoint(context, 0., -2.);

    CGContextMoveToPoint(context, -2., -1.);
    CGContextAddLineToPoint(context, 6., 7.);
    CGContextMoveToPoint(context, 4., -1.);
    CGContextAddLineToPoint(context, 7., 2.);
    CGContextMoveToPoint(context, -2., 5.);
    CGContextAddLineToPoint(context, 0., 7.);

    CGContextStrokePath(context);
  }];
}

- (BRANativeColor *)_lightHorizontalPatternedColor {
  return [self nativeColorWithSize:CGSizeMake(4, 4) drawingOperations:^(CGContextRef context){
    CGContextSetFillColorWithColor(context, _foregroundColor.CGColor);
    CGContextFillRect(context, CGRectMake(0., 0., 4., 4.));

    CGContextSetFillColorWithColor(context, _backgroundColor.CGColor);
    CGContextFillRect(context, CGRectMake(0., 0., 4., 1.));
  }];
}

- (BRANativeColor *)_lightVerticalPatternedColor {

  return [self nativeColorWithSize:CGSizeMake(4, 4) drawingOperations:^(CGContextRef context){
    CGContextSetFillColorWithColor(context, _foregroundColor.CGColor);
    CGContextFillRect(context, CGRectMake(0., 0., 4., 4.));

    CGContextSetFillColorWithColor(context, _backgroundColor.CGColor);
    CGContextFillRect(context, CGRectMake(0., 0., 1., 4.));
  }];
}

- (BRANativeColor *)_lightDownPatternedColor {

  return [self nativeColorWithSize:CGSizeMake(6, 6) drawingOperations:^(CGContextRef context){
    CGContextSetFillColorWithColor(context, _foregroundColor.CGColor);
    CGContextFillRect(context, CGRectMake(0., 0., 6., 6.));

    CGContextSetStrokeColorWithColor(context, _backgroundColor.CGColor);
    CGContextSetLineWidth(context, 1.);
    CGContextMoveToPoint(context, -2., -1.);
    CGContextAddLineToPoint(context, 6., 7.);
    CGContextMoveToPoint(context, 4., -1.);
    CGContextAddLineToPoint(context, 7., 2.);
    CGContextMoveToPoint(context, -2., 5.);
    CGContextAddLineToPoint(context, 0., 7.);
    CGContextStrokePath(context);
  }];
}

- (BRANativeColor *)_lightUpPatternedColor {
  return [self nativeColorWithSize:CGSizeMake(6, 6) drawingOperations:^(CGContextRef context){
    CGContextSetFillColorWithColor(context, _foregroundColor.CGColor);
    CGContextFillRect(context, CGRectMake(0., 0., 6., 6.));

    CGContextSetStrokeColorWithColor(context, _backgroundColor.CGColor);
    CGContextSetLineWidth(context, 1.);
    CGContextMoveToPoint(context, 6., -2.);
    CGContextAddLineToPoint(context, -2., 6.);
    CGContextMoveToPoint(context, 7., 3.);
    CGContextAddLineToPoint(context, 3., 7.);
    CGContextMoveToPoint(context, -2., 0.);
    CGContextAddLineToPoint(context, 0., -2.);
    CGContextStrokePath(context);
  }];
}

- (BRANativeColor *)_lightGridPatternedColor {
  return [self nativeColorWithSize:CGSizeMake(4, 4) drawingOperations:^(CGContextRef context){
    CGContextSetFillColorWithColor(context, _foregroundColor.CGColor);
    CGContextFillRect(context, CGRectMake(0., 0., 4., 4.));

    CGContextSetFillColorWithColor(context, _backgroundColor.CGColor);
    CGContextFillRect(context, CGRectMake(0., 0., 1., 4.));
    CGContextFillRect(context, CGRectMake(0., 3., 4., 1.));
  }];
}

- (BRANativeColor *)_lightTrellisPatternedColor {
  return [self nativeColorWithSize:CGSizeMake(6, 6) drawingOperations:^(CGContextRef context){
    CGContextSetFillColorWithColor(context, _foregroundColor.CGColor);
    CGContextFillRect(context, CGRectMake(0., 0., 6., 6.));

    CGContextSetStrokeColorWithColor(context, _backgroundColor.CGColor);
    CGContextSetLineWidth(context, 1.);
    CGContextMoveToPoint(context, 6., -2.);
    CGContextAddLineToPoint(context, -2., 6.);
    CGContextMoveToPoint(context, 7., 3.);
    CGContextAddLineToPoint(context, 3., 7.);
    CGContextMoveToPoint(context, -2., 0.);
    CGContextAddLineToPoint(context, 0., -2.);

    CGContextMoveToPoint(context, -2., -1.);
    CGContextAddLineToPoint(context, 6., 7.);
    CGContextMoveToPoint(context, 4., -1.);
    CGContextAddLineToPoint(context, 7., 2.);
    CGContextMoveToPoint(context, -2., 5.);
    CGContextAddLineToPoint(context, 0., 7.);

    CGContextStrokePath(context);
  }];
}

- (BRANativeColor *)__grayPatternedColorWithGrayLevel:(CGFloat)grayLevel {
  return [self nativeColorWithSize:CGSizeMake(4, 2) drawingOperations:^(CGContextRef context){
    CGRect patternBounds = CGRectMake(0., 0., 4., 2.);
    CGContextSetFillColorWithColor(context, _foregroundColor.CGColor);
    CGContextFillRect(context, patternBounds);

    CGContextSetFillColorWithColor(context, [_backgroundColor colorWithAlphaComponent:grayLevel].CGColor);
    CGContextFillRect(context, patternBounds);
  }];
}

@end


text:
#include "base/polygraph.h"

#include "base/polyLogCats.h"
#include "client/Client.h"
#include "kerberos/Mgr.h"
#include "kerberos/Xact.h"
#include "runtime/ErrorMgr.h"
#include "runtime/LogComment.h"
#include "runtime/globals.h"
#include "runtime/polyErrors.h"

namespace Kerberos {

// Whether all KDCs are believed to support persistent TCP connections.
// TODO: Make KDC-specific?
static bool UsePconnsWithKdc = true;

Xact::Xact() {
	theIn = new IOBuf();
	theOut = new IOBuf();
	theLastRequest = new IOBuf();
	reset();
}

Xact::~Xact() {
	closeSocket(); // we may be called w/o reset() when ObjFarm::put overflows
	delete theIn;
	delete theOut;
	delete theLastRequest;
}

void Xact::reset() {
	theOwner = 0;
	closeSocket();
	theIn->reset();
	theOut->reset();
	theLastRequest->reset();
	theTryCount = 0;
	sessionId = 0;
	doRetry = false;
	usingTcp = false;
	usingPconn = false;
}

bool Xact::configure(Mgr &anOwner) {
	Must(!theOwner);
	theOwner = &anOwner;
	usingTcp = anOwner.usingTcp;
	sessionId = anOwner.sessionId;
	return true;
}

void Xact::finish(const bool isSuccessful) {
	if (theSock)
		closeSocket();
	if (!doRetry)
		theLastRequest->reset();
	theOut->reset();
	theIn->reset();
}

void Xact::exec(const NetAddr &aKdcAddr) {
	++theTryCount;
	doRetry = false;

	theKdcAddr = aKdcAddr;
	Must(theKdcAddr);

	ShouldUs(!theSock);
	ShouldUs(theOut->empty());
	if (!theLastRequest->empty())
		theOut->append(theLastRequest->content(), theLastRequest->contSize());

	doStep();
}

void Xact::noteReadReady(int fd) {
	Must(fd == theSock.fd());
	Must(theIn->spaceSize() > 0); // to make sure our eof detection works
	const Size sz = theSock.read(theIn->space(), theIn->spaceSize());
	if (sz < 0) {
		const ::Error lastErr = ::Error::Last();
		if (lastErr != EWOULDBLOCK && lastErr != EAGAIN)
			reportErrorAndFinish("reading KDC response", lastErr);
		return;
	}

	if (sz == 0) {
		if (!usingTcp) {
			reportErrorAndFinish("reading KDC/UDP response", errKerberosKdcEof);
			return;
		}

		if (!usingPconn) {
			reportErrorAndFinish("reading KDC/TCP response", errKerberosKdcEof);
			return;
		}

		// We may be dealing with a KDC that does not support more than one
		// message per TCP connection. Remember that and reconnect the socket.
		UsePconnsWithKdc = false;
		closeSocket();
		theOut->reset();
		Must(theLastRequest->contSize() > 0); // we must have kept the request
		theOut->append(theLastRequest->content(), theLastRequest->contSize());
		doStep();
		return;
	}

	theIn->appended(sz);

	if (usingTcp) {
		/* extract message length prefix */
		uint32_t rawLength = 0;
		const int32_t pfxSize = sizeof(rawLength);
		if (theIn->contSize() < pfxSize)
			return;
		memcpy(&rawLength, theIn->content(), sizeof(rawLength));
		const uint32_t length = ntohl(rawLength);
		if (length > numeric_limits<int32_t>::max() - uint32_t(pfxSize)) {
			reportErrorAndFinish(errKerberosTcpPfx);
			return;
		}
		const int inSize = pfxSize + length;
		if (inSize > theIn->capacity()) {
			const int spaceSize = theIn->spaceSize();
			IOBuf *in = new IOBuf(inSize);
			in->append(theIn->content(), theIn->contSize());
			delete theIn;
			theIn = in;
			if (spaceSize == 0)
				noteReadReady(fd);
		}

		if (theIn->contSize() < static_cast<int32_t>(inSize))
			return; // did not get the entire message;

		theIn->consumed(pfxSize);
	}

	theOut->reset();
	theLastRequest->reset();

	if (usingTcp) {
		if (UsePconnsWithKdc)
			usingPconn = true;
		else
			closeSocket(); // will reconnect when needed
	}

	doStep();
}

void Xact::noteWriteReady(int fd) {
	Must(fd == theSock.fd());
	Must(!theOut->empty());

	const Size sz = theSock.write(theOut->content(), theOut->contSize());
	if (sz < 0) {
		reportErrorAndFinish("writing KDC request", ::Error::Last());
		return;
	}

	theOut->consumed(sz);
	if (theOut->empty())
		startIO(dirRead);
	else
	if (!usingTcp)
		finishAndRetry(); // UDP truncated our request
}

void Xact::noteTimeout(int fd, Time tout) {
	Must(fd == theSock.fd());
	reportErrorAndFinish(errKerberosKdcTimeout);
}

const Client &Xact::client() const {
	return owner().owner();
}

int Xact::logCat() const {
	return client().logCat();
}

bool Xact::openSocket() {
	const InAddress &addr = client().host().addrN();
	Must(addr.known());
	if (ShouldSys(theSock.create(addr.family(), (usingTcp ? SOCK_STREAM : SOCK_DGRAM), 0)) &&
		ShouldSys(theSock.blocking(false)) &&
		ShouldSys(theSock.reuseAddr(true)) &&
		ShouldSys(theSock.bind(NetAddr(addr, 0)))) {
		if (!theSock.connect(theKdcAddr)) {
			reportErrorAndFinish(usingTcp ? "connecting to KDC over TCP" :
				"connecting to KDC over UDP", ::Error::Last());
			return false;
		}
		return true;
	}

	reportError(usingTcp ? "opening TCP socket to KDC" : "opening UDP socket to KDC");
	return false;
}

bool Xact::reOpenSocket(ErrorCode e) {
	Must(!usingTcp);
	NetAddr *adrr = theOwner->switchToTcp();
	if (!adrr) {
		reportError("KDC-over-TCP server is needed but none are configured", e);
		finish(); // nothing is going to change if we retry
		return false;
	}

	closeSocket();
	theIn->reset();
	theOut->reset();
	theLastRequest->reset();

	theTryCount = 1;
	theKdcAddr = *adrr;
	usingTcp = true;

	return true;
}

void Xact::closeSocket() {
	if (theReserv)
		TheFileScanner->clearRes(theReserv);
	if (theSock)
		Should(theSock.close());
	usingPconn = false;
}

void Xact::startIO(const IODir dir) {
	if (theReserv)
		TheFileScanner->clearRes(theReserv);
	theReserv = TheFileScanner->setFD(theSock.fd(), dir, this);
	if (dir == dirRead)
		TheFileScanner->setTimeout(theSock.fd(), owner().timeout());
}

void Xact::reportError(const ::Error polyErr, const char *action, const ErrorCode krbErr) const {
	if (ReportError(polyErr)) {
		Comment << "error context: " << description() << " for " << owner().name();
		if (theKdcAddr)
			Comment << " from KDC " << theKdcAddr;

		if (action)
			Comment << endl << "failed action: " << action;
		if (krbErr)
			Comment << endl << "Kerberos details: " << Error(owner().context(), krbErr);

		if (tryCount())
			Comment << endl << "attemtps: " << tryCount();
		Comment << endc;
	}
}

void Xact::reportError(const char *action, const ErrorCode krbErr) const {
	reportError(polyError(), action, krbErr);
}

void Xact::doStep() {
	Data in(const_cast<char *>(theIn->content()), theIn->contSize());
	Data out;
	ErrorCode e = 0;
	if (!theOut->empty()) {
		// We get here after TCP pconn races and, via exec(), on retries.
		// We need to open a new socket and resend the same message.
	} else if ((e = step(in, out))) {
		if (e != KRB5KRB_ERR_RESPONSE_TOO_BIG || usingTcp) {
			finish(); // no retries on final Kerberos errors
			return;
		}
	}

	theIn->consumedAll();

	if (e == KRB5KRB_ERR_RESPONSE_TOO_BIG) {
		Comment(8) << "fyi: KDC response too big for UDP, retrying using TCP" << endc;
		if (!reOpenSocket(e))
			return;
	}

	if (!out.empty()) {
		const uint32_t rawLength = htonl(out.length());
		const uint32_t pfxSize = sizeof(rawLength);
		if (usingTcp)
			outAppend(theOut, reinterpret_cast<const char *> (&rawLength), pfxSize);
		outAppend(theOut, out.data(), out.length());
		// copy the last request message so that we can resend it
		outAppend(theLastRequest, theOut->content(), theOut->contSize());
	}

	if (theOut->empty())
		finish(true);
	else if (theSock || openSocket())
		startIO(dirWrite);
	else
		finishAndRetry(); // socket opening failure
}

void Xact::reportErrorAndFinish(const ::Error polyErr) {
	ReportError(polyErr);
	finishAndRetry();
}

void Xact::reportErrorAndFinish(const char *context, const ::Error sysErr) {
	reportError(sysErr, context);
	finishAndRetry();
}

void Xact::outAppend(IOBuf* &out ,const char* buf, Size sz) {
	if (out->spaceSize() < sz) {
		IOBuf *newOut = new IOBuf(sz + out->contSize());
		if (!out->empty())
			newOut->append(out->content(), out->contSize());
		delete out;
		out = newOut;
	}
	out->append(buf, sz);
}

}; // namespace Kerberos

redpajama_set_name: RedPajamaGithub


text: Tools for .h3c files - the HoMM3 Campaign file format


text:
import warnings
from functools import partial
from itertools import chain
from abc import ABCMeta, abstractmethod

from . import templates
from .ast import Constructor
from .parser import Includes, TypeInfo
from .defaultconfig import Config
from .template_specialization import (ClassSpecializer, FunctionSpecializer,
                                      MethodSpecializer)
from .templates import render
from .type_conversion import create_type_converter
from .utils import from_camel_case, replace_keyword_argnames

class AstExporter(object):
    """Base class of AST exporters.

    An AST exporter converts elements of an AST to a single string. This
    is an implementation of the visitor pattern to avoid duplication in the
    code that walks through the AST.
    """
    __metaclass__ = ABCMeta
    def __init__(self):
        self.typedefs = []
        self.enums = []
        self.functions = []
        self.classes = []
        self.arguments = []
        self._clear_class()

        self.output = None

    def _clear_class(self):
        """Set collected class members to empty list."""
        self.fields = []
        self.ctors = []
        self.methods = []

    def export(self):
        """Export generated string.

        Returns
        -------
        output : str
            Generated output
        """
        return self.output

    @abstractmethod
    def visit_ast(self, ast):
        """Visit AST.

        Parameters
        ----------
        ast : AST
            Abstract syntax tree
        """

    @abstractmethod
    def visit_enum(self, enum):
        """Visit enum.

        Parameters
        ----------
        enum : Enum
            Enumeration
        """

    @abstractmethod
    def visit_typedef(self, typedef):
        """Visit typedef.

        Parameters
        ----------
        typedef : Typedef
            Type definition
        """

    @abstractmethod
    def visit_clazz(self, clazz):
        """Visit class.

        Parameters
        ----------
        clazz : Clazz
            Custom class
        """

    @abstractmethod
    def visit_field(self, field):
        """Visit field.

        Parameters
        ----------
        field : Field
            Field, data member of a class
        """

    @abstractmethod
    def visit_constructor(self, ctor):
        """Visit constructor.

        Parameters
        ----------
        ctor : Constructor
            Class constructor
        """

    @abstractmethod
    def visit_template_class(self, template_class):
        """Visit template class.

        Parameters
        ----------
        template_class : TemplateClass
            Template class
        """

    @abstractmethod
    def visit_method(self, method):
        """Visit method.

        Parameters
        ----------
        method : Method
            Visit class method
        """

    @abstractmethod
    def visit_template_method(self, template_method):
        """Visit template method.

        Parameters
        ----------
        template_method : TemplateMethod
            Template method that defines its own template type(s)
        """

    @abstractmethod
    def visit_function(self, function):
        """Visit function.

        Parameters
        ----------
        function : Function
            Function that does not belong to a class
        """

    @abstractmethod
    def visit_template_function(self, template_function):
        """Visit template function.

        Parameters
        ----------
        template_function : TemplateFunction
            Template function
        """

    @abstractmethod
    def visit_param(self, param):
        """Visit function parameter.

        Parameters
        ----------
        param : Param
            A parameter of a constructor, method, or function
        """

class CythonDeclarationExporter(AstExporter):
    """Export to Cython declaration file (.pxd).

    Parameters
    ----------
    includes : Includes, optional
        Collects information about required import statements from the exporter

    config : Config, optional
        Configuration that controls e.g. template specializations
    """
    def __init__(self, includes=Includes(), config=Config()):
        super(CythonDeclarationExporter, self).__init__()
        self.includes = includes
        self.config = config

    def visit_ast(self, ast):
        self.output = render("declarations", typedefs=self.typedefs,
                             enums=self.enums, functions=self.functions,
                             classes=self.classes)

    def visit_enum(self, enum):
        self.enums.append(render("enum_decl", enum=enum))

    def visit_typedef(self, typedef):
        self.typedefs.append(templates.typedef_decl % typedef.__dict__)

    def visit_clazz(self, clazz):
        self._visit_class(clazz)

    def visit_template_class(self, template_class):
        name = "%s[%s]" % (template_class.name,
                           ", ".join(template_class.template_types))
        self._visit_class(template_class, {"name": name})

    def _visit_class(self, clazz, additional_args=None):
        if not clazz.ignored:
            class_decl = {}
            class_decl.update(clazz.__dict__)
            if additional_args is not None:
                class_decl.update(additional_args)
            class_decl["fields"] = self.fields
            class_decl["ctors"] = self.ctors
            class_decl["methods"] = self.methods
            class_decl["empty_body"] = (len(self.fields) + len(self.methods) +
                                        len(self.ctors) == 0)

            self.classes.append(render("class_decl", **class_decl))
        self._clear_class()

    def visit_field(self, field):
        if not field.ignored:
            self.fields.append(templates.field_decl % field.__dict__)

    def visit_constructor(self, ctor):
        if not ctor.ignored:
            const_dict = {"args": ", ".join(self.arguments)}
            const_dict.update(ctor.__dict__)
            const_str = templates.constructor_decl % const_dict
            self.ctors.append(const_str)
        self.arguments = []

    def visit_method(self, method):
        self._visit_method(method, templates.method_decl)

    def visit_template_method(self, template_method):
        self._visit_method(
            template_method, templates.template_method_decl,
            {"types": ", ".join(template_method.template_types)})

    def _visit_method(self, method, template, additional_args=None):
        if not method.ignored:
            method_dict = {"args": ", ".join(self.arguments)}
            method_dict.update(method.__dict__)
            if additional_args is not None:
                method_dict.update(additional_args)
            method_dict["name"] = replace_operator_decl(
                method_dict["name"], self.config)
            method_str = template % method_dict
            method_str += self._exception_suffix(method.result_type)
            self.methods.append(method_str)
        self.arguments = []

    def visit_function(self, function):
        if not function.ignored:
            function_dict = {"args": ", ".join(self.arguments)}
            function_dict.update(function.__dict__)
            function_str = templates.function_decl % function_dict
            function_str += self._exception_suffix(function.result_type)
            self.functions.append(function_str)
        self.arguments = []

    def visit_template_function(self, template_function):
        if not template_function.ignored:
            function_dict = {
                "args": ", ".join(self.arguments),
                "types": ", ".join(template_function.template_types)}
            function_dict.update(template_function.__dict__)
            function_str = templates.template_function_decl % function_dict
            function_str += self._exception_suffix(
                template_function.result_type)
            self.functions.append(function_str)
        self.arguments = []

    def visit_param(self, param):
        param_dict = param.__dict__
        param_dict["name"] = replace_keyword_argnames(param.name)
        self.arguments.append(templates.arg_decl % param_dict)

    def _exception_suffix(self, result_type):
        """Workaround for bug in Cython when returning C arrays."""
        if result_type == "char *":
            return ""
        else:
            return " except +"

def replace_operator_decl(method_name, config):
    if method_name in config.call_operators:
        return "%s \"%s\"" % (config.call_operators[method_name], method_name)
    else:
        return method_name

class CythonImplementationExporter(AstExporter):
    """Export to Cython implementation file (.pyx).

    Parameters
    ----------
    includes : Includes, optional
        Collects information about required import statements from the exporter

    type_info : TypeInfo, optional
        Contains names of custom C++ types that have been defined in the code

    config : Config, optional
        Configuration that controls e.g. template specializations
    """
    def __init__(self, includes=Includes(), type_info=TypeInfo(),
                 config=Config()):
        super(CythonImplementationExporter, self).__init__()
        self.includes = includes
        self.type_info = type_info
        self.config = config

    def visit_ast(self, ast):
        self.output = render("definitions", enums=self.enums,
                             functions=self.functions, classes=self.classes)

    def visit_enum(self, enum):
        self.enums.append(render("enum", enum=enum))

    def visit_typedef(self, typedef):
        pass

    def visit_clazz(self, clazz, cppname=None):
        if self.config.is_ignored_class(clazz.filename, clazz.name):
            warnings.warn("Class '%s' from file '%s' is on the blacklist and "
                          "will be ignored." % (clazz.name, clazz.filename))
            clazz.ignored = True
            self._clear_class()
            return

        if len(self.ctors) > 1:
            msg = ("Class '%s' has more than one constructor. This is not "
                   "compatible to Python. The last constructor will overwrite "
                   "all others." % clazz.name)
            warnings.warn(msg)
        elif len(self.ctors) == 0:
            self.ctors.append(Constructor(clazz.name, ""))
        if cppname is None:
            cppname = clazz.name

        try:
            self.type_info.attach_specialization(clazz.get_attached_typeinfo())
            class_def = {}
            class_def.update(clazz.__dict__)
            class_def["cppname"] = cppname
            class_def["comment"] = clazz.comment
            class_def["fields"] = map(partial(
                self._process_field, selftype=clazz.name), self.fields)
            class_def["ctors"] = map(partial(
                self._process_constructor, selftype=clazz.name,
                cpptype=clazz.get_cppname()), self.ctors)
            class_def["methods"] = map(partial(
                self._process_method, selftype=clazz.name), self.methods)
        finally:
            self.type_info.remove_specialization()

        self.classes.append(render("class", **class_def))
        self._clear_class()

    def visit_template_class(self, template_class):
        specializer = ClassSpecializer(self.config)
        for clazz in specializer.specialize(template_class):
            self.visit_clazz(clazz, cppname=clazz.get_cppname())

    def visit_field(self, field):
        self.fields.append(field)

    def _process_field(self, field, selftype):
        try:
            setter_def = SetterDefinition(
                selftype, field, self.includes, self.type_info,
                self.config).make()
            getter_def = GetterDefinition(
                selftype, field, self.includes, self.type_info,
                self.config).make()
            return {
                "name": from_camel_case(field.name),
                "getter": getter_def,
                "setter": setter_def
            }
        except NotImplementedError as e:
            warnings.warn(e.message + " Ignoring field '%s'" % field.name)
            field.ignored = True
            return {}

    def visit_constructor(self, ctor):
        self.ctors.append(ctor)

    def _process_constructor(self, ctor, selftype, cpptype):
        if self.config.is_abstract_class(ctor.class_name):
            warnings.warn("Class '%s' is abstract and will have no constructor."
                          % ctor.class_name)
            ctor.ignored = True
            return ""

        try:
            constructor_def = ConstructorDefinition(
                selftype, ctor.comment, ctor.nodes, self.includes,
                self.type_info, self.config, cpptype)
            return constructor_def.make()
        except NotImplementedError as e:
            warnings.warn(e.message + " Ignoring method '%s'" % ctor.name)
            ctor.ignored = True
            return ""

    def visit_method(self, method, cppname=None):
        if self.config.is_ignored_method(method.class_name, method.name):
            warnings.warn("Method '%s::%s' is on the blacklist and will be "
                          "ignored." % (method.class_name, method.name))
            method.ignored = True
            return

        self.methods.append((method, cppname))

    def _process_method(self, arg, selftype):
        method, cppname = arg
        try:
            method_def = MethodDefinition(
                selftype, method.comment, method.name, method.nodes,
                self.includes, method.result_type, self.type_info, self.config,
                cppname=cppname)
            return method_def.make()
        except NotImplementedError as e:
            warnings.warn(e.message + " Ignoring method '%s'" % method.name)
            method.ignored = True
            return ""

    def visit_template_method(self, template_method):
        specializer = MethodSpecializer(self.config)
        for method in specializer.specialize(template_method):
            self.visit_method(method, cppname=template_method.name)

    def visit_function(self, function, cppname=None):
        try:
            self.functions.append(FunctionDefinition(
                function.name, function.comment, function.nodes, self.includes,
                function.result_type, self.type_info,
                self.config, cppname=cppname).make())
        except NotImplementedError as e:
            warnings.warn(e.message + " Ignoring function '%s'" % function.name)
            function.ignored = True

    def visit_template_function(self, template_function):
        specializer = FunctionSpecializer(self.config)
        for method in specializer.specialize(template_function):
            self.visit_function(method, cppname=template_function.name)

    def visit_param(self, param):
        pass

class FunctionDefinition(object):
    def __init__(self, name, comment, arguments, includes, result_type,
                 type_info, config, cppname=None):
        self.name = name
        self.comment = comment
        self.arguments = arguments
        self.includes = includes
        self.initial_args = []
        self.result_type = result_type
        self.type_info = type_info
        self.config = config
        if cppname is None:
            self.cppname = self.name
        else:
            self.cppname = cppname
        self.output_is_copy = True
        self._create_type_converters()

    def _create_type_converters(self):
        skip = 0
        self.type_converters = []
        for i, arg in enumerate(self.arguments):
            if skip > 0:
                skip -= 1
                continue
            type_converter = create_type_converter(
                arg.tipe, arg.name, self.type_info, self.config,
                (self.arguments, i))
            type_converter.add_includes(self.includes)
            self.type_converters.append(type_converter)
            skip = type_converter.n_cpp_args() - 1
        self.output_type_converter = create_type_converter(
            self.result_type, None, self.type_info, self.config)
        self.output_type_converter.add_includes(self.includes)

    def make(self):
        function = self._signature()
        function["input_conversions"] = self._input_type_conversions()
        function["call"] = self._call_cpp_function(self._call_args())
        function["return_output"] = self.output_type_converter.return_output(
            self.output_is_copy)
        function["comment"] = self.comment
        return render("function", **function)

    def _signature(self):
        function_name = from_camel_case(
            self.config.cpp_to_py_operator(self.name))
        return {"def_prefix": self._def_prefix(function_name),
                "args": ", ".join(self._cython_signature_args()),
                "name": function_name}

    def _def_prefix(self, function_name):
        special_method = (function_name.startswith("__") and
                          function_name.endswith("__"))
        if special_method:
            return "def"
        else:
            return "cpdef"

    def _cython_signature_args(self):
        return self.initial_args + [tc.python_type_decl()
                                    for tc in self.type_converters]

    def _input_type_conversions(self):
        return [tc.python_to_cpp() for tc in self.type_converters]

    def _call_args(self):
        return list(chain.from_iterable(
            tc.cpp_call_args() for tc in self.type_converters))

    def _call_cpp_function(self, call_args):
        call = templates.fun_call % {"name": self.cppname,
                                     "call_args": ", ".join(call_args)}
        return catch_result(self.output_type_converter.cpp_type_decl(), call)

class ConstructorDefinition(FunctionDefinition):
    def __init__(self, class_name, comment, arguments, includes, type_info,
                 config, cpp_classname):
        super(ConstructorDefinition, self).__init__(
            "__init__", comment, arguments, includes, result_type=None,
            type_info=type_info, config=config)
        self.initial_args = ["%s self" % class_name]
        self.cpp_classname = cpp_classname

    def _call_cpp_function(self, call_args):
        return templates.ctor_call % {"class_name": self.cpp_classname,
                                      "call_args": ", ".join(call_args)}

class MethodDefinition(FunctionDefinition):
    def __init__(self, class_name, comment, name, arguments, includes,
                 result_type, type_info, config, cppname=None):
        super(MethodDefinition, self).__init__(
            name, comment, arguments, includes, result_type, type_info, config, cppname)
        self.initial_args = ["%s self" % class_name]

    def _call_cpp_function(self, call_args):
        call = templates.method_call % {
            "name": self.config.call_operators.get(self.cppname, self.cppname),
            "call_args": ", ".join(call_args)}
        return catch_result(self.output_type_converter.cpp_type_decl(), call)

class SetterDefinition(MethodDefinition):
    def __init__(self, python_classname, field, includes, type_info, config):
        name = "__set_%s" % field.name
        super(SetterDefinition, self).__init__(
            python_classname, "", name, [field], includes, "void", type_info,
            config)
        self.field_name = field.name

    def _call_cpp_function(self, call_args):
        assert len(call_args) == 1
        return templates.setter_call % {"name": self.field_name,
                                        "call_args": call_args[0]}

class GetterDefinition(MethodDefinition):
    def __init__(self, python_classname, field, includes, type_info, config):
        name = "__get_%s" % field.name
        super(GetterDefinition, self).__init__(
            python_classname, "", name, [], includes, field.tipe, type_info,
            config)
        self.output_is_copy = False
        self.field_name = field.name

    def _call_cpp_function(self, call_args):
        assert len(call_args) == 0
        call = templates.getter_call % {"name": self.field_name}
        return catch_result(self.output_type_converter.cpp_type_decl(), call)

def catch_result(result_type_decl, call):
    if result_type_decl == "":
        return call
    else:
        return templates.catch_result % {"cpp_type_decl": result_type_decl,
                                         "call": call}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
integrator Class Hierarchy (SLF4J 1.7.5 Test API)
</TITLE>

<META NAME="date" CONTENT="2013-03-25">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Hierarchy For Package integrator

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object

integrator.Activator (implements org.osgi.framework.BundleActivator)

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2005-2013 QOS.ch. All Rights Reserved.


text:
package com.tlh.springboot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.tlh.springboot.util.Message;

@Controller
public class HomeController {

	@RequestMapping("/")
	public String index(Model model){
		Message message=new Message("测试标题", "测试内容", "额外信息,只对管理员显示");
		model.addAttribute("msg", message);
		return "home";
	}

}


text:
Privacy Policy

      Rainforest Connection respects your privacy. It is Rainforest Connection's policy to respect your privacy regarding any information we may collect from you across our website,

        https://rfcx.org

      and other sites we own and operate.

      What information do we collect from you?
      The types of information we collect includes: your full name, email address, address, donation amount, favorite guardian streams and likes.

      When do we collect information?
      We keep your contact information when you sign up for our mailing list via the Rainforest Connection player app or website. We record your address and donation amount when you make a donation.

      How do we use this information?
      We only ask for personal information when we truly need it to provide a service to you. We collect it by fair and lawful means, with your knowledge and consent. We also let you know why we're collecting it and how it will be used.

      If you have signed up for our mailing list we will use your contact information to keep you informed of news related to Rainforest Connection.

      What are the lawful bases for collecting your information?
      We only retain collected information for as long as necessary to provide you with your requested service. What data we store, we'll protect within commercially acceptable means to prevent loss and theft, as well as unauthorised access, disclosure, copying, use or modification.

      Security precautions in place to protect the loss, misuse or alteration of your information.
      We take appropriate measures to ensure that the information disclosed to us is kept secure, accurate and up-to-date and kept only for so long as is necessary for the purposes for which it is used, as stated above. As an additional security measure, your personal information is also encrypted during transmission by using Secure Socket Layer (SSL) 128-bit encryption software.

When you give us personal information, we take steps to ensure that it is treated securely:

        Electronic records are kept on a password controlled and restricted access area of Google Cloud or Amazon Web Services. Mailing list names and email addresses are stored in MailChimp. Google Drive and MailChimp are GDPR compliant.

        Electronic versions and records are kept on secure computers and accessed through password protected devices.

      Who has access to your information?
      We don't share any of your information publicly or with third-parties, except when required to by law. Personal data is accessible to the Rainforest Connection founders and administrators at Rainforest Connection for the purposes described above.

      Our website may link to external sites that are not operated by us. Please be aware that we have no control over the content and practices of these sites, and cannot accept responsibility or liability for their respective privacy policies.

      You are free to refuse our request for your personal information, with the understanding that we may be unable to provide you with some of your desired services. Your continued use of our website will be regarded as acceptance of our practices around privacy and personal information. If you have any questions about how we handle user data and personal information, feel free to contact us at

        privacy@rfcx.org
      .

      How you can access and update your information?
      You can update your information held on the mailing list or unsubscribe by following the link at the bottom of every mailing list email. You have the right to ask for a copy of the information that Rainforest Connection holds about you (we may charge for information requests to cover our costs in providing you with details of the information we hold about you). Requests should be made by email to

        privacy@rfcx.org
      .

      If you are unhappy with the way you have been treated in relation to the data we collect and our processing of it please contact us so we can attempt to resolve it. If necessary, information on how you can raise a complaint is outlined

        here
      .

      Review of this Policy
      We keep this Policy under regular review. This Policy was last updated on August 8, 2019.


text:
<!doctype html>

  <meta charset="utf-8">
  <title>The Galaxy Hyper-browser Wizard</title>
  <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css">
  <link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.1/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="wizardApp/styles/wizard.css">

      Wizard ui-router test

      Some content will load here!

        Some content will load here!

        Some content will load here!


text:
/*
	SObjectizer 5.
*/

#include <so_5/rt/impl/h/so_environment_impl.hpp>

#include <so_5/rt/h/so_environment.hpp>

namespace so_5
{

namespace rt
{

//
// so_environment_params_t
//

so_environment_params_t::so_environment_params_t()
	:
		m_mbox_mutex_pool_size( 128 ),
		m_agent_coop_mutex_pool_size( 32 ),
		m_agent_event_queue_mutex_pool_size( 128 ),
		m_event_exception_logger( create_std_event_exception_logger() )
{
}

so_environment_params_t::so_environment_params_t(
	so_environment_params_t && other )
	:	m_mbox_mutex_pool_size( other.m_mbox_mutex_pool_size )
	,	m_agent_coop_mutex_pool_size( other.m_agent_coop_mutex_pool_size )
	,	m_agent_event_queue_mutex_pool_size(
			other.m_agent_event_queue_mutex_pool_size )
	,	m_named_dispatcher_map( std::move( other.m_named_dispatcher_map ) )
	,	m_timer_thread( std::move( other.m_timer_thread ) )
	,	m_so_layers( std::move( other.m_so_layers ) )
	,	m_coop_listener( std::move( other.m_coop_listener ) )
	,	m_event_exception_logger( std::move( other.m_event_exception_logger ) )
{}

so_environment_params_t::~so_environment_params_t()
{
}

so_environment_params_t &
so_environment_params_t::operator=( so_environment_params_t && other )
{
	so_environment_params_t tmp( std::move( other ) );
	this->swap( tmp );

	return *this;
}

void
so_environment_params_t::swap( so_environment_params_t & other )
{
	std::swap( m_mbox_mutex_pool_size, other.m_mbox_mutex_pool_size );
	std::swap( m_agent_coop_mutex_pool_size,
			other.m_agent_coop_mutex_pool_size );
	std::swap( m_agent_event_queue_mutex_pool_size,
			other.m_agent_event_queue_mutex_pool_size );
	m_named_dispatcher_map.swap( other.m_named_dispatcher_map );
	m_timer_thread.swap( other.m_timer_thread );
	m_so_layers.swap( other.m_so_layers );
	m_coop_listener.swap( other.m_coop_listener );
	m_event_exception_logger.swap( other.m_event_exception_logger );
}

so_environment_params_t &
so_environment_params_t::mbox_mutex_pool_size(
	unsigned int mutex_pool_size )
{
	m_mbox_mutex_pool_size = mutex_pool_size;
	return * this;
}

so_environment_params_t &
so_environment_params_t::agent_coop_mutex_pool_size(
	unsigned int mutex_pool_size )
{
	m_agent_coop_mutex_pool_size = mutex_pool_size;
	return * this;
}

so_environment_params_t &
so_environment_params_t::agent_event_queue_mutex_pool_size(
	unsigned int mutex_pool_size )
{
	m_agent_event_queue_mutex_pool_size = mutex_pool_size;
	return * this;
}

so_environment_params_t &
so_environment_params_t::add_named_dispatcher(
	const nonempty_name_t & name,
	dispatcher_unique_ptr_t dispatcher )
{
	m_named_dispatcher_map[ name.query_name() ] =
		dispatcher_ref_t( dispatcher.release() );
	return *this;
}

so_environment_params_t &
so_environment_params_t::timer_thread(
	so_5::timer_thread::timer_thread_unique_ptr_t timer_thread )
{
	m_timer_thread = std::move( timer_thread );
	return  *this;
}

so_environment_params_t &
so_environment_params_t::coop_listener(
	coop_listener_unique_ptr_t coop_listener )
{
	m_coop_listener = std::move( coop_listener );
	return *this;
}

so_environment_params_t &
so_environment_params_t::event_exception_logger(
	event_exception_logger_unique_ptr_t logger )
{
	if( nullptr != logger.get() )
		m_event_exception_logger = std::move( logger );

	return *this;
}

void
so_environment_params_t::add_layer(
	const std::type_index & type,
	so_layer_unique_ptr_t layer_ptr )
{
	m_so_layers[ type ] = so_layer_ref_t( layer_ptr.release() );
}

unsigned int
so_environment_params_t::mbox_mutex_pool_size() const
{
	return m_mbox_mutex_pool_size;
}

unsigned int
so_environment_params_t::agent_coop_mutex_pool_size() const
{
	return m_agent_coop_mutex_pool_size;
}

unsigned int
so_environment_params_t::agent_event_queue_mutex_pool_size() const
{
	return m_agent_event_queue_mutex_pool_size;
}

const named_dispatcher_map_t &
so_environment_params_t::named_dispatcher_map() const
{
	return m_named_dispatcher_map;
}

const so_layer_map_t &
so_environment_params_t::so_layers_map() const
{
	return m_so_layers;
}

//
// so_environment_t
//

so_environment_t &
so_environment_t::self_ref()
{
	return *this;
}

so_environment_t::so_environment_t(
	so_environment_params_t && so_environment_params )
	:
		m_so_environment_impl(
			new impl::so_environment_impl_t(
				std::move(so_environment_params),
				self_ref() ) )
{
}

so_environment_t::~so_environment_t()
{
	if( m_so_environment_impl )
		delete m_so_environment_impl;
}

mbox_ref_t
so_environment_t::create_local_mbox( )
{
	return m_so_environment_impl->create_local_mbox();
}

mbox_ref_t
so_environment_t::create_local_mbox(
	const nonempty_name_t & nonempty_name )
{
	return m_so_environment_impl->create_local_mbox( nonempty_name );
}

mbox_ref_t
so_environment_t::create_local_mbox(
	std::unique_ptr< ACE_RW_Thread_Mutex > lock_ptr )
{
	return m_so_environment_impl->create_local_mbox(
		std::move( lock_ptr ) );
}

mbox_ref_t
so_environment_t::create_local_mbox(
	const nonempty_name_t & nonempty_name,
	std::unique_ptr< ACE_RW_Thread_Mutex > lock_ptr )
{
	return m_so_environment_impl->create_local_mbox(
		nonempty_name,
		std::move( lock_ptr ) );
}

dispatcher_t &
so_environment_t::query_default_dispatcher()
{
	return m_so_environment_impl->query_default_dispatcher();
}

dispatcher_ref_t
so_environment_t::query_named_dispatcher(
	const std::string & disp_name )
{
	return m_so_environment_impl
		->query_named_dispatcher( disp_name );
}

void
so_environment_t::install_exception_logger(
	event_exception_logger_unique_ptr_t logger )
{
	m_so_environment_impl->install_exception_logger( std::move( logger ) );
}

agent_coop_unique_ptr_t
so_environment_t::create_coop(
	const nonempty_name_t & name )
{
	return create_coop(
		name,
		create_default_disp_binder() );
}

agent_coop_unique_ptr_t
so_environment_t::create_coop(
	const nonempty_name_t & name,
	disp_binder_unique_ptr_t disp_binder )
{
	return agent_coop_unique_ptr_t(
			new agent_coop_t( name, std::move(disp_binder), self_ref() ) );
}

void
so_environment_t::register_coop(
	agent_coop_unique_ptr_t agent_coop )
{
	m_so_environment_impl->register_coop( std::move( agent_coop ) );
}

void
so_environment_t::deregister_coop(
	const nonempty_name_t & name,
	int reason )
{
	m_so_environment_impl->deregister_coop( name, reason );
}

so_5::timer_thread::timer_id_ref_t
so_environment_t::schedule_timer(
	const std::type_index & type_index,
	const message_ref_t & msg,
	const mbox_ref_t & mbox,
	unsigned int delay_msec,
	unsigned int period_msec )
{
	return m_so_environment_impl->schedule_timer(
		type_index, msg, mbox, delay_msec, period_msec );
}

void
so_environment_t::single_timer(
	const std::type_index & type_index,
	const message_ref_t & msg,
	const mbox_ref_t & mbox,
	unsigned int delay_msec )
{
	m_so_environment_impl->single_timer(
		type_index, msg, mbox, delay_msec );
}

so_layer_t *
so_environment_t::query_layer(
	const std::type_index & type_index ) const
{
	return m_so_environment_impl->query_layer( type_index );
}

void
so_environment_t::add_extra_layer(
	const std::type_index & type_index,
	const so_layer_ref_t & layer )
{
	m_so_environment_impl->add_extra_layer( type_index, layer );
}

void
so_environment_t::run()
{
	m_so_environment_impl->run( *this );
}

void
so_environment_t::stop()
{
	m_so_environment_impl->stop();
}

impl::so_environment_impl_t &
so_environment_t::so_environment_impl()
{
	return *m_so_environment_impl;
}

void
so_environment_t::call_exception_logger(
	const std::exception & event_exception,
	const std::string & coop_name )
{
	m_so_environment_impl->call_exception_logger( event_exception, coop_name );
}

} /* namespace rt */

} /* namespace so_5 */


text:
/*
 * 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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.androidenterprise.model;

/**
 * Group license objects allow you to keep track of licenses (called entitlements) for both free and
 * paid apps. For a free app, a group license is created when an enterprise admin first approves the
 * product in Google Play or when the first entitlement for the product is created for a user via
 * the API. For a paid app, a group license object is only created when an enterprise admin
 * purchases the product in Google Play for the first time. Use the API to query group licenses. A
 * Grouplicenses resource includes the total number of licenses purchased (paid apps only) and the
 * total number of licenses currently in use. In other words, the total number of Entitlements that
 * exist for the product. Only one group license object is created per product and group license
 * objects are never deleted. If a product is unapproved, its group license remains. This allows
 * enterprise admins to keep track of any remaining entitlements for the product.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Google Play EMM API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class GroupLicense extends com.google.api.client.json.GenericJson {

  /**
   * How this group license was acquired. "bulkPurchase" means that this Grouplicenses resource was
   * created because the enterprise purchased licenses for this product; otherwise, the value is
   * "free" (for free products).
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String acquisitionKind;

  /**
   * Whether the product to which this group license relates is currently approved by the
   * enterprise. Products are approved when a group license is first created, but this approval may
   * be revoked by an enterprise admin via Google Play. Unapproved products will not be visible to
   * end users in collections, and new entitlements to them should not normally be created.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String approval;

  /**
   * The total number of provisioned licenses for this product. Returned by read operations, but
   * ignored in write operations.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Integer numProvisioned;

  /**
   * The number of purchased licenses (possibly in multiple purchases). If this field is omitted,
   * then there is no limit on the number of licenses that can be provisioned (for example, if the
   * acquisition kind is "free").
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Integer numPurchased;

  /**
   * The permission approval status of the product. This field is only set if the product is
   * approved. Possible states are: - "currentApproved", the current set of permissions is approved,
   * but additional permissions will require the administrator to reapprove the product (If the
   * product was approved without specifying the approved permissions setting, then this is the
   * default behavior.), - "needsReapproval", the product has unapproved permissions. No additional
   * product licenses can be assigned until the product is reapproved, -
   * "allCurrentAndFutureApproved", the current permissions are approved and any future permission
   * updates will be automatically approved without administrator review.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String permissions;

  /**
   * The ID of the product that the license is for. For example, "app:com.google.android.gm".
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String productId;

  /**
   * How this group license was acquired. "bulkPurchase" means that this Grouplicenses resource was
   * created because the enterprise purchased licenses for this product; otherwise, the value is
   * "free" (for free products).
   * @return value or {@code null} for none
   */
  public java.lang.String getAcquisitionKind() {
    return acquisitionKind;
  }

  /**
   * How this group license was acquired. "bulkPurchase" means that this Grouplicenses resource was
   * created because the enterprise purchased licenses for this product; otherwise, the value is
   * "free" (for free products).
   * @param acquisitionKind acquisitionKind or {@code null} for none
   */
  public GroupLicense setAcquisitionKind(java.lang.String acquisitionKind) {
    this.acquisitionKind = acquisitionKind;
    return this;
  }

  /**
   * Whether the product to which this group license relates is currently approved by the
   * enterprise. Products are approved when a group license is first created, but this approval may
   * be revoked by an enterprise admin via Google Play. Unapproved products will not be visible to
   * end users in collections, and new entitlements to them should not normally be created.
   * @return value or {@code null} for none
   */
  public java.lang.String getApproval() {
    return approval;
  }

  /**
   * Whether the product to which this group license relates is currently approved by the
   * enterprise. Products are approved when a group license is first created, but this approval may
   * be revoked by an enterprise admin via Google Play. Unapproved products will not be visible to
   * end users in collections, and new entitlements to them should not normally be created.
   * @param approval approval or {@code null} for none
   */
  public GroupLicense setApproval(java.lang.String approval) {
    this.approval = approval;
    return this;
  }

  /**
   * The total number of provisioned licenses for this product. Returned by read operations, but
   * ignored in write operations.
   * @return value or {@code null} for none
   */
  public java.lang.Integer getNumProvisioned() {
    return numProvisioned;
  }

  /**
   * The total number of provisioned licenses for this product. Returned by read operations, but
   * ignored in write operations.
   * @param numProvisioned numProvisioned or {@code null} for none
   */
  public GroupLicense setNumProvisioned(java.lang.Integer numProvisioned) {
    this.numProvisioned = numProvisioned;
    return this;
  }

  /**
   * The number of purchased licenses (possibly in multiple purchases). If this field is omitted,
   * then there is no limit on the number of licenses that can be provisioned (for example, if the
   * acquisition kind is "free").
   * @return value or {@code null} for none
   */
  public java.lang.Integer getNumPurchased() {
    return numPurchased;
  }

  /**
   * The number of purchased licenses (possibly in multiple purchases). If this field is omitted,
   * then there is no limit on the number of licenses that can be provisioned (for example, if the
   * acquisition kind is "free").
   * @param numPurchased numPurchased or {@code null} for none
   */
  public GroupLicense setNumPurchased(java.lang.Integer numPurchased) {
    this.numPurchased = numPurchased;
    return this;
  }

  /**
   * The permission approval status of the product. This field is only set if the product is
   * approved. Possible states are: - "currentApproved", the current set of permissions is approved,
   * but additional permissions will require the administrator to reapprove the product (If the
   * product was approved without specifying the approved permissions setting, then this is the
   * default behavior.), - "needsReapproval", the product has unapproved permissions. No additional
   * product licenses can be assigned until the product is reapproved, -
   * "allCurrentAndFutureApproved", the current permissions are approved and any future permission
   * updates will be automatically approved without administrator review.
   * @return value or {@code null} for none
   */
  public java.lang.String getPermissions() {
    return permissions;
  }

  /**
   * The permission approval status of the product. This field is only set if the product is
   * approved. Possible states are: - "currentApproved", the current set of permissions is approved,
   * but additional permissions will require the administrator to reapprove the product (If the
   * product was approved without specifying the approved permissions setting, then this is the
   * default behavior.), - "needsReapproval", the product has unapproved permissions. No additional
   * product licenses can be assigned until the product is reapproved, -
   * "allCurrentAndFutureApproved", the current permissions are approved and any future permission
   * updates will be automatically approved without administrator review.
   * @param permissions permissions or {@code null} for none
   */
  public GroupLicense setPermissions(java.lang.String permissions) {
    this.permissions = permissions;
    return this;
  }

  /**
   * The ID of the product that the license is for. For example, "app:com.google.android.gm".
   * @return value or {@code null} for none
   */
  public java.lang.String getProductId() {
    return productId;
  }

  /**
   * The ID of the product that the license is for. For example, "app:com.google.android.gm".
   * @param productId productId or {@code null} for none
   */
  public GroupLicense setProductId(java.lang.String productId) {
    this.productId = productId;
    return this;
  }

  @Override
  public GroupLicense set(String fieldName, Object value) {
    return (GroupLicense) super.set(fieldName, value);
  }

  @Override
  public GroupLicense clone() {
    return (GroupLicense) super.clone();
  }

}


text:
ReWebSocket is 99% API-compatible with WebSocket:

    var WebSocket = require('ws');
    var ReWebSocket = require('rewebsocket')(WebSocket);

    var ws = new ReWebSocket("ws://127.0.0.1:3000");
    ws.open();  // the only big difference: need to call open explicitly!

    ws.onmessage = function(event) {
      console.log("Received %j", event.data);
    };
    ws.onopen = function(event) {
      console.log("Connected");
    };
    ws.onclose = function(event) {
      if (event.previousReadyState == WebSocket.OPEN)
        console.log("Disconnected");
      else
        console.log("Connection failed.");
    };
    ws.onerror = function(event) {
      // in most cases, you only want to handle this event for logging purposes
      // console.log("Error: %s", event.message);
    };
    ws.onconnecting = function(event) {
      console.log("Connecting...");
    };

## Installation

    npm install rewebsocket

Also works as a client-side module via Browserify.

## API differences from WebSocket

Method differences:

* You need to call `open` explicitly to start connection.
* You can call `open` and `close` multiple times; after you call `open`, ReWebSocket will try to keep the connection open until you call `close`.
* Additional `reconnect` method closes and reopens the connection.

Event differences:

* In `onclose`, `readyState` will be `WebSocket.CONNECTING` if a reconnection attempt is pending, and `WebSocket.CLOSED` after an explicit `close` call.
* In `onclose`, additional `previousReadyState` property is provided. You can use it to distinguish failed connection attempts from aborted connections, as demonstrated by the example above.
* Additional `onconnecting` event is fired before each connection attempt.

Properties:

* `timeoutInterval` — connectiont timeout in milliseconds, defaults to 10000.
* `reconnectIntervals` — array of delays between reconnection attempts, in milliseconds; defaults to [10, 100, 500, 1000, 2000, 3000, 5000, 8000, 13000, 21000, 34000, 55000, 60000]; use this to specify your preferred back-off scheme; after a successful connection, the first value is used again; the last value is the maximum interval.

## Running the example

    node example/example.js

For additional logging, try:

    DEBUG=rewebsocket node example/example.js

## License

© 2012 Andrey Tarantsov <andrey@tarantsov.com>.

Provided under the MIT license.


text:
layout: index
title: Commands Specific to a Room
---

Frequently you will want to add a command that is specific to a certain room.  If the command involves an object, then Quest will attempt to match the object (for example, ATTACK GOBLIN, Quest will start by trying to match GOBLIN to any object present). Often there will be no object, for example, the player might have to CLIMB or SWIM.

One way to do that would be to test whether you are in the right room in the command script. However, the cool way is to have two commands - one in the room itself.

Let us suppose a room where the player has to CLIMB.

### The general command

In most rooms, CLIMB will do nothing. We will handle that first. Create a command as usual, and give it this pattern:

> climb

Now click the "Add new script" button, select "Print" and paste in some suitable text, "Nothing to climb here."

### The room command

Now create a second command. This will be the command that actually does something. Give it the same pattern, click the "Add new script" button, select "Print" and paste in some suitable text, "You climb the drainpipe, and go in through the window." Then click the "Add new script" button again, select "Move Object". Select the player object and some suitable room.

Now the clever bit. If you are using the web version, click on the "Move" button towards the top right, and select the room the player can climb in. For the desktop version, drag the command to the room (make sure you do the right one!).

If the player is in that room, Quest will use the CLIMB command for the room, and the player will climb the drainpipe. Otherwise the general command will be used.

### Another room?

If you have more than one room the player can climb in, just create a new command for each one. Each will have its own text and destination, and no need for any of those `if/else` things!


text:
package org.apache.polygene.api.query.grammar;

import java.util.Collection;
import java.util.Collections;
import java.util.function.Predicate;
import org.apache.polygene.api.composite.Composite;

/**
 * Base binary Specification, used for AND and OR Specifications..
 */
public abstract class BinaryPredicate
    extends ExpressionPredicate
{
    protected final Collection<Predicate<Composite>> operands;

    protected BinaryPredicate( Collection<Predicate<Composite>> operands )
    {
        this.operands = Collections.unmodifiableCollection( operands );
    }

    public Collection<Predicate<Composite>> operands()
    {
        return operands;
    }
}


text:
package org.jetbrains.plugins.scala
package lang.rearranger

import com.intellij.internal.statistic.UsageTrigger
import com.intellij.openapi.editor.Document
import com.intellij.openapi.util.{Pair, TextRange}
import com.intellij.psi.PsiElement
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.psi.codeStyle.arrangement.{ArrangementSettings, _}
import com.intellij.psi.codeStyle.arrangement.`match`.{ArrangementSectionRule, StdArrangementEntryMatcher, StdArrangementMatchRule}
import com.intellij.psi.codeStyle.arrangement.group.ArrangementGroupingRule
import com.intellij.psi.codeStyle.arrangement.model.{ArrangementAtomMatchCondition, ArrangementCompositeMatchCondition, ArrangementMatchCondition}
import com.intellij.psi.codeStyle.arrangement.std.StdArrangementTokens.EntryType._
import com.intellij.psi.codeStyle.arrangement.std.StdArrangementTokens.Grouping._
import com.intellij.psi.codeStyle.arrangement.std.StdArrangementTokens.Modifier._
import com.intellij.psi.codeStyle.arrangement.std.StdArrangementTokens.Order._
import com.intellij.psi.codeStyle.arrangement.std.StdArrangementTokens._
import com.intellij.psi.codeStyle.arrangement.std._

import scala.collection.JavaConversions._
import scala.collection.{immutable, mutable}

/**
 * @author Roman.Shein
 *         Date: 08.07.13
 */
class ScalaRearranger extends Rearranger[ScalaArrangementEntry] with ArrangementStandardSettingsAware {

  override def parseWithNew(root: PsiElement, document: Document, ranges: java.util.Collection[TextRange],
                                      element: PsiElement, settings: ArrangementSettings): Pair[ScalaArrangementEntry, java.util.List[ScalaArrangementEntry]] = {
    val groupingRules = getGroupingRules(settings)

    val existingInfo = new ScalaArrangementParseInfo
    root.accept(new ScalaArrangementVisitor(existingInfo, document, collectionAsScalaIterable(ranges), groupingRules))

    val newInfo = new ScalaArrangementParseInfo
    element.accept(new ScalaArrangementVisitor(newInfo, document, Iterable(element.getTextRange), groupingRules))
    if (newInfo.entries.size != 1) {
      null
    } else {
      Pair.create(newInfo.entries(0), existingInfo.entries)
    }
  }

  override def parse(root: PsiElement, document: Document,
                              ranges: java.util.Collection[TextRange], settings: ArrangementSettings) = {
    UsageTrigger.trigger(ScalaRearranger.featureId)
    val info = new ScalaArrangementParseInfo
    root.accept(new ScalaArrangementVisitor(info, document, ranges, getGroupingRules(settings)))
    if (settings != null) {
      for (rule <- settings.getGroupings) {
        if (DEPENDENT_METHODS == rule.getGroupingType) {
          setupUtilityMethods(info, rule.getOrderType)
        } else if (JAVA_GETTERS_AND_SETTERS == rule.getGroupingType) {
          setupJavaGettersAndSetters(info)
        } else if (SCALA_GETTERS_AND_SETTERS == rule.getGroupingType) {
          setupScalaGettersAndSetters(info)
        }
      }
    }
    info.entries
  }

  override def getBlankLines(settings: CodeStyleSettings, parent: ScalaArrangementEntry, previous:
  ScalaArrangementEntry, target: ScalaArrangementEntry): Int = {
    if (previous == null) {
      -1
    } else {
      val codeStyleSettings = settings.getCommonSettings(ScalaFileType.SCALA_LANGUAGE) //probably this will not work
      val targetType = target.getType
      if (targetType == VAL || targetType == VAR || targetType == TYPE) {
        codeStyleSettings.BLANK_LINES_AROUND_FIELD
      } else if (targetType == FUNCTION || targetType == MACRO) {
        codeStyleSettings.BLANK_LINES_AROUND_METHOD
      } else if (targetType == CLASS || targetType == TRAIT) {
        codeStyleSettings.BLANK_LINES_AROUND_CLASS
      } else {
        -1
      }
    }
  }

  private def getGroupingRules(settings: ArrangementSettings) = {
    var result = immutable.HashSet[ArrangementSettingsToken]()
    if (settings != null) {
      for (rule <- settings.getGroupings) {
        result = result + rule.getGroupingType
      }
    }
    result
  }

  override def getDefaultSettings = ScalaRearranger.defaultSettings

  override def getSerializer = ScalaRearranger.SETTINGS_SERIALIZER

  override def getSupportedGroupingTokens =
    seqAsJavaList(immutable.List(new CompositeArrangementSettingsToken(DEPENDENT_METHODS, BREADTH_FIRST, DEPTH_FIRST),
      new CompositeArrangementSettingsToken(JAVA_GETTERS_AND_SETTERS),
      new CompositeArrangementSettingsToken(SCALA_GETTERS_AND_SETTERS),
      new CompositeArrangementSettingsToken(SPLIT_INTO_UNARRANGEABLE_BLOCKS_BY_EXPRESSIONS)
    ))

  override def getSupportedMatchingTokens =
    seqAsJavaList(immutable.List(new CompositeArrangementSettingsToken(General.TYPE,
      scalaTypesValues.toList), new CompositeArrangementSettingsToken(General.MODIFIER, scalaModifiers.toList),
      new CompositeArrangementSettingsToken(General.ORDER, Order.KEEP, Order.BY_NAME)))

  override def isEnabled(token: ArrangementSettingsToken, current: ArrangementMatchCondition) =
    (scalaTypesValues.contains(token) || supportedOrders.contains(token)) ||
            (if (current != null) {
              val tokenType = ArrangementUtil.parseType(current)
              if (tokenType != null) {
                tokensForType(tokenType).contains(token)
              } else {
                commonModifiers.contains(token)
              }
            } else {
              commonModifiers.contains(token)
            })

  override def buildMatcher(condition: ArrangementMatchCondition) = throw new IllegalArgumentException("Can't build a matcher for condition " + condition)

  override def getMutexes = seqAsJavaList(immutable.List(scalaAccessModifiersValues, scalaTypesValues))

  private def setupUtilityMethods(info: ScalaArrangementParseInfo, orderType: ArrangementSettingsToken) {
    if (DEPTH_FIRST == orderType) {
      for (root <- info.getMethodDependencyRoots) {
        setupDepthFirstDependency(root)
      }
    }
    else if (BREADTH_FIRST == orderType) {
      for (root <- info.getMethodDependencyRoots) {
        setupBreadthFirstDependency(root)
      }
    }
    else {
      assert(assertion = false, orderType)
    }
  }

  private def setupDepthFirstDependency(info: ScalaArrangementDependency) {
    for (dependency <- info.getDependentMethodInfos) {
      setupDepthFirstDependency(dependency)
      val dependentEntry = dependency.getAnchorMethod
      if (dependentEntry.getDependencies == null) {
        dependentEntry.addDependency(info.getAnchorMethod)
      }
    }
  }

  private def setupBreadthFirstDependency(info: ScalaArrangementDependency) {
    val toProcess = mutable.Queue[ScalaArrangementDependency]()
    toProcess += info
    while (!toProcess.isEmpty) {
      val current = toProcess.dequeue()
      for (dependencyInfo <- current.getDependentMethodInfos) {
        val dependencyMethod = dependencyInfo.getAnchorMethod
        if (dependencyMethod.getDependencies == null) {
          dependencyMethod.addDependency(current.getAnchorMethod)
        }
        toProcess += dependencyInfo
      }
    }
  }

  private def setupJavaGettersAndSetters(info: ScalaArrangementParseInfo) = setupGettersAndSetters(info.javaProperties)

  private def setupScalaGettersAndSetters(info: ScalaArrangementParseInfo) = setupGettersAndSetters(info.scalaProperties)

  private def setupGettersAndSetters(properties: Iterable[ScalaPropertyInfo]) {
    for (propertyInfo <- properties) {
      if (propertyInfo.isComplete && propertyInfo.setter.getDependencies == null) {
        propertyInfo.setter.addDependency(propertyInfo.getter)
      }
    }
  }
}

object ScalaRearranger {

  private val featureId = "scala.rearrange"

  private def addCondition(matchRules: immutable.List[ArrangementSectionRule], conditions: ArrangementSettingsToken*) = {
    if (conditions.length == 1) {
      ArrangementSectionRule.create(
        new StdArrangementMatchRule(
          new StdArrangementEntryMatcher(new ArrangementAtomMatchCondition(conditions(0), conditions(0)))
        )
      ) :: matchRules
    } else {
      val composite = new ArrangementCompositeMatchCondition
      for (condition <- conditions) {
        composite.addOperand(new ArrangementAtomMatchCondition(condition, condition))
      }
      ArrangementSectionRule.create(new StdArrangementMatchRule(new StdArrangementEntryMatcher(composite))) :: matchRules
    }
  }

  private def getDefaultSettings = {
    val groupingRules = immutable.List[ArrangementGroupingRule](new ArrangementGroupingRule(DEPENDENT_METHODS, DEPTH_FIRST), new ArrangementGroupingRule(JAVA_GETTERS_AND_SETTERS),
      new ArrangementGroupingRule(SCALA_GETTERS_AND_SETTERS))
    var matchRules = immutable.List[ArrangementSectionRule]()
    for (access <- scalaAccessModifiersValues) {
      matchRules = addCondition(matchRules, TYPE, access, FINAL)
    }
    for (access <- scalaAccessModifiersValues) {
      matchRules = addCondition(matchRules, TYPE, access)
    }
//    matchRules = addCondition(matchRules, TYPE)
    for (access <- scalaAccessModifiersValues) {
      matchRules = addCondition(matchRules, VAL, access, FINAL, LAZY)
    }
    for (access <- scalaAccessModifiersValues) {
      matchRules = addCondition(matchRules, VAL, access, FINAL)
    }
    for (access <- scalaAccessModifiersValues) {
      matchRules = addCondition(matchRules, VAL, access, LAZY)
    }
    matchRules = addCondition(matchRules, VAL, ABSTRACT)
    matchRules = addCondition(matchRules, VAL, OVERRIDE)
    for (access <- scalaAccessModifiersValues) {
      matchRules = addCondition(matchRules, VAL, access)
    }
//    matchRules = addCondition(matchRules, VAL)
    for (access <- scalaAccessModifiersValues) {
      matchRules = addCondition(matchRules, VAR, access, OVERRIDE)
    }
    for (access <- scalaAccessModifiersValues) {
      matchRules = addCondition(matchRules, VAR, access)
    }
//    matchRules = addCondition(matchRules, VAR)
    for (access <- scalaAccessModifiersValues) {
      matchRules = addCondition(matchRules, CONSTRUCTOR, access)
    }
    matchRules = addCondition(matchRules, CONSTRUCTOR)
    matchRules = addCondition(matchRules, FUNCTION, PUBLIC, FINAL, OVERRIDE, IMPLICIT)
    matchRules = addCondition(matchRules, FUNCTION, PROTECTED, FINAL, OVERRIDE, IMPLICIT)
    for (access <- scalaAccessModifiersValues) {
      matchRules = addCondition(matchRules, FUNCTION, PUBLIC, FINAL, IMPLICIT)
    }
    matchRules = addCondition(matchRules, FUNCTION, PUBLIC, FINAL, OVERRIDE)
    matchRules = addCondition(matchRules, FUNCTION, PROTECTED, FINAL, OVERRIDE)
    for (access <- scalaAccessModifiersValues) {
      matchRules = addCondition(matchRules, FUNCTION, access)
    }
//    matchRules = addCondition(matchRules, FUNCTION)
    matchRules = addCondition(matchRules, MACRO, PUBLIC, OVERRIDE)
    matchRules = addCondition(matchRules, MACRO, PROTECTED, OVERRIDE)
    for (access <- scalaAccessModifiersValues) {
      matchRules = addCondition(matchRules, MACRO, access)
    }
//    matchRules = addCondition(matchRules, MACRO)
    for (access <- scalaAccessModifiersValues) {
      matchRules = addCondition(matchRules, TRAIT, access, ABSTRACT, SEALED)
    }
    for (access <- scalaAccessModifiersValues) {
      matchRules = addCondition(matchRules, TRAIT, access, ABSTRACT)
    }
    for (access <- scalaAccessModifiersValues) {
      matchRules = addCondition(matchRules, TRAIT, access, SEALED)
    }
    for (access <- scalaAccessModifiersValues) {
      matchRules = addCondition(matchRules, TRAIT, access)
    }
//    matchRules = addCondition(matchRules, TRAIT)
    for (access <- scalaAccessModifiersValues) {
      matchRules = addCondition(matchRules, CLASS, access, ABSTRACT, SEALED)
    }
    for (access <- scalaAccessModifiersValues) {
      matchRules = addCondition(matchRules, CLASS, access, ABSTRACT)
    }
    for (access <- scalaAccessModifiersValues) {
      matchRules = addCondition(matchRules, CLASS, access, SEALED)
    }
    for (access <- scalaAccessModifiersValues) {
      matchRules = addCondition(matchRules, CLASS, access)
    }
//    matchRules = addCondition(matchRules, CLASS)
    //TODO: Is 'override' ok for macros?

    new StdArrangementSettings(groupingRules, matchRules.reverse)
  }

  private val defaultSettings = getDefaultSettings

  private val SETTINGS_SERIALIZER = new DefaultArrangementSettingsSerializer(new ScalaSettingsSerializerMixin(), defaultSettings)

}


text:
This is a plugin for the moment.js JavaScript library, to display date/time ranges precisely, in a human-readable format.

Moment already contains some support for formatting date/time ranges, however it performs a lot of 'rounding' on the result and yields only an approximate description.

In the example below the difference between the 2 dates is 1 month, 2 days, 3 hours, 4 minutes and 5 seconds exactly, however this is simplified to just 'a month' by the library.

    var m1 = moment('2014-01-01 12:00:00','YYYY-MM-DD HH:mm:ss');
    var m2 = moment('2014-02-03 15:04:05','YYYY-MM-DD HH:mm:ss');
    var diff = moment.duration(m1.diff(m2)).humanize(); // 'a month'

Using the plugin, we can display the exact difference using the same 2 dates:

    var m1 = moment('2014-01-01 12:00:00','YYYY-MM-DD HH:mm:ss');
    var m2 = moment('2014-02-03 15:04:05','YYYY-MM-DD HH:mm:ss');
    var diff = moment.preciseDiff(m1, m2); // '1 month 2 days 3 hours 4 minutes 5 seconds'

To obtain the numeric values rather than a string, pass the value `true` as the third argument to the method:

    var diff = moment.preciseDiff(m1, m2, true); // {years : 0, months : 1, days : 2, hours : 3, minutes : 4, seconds : 5}

## Usage

### HTML/Browser

To use the plugin in a web page, add a `<script>` tag referencing the moment-precise-range.js file, ensuring that the tag appears
after the tag used to include the moment.js library:

### Node.js

To use the plugin within a node.js application, add the following `require` statement into your code:

    require('moment-precise-range-plugin');

You can try out the Node package online at tonicdev


text:
package org.apache.logging.log4j.core.appender.rolling;

import java.io.File;
import java.security.SecureRandom;
import java.util.Random;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.test.junit.LoggerContextRule;
import org.hamcrest.Matcher;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;

import static org.apache.logging.log4j.core.test.hamcrest.Descriptors.that;
import static org.apache.logging.log4j.core.test.hamcrest.FileMatchers.hasName;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.hasItemInArray;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

/**
 *
 */
public class RollingAppenderCronEvery2DirectTest {

    private static final String CONFIG = "log4j-rolling-cron-every2-direct.xml";
    private static final String DIR = "target/rolling-cron-every2Direct";
    private static final int LOOP_COUNT = 100;

    private final LoggerContextRule loggerContextRule = LoggerContextRule.createShutdownTimeoutLoggerContextRule(CONFIG);

    @Rule
    public RuleChain chain = loggerContextRule.withCleanFoldersRule(DIR);

    @Test
    public void testAppender() throws Exception {
        // TODO Is there a better way to test than putting the thread to sleep all over the place?
        final Logger logger = loggerContextRule.getLogger();
        final long end = System.currentTimeMillis() + 5000;
        final Random rand = new SecureRandom();
        rand.setSeed(end);
        int count = 1;
        do {
            logger.debug("Log Message {}", count++);
            Thread.sleep(10 * rand.nextInt(100));
        } while (System.currentTimeMillis() < end);
        final File dir = new File(DIR);
        assertTrue("Directory not created", dir.exists() && dir.listFiles().length > 0);

        final int MAX_TRIES = 20;
        final Matcher<File[]> hasGzippedFile = hasItemInArray(that(hasName(that(endsWith(".gz")))));
        boolean succeeded = false;
        for (int i = 0; i < MAX_TRIES; i++) {
            final File[] files = dir.listFiles();
            if (hasGzippedFile.matches(files)) {
                succeeded = true;
                break;
            }
            logger.debug("Sleeping #" + i);
            Thread.sleep(100); // Allow time for rollover to complete
        }
        if (!succeeded) {
            final File[] files = dir.listFiles();
            for (final File dirFile : files) {
                logger.error("Found file: " + dirFile.getPath());
            }
            fail("No compressed files found");
        }
    }

}


text:
//
// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// 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.
//

// Module dependencies.
var azureCommon = require('azure-common');
var azureutil = azureCommon.util;
var Constants = azureCommon.Constants;
var TableConstants = Constants.TableConstants;

/**
* Creates a new QueryTablesResultContinuation object.
*/
function QueryTablesResultContinuation(tableService, nextTableName) {
  if (tableService) {
    this.tableService = tableService;
  }

  if (nextTableName) {
    this.nextTableName = nextTableName;
  }
}

QueryTablesResultContinuation.parse = function (tableService, response) {
  var queryTablesResult = new QueryTablesResultContinuation(tableService);

  if (response.headers[TableConstants.CONTINUATION_NEXT_TABLE_NAME] &&
      !azureutil.objectIsEmpty(response.headers[TableConstants.CONTINUATION_NEXT_TABLE_NAME])) {
    queryTablesResult.nextTableName = response.headers[TableConstants.CONTINUATION_NEXT_TABLE_NAME];
  }

  return queryTablesResult;
};

QueryTablesResultContinuation.prototype.getNextPage = function (callback) {
  if (this.nextTableName) {
    this.tableService.queryTables({ nextTableName: this.nextTableName }, callback);
  } else {
    callback(new Error('No next page.'));
  }
};

QueryTablesResultContinuation.prototype.hasNextPage = function () {
  return (this.nextTableName !== undefined && this.nextTableName !== null);
};

module.exports = QueryTablesResultContinuation;


text:
module Sass::Tree
  # A static node representing an unproccessed Sass `@`-directive.
  # Directives known to Sass, like `@for` and `@debug`,
  # are handled by their own nodes;
  # only CSS directives like `@media` and `@font-face` become {DirectiveNode}s.
  #
  # `@import` and `@charset` are special cases;
  # they become {ImportNode}s and {CharsetNode}s, respectively.
  #
  # @see Sass::Tree
  class DirectiveNode < Node
    # The text of the directive, `@` and all.
    #
    # @return [String]
    attr_accessor :value

    # @param value [String] See \{#value}
    def initialize(value)
      @value = value
      super()
    end

    protected

    # @see Node#to_src
    def to_src(tabs, opts, fmt)
      res = "#{'  ' * tabs}#{value}"
      return res + "#{semi fmt}\n" unless has_children
      res + children_to_src(tabs, opts, fmt) + "\n"
    end

    # Computes the CSS for the directive.
    #
    # @param tabs [Fixnum] The level of indentation for the CSS
    # @return [String] The resulting CSS
    def _to_s(tabs)
      return value + ";" unless has_children
      return value + " {}" if children.empty?
      result = if style == :compressed
                 "#{value}{"
               else
                 "#{'  ' * (tabs - 1)}#{value} {" + (style == :compact ? ' ' : "\n")
               end
      was_prop = false
      first = true
      children.each do |child|
        next if child.invisible?
        if style == :compact
          if child.is_a?(PropNode)
            result << "#{child.to_s(first || was_prop ? 1 : tabs + 1)} "
          else
            if was_prop
              result[-1] = "\n"
            end
            rendered = child.to_s(tabs + 1).dup
            rendered = rendered.lstrip if first
            result << rendered.rstrip + "\n"
          end
          was_prop = child.is_a?(PropNode)
          first = false
        elsif style == :compressed
          result << (was_prop ? ";#{child.to_s(1)}" : child.to_s(1))
          was_prop = child.is_a?(PropNode)
        else
          result << child.to_s(tabs + 1) + "\n"
        end
      end
      result.rstrip + if style == :compressed
                        "}"
                      else
                        (style == :expanded ? "\n" : " ") + "}\n"
                      end
    end
  end
end


text:
cask 'anvil' do
  version '1.1.8,132'
  sha256 '485fd6cdd21edbbb2c3801fa0f4a5f6a4ef7da65316946ef5599497c676d6b68'

  # sparkler.herokuapp.com/apps/3/versions was verified as official when first introduced to the cask
  url "https://sparkler.herokuapp.com/apps/3/versions/#{version.after_comma}/download"
  appcast 'https://sparkler.herokuapp.com/apps/3/updates.xml'
  name 'Anvil'
  homepage 'https://anvilformac.com/'

  app 'Anvil.app'
end


text:
<template name="textEdit">
  {{i18nTooltips}}
  {{#with safeExercise this}}

      {{#if _id}}

{{#linkTo route="home"}}{{i18n "layout.homeTitle"}}{{/linkTo}}

{{#linkTo route="exerciseSearch" data=exerciseSearchData}}{{i18nProgrammingLanguage programmingLanguage}}{{/linkTo}}

{{#linkTo route="categoryExercises" data=category}}{{i18nCategoryName category author_id}}{{/linkTo}}

{{i18nDifficulty difficulty}}

{{#linkTo route="exerciseSolve" data=this}}{{i18nName this}}{{/linkTo}}

{{i18n "exercise.editBreadcrumb"}}

{{i18n "exercise.editTitle" (i18nName this)}}

      {{else}}

{{i18n "exercise.createTitle"}}

      {{/if}}

    {{#if _id}}
      {{#if author_id}}

            {{i18n "form.createdBy"}} {{userName author_id}}
            {{#if lastEditor_id}}
              — {{i18n "form.editedBy"}} {{userName lastEditor_id}} {{i18n "form.actionAt"}} {{i18nDateTime lastEdited}}
            {{/if}}

      {{/if}}
    {{/if}}

          {{#each i18nExerciseNamesDescriptions}}

{{language}}

          {{/each}}

          {{i18n "exercise.programmingLanguageLabel"}}
          <select id="select-language" class="form-control" disabled={{_id}}>
            <option value="">{{i18n "form.selectPleaseChoose"}}</option>
            {{#each i18nProgrammingLanguages}}
              <option value="{{_id}}" selected={{isActive}}>{{name}}</option>
            {{/each}}
          </select>

          {{i18n "exercise.categoryLabel"}}
          {{#if isAdmin}}
            {{#if categoryEditData}}
              — {{#linkTo route="categoryEdit" data=categoryEditData}}{{i18n "category.editButton"}}{{/linkTo}}
            {{/if}}
            — {{#linkTo route="categoryCreate"}}{{i18n "category.createButton"}}{{/linkTo}}
          {{/if}}
          <select id="select-category" class="form-control">
            <option value="">{{i18n "form.selectPleaseChoose"}}</option>
            {{#each i18nCategories}}
              <option value="{{_id}}" selected={{isActive}}>{{name}}</option>
            {{/each}}
          </select>

          {{i18n "exercise.difficultyLabel"}}
          <select id="select-difficulty" class="form-control">
            <option value="0">{{i18n "form.selectPleaseChoose"}}</option>
            {{#each i18nDifficulties}}
              <option value="{{_id}}" selected={{isActive}}>{{name}}</option>
            {{/each}}
          </select>

            {{#each i18nExerciseNamesDescriptions}}

{{language}}

            {{/each}}

          {{#each i18nExerciseNamesDescriptions}}

                {{i18n "exercise.nameLabel"}} ({{_id}})
                <input type="text" id="input-name-{{_id}}" class="form-control" value="{{name}}" />

                  {{i18n "exercise.descriptionLabel"}} ({{_id}})

										—
                     {{! https://help.github.com/articles/basic-writing-and-formatting-syntax/#styling-text }}
                    {{i18n "form.supportsMarkdown"}}

                <textarea id="textarea-description-{{_id}}" rows="5" cols="40" class="form-control">{{description}}</textarea>

          {{/each}}

{{i18n "exercise.solutionSubtitle"}}

            {{i18n "exercise.solutionPatternLabel"}}

          <input type="text" id="input-pattern" class="form-control" value="{{pattern}}" />

        {{#if pattern}}

            {{i18n "exercise.solutionLabel"}}

          {{#each solution}}

                  <input type="text" class="input-solution form-control" value="{{value}}" />

                <button class="btn btn-success btn-sm btn-add-solution" title="{{i18n "form.addButton"}}" data-toggle="tooltip"></button>
                <button class="btn btn-danger btn-sm btn-remove-solution" title="{{i18n "form.removeButton"}}" data-toggle="tooltip"></button>

          {{/each}}
        {{else}}

              {{i18n "exercise.solutionLabel"}}

            {{#with (solution.[0])}}
              <textarea id="textarea-solution" class="input-solution form-control" rows="5" cols="40">{{value}}</textarea>
            {{/with}}

        {{/if}}

            <input type="checkbox" id="checkbox-solution-visible" checked={{solutionVisible}}> {{i18n "exercise.showSolutionLabel"}}

      {{#if canSave}}

          <button class="btn btn-success btn-save">{{i18n "form.saveButton"}}</button>
          {{#if _id}}
            {{#linkTo route="exerciseSolve" data=this class="btn btn-warning"}}{{i18n "form.cancelButton"}}{{/linkTo}}
            <button class="btn btn-danger btn-delete">{{i18n "form.deleteButton"}}</button>
          {{/if}}

      {{/if}}
      {{#if _id}}

          {{#if canSave}}
            {{#unless (released.requested)}}
              <button class="btn btn-info btn-release-request">{{i18n "exercise.releaseRequestButton"}}</button>
            {{/unless}}
          {{/if}}
          {{#linkTo route="exerciseCreate" query=exerciseDuplicateQuery class="btn btn-info"}}{{i18n "exercise.duplicateButton"}}{{/linkTo}}
          <button class="btn btn-info btn-export">{{i18n "exercise.exportButton"}}</button>

      {{/if}}

    {{#unless canSave}}

{{i18n "form.cannotSaveMessage"}}

    {{/unless}}
  {{/with}}
</template>