text:
module TypeScript {
    export class SyntaxWalker implements ISyntaxVisitor {
        public visitToken(token: ISyntaxToken): void {
        }

        public visitNode(node: SyntaxNode): void {
            node.accept(this);
        }

        public visitNodeOrToken(nodeOrToken: ISyntaxNodeOrToken): void {
            if (nodeOrToken.isToken()) {
                this.visitToken(<ISyntaxToken>nodeOrToken);
            }
            else {
                this.visitNode(<SyntaxNode>nodeOrToken);
            }
        }

        private visitOptionalToken(token: ISyntaxToken): void {
            if (token === null) {
                return;
            }

            this.visitToken(token);
        }

        public visitOptionalNode(node: SyntaxNode): void {
            if (node === null) {
                return;
            }

            this.visitNode(node);
        }

        public visitOptionalNodeOrToken(nodeOrToken: ISyntaxNodeOrToken): void {
            if (nodeOrToken === null) {
                return;
            }

            this.visitNodeOrToken(nodeOrToken);
        }

        public visitList(list: ISyntaxList): void {
            for (var i = 0, n = list.childCount(); i < n; i++) {
               this.visitNodeOrToken(list.childAt(i));
            }
        }

        public visitSeparatedList(list: ISeparatedSyntaxList): void {
            for (var i = 0, n = list.childCount(); i < n; i++) {
                var item = list.childAt(i);
                this.visitNodeOrToken(item);
            }
        }

        public visitSourceUnit(node: SourceUnitSyntax): void {
            this.visitList(node.moduleElements);
            this.visitToken(node.endOfFileToken);
        }

        public visitExternalModuleReference(node: ExternalModuleReferenceSyntax): void {
            this.visitToken(node.requireKeyword);
            this.visitToken(node.openParenToken);
            this.visitToken(node.stringLiteral);
            this.visitToken(node.closeParenToken);
        }

        public visitModuleNameModuleReference(node: ModuleNameModuleReferenceSyntax): void {
            this.visitNodeOrToken(node.moduleName);
        }

        public visitImportDeclaration(node: ImportDeclarationSyntax): void {
            this.visitList(node.modifiers);
            this.visitToken(node.importKeyword);
            this.visitToken(node.identifier);
            this.visitToken(node.equalsToken);
            this.visitNodeOrToken(node.moduleReference);
            this.visitToken(node.semicolonToken);
        }

        public visitExportAssignment(node: ExportAssignmentSyntax): void {
            this.visitToken(node.exportKeyword);
            this.visitToken(node.equalsToken);
            this.visitToken(node.identifier);
            this.visitToken(node.semicolonToken);
        }

        public visitClassDeclaration(node: ClassDeclarationSyntax): void {
            this.visitList(node.modifiers);
            this.visitToken(node.classKeyword);
            this.visitToken(node.identifier);
            this.visitOptionalNode(node.typeParameterList);
            this.visitList(node.heritageClauses);
            this.visitToken(node.openBraceToken);
            this.visitList(node.classElements);
            this.visitToken(node.closeBraceToken);
        }

        public visitInterfaceDeclaration(node: InterfaceDeclarationSyntax): void {
            this.visitList(node.modifiers);
            this.visitToken(node.interfaceKeyword);
            this.visitToken(node.identifier);
            this.visitOptionalNode(node.typeParameterList);
            this.visitList(node.heritageClauses);
            this.visitNode(node.body);
        }

        public visitHeritageClause(node: HeritageClauseSyntax): void {
            this.visitToken(node.extendsOrImplementsKeyword);
            this.visitSeparatedList(node.typeNames);
        }

        public visitModuleDeclaration(node: ModuleDeclarationSyntax): void {
            this.visitList(node.modifiers);
            this.visitToken(node.moduleKeyword);
            this.visitOptionalNodeOrToken(node.name);
            this.visitOptionalToken(node.stringLiteral);
            this.visitToken(node.openBraceToken);
            this.visitList(node.moduleElements);
            this.visitToken(node.closeBraceToken);
        }

        public visitFunctionDeclaration(node: FunctionDeclarationSyntax): void {
            this.visitList(node.modifiers);
            this.visitToken(node.functionKeyword);
            this.visitToken(node.identifier);
            this.visitNode(node.callSignature);
            this.visitOptionalNode(node.block);
            this.visitOptionalToken(node.semicolonToken);
        }

        public visitVariableStatement(node: VariableStatementSyntax): void {
            this.visitList(node.modifiers);
            this.visitNode(node.variableDeclaration);
            this.visitToken(node.semicolonToken);
        }

        public visitVariableDeclaration(node: VariableDeclarationSyntax): void {
            this.visitToken(node.varKeyword);
            this.visitSeparatedList(node.variableDeclarators);
        }

        public visitVariableDeclarator(node: VariableDeclaratorSyntax): void {
            this.visitToken(node.propertyName);
            this.visitOptionalNode(node.typeAnnotation);
            this.visitOptionalNode(node.equalsValueClause);
        }

        public visitEqualsValueClause(node: EqualsValueClauseSyntax): void {
            this.visitToken(node.equalsToken);
            this.visitNodeOrToken(node.value);
        }

        public visitPrefixUnaryExpression(node: PrefixUnaryExpressionSyntax): void {
            this.visitToken(node.operatorToken);
            this.visitNodeOrToken(node.operand);
        }

        public visitArrayLiteralExpression(node: ArrayLiteralExpressionSyntax): void {
            this.visitToken(node.openBracketToken);
            this.visitSeparatedList(node.expressions);
            this.visitToken(node.closeBracketToken);
        }

        public visitOmittedExpression(node: OmittedExpressionSyntax): void {
        }

        public visitParenthesizedExpression(node: ParenthesizedExpressionSyntax): void {
            this.visitToken(node.openParenToken);
            this.visitNodeOrToken(node.expression);
            this.visitToken(node.closeParenToken);
        }

        public visitSimpleArrowFunctionExpression(node: SimpleArrowFunctionExpressionSyntax): void {
            this.visitToken(node.identifier);
            this.visitToken(node.equalsGreaterThanToken);
            this.visitOptionalNode(node.block);
            this.visitOptionalNodeOrToken(node.expression);
        }

        public visitParenthesizedArrowFunctionExpression(node: ParenthesizedArrowFunctionExpressionSyntax): void {
            this.visitNode(node.callSignature);
            this.visitToken(node.equalsGreaterThanToken);
            this.visitOptionalNode(node.block);
            this.visitOptionalNodeOrToken(node.expression);
        }

        public visitQualifiedName(node: QualifiedNameSyntax): void {
            this.visitNodeOrToken(node.left);
            this.visitToken(node.dotToken);
            this.visitToken(node.right);
        }

        public visitTypeArgumentList(node: TypeArgumentListSyntax): void {
            this.visitToken(node.lessThanToken);
            this.visitSeparatedList(node.typeArguments);
            this.visitToken(node.greaterThanToken);
        }

        public visitConstructorType(node: ConstructorTypeSyntax): void {
            this.visitToken(node.newKeyword);
            this.visitOptionalNode(node.typeParameterList);
            this.visitNode(node.parameterList);
            this.visitToken(node.equalsGreaterThanToken);
            this.visitNodeOrToken(node.type);
        }

        public visitFunctionType(node: FunctionTypeSyntax): void {
            this.visitOptionalNode(node.typeParameterList);
            this.visitNode(node.parameterList);
            this.visitToken(node.equalsGreaterThanToken);
            this.visitNodeOrToken(node.type);
        }

        public visitObjectType(node: ObjectTypeSyntax): void {
            this.visitToken(node.openBraceToken);
            this.visitSeparatedList(node.typeMembers);
            this.visitToken(node.closeBraceToken);
        }

        public visitArrayType(node: ArrayTypeSyntax): void {
            this.visitNodeOrToken(node.type);
            this.visitToken(node.openBracketToken);
            this.visitToken(node.closeBracketToken);
        }

        public visitGenericType(node: GenericTypeSyntax): void {
            this.visitNodeOrToken(node.name);
            this.visitNode(node.typeArgumentList);
        }

        public visitTypeQuery(node: TypeQuerySyntax): void {
            this.visitToken(node.typeOfKeyword);
            this.visitNodeOrToken(node.name);
        }

        public visitTypeAnnotation(node: TypeAnnotationSyntax): void {
            this.visitToken(node.colonToken);
            this.visitNodeOrToken(node.type);
        }

        public visitBlock(node: BlockSyntax): void {
            this.visitToken(node.openBraceToken);
            this.visitList(node.statements);
            this.visitToken(node.closeBraceToken);
        }

        public visitParameter(node: ParameterSyntax): void {
            this.visitOptionalToken(node.dotDotDotToken);
            this.visitList(node.modifiers);
            this.visitToken(node.identifier);
            this.visitOptionalToken(node.questionToken);
            this.visitOptionalNode(node.typeAnnotation);
            this.visitOptionalNode(node.equalsValueClause);
        }

        public visitMemberAccessExpression(node: MemberAccessExpressionSyntax): void {
            this.visitNodeOrToken(node.expression);
            this.visitToken(node.dotToken);
            this.visitToken(node.name);
        }

        public visitPostfixUnaryExpression(node: PostfixUnaryExpressionSyntax): void {
            this.visitNodeOrToken(node.operand);
            this.visitToken(node.operatorToken);
        }

        public visitElementAccessExpression(node: ElementAccessExpressionSyntax): void {
            this.visitNodeOrToken(node.expression);
            this.visitToken(node.openBracketToken);
            this.visitNodeOrToken(node.argumentExpression);
            this.visitToken(node.closeBracketToken);
        }

        public visitInvocationExpression(node: InvocationExpressionSyntax): void {
            this.visitNodeOrToken(node.expression);
            this.visitNode(node.argumentList);
        }

        public visitArgumentList(node: ArgumentListSyntax): void {
            this.visitOptionalNode(node.typeArgumentList);
            this.visitToken(node.openParenToken);
            this.visitSeparatedList(node.arguments);
            this.visitToken(node.closeParenToken);
        }

        public visitBinaryExpression(node: BinaryExpressionSyntax): void {
            this.visitNodeOrToken(node.left);
            this.visitToken(node.operatorToken);
            this.visitNodeOrToken(node.right);
        }

        public visitConditionalExpression(node: ConditionalExpressionSyntax): void {
            this.visitNodeOrToken(node.condition);
            this.visitToken(node.questionToken);
            this.visitNodeOrToken(node.whenTrue);
            this.visitToken(node.colonToken);
            this.visitNodeOrToken(node.whenFalse);
        }

        public visitConstructSignature(node: ConstructSignatureSyntax): void {
            this.visitToken(node.newKeyword);
            this.visitNode(node.callSignature);
        }

        public visitMethodSignature(node: MethodSignatureSyntax): void {
            this.visitToken(node.propertyName);
            this.visitOptionalToken(node.questionToken);
            this.visitNode(node.callSignature);
        }

        public visitIndexSignature(node: IndexSignatureSyntax): void {
            this.visitToken(node.openBracketToken);
            this.visitNode(node.parameter);
            this.visitToken(node.closeBracketToken);
            this.visitOptionalNode(node.typeAnnotation);
        }

        public visitPropertySignature(node: PropertySignatureSyntax): void {
            this.visitToken(node.propertyName);
            this.visitOptionalToken(node.questionToken);
            this.visitOptionalNode(node.typeAnnotation);
        }

        public visitCallSignature(node: CallSignatureSyntax): void {
            this.visitOptionalNode(node.typeParameterList);
            this.visitNode(node.parameterList);
            this.visitOptionalNode(node.typeAnnotation);
        }

        public visitParameterList(node: ParameterListSyntax): void {
            this.visitToken(node.openParenToken);
            this.visitSeparatedList(node.parameters);
            this.visitToken(node.closeParenToken);
        }

        public visitTypeParameterList(node: TypeParameterListSyntax): void {
            this.visitToken(node.lessThanToken);
            this.visitSeparatedList(node.typeParameters);
            this.visitToken(node.greaterThanToken);
        }

        public visitTypeParameter(node: TypeParameterSyntax): void {
            this.visitToken(node.identifier);
            this.visitOptionalNode(node.constraint);
        }

        public visitConstraint(node: ConstraintSyntax): void {
            this.visitToken(node.extendsKeyword);
            this.visitNodeOrToken(node.type);
        }

        public visitElseClause(node: ElseClauseSyntax): void {
            this.visitToken(node.elseKeyword);
            this.visitNodeOrToken(node.statement);
        }

        public visitIfStatement(node: IfStatementSyntax): void {
            this.visitToken(node.ifKeyword);
            this.visitToken(node.openParenToken);
            this.visitNodeOrToken(node.condition);
            this.visitToken(node.closeParenToken);
            this.visitNodeOrToken(node.statement);
            this.visitOptionalNode(node.elseClause);
        }

        public visitExpressionStatement(node: ExpressionStatementSyntax): void {
            this.visitNodeOrToken(node.expression);
            this.visitToken(node.semicolonToken);
        }

        public visitConstructorDeclaration(node: ConstructorDeclarationSyntax): void {
            this.visitList(node.modifiers);
            this.visitToken(node.constructorKeyword);
            this.visitNode(node.parameterList);
            this.visitOptionalNode(node.block);
            this.visitOptionalToken(node.semicolonToken);
        }

        public visitMemberFunctionDeclaration(node: MemberFunctionDeclarationSyntax): void {
            this.visitList(node.modifiers);
            this.visitToken(node.propertyName);
            this.visitNode(node.callSignature);
            this.visitOptionalNode(node.block);
            this.visitOptionalToken(node.semicolonToken);
        }

        public visitGetAccessor(node: GetAccessorSyntax): void {
            this.visitList(node.modifiers);
            this.visitToken(node.getKeyword);
            this.visitToken(node.propertyName);
            this.visitNode(node.parameterList);
            this.visitOptionalNode(node.typeAnnotation);
            this.visitNode(node.block);
        }

        public visitSetAccessor(node: SetAccessorSyntax): void {
            this.visitList(node.modifiers);
            this.visitToken(node.setKeyword);
            this.visitToken(node.propertyName);
            this.visitNode(node.parameterList);
            this.visitNode(node.block);
        }

        public visitMemberVariableDeclaration(node: MemberVariableDeclarationSyntax): void {
            this.visitList(node.modifiers);
            this.visitNode(node.variableDeclarator);
            this.visitToken(node.semicolonToken);
        }

        public visitIndexMemberDeclaration(node: IndexMemberDeclarationSyntax): void {
            this.visitList(node.modifiers);
            this.visitNode(node.indexSignature);
            this.visitToken(node.semicolonToken);
        }

        public visitThrowStatement(node: ThrowStatementSyntax): void {
            this.visitToken(node.throwKeyword);
            this.visitNodeOrToken(node.expression);
            this.visitToken(node.semicolonToken);
        }

        public visitReturnStatement(node: ReturnStatementSyntax): void {
            this.visitToken(node.returnKeyword);
            this.visitOptionalNodeOrToken(node.expression);
            this.visitToken(node.semicolonToken);
        }

        public visitObjectCreationExpression(node: ObjectCreationExpressionSyntax): void {
            this.visitToken(node.newKeyword);
            this.visitNodeOrToken(node.expression);
            this.visitOptionalNode(node.argumentList);
        }

        public visitSwitchStatement(node: SwitchStatementSyntax): void {
            this.visitToken(node.switchKeyword);
            this.visitToken(node.openParenToken);
            this.visitNodeOrToken(node.expression);
            this.visitToken(node.closeParenToken);
            this.visitToken(node.openBraceToken);
            this.visitList(node.switchClauses);
            this.visitToken(node.closeBraceToken);
        }

        public visitCaseSwitchClause(node: CaseSwitchClauseSyntax): void {
            this.visitToken(node.caseKeyword);
            this.visitNodeOrToken(node.expression);
            this.visitToken(node.colonToken);
            this.visitList(node.statements);
        }

        public visitDefaultSwitchClause(node: DefaultSwitchClauseSyntax): void {
            this.visitToken(node.defaultKeyword);
            this.visitToken(node.colonToken);
            this.visitList(node.statements);
        }

        public visitBreakStatement(node: BreakStatementSyntax): void {
            this.visitToken(node.breakKeyword);
            this.visitOptionalToken(node.identifier);
            this.visitToken(node.semicolonToken);
        }

        public visitContinueStatement(node: ContinueStatementSyntax): void {
            this.visitToken(node.continueKeyword);
            this.visitOptionalToken(node.identifier);
            this.visitToken(node.semicolonToken);
        }

        public visitForStatement(node: ForStatementSyntax): void {
            this.visitToken(node.forKeyword);
            this.visitToken(node.openParenToken);
            this.visitOptionalNode(node.variableDeclaration);
            this.visitOptionalNodeOrToken(node.initializer);
            this.visitToken(node.firstSemicolonToken);
            this.visitOptionalNodeOrToken(node.condition);
            this.visitToken(node.secondSemicolonToken);
            this.visitOptionalNodeOrToken(node.incrementor);
            this.visitToken(node.closeParenToken);
            this.visitNodeOrToken(node.statement);
        }

        public visitForInStatement(node: ForInStatementSyntax): void {
            this.visitToken(node.forKeyword);
            this.visitToken(node.openParenToken);
            this.visitOptionalNode(node.variableDeclaration);
            this.visitOptionalNodeOrToken(node.left);
            this.visitToken(node.inKeyword);
            this.visitNodeOrToken(node.expression);
            this.visitToken(node.closeParenToken);
            this.visitNodeOrToken(node.statement);
        }

        public visitWhileStatement(node: WhileStatementSyntax): void {
            this.visitToken(node.whileKeyword);
            this.visitToken(node.openParenToken);
            this.visitNodeOrToken(node.condition);
            this.visitToken(node.closeParenToken);
            this.visitNodeOrToken(node.statement);
        }

        public visitWithStatement(node: WithStatementSyntax): void {
            this.visitToken(node.withKeyword);
            this.visitToken(node.openParenToken);
            this.visitNodeOrToken(node.condition);
            this.visitToken(node.closeParenToken);
            this.visitNodeOrToken(node.statement);
        }

        public visitEnumDeclaration(node: EnumDeclarationSyntax): void {
            this.visitList(node.modifiers);
            this.visitToken(node.enumKeyword);
            this.visitToken(node.identifier);
            this.visitToken(node.openBraceToken);
            this.visitSeparatedList(node.enumElements);
            this.visitToken(node.closeBraceToken);
        }

        public visitEnumElement(node: EnumElementSyntax): void {
            this.visitToken(node.propertyName);
            this.visitOptionalNode(node.equalsValueClause);
        }

        public visitCastExpression(node: CastExpressionSyntax): void {
            this.visitToken(node.lessThanToken);
            this.visitNodeOrToken(node.type);
            this.visitToken(node.greaterThanToken);
            this.visitNodeOrToken(node.expression);
        }

        public visitObjectLiteralExpression(node: ObjectLiteralExpressionSyntax): void {
            this.visitToken(node.openBraceToken);
            this.visitSeparatedList(node.propertyAssignments);
            this.visitToken(node.closeBraceToken);
        }

        public visitSimplePropertyAssignment(node: SimplePropertyAssignmentSyntax): void {
            this.visitToken(node.propertyName);
            this.visitToken(node.colonToken);
            this.visitNodeOrToken(node.expression);
        }

        public visitFunctionPropertyAssignment(node: FunctionPropertyAssignmentSyntax): void {
            this.visitToken(node.propertyName);
            this.visitNode(node.callSignature);
            this.visitNode(node.block);
        }

        public visitFunctionExpression(node: FunctionExpressionSyntax): void {
            this.visitToken(node.functionKeyword);
            this.visitOptionalToken(node.identifier);
            this.visitNode(node.callSignature);
            this.visitNode(node.block);
        }

        public visitEmptyStatement(node: EmptyStatementSyntax): void {
            this.visitToken(node.semicolonToken);
        }

        public visitTryStatement(node: TryStatementSyntax): void {
            this.visitToken(node.tryKeyword);
            this.visitNode(node.block);
            this.visitOptionalNode(node.catchClause);
            this.visitOptionalNode(node.finallyClause);
        }

        public visitCatchClause(node: CatchClauseSyntax): void {
            this.visitToken(node.catchKeyword);
            this.visitToken(node.openParenToken);
            this.visitToken(node.identifier);
            this.visitOptionalNode(node.typeAnnotation);
            this.visitToken(node.closeParenToken);
            this.visitNode(node.block);
        }

        public visitFinallyClause(node: FinallyClauseSyntax): void {
            this.visitToken(node.finallyKeyword);
            this.visitNode(node.block);
        }

        public visitLabeledStatement(node: LabeledStatementSyntax): void {
            this.visitToken(node.identifier);
            this.visitToken(node.colonToken);
            this.visitNodeOrToken(node.statement);
        }

        public visitDoStatement(node: DoStatementSyntax): void {
            this.visitToken(node.doKeyword);
            this.visitNodeOrToken(node.statement);
            this.visitToken(node.whileKeyword);
            this.visitToken(node.openParenToken);
            this.visitNodeOrToken(node.condition);
            this.visitToken(node.closeParenToken);
            this.visitToken(node.semicolonToken);
        }

        public visitTypeOfExpression(node: TypeOfExpressionSyntax): void {
            this.visitToken(node.typeOfKeyword);
            this.visitNodeOrToken(node.expression);
        }

        public visitDeleteExpression(node: DeleteExpressionSyntax): void {
            this.visitToken(node.deleteKeyword);
            this.visitNodeOrToken(node.expression);
        }

        public visitVoidExpression(node: VoidExpressionSyntax): void {
            this.visitToken(node.voidKeyword);
            this.visitNodeOrToken(node.expression);
        }

        public visitDebuggerStatement(node: DebuggerStatementSyntax): void {
            this.visitToken(node.debuggerKeyword);
            this.visitToken(node.semicolonToken);
        }
    }
}


text:
package org.drools.core.reteoo;

import org.drools.core.common.InternalFactHandle;
import org.drools.core.spi.PropagationContext;

public class QueryRiaFixerNodeLeftTuple extends BaseLeftTuple {
    private static final long  serialVersionUID = 540l;

    public QueryRiaFixerNodeLeftTuple() {
        // constructor needed for serialisation
    }

    // ------------------------------------------------------------
    // Constructors
    // ------------------------------------------------------------
    public QueryRiaFixerNodeLeftTuple(final InternalFactHandle factHandle,
                                      final Sink sink,
                                      final boolean leftTupleMemoryEnabled) {
        super( factHandle,
               sink,
               leftTupleMemoryEnabled );
    }

    public QueryRiaFixerNodeLeftTuple(final LeftTuple leftTuple,
                                      final Sink sink,
                                      final PropagationContext pctx,
                                      final boolean leftTupleMemoryEnabled) {
        super( leftTuple,
               sink,
               pctx,
               leftTupleMemoryEnabled );
    }

    public QueryRiaFixerNodeLeftTuple(final LeftTuple leftTuple,
                                      final RightTuple rightTuple,
                                      final Sink sink) {
        super( leftTuple,
               rightTuple,
               sink );
    }

    public QueryRiaFixerNodeLeftTuple(final LeftTuple leftTuple,
                                      final RightTuple rightTuple,
                                      final Sink sink,
                                      final boolean leftTupleMemoryEnabled) {
        this( leftTuple,
              rightTuple,
              null,
              null,
              sink,
              leftTupleMemoryEnabled );
    }

    public QueryRiaFixerNodeLeftTuple(final LeftTuple leftTuple,
                                      final RightTuple rightTuple,
                                      final LeftTuple currentLeftChild,
                                      final LeftTuple currentRightChild,
                                      final Sink sink,
                                      final boolean leftTupleMemoryEnabled) {
        super( leftTuple,
               rightTuple,
               currentLeftChild,
               currentRightChild,
               sink,
               leftTupleMemoryEnabled );
    }

}

redpajama_set_name: RedPajamaGithub


text:
var assert = require('assert');
var common = require('../../common');

var server = common.createFakeServer();

server.listen(0, function (err) {
  assert.ifError(err);

  var pool = common.createPool({port: server.port()});

  pool.getConnection(function (err, connection) {
    assert.ifError(err);

    assert.strictEqual(connection, pool._allConnections[0]);
    connection.destroy();

    assert.strictEqual(pool._allConnections.length, 0);
    assert.ok(!connection._pool);

    assert.doesNotThrow(function () { connection.release(); });

    server.destroy();
  });
});


text:
package gen

import (
	"github.com/leanovate/gopter"
)

type int64Shrink struct {
	original int64
	half     int64
}

func (s *int64Shrink) Next() (interface{}, bool) {
	if s.half == 0 {
		return nil, false
	}
	value := s.original - s.half
	s.half /= 2
	return value, true
}

type uint64Shrink struct {
	original uint64
	half     uint64
}

func (s *uint64Shrink) Next() (interface{}, bool) {
	if s.half == 0 {
		return nil, false
	}
	value := s.original - s.half
	s.half >>= 1
	return value, true
}

// Int64Shrinker is a shrinker for int64 numbers
func Int64Shrinker(v interface{}) gopter.Shrink {
	negShrink := int64Shrink{
		original: -v.(int64),
		half:     -v.(int64),
	}
	posShrink := int64Shrink{
		original: v.(int64),
		half:     v.(int64) / 2,
	}
	return gopter.Shrink(negShrink.Next).Interleave(gopter.Shrink(posShrink.Next))
}

// UInt64Shrinker is a shrinker for uint64 numbers
func UInt64Shrinker(v interface{}) gopter.Shrink {
	shrink := uint64Shrink{
		original: v.(uint64),
		half:     v.(uint64),
	}
	return shrink.Next
}

// Int32Shrinker is a shrinker for int32 numbers
func Int32Shrinker(v interface{}) gopter.Shrink {
	return Int64Shrinker(int64(v.(int32))).Map(int64To32)
}

// UInt32Shrinker is a shrinker for uint32 numbers
func UInt32Shrinker(v interface{}) gopter.Shrink {
	return UInt64Shrinker(uint64(v.(uint32))).Map(uint64To32)
}

// Int16Shrinker is a shrinker for int16 numbers
func Int16Shrinker(v interface{}) gopter.Shrink {
	return Int64Shrinker(int64(v.(int16))).Map(int64To16)
}

// UInt16Shrinker is a shrinker for uint16 numbers
func UInt16Shrinker(v interface{}) gopter.Shrink {
	return UInt64Shrinker(uint64(v.(uint16))).Map(uint64To16)
}

// Int8Shrinker is a shrinker for int8 numbers
func Int8Shrinker(v interface{}) gopter.Shrink {
	return Int64Shrinker(int64(v.(int8))).Map(int64To8)
}

// UInt8Shrinker is a shrinker for uint8 numbers
func UInt8Shrinker(v interface{}) gopter.Shrink {
	return UInt64Shrinker(uint64(v.(uint8))).Map(uint64To8)
}

// IntShrinker is a shrinker for int numbers
func IntShrinker(v interface{}) gopter.Shrink {
	return Int64Shrinker(int64(v.(int))).Map(int64ToInt)
}

// UIntShrinker is a shrinker for uint numbers
func UIntShrinker(v interface{}) gopter.Shrink {
	return UInt64Shrinker(uint64(v.(uint))).Map(uint64ToUint)
}


text:
import socket
import httplib, urllib

TCP_ADDR = 'x.x.x.x'
TCP_PORT = 8899

PACK_LEN = 11

API_KEY = 'xxxx'

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.settimeout(30)

while True: #keep trying forever

    try:
        s.close()
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(30)
        s.connect((TCP_ADDR, TCP_PORT))

        while True:
            bytes_data = zeros(PACK_LEN,int)
            str_data = s.recv(PACK_LEN) #this should probably have a timeout
            hex_data = str_data.encode('hex')
            if len(hex_data)<>22:
                hex_data = '0000000000000000000011'
                raise Exception("Error reading data")

            for n in range(0,PACK_LEN): #convert to array of bytes
                lower = 2*n
                upper = lower + 2
                bytes_data[n] = int(hex_data[lower:upper],16)

            humid =  (((bytes_data[6])<<8)+(bytes_data[7]))/10.0
            temp =  (((((bytes_data[8])&0x7F)<<8)+(bytes_data[9]))/10.0)

            if int(bytes_data[8]) & 0x80: #invert temp if sign bit is set
                temp = -1.0* temp

            checksum = (uint(sum(bytes_data[0:10])) & 0xFF)+1

            if checksum == bytes_data[10]:
                print "Valid!"
                print "Temp: " + str(temp)
                print "Hum: " + str(humid)

                params = urllib.urlencode({'field1': temp, 'field2': humid,'key':API_KEY})
                headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}
                conn = httplib.HTTPConnection("api.thingspeak.com:80")
                conn.request("POST", "/update", params, headers)
                response = conn.getresponse()
                print response.status, response.reason
                data = response.read()
                conn.close()

            else:
                print "Invalid. :("
    except:
        print "Error ocurred, restarting"


text:
set -e
set -u

cd /build

go install github.com/google/addlicense@v1.1.0
ln -s $(go env GOPATH)/bin/addlicense /usr/local/bin/


text:
using System;
using System.Linq;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Localisation;
using osu.Game.Graphics;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Scoring;

namespace osu.Game.Rulesets.Mods
{
    public abstract class ModPerfect : ModFailCondition
    {
        public override string Name => "Perfect";
        public override string Acronym => "PF";
        public override IconUsage? Icon => OsuIcon.ModPerfect;
        public override ModType Type => ModType.DifficultyIncrease;
        public override double ScoreMultiplier => 1;
        public override LocalisableString Description => "SS or quit.";

        public override Type[] IncompatibleMods => base.IncompatibleMods.Append(typeof(ModSuddenDeath)).ToArray();

        protected ModPerfect()
        {
            Restart.Value = Restart.Default = true;
        }

        protected override bool FailCondition(HealthProcessor healthProcessor, JudgementResult result)
            => result.Type.AffectsAccuracy()
               && result.Type != result.Judgement.MaxResult;
    }
}


text:
package net.ripe.db.whois.common.grs;

import net.ripe.db.whois.common.jmx.JmxBase;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedOperationParameter;
import org.springframework.jmx.export.annotation.ManagedOperationParameters;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.stereotype.Component;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.Callable;

@Component
@ManagedResource(objectName = JmxBase.OBJECT_NAME_BASE + "AuthoritativeResources", description = "Whois authoritative resource data")
public class AuthoritativeResourceDataJmx extends JmxBase {
    private static final Logger LOGGER = LoggerFactory.getLogger(AuthoritativeResourceDataJmx.class);

    private final AuthoritativeResourceData authoritativeResourceData;
    private final AuthoritativeResourceDataValidator authoritativeResourceDataValidator;

    @Autowired
    public AuthoritativeResourceDataJmx(final AuthoritativeResourceData authoritativeResourceData, final AuthoritativeResourceDataValidator authoritativeResourceDataValidator) {
        super(LOGGER);
        this.authoritativeResourceData = authoritativeResourceData;
        this.authoritativeResourceDataValidator = authoritativeResourceDataValidator;
    }

    @ManagedOperation(description = "Refresh authoritative resource cache")
    @ManagedOperationParameters({
            @ManagedOperationParameter(name = "comment", description = "Optional comment for invoking the operation")
    })
    public String refreshCache(final String comment) {
        return invokeOperation("Refresh authoritative resource cache", comment, new Callable<String>() {
            @Override
            public String call() {
                authoritativeResourceData.refreshAuthoritativeResourceCache();
                return "Refreshed caches";
            }
        });
    }

    @ManagedOperation(description = "Check overlaps in authoritative resource definitions and output to file")
    @ManagedOperationParameters({
            @ManagedOperationParameter(name = "outputFile", description = "The file to write overlaps to"),
            @ManagedOperationParameter(name = "comment", description = "Optional comment for invoking the operation")
    })
    public String checkOverlaps(final String outputFile, final String comment) {
        return invokeOperation(String.format("Writing overlaps to %s", outputFile), comment, new Callable<String>() {
            @Override
            public String call() {
                final File output = new File(outputFile);
                final String absolutePath = output.getAbsolutePath();

                BufferedWriter writer = null;
                try {
                    if (!output.createNewFile()) {
                        return String.format("Abort, file already exists: %s", absolutePath);
                    }

                    writer = new BufferedWriter(new FileWriter(output));
                    authoritativeResourceDataValidator.checkOverlaps(writer);
                } catch (IOException e) {
                    LOGGER.error("Checking overlaps", e);
                    return String.format("Failed writing to: %s, %s", absolutePath, e.getMessage());
                } finally {
                    IOUtils.closeQuietly(writer);
                }

                return String.format("Overlaps written to: %s", absolutePath);
            }
        });
    }
}


text:
class Surface {
	public:
		ThreeDVector* diffuse;
		ThreeDVector* specular;
		ThreeDVector* emission;
		Eigen::Matrix4f transformation;
		Eigen::Matrix4f inverse;
		Eigen::Matrix4f inverse_transpose;
		Bounds* bounds;
		long double power_coefficient;

		virtual bool hit(Ray* ray, Record* record) = 0;
		virtual ThreeDVector* get_normal(ThreeDVector* surface_point, ThreeDVector* view_vector) = 0;
		virtual void apply_transformation(Eigen::Matrix4f transformation) = 0;
		virtual void get_bounds() = 0;
};

#endif


text:
package com.adivi.ncsa.fasttrack.sport;

import java.util.GregorianCalendar;

/**
 * @author devanhalli
 *
 * To change this generated comment edit the template variable "typecomment":
 * Window>Preferences>Java>Templates.
 * To enable and disable the creation of type comments go to
 * Window>Preferences>Java>Code Generation.
 */
public class SportBean {

	private int collegeID;

	private int sportID;

	private int athleticStrength;

	private int divisionID=0;

	private String phoneNumber;

	private String fax;

	private String addr1;

	private String addr2;

	private String addr3;

	private String city;

	private int stateId;

	private String zip;

	private int addressID;

	private int modifyUser = 0;

	private GregorianCalendar calendar = new  GregorianCalendar();
	private long modifyDate = calendar.getTimeInMillis();

	public void setCollegeID (int collegeID) {
		this.collegeID = collegeID;
	}

	public int getCollegeID () {
		return collegeID;
	}

	public void setSportID (int sportID) {
		this.sportID = sportID;
	}

	public int getSportID () {
		return sportID;
	}

	public void setAthleticStrength (int athleticStrength) {
		this.athleticStrength = athleticStrength;
	}

	public int getAthleticStrength () {
		return athleticStrength;
	}

	public void setDivisionID (int divisionID) {
		this.divisionID = divisionID;
	}

	public int getDivisionID () {
		return divisionID;
	}

	public void setPhoneNumber (String phoneNumber) {
		this.phoneNumber = phoneNumber;
	}

	public String getPhoneNumber () {
		return phoneNumber;
	}

	public void setFax (String fax) {
		this.fax = fax;
	}

	public String getFax () {
		return fax;
	}

	public void setAddr1 (String addr1) {
		this.addr1 = addr1;
	}

	public String getAddr1 () {
		return addr1;
	}

	public void setAddr2 (String addr2) {
		this.addr2 = addr2;
	}

	public String getAddr2 () {
		return addr2;
	}

	public void setAddr3 (String addr3) {
		this.addr3 = addr3;
	}

	public String getAddr3 () {
		return addr3;
	}

	public void setCity (String city) {
		this.city = city;
	}

	public String getCity () {
		return city;
	}

	public void setStateId (int stateId) {
		this.stateId = stateId;
	}

	public int getStateId () {
		return stateId;
	}

	public void setZip (String zip) {
		this.zip = zip;
	}

	public String getZip () {
		return zip;
	}

	public void setAddressID (int addressID) {
		this.addressID = addressID;
	}

	public int getAddressID () {
		return addressID;
	}

	/**
	 * Returns the modifyDate.
	 * @return long
	 */
	public long getModifyDate() {
		return modifyDate;
	}

	/**
	 * Returns the modifyUser.
	 * @return int
	 */
	public int getModifyUser() {
		return modifyUser;
	}

	/**
	 * Sets the modifyDate.
	 * @param modifyDate The modifyDate to set
	 */
	public void setModifyDate(long modifyDate) {
		this.modifyDate = modifyDate;
	}

	/**
	 * Sets the modifyUser.
	 * @param modifyUser The modifyUser to set
	 */
	public void setModifyUser(int modifyUser) {
		this.modifyUser = modifyUser;
	}

}


text:
import React from 'react';
import {Input, IconInput} from '../../../src';
import OptionsTable from '../../helper/OptionsTable';

export default () => {
    let propDescription = {
        disabled: {
            values: 'boolean',
            description: 'becomes disabled'
        },
        placeholder: {
            values: 'string',
            description: 'set input placeholder'
        },
        onChange: {
            values: 'function',
            description: 'Is called when a input value is changed'
        }
    };

    return (

Input

            <OptionsTable component={Input} propDescription={propDescription} />

IconInput

            <OptionsTable component={IconInput} propDescription={propDescription} />

    );
};


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:scrollbars="none"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.LinearLayoutCompat
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <android.support.v7.widget.AppCompatImageView
            android:contentDescription="@null"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/bottom_normal_margin_3"
            android:layout_marginBottom="@dimen/bottom_normal_margin_3"
            android:layout_gravity="center_horizontal"
            android:src="@drawable/ic_lock_black_24dp" />
        <View style="@style/TitleBorderBottom"
            android:layout_marginLeft="@dimen/left_normal_margin"
            android:layout_marginRight="@dimen/right_normal_margin"
            android:layout_marginBottom="@dimen/bottom_normal_margin_3" />

        <android.support.v7.widget.AppCompatEditText
            android:id="@+id/edit_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/top_normal_margin"
            android:layout_marginRight="@dimen/right_normal_margin"
            android:layout_marginBottom="@dimen/bottom_normal_margin"
            android:layout_marginLeft="@dimen/left_normal_margin"
            android:textSize="@dimen/normal_text_size"
            android:inputType="textPassword"
            android:hint="@string/unlock_password_hint" />

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/unlock_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="@dimen/normal_text_size"
            android:text="@string/unlock_button" />

    </android.support.v7.widget.LinearLayoutCompat>

</ScrollView>


text:
extern crate chrono;
#[macro_use]
extern crate router;
extern crate url;
#[macro_use]
extern crate slog;
extern crate slog_term;
extern crate slog_async;
#[macro_use]
extern crate maplit;
extern crate unicode_segmentation;
extern crate uuid;
extern crate serde;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde_json;
extern crate atomicwrites;
extern crate fnv;
#[macro_use]
extern crate bitflags;
extern crate roaring;
extern crate byteorder;
extern crate rocksdb;

pub mod search;
pub mod analysis;
pub mod query_parser;
pub mod mapping;
pub mod document;
pub mod index;
pub mod cluster;
pub mod system;
mod api;

use std::path::Path;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use std::panic;

use slog::Drain;

use system::System;

const VERSION: &'static str = env!("CARGO_PKG_VERSION");

fn main() {
    // Setup logging
    let decorator = slog_term::TermDecorator::new().build();
    let drain = slog_term::CompactFormat::new(decorator).build().fuse();
    let drain = slog_async::Async::new(drain).build().fuse();
    let log = slog::Logger::root(drain, o!());

    info!(log, "starting rusticsearch"; "version" => VERSION);

    let system = Arc::new(System::new(log, Path::new("data/").to_path_buf()));

    info!(system.log, "loading indices");
    system.load_indices();

    {
        let system = system.clone();
        thread::spawn(move || {
            loop {
                {
                    let cluster_metadata = system.metadata.read().unwrap();
                    for index in cluster_metadata.indices.values() {
                        let result = panic::catch_unwind(|| {
                            index.run_maintenance_task().unwrap();
                        });

                        if let Err(error) = result {
                            error!(system.log, "index maintenance task panicked"; "index" => index.canonical_name(), "error" => format!("{:?}", error));
                        }
                    }
                }

                thread::sleep(Duration::new(1, 0));
            }
        });
    }

    info!(system.log, "starting api server");
    api::api_main(system);
}


text:
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local')
django.setup()
from box_management.boxes.models import Box, ItemCategory, Item

BOX_KEYS = ['name', 'location']
CATEGORY_KEYS = ['name']
ITEM_KEYS = ['name', 'description', 'box', 'category']

BOX_VALUES = [
    ['Boxinator', 'Keller'],
    ['Rumpelkiste', 'Keller'],
    ['Zeugskarton', 'Keller'],
]

CATEGORY_VALUES = [
    ['Elektronisches'],
    ['Bücher'],
    ['Sonstiges'],
]

def add_box(name, location):
    b = Box.objects.get_or_create(name=name, location=location)[0]
    return b

def add_cat(name):
    c = ItemCategory.objects.get_or_create(name=name)[0]
    return c

def add_item(name, description, box, category):
    i = Item.objects.get_or_create(name=name, description=description, box=box, category=category)
    return i

def populate():
    for box_v in BOX_VALUES:
        add_box(**dict(zip(BOX_KEYS, box_v)))
    for cat_v in CATEGORY_VALUES:
        add_cat(**dict(zip(CATEGORY_KEYS, cat_v)))

    boxinator = Box.objects.get(name='Boxinator')
    rumpelkiste = Box.objects.get(name='Rumpelkiste')
    zeugskarton = Box.objects.get(name='Zeugskarton')
    elektronisches = ItemCategory.objects.get(name='Elektronisches')
    buecher = ItemCategory.objects.get(name='Bücher')
    sonstiges = ItemCategory.objects.get(name='Sonstiges')

    boxielek = [boxinator, elektronisches]
    rumpelbuch = [rumpelkiste, buecher]
    zeugssonst = [zeugskarton, sonstiges]

    item_values = [
        ['Kabel', 'Irgendein Kabel'] + boxielek,
        ['Ethernet Kabel', 'Das Rote(!)'] + boxielek,
        ['Wii controller', 'Ohne Wii Motion Plus'] + boxielek,
        ['Wii Ständer', 'Ist n bisschen eingerissen...'] + boxielek,
        ['NGE Band 1', 'Cooles Zeug dadrin...'] + rumpelbuch,
        ['NGE Band 2', 'Weisheits Lieblingsbuch'] + rumpelbuch,
        ['LTB Nr. 1', 'Neuauflage, aber trotzdem cool.'] + rumpelbuch,
        ['LTB Nr. 145', 'Pauls Favorit'] + rumpelbuch,
        ['Huberts Hut', 'Wie kommt der denn hierein?'] + zeugssonst,
        ['Norayas Bogensehne', 'In nem Raid gerissen'] + zeugssonst,
        ['Ravys Haschpfeife', 'Irgendwie muss man ja ausspannen...'] + zeugssonst,
    ]

    for item_v in item_values:
        add_item(**dict(zip(ITEM_KEYS, item_v)))

    for box in Box.objects.all():
        print("Box {box}:".format(box=box))
        print("-"*20)
        for item in Item.objects.filter(box=box):
            print("{item}".format(item=item))
        print("-"*20)

if __name__ == '__main__':
    print("Start population script...")
    populate()


text:
import { fromJS } from 'immutable';
import isUndefined from 'lodash/isUndefined';

import { matches, keyIn } from '../utils/immutableUtils';
import addMeta, { ARRAY_INDICATOR } from '../utils/meta';

import * as actions from './actions';
import * as groupsActions from '../groups/actions';
import * as rolesActions from '../roles/actions';

///
// Default state
///

const defaultState = fromJS({
	tabsets: [],
	groups: [],
	roles: [],
});

///
// Reducers
///

function root(state = defaultState, action) {
	const handlers = {
		[actions.GET_LIST_DONE]: getListDone,
		[groupsActions.GET_LIST_DONE]: getGroupsListDone,
		[rolesActions.GET_LIST_DONE]: getRolesListDone,
		[actions.ADD_ITEM_DONE]: addItemDone,
		[actions.EDIT_ITEM_DONE]: editItemDone,
		[actions.REMOVE_ITEM_DONE]: removeItemDone,
		[actions.RESTORE_ITEM_DONE]: restoreItemDone,
		default: (state) => state,
	};

	const handler = handlers[action.type] || handlers.default;
	return handler(state, action);
}

export default root;

///
// Delegates
///

function getListDone(state, action) {
	const tabsets = fromJS(action.payload);

	return addMetaToTabsets(state.set('tabsets', tabsets));
}

function getGroupsListDone(state, action) {
	const groups = fromJS(action.payload).filter(group => (
		group.get('tabsets') && group.get('tabsets').size > 0
	));

	return addMetaToGroups(mergeGroups(state, groups));
}

function getRolesListDone(state, action) {
	const allRoles = fromJS(action.payload);

	// Get group-owned roles that have tabsets
	const groupRoles = allRoles.filter(role => (
		! isUndefined(role.getIn(['group', 'id'])) &&
		role.get('tabsets') && role.get('tabsets').size > 0
	));

	state = addMetaToGroupRoles(mergeGroupRoles(state, groupRoles));

	// Get groupless roles that have tabsets
	const roles = allRoles.filter(role => (
		isUndefined(role.getIn(['group', 'id'])) &&
		role.get('tabsets') && role.get('tabsets').size > 0
	));

	return addMetaToRoles(state.set('roles', roles));
}

function addItemDone(state, action) {
	return addMetaToTabsets(
		state.update('tabsets', tabsets => (
			tabsets.push(fromJS(action.payload))
		))
	);
}

function editItemDone(state, action) {
	return state.setIn(
		action.payload._meta.keyPath,
		fromJS(action.payload)
	);
}

function removeItemDone(state, action) {
	return addMetaToAll(
		state.deleteIn(action.payload._meta.keyPath)
	);
}

function restoreItemDone(state, action) {
	const keyPath = fromJS(action.payload._meta.keyPath);
	const key = keyPath.last();
	const listPath = keyPath.skipLast(1).toJS();

	return addMetaToAll(state.updateIn(listPath, list => (
		list.splice(key, 0, fromJS(action.payload))
	)));
}

///
// Helpers
///

function addMetaToAll(state) {
	return addMetaToTabsets(
		addMetaToGroups(
			addMetaToGroupRoles(
				addMetaToRoles(state)
			)
		)
	);
}

function addMetaToTabsets(state) {
	return addMeta(state, [
		'tabsets', ARRAY_INDICATOR,
	]);
}

function addMetaToGroups(state) {
	return addMeta(state, [
		'groups', ARRAY_INDICATOR,
		'tabsets', ARRAY_INDICATOR,
	]);
}

function addMetaToGroupRoles(state) {
	return addMeta(state, [
		'groups', ARRAY_INDICATOR,
		'roles', ARRAY_INDICATOR,
		'tabsets', ARRAY_INDICATOR,
	]);
}

function addMetaToRoles(state) {
	return addMeta(state, [
		'roles', ARRAY_INDICATOR,
		'tabsets', ARRAY_INDICATOR,
	]);
}

function mergeGroups(state, groups) {
	state = state.update('groups', groups => (
		groups.map(group => (
			group.set('tabsets', fromJS([]))
		))
	));

	groups.forEach(group => {
		const groupKey = getGroupKey(state, group);

		if(isUndefined(groupKey)) {
			state = createGroup(state, group);
		} else {
			state = updateGroup(state, groupKey, group);
		}
	});

	return state;
}

function mergeGroupRoles(state, roles) {
	state = state.update('groups', groups => (
		groups.map(group => (
			group.set('roles', fromJS([]))
		))
	));

	roles.forEach(role => {
		const group = role.get('group');
		let groupKey = getGroupKey(state, group);

		if(isUndefined(groupKey)) {
			state = createGroup(state, group);
			groupKey = getGroupKey(state, group);
		}

		let roleKey = getGroupRoleKey(state, groupKey, role);

		if(roleKey) {
			state = updateGroupRole(state, groupKey, roleKey, role);
		} else {
			state = createGroupRole(state, groupKey, role);
		}
	});

	return state;
}

function getGroupKey(state, group) {
	return state.get('groups').findKey(matches({
		id: group.get('id')
	}));
}

function createGroup(state, group) {
	group = group
		.filter(keyIn('id', 'name', 'tabsets'))
		.set('roles', fromJS([]))
		.update('tabsets', tabsets => (
			isUndefined(tabsets) ? fromJS([]) : tabsets
		));

	return state.update('groups', groups => (
		groups.push(group)
	));
}

function updateGroup(state, groupKey, group) {
	return (state
		.setIn(['groups', groupKey, 'name'], group.get('name'))
		.setIn(
			['groups', groupKey, 'tabsets'], group.get('tabsets')
		)
	);
}

function getGroupRoleKey(state, groupKey, role) {
	return state.getIn(
		['groups', groupKey, 'roles']
	).findKey(matches({
		id: role.get('id'),
	}));
}

function createGroupRole(state, groupKey, role) {
	const keyPath = ['groups', groupKey, 'roles'];
	return state.updateIn(keyPath, roles => (
		roles.push(role)
	));
}

function updateGroupRole(state, groupKey, roleKey, role) {
	const keyPath = ['groups', groupKey, 'roles', roleKey];
	return state.setIn(keyPath, role);
}


text:
from ._alerts import ScanningAlertsClientV1

__all__ = ["ScanningAlertsClientV1"]


text:
import '#3p/polyfills';

import {register} from '#3p/3p';
import {draw3p, init} from '#3p/integration-lib';

import {tail} from '#ads/vendors/tail';

init(window);
register('tail', tail);

window.draw3p = draw3p;


text:
package de.beyondjava.jsf.sample.multipleControllers;

import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class Dice2 implements Serializable {
	private static final long serialVersionUID = 1L;

	private int value=2;

	public void throwDice() {
		setValue(((int) (Math.random() * 6.0)) + 1);
	}

	public int getValue() {
		return value;
	}

	public void setValue(int value) {
		this.value = value;
	}
}


text:
"""Functions useful to all element classes."""

import sys
import argparse
from subprocess import Popen, PIPE, STDOUT, CalledProcessError
# ==============================================================================
__version__ = "0.1"

__copyright__ = "Copyright 2017, devops.center"
__credits__ = ["Bob Lozano", "Gregg Jensen"]
__license__ = ' \
   # Copyright 2014-2017 devops.center llc                                    \
   #                                                                          \
   # Licensed under the Apache License, Version 2.0 (the "License");          \
   # you may not use this file except in compliance with the License.         \
   # You may obtain a copy of the License at                                  \
   #                                                                          \
   #   http://www.apache.org/licenses/LICENSE-2.0                             \
   #                                                                          \
   # Unless required by applicable law or agreed to in writing, software      \
   # distributed under the License is distributed on an "AS IS" BASIS,        \
   # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \
   # See the License for the specific language governing permissions and      \
   # limitations under the License.                                           \
   # '
__status__ = "Development"
# ==============================================================================

class ElementBase(object):
    """Serves base functionality for all element classes."""

    def __init__(self, nameIn, argList):
        """Constructor for the base class."""
        self.name = nameIn
#        if "CONFIG_FILE" in argList:
#            self.readConfigFile(argList["CONFIG_FILE"])
        if "APP_NAME" in argList:
            self.appName = argList["APP_NAME"]
        if "ORGANIZATION" in argList:
            self.profile = argList["ORGANIZATION"]
            self.organization = argList["ORGANIZATION"]
        if "REGION" in argList:
            self.region = argList["REGION"]
        if "ENV" in argList:
            self.env = argList["ENV"]
        if "SUFFIX" in argList:
            self.suffix = argList["SUFFIX"]
        if "STACK" in argList:
            self.stack = argList["STACK"]
        if "STACK_DIR" in argList:
            self.stackDir = argList["STACK_DIR"]
        if "PGVERSION" in argList:
            self.postgresVersion = argList["PGVERSION"]
        # print("ElementBase args: {}".format(argList))

#    def readConfigFile(self, theFileName):
#        """Read the config file for the key/value pairs listing the paths."""
#        # check to see if the config file exists
#        try:
#            tmpFileHandle = open(theFileName, 'r')
#            tmpFileHandle.close()
#        except IOError:
#            print("Unable to access the config file: {}".format(theFileName))
#            sys.exit(1)
#
#        self.config = ConfigParser()
#        self.config.read(theFileName)
#
#        for keyName, aValue in self.config.items("settings"):
#            if not hasattr(self, keyName):
#                setattr(self, keyName, aValue)

    def runScript(self, shellScript):
        """Execute the passed in shell script."""
        print(self.__class__.__name__ + " EXECUTING: " + shellScript)
        # NOTE: this is a python3
        with Popen(shellScript, shell=True, stdout=PIPE, bufsize=1,
                   universal_newlines=True) as p:
            for line in p.stdout:
                print(line, end='')  # process line here

        if p.returncode != 0:
            raise CalledProcessError(p.returncode, p.args)
            sys.exit(1)

    def priorToRun(self):
        """Execute steps prior to running."""
        return

    def postRunning(self):
        """Execute steps after the run has completed."""
        return

def checkArgs():
    """Check the command line arguments."""
    parser = argparse.ArgumentParser(
        description=('comment'))
    parser.parse_args()

def main(argv):
    """Main code goes here."""
    checkArgs()

if __name__ == "__main__":
    main(sys.argv[1:])

# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4


text:
'use strict'

const hello = 'world'

window.convertCase = (function () {
  const REGEX = {
    WORD_DELIM: /[_\- \t\n\r]+/,
    NEWLINE: /\r?\n\r?/
  }

  const convertCase = {
    toCamelCase: (string = '') => {
      const [first, ...rest] = String(string).split(REGEX.WORD_DELIM)

      return [
        first.toLowerCase(),
        ...rest.map(convertCase.capitalize)
      ].join('')
    },

    toPascalCase: (string = '') =>
      String(string).split(REGEX.WORD_DELIM).map(convertCase.capitalize).join(''),

    toKebabCase: (string = '') =>
      convertCase.seperaterize(string, convertCase.lowerize, '-'),

    toUpperKebabCase: (string = '') =>
      convertCase.seperaterize(string, convertCase.upperize, '-'),

    toSnakeCase: (string = '') =>
      convertCase.seperaterize(string, convertCase.lowerize, '_'),

    toUpperSnakeCase: (string = '') =>
      convertCase.seperaterize(string, convertCase.upperize, '_'),

    seperaterize: (string = '', convertCase, delim) =>
      String(string).split(REGEX.WORD_DELIM).map(convertCase).join(delim),

    lowerize: (string = '') => String(string).toLowerCase(),

    upperize: (string = '') => String(string).toUpperCase(),

    capitalize: ([first, ...rest] = '') => [
      String(first).toUpperCase(),
      ...rest.map(x => String(x).toLowerCase())
    ].join('')
  }

  return convertCase
})()

function ajax (query) {
  const xhr = new XMLHttpRequest()
  xhr.open('POST', '?type=api')

  return new Promise((resolve, reject) => {
    xhr.addEventListener('loadend', () => {
      const {status, response} = xhr

      if (status < 200 || status > 200) {
        reject({status, response, xhr})
      } else {
        try {
          resolve(JSON.parse(response))
        } catch (error) {
          reject({error, status, response, xhr})
        }
      }
    })

    xhr.addEventListener('error', error => reject({error, __proto__: xhr}))
    xhr.send(JSON.stringify(query))
  })
}

function renderTemplate(template, data = {}, clone = false, target = null) {
  if (typeof template === 'string') {
    return renderTemplate(document.querySelector(template), data, clone, target)
  }

  const fragment = template.content.cloneNode(true)

  const getNode = clone
    ? node => node.cloneNode(true)
    : x => x

  for (const selector in data) {
    const append = renderTemplate.createAppendFunction(data[selector])

    Array
      .from(fragment.querySelectorAll(selector))
      .forEach(append)
  }

  const result = fragment.querySelector('*')
  target instanceof Node && target.appendChild(result)
  return result
}

renderTemplate.createAppendFunction = prototype => {
  try {
    const node = createDOMNode(prototype)
    return container => container.appendChild(node)
  } catch (_) {
    return container => {
      for (const key in prototype) {
        const value = prototype[key]
        const append = renderTemplate.createAppendFunction.attributes[key]
        append ? append(container, value) : container.setAttribute(key, value)
      }
    }
  }
}

renderTemplate.createAppendFunction.attributes = {
  '': (container, child) =>
    container.appendChild(createDOMNode(child)),

  classList: (container, classes) =>
    container.classList.add(...classes),

  dataset: (container, dataset) =>
    Object.assign(container.dataset, dataset),

  children: (container, children) => Array
    .from(children)
    .map(createDOMNode)
    .forEach(child => container.appendChild(child)),

  textContent: (container, text) => {
    container.textContent = text
  },

  events: (container, listeners) => {
    if (typeof listeners !== 'object') {
      throw new TypeError(`Second argument is not an object: ${listeners}`)
    }

    const add = (type, fn) => fn instanceof Array
      ? fn.forEach(x => add(type, x))
      : container.addEventListener(type, fn, false)

    for (const type in listeners) {
      add(type, listeners[type])
    }
  },

  __proto__: null
}

renderTemplate.transform = (fn = (k, v) => [k, v], template, data = {}, ...args) => {
  const newData = {}

  for (const key in data) {
    const [newKey, newValue] = fn(key, data[key], data)
    newData[newKey] = newValue
  }

  return renderTemplate(template, newData, ...args)
}

renderTemplate.transformKey = (fn = x => x, ...args) =>
  renderTemplate.transform((k, v) => [fn(k), v], ...args)

renderTemplate.transformValue = (fn = x => x, ...args) =>
  renderTemplate.transform((k, v) => [k, fn(v)], ...args)

renderTemplate.prefix = (prefix = '', ...args) =>
  renderTemplate.transformKey(x => prefix + x, ...args)

renderTemplate.suffix = (suffix = '', ...args) =>
  renderTemplate.transformKey(x => x + suffix, ...args)

renderTemplate.byClass = (...args) =>
  renderTemplate.prefix('.', ...args)

renderTemplate.byId = (...args) =>
  renderTemplate.prefix('#', ...args)

function createDOMNode (content) {
  if (content instanceof Node) return content

  if (['string', 'number'].includes(typeof content)) {
    return document.createTextNode(String(content))
  }

  if (content instanceof Array) {
    const result = document.createDocumentFragment()
    Array.from(content).map(createDOMNode).forEach(child => result.appendChild(child))
    return result
  }

  throw new TypeError(`Invalid type of content: ${content}`)
}

function isFlashSupported () {
  let result

  try {
    result = new ActiveXObject('ShockwaveFlash.ShockwaveFlash')
  } catch (_) {
    result = navigator.plugins['Shockwave Flash']
  }

  return Boolean(result)
}

function callIfExists (subject, ontrue = x => x, onfalse = x => x) {
  return (subject ? ontrue : onfalse)(subject, ontrue, onfalse)
}

callIfExists.querySelector = (x = 'html', ...args) =>
  callIfExists(document.querySelector(x), ...args)

function makeClassToggler (toggler, target, name) {
  if (typeof toggler === 'string') {
    toggler = document.querySelector(toggler)
  }

  if (typeof target === 'string') {
    target = document.querySelector(target)
  }

  const {classList} = target
  const check = () => classList.contains(name)
  const add = () => classList.add(name)
  const remove = () => classList.remove(name)
  const onClick = event => check() ? remove() : add()

  toggler.addEventListener('click', onClick, false)

  return {
    fn: {
      check,
      add,
      remove,
      onClick,
      __proto__: null
    },
    node: {
      toggler,
      target,
      __proto__: null
    },
    class: {
      name,
      __proto__: null
    },
    __proto__: null
  }
}

function eventElsewhere (type = 'click', fn = () => {}, ...here) {
  document.addEventListener(type, event => {
    const {target} = event
    here.some(x => x.contains(target)) || fn()
  }, false)
}

function createJsonEmbedLoader () {
  const loaded = Object.create(null)

  return id => {
    if (id in loaded) return loaded[id]
    const selector = `script#data-${id}.x-component--json-data-embed`
    const element = document.querySelector(selector)

    const transform = x => {
      if (!x || typeof x !== 'object') return x
      if (x instanceof Array) return x.map(transform)

      const result = {}
      for (const key in x) {
        result[convertCase.toCamelCase(key)] = transform(x[key])
      }

      return result
    }

    const value = transform(JSON.parse(element.text))
    loaded[id] = value
    return value
  }
}

function createSizeTracker (element, delay = 1024) {
  if (typeof element === 'string') {
    element = document.querySelector(element)
  }

  let rect = element.getBoundingClientRect()
  const listeners = {width: [], height: [], all: []}

  const check = newRect =>
    ['width', 'height'].filter(x => rect[x] !== newRect[x])

  const call = (name, newVal, oldVal, newRect = newVal, oldRect = oldVal) => {
    listeners[name].forEach(fn => setTimeout(
      () => fn({newVal, oldVal, newRect, oldRect, element})
    ))
  }

  const loop = () => {
    const newRect = element.getBoundingClientRect()
    const change = check(newRect)
    if (!change.length) return
    change.includes('width') && call('width', newRect.width, rect.width, newRect, rect)
    change.includes('height') && call('height', newRect.height, rect.height, newRect, rect)
    call('all', newRect, rect)
    rect = newRect
  }

  const intervalId = setInterval(loop, delay)
  window.addEventListener('resize', loop, false)

  const validate = fn => {
    if (typeof fn !== 'function') {
      throw new TypeError(`Invalid type of callback: ${fn}`)
    }
  }

  const createListenerAdder = key => fn => {
    validate(fn)
    listeners[key].push(fn)
    return result
  }

  const proto = {
    element,
    delay,
    intervalId,
    __proto__: null
  }

  const result = {
    validate,
    stop: () => {
      clearInterval(intervalId)
      window.removeEventListener('resize', loop, false)
    },
    onChange: createListenerAdder('all'),
    width: {
      onChange: createListenerAdder('width'),
      __proto__: proto
    },
    height: {
      onChange: createListenerAdder('height'),
      __proto__: proto
    },
    __proto__: proto
  }

  element.addEventListener('DOMNodeRemoved', result.stop, false)

  return result
}

function focusAndScroll (element) {
  element.focus()
  element.scrollIntoView()
}


text:
require "buckit/version"
require "aws-sdk"
module Buckit
  # Your code goes here...
end


text:
return unless RUBYMOTION_ENV == "test"

module Term
  # The ANSIColor module can be used for namespacing and mixed into your own
  # classes.
  module ANSIColor
    # :stopdoc:
    ATTRIBUTES = [
      [ :clear        ,   0 ],
      [ :reset        ,   0 ],     # synonym for :clear
      [ :bold         ,   1 ],
      [ :dark         ,   2 ],
      [ :italic       ,   3 ],     # not widely implemented
      [ :underline    ,   4 ],
      [ :underscore   ,   4 ],     # synonym for :underline
      [ :blink        ,   5 ],
      [ :rapid_blink  ,   6 ],     # not widely implemented
      [ :negative     ,   7 ],     # no reverse because of String#reverse
      [ :concealed    ,   8 ],
      [ :strikethrough,   9 ],     # not widely implemented
      [ :black        ,  30 ],
      [ :red          ,  31 ],
      [ :green        ,  32 ],
      [ :yellow       ,  33 ],
      [ :blue         ,  34 ],
      [ :magenta      ,  35 ],
      [ :cyan         ,  36 ],
      [ :white        ,  37 ],
      [ :on_black     ,  40 ],
      [ :on_red       ,  41 ],
      [ :on_green     ,  42 ],
      [ :on_yellow    ,  43 ],
      [ :on_blue      ,  44 ],
      [ :on_magenta   ,  45 ],
      [ :on_cyan      ,  46 ],
      [ :on_white     ,  47 ],
    ]

    ATTRIBUTE_NAMES = ATTRIBUTES.transpose.first
    # :startdoc:

    # Returns true, if the coloring function of this module
    # is switched on, false otherwise.
    def self.coloring?
      @coloring
    end

    # Turns the coloring on or off globally, so you can easily do
    # this for example:
    #  Term::ANSIColor::coloring = STDOUT.isatty
    def self.coloring=(val)
      @coloring = val
    end
    self.coloring = true

      def clear(string = nil)
        result = ''
        result << "" if Term::ANSIColor.coloring?
        if block_given?
          result << yield
        elsif string
          result << string
        elsif respond_to?(:to_str)
          result << self
        else
          return result #only switch on
        end
        result << "" if Term::ANSIColor.coloring?
        result
      end

      def reset(string = nil)
        result = ''
        result << "" if Term::ANSIColor.coloring?
        if block_given?
          result << yield
        elsif string
          result << string
        elsif respond_to?(:to_str)
          result << self
        else
          return result #only switch on
        end
        result << "" if Term::ANSIColor.coloring?
        result
      end

      def bold(string = nil)
        result = ''
        result << "" if Term::ANSIColor.coloring?
        if block_given?
          result << yield
        elsif string
          result << string
        elsif respond_to?(:to_str)
          result << self
        else
          return result #only switch on
        end
        result << "" if Term::ANSIColor.coloring?
        result
      end

      def dark(string = nil)
        result = ''
        result << "" if Term::ANSIColor.coloring?
        if block_given?
          result << yield
        elsif string
          result << string
        elsif respond_to?(:to_str)
          result << self
        else
          return result #only switch on
        end
        result << "" if Term::ANSIColor.coloring?
        result
      end

      def italic(string = nil)
        result = ''
        result << "" if Term::ANSIColor.coloring?
        if block_given?
          result << yield
        elsif string
          result << string
        elsif respond_to?(:to_str)
          result << self
        else
          return result #only switch on
        end
        result << "" if Term::ANSIColor.coloring?
        result
      end

      def underline(string = nil)
        result = ''
        result << "" if Term::ANSIColor.coloring?
        if block_given?
          result << yield
        elsif string
          result << string
        elsif respond_to?(:to_str)
          result << self
        else
          return result #only switch on
        end
        result << "" if Term::ANSIColor.coloring?
        result
      end

      def underscore(string = nil)
        result = ''
        result << "" if Term::ANSIColor.coloring?
        if block_given?
          result << yield
        elsif string
          result << string
        elsif respond_to?(:to_str)
          result << self
        else
          return result #only switch on
        end
        result << "" if Term::ANSIColor.coloring?
        result
      end

      def blink(string = nil)
        result = ''
        result << "" if Term::ANSIColor.coloring?
        if block_given?
          result << yield
        elsif string
          result << string
        elsif respond_to?(:to_str)
          result << self
        else
          return result #only switch on
        end
        result << "" if Term::ANSIColor.coloring?
        result
      end

      def rapid_blink(string = nil)
        result = ''
        result << "" if Term::ANSIColor.coloring?
        if block_given?
          result << yield
        elsif string
          result << string
        elsif respond_to?(:to_str)
          result << self
        else
          return result #only switch on
        end
        result << "" if Term::ANSIColor.coloring?
        result
      end

      def negative(string = nil)
        result = ''
        result << "" if Term::ANSIColor.coloring?
        if block_given?
          result << yield
        elsif string
          result << string
        elsif respond_to?(:to_str)
          result << self
        else
          return result #only switch on
        end
        result << "" if Term::ANSIColor.coloring?
        result
      end

      def concealed(string = nil)
        result = ''
        result << "" if Term::ANSIColor.coloring?
        if block_given?
          result << yield
        elsif string
          result << string
        elsif respond_to?(:to_str)
          result << self
        else
          return result #only switch on
        end
        result << "" if Term::ANSIColor.coloring?
        result
      end

      def strikethrough(string = nil)
        result = ''
        result << "" if Term::ANSIColor.coloring?
        if block_given?
          result << yield
        elsif string
          result << string
        elsif respond_to?(:to_str)
          result << self
        else
          return result #only switch on
        end
        result << "" if Term::ANSIColor.coloring?
        result
      end

      def black(string = nil)
        result = ''
        result << "" if Term::ANSIColor.coloring?
        if block_given?
          result << yield
        elsif string
          result << string
        elsif respond_to?(:to_str)
          result << self
        else
          return result #only switch on
        end
        result << "" if Term::ANSIColor.coloring?
        result
      end

      def red(string = nil)
        result = ''
        result << "" if Term::ANSIColor.coloring?
        if block_given?
          result << yield
        elsif string
          result << string
        elsif respond_to?(:to_str)
          result << self
        else
          return result #only switch on
        end
        result << "" if Term::ANSIColor.coloring?
        result
      end

      def green(string = nil)
        result = ''
        result << "" if Term::ANSIColor.coloring?
        if block_given?
          result << yield
        elsif string
          result << string
        elsif respond_to?(:to_str)
          result << self
        else
          return result #only switch on
        end
        result << "" if Term::ANSIColor.coloring?
        result
      end

      def yellow(string = nil)
        result = ''
        result << "" if Term::ANSIColor.coloring?
        if block_given?
          result << yield
        elsif string
          result << string
        elsif respond_to?(:to_str)
          result << self
        else
          return result #only switch on
        end
        result << "" if Term::ANSIColor.coloring?
        result
      end

      def blue(string = nil)
        result = ''
        result << "" if Term::ANSIColor.coloring?
        if block_given?
          result << yield
        elsif string
          result << string
        elsif respond_to?(:to_str)
          result << self
        else
          return result #only switch on
        end
        result << "" if Term::ANSIColor.coloring?
        result
      end

      def magenta(string = nil)
        result = ''
        result << "" if Term::ANSIColor.coloring?
        if block_given?
          result << yield
        elsif string
          result << string
        elsif respond_to?(:to_str)
          result << self
        else
          return result #only switch on
        end
        result << "" if Term::ANSIColor.coloring?
        result
      end

      def cyan(string = nil)
        result = ''
        result << "" if Term::ANSIColor.coloring?
        if block_given?
          result << yield
        elsif string
          result << string
        elsif respond_to?(:to_str)
          result << self
        else
          return result #only switch on
        end
        result << "" if Term::ANSIColor.coloring?
        result
      end

      def white(string = nil)
        result = ''
        result << "" if Term::ANSIColor.coloring?
        if block_given?
          result << yield
        elsif string
          result << string
        elsif respond_to?(:to_str)
          result << self
        else
          return result #only switch on
        end
        result << "" if Term::ANSIColor.coloring?
        result
      end

      def on_black(string = nil)
        result = ''
        result << "" if Term::ANSIColor.coloring?
        if block_given?
          result << yield
        elsif string
          result << string
        elsif respond_to?(:to_str)
          result << self
        else
          return result #only switch on
        end
        result << "" if Term::ANSIColor.coloring?
        result
      end

      def on_red(string = nil)
        result = ''
        result << "" if Term::ANSIColor.coloring?
        if block_given?
          result << yield
        elsif string
          result << string
        elsif respond_to?(:to_str)
          result << self
        else
          return result #only switch on
        end
        result << "" if Term::ANSIColor.coloring?
        result
      end

      def on_green(string = nil)
        result = ''
        result << "" if Term::ANSIColor.coloring?
        if block_given?
          result << yield
        elsif string
          result << string
        elsif respond_to?(:to_str)
          result << self
        else
          return result #only switch on
        end
        result << "" if Term::ANSIColor.coloring?
        result
      end

      def on_yellow(string = nil)
        result = ''
        result << "" if Term::ANSIColor.coloring?
        if block_given?
          result << yield
        elsif string
          result << string
        elsif respond_to?(:to_str)
          result << self
        else
          return result #only switch on
        end
        result << "" if Term::ANSIColor.coloring?
        result
      end

      def on_blue(string = nil)
        result = ''
        result << "" if Term::ANSIColor.coloring?
        if block_given?
          result << yield
        elsif string
          result << string
        elsif respond_to?(:to_str)
          result << self
        else
          return result #only switch on
        end
        result << "" if Term::ANSIColor.coloring?
        result
      end

      def on_magenta(string = nil)
        result = ''
        result << "" if Term::ANSIColor.coloring?
        if block_given?
          result << yield
        elsif string
          result << string
        elsif respond_to?(:to_str)
          result << self
        else
          return result #only switch on
        end
        result << "" if Term::ANSIColor.coloring?
        result
      end

      def on_cyan(string = nil)
        result = ''
        result << "" if Term::ANSIColor.coloring?
        if block_given?
          result << yield
        elsif string
          result << string
        elsif respond_to?(:to_str)
          result << self
        else
          return result #only switch on
        end
        result << "" if Term::ANSIColor.coloring?
        result
      end

      def on_white(string = nil)
        result = ''
        result << "" if Term::ANSIColor.coloring?
        if block_given?
          result << yield
        elsif string
          result << string
        elsif respond_to?(:to_str)
          result << self
        else
          return result #only switch on
        end
        result << "" if Term::ANSIColor.coloring?
        result
      end

    # Regular expression that is used to scan for ANSI-sequences while
    # uncoloring strings.
    COLORED_REGEXP = /\e\[([34][0-7]|[0-9])m/

    # Returns an uncolored version of the string, that is all
    # ANSI-sequences are stripped from the string.
    def uncolored(string = nil) # :yields:
      if block_given?
        yield.gsub(COLORED_REGEXP, '')
      elsif string
        string.gsub(COLORED_REGEXP, '')
      elsif respond_to?(:to_str)
        gsub(COLORED_REGEXP, '')
      else
        ''
      end
    end

    module_function

    # Returns an array of all Term::ANSIColor attributes as symbols.
    def attributes
      ATTRIBUTE_NAMES
    end
    extend self
  end
end


text:
package com.bendb.dropwizard.redis.jersey;

import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.process.internal.RequestScoped;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * Bind a JedisPool instance, as configured in Dropwizard, and a
 * HK2 {@link org.glassfish.hk2.api.Factory} to create injectable
 * Jedis.
 */
public class JedisPoolBinder extends AbstractBinder {
    private final JedisPool pool;

    public JedisPoolBinder(JedisPool pool) { this.pool = pool; }

    @Override
    protected void configure() {
        // Always return the same pool when/where ever it's asked for
        bind(pool).to(JedisPool.class);

        bindFactory(new JedisFactory(pool))
                .to(Jedis.class)
                .in(RequestScoped.class);
    }
}


text:
package org.apache.geode.internal.cache;

// DO NOT modify this class. It was generated from LeafRegionEntry.cpp

import java.util.concurrent.atomic.AtomicLongFieldUpdater;

import org.apache.geode.internal.cache.lru.EnableLRU;

import org.apache.geode.internal.cache.persistence.DiskRecoveryStore;

import org.apache.geode.internal.util.concurrent.CustomEntryConcurrentHashMap.HashEntry;

// macros whose definition changes this class:
// disk: 1
// lru: LRU
// stats: STATS
// versioned: VERSIONED
// offheap: OFFHEAP
// One of the following key macros must be defined:
// key object: 1
// key int: KEY_INT
// key long: KEY_LONG
// key uuid: KEY_UUID
// key string1: KEY_STRING1
// key string2: KEY_STRING2

/**
 * Do not modify this class. It was generated. Instead modify LeafRegionEntry.cpp and then run
 * ./dev-tools/generateRegionEntryClasses.sh (it must be run from the top level directory).
 */
public class VMThinDiskRegionEntryHeapObjectKey extends VMThinDiskRegionEntryHeap {
  public VMThinDiskRegionEntryHeapObjectKey(RegionEntryContext context, Object key,

      Object value

  ) {
    super(context,

        (value instanceof RecoveredEntry ? null : value)

    );
    // DO NOT modify this class. It was generated from LeafRegionEntry.cpp

    initialize(context, value);

    this.key = key;

  }

  // DO NOT modify this class. It was generated from LeafRegionEntry.cpp

  // common code
  protected int hash;
  private HashEntry<Object, Object> next;
  @SuppressWarnings("unused")
  private volatile long lastModified;
  private static final AtomicLongFieldUpdater<VMThinDiskRegionEntryHeapObjectKey> lastModifiedUpdater =
      AtomicLongFieldUpdater.newUpdater(VMThinDiskRegionEntryHeapObjectKey.class, "lastModified");

  private volatile Object value;

  @Override
  protected Object getValueField() {
    return this.value;
  }

  @Override
  protected void setValueField(Object v) {
    this.value = v;
  }

  protected long getLastModifiedField() {
    return lastModifiedUpdater.get(this);
  }

  protected boolean compareAndSetLastModifiedField(long expectedValue, long newValue) {
    return lastModifiedUpdater.compareAndSet(this, expectedValue, newValue);
  }

  /**
   * @see HashEntry#getEntryHash()
   */
  public int getEntryHash() {
    return this.hash;
  }

  protected void setEntryHash(int v) {
    this.hash = v;
  }

  /**
   * @see HashEntry#getNextEntry()
   */
  public HashEntry<Object, Object> getNextEntry() {
    return this.next;
  }

  /**
   * @see HashEntry#setNextEntry
   */
  public void setNextEntry(final HashEntry<Object, Object> n) {
    this.next = n;
  }

  // DO NOT modify this class. It was generated from LeafRegionEntry.cpp

  // disk code

  protected void initialize(RegionEntryContext context, Object value) {
    diskInitialize(context, value);
  }

  @Override
  public int updateAsyncEntrySize(EnableLRU capacityController) {
    throw new IllegalStateException("should never be called");
  }

  // DO NOT modify this class. It was generated from LeafRegionEntry.cpp

  private void diskInitialize(RegionEntryContext context, Object value) {
    DiskRecoveryStore drs = (DiskRecoveryStore) context;
    DiskStoreImpl ds = drs.getDiskStore();
    long maxOplogSize = ds.getMaxOplogSize();
    // get appropriate instance of DiskId implementation based on maxOplogSize
    this.id = DiskId.createDiskId(maxOplogSize, true/* is persistence */, ds.needsLinkedList());
    Helper.initialize(this, drs, value);
  }

  /**
   * DiskId
   *
   * @since GemFire 5.1
   */
  protected DiskId id;// = new DiskId();

  public DiskId getDiskId() {
    return this.id;
  }

  @Override
  void setDiskId(RegionEntry old) {
    this.id = ((AbstractDiskRegionEntry) old).getDiskId();
  }
  // // inlining DiskId
  // // always have these fields
  // /**
  // * id consists of
  // * most significant
  // * 1 byte = users bits
  // * 2-8 bytes = oplog id
  // * least significant.
  // *
  // * The highest bit in the oplog id part is set to 1 if the oplog id
  // * is negative.
  // * @todo this field could be an int for an overflow only region
  // */
  // private long id;
  // /**
  // * Length of the bytes on disk.
  // * This is always set. If the value is invalid then it will be set to 0.
  // * The most significant bit is used by overflow to mark it as needing to be written.
  // */
  // protected int valueLength = 0;
  // // have intOffset or longOffset
  // // intOffset
  // /**
  // * The position in the oplog (the oplog offset) where this entry's value is
  // * stored
  // */
  // private volatile int offsetInOplog;
  // // longOffset
  // /**
  // * The position in the oplog (the oplog offset) where this entry's value is
  // * stored
  // */
  // private volatile long offsetInOplog;
  // // have overflowOnly or persistence
  // // overflowOnly
  // // no fields
  // // persistent
  // /** unique entry identifier * */
  // private long keyId;

  // DO NOT modify this class. It was generated from LeafRegionEntry.cpp

  // key code

  private final Object key;

  @Override
  public Object getKey() {
    return this.key;
  }

  // DO NOT modify this class. It was generated from LeafRegionEntry.cpp
}


text:
bundle exec rake db:migrate
bundle exec rails server


text:
package mcjty.rftools.blocks.endergen;

import mcjty.lib.blocks.BaseBlock;
import mcjty.lib.blocks.GenericBlock;
import mcjty.lib.builder.BlockFlags;
import mcjty.lib.container.GenericContainer;
import mcjty.lib.varia.ItemStackTools;
import mcjty.rftools.blocks.ModBlocks;
import mcjty.rftools.setup.GuiProxy;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

import static mcjty.lib.varia.ItemStackTools.mapTag;

public class EndergenicSetup {
    public static GenericBlock<EndergenicTileEntity, GenericContainer> endergenicBlock;
    public static GenericBlock<PearlInjectorTileEntity, GenericContainer> pearlInjectorBlock;
    public static EnderMonitorBlock enderMonitorBlock;

    public static void init() {
        endergenicBlock = ModBlocks.builderFactory.<EndergenicTileEntity> builder("endergenic")
                .tileEntityClass(EndergenicTileEntity.class)
                .emptyContainer()
                .flags(BlockFlags.REDSTONE_CHECK, BlockFlags.NON_OPAQUE, BlockFlags.RENDER_TRANSLUCENT)
                .rotationType(BaseBlock.RotationType.NONE)
                .infusable()
                .guiId(GuiProxy.GUI_ENDERGENIC)
                .info("message.rftools.shiftmessage")
                .infoExtended("message.rftools.endergenic")
                .build();

        pearlInjectorBlock = ModBlocks.builderFactory.<PearlInjectorTileEntity> builder("pearl_injector")
                .tileEntityClass(PearlInjectorTileEntity.class)
                .container(PearlInjectorTileEntity.CONTAINER_FACTORY)
                .flags(BlockFlags.REDSTONE_CHECK)
                .guiId(GuiProxy.GUI_PEARL_INJECTOR)
                .info("message.rftools.shiftmessage")
                .infoExtended("message.rftools.pearl_injector")
                .infoExtendedParameter(stack -> {
                    int count = mapTag(stack, compound -> (int) ItemStackTools.getListStream(compound, "Items").filter(nbt -> !new ItemStack((NBTTagCompound)nbt).isEmpty()).count(), 0);
                    return Integer.toString(count);
                })
                .build();

        enderMonitorBlock = new EnderMonitorBlock();
    }

    @SideOnly(Side.CLIENT)
    public static void initClient() {
        endergenicBlock.initModel();
        endergenicBlock.setGuiFactory(GuiEndergenic::new);
        EndergenicRenderer.register();

        pearlInjectorBlock.initModel();
        pearlInjectorBlock.setGuiFactory(GuiPearlInjector::new);

        enderMonitorBlock.initModel();
    }
}


text:
using System;

namespace Fonet.Pdf.Gdi.Font {
    /// <summary>
    ///     Class that represents the Font Header table.
    /// </summary>
    /// <remarks>
    ///     http://www.microsoft.com/typography/otspec/head.htm
    /// </remarks>
    internal class HeaderTable : FontTable {
        internal int versionNo;
        internal int fontRevision;
        internal uint checkSumAdjustment;
        internal uint magicNumber;
        internal ushort flags;
        internal ushort unitsPermEm;
        internal DateTime createDate;
        internal DateTime updateDate;
        internal short xMin;
        internal short yMin;
        internal short xMax;
        internal short yMax;
        internal ushort macStyle;
        internal ushort lowestRecPPEM;
        internal short fontDirectionHint;
        internal short indexToLocFormat;
        internal short glyphDataFormat;

        private static readonly DateTime BaseDate =
            new DateTime(1904, 1, 1, 0, 0, 0);

        /// <summary>
        ///     Class constructor.
        /// </summary>
        /// <param name="entry"></param>
        public HeaderTable(DirectoryEntry entry)
            : base(TableNames.Head, entry) {}

        /// <summary>
        ///     Gets a value that indicates whether glyph offsets in the
        ///     loca table are stored as a ushort or ulong.
        /// </summary>
        public bool IsShortFormat {
            get { return (indexToLocFormat == 0); }
        }

        /// <summary>
        ///     Reads the contents of the "head" table from the current position
        ///     in the supplied stream.
        /// </summary>
        /// <param name="reader"></param>
        protected internal override void Read(FontFileReader reader) {
            FontFileStream stream = reader.Stream;
            versionNo = stream.ReadFixed();
            fontRevision = stream.ReadFixed();
            checkSumAdjustment = stream.ReadULong();
            magicNumber = stream.ReadULong();
            flags = stream.ReadUShort();
            unitsPermEm = stream.ReadUShort();
            // Some fonts have dodgy date offsets that cause AddSeconds to throw an exception
            createDate = GetDate(stream.ReadLongDateTime());
            updateDate = GetDate(stream.ReadLongDateTime());
            xMin = stream.ReadShort();
            yMin = stream.ReadShort();
            xMax = stream.ReadShort();
            yMax = stream.ReadShort();
            macStyle = stream.ReadUShort();
            lowestRecPPEM = stream.ReadUShort();
            fontDirectionHint = stream.ReadShort();
            indexToLocFormat = stream.ReadShort();
            glyphDataFormat = stream.ReadShort();
        }

        /// <summary>
        ///     Returns a DateTime instance which is the result of adding <i>seconds</i>
        ///     to BaseDate.  If an exception occurs, BaseDate is returned.
        /// </summary>
        /// <param name="seconds"></param>
        private DateTime GetDate(long seconds) {
            try {
                return new DateTime(BaseDate.Ticks).AddSeconds(seconds);
            }
            catch {
                return BaseDate;
            }
        }

        /// <summary>
        ///     Writes the contents of the head table to the supplied stream.
        /// </summary>
        /// <param name="writer"></param>
        protected internal override void Write(FontFileWriter writer) {
            FontFileStream stream = writer.Stream;
            stream.WriteFixed(versionNo);
            stream.WriteFixed(fontRevision);
            // TODO: Calculate based on entire font
            stream.WriteULong(0);
            stream.WriteULong(0x5F0F3CF5);
            stream.WriteUShort(flags);
            stream.WriteUShort(unitsPermEm);
            stream.WriteDateTime((long) (createDate - BaseDate).TotalSeconds);
            stream.WriteDateTime((long) (updateDate - BaseDate).TotalSeconds);
            stream.WriteShort(xMin);
            stream.WriteShort(yMin);
            stream.WriteShort(xMax);
            stream.WriteShort(yMax);
            stream.WriteUShort(macStyle);
            stream.WriteUShort(lowestRecPPEM);
            stream.WriteShort(fontDirectionHint);
            // TODO: Always write loca offsets as ulongs
            stream.WriteShort(1);
            stream.WriteShort(glyphDataFormat);
        }
    }

}


text:
require 'facter'

# source the environment
File.readlines("/etc/container_environment.sh").each do |line|
    values = line.match('(?<=export ).+').to_s.split("=")
    ENV[values[0]] = values[1]
end

fqdn = Facter.value('fqdn')
hostname = Facter.value('hostname')
domain = Facter.value('domain')

puppetmaster_dns_names = ENV.fetch(
    "PUPPETMASTER_DNS_NAMES", "puppet,puppet.#{domain},#{hostname},#{fqdn}").split(",").join(" ")
puppetmaster_port = ENV.fetch("PUPPETMASTER_TCP_PORT", "8140")

template = %{# puppetmaster nginx config

server {
    listen #{puppetmaster_port} ssl default_server;
    server_name #{puppetmaster_dns_names};

    passenger_enabled          on;
    passenger_set_header       X_CLIENT_S_DN $ssl_client_s_dn;
    passenger_set_header       X_CLIENT_VERIFY $ssl_client_verify;

    access_log                 /var/log/nginx/puppet_access.log;
    error_log                  /var/log/nginx/puppet_error.log;

    root                       /usr/share/puppet/rack/puppetmaster/public;

    ssl_certificate            /var/lib/puppet/ssl/certs/#{fqdn}.pem;
    ssl_certificate_key        /var/lib/puppet/ssl/private_keys/#{fqdn}.pem;

    # ssl hardening - https://j.mp/1qiXFeW
    ssl_prefer_server_ciphers  on;
    ssl_protocols              TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers                ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS;

    ssl_crl                    /var/lib/puppet/ssl/ca/ca_crl.pem;
    ssl_client_certificate     /var/lib/puppet/ssl/certs/ca.pem;

    ssl_verify_client          optional;
    ssl_verify_depth           1;
}}

if not File.file?("/etc/nginx/sites-available/puppetmaster")
    File.open("/etc/nginx/sites-available/puppetmaster", "w") { |file|
        file.write(template)
    }
end


text:
#include "FlashMemoryStream.h"

FlashMemoryStream::FlashMemoryStream(const void *startAddress, uint32_t length) {
  _startAddress = (const uint8_t*) startAddress;
  _length = length;
  _pos = 0;
}

int FlashMemoryStream::peek() {
  return pgm_read_byte_far(_startAddress + _pos);
}

int FlashMemoryStream::read() {
  if (available()) {
    return pgm_read_byte_far(_startAddress + _pos++);
  } else {
    return -1;
  }
}

int FlashMemoryStream::available() {
  return min(_length - _pos, 0x7fff);
}

void FlashMemoryStream::flush() {
  // Nothing is done here
}

void FlashMemoryStream::seek(uint16_t position) {
  _pos = position;
}

void FlashMemoryStream::reset() {
  seek(0);
}

size_t FlashMemoryStream::write(uint8_t val) {
  return 0;
}