<commit_before>"use strict"

const math = require("mathjs")

// Math functions for nonlinearity
function sigmoid(value) {
    return 1/(1+math.pow(math.e, -value))
}

// derivative of sigmoid
function deriv(y) {
    return y * (1-y)
}

// both arrays must be of the same length
function multiplyElements(arr1, arr2) {
    arr1.forEach(function(index) {
        arr1[index] = arr1[index] * arr2[index];
    })
    return arr1
}

// must be vertical matrix
function getAveError(m1) {
    let sum = 0
    m1 = math.transpose(m1)
    let len = (m1.size())[1]

    for (let i = 0; i < len; i++) {
        sum += math.abs(m1.subset(math.index(0,i)))
    }
    return math.abs(sum / len)
}
// TODO: make a function that sets x and y

// Input Data
const x = math.matrix([[0, 0, 1, 1],
                       [0, 0, 1, 1],
                       [0, 0, 1, 1],
                       [0, 0, 1, 1],
                       [0, 1, 1, 1],
                       [0, 1, 1, 1],
                       [0, 1, 1, 1],
                       [0, 1, 1, 1],
                       [1, 0, 1, 1],
                       [1, 0, 1, 1],
                       [1, 0, 1, 1],
                       [1, 0, 1, 1],
                       [1, 1, 1, 1],
                       [1, 1, 1, 1],
                       [1, 1, 1, 1],
                       [1, 1, 1, 1]])

// Output Data
const y = math.transpose(math.matrix([[0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]))

const layer0 = x
let layer1
let layer1_error
let layer1_delta
let layer2
let layer2_error
let layer2_delta
let layer3
let layer3_error
let layer3_delta

let hiddenLayerSize
let error
let minError = 100
let synapse0
let synapse1
let synapse2
let minSynapse0
let minSynapse1
let minSynapse2

const hlSizes = [(x.size())[1], (x.size())[1] - 1, (x.size())[1] + 1]
const alphas = [0.1, 1, 10]
const dropout_percent = 0.2;

let count = 1;

for (let alphaIndex = 0; alphaIndex < 3; alphaIndex++) {

    // Iterate over 3 hidden layer sizes to get the best one
    for (let hlSizeIndex = 0; hlSizeIndex < 3; hlSizeIndex++) {

        // Weights
        hiddenLayerSize = hlSizes[hlSizeIndex]
        synapse0 = math.random([x.size()[1], hiddenLayerSize], -1, 1)
        synapse1 = math.random([hiddenLayerSize, hiddenLayerSize], -1, 1)
        synapse2 = math.random([hiddenLayerSize, 1], -1, 1)

        for (let i = 0; i < 40000; i++) {
            // forward propagation
            layer1 = math.multiply(layer0, synapse0).map(sigmoid)
            // dropout
            layer1.forEach(function(index) {
                let rand = math.random()
                if(rand < dropout_percent)
                    layer1[index] = 0
                layer1[index] *= 1.0/(1-dropout_percent)
            })
            layer2 = math.multiply(layer1, synapse1).map(sigmoid)
            layer3 = math.multiply(layer2, synapse2).map(sigmoid)
            // compare estimate with actual output
            layer3_error = math.subtract(y, layer3)
            // use slope of sigmoid to update values
            layer3_delta = multiplyElements(layer3_error, layer3.map(deriv))
            // distribute error over synapse 2
            layer2_error = math.multiply(layer3_delta, math.transpose(synapse2))
            // use slope of sigmoid to update values
            layer2_delta = multiplyElements(layer2_error, layer2.map(deriv))
            // distribute error over synapse 1
            layer1_error = math.multiply(layer2_delta, math.transpose(synapse1))
            // use slope of sigmoid to update values
            layer1_delta = multiplyElements(layer1_error, layer1.map(deriv))
            // compare estimate with actual output
            // update weights
            synapse0 = math.add(synapse0, math.multiply(math.transpose(layer0), layer1_delta))
            synapse1 = math.add(synapse1, math.multiply(math.transpose(layer1), layer2_delta))
            synapse2 = math.add(synapse2, math.multiply(math.transpose(layer2), layer3_delta))

            if(i % 10000 == 0) {
                if (i == 0) {
                    console.log(count)
                    count++
                }
                else
                    console.log(i)
            }
        }
        let currentError = getAveError(layer3_error)
        if (currentError < minError) {
            minError = currentError
            minSynapse2 = synapse2
            minSynapse1 = synapse1
            minSynapse0 = synapse0
            console.log("New min error")
            console.log(minError)
        }
    }
}

console.log("Min Error")
console.log(minError)

console.log("Output of training data after training")
let test1 = math.multiply(x, minSynapse0).map(sigmoid)
let test2 = math.multiply(test1, minSynapse1).map(sigmoid)
console.log(math.multiply(test2, minSynapse2).map(sigmoid))

// Test Cases for function
let testX = math.matrix([[0, 1, 1, 1]])
console.log("Output of [0, 1, 1, 1]")
let testl1 = math.multiply(testX, minSynapse0).map(sigmoid)
let testl2 = math.multiply(testl1, minSynapse1).map(sigmoid)
console.log(math.multiply(testl2, minSynapse2).map(sigmoid))

testX = math.matrix([[0, 0, 1, 1]])
console.log("Output of [0, 0, 1, 1]")
testl1 = math.multiply(testX, minSynapse0).map(sigmoid)
testl2 = math.multiply(testl1, minSynapse1).map(sigmoid)
console.log(math.multiply(testl2, minSynapse2).map(sigmoid))

testX = math.matrix([[1, 0, 1, 1]])
console.log("Output of [1, 0, 1, 1]")
testl1 = math.multiply(testX, minSynapse0).map(sigmoid)
testl2 = math.multiply(testl1, minSynapse1).map(sigmoid)
console.log(math.multiply(testl2, minSynapse2).map(sigmoid))

testX = math.matrix([[1, 1, 1, 1]])
console.log("Output of [1, 1, 1, 1]")
testl1 = math.multiply(testX, minSynapse0).map(sigmoid)
testl2 = math.multiply(testl1, minSynapse1).map(sigmoid)
console.log(math.multiply(testl2, minSynapse2).map(sigmoid))

console.log("Final Synapse0")
console.log(minSynapse0)
console.log("Final Synapse1")
console.log(minSynapse1)
console.log("Final Synapse2")
console.log(minSynapse2)
<commit_msg>changed alphas<commit_after>"use strict"

const math = require("mathjs")

// Math functions for nonlinearity
function sigmoid(value) {
    return 1/(1+math.pow(math.e, -value))
}

// derivative of sigmoid
function deriv(y) {
    return y * (1-y)
}

// both arrays must be of the same length
function multiplyElements(arr1, arr2) {
    arr1.forEach(function(index) {
        arr1[index] = arr1[index] * arr2[index];
    })
    return arr1
}

// must be vertical matrix
function getAveError(m1) {
    let sum = 0
    m1 = math.transpose(m1)
    let len = (m1.size())[1]

    for (let i = 0; i < len; i++) {
        sum += math.abs(m1.subset(math.index(0,i)))
    }
    return math.abs(sum / len)
}
// TODO: make a function that sets x and y

// Input Data
const x = math.matrix([[0, 0, 1, 1],
                       [0, 0, 1, 1],
                       [0, 0, 1, 1],
                       [0, 0, 1, 1],
                       [0, 1, 1, 1],
                       [0, 1, 1, 1],
                       [0, 1, 1, 1],
                       [0, 1, 1, 1],
                       [1, 0, 1, 1],
                       [1, 0, 1, 1],
                       [1, 0, 1, 1],
                       [1, 0, 1, 1],
                       [1, 1, 1, 1],
                       [1, 1, 1, 1],
                       [1, 1, 1, 1],
                       [1, 1, 1, 1]])

// Output Data
const y = math.transpose(math.matrix([[0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]))

const layer0 = x
let layer1
let layer1_error
let layer1_delta
let layer2
let layer2_error
let layer2_delta
let layer3
let layer3_error
let layer3_delta

let hiddenLayerSize
let error
let minError = 100
let synapse0
let synapse1
let synapse2
let minSynapse0
let minSynapse1
let minSynapse2

const hlSizes = [(x.size())[1], (x.size())[1] - 1, (x.size())[1] + 1]
const alphas = [0.01, 0.1, 1]
const dropout_percent = 0.2;

let count = 1;

for (let alphaIndex = 0; alphaIndex < 3; alphaIndex++) {

    // Iterate over 3 hidden layer sizes to get the best one
    for (let hlSizeIndex = 0; hlSizeIndex < 3; hlSizeIndex++) {

        // Weights
        hiddenLayerSize = hlSizes[hlSizeIndex]
        synapse0 = math.random([x.size()[1], hiddenLayerSize], -1, 1)
        synapse1 = math.random([hiddenLayerSize, hiddenLayerSize], -1, 1)
        synapse2 = math.random([hiddenLayerSize, 1], -1, 1)

        for (let i = 0; i < 40000; i++) {
            // forward propagation
            layer1 = math.multiply(layer0, synapse0).map(sigmoid)
            // dropout
            layer1.forEach(function(index) {
                let rand = math.random()
                if(rand < dropout_percent)
                    layer1[index] = 0
                layer1[index] *= 1.0/(1-dropout_percent)
            })
            layer2 = math.multiply(layer1, synapse1).map(sigmoid)
            layer3 = math.multiply(layer2, synapse2).map(sigmoid)
            // compare estimate with actual output
            layer3_error = math.subtract(y, layer3)
            // use slope of sigmoid to update values
            layer3_delta = multiplyElements(layer3_error, layer3.map(deriv))
            // distribute error over synapse 2
            layer2_error = math.multiply(layer3_delta, math.transpose(synapse2))
            // use slope of sigmoid to update values
            layer2_delta = multiplyElements(layer2_error, layer2.map(deriv))
            // distribute error over synapse 1
            layer1_error = math.multiply(layer2_delta, math.transpose(synapse1))
            // use slope of sigmoid to update values
            layer1_delta = multiplyElements(layer1_error, layer1.map(deriv))
            // compare estimate with actual output
            // update weights
            synapse0 = math.add(synapse0, math.multiply(math.transpose(layer0), layer1_delta))
            synapse1 = math.add(synapse1, math.multiply(math.transpose(layer1), layer2_delta))
            synapse2 = math.add(synapse2, math.multiply(math.transpose(layer2), layer3_delta))

            if(i % 10000 == 0) {
                if (i == 0) {
                    console.log(count)
                    count++
                }
                else
                    console.log(i)
            }
        }
        let currentError = getAveError(layer3_error)
        if (currentError < minError) {
            minError = currentError
            minSynapse2 = synapse2
            minSynapse1 = synapse1
            minSynapse0 = synapse0
            console.log("New min error")
            console.log(minError)
        }
    }
}

console.log("Min Error")
console.log(minError)

console.log("Output of training data after training")
let test1 = math.multiply(x, minSynapse0).map(sigmoid)
let test2 = math.multiply(test1, minSynapse1).map(sigmoid)
console.log(math.multiply(test2, minSynapse2).map(sigmoid))

// Test Cases for function
let testX = math.matrix([[0, 1, 1, 1]])
console.log("Output of [0, 1, 1, 1]")
let testl1 = math.multiply(testX, minSynapse0).map(sigmoid)
let testl2 = math.multiply(testl1, minSynapse1).map(sigmoid)
console.log(math.multiply(testl2, minSynapse2).map(sigmoid))

testX = math.matrix([[0, 0, 1, 1]])
console.log("Output of [0, 0, 1, 1]")
testl1 = math.multiply(testX, minSynapse0).map(sigmoid)
testl2 = math.multiply(testl1, minSynapse1).map(sigmoid)
console.log(math.multiply(testl2, minSynapse2).map(sigmoid))

testX = math.matrix([[1, 0, 1, 1]])
console.log("Output of [1, 0, 1, 1]")
testl1 = math.multiply(testX, minSynapse0).map(sigmoid)
testl2 = math.multiply(testl1, minSynapse1).map(sigmoid)
console.log(math.multiply(testl2, minSynapse2).map(sigmoid))

testX = math.matrix([[1, 1, 1, 1]])
console.log("Output of [1, 1, 1, 1]")
testl1 = math.multiply(testX, minSynapse0).map(sigmoid)
testl2 = math.multiply(testl1, minSynapse1).map(sigmoid)
console.log(math.multiply(testl2, minSynapse2).map(sigmoid))

console.log("Final Synapse0")
console.log(minSynapse0)
console.log("Final Synapse1")
console.log(minSynapse1)
console.log("Final Synapse2")
console.log(minSynapse2)
<|endoftext|>


<commit_before>import {Col, Row} from 'antd';
import React, { Component } from 'react';

import ReactEcharts from 'echarts-for-react';
import { autobind } from 'core-decorators';

const echarts = require('echarts');

export default class Chart extends Component {
    constructor(props) {
        super(props);

        this.state = {
            width: '44.45%'
        };
    }

    componentWillReceiveProps(nextProps) {
        if (!nextProps.initialWidth) this.setState({ width: '100%' });
        /*
            Ugly hack for non-chrome browsers, where the chart would take the length of the entire viewport
        */
    }

    @autobind
    onChartReady(chart) {
        chart.hideLoading();
    }

    @autobind
    getOption() {
        const option = {
            title: {
                text: 'Gráfico 1'
            },
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['Serie 1', 'Serie 2', 'Serie 3']
            },
            toolbox: {
                feature: {
                    saveAsImage: {
                        title: 'PNG'
                    }
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: [
                {
                    type: 'category',
                    boundaryGap: false,
                    data: ['abc', 'def', 'ghi', 'jk', 'lm', 'no', 'pq']
                }
            ],
            yAxis: [
                {
                    type: 'value'
                }
            ],
            series: [
                {
                    name: 'Serie 1',
                    type: 'line',
                    stack: '123',
                    areaStyle: {normal: {}},
                    data: [120, 132, 101, 134, 90, 230, 210]
                },
                {
                    name: 'Serie 2',
                    type: 'line',
                    stack: '456',
                    areaStyle: {normal: {}},
                    data: [220, 182, 191, 234, 290, 330, 310]
                },
                {
                    name: 'Serie 3',
                    type: 'line',
                    stack: '789',
                    areaStyle: {normal: {}},
                    data: [150, 232, 201, 154, 190, 330, 410]
                }
            ]
        };

        return option;
    }

    render() {
        const styles = require('./Chart.scss');
        const sia = require('./themes/sia');

        echarts.registerTheme(sia.name, sia.theme);

        return (

                <ReactEcharts
                  option={this.getOption()}
                  style={{
                      height: '27rem',
                      width: this.state.width
                  }}
                  className="react_for_echarts"
                  theme="sia"
                  onChartReady={this.onChartReady} />

        );
    }
}
<commit_msg>Style tweak<commit_after>import {Col, Row} from 'antd';
import React, { Component } from 'react';

import ReactEcharts from 'echarts-for-react';
import { autobind } from 'core-decorators';

const echarts = require('echarts');

export default class Chart extends Component {
    constructor(props) {
        super(props);

        this.state = {
            width: '44.45%'
        };
    }

    componentWillReceiveProps(nextProps) {
        if (!nextProps.initialWidth) this.setState({ width: '100%' });
        /*
            Ugly hack for non-chrome browsers, where the chart would take the length of the entire viewport
        */
    }

    @autobind
    onChartReady(chart) {
        chart.hideLoading();
    }

    @autobind
    getOption() {
        const option = {
            title: {
                text: 'Gráfico 1'
            },
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['Serie 1', 'Serie 2', 'Serie 3']
            },
            toolbox: {
                feature: {
                    saveAsImage: {
                        title: 'PNG'
                    }
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: [
                {
                    type: 'category',
                    boundaryGap: false,
                    data: ['abc', 'def', 'ghi', 'jk', 'lm', 'no', 'pq']
                }
            ],
            yAxis: [
                {
                    type: 'value'
                }
            ],
            series: [
                {
                    name: 'Serie 1',
                    type: 'line',
                    stack: '123',
                    areaStyle: {normal: {}},
                    data: [120, 132, 101, 134, 90, 230, 210]
                },
                {
                    name: 'Serie 2',
                    type: 'line',
                    stack: '456',
                    areaStyle: {normal: {}},
                    data: [220, 182, 191, 234, 290, 330, 310]
                },
                {
                    name: 'Serie 3',
                    type: 'line',
                    stack: '789',
                    areaStyle: {normal: {}},
                    data: [150, 232, 201, 154, 190, 330, 410]
                }
            ]
        };

        return option;
    }

    render() {
        const styles = require('./Chart.scss');
        const sia = require('./themes/sia');

        echarts.registerTheme(sia.name, sia.theme);

        return (

                <ReactEcharts
                  option={this.getOption()}
                  style={{
                      height: '27rem',
                      width: this.state.width
                  }}
                  theme="sia"
                  onChartReady={this.onChartReady} />

        );
    }
}
<|endoftext|>


<commit_before>// Styles
import './_Sub-Menu.css';

// Libraries
import React, { Component, PropTypes } from 'react';
import TextField from 'material-ui/lib/text-field';
import { Link } from 'react-router';

class SubMenu extends Component {
	render () {
		const { data, headerTitle } = this.props;
		let linkHtml = data.map(({ name, url }, i) => {
			url = url ? url : '/';
			return (
				<span className="mdl-navigation__link" key={`submenu-${i}`}>
				    <Link className="mdl-navigation__link__tag" activeClassName="mdl-navigation__link__tag--active" to={url} key={i}>{name}</Link>

			);
		});

		return (

					{headerTitle}

			            {linkHtml}

            <TextField
              hintText="Search..." />
            search

		);
	}
}

SubMenu.propTypes = {
	data       : PropTypes.array.isRequired,
	headerTitle: PropTypes.string
};

SubMenu.defaultProps = {
	headerTitle: ''
};

export default SubMenu;
<commit_msg>Fix submenu css<commit_after>// Styles
import './_Sub-Menu.css';

// Libraries
import React, { Component, PropTypes } from 'react';
import TextField from 'material-ui/lib/text-field';
import { Link } from 'react-router';

class SubMenu extends Component {
	render () {
		const { data, headerTitle } = this.props;
		let linkHtml = data.map(({ name, url }, i) => {
			url = url ? url : '/';
			return (
				<span className="mdl-navigation__link" key={`submenu-${i}`}>
				    <Link
					    className="mdl-navigation__link__tag"
						activeClassName="mdl-navigation__link__tag--active"
						to={url}
						key={i}
						onlyActiveOnIndex={url.split('/').length <= 3}>
						    {name}
					</Link>

			);
		});

		return (

					{headerTitle}

			            {linkHtml}

            <TextField
              hintText="Search..." />
            search

		);
	}
}

SubMenu.propTypes = {
	data       : PropTypes.array.isRequired,
	headerTitle: PropTypes.string
};

SubMenu.defaultProps = {
	headerTitle: ''
};

export default SubMenu;
<|endoftext|>


<commit_before>/*
Copyright (c) 2014, EDINA.
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this
   list of conditions and the following disclaimer in the documentation and/or
   other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software must
   display the following acknowledgement: This product includes software
   developed by the EDINA.
4. Neither the name of the EDINA nor the names of its contributors may be used to
   endorse or promote products derived from this software without specific prior
   written permission.

THIS SOFTWARE IS PROVIDED BY EDINA ''AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL EDINA BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
*/

"use strict";

define(function(){

    var db;

    var DATABASE_CREATED = 'DATABASE_CREATED_FLAG';

    var onError = function(tx, e) {
        console.warn("There has been an error: " + e.message);
    };

    var onSuccess = function(tx, r) {
        localStorage.setItem(DATABASE_CREATED, "true");
    };

    var webdb = {
        open: function() {
            var dbSize = 10 * 1024 * 1024; // 10MB
            var databaseOpened;
            if(window.sqlitePlugin) {
                window.sqlitePlugin.openDatabase("webDbCache", "1.0", "Cached Tiles", dbSize);
            } else {

                databaseOpened = openDatabase("webDbCache", "1.0", "Cached Tiles", dbSize);
            }
            return databaseOpened;
        },

        createTablesIfRequired: function() {
                console.log("Creating DataBase Tables");

                db.transaction(function(tx) {
                    tx.executeSql("CREATE TABLE IF NOT EXISTS " +
                                  "tiles(zoom_level INTEGER, tile_column INTEGER, tile_row INTEGER, tile_data TEXT, mapName TEXT)", [], onSuccess,
                                  onError);

                    tx.executeSql("CREATE UNIQUE INDEX  IF NOT EXISTS " +
                                  " tile_index on tiles(zoom_level, tile_column, tile_row, mapName)", [], onSuccess,
                                  onError);

                });
        },

        deleteMap: function(mapName, callback){

            var success = function (tx, rs){

                if(callback){
                    callback(true);
                }
            };
            var error = function (tx,e){
                console.log("error DELETING MAP");
                console.log(e);
            };
            db.transaction(function(tx) {
                console.log("Delete mapname  " + mapName);
                tx.executeSql("DELETE FROM tiles WHERE mapName=?",
                              [ mapName],
                              success,
                              error
                             );

            });
        },

        insertCachedTilePath: function(x, y, z, tileData, mapName, callback){// jshint ignore:line

            var successAndCallback = function (tx, rs){

                if(callback){
                    callback();
                }
            };
            var errorAndCallback = function (tx,e){
                console.log("error");
                console.log(e.message);
                if(callback){
                    callback();
                }
            };
            db.transaction(function(tx) {

                tx.executeSql("INSERT INTO tiles(zoom_level, tile_column, tile_row, tile_data, mapName) VALUES (?,?,?,?,?)",
                              [z, x, y, tileData, mapName],
                              successAndCallback,
                              errorAndCallback
                             );

            });
        },

        getCachedTilePath: function(callback, scope, tile, url, externalStorageDir ){// jshint ignore:line

            var resultsCallback = function(tx, rs) {

                if(callback) {
                    if( rs.rows.length > 0 ) {
                        var rowOutput  = rs.rows.item(0);
                        var tileFileLocation = (externalStorageDir || '') + rowOutput.tile_data;// jshint ignore:line
                        callback.call(scope, tileFileLocation);

                    } else {
                        callback.call(scope, url);
                    }
                }

            };
            db.transaction(function(tx) {

                tx.executeSql("SELECT tile_data FROM tiles where zoom_level=? AND tile_column=? AND tile_row=?", [tile.z, tile.x, tile.y], resultsCallback,
                    onError);
            });

        }

    };

    if(typeof(openDatabase) !== 'undefined'){
        if(!db){
            db = webdb.open();
        }
    }

    return webdb;

});

<commit_msg>open db check incorrect location<commit_after>/*
Copyright (c) 2014, EDINA.
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this
   list of conditions and the following disclaimer in the documentation and/or
   other materials provided with the distribution.
3. All advertising materials mentioning features or use of this software must
   display the following acknowledgement: This product includes software
   developed by the EDINA.
4. Neither the name of the EDINA nor the names of its contributors may be used to
   endorse or promote products derived from this software without specific prior
   written permission.

THIS SOFTWARE IS PROVIDED BY EDINA ''AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL EDINA BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
*/

"use strict";

define(function(){

    var db;

    var DATABASE_CREATED = 'DATABASE_CREATED_FLAG';

    var onError = function(tx, e) {
        console.warn("There has been an error: " + e.message);
    };

    var onSuccess = function(tx, r) {
        localStorage.setItem(DATABASE_CREATED, "true");
    };

    var webdb = {
        open: function() {
            var dbSize = 10 * 1024 * 1024; // 10MB
            var databaseOpened;
            if(window.sqlitePlugin) {
                databaseOpened = window.sqlitePlugin.openDatabase("webDb", "1.0", "Cached Tiles", dbSize);
            } else {
                if(typeof(openDatabase) !== 'undefined'){
                    databaseOpened = openDatabase("webDbCache", "1.0", "Cached Tiles", dbSize);
                }
            }
            return databaseOpened;
        },

        createTablesIfRequired: function() {
                console.log("Creating DataBase Tables");

                db.transaction(function(tx) {
                    tx.executeSql("CREATE TABLE IF NOT EXISTS " +
                                  "tiles(zoom_level INTEGER, tile_column INTEGER, tile_row INTEGER, tile_data TEXT, mapName TEXT)", [], onSuccess,
                                  onError);

                    tx.executeSql("CREATE UNIQUE INDEX  IF NOT EXISTS " +
                                  " tile_index on tiles(zoom_level, tile_column, tile_row, mapName)", [], onSuccess,
                                  onError);

                });
        },

        deleteMap: function(mapName, callback){

            var success = function (tx, rs){

                if(callback){
                    callback(true);
                }
            };
            var error = function (tx,e){
                console.log("error DELETING MAP");
                console.log(e);
            };
            db.transaction(function(tx) {
                console.log("Delete mapname  " + mapName);
                tx.executeSql("DELETE FROM tiles WHERE mapName=?",
                              [ mapName],
                              success,
                              error
                             );

            });
        },

        insertCachedTilePath: function(x, y, z, tileData, mapName, callback){// jshint ignore:line

            var successAndCallback = function (tx, rs){

                if(callback){
                    callback();
                }
            };
            var errorAndCallback = function (tx,e){
                console.log("error");
                console.log(e.message);
                if(callback){
                    callback();
                }
            };
            db.transaction(function(tx) {

                tx.executeSql("INSERT INTO tiles(zoom_level, tile_column, tile_row, tile_data, mapName) VALUES (?,?,?,?,?)",
                              [z, x, y, tileData, mapName],
                              successAndCallback,
                              errorAndCallback
                             );

            });
        },

        getCachedTilePath: function(callback, scope, tile, url, externalStorageDir ){// jshint ignore:line

            var resultsCallback = function(tx, rs) {

                if(callback) {
                    if( rs.rows.length > 0 ) {
                        var rowOutput  = rs.rows.item(0);
                        var tileFileLocation = (externalStorageDir || '') + rowOutput.tile_data;// jshint ignore:line
                        callback.call(scope, tileFileLocation);

                    } else {
                        callback.call(scope, url);
                    }
                }

            };
            db.transaction(function(tx) {

                tx.executeSql("SELECT tile_data FROM tiles where zoom_level=? AND tile_column=? AND tile_row=?", [tile.z, tile.x, tile.y], resultsCallback,
                    onError);
            });

        }

    };

    if(!db){
        db = webdb.open();
    }

    return webdb;

});

<|endoftext|>


<commit_before>import styled from 'styled-components';
import StyledIcon from '../icon/icon.style';
import IconButton from '../icon-button';
import Icon from '../icon';
import { baseTheme } from '../../style/themes';

const StyledBadgeWrapper = styled.div`
  position: relative;
  width: fit-content;
`;

const StyledCounter = styled.div`
  font-weight: 700;
`;

const StyledIconButton = styled(IconButton)`
  padding: 0;
  width: 22px;
  height: 22px;
  border-radius: 50%;
  text-align: center;
  margin-top: -1px;
  margin-right: 0;
  position: absolute;
  top: -8px;
  right: -8px;
  background: ${({ theme }) => theme.colors.white};
  border: ${({ theme }) => `2px solid ${theme.colors.primary}`};
  color: ${({ theme }) => theme.colors.primary};

  &:hover, &:focus{
    background: ${({ theme }) => theme.colors.primary};

    ${StyledCounter}{
      display: none;
    }

    ${StyledIcon}{
      display: block;

      :before{
        margin-right: 3px;
        margin-top: 1px;
        font-size: 16px;
        color: ${({ theme }) => theme.colors.white};
      }
    }
  }
`;

const StyledCrossIcon = styled(Icon)`
  margin: 0;
  display: none;
  height: 21px;
  width: 21px;
`;

StyledIconButton.defaultProps = {
  theme: baseTheme
};

export {
  StyledBadgeWrapper,
  StyledIconButton,
  StyledCrossIcon,
  StyledCounter
};
<commit_msg>feat(badge): add new component<commit_after>import styled from 'styled-components';
import StyledIcon from '../icon/icon.style';
import IconButton from '../icon-button';
import Icon from '../icon';
import { baseTheme } from '../../style/themes';

const StyledBadgeWrapper = styled.div`
  position: relative;
  width: fit-content;
`;

const StyledCounter = styled.div`
  font-weight: 700;
  font-size: 12px;
  margin-top: -1px;
`;

const StyledIconButton = styled(IconButton)`
  padding: 0;
  width: 22px;
  height: 22px;
  border-radius: 50%;
  text-align: center;
  position: absolute;
  top: -8px;
  right: -8px;
  background: ${({ theme }) => theme.colors.white};
  border: ${({ theme }) => `2px solid ${theme.colors.primary}`};
  color: ${({ theme }) => theme.colors.primary};

  &:hover, &:focus{
    background: ${({ theme }) => theme.colors.primary};

    ${StyledCounter}{
      display: none;
    }

    ${StyledIcon}{
      display: block;

      :before{
        margin-right: 3px;
        margin-top: 1px;
        font-size: 16px;
        color: ${({ theme }) => theme.colors.white};
      }
    }
  }
`;

const StyledCrossIcon = styled(Icon)`
  margin: 0;
  display: none;
  height: 21px;
  width: 21px;
`;

StyledIconButton.defaultProps = {
  theme: baseTheme
};

export {
  StyledBadgeWrapper,
  StyledIconButton,
  StyledCrossIcon,
  StyledCounter
};
<|endoftext|>


<commit_before>// title      : thumb
// author     : Gino Tubaro
// license    : MIT License
// description: just a thumb
// file       : pulgar.jscad
//!OpenSCAD
//Hay que corregir los agujeros en el agulo

include('lodash.js');

include("node_modules/jscad-utils/jscad-utils.jscad");
include("node_modules/jscad-utils/jscad-utils-color.jscad");

include('node_modules/jscad-utils/jscad-utils-parts.jscad');
include('node_modules/jscad-utils/jscad-boxes.jscad');

function getParameterDefinitions() {
  return [
    { name: 'largodedos', type: 'float', initial: 5, caption: "x:" },
    { name: 'y', type: 'float', initial: 30, caption: "y:" },
    { name: 'z', type: 'float', initial: 8, caption: "z:" },
    { name: 'altopata', type: 'float', initial: 20, caption: "altopata" },
    { name: 'colors', type: 'choice', caption: "Colores", values:["red", "blue", "black"], captions:["Rojo", "Azul", "Negro"], initial: "Rojo" },
  ];
}
 var r = [], y = [], t = [];
 var result,xbo;
 var alto=20;
 var pinconector=2;
 var tornilloconector=3;
function main()
      {
        util.init(CSG);
        var thing = thingTwisted(10, 30);
        return thing;
      }

function conector() {

    var o = new Array();
    var g = new Array();
    var e = new Array();
    var largo=20;
    var last=1;
    var long=0;

  o.push(circle({r:10, center:true}).translate([10,0,0]));
  o.push(circle({r:10, center:true}).translate([-10,0,0]));
  o.push(square({size: [40,10], center: true}).translate([0, 5, 0]));

  g.push(linear_extrude({ height: 5 }, hull(o)).translate([0, 0, 0]));

var todo = union(
    Parts.Triangle(5, 50).translate([0, -1, -1]),
    Parts.Triangle(5, 50).translate([5, -1, -1]),
    cube({size: [5, 10, 50], center: [true, true, false]}).translate([2.5, -6, 0])
  );

  todo= union(g).subtract(todo.rotateX(-90).rotateZ(90).snap(union(g), 'x', 'inside-').translate([-1, -1, 0]));
  todo= todo.subtract(cylinder({r: 1, h: 20, center: true}).rotateX(-90).snap(todo, 'x', 'center-').translate([-1,0, 2]));

return todo;

}
function cuerpito(h) {
var o = new Array();
  o.push(circle({r:10, center:true}).translate([10,0,0]));
  o.push(circle({r:10, center:true}).translate([-10,0,0]));
  o.push(square({size: [40,10], center: true}).translate([0, 5, 0]));
  o.push(square({size:[40,40], center:true}).translate([0, 20, 0]))
o = linear_extrude({ height: h }, hull(o));

  return o.scale([0.8,0.8,2]);
}

function thingTwisted(radius, height) {

	var cag = CAG.fromPoints([
		[-radius, -radius, 0],
		[radius, -radius, 0],
		[radius, radius, 0]
	]).expand(1, CSG.defaultResolution2D);

	var flatBottom = CSG.Polygon.createFromPoints(
		cag.getOutlinePaths()[0].points
	);
 height=40;

  var thing = flatBottom.solidFromSlices({
	numslices: height
	,callback: function(t) {
		var coef = t;
    var o = new Array();
		if (coef < 0.01) coef = 0.01;//must not collapse polygon
		var h = height*t;
  //  var y = -4(coef*1)+(coef*2) Hay que hacer una parabola para limitar el comienzo y final dl pulgar

o.push(circle({r:10, center:true}).translate([10,0,0]));
o.push(circle({r:10, center:true}).translate([-10,0,0]));
if ((h>=3)&&(h<=50))o.push(circle({r:Math.sin(coef*3)*6, center:true}).translate([18,10,0]));
o.push(square({size: [40,10], center: true}).translate([0, 5, 0]));

cag =  hull(o); //.expand(1,CSG.defaultResolution2D)

var cage = CAG.circle({
            center: [0,0],
            radius: 3*Math.sin(coef*1.2),
            resolution: 32
       }).expand(1, CSG.defaultResolution2D);

    var cags = CAG.fromPoints([
			[-radius, -radius, h],
			[radius, -radius, h],
	 		[radius , radius, h],
			[-radius, radius, h]
		]).expand(1, CSG.defaultResolution2D);

		return CSG.Polygon.createFromPoints(
			cag.getOutlinePaths()[0].points
		).translate([0, 0, h]);
	}
  });
   return    difference(union(thing,conector().mirroredZ()),cuerpito(20));
}
<commit_msg>Agregado conectores, contornos y pulgar<commit_after>// title      : thumb
// author     : Gino Tubaro
// license    : MIT License
// description: just a thumb
// file       : pulgar.jscad
//!OpenSCAD
//Hay que corregir los agujeros en el agulo

include('lodash.js');

include("node_modules/jscad-utils/jscad-utils.jscad");
include("node_modules/jscad-utils/jscad-utils-color.jscad");

include('node_modules/jscad-utils/jscad-utils-parts.jscad');
include('node_modules/jscad-utils/jscad-boxes.jscad');

function getParameterDefinitions() {
  return [
    { name: 'largodedos', type: 'float', initial: 5, caption: "x:" },
    { name: 'y', type: 'float', initial: 30, caption: "y:" },
    { name: 'z', type: 'float', initial: 8, caption: "z:" },
    { name: 'altopata', type: 'float', initial: 20, caption: "altopata" },
    { name: 'colors', type: 'choice', caption: "Colores", values:["red", "blue", "black"], captions:["Rojo", "Azul", "Negro"], initial: "Rojo" },
  ];
}
 var r = [], y = [], t = [];
 var result,xbo;
 var alto=20;
 var pinconector=2;
 var tornilloconector=3;
function main()
      {
        util.init(CSG);
        var thing = thingTwisted(10, 30);
        return thing;
      }

function slider() {

    var o = new Array();
    var g = new Array();
    var e = new Array();
    var largo=20;
    var last=1;
    var long=0;

  o.push(circle({r:10, center:true}).translate([10,0,0]));
  o.push(circle({r:10, center:true}).translate([-10,0,0]));
  o.push(square({size: [40,10], center: true}).translate([0, 5, 0]));

  g.push(linear_extrude({ height: 5 }, hull(o)).translate([0, 0, 0]));

var todo = union(
    Parts.Triangle(5, 50).translate([0, -1, -1]),
    Parts.Triangle(5, 50).translate([5, -1, -1]),
    cube({size: [5, 10, 50], center: [true, true, false]}).translate([2.5, -6, 0])
  );

  todo= union(g).subtract(todo.rotateX(-90).rotateZ(90).snap(union(g), 'x', 'inside-').translate([-1, -1, 0]));
  todo= todo.subtract(cylinder({r: 1, h: 20, center: true}).rotateX(-90).snap(todo, 'x', 'center-').translate([-1,0, 2]));

return todo;

}
function conectores(alto) {
  var o = new Array();
  o.push(cube({size: [100, 2, alto/3], center: [true, true, true]}).translate([0, 2, alto/3]));
  o.push(cube({size: [100, 2, alto/3], center: [true, true, true]}).translate([0, -2, alto/3]));
  o.push(cylinder({r: 2.75, h: alto, center: [true, true, true]}).rotateX(90).rotateZ(90).translate([0, 5, alto-5]));

  return union(o);
}
function contornos(alto) {
  var o = new Array();
  o.push(cylinder({r: 10, h: alto, center: [true, true, true]}).rotateX(90).rotateZ(90).translate([0, -10, alto]));
  o.push(cylinder({r: 15, h: alto, center: [true, true, true]}).rotateX(90).translate([0, -10, alto-5]));
  return union(o);
}
function cuerpito(h) {
var o = new Array();
  o.push(circle({r:10, center:true}).translate([10,0,0]));
  o.push(circle({r:10, center:true}).translate([-10,0,0]));
  o.push(square({size: [40,10], center: true}).translate([0, 5, 0]));
  o.push(square({size:[40,40], center:true}).translate([0, 20, 0]))
o = linear_extrude({ height: h }, hull(o));

  return o.scale([0.8,0.8,2]);
}

function thingTwisted(radius, height) {

	var cag = CAG.fromPoints([
		[-radius, -radius, 0],
		[radius, -radius, 0],
		[radius, radius, 0]
	]).expand(1, CSG.defaultResolution2D);

	var flatBottom = CSG.Polygon.createFromPoints(
		cag.getOutlinePaths()[0].points
	);
 height=50;

  var thing = flatBottom.solidFromSlices({
	numslices: height
	,callback: function(t) {
		var coef = t;
    var o = new Array();
		if (coef < 0.01) coef = 0.01;//must not collapse polygon
		var h = height*t;
    var y = 0;
    //var e = 1/(Math.sqrt(1+(Math.pow(coef*0.01,3)))); //Hay que hacer una parabola para limitar el comienzo y final dl pulgar
    var b = 10+Math.sin(coef*3);
o.push(circle({r:b, center:true}).translate([10,0,0]));
o.push(circle({r:b, center:true}).translate([-10,0,0]));
if ((h>=height/6)&&(h<=(height*2/3))){
y=(h-height/6)*(h-(height*2/3))*0.6+2;
o.push(circle({r:y/10, center:true}).translate([17,9,0]));
};
o.push(square({size: [40,10], center: true}).translate([0, 5, 0]));

cag =  hull(o); //.expand(1,CSG.defaultResolution2D)

var cage = CAG.circle({
            center: [0,0],
            radius: 3*Math.sin(coef*1.2),
            resolution: 32
       }).expand(1, CSG.defaultResolution2D);

    var cags = CAG.fromPoints([
			[-radius, -radius, h],
			[radius, -radius, h],
	 		[radius , radius, h],
			[-radius, radius, h]
		]).expand(1, CSG.defaultResolution2D);

		return CSG.Polygon.createFromPoints(
			cag.getOutlinePaths()[0].points
		).translate([0, 0, h]);
	}
  });

  var palma=
  difference(
    union(thing,slider().mirroredZ()).fillet(3,'z+'),
    cuerpito(height),
    conectores(height),
    contornos(height)

  );

   return palma;
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
  Carousel as ReactstrapCarousel,
  CarouselItem,
  CarouselControl,
  CarouselIndicators
} from 'reactstrap';

class Carousel extends Component {
  constructor(props) {
    super(props);
    this.state = { activeIndex: 0 };
    this.next = this.next.bind(this);
    this.previous = this.previous.bind(this);
    this.goToIndex = this.goToIndex.bind(this);
    this.onExiting = this.onExiting.bind(this);
    this.onExited = this.onExited.bind(this);
  }

  onExiting() {
    this.animating = true;
  }

  onExited() {
    this.animating = false;
  }

  next(items) {
    if (this.animating) {
      return;
    }

    const nextIndex =
      this.state.activeIndex === items.length - 1
        ? 0
        : this.state.activeIndex + 1;
    this.setState({ activeIndex: nextIndex });
  }

  previous(items) {
    if (this.animating) {
      return;
    }

    const nextIndex =
      this.state.activeIndex === 0
        ? items.length - 1
        : this.state.activeIndex - 1;
    this.setState({ activeIndex: nextIndex });
  }

  goToIndex(newIndex) {
    if (this.animating) {
      return;
    }

    this.setState({ activeIndex: newIndex });
  }

  render() {
    const { activeIndex } = this.state;
    const { items } = this.props;

    const slides = items.map(item => {
      return (
        <CarouselItem
          onExiting={this.onExiting}
          onExited={this.onExited}
          key={item.src}
          src={item.src}
          altText={item.altText}
          cssModule={{ 'img-fluid': 'img-fluid ' + item.imageClassName }}
        >

{item.title}

{item.caption}

        </CarouselItem>
      );
    });

    return (
      <ReactstrapCarousel
        activeIndex={activeIndex}
        next={() => {
          this.next(items);
        }}
        previous={() => {
          this.previous(items);
        }}
        interval={false}
      >
        <CarouselIndicators
          items={items}
          activeIndex={activeIndex}
          onClickHandler={this.goToIndex}
        />
        {slides}
        <CarouselControl
          direction="prev"
          directionText="Previous"
          onClickHandler={() => {
            this.previous(items);
          }}
        />
        <CarouselControl
          direction="next"
          directionText="Next"
          onClickHandler={() => {
            this.next(items);
          }}
        />
      </ReactstrapCarousel>
    );
  }
}

Carousel.propTypes = {
  items: PropTypes.array.isRequired
};

export default Carousel;
<commit_msg>convert proptypes to static property, remove constructor, and move animating property to state<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
  Carousel as ReactstrapCarousel,
  CarouselItem,
  CarouselControl,
  CarouselIndicators
} from 'reactstrap';

class Carousel extends Component {
  static propTypes = {
    items: PropTypes.array.isRequired
  };

  state = {
    activeIndex: 0,
    animating: false
  };

  onExiting() {
    this.setState({ animating: true });
  }

  onExited() {
    this.setState({ animating: false });
  }

  next(items) {
    if (this.state.animating) {
      return;
    }

    const nextIndex =
      this.state.activeIndex === items.length - 1
        ? 0
        : this.state.activeIndex + 1;
    this.setState({ activeIndex: nextIndex });
  }

  previous(items) {
    if (this.state.animating) {
      return;
    }

    const nextIndex =
      this.state.activeIndex === 0
        ? items.length - 1
        : this.state.activeIndex - 1;
    this.setState({ activeIndex: nextIndex });
  }

  goToIndex(newIndex) {
    if (this.state.animating) {
      return;
    }

    this.setState({ activeIndex: newIndex });
  }

  render() {
    const { activeIndex } = this.state;
    const { items } = this.props;

    const slides = items.map(item => {
      return (
        <CarouselItem
          onExiting={() => this.onExiting}
          onExited={() => this.onExited}
          key={item.src}
          src={item.src}
          altText={item.altText}
          cssModule={{ 'img-fluid': 'img-fluid ' + item.imageClassName }}
        >

{item.title}

{item.caption}

        </CarouselItem>
      );
    });

    return (
      <ReactstrapCarousel
        activeIndex={activeIndex}
        next={() => {
          this.next(items);
        }}
        previous={() => {
          this.previous(items);
        }}
        interval={false}
      >
        <CarouselIndicators
          items={items}
          activeIndex={activeIndex}
          onClickHandler={this.goToIndex}
        />
        {slides}
        <CarouselControl
          direction="prev"
          directionText="Previous"
          onClickHandler={() => {
            this.previous(items);
          }}
        />
        <CarouselControl
          direction="next"
          directionText="Next"
          onClickHandler={() => {
            this.next(items);
          }}
        />
      </ReactstrapCarousel>
    );
  }
}

export default Carousel;
<|endoftext|>


<commit_before>import _ from 'lodash';
import Field from '../_classes/field/Field';

export default class CheckBoxComponent extends Field {
  static schema(...extend) {
    return Field.schema({
      type: 'checkbox',
      inputType: 'checkbox',
      label: 'Checkbox',
      key: 'checkbox',
      dataGridLabel: true,
      labelPosition: 'right',
      value: '',
      name: ''
    }, ...extend);
  }

  static get builderInfo() {
    return {
      title: 'Checkbox',
      group: 'basic',
      icon: 'check-square',
      documentation: 'http://help.form.io/userguide/#checkbox',
      weight: 50,
      schema: CheckBoxComponent.schema()
    };
  }

  get defaultSchema() {
    return CheckBoxComponent.schema();
  }

  get defaultValue() {
    return this.component.name ? '' : (this.component.defaultValue || false).toString() === 'true';
  }

  get labelClass() {
    let className = '';
    if (this.isInputComponent
      && !this.options.inputsOnly
      && this.component.validate
      && this.component.validate.required) {
      className += ' field-required';
    }
    return `${className}`;
  }

  get hasSetValue() {
    return this.hasValue();
  }

  get inputInfo() {
    const info = super.elementInfo();
    info.type = 'input';
    info.changeEvent = 'click';
    info.attr.type = this.component.inputType || 'checkbox';
    info.attr.class = 'form-check-input';
    if (this.component.name) {
      info.attr.name = `data[${this.component.name}]`;
    }
    info.attr.value = this.component.value ? this.component.value : 0;
    info.label = this.t(this.component.label);
    info.labelClass = this.labelClass;
    return info;
  }

  get labelInfo() {
    return {
      hidden: true
    };
  }

  render() {
    return super.render(this.renderTemplate('checkbox', {
      input: this.inputInfo,
      checked: this.dataValue,
      tooltip: this.interpolate(this.t(this.component.tooltip) || '').replace(/(?:\r\n|\r|\n)/g, '
')
    }));
  }

  attach(element) {
    this.loadRefs(element, { input: 'multiple' });
    this.input = this.refs.input[0];
    if (this.refs.input) {
      this.addEventListener(this.input, this.inputInfo.changeEvent, () => this.updateValue(null, {
        modified: true
      }));
      this.addShortcut(this.input);
    }
    return super.attach(element);
  }

  detach(element) {
    if (element && this.input) {
      this.removeShortcut(this.input);
    }
  }

  get emptyValue() {
    return false;
  }

  isEmpty(value = this.dataValue) {
    return super.isEmpty(value) || value === false;
  }

  /**
   *
   * @param value {*}
   * @returns {*}
   */
  set dataValue(value) {
    const setValue = (super.dataValue = value);
    if (
      !this.key ||
      (!this.visible && this.component.clearOnHide && !this.rootPristine)
    ) {
      return setValue;
    }
    if (this.component.name) {
      _.set(this._data, this.component.key, setValue === this.component.value);
    }
    return setValue;
  }

  get dataValue() {
    const getValue = super.dataValue;
    if (this.component.name) {
      _.set(this._data, this.component.key, getValue === this.component.value);
    }
    return getValue;
  }

  get key() {
    return this.component.name ? this.component.name : super.key;
  }

  getValueAt(index) {
    if (this.component.name) {
      return this.refs.input[index].checked ? this.component.value : '';
    }
    return !!this.refs.input[index].checked;
  }

  getValue() {
    const value = super.getValue();
    if (this.component.name) {
      return value ? this.setCheckedState(value) : this.setCheckedState(this.dataValue);
    }
    else {
      return (value === '') ? this.dataValue : !!value;
    }
  }

  setCheckedState(value) {
    if (!this.input) {
      return;
    }
    if (this.component.name) {
      this.input.value = (value === this.component.value) ? this.component.value : 0;
      this.input.checked = (value === this.component.value) ? 1 : 0;
    }
    else if (value === 'on') {
      this.input.value = 1;
      this.input.checked = 1;
    }
    else if (value === 'off') {
      this.input.value = 0;
      this.input.checked = 0;
    }
    else if (value) {
      this.input.value = 1;
      this.input.checked = 1;
    }
    else {
      this.input.value = 0;
      this.input.checked = 0;
    }
    if (this.input.checked) {
      this.input.setAttribute('checked', true);
    }
    else {
      this.input.removeAttribute('checked');
    }
    return value;
  }

  setValue(value, flags = {}) {
    if (
      this.setCheckedState(value) !== undefined ||
      (!this.input && value !== undefined && (this.visible || !this.component.clearOnHide))
    ) {
      return this.updateValue(value, flags);
    }
    return false;
  }

  getValueAsString(value) {
    return value ? 'Yes' : 'No';
  }
}
<commit_msg>Removed the erroneous requirement that if you have a checkbox configured as a radio, it should still add the checkbox value to the payload.<commit_after>import Field from '../_classes/field/Field';

export default class CheckBoxComponent extends Field {
  static schema(...extend) {
    return Field.schema({
      type: 'checkbox',
      inputType: 'checkbox',
      label: 'Checkbox',
      key: 'checkbox',
      dataGridLabel: true,
      labelPosition: 'right',
      value: '',
      name: ''
    }, ...extend);
  }

  static get builderInfo() {
    return {
      title: 'Checkbox',
      group: 'basic',
      icon: 'check-square',
      documentation: 'http://help.form.io/userguide/#checkbox',
      weight: 50,
      schema: CheckBoxComponent.schema()
    };
  }

  get defaultSchema() {
    return CheckBoxComponent.schema();
  }

  get defaultValue() {
    return this.component.name ? '' : (this.component.defaultValue || false).toString() === 'true';
  }

  get labelClass() {
    let className = '';
    if (this.isInputComponent
      && !this.options.inputsOnly
      && this.component.validate
      && this.component.validate.required) {
      className += ' field-required';
    }
    return `${className}`;
  }

  get hasSetValue() {
    return this.hasValue();
  }

  get inputInfo() {
    const info = super.elementInfo();
    info.type = 'input';
    info.changeEvent = 'click';
    info.attr.type = this.component.inputType || 'checkbox';
    info.attr.class = 'form-check-input';
    if (this.component.name) {
      info.attr.name = `data[${this.component.name}]`;
    }
    info.attr.value = this.component.value ? this.component.value : 0;
    info.label = this.t(this.component.label);
    info.labelClass = this.labelClass;
    return info;
  }

  get labelInfo() {
    return {
      hidden: true
    };
  }

  render() {
    return super.render(this.renderTemplate('checkbox', {
      input: this.inputInfo,
      checked: this.dataValue,
      tooltip: this.interpolate(this.t(this.component.tooltip) || '').replace(/(?:\r\n|\r|\n)/g, '
')
    }));
  }

  attach(element) {
    this.loadRefs(element, { input: 'multiple' });
    this.input = this.refs.input[0];
    if (this.refs.input) {
      this.addEventListener(this.input, this.inputInfo.changeEvent, () => this.updateValue(null, {
        modified: true
      }));
      this.addShortcut(this.input);
    }
    return super.attach(element);
  }

  detach(element) {
    if (element && this.input) {
      this.removeShortcut(this.input);
    }
  }

  get emptyValue() {
    return false;
  }

  isEmpty(value = this.dataValue) {
    return super.isEmpty(value) || value === false;
  }

  get key() {
    return this.component.name ? this.component.name : super.key;
  }

  getValueAt(index) {
    if (this.component.name) {
      return this.refs.input[index].checked ? this.component.value : '';
    }
    return !!this.refs.input[index].checked;
  }

  getValue() {
    const value = super.getValue();
    if (this.component.name) {
      return value ? this.setCheckedState(value) : this.setCheckedState(this.dataValue);
    }
    else {
      return (value === '') ? this.dataValue : !!value;
    }
  }

  setCheckedState(value) {
    if (!this.input) {
      return;
    }
    if (this.component.name) {
      this.input.value = (value === this.component.value) ? this.component.value : 0;
      this.input.checked = (value === this.component.value) ? 1 : 0;
    }
    else if (value === 'on') {
      this.input.value = 1;
      this.input.checked = 1;
    }
    else if (value === 'off') {
      this.input.value = 0;
      this.input.checked = 0;
    }
    else if (value) {
      this.input.value = 1;
      this.input.checked = 1;
    }
    else {
      this.input.value = 0;
      this.input.checked = 0;
    }
    if (this.input.checked) {
      this.input.setAttribute('checked', true);
    }
    else {
      this.input.removeAttribute('checked');
    }
    return value;
  }

  setValue(value, flags = {}) {
    if (
      this.setCheckedState(value) !== undefined ||
      (!this.input && value !== undefined && (this.visible || !this.component.clearOnHide))
    ) {
      return this.updateValue(value, flags);
    }
    return false;
  }

  getValueAsString(value) {
    return value ? 'Yes' : 'No';
  }
}
<|endoftext|>


<commit_before>import React from 'react';

import Promise from 'promise';
import Diff from './Diff';

class DiffPanel extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      diffsArr: [],
      checked: [],
    };
  }

  formatDiffs = (props) => {

    const LINESTATUS = {
      UNMODIFIED: 32,
      ADDED: 43,
      DELETED: 45,
    };

    if(props.diffs) {

      let diffsArr = [];
      let checked = [];
      let patches;

      let promises1 = [];
      props.diffs.forEach( (diff, index) => {
          // push all promises to get the patches from every diff
          promises1.push( diff.patches().then((retPatches) => {
            patches = retPatches;
          }) );
        });

      // perform operation on those patches after you get them
      return Promise.all(promises1)
      .then( () => {
        if(patches) {

          let promises2 = [];
          patches.forEach( (patch, fileIndex) => {

            // this array stores the Git line objects, header and file path
            // of a single diff
            let diffs = [];
            let checklets = [];

            // obtain promises for all the hunks belonging to a single
            // patch. Each patch corresponds to a single file
            promises2.push( patch.hunks().then( (hunks) => {

              let promises3 = [];
              hunks.forEach( (hunk, hunkIndex) => {

                // obtain promises for getting the lines from each hunk
                promises3.push(
                  hunk.lines().then( (lines) => {

                    // this makes it easier to stage hunks
                    diffs.push({
                      header: hunk.header(),
                      lines: lines,
                      path: patch.oldFile().path()
                    });

                    checklets.push(lines.map((line) => {return false;}));
                  }) );
              });

              // return promises for inserting the lines into diffLines
              return Promise.all(promises3);
            })
            .then( () => {
              checked.push(checklets);
              diffsArr.push({
                diffs: diffs,
                // diff already contains a path, but we need the old path as well as
                // the new one
                path: {
                  old: patch.oldFile().path(),
                  new: patch.newFile().path()
                }
              });
            }));
          });

          // return promises for inserting ALL the diffLines belonging to ALL the patches
          return Promise.all(promises2);
        }
      })
      .done( () => {

        /***
         * diffsArr: Array of diffFiles
         * diffFile: All the hunks from one single file
         *  |
         *  |-diffs: Array of diffs of ONE file
         *  |  diff: data of ONE hunk
         *  |   |
         *  |   |- header: string of header
         *  |   |- lines: array of Git line objects
         *  |   |- path: path of hunk
         *  |
         *  |-path: contains path of new and old file
         ***/

        this.setState({
          diffsArr: diffsArr,
          checked: checked
        });
      });
    }
  }

  callbackLine = (isChecked, fileIndex, diffIndex, lineIndex) => {
    this.setState((prevState) => {
      prevState.checked[fileIndex][diffIndex][lineIndex] = isChecked;
      return {
        checked: prevState.checked
      };
    })
  }

  callbackHunk = (isChecked, fileIndex, diffIndex) => {
    this.setState( (prevState) => {
      let checked = prevState.checked;
      checked[fileIndex][diffIndex].forEach( (line, lineIndex) => {
        checked[fileIndex][diffIndex][lineIndex] = isChecked;
      });
      return {
        checked: checked
      };
    })
  }

  componentDidMount = () => {
    this.formatDiffs(this.props);
  }

  componentWillReceiveProps = (newprops) => {
    this.formatDiffs(newprops);
  }

  render = () => {

    let diffTree = [];
    let diffSelect = [];

    this.state.diffsArr.forEach((diffFile, fileIndex) => {
      let { diffs, path } = diffFile;

      let formattedLines = [];

      diffs.forEach( (diff, diffIndex) => {
        let { header, lines, path } = diff;

        formattedLines.push(header);
        lines.forEach( (line) => {
            formattedLines.push(String.fromCharCode(line.origin())+line.content());
        });
      });

      // collecting all the header and lines of the hunks in a single file
      // and putting them in a diffDisplay object
      let diffDisplay = {
        lines:formattedLines,
        path: 'old:'+path.old+' new:'+path.new,
      };
      diffTree.push(<Diff diff={diffDisplay} key={fileIndex} />);

      // creating a column of checboxes to select individual lines/hunks
      diffSelect.push(

      // each div contains all the checkboxes of a single file

        {diffs.map( (diff, diffIndex) => {
          let { header, lines, path } = diff;

          const styles = {
            checkbox: {
              height: 13,
              padding: 0,
              margin: 0,
              marginTop: 1,
              marginBottom: 1,
            }
          };
          // the header calls the callback with an array containing all the difflines
          // and the line calls the callback with its corresponding diffline
          return (

            <input type='checkbox' style={styles.checkbox}
            onChange={(e) => {this.callbackHunk(e.target.checked,fileIndex, diffIndex);}} />
            {lines.map( (line, lineIndex) => {
              return <input type='checkbox' style={styles.checkbox}
              key={lineIndex}
              checked={this.state.checked[fileIndex][diffIndex][lineIndex]}
              onChange={(e) => {this.callbackLine(e.target.checked, fileIndex, diffIndex, lineIndex);}} />;
            })}

          );

        })}

      );

    });

    const styles = {
      main: {
        display: 'flex',
        width: '100%',
      },
      diffTree: {
        width: '100%',
        border: '1px solid black',
      }
    };
    return(

        {this.props.showSelect?

{diffSelect}
:
        null}

{diffTree}

    );
  }
}

export default DiffPanel;<commit_msg>Core: Added check to remove last line added by nodegit when no new line at EOF<commit_after>import React from 'react';

import Promise from 'promise';
import Diff from './Diff';

class DiffPanel extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      diffsArr: [],
      checked: [],
    };
  }

  formatDiffs = (props) => {

    const LINESTATUS = {
      UNMODIFIED: 32,
      ADDED: 43,
      DELETED: 45,
    };

    if(props.diffs) {

      let diffsArr = [];
      let checked = [];
      let patches;

      let promises1 = [];
      props.diffs.forEach( (diff, index) => {
          // push all promises to get the patches from every diff
          promises1.push( diff.patches().then((retPatches) => {
            patches = retPatches;
          }) );
        });

      // perform operation on those patches after you get them
      return Promise.all(promises1)
      .then( () => {
        if(patches) {

          let promises2 = [];
          patches.forEach( (patch, fileIndex) => {

            // this array stores the Git line objects, header and file path
            // of a single diff
            let diffs = [];
            let checklets = [];

            // obtain promises for all the hunks belonging to a single
            // patch. Each patch corresponds to a single file
            promises2.push( patch.hunks().then( (hunks) => {

              let promises3 = [];
              hunks.forEach( (hunk, hunkIndex) => {

                // obtain promises for getting the lines from each hunk
                promises3.push(
                  hunk.lines().then( (lines) => {

                    // we don't want the last line if there was no newline in the org file
                    if(lines[lines.length - 1].content().match(/\ No newline at end of file/))
                      lines.pop();

                    // this makes it easier to stage hunks
                    diffs.push({
                      header: hunk.header(),
                      lines: lines,
                      path: patch.oldFile().path()
                    });

                    checklets.push(lines.map((line) => {return false;}));
                  }) );
              });

              // return promises for inserting the lines into diffLines
              return Promise.all(promises3);
            })
            .then( () => {
              checked.push(checklets);
              diffsArr.push({
                diffs: diffs,
                // diff already contains a path, but we need the old path as well as
                // the new one
                path: {
                  old: patch.oldFile().path(),
                  new: patch.newFile().path()
                }
              });
            }));
          });

          // return promises for inserting ALL the diffLines belonging to ALL the patches
          return Promise.all(promises2);
        }
      })
      .done( () => {

        /***
         * diffsArr: Array of diffFiles
         * diffFile: All the hunks from one single file
         *  |
         *  |-diffs: Array of diffs of ONE file
         *  |  diff: data of ONE hunk
         *  |   |
         *  |   |- header: string of header
         *  |   |- lines: array of Git line objects
         *  |   |- path: path of hunk
         *  |
         *  |-path: contains path of new and old file
         ***/

        this.setState({
          diffsArr: diffsArr,
          checked: checked
        });
      });
    }
  }

  callbackLine = (isChecked, fileIndex, diffIndex, lineIndex) => {
    this.setState((prevState) => {
      prevState.checked[fileIndex][diffIndex][lineIndex] = isChecked;
      return {
        checked: prevState.checked
      };
    })
  }

  callbackHunk = (isChecked, fileIndex, diffIndex) => {
    this.setState( (prevState) => {
      let checked = prevState.checked;
      checked[fileIndex][diffIndex].forEach( (line, lineIndex) => {
        checked[fileIndex][diffIndex][lineIndex] = isChecked;
      });
      return {
        checked: checked
      };
    })
  }

  componentDidMount = () => {
    this.formatDiffs(this.props);
  }

  componentWillReceiveProps = (newprops) => {
    this.formatDiffs(newprops);
  }

  render = () => {

    let diffTree = [];
    let diffSelect = [];

    this.state.diffsArr.forEach((diffFile, fileIndex) => {
      let { diffs, path } = diffFile;

      let formattedLines = [];

      diffs.forEach( (diff, diffIndex) => {
        let { header, lines, path } = diff;

        formattedLines.push(header);
        lines.forEach( (line) => {
            formattedLines.push(String.fromCharCode(line.origin())+line.content());
        });
      });

      // collecting all the header and lines of the hunks in a single file
      // and putting them in a diffDisplay object
      let diffDisplay = {
        lines:formattedLines,
        path: 'old:'+path.old+' new:'+path.new,
      };
      diffTree.push(<Diff diff={diffDisplay} key={fileIndex} />);

      // creating a column of checboxes to select individual lines/hunks
      diffSelect.push(

      // each div contains all the checkboxes of a single file

        {diffs.map( (diff, diffIndex) => {
          let { header, lines, path } = diff;

          const styles = {
            checkbox: {
              height: 13,
              padding: 0,
              margin: 0,
              marginTop: 1,
              marginBottom: 1,
            }
          };
          // the header calls the callback with an array containing all the difflines
          // and the line calls the callback with its corresponding diffline
          return (

            <input type='checkbox' style={styles.checkbox}
            onChange={(e) => {this.callbackHunk(e.target.checked,fileIndex, diffIndex);}} />
            {lines.map( (line, lineIndex) => {
              return <input type='checkbox' style={styles.checkbox}
              key={lineIndex}
              checked={this.state.checked[fileIndex][diffIndex][lineIndex]}
              onChange={(e) => {this.callbackLine(e.target.checked, fileIndex, diffIndex, lineIndex);}} />;
            })}

          );

        })}

      );

    });

    const styles = {
      main: {
        display: 'flex',
        width: '100%',
      },
      diffTree: {
        width: '100%',
        border: '1px solid black',
      }
    };
    return(

        {this.props.showSelect?

{diffSelect}
:
        null}

{diffTree}

    );
  }
}

export default DiffPanel;<|endoftext|>


<commit_before>const path = require('path')
const {ifDevDep} = require('../utils')

const here = p => path.join(__dirname, p)

const ignores = [
  '/node_modules/',
  '/fixtures/',
  '/__tests__/helpers/',
  '__mocks__',
]

module.exports = {
  testEnvironment: ifDevDep(['webpack', 'rollup'], 'jsdom', 'node'),
  collectCoverageFrom: ['src/**/*.js'],
  testMatch: ['**/__tests__/**/*.js'],
  testPathIgnorePatterns: ignores,
  coveragePathIgnorePatterns: ignores,
  transform: {
    '^.+\\.js$': here('./babel-transform'),
  },
  transformIgnorePatterns: ['[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$'],
  coverageThreshold: {
    global: {
      branches: 100,
      functions: 100,
      lines: 100,
      statements: 100,
    },
  },
}
<commit_msg>fix(jest): use jsdom with react and any dep<commit_after>const path = require('path')
const {ifAnyDep} = require('../utils')

const here = p => path.join(__dirname, p)

const ignores = [
  '/node_modules/',
  '/fixtures/',
  '/__tests__/helpers/',
  '__mocks__',
]

module.exports = {
  testEnvironment: ifAnyDep(['webpack', 'rollup', 'react'], 'jsdom', 'node'),
  collectCoverageFrom: ['src/**/*.js'],
  testMatch: ['**/__tests__/**/*.js'],
  testPathIgnorePatterns: ignores,
  coveragePathIgnorePatterns: ignores,
  transform: {
    '^.+\\.js$': here('./babel-transform'),
  },
  transformIgnorePatterns: ['[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$'],
  coverageThreshold: {
    global: {
      branches: 100,
      functions: 100,
      lines: 100,
      statements: 100,
    },
  },
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $, window */

define(function (require, exports, module) {
    'use strict';

    var SCROLL_SHADOW_HEIGHT = 5;

    /**
     * @private
     */
    var _resizeHandlers = [];

    /**
     * Positions shadow background elements to indicate vertical scrolling.
     * @param {!DOMElement} $displayElement the DOMElement that displays the shadow
     * @param {!Object} $scrollElement the object that is scrolled
     * @param {!DOMElement} $shadowTop div .scroller-shadow.top
     * @param {!DOMElement} $shadowBottom div .scroller-shadow.bottom
     * @param {boolean} isPositionFixed When using absolute position, top remains at 0.
     */
    function _updateScrollerShadow($displayElement, $scrollElement, $shadowTop, $shadowBottom, isPositionFixed) {
        var offsetTop           = 0,
            scrollElement       = $scrollElement.get(0),
            scrollTop           = scrollElement.scrollTop,
            topShadowOffset     = Math.min(scrollTop - SCROLL_SHADOW_HEIGHT, 0),
            displayElementWidth = $displayElement.width();

        if ($shadowTop) {
            $shadowTop.css("background-position", "0px " + topShadowOffset + "px");

            if (isPositionFixed) {
                offsetTop = $displayElement.offset().top;
                $shadowTop.css("top", offsetTop);
            }

            if (isPositionFixed) {
                $shadowTop.css("width", displayElementWidth);
            }
        }

        if ($shadowBottom) {
            var clientHeight        = scrollElement.clientHeight,
                outerHeight         = $displayElement.outerHeight(),
                scrollHeight        = scrollElement.scrollHeight,
                bottomOffset        = outerHeight - clientHeight,
                bottomShadowOffset  = SCROLL_SHADOW_HEIGHT; // outside of shadow div viewport

            if (scrollHeight > clientHeight) {
                bottomShadowOffset -= Math.min(SCROLL_SHADOW_HEIGHT, (scrollHeight - (scrollTop + clientHeight)));
            }

            $shadowBottom.css("background-position", "0px " + bottomShadowOffset + "px");
            $shadowBottom.css("top", offsetTop + outerHeight - SCROLL_SHADOW_HEIGHT);
            $shadowBottom.css("width", displayElementWidth);
        }
    }

    function getOrCreateShadow($displayElement, position, isPositionFixed) {
        var $findShadow = $displayElement.find(".scroller-shadow." + position);

        if ($findShadow.length === 0) {
            $findShadow = $(window.document.createElement("div")).addClass("scroller-shadow " + position);
            $displayElement.append($findShadow);
        }

        if (!isPositionFixed) {
            // position is fixed by default
            $findShadow.css("position", "absolute");
            $findShadow.css(position, "0");
        }

        return $findShadow;
    }

    /**
     * Installs event handlers for updatng shadow background elements to indicate vertical scrolling.
     * @param {!DOMElement} displayElement the DOMElement that displays the shadow. Must fire
     *  "contentChanged" events when the element is resized or repositioned.
     * @param {?Object} scrollElement the object that is scrolled. Must fire "scroll" events
     *  when the element is scrolled. If null, the displayElement is used.
     * @param {?boolean} showBottom optionally show the bottom shadow
     */
    function addScrollerShadow(displayElement, scrollElement, showBottom) {
        // use fixed positioning when the display and scroll elements are the same
        var isPositionFixed = false;

        if (!scrollElement) {
            scrollElement = displayElement;
            isPositionFixed = true;
        }

        // update shadows when the scrolling element is scrolled
        var $displayElement = $(displayElement),
            $scrollElement = $(scrollElement);

        var $shadowTop = getOrCreateShadow($displayElement, "top", isPositionFixed);
        var $shadowBottom = (showBottom) ? getOrCreateShadow($displayElement, "bottom", isPositionFixed) : null;

        var doUpdate = function () {
            _updateScrollerShadow($displayElement, $scrollElement, $shadowTop, $shadowBottom, isPositionFixed);
        };

        $scrollElement.on("scroll.scroller-shadow", doUpdate);
        $displayElement.on("contentChanged.scroller-shadow", doUpdate);

        // update immediately
        doUpdate();
    }

    /**
     * Remove scroller-shadow effect.
     * @param {!DOMElement} displayElement the DOMElement that displays the shadow
     * @param {?Object} scrollElement the object that is scrolled
     */
    function removeScrollerShadow(displayElement, scrollElement) {
        if (!scrollElement) {
            scrollElement = displayElement;
        }

        var $displayElement = $(displayElement),
            $scrollElement = $(scrollElement);

        // remove scrollerShadow elements from DOM
        $displayElement.find(".scrollerShadow.top").remove();
        $displayElement.find(".scrollerShadow.bottom").remove();

        // remove event handlers
        $scrollElement.off("scroll.scrollerShadow");
        $displayElement.off("contentChanged.scrollerShadow");
        $(displayElement).triggerHandler("remove-scroller-shadow");
    }

    /**
     * Within a scrolling DOMElement, creates and positions a styled selection
     * div to align a single selected list item from a ul list element.
     *
     * Assumptions:
     * - scrollElement is a child of the #file-section div
     * - ul list element fires a "selectionChanged" event after the
     *   selectedClassName is assigned to a new list item
     *
     * @param {!DOMElement} scrollElement A DOMElement containing a ul list element
     * @param {!string} selectedClassName A CSS class name on at most one list item in the contained list
     */
    function sidebarList($scrollerElement, selectedClassName, leafClassName) {
        var $listElement = $scrollerElement.find("ul"),
            $selectionMarker,
            $selectionTriangle,
            $sidebar = $("#sidebar"),
            showTriangle = true;

        // build selectionMarker and position absolute within the scroller
        $selectionMarker = $(window.document.createElement("div")).addClass("sidebar-selection");
        $scrollerElement.prepend($selectionMarker);

        // enable scrolling
        $scrollerElement.css("overflow", "auto");

        // use relative postioning for clipping the selectionMarker within the scrollElement
        $scrollerElement.css("position", "relative");

        // build selectionTriangle and position fixed to the window
        $selectionTriangle = $(window.document.createElement("div")).addClass("sidebar-selection-triangle");

        $scrollerElement.append($selectionTriangle);

        selectedClassName = "." + (selectedClassName || "selected");

        var updateSelectionTriangle = function () {
            var selectionMarkerHeight = $selectionMarker.height(),
                selectionMarkerOffset = $selectionMarker.offset(),
                scrollerOffset = $scrollerElement.offset(),
                triangleHeight = $selectionTriangle.outerHeight(),
                scrollerTop = scrollerOffset.top,
                scrollerBottom = scrollerTop + $scrollerElement.outerHeight(),
                scrollerLeft = scrollerOffset.left,
                triangleTop = selectionMarkerOffset.top;

            $selectionTriangle.css("top", triangleTop);
            $selectionTriangle.css("left", $sidebar.width() - $selectionTriangle.outerWidth());
            $selectionTriangle.toggleClass("triangle-visible", showTriangle);

            var triangleClipOffsetYBy = Math.floor((selectionMarkerHeight - triangleHeight) / 2),
                triangleBottom = triangleTop + triangleHeight + triangleClipOffsetYBy;

            if (triangleTop < scrollerTop || triangleBottom > scrollerBottom) {
                $selectionTriangle.css("clip", "rect(" + Math.max(scrollerTop - triangleTop - triangleClipOffsetYBy, 0) + "px, auto, " +
                                           (triangleHeight - Math.max(triangleBottom - scrollerBottom, 0)) + "px, auto)");
            } else {
                $selectionTriangle.css("clip", "");
            }
        };

        var updateSelectionMarker = function (event, reveal) {
            // find the selected list item
            var $listItem = $listElement.find(selectedClassName).closest("li");

            if (leafClassName) {
                showTriangle = $listItem.hasClass(leafClassName);
            }

            // always hide selection visuals first to force layout (issue #719)
            $selectionTriangle.hide();
            $selectionMarker.hide();

            if ($listItem.length === 1) {
                // list item position is relative to scroller
                var selectionMarkerTop = $listItem.offset().top - $scrollerElement.offset().top + $scrollerElement.get(0).scrollTop;

                // force selection width to match scroller
                $selectionMarker.width($scrollerElement.get(0).scrollWidth);

                // move the selectionMarker position to align with the list item
                $selectionMarker.css("top", selectionMarkerTop);
                $selectionMarker.show();

                updateSelectionTriangle();
                $selectionTriangle.show();

                // fully scroll to the selectionMarker if it's not initially in the viewport
                var scrollerElement = $scrollerElement.get(0),
                    scrollerHeight = scrollerElement.clientHeight,
                    selectionMarkerHeight = $selectionMarker.height(),
                    selectionMarkerBottom = selectionMarkerTop + selectionMarkerHeight,
                    currentScrollBottom = scrollerElement.scrollTop + scrollerHeight;

                // update scrollTop to reveal the selected list item
                if (reveal) {
                    if (selectionMarkerTop >= currentScrollBottom) {
                        $listItem.get(0).scrollIntoView(false);
                    } else if (selectionMarkerBottom <= scrollerElement.scrollTop) {
                        $listItem.get(0).scrollIntoView(true);
                    }
                }
            }
        };

        $listElement.on("selectionChanged", updateSelectionMarker);
        $scrollerElement.on("scroll", updateSelectionTriangle);

        // update immediately
        updateSelectionMarker();

        // update clipping when the window resizes
        _resizeHandlers.push(updateSelectionTriangle);
    }

    /**
     * @private
     */
    function _handleResize() {
        _resizeHandlers.forEach(function (f) {
            f.apply();
        });
    }

    // handle all resize handlers in a single listener
    $(window).resize(_handleResize);

    // Define public API
    exports.SCROLL_SHADOW_HEIGHT = SCROLL_SHADOW_HEIGHT;
    exports.addScrollerShadow = addScrollerShadow;
    exports.removeScrollerShadow = removeScrollerShadow;
    exports.sidebarList = sidebarList;
});
<commit_msg>fix merge issues<commit_after>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $, window */

define(function (require, exports, module) {
    'use strict';

    var SCROLL_SHADOW_HEIGHT = 5;

    /**
     * @private
     */
    var _resizeHandlers = [];

    /**
     * Positions shadow background elements to indicate vertical scrolling.
     * @param {!DOMElement} $displayElement the DOMElement that displays the shadow
     * @param {!Object} $scrollElement the object that is scrolled
     * @param {!DOMElement} $shadowTop div .scroller-shadow.top
     * @param {!DOMElement} $shadowBottom div .scroller-shadow.bottom
     * @param {boolean} isPositionFixed When using absolute position, top remains at 0.
     */
    function _updateScrollerShadow($displayElement, $scrollElement, $shadowTop, $shadowBottom, isPositionFixed) {
        var offsetTop           = 0,
            scrollElement       = $scrollElement.get(0),
            scrollTop           = scrollElement.scrollTop,
            topShadowOffset     = Math.min(scrollTop - SCROLL_SHADOW_HEIGHT, 0),
            displayElementWidth = $displayElement.width();

        if ($shadowTop) {
            $shadowTop.css("background-position", "0px " + topShadowOffset + "px");

            if (isPositionFixed) {
                offsetTop = $displayElement.offset().top;
                $shadowTop.css("top", offsetTop);
            }

            if (isPositionFixed) {
                $shadowTop.css("width", displayElementWidth);
            }
        }

        if ($shadowBottom) {
            var clientHeight        = scrollElement.clientHeight,
                outerHeight         = $displayElement.outerHeight(),
                scrollHeight        = scrollElement.scrollHeight,
                bottomOffset        = outerHeight - clientHeight,
                bottomShadowOffset  = SCROLL_SHADOW_HEIGHT; // outside of shadow div viewport

            if (scrollHeight > clientHeight) {
                bottomShadowOffset -= Math.min(SCROLL_SHADOW_HEIGHT, (scrollHeight - (scrollTop + clientHeight)));
            }

            $shadowBottom.css("background-position", "0px " + bottomShadowOffset + "px");
            $shadowBottom.css("top", offsetTop + outerHeight - SCROLL_SHADOW_HEIGHT);
            $shadowBottom.css("width", displayElementWidth);
        }
    }

    function getOrCreateShadow($displayElement, position, isPositionFixed) {
        var $findShadow = $displayElement.find(".scroller-shadow." + position);

        if ($findShadow.length === 0) {
            $findShadow = $(window.document.createElement("div")).addClass("scroller-shadow " + position);
            $displayElement.append($findShadow);
        }

        if (!isPositionFixed) {
            // position is fixed by default
            $findShadow.css("position", "absolute");
            $findShadow.css(position, "0");
        }

        return $findShadow;
    }

    /**
     * Installs event handlers for updatng shadow background elements to indicate vertical scrolling.
     * @param {!DOMElement} displayElement the DOMElement that displays the shadow. Must fire
     *  "contentChanged" events when the element is resized or repositioned.
     * @param {?Object} scrollElement the object that is scrolled. Must fire "scroll" events
     *  when the element is scrolled. If null, the displayElement is used.
     * @param {?boolean} showBottom optionally show the bottom shadow
     */
    function addScrollerShadow(displayElement, scrollElement, showBottom) {
        // use fixed positioning when the display and scroll elements are the same
        var isPositionFixed = false;

        if (!scrollElement) {
            scrollElement = displayElement;
            isPositionFixed = true;
        }

        // update shadows when the scrolling element is scrolled
        var $displayElement = $(displayElement),
            $scrollElement = $(scrollElement);

        var $shadowTop = getOrCreateShadow($displayElement, "top", isPositionFixed);
        var $shadowBottom = (showBottom) ? getOrCreateShadow($displayElement, "bottom", isPositionFixed) : null;

        var doUpdate = function () {
            _updateScrollerShadow($displayElement, $scrollElement, $shadowTop, $shadowBottom, isPositionFixed);
        };

        $scrollElement.on("scroll.scroller-shadow", doUpdate);
        $displayElement.on("contentChanged.scroller-shadow", doUpdate);

        // update immediately
        doUpdate();
    }

    /**
     * Remove scroller-shadow effect.
     * @param {!DOMElement} displayElement the DOMElement that displays the shadow
     * @param {?Object} scrollElement the object that is scrolled
     */
    function removeScrollerShadow(displayElement, scrollElement) {
        if (!scrollElement) {
            scrollElement = displayElement;
        }

        var $displayElement = $(displayElement),
            $scrollElement = $(scrollElement);

        // remove scrollerShadow elements from DOM
        $displayElement.find(".scroller-shadow.top").remove();
        $displayElement.find(".scroller-shadow.bottom").remove();

        // remove event handlers
        $scrollElement.off("scroll.scroller-shadow");
        $displayElement.off("contentChanged.scroller-shadow");
    }

    /**
     * Within a scrolling DOMElement, creates and positions a styled selection
     * div to align a single selected list item from a ul list element.
     *
     * Assumptions:
     * - scrollElement is a child of the #file-section div
     * - ul list element fires a "selectionChanged" event after the
     *   selectedClassName is assigned to a new list item
     *
     * @param {!DOMElement} scrollElement A DOMElement containing a ul list element
     * @param {!string} selectedClassName A CSS class name on at most one list item in the contained list
     */
    function sidebarList($scrollerElement, selectedClassName, leafClassName) {
        var $listElement = $scrollerElement.find("ul"),
            $selectionMarker,
            $selectionTriangle,
            $sidebar = $("#sidebar"),
            showTriangle = true;

        // build selectionMarker and position absolute within the scroller
        $selectionMarker = $(window.document.createElement("div")).addClass("sidebar-selection");
        $scrollerElement.prepend($selectionMarker);

        // enable scrolling
        $scrollerElement.css("overflow", "auto");

        // use relative postioning for clipping the selectionMarker within the scrollElement
        $scrollerElement.css("position", "relative");

        // build selectionTriangle and position fixed to the window
        $selectionTriangle = $(window.document.createElement("div")).addClass("sidebar-selection-triangle");

        $scrollerElement.append($selectionTriangle);

        selectedClassName = "." + (selectedClassName || "selected");

        var updateSelectionTriangle = function () {
            var selectionMarkerHeight = $selectionMarker.height(),
                selectionMarkerOffset = $selectionMarker.offset(),
                scrollerOffset = $scrollerElement.offset(),
                triangleHeight = $selectionTriangle.outerHeight(),
                scrollerTop = scrollerOffset.top,
                scrollerBottom = scrollerTop + $scrollerElement.outerHeight(),
                scrollerLeft = scrollerOffset.left,
                triangleTop = selectionMarkerOffset.top;

            $selectionTriangle.css("top", triangleTop);
            $selectionTriangle.css("left", $sidebar.width() - $selectionTriangle.outerWidth());
            $selectionTriangle.toggleClass("triangle-visible", showTriangle);

            var triangleClipOffsetYBy = Math.floor((selectionMarkerHeight - triangleHeight) / 2),
                triangleBottom = triangleTop + triangleHeight + triangleClipOffsetYBy;

            if (triangleTop < scrollerTop || triangleBottom > scrollerBottom) {
                $selectionTriangle.css("clip", "rect(" + Math.max(scrollerTop - triangleTop - triangleClipOffsetYBy, 0) + "px, auto, " +
                                           (triangleHeight - Math.max(triangleBottom - scrollerBottom, 0)) + "px, auto)");
            } else {
                $selectionTriangle.css("clip", "");
            }
        };

        var updateSelectionMarker = function (event, reveal) {
            // find the selected list item
            var $listItem = $listElement.find(selectedClassName).closest("li");

            if (leafClassName) {
                showTriangle = $listItem.hasClass(leafClassName);
            }

            // always hide selection visuals first to force layout (issue #719)
            $selectionTriangle.hide();
            $selectionMarker.hide();

            if ($listItem.length === 1) {
                // list item position is relative to scroller
                var selectionMarkerTop = $listItem.offset().top - $scrollerElement.offset().top + $scrollerElement.get(0).scrollTop;

                // force selection width to match scroller
                $selectionMarker.width($scrollerElement.get(0).scrollWidth);

                // move the selectionMarker position to align with the list item
                $selectionMarker.css("top", selectionMarkerTop);
                $selectionMarker.show();

                updateSelectionTriangle();
                $selectionTriangle.show();

                // fully scroll to the selectionMarker if it's not initially in the viewport
                var scrollerElement = $scrollerElement.get(0),
                    scrollerHeight = scrollerElement.clientHeight,
                    selectionMarkerHeight = $selectionMarker.height(),
                    selectionMarkerBottom = selectionMarkerTop + selectionMarkerHeight,
                    currentScrollBottom = scrollerElement.scrollTop + scrollerHeight;

                // update scrollTop to reveal the selected list item
                if (reveal) {
                    if (selectionMarkerTop >= currentScrollBottom) {
                        $listItem.get(0).scrollIntoView(false);
                    } else if (selectionMarkerBottom <= scrollerElement.scrollTop) {
                        $listItem.get(0).scrollIntoView(true);
                    }
                }
            }
        };

        $listElement.on("selectionChanged", updateSelectionMarker);
        $scrollerElement.on("scroll", updateSelectionTriangle);

        // update immediately
        updateSelectionMarker();

        // update clipping when the window resizes
        _resizeHandlers.push(updateSelectionTriangle);
    }

    /**
     * @private
     */
    function _handleResize() {
        _resizeHandlers.forEach(function (f) {
            f.apply();
        });
    }

    // handle all resize handlers in a single listener
    $(window).resize(_handleResize);

    // Define public API
    exports.SCROLL_SHADOW_HEIGHT = SCROLL_SHADOW_HEIGHT;
    exports.addScrollerShadow = addScrollerShadow;
    exports.removeScrollerShadow = removeScrollerShadow;
    exports.sidebarList = sidebarList;
});
<|endoftext|>