text:
/* *********************************************************************************************

   To connect to remote Leap Motion controllers, add this to the host's Leap Motion config.json:
     "websockets_allow_remote": true

   ********************************************************************************************* */

/* global Leap, THREE, CANNON */
var Utils = require('./Utils.js');

module.exports = ( function () {
    "use strict";

    const INCH2METERS = 0.0254;
    const LEAP2METERS = 0.001;
    const METERS2LEAP = 1000;
    const UP = THREE.Object3D.DefaultUp;
    const FORWARD = new THREE.Vector3(0, 0, -1);

    const DEFAULT_OPTIONS = {
        toolLength: 0.15,
        toolRadius: 0.0034,
        tipRadius: 0.0034,
        toolMass: 0.04,
        tipShape: 'ImplicitCylinder',
        interactionBoxColor: 0x99eebb,
        leapColor: 0x777777,
        toolColor: 0xeebb99,
        tipColor: 0x99bbee,
        handColor: 0x113399,
        useShadowMesh: true,
        shadowMaterial: new THREE.MeshBasicMaterial({color: 0x333333}),
        shadowLightPosition: new THREE.Vector4(0, 7, 0, 0.1),
        shadowPlane: 0.002,
        numSegments: 10,
        interactionPlaneOpacity: 0.22,
        timeA: 0.25,
        timeB: 0.25 + 1.5,
        minConfidence: 0.13,
        host: '127.0.0.1',
        port: 6437
    };

    function makeTool(options) {
        options = Utils.combineObjects(DEFAULT_OPTIONS, options || {});
        console.log('Leap Motion tool options:');
        console.log(options);

        // coordinate transformations are performed via three.js scene graph
        var toolRoot = new THREE.Object3D();
        toolRoot.scale.set(LEAP2METERS, LEAP2METERS, LEAP2METERS);

        toolRoot.position.set(0, -18 * 0.0254, -0.49);

        // set up / connect to leap controller:

        var leapController = new Leap.Controller({background: true,
                                                  host: options.host,
                                                  port: options.port});

        // leap motion event callbacks:
        var onConnect = options.onConnect || function () {
            console.log('Leap Motion WebSocket connected (host: %s, port: %d)', options.host, options.port);
        };
        leapController.on('connect', onConnect);

        var onDisconnect = options.onDisconnect || function () {
            console.log('Leap Motion WebSocket disconnected (host: %s, port: %d)', options.host, options.port);
        };
        leapController.on('disconnect', onDisconnect);

        var onStreamingStarted = options.onStreamingStarted || function () {
            console.log('Leap Motion streaming started (host: %s, port: %d)', options.host, options.port);
        };
        leapController.on('streamingStarted', onStreamingStarted);

        var onStreamingStopped = options.onStreamingStopped || function () {
            console.warn('Leap Motion streaming stopped (host: %s, port: %d)', options.host, options.port);
        };
        leapController.on('streamingStopped', onStreamingStopped);

        // setup tool visuals:

        // interaction box visual guide:
        var interactionBoxRoot = new THREE.Object3D();
        toolRoot.add(interactionBoxRoot);

        var interactionPlaneMaterial = new THREE.MeshBasicMaterial({color: options.interactionBoxColor, transparent: true, opacity: options.interactionPlaneOpacity});
        var interactionPlaneGeom = new THREE.PlaneBufferGeometry(METERS2LEAP, METERS2LEAP);

        var interactionPlaneMesh = new THREE.Mesh(interactionPlaneGeom, interactionPlaneMaterial);
        interactionBoxRoot.add(interactionPlaneMesh);

        interactionPlaneMesh = interactionPlaneMesh.clone();
        interactionPlaneMesh.position.z = METERS2LEAP * 0.5;
        interactionPlaneMesh.updateMatrix();
        interactionBoxRoot.add(interactionPlaneMesh);

        interactionPlaneMesh = interactionPlaneMesh.clone();
        interactionPlaneMesh.position.z = METERS2LEAP * (-0.5);
        interactionPlaneMesh.updateMatrix();
        interactionBoxRoot.add(interactionPlaneMesh);

        // leap motion controller:
        var boxGeom = new THREE.BoxGeometry(METERS2LEAP*INCH2METERS*(3+1/8), METERS2LEAP*INCH2METERS*7/16, METERS2LEAP*INCH2METERS*(1 + 3/16));
        var leapGeom = new THREE.BufferGeometry();
        leapGeom.fromGeometry(boxGeom);
        boxGeom.dispose();
        var leapMaterial = new THREE.MeshLambertMaterial({color: options.leapColor});
        var leapMesh = new THREE.Mesh(leapGeom, leapMaterial);
        leapMesh.position.y = METERS2LEAP*INCH2METERS*(7/32);
        leapMesh.updateMatrix();
        toolRoot.add(leapMesh);

        // the stick:
        var toolGeom = new THREE.CylinderGeometry(METERS2LEAP*options.toolRadius, METERS2LEAP*options.toolRadius, METERS2LEAP*options.toolLength, 10, 1, false);
        toolGeom.translate(0, -0.5*METERS2LEAP*options.toolLength, 0);
        toolGeom.rotateX(-0.5 * Math.PI);
        var bufferGeom = new THREE.BufferGeometry();
        bufferGeom.fromGeometry(toolGeom);
        toolGeom.dispose();
        toolGeom = bufferGeom;
        var toolMaterial = new THREE.MeshLambertMaterial({color: options.toolColor, transparent: true});
        var toolMesh = new THREE.Mesh(toolGeom, toolMaterial);
        toolRoot.add(toolMesh);

        var toolShadowMesh;
        if (options.useShadowMesh) {
            toolShadowMesh = new THREE.ShadowMesh(toolMesh, options.shadowMaterial);
            var shadowPlane = new THREE.Plane(UP, options.shadowPlane);
            toolShadowMesh.updateShadowMatrix(shadowPlane, options.shadowLightPosition);
        } else {
            toolMesh.castShadow = true;
        }

        var toolBody = new CANNON.Body({mass: options.toolMass, type: CANNON.Body.KINEMATIC});

        var tipMesh = null;
        if (options.tipShape === 'Sphere') {
            var tipGeom = new THREE.SphereBufferGeometry(METERS2LEAP*options.tipRadius, 10);
            toolBody.addShape(new CANNON.Sphere(options.tipRadius));
            var tipMaterial = new THREE.MeshLambertMaterial({color: options.tipColor, transparent: true});
            tipMesh = new THREE.Mesh(tipGeom, tipMaterial);
            tipMesh.castShadow = true;
            toolMesh.add(tipMesh);
        } else {
            // cannon body is a cylinder at end of tool
            var cylLength = options.toolLength;
            var shapePosition = new CANNON.Vec3(0, 0, 0.5*cylLength);
            if (options.tipShape === 'ImplicitCylinder') {
                toolBody.addShape(new CANNON.ImplicitCylinder(options.tipRadius, cylLength), shapePosition, (new CANNON.Quaternion()).setFromAxisAngle(CANNON.Vec3.UNIT_X, 0.5*Math.PI));
            } else {
                toolBody.addShape(new CANNON.Cylinder(options.tipRadius, options.tipRadius, cylLength, options.numSegments), shapePosition);
            }
        }

        // to store decomposed toolRoot world matrix, used to convert three.js local coords to cannon.js world coords:
        var worldPosition = new THREE.Vector3();
        var worldQuaternion = new THREE.Quaternion();
        var worldScale = new THREE.Vector3();
        // inverse of toolRoot.matrixWorld, used for converting cannon.js world coords to three.js local coords:
        var matrixWorldInverse = new THREE.Matrix4();

        function updateToolMapping() {
            toolRoot.matrixWorld.decompose(worldPosition, worldQuaternion, worldScale);
            matrixWorldInverse.getInverse(toolRoot.matrixWorld);
        }

        function updateToolPostStep() {
            toolMesh.position.copy(toolBody.interpolatedPosition);
            toolMesh.position.applyMatrix4(matrixWorldInverse);
            toolMesh.updateMatrix();
            if (toolShadowMesh) {
                toolShadowMesh.updateMatrix();
            }
        }

        var direction = new THREE.Vector3();
        var position = new THREE.Vector3();
        var velocity = new THREE.Vector3();
        var quaternion = new THREE.Quaternion();

        var deadtime = 0;

        var lastFrameID;

        function setDeadtime(t) {
            deadtime = t;
            if (deadtime === 0) {
                interactionBoxRoot.visible = true;
                interactionPlaneMaterial.opacity = options.interactionPlaneOpacity;
            }
        }

        function updateTool(dt) {

            deadtime += dt;

            var frame = leapController.frame();
            if (frame.valid && frame.id !== lastFrameID) {

                lastFrameID = frame.id;

                var interactionBox = frame.interactionBox;
                if (interactionBox.valid) {
                    interactionBoxRoot.position.fromArray(interactionBox.center);
                    interactionBoxRoot.scale.set(interactionBox.width*LEAP2METERS, interactionBox.height*LEAP2METERS, interactionBox.depth*LEAP2METERS);
                    interactionBoxRoot.updateMatrix();
                    interactionBoxRoot.updateMatrixWorld();
                }

                if (frame.tools.length === 1) {

                    deadtime = 0;

                    var tool = frame.tools[0];

                    if (toolMesh.visible === false || toolMesh.material.opacity < 1) {
                        toolMesh.visible = true;

                        if (toolShadowMesh) toolShadowMesh.visible = true;

                        toolMesh.material.opacity = 1;
                        if (tipMesh) tipMesh.material.opacity = 1;
                        interactionBoxRoot.visible = true;
                        interactionPlaneMaterial.opacity = options.interactionPlaneOpacity;
                    }

                    position.fromArray(tool.tipPosition);
                    //position.fromArray(tool.stabilizedTipPosition);
                    direction.fromArray(tool.direction);

                    toolMesh.position.copy(position);
                    position.applyMatrix4(toolRoot.matrixWorld);
                    toolBody.position.copy(position);

                    toolMesh.quaternion.setFromUnitVectors(FORWARD, direction);

                    quaternion.multiplyQuaternions(worldQuaternion, toolMesh.quaternion);
                    toolBody.quaternion.copy(quaternion);

                    toolMesh.updateMatrix();
                    toolMesh.updateMatrixWorld();

                    if (toolShadowMesh) {
                        toolShadowMesh.updateMatrix();
                        toolShadowMesh.updateMatrixWorld();
                    }

                    velocity.fromArray(tool.tipVelocity);
                    velocity.applyQuaternion(worldQuaternion);
                    velocity.multiplyScalar(LEAP2METERS);
                    toolBody.velocity.copy(velocity);

                    if (tool.timeVisible > options.timeA) {
                        // stick becomes collidable once it has been detected for some time
                        if (toolBody.sleepState === CANNON.Body.SLEEPING) {
                            toolBody.wakeUp();
                            // TODO: indicator (particle effect)
                            if (tipMesh) tipMesh.material.color.setHex(0xff0000);
                        }

                        if (tool.timeVisible > options.timeB && interactionPlaneMaterial.opacity > 0.1) {
                            // dim the interaction box:
                            interactionPlaneMaterial.opacity *= 0.94;
                        }

                    }

                } else if (toolBody.sleepState === CANNON.Body.AWAKE) {
                    // tool detection was just lost
                    toolBody.sleep();
                    if (tipMesh) tipMesh.material.color.setHex(options.tipColor);

                } else {
                    // tool is already lost
                    if (toolMesh.visible && toolMesh.material.opacity > 0.1) {
                        // fade out tool
                        toolMesh.material.opacity *= 0.8;
                        if (tipMesh) tipMesh.material.opacity = toolMesh.material.opacity;
                    } else {
                        toolMesh.visible = false;
                        if (toolShadowMesh) toolShadowMesh.visible = false;
                    }
                }

                updateHands(frame);

            }

            if ( deadtime > 1.5 && interactionBoxRoot.visible ) {
                interactionPlaneMaterial.opacity *= 0.93;
                if (interactionPlaneMaterial.opacity < 0.02) interactionBoxRoot.visible = false;
            }

        }

        // setup hands:

        // hands don't necessarily correspond the left / right labels, but doesn't matter in this case because they look indistinguishable
        var leftRoot = new THREE.Object3D(),
            rightRoot = new THREE.Object3D();
        var handRoots = [leftRoot, rightRoot];
        toolRoot.add(leftRoot);
        toolRoot.add(rightRoot);

        var handMaterial = new THREE.MeshBasicMaterial({color: options.handColor, transparent: true, opacity: 0});

        // arms:
        var armRadius = METERS2LEAP*0.021,
            armLength = METERS2LEAP*0.22;
        var armGeom = new THREE.CylinderGeometry(armRadius, armRadius, armLength);
        bufferGeom = new THREE.BufferGeometry();
        bufferGeom.fromGeometry(armGeom);
        armGeom.dispose();
        armGeom = bufferGeom;
        var armMesh = new THREE.Mesh(armGeom, handMaterial);
        var arms = [armMesh, armMesh.clone()];
        leftRoot.add(arms[0]);
        rightRoot.add(arms[1]);
        // palms:
        var radius = METERS2LEAP*0.02;
        var palmGeom = new THREE.SphereBufferGeometry(radius).scale(1, 0.4, 1);
        var palmMesh = new THREE.Mesh(palmGeom, handMaterial);
        var palms = [palmMesh, palmMesh.clone()];
        leftRoot.add(palms[0]);
        rightRoot.add(palms[1]);

        // var textureLoader = new THREE.TextureLoader();
        // var spriteTexture = textureLoader.load('/node_modules/three/examples/textures/sprite1.png'); , function (texture) {
        // } );
        // var spriteMaterial = new THREE.SpriteMaterial({map: spriteTexture});
        // var sphereSprite = new THREE.Sprite(spriteMaterial);

        // fingertips:
        radius = METERS2LEAP*0.005;
        var fingerTipGeom = new THREE.SphereBufferGeometry(radius);
        var fingerTipMesh = new THREE.Mesh(fingerTipGeom, handMaterial);
        // var fingerTipMesh = sphereSprite.clone();
        // fingerTipMesh.scale.set(radius, radius, radius);
        var fingerTips = [[fingerTipMesh, fingerTipMesh.clone(), fingerTipMesh.clone(), fingerTipMesh.clone(), fingerTipMesh.clone()],
                          [fingerTipMesh.clone(), fingerTipMesh.clone(), fingerTipMesh.clone(), fingerTipMesh.clone(), fingerTipMesh.clone()]];
        leftRoot.add(fingerTips[0][0], fingerTips[0][1], fingerTips[0][2], fingerTips[0][3], fingerTips[0][4]);
        rightRoot.add(fingerTips[1][0], fingerTips[1][1], fingerTips[1][2], fingerTips[1][3], fingerTips[1][4]);
        // finger joints:
        var jointMesh = fingerTipMesh.clone();
        jointMesh.scale.set(7/5, 7/5, 7/5);
        var joints = [[jointMesh, jointMesh.clone(), jointMesh.clone(), jointMesh.clone(), jointMesh.clone()],
                      [jointMesh.clone(), jointMesh.clone(), jointMesh.clone(), jointMesh.clone(), jointMesh.clone()]];
        leftRoot.add(joints[0][0], joints[0][1], joints[0][2], joints[0][3], joints[0][4]);
        rightRoot.add(joints[1][0], joints[1][1], joints[1][2], joints[1][3], joints[1][4]);
        var joint2Mesh = fingerTipMesh.clone();
        joint2Mesh.scale.set(55/50, 55/50, 55/50);
        var joint2s = [[joint2Mesh, joint2Mesh.clone(), joint2Mesh.clone(), joint2Mesh.clone(), joint2Mesh.clone()],
                       [joint2Mesh.clone(), joint2Mesh.clone(), joint2Mesh.clone(), joint2Mesh.clone(), joint2Mesh.clone()]];
        leftRoot.add(joint2s[0][0], joint2s[0][1], joint2s[0][2], joint2s[0][3], joint2s[0][4]);
        rightRoot.add(joint2s[1][0], joint2s[1][1], joint2s[1][2], joint2s[1][3], joint2s[1][4]);
        var joint3Mesh = fingerTipMesh.clone();
        joint3Mesh.scale.set(7/5, 7/5, 7/5);
        var joint3s = [[joint3Mesh, joint3Mesh.clone(), joint3Mesh.clone(), joint3Mesh.clone()],
                       [joint3Mesh.clone(), joint3Mesh.clone(), joint3Mesh.clone(), joint3Mesh.clone()]];
        leftRoot.add(joint3s[0][0], joint3s[0][1], joint3s[0][2], joint3s[0][3]);
        rightRoot.add(joint3s[1][0], joint3s[1][1], joint3s[1][2], joint3s[1][3]);

        function updateHands(frame) {
            leftRoot.visible = rightRoot.visible = false;
            for (var i = 0; i < frame.hands.length; i++) {
                var hand = frame.hands[i];
                if (hand.confidence > options.minConfidence) {

                    handRoots[i].visible = true;
                    handMaterial.opacity = 0.5*handMaterial.opacity + 0.5*(hand.confidence - options.minConfidence) / (1 - options.minConfidence);

                    var arm = arms[i];
                    direction.fromArray(hand.arm.basis[2]);
                    arm.quaternion.setFromUnitVectors(UP, direction);
                    arm.position.fromArray(hand.arm.center());
                    arm.updateMatrix();

                    var palm = palms[i];
                    direction.fromArray(hand.palmNormal);
                    palm.quaternion.setFromUnitVectors(UP, direction);
                    palm.position.fromArray(hand.palmPosition);
                    palm.updateMatrix();

                    var handFingerTips = fingerTips[i];
                    var handJoints = joints[i];
                    var handJoint2s = joint2s[i];
                    var handJoint3s = joint3s[i];
                    for (var j = 0; j < hand.fingers.length; j++) {
                        var finger = hand.fingers[j];
                        handFingerTips[j].position.fromArray(finger.tipPosition);
                        handFingerTips[j].updateMatrix();
                        handJoints[j].position.fromArray(finger.bones[1].nextJoint);
                        handJoints[j].updateMatrix();
                        handJoint2s[j].position.fromArray(finger.bones[2].nextJoint);
                        handJoint2s[j].updateMatrix();
                    }
                    for (j = 0; j < 4; j++) {
                        finger = hand.fingers[j+1];
                        handJoint3s[j].position.fromArray(finger.bones[1].prevJoint);
                        handJoint3s[j].updateMatrix();
                    }
                }
            }
        }

        // initialize matrices:
        toolRoot.traverse( function (node) {
            node.matrixAutoUpdate = false;
            node.updateMatrix();
        } );

        interactionBoxRoot.visible = false;
        toolMesh.visible = false;
        if (toolShadowMesh) toolShadowMesh.visible = false;
        leftRoot.visible  = false;
        rightRoot.visible = false;

        return {
            leapController:     leapController,
            toolRoot:           toolRoot,
            toolMesh:           toolMesh,
            toolBody:           toolBody,
            updateTool:         updateTool,
            updateToolPostStep: updateToolPostStep,
            updateToolMapping:  updateToolMapping,
            setDeadtime:        setDeadtime,
            toolShadowMesh: toolShadowMesh,
            worldQuaternion: worldQuaternion,
            worldPosition: worldPosition
        };
    }

    return {
        makeTool: makeTool
    };

} )();


text:
CCScene* CCHierarchiesSpriteTestScene::scene()
{
    // 'scene' is an autorelease object
    CCScene *scene = CCScene::create();

    // 'layer' is an autorelease object
    CCHierarchiesSpriteTestScene *layer = CCHierarchiesSpriteTestScene::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

CCHierarchiesSpriteTestScene::~CCHierarchiesSpriteTestScene () {
    CC_SAFE_RELEASE(_hSprites);
}

bool CCHierarchiesSpriteTestScene::init()
{
    if ( !CCLayer::init() )
    {
        return false;
    }

    this->setTouchEnabled(true);

    this->scheduleUpdate();

    _hSprites = new CCArray();
    _hSprites->init();

//    CCDirector::sharedDirector()->getScheduler()->setTimeScale(0.5);

    CCLayerColor* bgLayer = CCLayerColor::create(ccc4(64, 64, 64, 255));
    this->addChild(bgLayer, -1000);

    this->loadSprites();

    return true;
}

#pragma mark - Update

void CCHierarchiesSpriteTestScene::update (float delta) {

}

#pragma mark - Draw

void CCHierarchiesSpriteTestScene::draw () {

}

#pragma mark - Touch callback

void CCHierarchiesSpriteTestScene::ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent) {
    // 点击测试
    CCTouch* touch = (CCTouch*)pTouches->anyObject();
    CCPoint touchPoint = touch->getLocation();
    CCLOG("hit at %f, %f", touchPoint.x, touchPoint.y);

    CCObject* iter = NULL;
    CCARRAY_FOREACH(_hSprites, iter) {
        CCHierarchiesSprite* spr = dynamic_cast<CCHierarchiesSprite*>(iter);
        if (spr && spr->boundingBox().containsPoint(touchPoint)) {
            CCLOG("hit %s with %u * fxattack", spr->getAnimationName(), spr->getEventContentCount("fxattack"));
        }
    }

    // 资源管理测试
    if (_hSprites->count() > 0) {
        CCLOG("release unused resource BEGIN");
        report_memory();

        CCObject* iter = NULL;
        CCARRAY_FOREACH(_hSprites, iter) {
            CCHierarchiesSprite* spr = dynamic_cast<CCHierarchiesSprite*>(iter);
            spr->removeFromParent();
        }
        _hSprites->removeAllObjects();

        CCHierarchiesSpriteRuntime::sharedHierarchiesSpriteRuntime()->releaseUnusedResource();
        CCTextureCache::sharedTextureCache()->removeUnusedTextures();

        report_memory();
        CCLOG("release unused resource END");
    }
    else {
        this->loadSprites();
    }

    report_memory();
}

void CCHierarchiesSpriteTestScene::ccTouchesMoved(CCSet *pTouches, CCEvent *pEvent) {
}

void CCHierarchiesSpriteTestScene::ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent) {
}

void CCHierarchiesSpriteTestScene::ccTouchesCancelled(CCSet *pTouches, CCEvent *pEvent) {
}

#pragma mark - CCHierarchiesSpriteEventDelegate

void CCHierarchiesSpriteTestScene::onEventContent (CCHierarchiesSpriteBase* sprite, const char* eventContent) {
    // 动画事件测试
    CCLOG("on event content [%s] [%s]", sprite->getAnimationName(), eventContent);
}

void CCHierarchiesSpriteTestScene::loadSprites () {
    CCSize winSize = CCDirector::sharedDirector()->getWinSize();

    CCLOG("load sprites BEGIN");
    report_memory();

#define SPRITE_ARRAY_COL_COUNT (4)
#define SPRITE_ARRAY_ROW_COUNT (4)
    for (int i = 0; i < SPRITE_ARRAY_ROW_COUNT; i++) {
        for (int j = 1; j <= SPRITE_ARRAY_COL_COUNT; j++) {
            CCHierarchiesSprite* spr = NULL;

            switch (j % 4) {
                case 0: {
                    spr = CCHierarchiesSprite::create("test_new_anim/hanim_test_lvmeng/lumengquan.hsheet",
                                                      "test_new_anim/hanim_test_lvmeng/lumengquan.hanims",
                                                      this);
                    break;
                }
                case 1: {
                    spr = CCHierarchiesSprite::create("test_new_anim/hanim_test_taishici/taishiciquan.hsheet",
                                                      "test_new_anim/hanim_test_taishici/taishiciquan.hanims",
                                                      this);
                    spr->setOpacity(128);
                    break;
                }
                case 2: {
                    spr = CCHierarchiesSprite::create("test_new_anim/hanim_test_xiahouyuan/xiahouyuanquan.hsheet",
                                                      "test_new_anim/hanim_test_xiahouyuan/xiahouyuanquan.hanims",
                                                      this);
                    spr->setFlipX(true);
                    break;
                }
                case 3: {
                    spr = CCHierarchiesSprite::create("test_new_anim/hanim_test_zhangjiao/zhangjiaoquan.hsheet",
                                                      "test_new_anim/hanim_test_zhangjiao/zhangjiaoquan.hanims",
                                                      this);
                    spr->setColor(ccRED);
                    break;
                }
            }

            spr->setPosition(ccp(winSize.width / (SPRITE_ARRAY_COL_COUNT + 1) * j, winSize.height / (SPRITE_ARRAY_ROW_COUNT + 1) * i));

            CCAction* action = NULL;
            action = CCRepeatForever::create(CCHierarchiesAnimate::createWholeAnimation(spr->getAnimationName()));
            spr->runAction(action);

            spr->setZOrder((SPRITE_ARRAY_ROW_COUNT - i) * SPRITE_ARRAY_COL_COUNT + j);
            this->addChild(spr);

            _hSprites->addObject(spr);
        }
    }

    CCLOG("load sprites END");
    report_memory();
}

redpajama_set_name: RedPajamaGithub


text:
const getPublishTags = require('./get-publish-tags');

module.exports = function getPublishInfo (packageInfo) {
    const PUBLISH_TAGS = getPublishTags(packageInfo);
    const PUBLISH_REPO = 'testcafe/testcafe';

    return {
        PUBLISH_TAGS,
        PUBLISH_REPO,
    };
};


text:
using Invoice.Core.Domain;
using Invoice.Core.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Text;

namespace Invoice.Infrastructure.EF
{
    public class InvoiceContext : DbContext
    {
        private readonly SqlSettings _settings;
        public DbSet<User> Users { get; set; }
        public DbSet<Customer> Customers { get; set; }
        public DbSet<InvoiceDocument> InvoiceDocuments { get; set; }

        public InvoiceContext(DbContextOptions<InvoiceContext> options, SqlSettings settings) : base(options)
        {
            _settings = settings;
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if(_settings.InMemory)
            {
                optionsBuilder.UseInMemoryDatabase();

                return;
            }
            optionsBuilder.UseSqlServer(_settings.ConnectionString);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            var userBuilder = modelBuilder.Entity<User>();
            userBuilder.HasKey(x => x.Id);
            var customerBuilder = modelBuilder.Entity<Customer>();
            customerBuilder.HasKey(x => x.Id);
            var invoiceDocumentBuilder = modelBuilder.Entity<InvoiceDocument>();
            invoiceDocumentBuilder.HasKey(x => x.Id);
        }
    }
}


text:
<configuration>
    <jmxConfigurator />

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%-5level [%thread] %F:%L %msg%n</pattern>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="STDOUT" />
    </root>

    <logger name="org.apache.cassandra" level="INFO"/>
    <logger name="com.thinkaurelius.thrift" level="ERROR"/>
</configuration>


text:
'''
Miscellaneous helper functions
'''

import re
from . import lut

def _Z_from_str(s):
    if s.isdecimal():
        return int(s)
    else:
        return lut.element_Z_from_sym(s)

def transpose_matrix(mat):
    '''Transposes a matrix (list of lists) commonly done do coefficients'''

    return list(map(list, zip(*mat)))

def max_am(shells):
    '''Determine the maximum angular momentum of a list of shells or potentials'''
    all_am = [max(x['angular_momentum']) for x in shells]
    return max(all_am)

def contraction_string(element):
    """
    Forms a string specifying the contractions for an element

    ie, (16s,10p) -> [4s,3p]
    """

    # Does not have electron shells (ECP only?)
    if 'electron_shells' not in element:
        return ""

    cont_map = dict()
    for sh in element['electron_shells']:
        nprim = len(sh['exponents'])
        ngeneral = len(sh['coefficients'])

        # is a combined general contraction (sp, spd, etc)
        is_spdf = len(sh['angular_momentum']) > 1

        for am in sh['angular_momentum']:
            # If this a general contraction (and not combined am), then use that
            ncont = ngeneral if not is_spdf else 1

            if am not in cont_map:
                cont_map[am] = (nprim, ncont)
            else:
                cont_map[am] = (cont_map[am][0] + nprim, cont_map[am][1] + ncont)

    primstr = ""
    contstr = ""
    for am in sorted(cont_map.keys()):
        nprim, ncont = cont_map[am]

        if am != 0:
            primstr += ','
            contstr += ','
        primstr += str(nprim) + lut.amint_to_char([am])
        contstr += str(ncont) + lut.amint_to_char([am])

    return "({}) -> [{}]".format(primstr, contstr)

def compact_elements(elements):
    """
    Create a string (with ranges) given a list of element numbers

    For example, [1, 2, 3, 6, 7, 8, 10] will return "H-Li,C-O,Ne"
   """

    if not elements:
        return

    # We have to convert to integers for this function
    elements = [int(el) for el in elements]

    # Just to be safe, sort the list
    el = sorted(set(elements))

    ranges = []
    i = 0
    while i < len(el):
        start_el = el[i]
        end_el = start_el

        i += 1
        while i < len(el):
            if el[i] != end_el + 1:
                break

            end_el += 1
            i += 1

        if start_el == end_el:
            ranges.append([start_el])
        else:
            ranges.append([start_el, end_el])

    # Convert to elemental symbols
    range_strs = []
    for r in ranges:
        sym = lut.element_sym_from_Z(r[0], True)

        if len(r) == 1:
            range_strs.append(sym)
        elif len(r) == 2 and r[1] == r[0] + 1:
            sym2 = lut.element_sym_from_Z(r[1], True)
            range_strs.append(sym + "," + sym2)
        else:
            sym2 = lut.element_sym_from_Z(r[1], True)
            range_strs.append(sym + "-" + sym2)

    return ",".join(range_strs)

def expand_elements(compact_el, as_str=False):
    """
    Create a list of integers given a string or list of compacted elements

    This is partly the opposite of compact_elements, but is more flexible.

    compact_el can be a list or a string. If compact_el is a list, each element is processed individually
    as a string (meaning list elements can contain commas, ranges, etc)
    If compact_el is a string, it is split by commas and then each section is processed.

    In all cases, element symbols (case insensitive) and Z numbers (as integers or strings)
    can be used interchangeably. Ranges are also allowed in both lists and strings.

    Some examples:
        "H-Li,C-O,Ne" will return [1, 2, 3, 6, 7, 8, 10]
        "H-N,8,Na-12" will return [1, 2, 3, 4, 5, 6, 7, 8, 11, 12]
        ['C', 'Al-15,S', 17, '18'] will return [6, 13, 14, 15, 16, 17, 18]

    If as_str is True, the list will contain strings of the integers
    (ie, the first example above will return ['1', '2', '3', '6', '7', '8', '10']
    """

    # If an integer, just return it
    if isinstance(compact_el, int):
        if as_str:
            return [str(compact_el)]
        else:
            return [compact_el]

    # If compact_el is a list, make it a comma-separated string
    if isinstance(compact_el, list):
        compact_el = [str(x) for x in compact_el]
        compact_el = [x for x in compact_el if x]
        compact_el = ','.join(compact_el)

    # Find multiple - or ,
    # Also replace all whitespace with spaces
    compact_el = re.sub(r',+', ',', compact_el)
    compact_el = re.sub(r'-+', '-', compact_el)
    compact_el = re.sub(r'\s+', '', compact_el)

    # Find starting with or ending with comma and strip them
    compact_el = compact_el.strip(',')

    # Check if I was passed an empty string or list
    if not compact_el:
        return []

    # Find some erroneous patterns
    # -, and ,-
    if '-,' in compact_el:
        raise RuntimeError("Malformed element string")
    if ',-' in compact_el:
        raise RuntimeError("Malformed element string")

    # Strings ends or begins with -
    if compact_el.startswith('-') or compact_el.endswith('-'):
        raise RuntimeError("Malformed element string")

    # x-y-z
    if re.search(r'\w+-\w+-\w+', compact_el):
        raise RuntimeError("Malformed element string")

    # Split on commas
    tmp_list = compact_el.split(',')

    # Now go over each one and replace elements with ints
    el_list = []
    for el in tmp_list:
        if '-' not in el:
            el_list.append(_Z_from_str(el))
        else:
            begin, end = el.split('-')
            begin = _Z_from_str(begin)
            end = _Z_from_str(end)
            el_list.extend(list(range(begin, end + 1)))

    if as_str:
        return [str(x) for x in el_list]
    else:
        return el_list

def transform_basis_name(name):
    """
    Transforms the name of a basis set to an internal representation

    This makes comparison of basis set names easier by, for example,
    converting the name to all lower case.
    """

    name = name.lower()
    name = name.replace('/', '_sl_')
    name = name.replace('*', '_st_')
    return name

def basis_name_to_filename(name):
    '''
    Given a basis set name, transform it into a valid filename

    This makes sure filenames don't contain invalid characters
    '''

    return transform_basis_name(name)

def basis_name_from_filename(filename):
    '''
    Given a basis set name that was part of a filename, determine the basis set name

    This is opposite of :func:`transform_basis_name`

    Pass only the part of the filename that contains the basis set name
    '''

    name = filename.lower()
    name = name.replace('_sl_', '/')
    name = name.replace('_st_', '*')
    return name


text:
{% load i18n %}

{% block pre_login %}
<form id="" class="ng-pristine ng-valid ng-scope"
      method="POST"
      action=""
      autocomplete="off"
      ng-controller="hzLoginController">
  {% csrf_token %}
{% endblock %}

    {% block login_header %}

        {% trans 'Change password' %}

    {% endblock %}

    {% block login_body %}
      {% comment %}
        These fake fields are required to prevent Chrome v34+ from autofilling form.
      {% endcomment %}
      {% if HORIZON_CONFIG.password_autocomplete != "on" %}

          <input type="text" name="fake_email" value="" />
          <input type="password" name="fake_password" value="" />

      {%endif%}
      <fieldset hz-login-finder>
        {% if request.COOKIES.logout_reason %}
          {% if request.COOKIES.logout_status == "success" %}

          {% else %}

          {% endif %}

{{ request.COOKIES.logout_reason }}

        {% endif %}
        {% include "horizon/common/_form_fields.html" %}
      </fieldset>
    {% endblock %}

      {% block login_footer %}
        <button id="changeBtn" type="submit" class="btn btn-primary pull-right">
          {% trans "Change" %}
        </button>

      {% endblock %}

{% block post_login%}
</form>
{% endblock %}


text:
JNIEXPORT jstring JNICALL Java_com_qf_teach_project_zhihudaily_c_API_getThemesUrl(
		JNIEnv *env, jclass thiz) {
	return (*env)->NewStringUTF(env, "http://news-at.zhihu.com/api/3/themes");
}

JNIEXPORT jstring JNICALL Java_com_qf_teach_project_zhihudaily_c_API_getStartImageUrl(
		JNIEnv *env, jclass thiz) {
	return (*env)->NewStringUTF(env,
			"http://news-at.zhihu.com/api/3/start-image/480*728");
}

JNIEXPORT jstring JNICALL Java_com_qf_teach_project_zhihudaily_c_API_getLatestUrl(
		JNIEnv *env, jclass thiz) {
	return (*env)->NewStringUTF(env,
			"http://news-at.zhihu.com/api/3/stories/latest");
}

JNIEXPORT jstring JNICALL Java_com_qf_teach_project_zhihudaily_c_API_getBefore(
		JNIEnv *env, jclass thiz) {
	return (*env)->NewStringUTF(env,
				"http://news-at.zhihu.com/api/3/stories/before/%s");
}

JNIEXPORT jstring JNICALL Java_com_qf_teach_project_zhihudaily_c_API_getTheme
  (JNIEnv *env, jclass thiz) {
	return (*env)->NewStringUTF(env,
					"http://news-at.zhihu.com/api/3/theme/%s");
}

JNIEXPORT jstring JNICALL Java_com_qf_teach_project_zhihudaily_c_API_getStory
  (JNIEnv *env, jclass thiz) {
	return (*env)->NewStringUTF(env,
						"http://news-at.zhihu.com/api/3/story/%s");
}

JNIEXPORT jstring JNICALL Java_com_qf_teach_project_zhihudaily_c_API_getStoryExtra
  (JNIEnv *env, jclass thiz) {
	return (*env)->NewStringUTF(env,
						"http://news-at.zhihu.com/api/3/story-extra/%s");
}


text:
/**
 * Contains the potential errors thrown by a lock.
 */

var util = require('util');

/**
 * The constructor for a LockAcquisitionError. Thrown or returned when a lock
 * could not be acquired.
 *
 * @constructor
 * @extends Error
 *
 * @param {string} message The message to assign the error
 */
function LockAcquisitionError(message) {
  Error.captureStackTrace(this, LockAcquisitionError);
  this.name = 'LockAcquisitionError';
  this.message = message;
}

/**
 * The constructor for a LockReleaseError. Thrown or returned when a lock
 * could not be released.
 *
 * @constructor
 * @extends Error
 *
 * @param {string} message The message to assign the error
 */
function LockReleaseError(message) {
  Error.captureStackTrace(this, LockReleaseError);
  this.name = 'LockReleaseError';
  this.message = message;
}

/**
 * The constructor for a LockExtendError. Thrown or returned when a lock
 * could not be extended.
 *
 * @constructor
 * @extends Error
 *
 * @param {string} message The message to assign the error
 */
function LockExtendError(message) {
  Error.captureStackTrace(this, LockExtendError);
  this.name = 'LockExtendError';
  this.message = message;
}

util.inherits(LockAcquisitionError, Error);
util.inherits(LockReleaseError, Error);
util.inherits(LockExtendError, Error);

exports.LockAcquisitionError = LockAcquisitionError;
exports.LockReleaseError     = LockReleaseError;
exports.LockExtendError      = LockExtendError;


text:
using Foundation;
using Xamarin.Forms;
using XyTodo.Cross;
using XyTodo.iOS.Cross;

[assembly: Dependency( typeof( CrossUserPreferences ) )]
namespace XyTodo.iOS.Cross
{
    class CrossUserPreferences : ICrossUserPreferences
    {
        public void Clear()
        {
            throw new System.NotImplementedException();
        }

        public string GetString( string key )
        {
            var rst = "";
            rst = NSUserDefaults.StandardUserDefaults.StringForKey( key );
            return rst;
        }

        public void PutString( string key, string value )
        {
            NSUserDefaults.StandardUserDefaults.SetString( value, key );
        }

        public int GetInt( string key )
        {
            var rst = 0;
            rst = (int) NSUserDefaults.StandardUserDefaults.IntForKey( key );
            return rst;
        }

        public void PutInt( string key, int value )
        {
            NSUserDefaults.StandardUserDefaults.SetInt( value, key );
        }
    }
}


text:
#include <aws/clouddirectory/model/ListObjectPoliciesRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

#include <utility>

using namespace Aws::CloudDirectory::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

ListObjectPoliciesRequest::ListObjectPoliciesRequest() :
    m_directoryArnHasBeenSet(false),
    m_objectReferenceHasBeenSet(false),
    m_nextTokenHasBeenSet(false),
    m_maxResults(0),
    m_maxResultsHasBeenSet(false),
    m_consistencyLevel(ConsistencyLevel::NOT_SET),
    m_consistencyLevelHasBeenSet(false)
{
}

Aws::String ListObjectPoliciesRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_objectReferenceHasBeenSet)
  {
   payload.WithObject("ObjectReference", m_objectReference.Jsonize());

  }

  if(m_nextTokenHasBeenSet)
  {
   payload.WithString("NextToken", m_nextToken);

  }

  if(m_maxResultsHasBeenSet)
  {
   payload.WithInteger("MaxResults", m_maxResults);

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection ListObjectPoliciesRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  Aws::StringStream ss;
  if(m_directoryArnHasBeenSet)
  {
    ss << m_directoryArn;
    headers.emplace("x-amz-data-partition",  ss.str());
    ss.str("");
  }

  if(m_consistencyLevelHasBeenSet)
  {
    headers.emplace("x-amz-consistency-level", ConsistencyLevelMapper::GetNameForConsistencyLevel(m_consistencyLevel));
  }

  return headers;

}


text:
spring_tutorial
===============


text:
<?php

declare(strict_types=1);

namespace Kreta\TaskManager\Application\Query\Organization;

class OrganizationOfIdQuery
{
    private $organizationId;
    private $userId;

    public function __construct(string $organizationId, string $userId)
    {
        $this->organizationId = $organizationId;
        $this->userId = $userId;
    }

    public function organizationId() : string
    {
        return $this->organizationId;
    }

    public function userId() : string
    {
        return $this->userId;
    }
}


text:
/* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * aapt tool from the resource data it found.  It
 * should not be modified by hand.
 */

package com.hunterdavis.easytonedialer;

public final class R {
    public static final class attr {
    }
    public static final class drawable {
        public static final int icon=0x7f020000;
    }
    public static final class id {
        public static final int adView=0x7f050000;
        public static final int dialbutton=0x7f050015;
        public static final int dialnums=0x7f050016;
        public static final int dialtable=0x7f050014;
        public static final int eightbutton=0x7f05000b;
        public static final int firstrow=0x7f050001;
        public static final int fivebutton=0x7f050007;
        public static final int fourbutton=0x7f050006;
        public static final int fourthrow=0x7f05000d;
        public static final int freq=0x7f050013;
        public static final int freqbutton=0x7f050012;
        public static final int frequencytable=0x7f050011;
        public static final int ninebutton=0x7f05000c;
        public static final int onebutton=0x7f050002;
        public static final int poundbutton=0x7f050010;
        public static final int secondrow=0x7f050005;
        public static final int sevenbutton=0x7f05000a;
        public static final int sixbutton=0x7f050008;
        public static final int starbutton=0x7f05000e;
        public static final int thirdrow=0x7f050009;
        public static final int threebutton=0x7f050004;
        public static final int twobutton=0x7f050003;
        public static final int zerobutton=0x7f05000f;
    }
    public static final class layout {
        public static final int main=0x7f030000;
    }
    public static final class string {
        public static final int app_name=0x7f040001;
        public static final int hello=0x7f040000;
    }
}


text:
        <form>
            Search all {{searchType}}

                <input
                    #searchInput
                    type="text"
                    id="search"
                    class="form-control"
                    placeholder="Search available {{searchType}}"
                    (keyup)="searchContent(searchInput.value)">

                    <input
                        type="reset"
                        class="btn btn-default"
                        value="Clear"
                        (click)="clearQuestionSearchResults()"
                        [disabled]="!searchInput.value">

        </form>


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include layout="@layout/include_toolbar"/>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler"
        android:layout_marginTop="?attr/actionBarSize"
        android:paddingBottom="@dimen/item_list_height"
        android:clipToPadding="false"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab_view_articles"
        android:src="@drawable/ic_view_articles"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:elevation="6dp"
        android:layout_marginBottom="@dimen/big_margin"
        android:layout_marginRight="@dimen/big_margin"
        android:layout_gravity="bottom|right"
        />

</android.support.design.widget.CoordinatorLayout>


text:
<?php

namespace Amadeus\Client\Struct\Fop;

/**
 * InvoiceFormOfPayment
 *
 * @package Amadeus\Client\Struct\Fop
 * @author Dieter Devlieghere <dermikagh@gmail.com>
 */
class InvoiceFormOfPayment extends FormOfPayment
{
    const INDICATOR_COLLECTIVE_INVOICE = "C";

    /**
     * self::INDICATOR_*
     *
     * @var string
     */
    public $indicator;

    /**
     * @var string
     */
    public $merchantCode;

    /**
     * @var string
     */
    public $expiryDate;

    /**
     * @var string
     */
    public $customerAccount;

    /**
     * @var string
     */
    public $membershipStatus;

    /**
     * @var string
     */
    public $transactionInfo;

    /**
     * @var string
     */
    public $pinCode;

    /**
     * @var string
     */
    public $pinCodeType;

    /**
     * InvoiceFormOfPayment constructor.
     *
     * @param string $type
     * @param string $customerAccount
     * @param string $membershipStatus
     * @param string|null $merchantCode
     */
    public function __construct($type, $customerAccount, $membershipStatus, $merchantCode = null)
    {
        parent::__construct($type);
        $this->customerAccount = $customerAccount;
        $this->membershipStatus = $membershipStatus;
        $this->merchantCode = $merchantCode;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<schema
  xmlns="http://www.concrete5.org/doctrine-xml/0.5"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.concrete5.org/doctrine-xml/0.5 http://concrete5.github.io/doctrine-xml/doctrine-xml-0.5.xsd">

  <table name="btBLockTable">
    <field name="bID" type="integer">
      <unsigned/>
      <default value="0"/>
    </field>
  </table>

</schema>


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createFormValues = require('./createFormValues');

var _createFormValues2 = _interopRequireDefault(_createFormValues);

var _plain = require('./structure/plain');

var _plain2 = _interopRequireDefault(_plain);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.default = (0, _createFormValues2.default)(_plain2.default);


text:
#import "NSObject.h"

@class MFMailbox, MFMessageStore, NSArray, NSDictionary, NSMutableArray, NSMutableDictionary;

@interface _TransferOperation : NSObject
{
    NSMutableArray *_sourceMessages;
    NSMutableArray *_documentIDs;
    id _messagesForGmailLabelsToRemoveLock;
    NSMutableDictionary *_messagesForGmailLabelsToRemove;
    BOOL _editableDocuments;
    MFMessageStore *_sourceStore;
    MFMailbox *_destinationMailbox;
    NSArray *_unreadSourceMessages;
    NSArray *_destinationMessageIDs;
}

@property(readonly, nonatomic) BOOL editableDocuments; // @synthesize editableDocuments=_editableDocuments;
@property(retain) NSArray *destinationMessageIDs; // @synthesize destinationMessageIDs=_destinationMessageIDs;
@property(retain) NSArray *unreadSourceMessages; // @synthesize unreadSourceMessages=_unreadSourceMessages;
@property(readonly, nonatomic) MFMailbox *destinationMailbox; // @synthesize destinationMailbox=_destinationMailbox;
@property(readonly, nonatomic) MFMessageStore *sourceStore; // @synthesize sourceStore=_sourceStore;
- (id)popMessagesForGmailLabelsToRemove;
- (void)addMessage:(id)arg1 forLabelsToRemove:(id)arg2;
@property(readonly) NSDictionary *messagesForGmailLabelsToRemove;
- (void)removeSourceMessages:(id)arg1;
- (void)addSourceMessage:(id)arg1;
@property(retain, nonatomic) NSArray *sourceMessages;
@property(readonly, nonatomic) NSArray *documentIDs; // @synthesize documentIDs=_documentIDs;
- (id)sourceLibraryStore;
- (void)dealloc;
- (id)initWithSourceStore:(id)arg1 destinationMailbox:(id)arg2 editableDocuments:(BOOL)arg3;

@end


text:
class Admin::PlayerConferencesController < AdminController

  def index
    @player_conferences = PlayerConference.all
  end

  def show
    @player_conference = PlayerConference.find_by_id(params[:id])
  end

  def new
    @player_conference = PlayerConference.new
  end

  def create
    player_conference = PlayerConference.create!(player_conference_params)
    flash[:notice] = "Conference created"
    redirect_to admin_player_conference_path(player_conference)
  end

  def edit
    @player_conference = PlayerConference.find_by_id(params[:id])
  end

  def update
    player_conference = PlayerConference.find(params[:id])
    player_conference.update_attributes!(player_conference_params)
    flash[:notice] = "Conference updated"
    redirect_to admin_player_conference_path(player_conference)
  end

  def destroy
    PlayerConference.find(params[:id]).destroy
    flash[:notice] = "Conference deleted"
    redirect_to admin_player_conferences_path
  end

  private

  def player_conference_params
    params.require(:player_conference).permit(:name, :abbreviation)
  end

end


text:
/* Copied from commons-validator:commons-validator:1.7, with [PATCH] modifications */

package jenkins.org.apache.commons.validator.routines;

import java.io.Serializable;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;

/**
 *
URL Validation routines.

 * Behavior of validation is modified by passing in options:
 *

 *
ALLOW_2_SLASHES - [FALSE]  Allows double '/' characters in the path
 * component.

 *
NO_FRAGMENT- [FALSE]  By default fragments are allowed, if this option is
 * included then fragments are flagged as illegal.

 *
ALLOW_ALL_SCHEMES - [FALSE] By default only http, https, and ftp are
 * considered valid schemes.  Enabling this option will let any scheme pass validation.

 *

 *
 *
Originally based in on php script by Debbie Dyer, validation.php v1.2b, Date: 03/07/02,
 * http://javascript.internet.com. However, this validation now bears little resemblance
 * to the php original.

 *

 *   Example of usage:
 *   Construct a UrlValidator with valid schemes of "http", and "https".
 *
 *    String[] schemes = {"http","https"}.
 *    UrlValidator urlValidator = new UrlValidator(schemes);
 *    if (urlValidator.isValid("ftp://foo.bar.com/")) {
 *       System.out.println("url is valid");
 *    } else {
 *       System.out.println("url is invalid");
 *    }
 *
 *    prints "url is invalid"
 *   If instead the default constructor is used.
 *
 *    UrlValidator urlValidator = new UrlValidator();
 *    if (urlValidator.isValid("ftp://foo.bar.com/")) {
 *       System.out.println("url is valid");
 *    } else {
 *       System.out.println("url is invalid");
 *    }
 *
 *   prints out "url is valid"
 *

 *
 * @see
 *
 *  Uniform Resource Identifiers (URI): Generic Syntax
 *
 *
 * @version $Revision$
 * @since Validator 1.4
 */
//[PATCH]
@Restricted(NoExternalUse.class)
// end of [PATCH]
public class UrlValidator implements Serializable {

    private static final long serialVersionUID = 7557161713937335013L;

    private static final int MAX_UNSIGNED_16_BIT_INT = 0xFFFF; // port max

    /**
     * Allows all validly formatted schemes to pass validation instead of
     * supplying a set of valid schemes.
     */
    public static final long ALLOW_ALL_SCHEMES = 1 << 0;

    /**
     * Allow two slashes in the path component of the URL.
     */
    public static final long ALLOW_2_SLASHES = 1 << 1;

    /**
     * Enabling this options disallows any URL fragments.
     */
    public static final long NO_FRAGMENTS = 1 << 2;

    /**
     * Allow local URLs, such as http://localhost/ or http://machine/ .
     * This enables a broad-brush check, for complex local machine name
     *  validation requirements you should create your validator with
     *  a {@link RegexValidator} instead ({@link #UrlValidator(RegexValidator, long)})
     */
    public static final long ALLOW_LOCAL_URLS = 1 << 3; // CHECKSTYLE IGNORE MagicNumber

    /**
     * Protocol scheme (e.g. http, ftp, https).
     */
    private static final String SCHEME_REGEX = "^\\p{Alpha}[\\p{Alnum}\\+\\-\\.]*";
    private static final Pattern SCHEME_PATTERN = Pattern.compile(SCHEME_REGEX);

    // Drop numeric, and  "+-." for now
    // TODO does not allow for optional userinfo.
    // Validation of character set is done by isValidAuthority
    private static final String AUTHORITY_CHARS_REGEX = "\\p{Alnum}\\-\\."; // allows for IPV4 but not IPV6
    // Allow for IPv4 mapped addresses: ::FFF:123.123.123.123
    private static final String IPV6_REGEX = "::FFFF:(?:\\d{1,3}\\.){3}\\d{1,3}|[0-9a-fA-F:]+"; // do this as separate match because : could cause ambiguity with port prefix

    // userinfo    = *( unreserved / pct-encoded / sub-delims / ":" )
    // unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
    // sub-delims    = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
    // We assume that password has the same valid chars as user info
    private static final String USERINFO_CHARS_REGEX = "[a-zA-Z0-9%-._~!$&'()*+,;=]";
    // since neither ':' nor '@' are allowed chars, we don't need to use non-greedy matching
    private static final String USERINFO_FIELD_REGEX =
            USERINFO_CHARS_REGEX + "+" + // At least one character for the name
                    "(?::" + USERINFO_CHARS_REGEX + "*)?@"; // colon and password may be absent
    private static final String AUTHORITY_REGEX =
            "(?:\\[(" + IPV6_REGEX + ")\\]|(?:(?:" + USERINFO_FIELD_REGEX + ")?([" + AUTHORITY_CHARS_REGEX + "]*)))(?::(\\d*))?(.*)?";
    //             1                          e.g. user:pass@          2                                         3       4
    private static final Pattern AUTHORITY_PATTERN = Pattern.compile(AUTHORITY_REGEX);

    private static final int PARSE_AUTHORITY_IPV6 = 1;

    private static final int PARSE_AUTHORITY_HOST_IP = 2; // excludes userinfo, if present

    private static final int PARSE_AUTHORITY_PORT = 3; // excludes leading colon

    /**
     * Should always be empty. The code currently allows spaces.
     */
    private static final int PARSE_AUTHORITY_EXTRA = 4;

    private static final String PATH_REGEX = "^(/[-\\w:@&?=+,.!/~*'%$_;\\(\\)]*)?$";
    private static final Pattern PATH_PATTERN = Pattern.compile(PATH_REGEX);

    private static final String QUERY_REGEX = "^(\\S*)$";
    private static final Pattern QUERY_PATTERN = Pattern.compile(QUERY_REGEX);

    /**
     * Holds the set of current validation options.
     */
    private final long options;

    /**
     * The set of schemes that are allowed to be in a URL.
     */
    private final Set<String> allowedSchemes; // Must be lower-case

    /**
     * Regular expressions used to manually validate authorities if IANA
     * domain name validation isn't desired.
     */
    private final RegexValidator authorityValidator;

    /**
     * If no schemes are provided, default to this set.
     */
    private static final String[] DEFAULT_SCHEMES = {"http", "https", "ftp"}; // Must be lower-case

    /**
     * Singleton instance of this class with default schemes and options.
     */
    private static final UrlValidator DEFAULT_URL_VALIDATOR = new UrlValidator();

    /**
     * Returns the singleton instance of this class with default schemes and options.
     * @return singleton instance with default schemes and options
     */
    public static UrlValidator getInstance() {
        return DEFAULT_URL_VALIDATOR;
    }

    private final DomainValidator domainValidator;

    /**
     * Create a UrlValidator with default properties.
     */
    public UrlValidator() {
        this(null);
    }

    /**
     * Behavior of validation is modified by passing in several strings options:
     * @param schemes Pass in one or more url schemes to consider valid, passing in
     *        a null will default to "http,https,ftp" being valid.
     *        If a non-null schemes is specified then all valid schemes must
     *        be specified. Setting the ALLOW_ALL_SCHEMES option will
     *        ignore the contents of schemes.
     */
    public UrlValidator(String[] schemes) {
        this(schemes, 0L);
    }

    /**
     * Initialize a UrlValidator with the given validation options.
     * @param options The options should be set using the public constants declared in
     * this class.  To set multiple options you simply add them together.  For example,
     * ALLOW_2_SLASHES + NO_FRAGMENTS enables both of those options.
     */
    public UrlValidator(long options) {
        this(null, null, options);
    }

    /**
     * Behavior of validation is modified by passing in options:
     * @param schemes The set of valid schemes. Ignored if the ALLOW_ALL_SCHEMES option is set.
     * @param options The options should be set using the public constants declared in
     * this class.  To set multiple options you simply add them together.  For example,
     * ALLOW_2_SLASHES + NO_FRAGMENTS enables both of those options.
     */
    public UrlValidator(String[] schemes, long options) {
        this(schemes, null, options);
    }

    /**
     * Initialize a UrlValidator with the given validation options.
     * @param authorityValidator Regular expression validator used to validate the authority part
     * This allows the user to override the standard set of domains.
     * @param options Validation options. Set using the public constants of this class.
     * To set multiple options, simply add them together:
     *
{@code ALLOW_2_SLASHES + NO_FRAGMENTS}

     * enables both of those options.
     */
    public UrlValidator(RegexValidator authorityValidator, long options) {
        this(null, authorityValidator, options);
    }

    /**
     * Customizable constructor. Validation behavior is modified by passing in options.
     * @param schemes the set of valid schemes. Ignored if the ALLOW_ALL_SCHEMES option is set.
     * @param authorityValidator Regular expression validator used to validate the authority part
     * @param options Validation options. Set using the public constants of this class.
     * To set multiple options, simply add them together:
     *
{@code ALLOW_2_SLASHES + NO_FRAGMENTS}

     * enables both of those options.
     */
    public UrlValidator(String[] schemes, RegexValidator authorityValidator, long options) {
        this(schemes, authorityValidator, options, DomainValidator.getInstance(isOn(ALLOW_LOCAL_URLS, options)));
    }

    /**
     * Customizable constructor. Validation behavior is modified by passing in options.
     * @param schemes the set of valid schemes. Ignored if the ALLOW_ALL_SCHEMES option is set.
     * @param authorityValidator Regular expression validator used to validate the authority part
     * @param options Validation options. Set using the public constants of this class.
     * To set multiple options, simply add them together:
     *
{@code ALLOW_2_SLASHES + NO_FRAGMENTS}

     * enables both of those options.
     * @param domainValidator the DomainValidator to use; must agree with ALLOW_LOCAL_URLS setting
     * @since 1.7
     */
    public UrlValidator(String[] schemes, RegexValidator authorityValidator, long options, DomainValidator domainValidator) {
        this.options = options;
        if (domainValidator == null) {
            throw new IllegalArgumentException("DomainValidator must not be null");
        }
        if (domainValidator.isAllowLocal() != ((options & ALLOW_LOCAL_URLS) > 0)) {
            throw new IllegalArgumentException("DomainValidator disagrees with ALLOW_LOCAL_URLS setting");
        }
        this.domainValidator = domainValidator;

        if (isOn(ALLOW_ALL_SCHEMES)) {
            allowedSchemes = Collections.emptySet();
        } else {
            if (schemes == null) {
                schemes = DEFAULT_SCHEMES;
            }
            allowedSchemes = new HashSet<>(schemes.length);
            for (String scheme : schemes) {
                allowedSchemes.add(scheme.toLowerCase(Locale.ENGLISH));
            }
        }

        this.authorityValidator = authorityValidator;
    }

    /**
     *
Checks if a field has a valid url address.

     *
     * Note that the method calls #isValidAuthority()
     * which checks that the domain is valid.
     *
     * @param value The value validation is being performed on.  A {@code null}
     * value is considered invalid.
     * @return true if the url is valid.
     */
    public boolean isValid(String value) {
        if (value == null) {
            return false;
        }

        URI uri; // ensure value is a valid URI
        try {
            uri = new URI(value);
        } catch (URISyntaxException e) {
            return false;
        }
        // OK, perfom additional validation

        String scheme = uri.getScheme();
        if (!isValidScheme(scheme)) {
            return false;
        }

        String authority = uri.getRawAuthority();
        if ("file".equals(scheme) && (authority == null || "".equals(authority))) { // Special case - file: allows an empty authority
            return true; // this is a local file - nothing more to do here
        } else if ("file".equals(scheme) && authority != null && authority.contains(":")) {
            return false;
        } else {
            // Validate the authority
            if (!isValidAuthority(authority)) {
                return false;
            }
        }

        if (!isValidPath(uri.getRawPath())) {
            return false;
        }

        if (!isValidQuery(uri.getRawQuery())) {
            return false;
        }

        if (!isValidFragment(uri.getRawFragment())) {
            return false;
        }

        return true;
    }

    /**
     * Validate scheme. If schemes[] was initialized to a non null,
     * then only those schemes are allowed.
     * Otherwise the default schemes are "http", "https", "ftp".
     * Matching is case-blind.
     * @param scheme The scheme to validate.  A {@code null} value is considered
     * invalid.
     * @return true if valid.
     */
    protected boolean isValidScheme(String scheme) {
        if (scheme == null) {
            return false;
        }

        if (!SCHEME_PATTERN.matcher(scheme).matches()) {
            return false;
        }

        if (isOff(ALLOW_ALL_SCHEMES) && !allowedSchemes.contains(scheme.toLowerCase(Locale.ENGLISH))) {
            return false;
        }

        return true;
    }

    /**
     * Returns true if the authority is properly formatted.  An authority is the combination
     * of hostname and port.  A {@code null} authority value is considered invalid.
     * Note: this implementation validates the domain unless a RegexValidator was provided.
     * If a RegexValidator was supplied and it matches, then the authority is regarded
     * as valid with no further checks, otherwise the method checks against the
     * AUTHORITY_PATTERN and the DomainValidator (ALLOW_LOCAL_URLS)
     * @param authority Authority value to validate, allows IDN
     * @return true if authority (hostname and port) is valid.
     */
    protected boolean isValidAuthority(String authority) {
        if (authority == null) {
            return false;
        }

        // check manual authority validation if specified
        if (authorityValidator != null && authorityValidator.isValid(authority)) {
            return true;
        }
        // convert to ASCII if possible
        final String authorityASCII = DomainValidator.unicodeToASCII(authority);

        Matcher authorityMatcher = AUTHORITY_PATTERN.matcher(authorityASCII);
        if (!authorityMatcher.matches()) {
            return false;
        }

        // We have to process IPV6 separately because that is parsed in a different group
        String ipv6 = authorityMatcher.group(PARSE_AUTHORITY_IPV6);
        if (ipv6 != null) {
            InetAddressValidator inetAddressValidator = InetAddressValidator.getInstance();
            if (!inetAddressValidator.isValidInet6Address(ipv6)) {
                return false;
            }
        } else {
            String hostLocation = authorityMatcher.group(PARSE_AUTHORITY_HOST_IP);
            // check if authority is hostname or IP address:
            // try a hostname first since that's much more likely
            if (!this.domainValidator.isValid(hostLocation)) {
                // try an IPv4 address
                InetAddressValidator inetAddressValidator = InetAddressValidator.getInstance();
                if (!inetAddressValidator.isValidInet4Address(hostLocation)) {
                    // isn't IPv4, so the URL is invalid
                    return false;
                }
            }
            String port = authorityMatcher.group(PARSE_AUTHORITY_PORT);
            if (port != null && port.length() > 0) {
                try {
                    int iPort = Integer.parseInt(port);
                    if (iPort < 0 || iPort > MAX_UNSIGNED_16_BIT_INT) {
                        return false;
                    }
                } catch (NumberFormatException nfe) {
                    return false; // this can happen for big numbers
                }
            }
        }

        String extra = authorityMatcher.group(PARSE_AUTHORITY_EXTRA);
        if (extra != null && extra.trim().length() > 0) {
            return false;
        }

        return true;
    }

    /**
     * Returns true if the path is valid.  A {@code null} value is considered invalid.
     * @param path Path value to validate.
     * @return true if path is valid.
     */
    protected boolean isValidPath(String path) {
        if (path == null) {
            return false;
        }

        if (!PATH_PATTERN.matcher(path).matches()) {
            return false;
        }

        try {
            // Don't omit host otherwise leading path may be taken as host if it starts with //
            URI uri = new URI(null, "localhost", path, null);
            String norm = uri.normalize().getPath();
            if (norm.startsWith("/../") // Trying to go via the parent dir
                    || norm.equals("/..")) {   // Trying to go to the parent dir
                return false;
            }
        } catch (URISyntaxException e) {
            return false;
        }

        int slash2Count = countToken("//", path);
        if (isOff(ALLOW_2_SLASHES) && slash2Count > 0) {
            return false;
        }

        return true;
    }

    /**
     * Returns true if the query is null or it's a properly formatted query string.
     * @param query Query value to validate.
     * @return true if query is valid.
     */
    protected boolean isValidQuery(String query) {
        if (query == null) {
            return true;
        }

        return QUERY_PATTERN.matcher(query).matches();
    }

    /**
     * Returns true if the given fragment is null or fragments are allowed.
     * @param fragment Fragment value to validate.
     * @return true if fragment is valid.
     */
    protected boolean isValidFragment(String fragment) {
        if (fragment == null) {
            return true;
        }

        return isOff(NO_FRAGMENTS);
    }

    /**
     * Returns the number of times the token appears in the target.
     * @param token Token value to be counted.
     * @param target Target value to count tokens in.
     * @return the number of tokens.
     */
    protected int countToken(String token, String target) {
        int tokenIndex = 0;
        int count = 0;
        while (tokenIndex != -1) {
            tokenIndex = target.indexOf(token, tokenIndex);
            if (tokenIndex > -1) {
                tokenIndex++;
                count++;
            }
        }
        return count;
    }

    /**
     * Tests whether the given flag is on.  If the flag is not a power of 2
     * (ie. 3) this tests whether the combination of flags is on.
     *
     * @param flag Flag value to check.
     *
     * @return whether the specified flag value is on.
     */
    private boolean isOn(long flag) {
        return (options & flag) > 0;
    }

    /**
     * Tests whether the given flag is on.  If the flag is not a power of 2
     * (e.g. 3) this tests whether the combination of flags is on.
     *
     * @param flag Flag value to check.
     * @param options what to check
     *
     * @return whether the specified flag value is on.
     */
    private static boolean isOn(long flag, long options) {
        return (options & flag) > 0;
    }

    /**
     * Tests whether the given flag is off.  If the flag is not a power of 2
     * (ie. 3) this tests whether the combination of flags is off.
     *
     * @param flag Flag value to check.
     *
     * @return whether the specified flag value is off.
     */
    private boolean isOff(long flag) {
        return (options & flag) == 0;
    }
}


text:
package vegetaclihelper

import (
	"flag"
	"fmt"
	"log"
	"os"
	"runtime"
	"runtime/pprof"
	"strings"
)

var AppHost string

func VegetaCliExecute(vegetaArgs []string, host string) {
	commands := map[string]command{
		"attack": attackCmd(host),
		"report": reportCmd(),
		"dump":   dumpCmd(),
	}

	fs := flag.NewFlagSet("vegeta", flag.ExitOnError)
	cpus := fs.Int("cpus", runtime.NumCPU(), "Number of CPUs to use")
	profile := fs.String("profile", "", "Enable profiling of [cpu, heap]")
	version := fs.Bool("version", false, "Print version and exit")

	fs.Usage = func() {
		fmt.Println("Usage: vegeta [global flags] <command> [command flags]")
		fmt.Printf("\nglobal flags:\n")
		fs.PrintDefaults()
		for name, cmd := range commands {
			fmt.Printf("\n%s command:\n", name)
			cmd.fs.PrintDefaults()
		}
		fmt.Println(examples)
	}

	fs.Parse(vegetaArgs)

	if *version {
		fmt.Println(Version)
		return
	}

	runtime.GOMAXPROCS(*cpus)

	for _, prof := range strings.Split(*profile, ",") {
		if prof = strings.TrimSpace(prof); prof == "" {
			continue
		}

		f, err := os.Create(prof + ".pprof")
		if err != nil {
			log.Fatal(err)
		}
		defer f.Close()

		switch {
		case strings.HasPrefix(prof, "cpu"):
			pprof.StartCPUProfile(f)
			defer pprof.StopCPUProfile()
		case strings.HasPrefix(prof, "heap"):
			defer pprof.Lookup("heap").WriteTo(f, 0)
		}
	}

	args := fs.Args()
	if len(args) == 0 {
		fs.Usage()
		os.Exit(1)
	}

	if cmd, ok := commands[args[0]]; !ok {
		log.Fatalf("Unknown command: %s", args[0])
	} else if err := cmd.fn(args[1:]); err != nil {
		log.Fatal(err)
	}
}

// Version is set at compile time.
var Version = "???"

const examples = `
examples:
  echo "GET http://localhost/" | vegeta attack -duration=5s | tee results.bin | vegeta report
  vegeta attack -targets=targets.txt > results.bin
  vegeta report -inputs=results.bin -reporter=json > metrics.json
  cat results.bin | vegeta report -reporter=plot > plot.html
  cat results.bin | vegeta report -reporter="hist[0,100ms,200ms,300ms]"
`

type command struct {
	fs *flag.FlagSet
	fn func(args []string) error
}


text:
<mvc:View
		xmlns:mvc="sap.ui.core.mvc"
		xmlns="sap.m"
		xmlns:forms="sap.ui.layout.form"
		xmlns:core="sap.ui.core"
		controllerName="sap.uxap.testblocks.freeform.FreeFormBlockController">

	<forms:SimpleForm
			maxContainerCols="2"
			editable="false"
			layout="ResponsiveGridLayout">
		<core:Title text="Freeform block"/>
		<Button text="press me (Free form)" press="handlePress"/>
	</forms:SimpleForm>
</mvc:View>


text:
namespace crashpad {
namespace test {

TestMinidumpMemoryWriter::TestMinidumpMemoryWriter(uint64_t base_address,
                                                   size_t size,
                                                   uint8_t value)
    : SnapshotMinidumpMemoryWriter(&test_snapshot_) {
  test_snapshot_.SetAddress(base_address);
  test_snapshot_.SetSize(size);
  test_snapshot_.SetValue(value);
}

TestMinidumpMemoryWriter::~TestMinidumpMemoryWriter() {
}

void ExpectMinidumpMemoryDescriptor(
    const MINIDUMP_MEMORY_DESCRIPTOR* expected,
    const MINIDUMP_MEMORY_DESCRIPTOR* observed) {
  EXPECT_EQ(expected->StartOfMemoryRange, observed->StartOfMemoryRange);
  EXPECT_EQ(expected->Memory.DataSize, observed->Memory.DataSize);
  if (expected->Memory.Rva != 0) {
    const uint32_t kMemoryAlignment = 16;
    EXPECT_EQ(
        (expected->Memory.Rva + kMemoryAlignment - 1) & ~(kMemoryAlignment - 1),
        observed->Memory.Rva);
  }
}

void ExpectMinidumpMemoryDescriptorAndContents(
    const MINIDUMP_MEMORY_DESCRIPTOR* expected,
    const MINIDUMP_MEMORY_DESCRIPTOR* observed,
    const std::string& file_contents,
    uint8_t value,
    bool at_eof) {
  ExpectMinidumpMemoryDescriptor(expected, observed);

  if (at_eof) {
    EXPECT_EQ(file_contents.size(),
              observed->Memory.Rva + observed->Memory.DataSize);
  } else {
    EXPECT_GE(file_contents.size(),
              observed->Memory.Rva + observed->Memory.DataSize);
  }

  std::string expected_data(expected->Memory.DataSize, value);
  std::string observed_data(&file_contents[observed->Memory.Rva],
                            observed->Memory.DataSize);
  EXPECT_EQ(expected_data, observed_data);
}

}  // namespace test
}  // namespace crashpad


text:
package gov.hhs.onc.sdcct.ws.metadata.impl;

import com.github.sebhoss.warnings.CompilerWarnings;
import gov.hhs.onc.sdcct.api.SpecificationType;
import gov.hhs.onc.sdcct.ws.metadata.InteractionWsMetadata;
import gov.hhs.onc.sdcct.ws.metadata.ResourceWsMetadata;
import gov.hhs.onc.sdcct.ws.metadata.WsMetadata;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Stream;

public abstract class AbstractWsMetadata<T extends InteractionWsMetadata, U extends ResourceWsMetadata<?, ?, T>> extends AbstractWsMetadataComponent
    implements WsMetadata<T, U> {
    protected SpecificationType specType;
    protected Map<String, U> resourceMetadatas = new TreeMap<>();

    protected AbstractWsMetadata(SpecificationType specType, String id, String name) {
        super(id, name);

        this.specType = specType;
    }

    @Override
    public Map<String, U> getResourceMetadatas() {
        return this.resourceMetadatas;
    }

    @Override
    @SuppressWarnings({ CompilerWarnings.UNCHECKED })
    public void setResourceMetadatas(U ... resourceMetadatas) {
        this.resourceMetadatas.clear();

        Stream.of(resourceMetadatas)
            .forEach(resourceMetadata -> this.resourceMetadatas.put(resourceMetadata.getResourceMetadata().getPath(), resourceMetadata));
    }

    @Override
    public SpecificationType getSpecificationType() {
        return this.specType;
    }
}


text:
<?php
return array (
  'Edit user' => 'Bearbeite Benutzer',
);


text:
{% extends "base.html" %}

{% block content %}

This is a {{ project.title }}.

    / {{ chapter.title }}

    {{ chapter.content_html }}
{% endblock %}


text:
require_relative "../../cli/parser"

describe Homebrew::CLI::Parser do
  describe "test switch options" do
    subject(:parser) {
      described_class.new do
        switch "--more-verbose", description: "Flag for higher verbosity"
        switch "--pry", env: :pry
      end
    }

    before do
      allow(Homebrew::EnvConfig).to receive(:pry?).and_return(true)
    end

    context "when using binary options" do
      subject(:parser) {
        described_class.new do
          switch "--[no-]positive"
        end
      }

      it "does not create no_positive?" do
        args = parser.parse(["--no-positive"])
        expect { args.no_positive? }.to raise_error(NoMethodError)
      end

      it "sets the positive name to false if the negative flag is passed" do
        args = parser.parse(["--no-positive"])
        expect(args).not_to be_positive
      end

      it "sets the positive name to true if the positive flag is passed" do
        args = parser.parse(["--positive"])
        expect(args).to be_positive
      end

      it "does not set the positive name if the positive flag is not passed" do
        args = parser.parse([])
        expect(args.positive?).to be nil
      end
    end

    context "when using negative options" do
      subject(:parser) {
        described_class.new do
          switch "--no-positive"
        end
      }

      it "does not set the positive name" do
        args = parser.parse(["--no-positive"])
        expect { args.positive? }.to raise_error(NoMethodError)
      end

      it "fails when using the positive name" do
        expect {
          parser.parse(["--positive"])
        }.to raise_error(/invalid option/)
      end

      it "sets the negative name to true if the negative flag is passed" do
        args = parser.parse(["--no-positive"])
        expect(args.no_positive?).to be true
      end
    end

    context "when `ignore_invalid_options` is true" do
      it "passes through invalid options" do
        args = parser.parse(["-v", "named-arg", "--not-a-valid-option"], ignore_invalid_options: true)
        expect(args.remaining).to eq ["named-arg", "--not-a-valid-option"]
        expect(args.named).to be_empty
      end
    end

    it "parses short option" do
      args = parser.parse(["-v"])
      expect(args).to be_verbose
    end

    it "parses a single valid option" do
      args = parser.parse(["--verbose"])
      expect(args).to be_verbose
    end

    it "parses a valid option along with few unnamed args" do
      args = parser.parse(%w[--verbose unnamed args])
      expect(args).to be_verbose
      expect(args.named).to eq %w[unnamed args]
    end

    it "parses a single option and checks other options to be false" do
      args = parser.parse(["--verbose"])
      expect(args).to be_verbose
      expect(args.more_verbose?).to be false
    end

    it "raises an exception and outputs help text when an invalid option is passed" do
      expect { parser.parse(["--random"]) }.to raise_error(OptionParser::InvalidOption, /--random/)
                                           .and output(/Usage: brew/).to_stderr
    end

    it "maps environment var to an option" do
      args = parser.parse([])
      expect(args.pry?).to be true
    end
  end

  describe "test long flag options" do
    subject(:parser) {
      described_class.new do
        flag        "--filename=", description: "Name of the file"
        comma_array "--files",     description: "Comma separated filenames"
      end
    }

    it "parses a long flag option with its argument" do
      args = parser.parse(["--filename=random.txt"])
      expect(args.filename).to eq "random.txt"
    end

    it "raises an exception when a flag's required value is not passed" do
      expect { parser.parse(["--filename"]) }.to raise_error(OptionParser::MissingArgument, /--filename/)
    end

    it "parses a comma array flag option" do
      args = parser.parse(["--files=random1.txt,random2.txt"])
      expect(args.files).to eq %w[random1.txt random2.txt]
    end
  end

  describe "test short flag options" do
    subject(:parser) {
      described_class.new do
        flag "-f", "--filename=", description: "Name of the file"
      end
    }

    it "parses a short flag option with its argument" do
      args = parser.parse(["--filename=random.txt"])
      expect(args.filename).to eq "random.txt"
      expect(args.f).to eq "random.txt"
    end
  end

  describe "test constraints for flag options" do
    subject(:parser) {
      described_class.new do
        flag      "--flag1="
        flag      "--flag3="
        flag      "--flag2=", required_for: "--flag1="
        flag      "--flag4=", depends_on: "--flag3="

        conflicts "--flag1=", "--flag3="
      end
    }

    it "raises exception on required_for constraint violation" do
      expect { parser.parse(["--flag1=flag1"]) }.to raise_error(Homebrew::CLI::OptionConstraintError)
    end

    it "raises exception on depends_on constraint violation" do
      expect { parser.parse(["--flag2=flag2"]) }.to raise_error(Homebrew::CLI::OptionConstraintError)
      expect { parser.parse(["--flag4=flag4"]) }.to raise_error(Homebrew::CLI::OptionConstraintError)
    end

    it "raises exception for conflict violation" do
      expect { parser.parse(["--flag1=flag1", "--flag3=flag3"]) }.to raise_error(Homebrew::CLI::OptionConflictError)
    end

    it "raises no exception" do
      args = parser.parse(["--flag1=flag1", "--flag2=flag2"])
      expect(args.flag1).to eq "flag1"
      expect(args.flag2).to eq "flag2"
    end

    it "raises no exception for optional dependency" do
      args = parser.parse(["--flag3=flag3"])
      expect(args.flag3).to eq "flag3"
    end
  end

  describe "test invalid constraints" do
    subject(:parser) {
      described_class.new do
        flag      "--flag1="
        flag      "--flag2=", depends_on: "--flag1="
        conflicts "--flag1=", "--flag2="
      end
    }

    it "raises exception due to invalid constraints" do
      expect { parser.parse([]) }.to raise_error(Homebrew::CLI::InvalidConstraintError)
    end
  end

  describe "test constraints for switch options" do
    subject(:parser) {
      described_class.new do
        switch      "-a", "--switch-a", env: "switch_a"
        switch      "-b", "--switch-b", env: "switch_b"
        switch      "--switch-c", required_for: "--switch-a"
        switch      "--switch-d", depends_on: "--switch-b"

        conflicts "--switch-a", "--switch-b"
      end
    }

    it "raises exception on required_for constraint violation" do
      expect { parser.parse(["--switch-a"]) }.to raise_error(Homebrew::CLI::OptionConstraintError)
    end

    it "raises exception on depends_on constraint violation" do
      expect { parser.parse(["--switch-c"]) }.to raise_error(Homebrew::CLI::OptionConstraintError)
      expect { parser.parse(["--switch-d"]) }.to raise_error(Homebrew::CLI::OptionConstraintError)
    end

    it "raises exception for conflict violation" do
      expect { parser.parse(["-ab"]) }.to raise_error(Homebrew::CLI::OptionConflictError)
    end

    it "raises no exception" do
      args = parser.parse(["--switch-a", "--switch-c"])
      expect(args.switch_a?).to be true
      expect(args.switch_c?).to be true
    end

    it "raises no exception for optional dependency" do
      args = parser.parse(["--switch-b"])
      expect(args.switch_b?).to be true
    end

    it "prioritizes cli arguments over env vars when they conflict" do
      allow(Homebrew::EnvConfig).to receive(:switch_a?).and_return(true)
      allow(Homebrew::EnvConfig).to receive(:switch_b?).and_return(false)
      args = parser.parse(["--switch-b"])
      expect(args.switch_a?).to be false
      expect(args).to be_switch_b
    end

    it "raises an exception on constraint violation when both are env vars" do
      allow(Homebrew::EnvConfig).to receive(:switch_a?).and_return(true)
      allow(Homebrew::EnvConfig).to receive(:switch_b?).and_return(true)
      expect { parser.parse([]) }.to raise_error(Homebrew::CLI::OptionConflictError)
    end
  end

  describe "test immutability of args" do
    subject(:parser) {
      described_class.new do
        switch "-a", "--switch-a"
        switch "-b", "--switch-b"
      end
    }

    it "raises exception when arguments were already parsed" do
      parser.parse(["--switch-a"])
      expect { parser.parse(["--switch-b"]) }.to raise_error(RuntimeError, /Arguments were already parsed!/)
    end
  end

  describe "test inferrability of args" do
    subject(:parser) {
      described_class.new do
        switch "--switch-a"
        switch "--switch-b"
        switch "--foo-switch"
        flag "--flag-foo="
        comma_array "--comma-array-foo"
      end
    }

    it "parses a valid switch that uses `_` instead of `-`" do
      args = parser.parse(["--switch_a"])
      expect(args).to be_switch_a
    end

    it "parses a valid flag that uses `_` instead of `-`" do
      args = parser.parse(["--flag_foo=foo.txt"])
      expect(args.flag_foo).to eq "foo.txt"
    end

    it "parses a valid comma_array that uses `_` instead of `-`" do
      args = parser.parse(["--comma_array_foo=foo.txt,bar.txt"])
      expect(args.comma_array_foo).to eq %w[foo.txt bar.txt]
    end

    it "raises an error when option is ambiguous" do
      expect { parser.parse(["--switch"]) }.to raise_error(RuntimeError, /ambiguous option: --switch/)
    end

    it "inferrs the option from an abbreviated name" do
      args = parser.parse(["--foo"])
      expect(args).to be_foo_switch
    end
  end

  describe "test argv extensions" do
    subject(:parser) {
      described_class.new do
        switch "--foo"
        flag   "--bar"
        switch "-s"
      end
    }

    it "#options_only" do
      args = parser.parse(["--foo", "--bar=value", "-v", "-s", "a", "b", "cdefg"])
      expect(args.options_only).to eq %w[--verbose --foo --bar=value -s]
    end

    it "#flags_only" do
      args = parser.parse(["--foo", "--bar=value", "-v", "-s", "a", "b", "cdefg"])
      expect(args.flags_only).to eq %w[--verbose --foo --bar=value]
    end

    it "#named returns an array of non-option arguments" do
      args = parser.parse(["foo", "-v", "-s"])
      expect(args.named).to eq ["foo"]
    end

    it "#named returns an empty array when there are no named arguments" do
      args = parser.parse([])
      expect(args.named).to be_empty
    end
  end

  describe "usage banner generation" do
    it "includes `[options]` if more than two non-global options are available" do
      parser = described_class.new do
        switch "--foo"
        switch "--baz"
        switch "--bar"
      end
      expect(parser.generate_help_text).to match(/\[options\]/)
    end

    it "includes individual options if less than two non-global options are available" do
      parser = described_class.new do
        switch "--foo"
        switch "--bar"
      end
      expect(parser.generate_help_text).to match(/\[--foo\] \[--bar\]/)
    end

    it "formats flags correctly when less than two non-global options are available" do
      parser = described_class.new do
        flag "--foo"
        flag "--bar="
      end
      expect(parser.generate_help_text).to match(/\[--foo\] \[--bar=\]/)
    end

    it "formats comma arrays correctly when less than two non-global options are available" do
      parser = described_class.new do
        comma_array "--foo"
      end
      expect(parser.generate_help_text).to match(/\[--foo=\]/)
    end

    it "doesn't include `[options]` if non non-global options are available" do
      parser = described_class.new
      expect(parser.generate_help_text).not_to match(/\[options\]/)
    end

    it "includes a description" do
      parser = described_class.new do
        description <<~EOS
          This command does something
        EOS
      end
      expect(parser.generate_help_text).to match(/This command does something/)
    end

    it "allows the usage banner to be overriden" do
      parser = described_class.new do
        usage_banner "`test` [foo] <bar>"
      end
      expect(parser.generate_help_text).to match(/test \[foo\] bar/)
    end

    it "allows a usage banner and a description to be overriden" do
      parser = described_class.new do
        usage_banner "`test` [foo] <bar>"
        description <<~EOS
          This command does something
        EOS
      end
      expect(parser.generate_help_text).to match(/test \[foo\] bar/)
      expect(parser.generate_help_text).to match(/This command does something/)
    end

    it "shows the correct usage for no named argument" do
      parser = described_class.new do
        named_args :none
      end
      expect(parser.generate_help_text).to match(/^Usage: [^\[]+$/s)
    end

    it "shows the correct usage for a single typed argument" do
      parser = described_class.new do
        named_args :formula, number: 1
      end
      expect(parser.generate_help_text).to match(/^Usage: .* formula$/s)
    end

    it "shows the correct usage for a subcommand argument with a maximum" do
      parser = described_class.new do
        named_args %w[off on], max: 1
      end
      expect(parser.generate_help_text).to match(/^Usage: .* \[subcommand\]$/s)
    end

    it "shows the correct usage for multiple typed argument with no maximum or minimum" do
      parser = described_class.new do
        named_args [:tap, :command]
      end
      expect(parser.generate_help_text).to match(/^Usage: .* \[tap|command ...\]$/s)
    end

    it "shows the correct usage for a subcommand argument with a minimum of 1" do
      parser = described_class.new do
        named_args :installed_formula, min: 1
      end
      expect(parser.generate_help_text).to match(/^Usage: .* installed_formula \[...\]$/s)
    end

    it "shows the correct usage for a subcommand argument with a minimum greater than 1" do
      parser = described_class.new do
        named_args :installed_formula, min: 2
      end
      expect(parser.generate_help_text).to match(/^Usage: .* installed_formula ...$/s)
    end
  end

  describe "named_args" do
    let(:parser_none) {
      described_class.new do
        named_args :none
      end
    }
    let(:parser_number) {
      described_class.new do
        named_args number: 1
      end
    }

    it "doesn't allow :none passed with a number" do
      expect do
        described_class.new do
          named_args :none, number: 1
        end
      end.to raise_error(ArgumentError, /Do not specify both `number`, `min` or `max` with `named_args :none`/)
    end

    it "doesn't allow number and min" do
      expect do
        described_class.new do
          named_args number: 1, min: 1
        end
      end.to raise_error(ArgumentError, /Do not specify both `number` and `min` or `max`/)
    end

    it "doesn't accept fewer than the passed number of arguments" do
      expect { parser_number.parse([]) }.to raise_error(Homebrew::CLI::NumberOfNamedArgumentsError)
    end

    it "doesn't accept more than the passed number of arguments" do
      expect { parser_number.parse(["foo", "bar"]) }.to raise_error(Homebrew::CLI::NumberOfNamedArgumentsError)
    end

    it "accepts the passed number of arguments" do
      expect { parser_number.parse(["foo"]) }.not_to raise_error
    end

    it "doesn't accept any arguments with :none" do
      expect { parser_none.parse(["foo"]) }
        .to raise_error(Homebrew::CLI::MaxNamedArgumentsError, /This command does not take named arguments/)
    end

    it "accepts no arguments with :none" do
      expect { parser_none.parse([]) }.not_to raise_error
    end

    it "displays the correct error message with no arg types and min" do
      parser = described_class.new do
        named_args min: 2
      end
      expect { parser.parse([]) }.to raise_error(
        Homebrew::CLI::MinNamedArgumentsError, /This command requires at least 2 named arguments/
      )
    end

    it "displays the correct error message with no arg types and number" do
      parser = described_class.new do
        named_args number: 2
      end
      expect { parser.parse([]) }.to raise_error(
        Homebrew::CLI::NumberOfNamedArgumentsError, /This command requires exactly 2 named arguments/
      )
    end

    it "displays the correct error message with no arg types and max" do
      parser = described_class.new do
        named_args max: 1
      end
      expect { parser.parse(%w[foo bar]) }.to raise_error(
        Homebrew::CLI::MaxNamedArgumentsError, /This command does not take more than 1 named argument/
      )
    end

    it "displays the correct error message with an array of strings" do
      parser = described_class.new do
        named_args %w[on off], number: 1
      end
      expect { parser.parse([]) }.to raise_error(
        Homebrew::CLI::NumberOfNamedArgumentsError, /This command requires exactly 1 subcommand/
      )
    end

    it "displays the correct error message with an array of symbols" do
      parser = described_class.new do
        named_args [:formula, :cask], min: 1
      end
      expect { parser.parse([]) }.to raise_error(
        Homebrew::CLI::MinNamedArgumentsError, /This command requires at least 1 formula or cask argument/
      )
    end

    it "displays the correct error message with an array of symbols and max" do
      parser = described_class.new do
        named_args [:formula, :cask], max: 1
      end
      expect { parser.parse(%w[foo bar]) }.to raise_error(
        Homebrew::CLI::MaxNamedArgumentsError, /This command does not take more than 1 formula or cask argument/
      )
    end
  end
end


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Revis. gen. pl. (Leipzig) 3: 468 (1898)

#### Original name
Puccinia fergussonii Berk. & Broome, 1875

### Remarks
null


text:
namespace pythonic
{

  namespace numpy
  {

    namespace wrapper
    {
      template <class I>
      typename std::enable_if<types::is_complex<I>::value, bool>::type
      iscomplex(I const &a);

      template <class I>
      constexpr
          typename std::enable_if<not types::is_complex<I>::value, bool>::type
          iscomplex(I const &a);
    }

#define NUMPY_NARY_FUNC_NAME iscomplex
#define NUMPY_NARY_FUNC_SYM wrapper::iscomplex
#include "pythonic/include/types/numpy_nary_expr.hpp"
  }
}

#endif


text:
#ifndef QTARG__CMDLINEIFACE_HPP__INCLUDED
#define QTARG__CMDLINEIFACE_HPP__INCLUDED

// Qt include.
#include <QChar>
#include <QList>
#include <QFlags>

// QtArg include.
#include "parseable.hpp"

class QtArgIface;

//
// QtArgCmdLineIface
//

/*!
	\class QtArgCmdLineIface
	\brief Command line arguments parser interface.

	This is an interface for command line parser. In usual cases
	you don't nedd to implement this interface, because there are
	always ready implementation of this interface that handles
	various situations.

	\sa QtArgCmdLine
*/
class QtArgCmdLineIface {
public:
	//! Type of the list of the arguments in the command line.
	typedef QList< QtArgParseableIface* > QtParseableList;

	QtArgCmdLineIface()
	{}

	virtual ~QtArgCmdLineIface()
	{}

	//! Parse option.
	enum ParseOption {
		//! Parse after ignore rest.
		ParseAfterIgnoreRest = 1,
		//! Command is required.
		CommandIsRequired = 2
	}; // enum ParseOption

	Q_DECLARE_FLAGS( ParseOptions, ParseOption )

	/*!
		\return List of arguments.

		\sa QtArgCmdLine::arguments()
	*/
	virtual const QtParseableList & parseable() const = 0;

	/*!
		Add new parseable for handling.

		\sa QtArgCmdLine::addParseable()
	*/
	virtual void addParseable( QtArgParseableIface & arg ) = 0;

	/*!
		Add new parseable for handling.

		\sa QtArgCmdLine::addParseable()
	*/
	virtual void addParseable( QtArgParseableIface * arg ) = 0;

	/*!
		\return Delimiter char.

		By default used '-' as delimiter.

		\sa QtArgCmdLine::delimiter()
	*/
	virtual const QChar & delimiter() const = 0;

	/*!
		Set delimiter char.

		\sa QtArgCmdLine::setDelimiter()
	*/
	virtual void setDelimiter( const QChar & delim ) = 0;

	/*!
		Parse arguments.

		Usually this is very difficult process.

		\sa QtArgCmdLine::parse()
	*/
	virtual void parse() = 0;

	/*!
		\return Is str an flag or string of the flags.
		\retval true if str is an flag or string of the flags.
		\retval false if str is not a flag or string of the flags.
	*/
	virtual bool isFlag( const QString & str ) const = 0;

	/*!
		\return Is str an argument.
		\retval true if str is an argument.
		\retval false if str is not an argument.
	*/
	virtual bool isArgument( const QString & str ) const = 0;

	//! Removes all delimiters from the beginning of the given string.
	virtual QString removeDelimiters( const QString & str ) const = 0;

	//! Find parseable by his name.
	virtual QtArgParseableIface * findParseable( const QString & name,
		bool throwExceptions = true,
		QtArgParseableIface * command = 0 ) const = 0;

private:
	Q_DISABLE_COPY( QtArgCmdLineIface )
}; // class QtArgCmdLineIface

Q_DECLARE_OPERATORS_FOR_FLAGS( QtArgCmdLineIface::ParseOptions )

#endif // QTARG__CMDLINEIFACE_HPP__INCLUDED


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BongApiV1.WebServiceImplementation
{
    public class ListBroadcastsResponse
    {
        public List<DataBroadcast> Broadcasts { get; set; }
    }
}


text:
import React from 'react';

class Info extends React.Component {

    render(){
        return(

                 ✕

                     {this.props.description}
                     Plays: {this.props.plays}
                     Favorites: {this.props.favorites}
                     Comments: {this.props.comments}
                     {this.props.url}

        )
    }
}

export default Info


text:
__author__ = 'nuok'
from city import City
from dungeon import Dungeon

class Map:
    def __init__(self, config_data):
        locations = {}

        # init city
        for city in config_data['cities']:
            locations[city['name']] = City(city)

        # init dungeon
        for dungeon in config_data['dungeons']:
            locations[dungeon['name']] = Dungeon(dungeon)

        self.locations = locations
        self.current_location = self.locations['main_city']

    def get_current_location_name(self):
        return self.current_location.get_name()

    def get_neighbor(self):
        return self.current_location.get_movable_location()

    def move(self, location_name, player):
        for neighbor in self.get_neighbor():
            if location_name in neighbor:
                self.current_location = self.locations[location_name]
                return True
        return False

    def make_move_action(self, location_name):
        return lambda player: self.move(location_name, player)

    def get_current_action(self):
        action_dic = self.current_location.get_action()
        for location in self.get_neighbor():
            action_dic['move_' + location] = self.make_move_action(location)
        return action_dic