<commit_before>
'use strict';

var expect  = require('chai').expect,
    _       = require('underscore'),
    MockExpressReq          = require('../../lib/mock_express_request'),
    leave_request_validator = require('../../../lib/route/validator/leave_request');

describe('Check validation for leave request', function(){

    it('No parameters provided', function(){
        var req = new MockExpressReq({});

        expect(function(){
            leave_request_validator({req : req})
        }).to.throw('Got validation errors');

        expect( req.session.flash.errors.length ).to.be.equal( 5 );
    });

});
<commit_msg>More tests for leave_request validation function<commit_after>
'use strict';

var expect  = require('chai').expect,
    _       = require('underscore'),
    MockExpressReq          = require('../../lib/mock_express_request'),
    leave_request_validator = require('../../../lib/route/validator/leave_request');

describe('Check validation for leave request', function(){

    it('No parameters provided', function(){
        var req = new MockExpressReq({});

        expect(function(){
            leave_request_validator({req : req})
        }).to.throw('Got validation errors');

        expect( req.session.flash.errors.length ).to.be.equal( 5 );
    });

    it('User index is invalid', function(){
        var req = new MockExpressReq({params : {user : 'foo'}});

        expect(function(){
            leave_request_validator({req : req})
        }).to.throw('Got validation errors');

        expect(
            _.findIndex(
                req.session.flash.errors, function(msg){
                    return msg === 'Incorrect employee';
                })
        ).to.be.greaterThan( -1 );

        expect( req.session.flash.errors.length ).to.be.equal( 6 );
    });

    var valid_params = {
        user           : '1',
        leave_type     : '1',
        from_date      : '2015-05-10',
        from_date_part : '1',
        to_date        : '2015-05-12',
        to_date_part   : '2',
        reason         : 'some reason',
    };

    it('Successfull scenario', function(){

        var req = new MockExpressReq({params : valid_params});

        expect(
            leave_request_validator({req : req})
        ).to.be.eql(valid_params);

        expect( req.session ).not.to.have.property( 'flash' );
    });

    it('from_date_part has invalid value', function(){
        var params = _.clone(valid_params);
        params.from_date_part = "11";
        var req = new MockExpressReq({params : params});
        expect(function(){
            leave_request_validator({req : req})
        }).to.throw('Got validation errors');

        expect(
            _.findIndex(
                req.session.flash.errors, function(msg){
                    return msg === 'Incorrect day part';
                })
        ).to.be.greaterThan( -1 );

        expect( req.session.flash.errors.length ).to.be.equal( 1 );
    });

    it('from_date has invalid value', function(){
        var params = _.clone(valid_params);
        params.from_date = "some horrible date";
        var req = new MockExpressReq({params : params});
        expect(function(){
            leave_request_validator({req : req})
        }).to.throw('Got validation errors');

        expect(
            _.findIndex(
                req.session.flash.errors, function(msg){
                    return msg === 'From date should be a date';
                })
        ).to.be.greaterThan( -1 );

        expect( req.session.flash.errors.length ).to.be.equal( 1 );
    });

    it('start dates is greater than end one', function(){
        var params = _.clone(valid_params);
        params.from_date = '2015-04-12';
        params.to_date   = '2015-04-02';
        var req = new MockExpressReq({params : params});
        expect(function(){
            leave_request_validator({req : req})
        }).to.throw('From date should be before To date');

        expect( req.session ).not.to.have.property( 'flash' );
    });
});
<|endoftext|>


<commit_before>import React, {PropTypes} from 'react';
import classNames from 'classnames';
import { DOMMouseMoveTracker } from 'dom-lib';
import ClassNameMixin from './mixins/ClassNameMixin';
import ReactComponentWithPureRenderMixin from './mixins/ReactComponentWithPureRenderMixin';

function clamp(value, min, max) {
    if (value < min) {
        return min;
    }
    if (value > max) {
        return max;
    }
    return value;
}

const ColumnResizeHandle = React.createClass({
    mixins: [
        ClassNameMixin,
        ReactComponentWithPureRenderMixin
    ],
    propTypes: {
        columnWidth: PropTypes.number,
        columnLeft: PropTypes.number,
        columnFixed: PropTypes.bool,
        onColumnResize: PropTypes.func,
        onColumnResizeEnd: PropTypes.func,
        onColumnResizeMove: PropTypes.func,
    },
    getInitialState() {
        return {
            columnWidth: this.props.columnWidth,
            cursorDelta: 0,
            visible: false
        };
    },
    _onMove(deltaX, deltaY) {

        if (!this.isKeyDown) {
            return;
        }

        var newWidth = this.state.cursorDelta + deltaX;
        var newColumnWidth = clamp(this.props.columnWidth + newWidth, 20);

        this.setState({
            columnWidth: newColumnWidth,
            cursorDelta: newWidth
        });

        this.props.onColumnResizeMove(newColumnWidth, this.props.columnLeft, this.props.columnFixed);
    },

    _onColumnResizeEnd() {

        this.isKeyDown = false;

        this.props.onColumnResizeEnd(
            this.state.columnWidth,
            this.state.cursorDelta
        );

        if (this._mouseMoveTracker) {
            this._mouseMoveTracker.releaseMouseMoves();
            this._mouseMoveTracker = null;
        }

        this.setState({
            visible: false
        });
    },
    _getMouseMoveTracker() {
        return this._mouseMoveTracker || new DOMMouseMoveTracker(
            this._onMove,
            this._onColumnResizeEnd,
            document.body
        );
    },
    _onColumnResizeMouseDown(event) {

        this._mouseMoveTracker = this._getMouseMoveTracker();
        this.isKeyDown = true;
        this.setState({
            visible: true,
            cursorDelta: 0
        });

        this.props.onColumnResize(
            this.props.columnWidth,
            this.props.columnLeft, {
                clientX: event.clientX,
                clientY: event.clientY,
                preventDefault: function () { }
            }
        );

    },
    componentWillReceiveProps(newProps) {
        if (this.isKeyDown && newProps.initialEvent && !this._mouseMoveTracker.isDragging()) {
            this._mouseMoveTracker.captureMouseMoves(newProps.initialEvent);
        }
    },
    componentWillUnmount() {
        this._mouseMoveTracker.releaseMouseMoves();
        this._mouseMoveTracker = null;
    },
    render() {

        let {columnLeft} = this.props;
        let {columnWidth, visible} = this.state;

        let styles = {
            width: 6,
            left: columnWidth + columnLeft - 2
        };

        let classes = classNames({ visible }, this.prefix('column-resize-spanner'));

        return (
            <div
                className={classes}
                style={styles}
                onMouseDown={this._onColumnResizeMouseDown}
                ref="spanner"
                >
            </div>
        );
    }
});

export default ColumnResizeHandle;
<commit_msg>bugfix<commit_after>import React, {PropTypes} from 'react';
import classNames from 'classnames';
import { DOMMouseMoveTracker } from 'dom-lib';
import ClassNameMixin from './mixins/ClassNameMixin';
import ReactComponentWithPureRenderMixin from './mixins/ReactComponentWithPureRenderMixin';

function clamp(value, min, max) {
    if (value < min) {
        return min;
    }
    if (value > max) {
        return max;
    }
    return value;
}

const ColumnResizeHandle = React.createClass({
    mixins: [
        ClassNameMixin,
        ReactComponentWithPureRenderMixin
    ],
    propTypes: {
        columnWidth: PropTypes.number,
        columnLeft: PropTypes.number,
        columnFixed: PropTypes.bool,
        onColumnResize: PropTypes.func,
        onColumnResizeEnd: PropTypes.func,
        onColumnResizeMove: PropTypes.func,
    },
    getInitialState() {
        return {
            columnWidth: this.props.columnWidth,
            cursorDelta: 0,
            visible: false
        };
    },
    _onMove(deltaX, deltaY) {

        if (!this.isKeyDown) {
            return;
        }

        var newWidth = this.state.cursorDelta + deltaX;
        var newColumnWidth = clamp(this.props.columnWidth + newWidth, 20);

        this.setState({
            columnWidth: newColumnWidth,
            cursorDelta: newWidth
        });

        this.props.onColumnResizeMove(newColumnWidth, this.props.columnLeft, this.props.columnFixed);
    },

    _onColumnResizeEnd() {

        this.isKeyDown = false;

        this.props.onColumnResizeEnd(
            this.state.columnWidth,
            this.state.cursorDelta
        );

        if (this._mouseMoveTracker) {
            this._mouseMoveTracker.releaseMouseMoves();
            this._mouseMoveTracker = null;
        }

        this.setState({
            visible: false
        });
    },
    _getMouseMoveTracker() {
        return this._mouseMoveTracker || new DOMMouseMoveTracker(
            this._onMove,
            this._onColumnResizeEnd,
            document.body
        );
    },
    _onColumnResizeMouseDown(event) {

        this._mouseMoveTracker = this._getMouseMoveTracker();
        this.isKeyDown = true;
        this.setState({
            visible: true,
            cursorDelta: 0
        });

        this.props.onColumnResize(
            this.props.columnWidth,
            this.props.columnLeft, {
                clientX: event.clientX,
                clientY: event.clientY,
                preventDefault: function () { }
            }
        );

    },
    componentWillReceiveProps(newProps) {
        if (this.isKeyDown && newProps.initialEvent && !this._mouseMoveTracker.isDragging()) {
            this._mouseMoveTracker.captureMouseMoves(newProps.initialEvent);
        }
    },
    componentWillUnmount() {
        if (this._mouseMoveTracker) {
            this._mouseMoveTracker.releaseMouseMoves();
            this._mouseMoveTracker = null;
        }
    },
    render() {

        let {columnLeft} = this.props;
        let {columnWidth, visible} = this.state;

        let styles = {
            width: 6,
            left: columnWidth + columnLeft - 2
        };

        let classes = classNames({ visible }, this.prefix('column-resize-spanner'));

        return (
            <div
                className={classes}
                style={styles}
                onMouseDown={this._onColumnResizeMouseDown}
                ref="spanner"
                >
            </div>
        );
    }
});

export default ColumnResizeHandle;
<|endoftext|>


<commit_before>/*global $, jQuery, alert, console, i, j, ii*/

var GF = function (CHROMO_STRUCTURE, options) {

    "use strict";

    // Check for invalid parameter CHROMO_STRUCTURE
    if ((typeof CHROMO_STRUCTURE === "undefined")) {
        // console.error("Invalid parameter passed to GF. You need to pass a chromosome structure.");
        return null;
    }

    ///////////////////////////////////////////////////////////
    //      START OF PRIVATE CLASS METHODS/PROPERTIES
    ///////////////////////////////////////////////////////////

    /** Object that represents all of the class private methods and properties. */
    var gfprivate = {};

    // Chromosome structure
    gfprivate.CHROMO_STRUCTURE = CHROMO_STRUCTURE;

    // Default options
    gfprivate.DEFAULT_OPTIONS = {
        MAX_POPULATION_SIZE: 45,
        MAX_GENERATIONS: 100,
        MUTATION_PROB: 0.05,
        NUM_TO_SELECT: 10
    };

    // Setting default options
    $.extend(gfprivate, gfprivate.DEFAULT_OPTIONS);

    // Maximum population size
    gfprivate.MAX_POPULATION_SIZE = 45; // default to 45

    // Maximum number of generations
    gfprivate.MAX_GENERATIONS = 100; // default to 100

    // Mutation probability
    gfprivate.MUTATION_PROB = 0.05; // default to 5%

    // Selection number
    gfprivate.NUM_TO_SELECT = 10; // default to 10 tributes (they volunteer)

    // Chromosome atrributes
    gfprivate.chromosome = {
        genes: {},
        score: 0
    };

    // Generation Population Array
    gfprivate.population = [];

    // Sort (descending) chromosomes based on score
    gfprivate.sortPopulation = function () {
        gfprivate.population.sort(function (a,b) {
            return b.score - a.score; // descending score order
        });
    };

    // Crossover Xgene and Ygene and return crossover
    gfprivate.crossover = function (Xchromo, Ychromo) {
        var crossedChromo = $.extend({},gfprivate.chromosome),
            property;
        for (property in Xchromo.genes) {
            if (Xchromo.genes.hasOwnProperty(property)) {
                // 50/50 chance of picking a gene from either
                crossedChromo.genes[property] = ((Math.random() > 0.5) ? Xchromo.genes[property] : Ychromo.genes[property]);
            }
        }
        return $.extend({},crossedChromo);
    };

    // Mutate individual chromosomes
    gfprivate.getMutated = function (chromo) {
        var mutatedChromo = $.extend({},gfprivate.chromosome),
            property;
        for (property in chromo.genes) {
            if (chromo.genes.hasOwnProperty(property)) {
                mutatedChromo.genes[property] = ((Math.random() < gfprivate.MUTATION_PROB) ? Math.random() : chromo.genes[property]);
            }
        }
        return mutatedChromo;
    };

    // Generates a new random chromosome using the structure provided
    gfprivate.generateChromosome = function () {
        var newChromosome = gfprivate.CHROMO_STRUCTURE,
            property;
        for (property in newChromosome.genes) {
            if (newChromosome.genes.hasOwnProperty(property)) {
                newChromosome.genes[property] = Math.random();
            }
        }
        return newChromosome;
    };

    // Default fitness function (should be replaced with custom function by framework user)
    gfprivate.fitnessFunction = function (genes) {
        var property;
        for (property in genes) {
            if (genes.hasOwnProperty(property)) {
                return genes[property];
            }
        }
    };

    // Evaluate scores of all chromosomes and sets their score property
    gfprivate.evaluate = function () {
        for (var i = 0; i < gfprivate.population.length; i+=1) {
            var score = { score: gfprivate.fitnessFunction(gfprivate.population[i].genes)};
            $.extend(gfprivate.population[i],score);
        }
    }

    // Selects the most fit in the population
    gfprivate.selectFittest = function () {
        gfprivate.sortPopulation();
        gfprivate.population.splice(gfprivate.NUM_TO_SELECT);
    }

    // Selects random chromosomes in a population
    gfprivate.selectRandom = function (selectionPop) {
        gfprivate.population = [];
        for (var i = 0; i < gfprivate.MAX_POPULATION_SIZE; i += 1) {
            var selector = Math.floor(Math.random()*selectionPop.length); // Random number from 0 to selectionPop.length
            gfprivate.population.push($.extend({},selectionPop[selector])); // add the selected value to the population
        }
    }

    /** Crossover the entire population in gfprivate.population
     * This method has the efficiency class of O(n^2) but is usually run on the fittest
     * chromosomes selected (which are only 10 by default). Keep this in mind when changing the
     * default ```NUM_SELECTED``` option.
     */
    gfprivate.crossPopulation = function () {
        var crossoverPopulation = [];
        // Crosses all n chromosomes with all other n-1 chromosomes
        for (var i = 0; i < gfprivate.population.length; i += 1) {
            for (var ii = 1; ii < gfprivate.population.length - i; ii += 1) {
                // 50/50 chance for selecting genes
                var crossoverChromosome = $.extend({},gfprivate.crossover(gfprivate.population[i], gfprivate.population[ii]));
                crossoverPopulation.push(JSON.parse(JSON.stringify(crossoverChromosome))); // HACK SOLUTION FOR REFERENCE PROBLEM, TODO REPLACE THIS
            }
        }
        gfprivate.selectRandom(crossoverPopulation);
    }

    // Mutate population
    gfprivate.mutate = function () {
        for (var i = 0; i < gfprivate.population.length; i += 1) {
            gfprivate.population[i] = JSON.parse(JSON.stringify(gfprivate.getMutated(gfprivate.population[i]))); // HACK, TODO FIX
        }
    }

    ///////////////////////////////////////////////////////////
    //             START OF PUBLIC METHODS/API
    ///////////////////////////////////////////////////////////

    // Class public methods/properties
    var gfpublic = {};

    gfpublic.initPopulation = function (chromosomeStruct) {
        /* CREATE RANDOM POPULATION */
        for (var i = 0; i < gfprivate.MAX_POPULATION_SIZE; i += 1) {
            // Create new random chromosome
            var newChromosome = $.extend(true, {}, gfprivate.generateChromosome());
            // Add it to the population
            gfprivate.population.push(newChromosome);
        }
    };

    gfpublic.evolve = function (evolveOptions, fitfunc) {
        // Update options again.
        $.extend(gfprivate, evolveOptions);

        // The generation counter
        var generationCount = gfprivate.MAX_GENERATIONS;

        // Set the fitness function if it was passed in
        if (typeof fitfunc === "function") {
            gfprivate.fitnessFunction = fitfunc;
        }

        // Abort
        // If the population is not initialized
        if (!gfprivate.population.length) {
            // console.error("No population initialized. Hint: Use .initPopulation before .evolve");
            return;
        }

        // Loops for each generation
        while (generationCount--) {
            /* START EVOLUTION */

            /* EVALUATION PHASE */

            gfprivate.evaluate(); // Test all chromosomes and score them

            /* SELECTION PHASE */

            gfprivate.selectFittest(); // Select most fit chromosomes in terms of score attribute

            /* CROSSOVER & MUTATION PHASE */

            gfprivate.crossPopulation();
            gfprivate.mutate();

            /* REPEAT UNTIL LAST GENERATION */
        }

        /* END EVOLUTION */
        gfprivate.evaluate();
        gfprivate.selectFittest();
    };

    // Resets all options to the defaults
    gfpublic.resetOptions = function () {
        $.extend(gfprivate, gfprivate.DEFAULT_OPTIONS);
    };

    // Pretty straightforward
    gfpublic.getPopulation = function () {
        return gfprivate.population;
    }

    // Options merging (requires Jquery)
    $.extend(gfprivate, options);

    // Return class public methods (a.k.a. make them available for use)
    return gfpublic;
};<commit_msg>Remove browser globals Add CHROMO_STRUCTURE validation<commit_after>/*global $, jQuery, i, j, ii*/

var GF = function (CHROMO_STRUCTURE, options) {

    "use strict";

    // Check for invalid parameter CHROMO_STRUCTURE
    if ((typeof CHROMO_STRUCTURE === "undefined") || (typeof CHROMO_STRUCTURE !== "object")) {
        // console.error("Invalid parameter passed to GF. You need to pass a chromosome structure.");
        return null;
    }

    ///////////////////////////////////////////////////////////
    //      START OF PRIVATE CLASS METHODS/PROPERTIES
    ///////////////////////////////////////////////////////////

    /** Object that represents all of the class private methods and properties. */
    var gfprivate = {};

    // Chromosome structure
    gfprivate.CHROMO_STRUCTURE = CHROMO_STRUCTURE;

    // Default options
    gfprivate.DEFAULT_OPTIONS = {
        MAX_POPULATION_SIZE: 45,
        MAX_GENERATIONS: 100,
        MUTATION_PROB: 0.05,
        NUM_TO_SELECT: 10
    };

    // Setting default options
    $.extend(gfprivate, gfprivate.DEFAULT_OPTIONS);

    // Maximum population size
    gfprivate.MAX_POPULATION_SIZE = 45; // default to 45

    // Maximum number of generations
    gfprivate.MAX_GENERATIONS = 100; // default to 100

    // Mutation probability
    gfprivate.MUTATION_PROB = 0.05; // default to 5%

    // Selection number
    gfprivate.NUM_TO_SELECT = 10; // default to 10 tributes (they volunteer)

    // Chromosome atrributes
    gfprivate.chromosome = {
        genes: {},
        score: 0
    };

    // Generation Population Array
    gfprivate.population = [];

    // Sort (descending) chromosomes based on score
    gfprivate.sortPopulation = function () {
        gfprivate.population.sort(function (a,b) {
            return b.score - a.score; // descending score order
        });
    };

    // Crossover Xgene and Ygene and return crossover
    gfprivate.crossover = function (Xchromo, Ychromo) {
        var crossedChromo = $.extend({},gfprivate.chromosome),
            property;
        for (property in Xchromo.genes) {
            if (Xchromo.genes.hasOwnProperty(property)) {
                // 50/50 chance of picking a gene from either
                crossedChromo.genes[property] = ((Math.random() > 0.5) ? Xchromo.genes[property] : Ychromo.genes[property]);
            }
        }
        return $.extend({},crossedChromo);
    };

    // Mutate individual chromosomes
    gfprivate.getMutated = function (chromo) {
        var mutatedChromo = $.extend({},gfprivate.chromosome),
            property;
        for (property in chromo.genes) {
            if (chromo.genes.hasOwnProperty(property)) {
                mutatedChromo.genes[property] = ((Math.random() < gfprivate.MUTATION_PROB) ? Math.random() : chromo.genes[property]);
            }
        }
        return mutatedChromo;
    };

    // Generates a new random chromosome using the structure provided
    gfprivate.generateChromosome = function () {
        var newChromosome = gfprivate.CHROMO_STRUCTURE,
            property;
        for (property in newChromosome.genes) {
            if (newChromosome.genes.hasOwnProperty(property)) {
                newChromosome.genes[property] = Math.random();
            }
        }
        return newChromosome;
    };

    // Default fitness function (should be replaced with custom function by framework user)
    gfprivate.fitnessFunction = function (genes) {
        var property;
        for (property in genes) {
            if (genes.hasOwnProperty(property)) {
                return genes[property];
            }
        }
    };

    // Evaluate scores of all chromosomes and sets their score property
    gfprivate.evaluate = function () {
        for (var i = 0; i < gfprivate.population.length; i+=1) {
            var score = { score: gfprivate.fitnessFunction(gfprivate.population[i].genes)};
            $.extend(gfprivate.population[i],score);
        }
    }

    // Selects the most fit in the population
    gfprivate.selectFittest = function () {
        gfprivate.sortPopulation();
        gfprivate.population.splice(gfprivate.NUM_TO_SELECT);
    }

    // Selects random chromosomes in a population
    gfprivate.selectRandom = function (selectionPop) {
        gfprivate.population = [];
        for (var i = 0; i < gfprivate.MAX_POPULATION_SIZE; i += 1) {
            var selector = Math.floor(Math.random()*selectionPop.length); // Random number from 0 to selectionPop.length
            gfprivate.population.push($.extend({},selectionPop[selector])); // add the selected value to the population
        }
    }

    /** Crossover the entire population in gfprivate.population
     * This method has the efficiency class of O(n^2) but is usually run on the fittest
     * chromosomes selected (which are only 10 by default). Keep this in mind when changing the
     * default ```NUM_SELECTED``` option.
     */
    gfprivate.crossPopulation = function () {
        var crossoverPopulation = [];
        // Crosses all n chromosomes with all other n-1 chromosomes
        for (var i = 0; i < gfprivate.population.length; i += 1) {
            for (var ii = 1; ii < gfprivate.population.length - i; ii += 1) {
                // 50/50 chance for selecting genes
                var crossoverChromosome = $.extend({},gfprivate.crossover(gfprivate.population[i], gfprivate.population[ii]));
                crossoverPopulation.push(JSON.parse(JSON.stringify(crossoverChromosome))); // HACK SOLUTION FOR REFERENCE PROBLEM, TODO REPLACE THIS
            }
        }
        gfprivate.selectRandom(crossoverPopulation);
    }

    // Mutate population
    gfprivate.mutate = function () {
        for (var i = 0; i < gfprivate.population.length; i += 1) {
            gfprivate.population[i] = JSON.parse(JSON.stringify(gfprivate.getMutated(gfprivate.population[i]))); // HACK, TODO FIX
        }
    }

    ///////////////////////////////////////////////////////////
    //             START OF PUBLIC METHODS/API
    ///////////////////////////////////////////////////////////

    // Class public methods/properties
    var gfpublic = {};

    gfpublic.initPopulation = function (chromosomeStruct) {
        /* CREATE RANDOM POPULATION */
        for (var i = 0; i < gfprivate.MAX_POPULATION_SIZE; i += 1) {
            // Create new random chromosome
            var newChromosome = $.extend(true, {}, gfprivate.generateChromosome());
            // Add it to the population
            gfprivate.population.push(newChromosome);
        }
    };

    gfpublic.evolve = function (evolveOptions, fitfunc) {
        // Update options again.
        $.extend(gfprivate, evolveOptions);

        // The generation counter
        var generationCount = gfprivate.MAX_GENERATIONS;

        // Set the fitness function if it was passed in
        if (typeof fitfunc === "function") {
            gfprivate.fitnessFunction = fitfunc;
        }

        // Abort
        // If the population is not initialized
        if (!gfprivate.population.length) {
            // console.error("No population initialized. Hint: Use .initPopulation before .evolve");
            return;
        }

        // Loops for each generation
        while (generationCount--) {
            /* START EVOLUTION */

            /* EVALUATION PHASE */

            gfprivate.evaluate(); // Test all chromosomes and score them

            /* SELECTION PHASE */

            gfprivate.selectFittest(); // Select most fit chromosomes in terms of score attribute

            /* CROSSOVER & MUTATION PHASE */

            gfprivate.crossPopulation();
            gfprivate.mutate();

            /* REPEAT UNTIL LAST GENERATION */
        }

        /* END EVOLUTION */
        gfprivate.evaluate();
        gfprivate.selectFittest();
    };

    // Resets all options to the defaults
    gfpublic.resetOptions = function () {
        $.extend(gfprivate, gfprivate.DEFAULT_OPTIONS);
    };

    // Pretty straightforward
    gfpublic.getPopulation = function () {
        return gfprivate.population;
    }

    // Options merging
    $.extend(gfprivate, options);

    // Return class public methods (a.k.a. make them available for use)
    return gfpublic;
};<|endoftext|>


<commit_before>import React, {PropTypes as T} from 'react'

function styles(invalid) {
  return {
    display: 'block',
    width: '100%',
    maxWidth: '100%',
    boxSizing: 'border-box',
    borderColor: '#cccccc',
    backgroundColor: invalid ? 'pink' : 'white',
    fontFamily: 'Menlo, Monaco, Consolas, "Lucida Console", monospace',
  }
}

function stringifyFromUntrustedProp(obj) {
  try {
    return JSON.stringify(obj, null, 2)
  } catch (e) {
    return JSON.stringify({
      message: e.message,
    }, null, 2)
  }
}

export default React.createClass({

  displayName: 'Demo.Controls.InputJson',

  propTypes: {
    value: T.any.isRequired,
    onChange: T.func.isRequired,
  },

  getInitialState() {
    return {
      strValue: stringifyFromUntrustedProp(this.props.value),
      invalid: false,
    }
  },

  componentWillReceiveProps(nextProps) {
    if (nextProps.value !== this.props.value) {
      this.setState({
        strValue: stringifyFromUntrustedProp(nextProps.value),
        invalid: false,
      })
    }
  },

  handleChange(event) {
    const nextStrValue = event.target.value
    try {
      this.props.onChange(JSON.parse(nextStrValue))
    } catch (e) {
      this.setState({strValue: nextStrValue, invalid: true})
    }
  },

  render() {
    const {strValue, invalid} = this.state
    return <textarea
      rows={4}
      style={styles(invalid)}
      value={strValue}
      onChange={this.handleChange}
    />
  },

})
<commit_msg>fix a bug in json control<commit_after>import React, {PropTypes as T} from 'react'

function styles(invalid) {
  return {
    display: 'block',
    width: '100%',
    maxWidth: '100%',
    boxSizing: 'border-box',
    borderColor: '#cccccc',
    backgroundColor: invalid ? 'pink' : 'white',
    fontFamily: 'Menlo, Monaco, Consolas, "Lucida Console", monospace',
  }
}

function stringifyFromUntrustedProp(obj) {
  try {
    return JSON.stringify(obj, null, 2)
  } catch (e) {
    return JSON.stringify({
      message: e.message,
    }, null, 2)
  }
}

export default React.createClass({

  displayName: 'Demo.Controls.InputJson',

  propTypes: {
    value: T.any.isRequired,
    onChange: T.func.isRequired,
  },

  getInitialState() {
    return {
      strValue: stringifyFromUntrustedProp(this.props.value),
      invalid: false,
    }
  },

  componentWillReceiveProps(nextProps) {
    if (nextProps.value !== this.props.value) {
      this.setState({
        strValue: stringifyFromUntrustedProp(nextProps.value),
        invalid: false,
      })
    }
  },

  handleChange(event) {
    const strValue = event.target.value
    let invalid = true
    let value
    try {
      value = JSON.parse(strValue)
      invalid = false
    } catch (e) {} // eslint-disable-line no-empty
    this.setState({strValue, invalid})
    if (!invalid) {
      this.props.onChange(value)
    }
  },

  render() {
    const {strValue, invalid} = this.state
    return <textarea
      rows={4}
      style={styles(invalid)}
      value={strValue}
      onChange={this.handleChange}
    />
  },

})
<|endoftext|>


<commit_before>document.observe('dom:loaded', function() {
    // hpo: namespace:medical_genetics
    // go : namespace:
    var highlightChecked = function(element) {
      var subsection = element.up('.subsection');
      if (subsection) {
	var subsectionTitle = subsection.previous('label.section');
      }
      if (element.checked) {
        element.up('label').addClassName('selected');
	if (subsectionTitle) {
	  subsectionTitle.addClassName('selected');
	}
      } else {
        element.up('label').removeClassName('selected');
	if (subsectionTitle) {
	  subsectionTitle.removeClassName('selected');
	}
      }
    };
    var enableHighlightChecked = function(element) {
      highlightChecked(element);
      ['change', 'suggest:change'].each(function(eventName) {
        element.observe(eventName, highlightChecked.bind(element,element));
      });
    };
    $$('label input[type=checkbox]').each(enableHighlightChecked);
    var suggestionsMapping = {
        "hpo" : {
            script: "/solr/select?start=0&rows=15&debugQuery=on&",
            queryProcessor: typeof(MS.widgets.SolrQueryProcessor) == "undefined" ? null : new MS.widgets.SolrQueryProcessor({
                           'name' : { 'stub': true, 'boost': 50 },
                           'synonym' : { 'stub': true, 'boost': 50 },
                           'text' : { 'stub': true, 'default': true },
                           'phonetic' : {'boost': 0.1 },
                           'id' : {'activationRegex' : 'HP:[0-9]+', 'stub': true, 'boost' : 50}
                         }),
            varname: "q",
            noresults: "No matching terms",
            json: false,
            resultsParameter : "doc",
            resultId : "str[name=id]",
            resultValue : "str[name=name]",
            resultInfo : {
                           "Definition"    : {"selector"  : "str[name=def]"},
                           "Synonyms"      : {"selector"  : "arr[name=synonym] str"},
                           "Is a"          : {"selector"  : "arr[name=is_a] str",
                                              "processor" : function (text){
                                                            return text.replace(/(HP:[0-9]+)\s*!\s*(.*)/, "[$1] $2");
                                                          },
                                              "collapsed" : true
                                             },
                           "Subcategories" : {"selector"  : "str[name=id]",
                                              "dynamic"   : true,
                                              "queryProcessor" : typeof(MS.widgets.SolrQueryProcessor) == "undefined" ? null : new MS.widgets.SolrQueryProcessor({
                                                                 'is_a' : { 'stub': false, 'activationRegex' : 'HP:[0-9]+' }
                                               }),
                                              "processor" : function (response) {
                                                              var suggestions = this.getSuggestionList(response);
                                                              for (var i = 0; i < suggestions.length; ++i) {
                                                                suggestions[i].info = "";
                                                                /*var info = suggestions[i].info;
                                                                Element.select(info, 'dt').each(function (elt){
                                                                  if (!elt.hasClassName('subcategories')) {
                                                                    elt.next('dd').remove();
                                                                    elt.remove();
                                                                  }
                                                                });*/
                                                              }
                                                              return this.createListElement(suggestions, this);
                                                            }
                                             }
                         },
            enableHierarchy: true,
            resultParent : "arr[name=is_a] str",
            fadeOnClear : false
        }
    };
    var pickerSpecialClassOptions = {
      'defaultPicker' : {},
      'generateCheckboxes' : {
                  'showKey' : false,
                  'showTooltip' : false,
                  'showDeleteTool' : true,
                  'enableSort' : false,
                  'showClearTool' : false,
                  'inputType': 'checkbox',
                  'listInsertionElt' : '.label-other-phenotype',
                  'listInsertionPosition' : 'before',
                  'onItemAdded' : enableHighlightChecked
                },
      'quickSearch' : {
                  'showKey' : false,
                  'showTooltip' : false,
                  'showDeleteTool' : true,
                  'enableSort' : false,
                  'showClearTool' : false,
                  'inputType': 'checkbox',
                  'listInsertionElt' : document.documentElement.down('.clinical-info .phenotype-group:last-child'),
                  'listInsertionPosition' : 'bottom',
                  'onItemAdded' : enableHighlightChecked
                }
    }
    if (typeof(MS.widgets.Suggest) != "undefined") {
      var keys = Object.keys(suggestionsMapping);
      var specialClasses = Object.keys(pickerSpecialClassOptions);
      for (var i = 0; i < keys.length; i++) {
        var selector = 'input.suggest-' + keys[i];
        $$(selector).each(function(item) {
          if (!item.hasClassName('initialized')) {
            var options = {
              timeout : 30000,
              parentContainer : null
            };
            Object.extend(options, suggestionsMapping[keys[i]]);
            // Create the Suggest.
            var suggest = new MS.widgets.Suggest(item, options);
            if (item.hasClassName('multi') && typeof(MS.widgets.SuggestPicker) != "undefined") {
              var multiSuggestOptions = {};
              for (var j = 0; j < specialClasses.length; j++) {
                if (item.hasClassName(specialClasses[j])) {
                  multiSuggestOptions = pickerSpecialClassOptions[specialClasses[j]];
                  break;
                }
              }
              var suggestPicker = new MS.widgets.SuggestPicker(item, suggest, multiSuggestOptions);
            }
            item.addClassName('initialized');
          }
        });
      }
    }

    var qsBox = $('quick-search-box');
    if (qsBox) {
      var content = qsBox.next('div');
      var qsInput = qsBox.down('input[type=text]');
      Event.observe(window, 'scroll', function(){
	var boxHeight = qsBox.getHeight();
	var boxWidth = qsBox.getWidth();
	var boxMinTop = content.cumulativeOffset().top ;
	var boxMaxTop = content.cumulativeOffset().top + content.getHeight() - boxHeight;
	var boxLeft = qsBox.cumulativeOffset().left;
	var qsSuggest = null;
	if (qsInput && qsInput._suggestWidget && typeof(qsInput._suggestWidget.suggest) != "undefined") {
	  qsSuggest = qsInput._suggestWidget.suggest;
	  qsSuggest.style.left = qsInput.cumulativeOffset().left;
	  qsSuggest.style.width = qsInput.getWidth();
	}
	if (document.viewport.getScrollOffsets().top >= boxMinTop && document.viewport.getScrollOffsets().top < boxMaxTop) {
	  qsBox.style.position = 'fixed';
	  qsBox.style.left = boxLeft + 'px';
	  qsBox.style.width = boxWidth + 'px';
	  qsBox.style.top = 0;
	  if (qsSuggest) {
	    qsSuggest.style.position = 'fixed';
	    qsSuggest.style.top = qsInput.viewportOffset().top + qsInput.getHeight();
	  }
	} else if (document.viewport.getScrollOffsets().top >= boxMaxTop) {
	  qsBox.style.position = 'absolute';
	  qsBox.style.top = boxMaxTop;
	  qsBox.style.left = '';//boxLeft + 'px';
	  qsBox.style.right = 0;
	  if (qsSuggest) {
	    qsSuggest.style.position = 'absolute';
	    qsSuggest.style.top = qsInput.cumulativeOffset().top + qsInput.getHeight();
	  }
	} else {
	  qsBox.style.position = '';
	  qsBox.style.top = '';
	  qsBox.style.left = '';
	  qsBox.style.width = '';
	  if (qsSuggest) {
	    qsSuggest.style.position = 'absolute';
	    qsSuggest.style.top = qsInput.cumulativeOffset().top + qsInput.getHeight();
	  }
	}
      });
    }
    $$('fieldset.phenotype-group legend').invoke('observe', 'click', function(event) {
      event.element().up('fieldset.phenotype-group').toggleClassName('collapsed');
    });
});
<commit_msg>[bug][ui] fixed the positioning of the quickSearch suggest<commit_after>document.observe('dom:loaded', function() {

    // ------------------------------------------------------------------------
    // Selected term highlighting

    var highlightChecked = function(element) {
      var subsection = element.up('.subsection');
      if (subsection) {
	var subsectionTitle = subsection.previous('label.section');
      }
      if (element.checked) {
        element.up('label').addClassName('selected');
	if (subsectionTitle) {
	  subsectionTitle.addClassName('selected');
	}
      } else {
        element.up('label').removeClassName('selected');
	if (subsectionTitle) {
	  subsectionTitle.removeClassName('selected');
	}
      }
    };
    var enableHighlightChecked = function(element) {
      highlightChecked(element);
      ['change', 'suggest:change'].each(function(eventName) {
        element.observe(eventName, highlightChecked.bind(element,element));
      });
    };
    $$('label input[type=checkbox]').each(enableHighlightChecked);

    // ------------------------------------------------------------------------
    // Creation of suggest widgets

    // hpo: namespace:medical_genetics
    // go : namespace:
    var suggestionsMapping = {
        "hpo" : {
            script: "/solr/select?start=0&rows=15&debugQuery=on&",
            queryProcessor: typeof(MS.widgets.SolrQueryProcessor) == "undefined" ? null : new MS.widgets.SolrQueryProcessor({
                           'name' : { 'stub': true, 'boost': 50 },
                           'synonym' : { 'stub': true, 'boost': 50 },
                           'text' : { 'stub': true, 'default': true },
                           'phonetic' : {'boost': 0.1 },
                           'id' : {'activationRegex' : 'HP:[0-9]+', 'stub': true, 'boost' : 50}
                         }),
            varname: "q",
            noresults: "No matching terms",
            json: false,
            resultsParameter : "doc",
            resultId : "str[name=id]",
            resultValue : "str[name=name]",
            resultInfo : {
                           "Definition"    : {"selector"  : "str[name=def]"},
                           "Synonyms"      : {"selector"  : "arr[name=synonym] str"},
                           "Is a"          : {"selector"  : "arr[name=is_a] str",
                                              "processor" : function (text){
                                                            return text.replace(/(HP:[0-9]+)\s*!\s*(.*)/, "[$1] $2");
                                                          },
                                              "collapsed" : true
                                             },
                           "Subcategories" : {"selector"  : "str[name=id]",
                                              "dynamic"   : true,
                                              "queryProcessor" : typeof(MS.widgets.SolrQueryProcessor) == "undefined" ? null : new MS.widgets.SolrQueryProcessor({
                                                                 'is_a' : { 'stub': false, 'activationRegex' : 'HP:[0-9]+' }
                                               }),
                                              "processor" : function (response) {
                                                              var suggestions = this.getSuggestionList(response);
                                                              for (var i = 0; i < suggestions.length; ++i) {
                                                                suggestions[i].info = "";
                                                                /*var info = suggestions[i].info;
                                                                Element.select(info, 'dt').each(function (elt){
                                                                  if (!elt.hasClassName('subcategories')) {
                                                                    elt.next('dd').remove();
                                                                    elt.remove();
                                                                  }
                                                                });*/
                                                              }
                                                              return this.createListElement(suggestions, this);
                                                            }
                                             }
                         },
            enableHierarchy: true,
            resultParent : "arr[name=is_a] str",
            fadeOnClear : false
        }
    };
    var pickerSpecialClassOptions = {
      'defaultPicker' : {},
      'generateCheckboxes' : {
                  'showKey' : false,
                  'showTooltip' : false,
                  'showDeleteTool' : true,
                  'enableSort' : false,
                  'showClearTool' : false,
                  'inputType': 'checkbox',
                  'listInsertionElt' : '.label-other-phenotype',
                  'listInsertionPosition' : 'before',
                  'onItemAdded' : enableHighlightChecked
                },
      'quickSearch' : {
                  'showKey' : false,
                  'showTooltip' : false,
                  'showDeleteTool' : true,
                  'enableSort' : false,
                  'showClearTool' : false,
                  'inputType': 'checkbox',
                  'listInsertionElt' : document.documentElement.down('.clinical-info .phenotype-group:last-child'),
                  'listInsertionPosition' : 'bottom',
                  'onItemAdded' : enableHighlightChecked
                }
    }
    if (typeof(MS.widgets.Suggest) != "undefined") {
      var keys = Object.keys(suggestionsMapping);
      var specialClasses = Object.keys(pickerSpecialClassOptions);
      for (var i = 0; i < keys.length; i++) {
        var selector = 'input.suggest-' + keys[i];
        $$(selector).each(function(item) {
          if (!item.hasClassName('initialized')) {
            var options = {
              timeout : 30000,
              parentContainer : null
            };
            Object.extend(options, suggestionsMapping[keys[i]]);
            // Create the Suggest.
            var suggest = new MS.widgets.Suggest(item, options);
            if (item.hasClassName('multi') && typeof(MS.widgets.SuggestPicker) != "undefined") {
              var multiSuggestOptions = {};
              for (var j = 0; j < specialClasses.length; j++) {
                if (item.hasClassName(specialClasses[j])) {
                  multiSuggestOptions = pickerSpecialClassOptions[specialClasses[j]];
                  break;
                }
              }
              var suggestPicker = new MS.widgets.SuggestPicker(item, suggest, multiSuggestOptions);
            }
            item.addClassName('initialized');
          }
        });
      }
    }

    // ------------------------------------------------------------------------
    // Behavior of the quick search box

    var qsBox = $('quick-search-box');
    if (qsBox) {
      var content = qsBox.next('div');
      var qsInput = qsBox.down('input[type=text]');
      var qsResetPosition = function() {
	if (qsInput._activeSuggest) {
	  return;
	}
	var boxHeight = qsBox.getHeight();
	var boxWidth = qsBox.getWidth();
	var boxMinTop = content.cumulativeOffset().top ;
	var boxMaxTop = content.cumulativeOffset().top + content.getHeight() - boxHeight;
	var boxLeft = qsBox.cumulativeOffset().left;
	if (document.viewport.getScrollOffsets().top >= boxMinTop && document.viewport.getScrollOffsets().top < boxMaxTop) {
	  qsBox.style.position = 'fixed';
	  qsBox.style.left = boxLeft + 'px';
	  qsBox.style.width = boxWidth + 'px';
	  qsBox.style.top = 0;
	} else if (document.viewport.getScrollOffsets().top >= boxMaxTop) {
	  qsBox.style.position = 'absolute';
	  qsBox.style.top = boxMaxTop + 'px';
	  qsBox.style.left = '';
	  qsBox.style.right = 0;
	} else {
	  qsBox.style.position = '';
	  qsBox.style.top = '';
	  qsBox.style.left = '';
	  qsBox.style.width = '';
	}
      }
      Event.observe(document, 'ms:suggest:containerCreated', function(event) {
	if (event.memo.suggest.fld == qsInput) {
	  qsInput._activeSuggest = true;
	  if (qsBox.style.position == 'fixed') {
	    qsBox.style.position = 'absolute';
	    qsBox.style.top = ((document.viewport.getScrollOffsets().top - content.cumulativeOffset().top) + 14) + 'px';
	    qsBox.style.left = '';
	    qsBox.style.right = 0;
	  }
	  var qsSuggest = event.memo.container;
	  qsSuggest.style.top = (qsInput.cumulativeOffset().top + qsInput.getHeight()) + 'px';
	  qsSuggest.style.marginTop = '1.6em';
	}
      });
      Event.observe(document, 'ms:suggest:clearSuggestions', function(event) {
	if (event.memo.suggest.fld == qsInput) {
	  qsInput._activeSuggest = false;
	  qsResetPosition();
	}
      });
      Event.observe(window, 'scroll', qsResetPosition);
    }

    // ------------------------------------------------------------------------
    // Expand/collapse phenotype groups

    $$('fieldset.phenotype-group legend').invoke('observe', 'click', function(event) {
      event.element().up('fieldset.phenotype-group').toggleClassName('collapsed');
    });
});
<|endoftext|>


<commit_before>'use strict';
import React, {Component} from "react";
import {AppRegistry, StyleSheet, Text, Image, View, TouchableOpacity, ListView, BackAndroid} from "react-native";
import NavigationBar from "./navigation/Navigation";
import Item3 from "./Item3";

export default class Item2 extends Component {

    constructor(props) {
        super(props);
        this.state = {
            dataSource: new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2,}),
            title: "Item1",
            loaded: false
        };
    }

    _onRowPress(rowData, rowID) {
        this.setState({title: rowData.title});
    }

    _renderRow(rowData, sectionID, rowID) {
        return (
            <TouchableOpacity onPress={() => this._onRowPress(rowData, rowID)}>
                <View style={styles.row}>
                    <Image
                        style={styles.icon}
                        source={{uri: rowData.images.large}}/>
                    <View style={{flexDirection: 'column', marginLeft: 10}}>
                        <Text style={styles.text}>{rowData.title}</Text>
                        <Text style={styles.text}>{rowData.year}</Text>
                        <Text style={styles.text}>{rowData.rating.average}</Text>
                    </View>
                </View>
            </TouchableOpacity>
        );
    }

    componentDidMount() {
        this._fetchData();
    }

    _fetchData() {
        let url = "https://api.douban.com/v2/movie/coming_soon?count=84";
        fetch(url, {
            method: 'GET',
            headers: {},
        }).then((response) => {
            if (response.ok) {
                return response.json();
            }
        }).then((json) => {
            if (json.subjects) {
                console.log(json.subjects[0].title);
                this.setState({
                    dataSource: this.state.dataSource.cloneWithRows(json.subjects),
                    title: json.title,
                    loaded: true
                });
            }
        }).catch((error) => {
            console.error(error);
        }).done();
    }

    _leftItemAction() {
        this.props.navigator.push({
            component: Item3,
            params: {
                text: '呵呵呵呵呵'
            }
        });
    }

    _rightItemAction() {
        alert('右侧按钮点击了');
    }

    _renderLoadingView() {
        return (<View style={styles.container}>
                <Text>Loading movies......</Text>
            </View>
        );
    }

    _renderView() {
        return (
            <View style={{flex: 1}}>
                <NavigationBar
                    title={this.state.title}
                    titleTextColor="red"
                    leftItemTitle="打开Item3"
                    leftTextColor="#123456"
                    rightItemTitle='forward'
                    rightTextColor='#3393F2'
                    leftItemFunc={() => this._leftItemAction()}
                    rightItemFunc={this._rightItemAction.bind(this)}/>
                <TouchableOpacity onPress={() => this.props.onPress(Item3)}>
                    <Text style={styles.instructions}>
                        点我到Item3
                    </Text>
                </TouchableOpacity>
                <ListView
                    dataSource={this.state.dataSource}
                    renderRow={this._renderRow.bind(this)}/>
            </View>
        );
    }

    render() {
        if (!this.state.loaded) {
            return this._renderLoadingView();
        } else {
            return this._renderView();
        }
    }
}

const styles = StyleSheet.create({
    container: {
        alignItems: 'center',
        justifyContent: 'center',
        flex: 1
    },
    instructions: {
        textAlign: 'center',
        color: 'red',
        marginBottom: 5
    },
    icon: {
        width: 100,
        height: 100,
    },
    row: {
        flexDirection: 'row',
        justifyContent: 'flex-start',
        padding: 10,
        backgroundColor: '#F6F6F6',
    },
    thumb: {
        width: 64,
        height: 64,
    },
    text: {
        flex: 1,
    },
});<commit_msg>update<commit_after>'use strict';
import React, {Component} from "react";
import {AppRegistry, StyleSheet, Text, Image, View, TouchableOpacity, ListView, BackAndroid} from "react-native";
import NavigationBar from "./navigation/Navigation";
import Item3 from "./Item3";

export default class Item2 extends Component {

    constructor(props) {
        super(props);
        this.state = {
            dataSource: new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2,}),
            title: "Item1",
            loaded: false
        };
    }

    _onRowPress(rowData, rowID) {
        this.setState({title: rowData.title});
    }

    _renderRow(rowData, sectionID, rowID) {
        return (
            <TouchableOpacity onPress={() => this._onRowPress(rowData, rowID)}>
                <View style={styles.row}>
                    <Image
                        style={styles.icon}
                        source={{uri: rowData.images.large}}/>
                    <View style={{flexDirection: 'column', marginLeft: 10}}>
                        <Text style={styles.text}>{rowData.title}</Text>
                        <Text style={styles.text}>{rowData.year}</Text>
                        <Text style={styles.text}>{rowData.rating.average}</Text>
                    </View>
                </View>
            </TouchableOpacity>
        );
    }

    componentDidMount() {
        this._fetchData();
    }

    _fetchData() {
        let url = "https://api.douban.com/v2/movie/coming_soon?count=84";
        fetch(url, {
            method: 'GET',
            headers: {},
        }).then((response) => {
            if (response.ok) {
                return response.json();
            }
        }).then((json) => {
            if (json.subjects) {
                console.log(json.subjects[0].title);
                this.setState({
                    dataSource: this.state.dataSource.cloneWithRows(json.subjects),
                    title: json.title,
                    loaded: true
                });
            }
        }).catch((error) => {
            console.error(error);
        }).done();
    }

    _leftItemAction() {
        this.props.navigator.push({
            component: Item3,
            params: {
                text: '呵呵呵呵呵'
            }
        });
    }

    _rightItemAction() {
        alert('右侧按钮点击了');
    }

    _renderLoadingView() {
        return (<View style={styles.container}>
                <Text>Loading movies......</Text>
            </View>
        );
    }

    _renderView() {
        return (
            <View style={{flex: 1}}>
                <NavigationBar
                    title={this.state.title}
                    titleTextColor="red"
                    leftItemTitle="打开Item3"
                    leftTextColor="#123456"
                    rightItemTitle='forward'
                    rightTextColor='#3393F2'
                    leftItemFunc={() => this._leftItemAction()}
                    rightItemFunc={this._rightItemAction.bind(this)}/>
                <TouchableOpacity onPress={() => this._leftItemAction()}>
                    <Text style={styles.instructions}>
                        点我到Item3
                    </Text>
                </TouchableOpacity>
                <ListView
                    dataSource={this.state.dataSource}
                    renderRow={this._renderRow.bind(this)}/>
            </View>
        );
    }

    render() {
        if (!this.state.loaded) {
            return this._renderLoadingView();
        } else {
            return this._renderView();
        }
    }
}

const styles = StyleSheet.create({
    container: {
        alignItems: 'center',
        justifyContent: 'center',
        flex: 1
    },
    instructions: {
        textAlign: 'center',
        color: 'red',
        marginBottom: 5
    },
    icon: {
        width: 100,
        height: 100,
    },
    row: {
        flexDirection: 'row',
        justifyContent: 'flex-start',
        padding: 10,
        backgroundColor: '#F6F6F6',
    },
    thumb: {
        width: 64,
        height: 64,
    },
    text: {
        flex: 1,
    },
});<|endoftext|>


<commit_before>var chalk = require('chalk');

var Level = function(str, int, printStackTraces, colorModifier) {
    this.str = str;
    this.int = int;
    this.printStackTraces = printStackTraces;
    this.colorModifier = colorModifier;
};
Level.prototype.constructor = Level;

module.exports = {
    Level: Level,
    ALL:   new Level("ALL  ", 500,  false, null),
    DEBUG: new Level("DEBUG", 1000, false, null),
    INFO:  new Level("INFO ", 1500, false, null),
    WARN:  new Level("WARN ", 2000, false, chalk.yellow),
    ERROR: new Level("ERROR", 4000, true , chalk.red),
    FATAL: new Level("FATAL", 5000, true , chalk.red)
};<commit_msg>added level type for future use<commit_after>var chalk = require('chalk');

var Level = function(level, str, int, printStackTraces, colorModifier) {
    this.level = level;
    this.str = str;
    this.int = int;
    this.printStackTraces = printStackTraces;
    this.colorModifier = colorModifier;
};
Level.prototype.constructor = Level;

module.exports = {
    Level: Level,
    ALL:   new Level("all",   "ALL  ", 500,  false, null),
    DEBUG: new Level("debug", "DEBUG", 1000, false, null),
    INFO:  new Level("info",  "INFO ", 1500, false, null),
    WARN:  new Level("warn",  "WARN ", 2000, false, chalk.yellow),
    ERROR: new Level("error", "ERROR", 4000, true , chalk.red),
    FATAL: new Level("fatal", "FATAL", 5000, true , chalk.red)
};<|endoftext|>


<commit_before>/*
==================================================================================================
  Jasy - JavaScript Tooling Refined
  Copyright 2010 Sebastian Werner
==================================================================================================
*/

(function(global)
{
  declare("Core",
  {
    /**
     * Declares the given namespace and stores the given object onto it.
     *
     * @param namespace {String} Namespace/Package e.g. foo.bar.baz
     * @param object {Object} Any object
     */
    declare : function(namespace, object)
    {
      var splits = namespace.split(".");
      var current = global;
      var length = splits.length-1;
      var i = 0;
      var test;

      // Fast-check for existing segments
      while(test=current[splits[i]])
      {
        current = test;
        i++;
      }

      // Create missing segments
      while(i<length) {
        current = current[splits[i++]] = {};
      }

      // Store Object
      return current[splits[i]] = object;
    },

    /**
     * Resolves a given namespace into the already existing object/class.
     *
     * @param name {String} Name to resolve
     */
    resolve : function(name)
    {
      var current = global;

      if (name)
      {
        var splitted = name.split(".");
        for (var i=0, l=splitted.length; i<l; i++)
        {
          current = current[splitted[i]];
          if (!current) {
            break;
          }
        }
      }

      return current || null;
    }
  });
})(this);
<commit_msg>Fixed missing declare()<commit_after>/*
==================================================================================================
  Jasy - JavaScript Tooling Refined
  Copyright 2010 Sebastian Werner
==================================================================================================
*/

(function(global)
{
  var declare = function(namespace, object)
  {
    var splits = namespace.split(".");
    var current = global;
    var length = splits.length-1;
    var i = 0;
    var test;

    // Fast-check for existing segments
    while(test=current[splits[i]])
    {
      current = test;
      i++;
    }

    // Create missing segments
    while(i<length) {
      current = current[splits[i++]] = {};
    }

    // Store Object
    return current[splits[i]] = object;
  };

  declare("Core",
  {
    /**
     * Declares the given namespace and stores the given object onto it.
     *
     * @param namespace {String} Namespace/Package e.g. foo.bar.baz
     * @param object {Object} Any object
     */
    declare : declare,

    /**
     * Resolves a given namespace into the already existing object/class.
     *
     * @param name {String} Name to resolve
     */
    resolve : function(name)
    {
      var current = global;

      if (name)
      {
        var splitted = name.split(".");
        for (var i=0, l=splitted.length; i<l; i++)
        {
          current = current[splitted[i]];
          if (!current) {
            break;
          }
        }
      }

      return current || null;
    }
  });
})(this);
<|endoftext|>


<commit_before>import React from 'react'
import { func, bool } from 'prop-types'
import { connect } from 'react-redux'
// components
import { push } from 'react-router-redux'
import Drawer from '@material-ui/core/Drawer'
import { List, ListItem, ListItemIcon, ListItemText } from '@material-ui/core';
// icons
import StarIcon from '@material-ui/icons/Star';
import BitcoinIcon from '@material-ui/icons/AccountBalanceWallet';
import PaymentIcon from '@material-ui/icons/Send';
import SettingsIcon from '@material-ui/icons/Settings'

const DrawerComponent = ({ toggleDrawer, drawerOpen, push }) => {

  return (
    <Drawer
      onClose={toggleDrawer}
      open={drawerOpen}
    >
      <List component='nav'>
        <ListItem button onClick={() => push('/claim')}>
          <ListItemIcon><StarIcon/></ListItemIcon>
          <ListItemText primary='My Reputation' />
        </ListItem>
        <ListItem button onClick={() => push('/transactions')}>
          <ListItemIcon><BitcoinIcon/></ListItemIcon>
          <ListItemText primary='Transactions' />
        </ListItem>
        <ListItem button onClick={() => push('/pay')}>
          <ListItemIcon><PaymentIcon/></ListItemIcon>
          <ListItemText primary='Pay with Chlu' />
        </ListItem>
        <ListItem button onClick={() => push('/settings')}>
          <ListItemIcon><SettingsIcon/></ListItemIcon>
          <ListItemText primary='Settings' />
        </ListItem>
      </List>
    </Drawer>
  )
}

DrawerComponent.propTypes = {
  toggleDrawer: func,
  drawerOpen: bool
}

function mapDispatchToProps(dispatch) {
  return {
    push: x => dispatch(push(x))
  }
}

export default connect(
  null,
  mapDispatchToProps
)(DrawerComponent)
<commit_msg>renamed Pay with Chlu to Pay<commit_after>import React from 'react'
import { func, bool } from 'prop-types'
import { connect } from 'react-redux'
// components
import { push } from 'react-router-redux'
import Drawer from '@material-ui/core/Drawer'
import { List, ListItem, ListItemIcon, ListItemText } from '@material-ui/core';
// icons
import StarIcon from '@material-ui/icons/Star';
import BitcoinIcon from '@material-ui/icons/AccountBalanceWallet';
import PaymentIcon from '@material-ui/icons/Send';
import SettingsIcon from '@material-ui/icons/Settings'

const DrawerComponent = ({ toggleDrawer, drawerOpen, push }) => {

  return (
    <Drawer
      onClose={toggleDrawer}
      open={drawerOpen}
    >
      <List component='nav'>
        <ListItem button onClick={() => push('/claim')}>
          <ListItemIcon><StarIcon/></ListItemIcon>
          <ListItemText primary='My Reputation' />
        </ListItem>
        <ListItem button onClick={() => push('/transactions')}>
          <ListItemIcon><BitcoinIcon/></ListItemIcon>
          <ListItemText primary='Transactions' />
        </ListItem>
        <ListItem button onClick={() => push('/pay')}>
          <ListItemIcon><PaymentIcon/></ListItemIcon>
          <ListItemText primary='Pay' />
        </ListItem>
        <ListItem button onClick={() => push('/settings')}>
          <ListItemIcon><SettingsIcon/></ListItemIcon>
          <ListItemText primary='Settings' />
        </ListItem>
      </List>
    </Drawer>
  )
}

DrawerComponent.propTypes = {
  toggleDrawer: func,
  drawerOpen: bool
}

function mapDispatchToProps(dispatch) {
  return {
    push: x => dispatch(push(x))
  }
}

export default connect(
  null,
  mapDispatchToProps
)(DrawerComponent)
<|endoftext|>


<commit_before>var app = angular.module('messages', ['core', 'infinite-scroll']);

app.config(['$httpProvider', '$interpolateProvider', function($httpProvider, $interpolateProvider) {
    $interpolateProvider.startSymbol('{$');
    $interpolateProvider.endSymbol('$}');
    $httpProvider.defaults.xsrfCookieName = 'csrftoken';
    $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
}]);

// throttle/debounce the frequency of infinite-scroll events
angular.module('infinite-scroll').value('THROTTLE_MILLISECONDS', 100);

app.factory('MessagesService', ['$http', '$timeout', function($http, $timeout) {

    // the url under which the profiles api is located
    var resource_url = '/contact/api/messages/';

    var service = {};

    function fetchMessages() {
        return $http.get(service.current_url)
            .success(function(response) {
                console.log(response);
                service.count = response.count;
                service.next = response.next;
                service.rows = service.rows.concat(response.results);
            });
    }

    service.init = function() {
        // reset the url
        service.current_url = resource_url;

        console.log(service.current_url + ('api/status'))
        $http.get(service.current_url).success(function(response) {
                console.log(response);
                //service.rows = service.rows.concat(response.results);
            });
        // reset data
        service.search_string = null;
        service.rows = [];

        // fetch the first set of profiles
        fetchMessages();
    };

    service.search = function() {
        // reset the url and add the search string
        service.current_url = resource_url + '?search=' + service.search_string;

        // reset data
        service.rows = [];

        // fetch the profiles with the search parameter
        fetchMessages();
    };

    service.scroll = function() {
        if (service.next_url) {
            // set the url to next and invalidate next so this code will not be triggered again
            service.url = service.next_url;
            service.next_url = null;

            // fetch the profiles with the next url
            fetchMessages();
        }
    };

    service.modal = function(modal_id, index) {
        service.current_index = index;
        service.current_row = angular.copy(service.rows[index]);
        service.errors = {};

        $timeout(function() {
            $('#' + modal_id).modal('show');
        });
    };

    service.updateMessage = function(row, status) {
        console.log('updateMessage')
        //console.log(action)
        service.errors = {};

        row.status = status;
        row.status_label = status;
        return $http.put(resource_url + row.id + '/', row)

    }

    return service;
}]);

app.controller('MessagesController', ['$scope', 'MessagesService', function($scope, MessagesService) {

    $scope.service = MessagesService;
    $scope.service.init();

}]);
<commit_msg>labels and status set<commit_after>var app = angular.module('messages', ['core', 'infinite-scroll']);

app.config(['$httpProvider', '$interpolateProvider', function($httpProvider, $interpolateProvider) {
    $interpolateProvider.startSymbol('{$');
    $interpolateProvider.endSymbol('$}');
    $httpProvider.defaults.xsrfCookieName = 'csrftoken';
    $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
}]);

// throttle/debounce the frequency of infinite-scroll events
angular.module('infinite-scroll').value('THROTTLE_MILLISECONDS', 100);

app.factory('MessagesService', ['$http', '$timeout', function($http, $timeout) {

    // the url under which the profiles api is located
    var resource_url = '/contact/api/messages/';

    var service = {};

    function fetchMessages() {
        return $http.get(service.current_url)
            .success(function(response) {
                service.count = response.count;
                service.next = response.next;
                service.rows = service.rows.concat(response.results);
            });
    }

    service.init = function() {
        // reset the url
        service.current_url = resource_url;

        console.log(resource_url)
        $http.get(service.current_url).success(function(response) {
                console.log(response);
                //service.rows = service.rows.concat(response.results);
            });
        // reset data
        service.search_string = null;
        service.rows = [];

        // fetch the first set of profiles
        fetchMessages();
    };

    service.search = function() {
        // reset the url and add the search string
        service.current_url = resource_url + '?search=' + service.search_string;

        // reset data
        service.rows = [];

        // fetch the profiles with the search parameter
        fetchMessages();
    };

    service.scroll = function() {
        if (service.next_url) {
            // set the url to next and invalidate next so this code will not be triggered again
            service.url = service.next_url;
            service.next_url = null;

            // fetch the profiles with the next url
            fetchMessages();
        }
    };

    service.modal = function(modal_id, index) {
        service.current_index = index;
        service.current_row = angular.copy(service.rows[index]);
        service.errors = {};

        $timeout(function() {
            $('#' + modal_id).modal('show');
        });
    };

    service.updateMessage = function(row, status) {
        console.log('status:', status)
        console.log(row)

        //console.log(action)
        service.errors = {};
        row.status = status;

        $http.get('/contact/api/status/?format=json').success(function(status_json) {
            console.log(status_json)
            text = ""
            for(i = 0; i < status_json.length; i++){
                console.log(i)
                console.log(status_json[i])
                if (status_json[i].id == status){
                    row.status_label = status_json[i].text

                }
            }
        });
        return $http.put(resource_url + row.id + '/', row)
    }

    return service;
}]);

app.controller('MessagesController', ['$scope', 'MessagesService', function($scope, MessagesService) {

    $scope.service = MessagesService;
    $scope.service.init();

}]);
<|endoftext|>


<commit_before>$(function() {

  var doc;
  var iphone;
  var windowWidth;
  var windowHeight;
  var pageHeight;
  var contentPadding;
  var footerHeight;
  var noticeBanner;
  var componentsList;
  var navComponentLinks;
  var contentSection;
  var currentActive;
  var topCache;
  var eventListeners;

  var initialize = function  () {
    currentActive        = 0;
    topCache             = [];
    win                  = $(window);
    doc                  = $(document);
    bod                  = $(document.body)
    iphone               = iphone || $('.iphone');
    noticeBanner         = $('.notice-banner');
    navComponentLinks    = $('.nav-components-link');
    componentsList       = $('.components-list');
    componentLinks       = $('.component-example a');
    contentSection       = $('.component');
    topCache             = contentSection.map(function () { return $(this).offset().top })
    windowHeight         = $(window).height() / 3
    pageHeight           = $(document).height();
    contentPadding       = parseInt($('.docs-content').css('padding-bottom'));
    footerHeight         = $('.docs-footer').outerHeight(false);

    iphone.initialLeft   = iphone.offset().left;
    iphone.initialTop    = iphone.initialTop || iphone.offset().top;
    iphone.dockingOffset = ($(window).height() + $('.platform-toggle').height() - iphone.height())/2;
    checkDesktopContent();
    calculateScroll();
    console.log(iphone.dockingOffset);

    if (!eventListeners) addEventListeners();
  }

  var addEventListeners = function () {
    eventListeners = true;

    noticeBanner.on('click', function () {
      $(this).hide();
    });

    iphone.on('click', function (e) {
      e.preventDefault();
    });

    navComponentLinks.click(function(e) {
      e.stopPropagation();
      e.preventDefault();
      componentsList.toggleClass('active');
    })

    doc.on('click', function () {
      componentsList.removeClass('active');
    })

    win.on('scroll', calculateScroll);
  }

  var checkDesktopContent = function () {
    windowWidth = $(window).width();
    if (windowWidth <= 768) {
      var content = $('.content')
      if (content.length > 1) {
        $(content[0]).remove()
      }
    }
  }

  var calculateScroll = function() {
    // if small screen don't worry about this
    if (windowWidth <= 768) return

    // Save scrollTop value
    var contentSectionItem;
    var currentTop = win.scrollTop();

    // If page is scrolled to bottom near footers
    if(pageHeight - currentTop < footerHeight + contentPadding + 1400) {
      iphone[0].className = "iphone iphone-bottom";
      iphone[0].setAttribute('style','')
    } else if((iphone.initialTop - currentTop) <= iphone.dockingOffset + 40) {
      iphone[0].className = "iphone iphone-fixed";
      iphone.css({top: iphone.dockingOffset})
    } else {
      iphone[0].className = "iphone"
      iphone[0].setAttribute('style','')
    }

    if(pageHeight - currentTop <= $('.platform-toggle') {
      $('.platform-toggle').addClass('fixed');
    } else {
      $('.platform-toggle').removeClass('fixed');
    }

    // Injection of components into phone
    for (var l = contentSection.length; l--;) {
      if ((topCache[l] - currentTop) < windowHeight) {
        if (currentActive == l) return;
        currentActive = l;
        bod.find('.component.active').removeClass('active');
        contentSectionItem = $(contentSection[l])
        contentSectionItem.addClass('active')
        if(contentSectionItem.attr('id')) {
          iphone.attr("id", contentSectionItem.attr('id') + "InPhone");
        } else {
          iphone.attr("id", "")
        }
        if (!contentSectionItem.hasClass('informational')) {
          updateContent(contentSectionItem.find('.highlight .html').text())
        }
        break
      }
    }

    function updateContent(content) {
      $('#iwindow').html(content);
    }
  }

  $(window).on('load resize', initialize);
  $(window).on('load', function () { new FingerBlast('.iphone-content'); });
});<commit_msg>fixing up the phone placement<commit_after>$(function() {

  var doc;
  var iphone;
  var windowWidth;
  var windowHeight;
  var pageHeight;
  var contentPadding;
  var footerHeight;
  var noticeBanner;
  var componentsList;
  var navComponentLinks;
  var contentSection;
  var currentActive;
  var topCache;
  var eventListeners;

  var initialize = function  () {
    currentActive        = 0;
    topCache             = [];
    win                  = $(window);
    doc                  = $(document);
    bod                  = $(document.body)
    iphone               = iphone || $('.iphone');
    noticeBanner         = $('.notice-banner');
    navComponentLinks    = $('.nav-components-link');
    componentsList       = $('.components-list');
    componentLinks       = $('.component-example a');
    contentSection       = $('.component');
    topCache             = contentSection.map(function () { return $(this).offset().top })
    windowHeight         = $(window).height() / 3
    pageHeight           = $(document).height();
    contentPadding       = parseInt($('.docs-content').css('padding-bottom'));
    footerHeight         = $('.docs-footer').outerHeight(false);

    iphone.initialLeft   = iphone.offset().left;
    iphone.initialTop    = iphone.initialTop || iphone.offset().top;
    iphone.dockingOffset = ($(window).height() + $('.platform-toggle').height() - iphone.height())/2;
    checkDesktopContent();
    calculateScroll();

    if (!eventListeners) addEventListeners();
  }

  var addEventListeners = function () {
    eventListeners = true;

    noticeBanner.on('click', function () {
      $(this).hide();
    });

    iphone.on('click', function (e) {
      e.preventDefault();
    });

    navComponentLinks.click(function(e) {
      e.stopPropagation();
      e.preventDefault();
      componentsList.toggleClass('active');
    })

    doc.on('click', function () {
      componentsList.removeClass('active');
    })

    win.on('scroll', calculateScroll);
  }

  var checkDesktopContent = function () {
    windowWidth = $(window).width();
    if (windowWidth <= 768) {
      var content = $('.content')
      if (content.length > 1) {
        $(content[0]).remove()
      }
    }
  }

  var calculateScroll = function() {
    // if small screen don't worry about this
    if (windowWidth <= 768) return

    // Save scrollTop value
    var contentSectionItem;
    var currentTop = win.scrollTop();

    // If page is scrolled to bottom near footers
    if(pageHeight - currentTop < footerHeight + contentPadding + 1400) {
      iphone[0].className = "iphone iphone-bottom";
      iphone[0].setAttribute('style','')
    } else if((iphone.initialTop - currentTop) <= iphone.dockingOffset + 40) {
      iphone[0].className = "iphone iphone-fixed";
      iphone.css({top: iphone.dockingOffset})
    } else {
      iphone[0].className = "iphone"
      iphone[0].setAttribute('style','')
    }

    if(currentTop >= $('.docs-masthead').outerHeight()) {
      $('.platform-toggle').addClass('fixed');
      console.log('fixed');
    } else {
      $('.platform-toggle').removeClass('fixed');
      console.log('not fixed');
    }

    // Injection of components into phone
    for (var l = contentSection.length; l--;) {
      if ((topCache[l] - currentTop) < windowHeight) {
        if (currentActive == l) return;
        currentActive = l;
        bod.find('.component.active').removeClass('active');
        contentSectionItem = $(contentSection[l])
        contentSectionItem.addClass('active')
        if(contentSectionItem.attr('id')) {
          iphone.attr("id", contentSectionItem.attr('id') + "InPhone");
        } else {
          iphone.attr("id", "")
        }
        if (!contentSectionItem.hasClass('informational')) {
          updateContent(contentSectionItem.find('.highlight .html').text())
        }
        break
      }
    }

    function updateContent(content) {
      $('#iwindow').html(content);
    }
  }

  $(window).on('load resize', initialize);
  $(window).on('load', function () { new FingerBlast('.iphone-content'); });
});<|endoftext|>


<commit_before>describe("IAS", function () {
  before(function() {
    this.timeout = 10000;

    window.scrollTo(0, 0);

    jQuery.ias({
      container : '.listing',
      item: '.post',
      pagination: '.navigation',
      next: '.next-posts a'
    });
  });

  after(function() {
    jQuery.ias('destroy');
  });

  it("should display a trigger", function() {
    var deferred = when.defer();

    jQuery.ias().extension(new IASTriggerExtension({
      text: 'trigger text',
      html: '
{text}
'
    }));

    jQuery.ias().initialize();

    expect($('.ias-trigger:visible').length).toEqual(0); // ensure it isn't already there

    scrollDown().then(function() {
      wait(1000).then(function() {
        // expect the trigger to be visible
        expect($('.ias-trigger:visible').length).toEqual(1);

        // expect it not to have loaded the next page
        expect($('#post11').length).toEqual(0);

        // expect it to have the correct text, as given with the options
        expect($('.ias-trigger:visible').text()).toEqual('trigger text');

        // expect it to have the additional class as given with the options
        expect($('.ias-trigger:visible').get(0)).toHaveClassName('extra-trigger-class');

        deferred.resolve();
      });
    });

    return deferred.promise;
  });

  it("should load the next page when the trigger is clicked", function() {
    var deferred = when.defer();

    jQuery.ias().extension(new IASTriggerExtension({
      text: 'trigger text',
      html: '
{text}
'
    }));

    jQuery.ias().initialize();

    scrollDown().then(function() {
      wait(1000).then(function() {
        $('.ias-trigger:visible').trigger('click');

        wait(2000).then(function() {
          expect($('#post11').length).toEqual(1);

          deferred.resolve();
        });
      });
    });

    return deferred.promise;
  });

  it("should display a trigger after offset", function() {
    var deferred = when.defer();

    jQuery.ias().extension(new IASTriggerExtension({
      text: 'trigger text',
      html: '
{text}
',
      offset: 2
    }));

    jQuery.ias().initialize();

    expect($('.ias-trigger:visible').length).toEqual(0); // ensure it isn't already there

    // scroll to page 2
    scrollDown().then(function() {
      wait(1000).then(function() {
        // expect the trigger not to be visible
        expect($('.ias-trigger:visible').length).toEqual(0);

        // expect it to have loaded the next page
        expect($('#post11').length).toEqual(1);

        // scroll to page 3
        scrollDown().then(function() {
          wait(1000).then(function() {
            // expect the trigger to be visible
            expect($('.ias-trigger:visible').length).toEqual(1);

            // expect it not to have loaded the next page
            expect($('#post21').length).toEqual(0);

            deferred.resolve();
          });
        });
      });
    });

    return deferred.promise;
  });

  it("should display a prev trigger", function() {
    var deferred = when.defer();

    jQuery.ias('destroy');

    loadFixture("page2.html", function() {
      jQuery.ias({
        container : '.listing',
        item: '.post',
        pagination: '.navigation',
        next: '.next-posts a'
      });

      expect($('.ias-trigger-prev:visible').length).toEqual(0); // ensure it isn't already there

      jQuery.ias().extension(new IASPagingExtension());
      jQuery.ias().extension(new IASTriggerExtension({
        textPrev: 'trigger prev text'
      }));
      jQuery.ias().extension(new IASHistoryExtension({
        prev: '.prev-posts a'
      }));

      wait(1000).then(function() {
        expect($('.ias-trigger-prev:visible').length).toEqual(1);

        expect($('.ias-trigger-prev:visible').text()).toEqual('trigger prev text');

        deferred.resolve();
      })
    });

    return deferred.promise;
  });
});
<commit_msg>increase wait time<commit_after>describe("IAS", function () {
  before(function() {
    this.timeout = 10000;

    window.scrollTo(0, 0);

    jQuery.ias({
      container : '.listing',
      item: '.post',
      pagination: '.navigation',
      next: '.next-posts a'
    });
  });

  after(function() {
    jQuery.ias('destroy');
  });

  it("should display a trigger", function() {
    var deferred = when.defer();

    jQuery.ias().extension(new IASTriggerExtension({
      text: 'trigger text',
      html: '
{text}
'
    }));

    jQuery.ias().initialize();

    expect($('.ias-trigger:visible').length).toEqual(0); // ensure it isn't already there

    scrollDown().then(function() {
      wait(2000).then(function() {
        // expect the trigger to be visible
        expect($('.ias-trigger:visible').length).toEqual(1);

        // expect it not to have loaded the next page
        expect($('#post11').length).toEqual(0);

        // expect it to have the correct text, as given with the options
        expect($('.ias-trigger:visible').text()).toEqual('trigger text');

        // expect it to have the additional class as given with the options
        expect($('.ias-trigger:visible').get(0)).toHaveClassName('extra-trigger-class');

        deferred.resolve();
      });
    });

    return deferred.promise;
  });

  it("should load the next page when the trigger is clicked", function() {
    var deferred = when.defer();

    jQuery.ias().extension(new IASTriggerExtension({
      text: 'trigger text',
      html: '
{text}
'
    }));

    jQuery.ias().initialize();

    scrollDown().then(function() {
      wait(1000).then(function() {
        $('.ias-trigger:visible').trigger('click');

        wait(2000).then(function() {
          expect($('#post11').length).toEqual(1);

          deferred.resolve();
        });
      });
    });

    return deferred.promise;
  });

  it("should display a trigger after offset", function() {
    var deferred = when.defer();

    jQuery.ias().extension(new IASTriggerExtension({
      text: 'trigger text',
      html: '
{text}
',
      offset: 2
    }));

    jQuery.ias().initialize();

    expect($('.ias-trigger:visible').length).toEqual(0); // ensure it isn't already there

    // scroll to page 2
    scrollDown().then(function() {
      wait(1000).then(function() {
        // expect the trigger not to be visible
        expect($('.ias-trigger:visible').length).toEqual(0);

        // expect it to have loaded the next page
        expect($('#post11').length).toEqual(1);

        // scroll to page 3
        scrollDown().then(function() {
          wait(1000).then(function() {
            // expect the trigger to be visible
            expect($('.ias-trigger:visible').length).toEqual(1);

            // expect it not to have loaded the next page
            expect($('#post21').length).toEqual(0);

            deferred.resolve();
          });
        });
      });
    });

    return deferred.promise;
  });

  it("should display a prev trigger", function() {
    var deferred = when.defer();

    jQuery.ias('destroy');

    loadFixture("page2.html", function() {
      jQuery.ias({
        container : '.listing',
        item: '.post',
        pagination: '.navigation',
        next: '.next-posts a'
      });

      expect($('.ias-trigger-prev:visible').length).toEqual(0); // ensure it isn't already there

      jQuery.ias().extension(new IASPagingExtension());
      jQuery.ias().extension(new IASTriggerExtension({
        textPrev: 'trigger prev text'
      }));
      jQuery.ias().extension(new IASHistoryExtension({
        prev: '.prev-posts a'
      }));

      wait(1000).then(function() {
        expect($('.ias-trigger-prev:visible').length).toEqual(1);

        expect($('.ias-trigger-prev:visible').text()).toEqual('trigger prev text');

        deferred.resolve();
      })
    });

    return deferred.promise;
  });
});
<|endoftext|>


<commit_before>
var test    = require('tape').test
  , msgpack = require('../')
  , bl      = require('bl')

test('encoding/decoding 64-bits big-endian unsigned integers', function(t) {
  var encoder = msgpack()
    , allNum  = []
    , base    = 0xffffffff

  allNum.push(0xffffffff)

  allNum.push(0xffffffffeeeee)

  allNum.forEach(function(num) {
    t.test('encoding ' + num, function(t) {
      var buf = encoder.encode(num)
      t.equal(buf.length, 9, 'must have 9 bytes')
      t.equal(buf[0], 0xcf, 'must have the proper header')
      t.equal(buf.readUInt32BE(5) * base + buf.readUInt32BE(1), num, 'must decode correctly');
      t.end()
    })

    t.test('mirror test ' + num, function(t) {
      t.equal(encoder.decode(encoder.encode(num)), num, 'must stay the same');
      t.end()
    })
  })

  t.end()
})

test('decoding an incomplete 64-bits big-endian unsigned integer', function(t) {
  var encoder = msgpack()
  var buf = new Buffer(8)
  buf[0] = 0xcf
  buf = bl().append(buf)
  var origLength = buf.length
  t.throws(function() {encoder.decode(buf)}, encoder.IncompleteBufferError, "must throw IncompleteBufferError")
  t.equals(buf.length, origLength, "must not consume any byte")
  t.end()
})
<commit_msg>fix uint64 tests<commit_after>
var test    = require('tape').test
  , msgpack = require('../')
  , bl      = require('bl')

test('encoding/decoding 64-bits big-endian unsigned integers', function(t) {
  var encoder = msgpack()
    , allNum  = []
    , base    = 0xffffffff

  allNum.push(0xffffffff)

  allNum.push(0xffffffffeeeee)

  allNum.forEach(function(num) {
    t.test('encoding ' + num, function(t) {
      var buf = encoder.encode(num)
      t.equal(buf.length, 9, 'must have 9 bytes')
      t.equal(buf[0], 0xcf, 'must have the proper header')
      var result = 0;
      for (var k = 7; k >= 0; k--) {
           result += (buf.readUInt8(k + 1) * Math.pow(2 , (8 *(7-k))));
       }
      t.end()
    })

    t.test('mirror test ' + num, function(t) {
      t.equal(encoder.decode(encoder.encode(num)), num, 'must stay the same');
      t.end()
    })
  })

  t.end()
})

test('decoding an incomplete 64-bits big-endian unsigned integer', function(t) {
  var encoder = msgpack()
  var buf = new Buffer(8)
  buf[0] = 0xcf
  buf = bl().append(buf)
  var origLength = buf.length
  t.throws(function() {encoder.decode(buf)}, encoder.IncompleteBufferError, "must throw IncompleteBufferError")
  t.equals(buf.length, origLength, "must not consume any byte")
  t.end()
})
<|endoftext|>


<commit_before>import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
import FadeMixin from './FadeMixin';
import domUtils from './utils/domUtils';
import EventListener from './utils/EventListener';

// TODO:
// - aria-labelledby
// - Add `modal-body` div if only one child passed in that doesn't already have it
// - Tests

const Modal = React.createClass({
  mixins: [BootstrapMixin, FadeMixin],

  propTypes: {
    title: React.PropTypes.node,
    backdrop: React.PropTypes.oneOf(['static', true, false]),
    keyboard: React.PropTypes.bool,
    closeButton: React.PropTypes.bool,
    animation: React.PropTypes.bool,
    onRequestHide: React.PropTypes.func.isRequired
  },

  getDefaultProps() {
    return {
      bsClass: 'modal',
      backdrop: true,
      keyboard: true,
      animation: true,
      closeButton: true
    };
  },

  render() {
    let modalStyle = {display: 'block'};
    let dialogClasses = this.getBsClassSet();
    delete dialogClasses.modal;
    dialogClasses['modal-dialog'] = true;

    let classes = {
      modal: true,
      fade: this.props.animation,
      'in': !this.props.animation || !document.querySelectorAll
    };

    let modal = (

            {this.props.title ? this.renderHeader() : null}
            {this.props.children}

    );

    return this.props.backdrop ?
      this.renderBackdrop(modal) : modal;
  },

  renderBackdrop(modal) {
    let classes = {
      'modal-backdrop': true,
      'fade': this.props.animation
    };

    classes.in = !this.props.animation || !document.querySelectorAll;

    let onClick = this.props.backdrop === true ?
      this.handleBackdropClick : null;

    return (

        {modal}

    );
  },

  renderHeader() {
    let closeButton;
    if (this.props.closeButton) {
      closeButton = (
          <button type="button" className="close" aria-hidden="true" onClick={this.props.onRequestHide}>×</button>
        );
    }

    let style = this.props.bsStyle;
    let classes = {
      'modal-header': true
    };
    classes['bg-' + style] = style;
    classes['text-' + style] = style;

    let className = classNames(classes);

    return (

        {closeButton}
        {this.renderTitle()}

    );
  },

  renderTitle() {
    return (
      React.isValidElement(this.props.title) ?
        this.props.title :
{this.props.title}

    );
  },

  iosClickHack() {
    // IOS only allows click events to be delegated to the document on elements
    // it considers 'clickable' - anchors, buttons, etc. We fake a click handler on the
    // DOM nodes themselves. Remove if handled by React: https://github.com/facebook/react/issues/1169
    React.findDOMNode(this.refs.modal).onclick = function () {};
    React.findDOMNode(this.refs.backdrop).onclick = function () {};
  },

  componentDidMount() {
    this._onDocumentKeyupListener =
      EventListener.listen(domUtils.ownerDocument(this), 'keyup', this.handleDocumentKeyUp);

    let container = (this.props.container && React.findDOMNode(this.props.container)) ||
          domUtils.ownerDocument(this).body;
    container.className += container.className.length ? ' modal-open' : 'modal-open';

    if (this.props.backdrop) {
      this.iosClickHack();
    }
  },

  componentDidUpdate(prevProps) {
    if (this.props.backdrop && this.props.backdrop !== prevProps.backdrop) {
      this.iosClickHack();
    }
  },

  componentWillUnmount() {
    this._onDocumentKeyupListener.remove();
    let container = (this.props.container && React.findDOMNode(this.props.container)) ||
          domUtils.ownerDocument(this).body;
    container.className = container.className.replace(/ ?modal-open/, '');
  },

  handleBackdropClick(e) {
    if (e.target !== e.currentTarget) {
      return;
    }

    this.props.onRequestHide();
  },

  handleDocumentKeyUp(e) {
    if (this.props.keyboard && e.keyCode === 27) {
      this.props.onRequestHide();
    }
  }
});

export default Modal;
<commit_msg>[fixed] Modal div.modal-content should not have hidden class<commit_after>import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
import FadeMixin from './FadeMixin';
import domUtils from './utils/domUtils';
import EventListener from './utils/EventListener';

// TODO:
// - aria-labelledby
// - Add `modal-body` div if only one child passed in that doesn't already have it
// - Tests

const Modal = React.createClass({
  mixins: [BootstrapMixin, FadeMixin],

  propTypes: {
    title: React.PropTypes.node,
    backdrop: React.PropTypes.oneOf(['static', true, false]),
    keyboard: React.PropTypes.bool,
    closeButton: React.PropTypes.bool,
    animation: React.PropTypes.bool,
    onRequestHide: React.PropTypes.func.isRequired
  },

  getDefaultProps() {
    return {
      bsClass: 'modal',
      backdrop: true,
      keyboard: true,
      animation: true,
      closeButton: true
    };
  },

  render() {
    let modalStyle = {display: 'block'};
    let dialogClasses = this.getBsClassSet();
    delete dialogClasses.modal;
    dialogClasses['modal-dialog'] = true;

    let classes = {
      modal: true,
      fade: this.props.animation,
      'in': !this.props.animation || !document.querySelectorAll
    };

    let modal = (

            {this.props.title ? this.renderHeader() : null}
            {this.props.children}

    );

    return this.props.backdrop ?
      this.renderBackdrop(modal) : modal;
  },

  renderBackdrop(modal) {
    let classes = {
      'modal-backdrop': true,
      'fade': this.props.animation
    };

    classes.in = !this.props.animation || !document.querySelectorAll;

    let onClick = this.props.backdrop === true ?
      this.handleBackdropClick : null;

    return (

        {modal}

    );
  },

  renderHeader() {
    let closeButton;
    if (this.props.closeButton) {
      closeButton = (
          <button type="button" className="close" aria-hidden="true" onClick={this.props.onRequestHide}>×</button>
        );
    }

    let bsStyle = this.props.bsStyle;
    let classes = {
      'modal-header': true
    };
    classes['bg-' + bsStyle] = bsStyle;
    classes['text-' + bsStyle] = bsStyle;

    let className = classNames(classes);

    let style = {};
    if (this.props.bsStyle) {
      style.borderTopLeftRadius = 'inherit';
      style.borderTopRightRadius = 'inherit';
    }

    return (

        {closeButton}
        {this.renderTitle()}

    );
  },

  renderTitle() {
    return (
      React.isValidElement(this.props.title) ?
        this.props.title :
{this.props.title}

    );
  },

  iosClickHack() {
    // IOS only allows click events to be delegated to the document on elements
    // it considers 'clickable' - anchors, buttons, etc. We fake a click handler on the
    // DOM nodes themselves. Remove if handled by React: https://github.com/facebook/react/issues/1169
    React.findDOMNode(this.refs.modal).onclick = function () {};
    React.findDOMNode(this.refs.backdrop).onclick = function () {};
  },

  componentDidMount() {
    this._onDocumentKeyupListener =
      EventListener.listen(domUtils.ownerDocument(this), 'keyup', this.handleDocumentKeyUp);

    let container = (this.props.container && React.findDOMNode(this.props.container)) ||
          domUtils.ownerDocument(this).body;
    container.className += container.className.length ? ' modal-open' : 'modal-open';

    if (this.props.backdrop) {
      this.iosClickHack();
    }
  },

  componentDidUpdate(prevProps) {
    if (this.props.backdrop && this.props.backdrop !== prevProps.backdrop) {
      this.iosClickHack();
    }
  },

  componentWillUnmount() {
    this._onDocumentKeyupListener.remove();
    let container = (this.props.container && React.findDOMNode(this.props.container)) ||
          domUtils.ownerDocument(this).body;
    container.className = container.className.replace(/ ?modal-open/, '');
  },

  handleBackdropClick(e) {
    if (e.target !== e.currentTarget) {
      return;
    }

    this.props.onRequestHide();
  },

  handleDocumentKeyUp(e) {
    if (this.props.keyboard && e.keyCode === 27) {
      this.props.onRequestHide();
    }
  }
});

export default Modal;
<|endoftext|>