<commit_before>const autoprefixer = require('autoprefixer');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const PurifyCSSPlugin = require('purifycss-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

const EMBED_IMAGES_SIZE = 50000; // inline images smaller than this value in Kb

exports.devServer = function(options) {
    return {
        devServer: {
            // Enable history API fallback so HTML5 History API based
            // routing works. This is a good default that will come
            // in handy in more complicated setups.
            historyApiFallback: true,

            // Unlike the cli flag, this doesn't set
            // HotModuleReplacementPlugin!
            hot: true,

            // Don't refresh if hot loading fails. If you want
            // refresh behavior, set inline: true instead.
            hotOnly: true,
            // inline: true,

            // Display only errors to reduce the amount of output.
            stats: 'errors-only',

            // Parse host and port from env to allow customization.
            //
            // If you use Vagrant or Cloud9, set
            // host: options.host || '0.0.0.0';
            //
            // 0.0.0.0 is available to all network devices
            // unlike default `localhost`.
            host: options.host, // Defaults to `localhost`
            port: options.port, // Defaults to 8080
        },
        plugins: [
            // Enable multi-pass compilation for enhanced performance
            // in larger projects. Good default.
            new webpack.HotModuleReplacementPlugin({
            // Disabled as this won't work with html-webpack-template yet
            //multiStep: true
            }),
        ],
    };
};

exports.lintJavaScript = function(paths) {
    return {
        module: {
            rules: [
                {
                    test: /\.js$/,
                    include: paths,

                    use: {
                        loader: 'eslint-loader',
                        options: {
                            quiet: true,
                        },
                    },
                    enforce: 'pre',
                },
            ],
        },
    };
};

exports.loadCSS = function(paths) {
    return {
        module: {
            rules: [
                {
                    test: /(\.less$)|(\.css$)/,
                    // Restrict extraction process to the given
                    // paths.
                    include: paths,

                    use: [
                        'style-loader',
                        'css-loader',
                        {
                            loader: 'postcss-loader',
                            options: {
                                plugins: function() {
                                    return [
                                        autoprefixer,
                                    ];
                                },
                            },
                        },
                        'less-loader',
                    ],
                },
                {
                    test: /\.(svg|ttf|woff|woff2|eot)$/,
                    loader: `url-loader?limit=${EMBED_IMAGES_SIZE}`,
                },
            ],
        },
    };
};

exports.extractCSS = function(paths) {
    return {
        module: {
            rules: [
                // Extract CSS during build
                {
                    test: /(\.less$)|(\.css$)/,
                    // Restrict extraction process to the given
                    // paths.
                    include: paths,

                    loader: ExtractTextPlugin.extract([
                        'css-loader',
                        {
                            loader: 'postcss-loader',
                            options: {
                                plugins: function() {
                                    return [
                                        autoprefixer,
                                    ];
                                },
                            },
                        },
                        'less-loader',
                    ]),
                },
                // load fonts before css
                {
                    // Match woff2 in addition to patterns like .woff?v=1.1.1.
                    test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                    loader: 'url-loader',
                    options: {
                        limit: EMBED_IMAGES_SIZE,
                        mimetype: 'application/font-woff',
                        name: 'fonts/[name].[hash].[ext]',
                    },
                },
                {
                    test: /\.ttf$|\.eot$|\.svg$/,
                    loader: 'url-loader',
                    options: {
                        limit: EMBED_IMAGES_SIZE,
                        name: 'fonts/[name].[hash].[ext]',
                    },
                },
            ],
        },
        plugins: [
            // Output extracted CSS to a file
            new ExtractTextPlugin('styles/[name].[contenthash].css'),
        ],
    };
};

exports.purifyCSS = function(paths) {
    paths = Array.isArray(paths) ? paths : [paths];

    return {
        plugins: [
            new PurifyCSSPlugin({
                // Our paths are absolute so Purify needs patching
                // against that to work.
                basePath: '/',

                purifyOptions: {
                    minify: true,

                    /* TODO: there's actually a problem here, i had to whitelist
                     * everything. To find out what to remove, purify checks the
                     * html files in the project. But since this is a react app
                     * the html only have a single div#app. So pretty much
                     * everything is removed. To work around the issue, i
                     * allowed everything. Now the only good thing about this
                     * purify plugin is the minification option above.
                     */
                    whitelist: ['*'],

                    // rejected: true, // logs everything that was removed
                },

                // `paths` is used to point PurifyCSS to files not
                // visible to Webpack. This expects glob patterns so
                // we adapt here.
                paths: paths.map(path => `${path}/*`),

                // Walk through only html files within node_modules. It
                // picks up .js files by default!
                resolveExtensions: ['.html'],
            }),
        ],
    };
};

exports.lintCSS = function(paths) {
    return {
        module: {
            rules: [
                {
                    test: /\.css$/,
                    include: paths,

                    use: 'postcss-loader',
                    enforce: 'pre',
                },
            ],
        },
    };
};

exports.generateSourcemaps = function(type) {
    return {
        devtool: type,
    };
};

exports.extractBundles = function(bundles, options) {
    const entry = {};
    const names = [];

    // Set up entries and names.
    bundles.forEach(({ name, entries }) => {
        if (entries) {
            entry[name] = entries;
        }

        names.push(name);
    });

    return {
        // Define an entry point needed for splitting.
        entry,
        plugins: [
            // Extract bundles.
            new webpack.optimize.CommonsChunkPlugin(
                Object.assign({}, options, {names})
            ),
        ],
    };
};

exports.loadJavaScript = function(paths) {
    return {
        module: {
            rules: [
                {
                    test: /\.jsx?$/,
                    include: paths,
                    exclude: /node_modules|\.css$|\.less$/,

                    loader: 'babel-loader',
                    options: {
                        // Enable caching for improved performance during
                        // development.
                        // It uses default OS directory by default. If you need
                        // something more custom, pass a path to it.
                        // I.e., { cacheDirectory: '<path>' }
                        cacheDirectory: true,
                    },
                },
            ],
        },
    };
};

exports.clean = function(path) {
    return {
        plugins: [
            new CleanWebpackPlugin([path]),
        ],
    };
};

exports.minifyJavaScript = function(sourceMap) {
    return {
        plugins: [
            new webpack.optimize.UglifyJsPlugin({
                sourceMap: sourceMap,
                compress: {
                    warnings: false,
                },
            }),
        ],
    };
};

exports.setFreeVariable = function(key, value) {
    const env = {};
    env[key] = JSON.stringify(value);

    return {
        plugins: [
            new webpack.DefinePlugin(env),
        ],
    };
};

exports.loadImageFiles = function() {
    return {
        module: {
            loaders: [
                {
                    test: /(\.jpe?g$)|(\.png$)/,
                    use: 'file-loader',
                    options: {
                        name: 'assets/[name].[hash].[ext]',
                    },
                },
                {
                    test: /(\.jpe?g$)|(\.png$)/,
                    loader: 'url-loader',
                    options: {
                        limit: EMBED_IMAGES_SIZE,
                    },
                },
            ],
        },
    };
};
<commit_msg>fix: editing comments<commit_after>const autoprefixer = require('autoprefixer');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const PurifyCSSPlugin = require('purifycss-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

const EMBED_IMAGES_SIZE = 50000; // inline images smaller than this value in Kb

exports.devServer = function(options) {
    return {
        devServer: {
            // Enable history API fallback so HTML5 History API based
            // routing works. This is a good default that will come
            // in handy in more complicated setups.
            historyApiFallback: true,

            // Unlike the cli flag, this doesn't set
            // HotModuleReplacementPlugin!
            hot: true,

            // Don't refresh if hot loading fails. If you want
            // refresh behavior, set inline: true instead.
            hotOnly: true,
            // inline: true,

            // Display only errors to reduce the amount of output.
            stats: 'errors-only',

            // Parse host and port from env to allow customization.
            //
            // If you use Vagrant or Cloud9, set
            // host: options.host || '0.0.0.0';
            //
            // 0.0.0.0 is available to all network devices
            // unlike default `localhost`.
            host: options.host, // Defaults to `localhost`
            port: options.port, // Defaults to 8080
        },
        plugins: [
            // Enable multi-pass compilation for enhanced performance
            // in larger projects. Good default.
            new webpack.HotModuleReplacementPlugin({
            // Disabled as this won't work with html-webpack-template yet
            //multiStep: true
            }),
        ],
    };
};

exports.lintJavaScript = function(paths) {
    return {
        module: {
            rules: [
                {
                    test: /\.js$/,
                    include: paths,

                    use: {
                        loader: 'eslint-loader',
                        options: {
                            quiet: true,
                        },
                    },
                    enforce: 'pre',
                },
            ],
        },
    };
};

exports.loadCSS = function(paths) {
    return {
        module: {
            rules: [
                {
                    test: /(\.less$)|(\.css$)/,
                    // Restrict extraction process to the given
                    // paths.
                    include: paths,

                    use: [
                        'style-loader',
                        'css-loader',
                        {
                            loader: 'postcss-loader',
                            options: {
                                plugins: function() {
                                    return [
                                        autoprefixer,
                                    ];
                                },
                            },
                        },
                        'less-loader',
                    ],
                },
                {
                    test: /\.(svg|ttf|woff|woff2|eot)$/,
                    loader: `url-loader?limit=${EMBED_IMAGES_SIZE}`,
                },
            ],
        },
    };
};

exports.extractCSS = function(paths) {
    return {
        module: {
            rules: [
                // Extract CSS during build
                {
                    test: /(\.less$)|(\.css$)/,
                    // Restrict extraction process to the given
                    // paths.
                    include: paths,

                    loader: ExtractTextPlugin.extract([
                        'css-loader',
                        {
                            loader: 'postcss-loader',
                            options: {
                                plugins: function() {
                                    return [
                                        autoprefixer,
                                    ];
                                },
                            },
                        },
                        'less-loader',
                    ]),
                },
                // load fonts before css
                {
                    // Match woff2 in addition to patterns like .woff?v=1.1.1.
                    test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                    loader: 'url-loader',
                    options: {
                        limit: EMBED_IMAGES_SIZE,
                        mimetype: 'application/font-woff',
                        name: 'fonts/[name].[hash].[ext]',
                    },
                },
                {
                    test: /\.ttf$|\.eot$|\.svg$/,
                    loader: 'url-loader',
                    options: {
                        limit: EMBED_IMAGES_SIZE,
                        name: 'fonts/[name].[hash].[ext]',
                    },
                },
            ],
        },
        plugins: [
            // Output extracted CSS to a file
            new ExtractTextPlugin('styles/[name].[contenthash].css'),
        ],
    };
};

exports.purifyCSS = function(paths) {
    paths = Array.isArray(paths) ? paths : [paths];

    return {
        plugins: [
            new PurifyCSSPlugin({
                // Our paths are absolute so Purify needs patching
                // against that to work.
                basePath: '/',

                purifyOptions: {
                    minify: true,

                    /* TODO: there's actually a problem here, i had to whitelist
                     * everything. To find out what to remove. Purify checks the
                     * html files in the project. But since this is a react app
                     * the html only have a single div#app. So pretty much
                     * everything is removed. To work around the issue, i
                     * allowed everything. Now the only good thing about this
                     * purify plugin is the minification option above.
                     */
                    whitelist: ['*'],

                    // rejected: true, // logs everything that was removed
                },

                // `paths` is used to point PurifyCSS to files not
                // visible to Webpack. This expects glob patterns so
                // we adapt here.
                paths: paths.map(path => `${path}/*`),

                // Walk through only html files within node_modules. It
                // picks up .js files by default!
                resolveExtensions: ['.html'],
            }),
        ],
    };
};

exports.lintCSS = function(paths) {
    return {
        module: {
            rules: [
                {
                    test: /\.css$/,
                    include: paths,

                    use: 'postcss-loader',
                    enforce: 'pre',
                },
            ],
        },
    };
};

exports.generateSourcemaps = function(type) {
    return {
        devtool: type,
    };
};

exports.extractBundles = function(bundles, options) {
    const entry = {};
    const names = [];

    // Set up entries and names.
    bundles.forEach(({ name, entries }) => {
        if (entries) {
            entry[name] = entries;
        }

        names.push(name);
    });

    return {
        // Define an entry point needed for splitting.
        entry,
        plugins: [
            // Extract bundles.
            new webpack.optimize.CommonsChunkPlugin(
                Object.assign({}, options, {names})
            ),
        ],
    };
};

exports.loadJavaScript = function(paths) {
    return {
        module: {
            rules: [
                {
                    test: /\.jsx?$/,
                    include: paths,
                    exclude: /node_modules|\.css$|\.less$/,

                    loader: 'babel-loader',
                    options: {
                        // Enable caching for improved performance during
                        // development.
                        // It uses default OS directory by default. If you need
                        // something more custom, pass a path to it.
                        // I.e., { cacheDirectory: '<path>' }
                        cacheDirectory: true,
                    },
                },
            ],
        },
    };
};

exports.clean = function(path) {
    return {
        plugins: [
            new CleanWebpackPlugin([path]),
        ],
    };
};

exports.minifyJavaScript = function(sourceMap) {
    return {
        plugins: [
            new webpack.optimize.UglifyJsPlugin({
                sourceMap: sourceMap,
                compress: {
                    warnings: false,
                },
            }),
        ],
    };
};

exports.setFreeVariable = function(key, value) {
    const env = {};
    env[key] = JSON.stringify(value);

    return {
        plugins: [
            new webpack.DefinePlugin(env),
        ],
    };
};

exports.loadImageFiles = function() {
    return {
        module: {
            loaders: [
                {
                    test: /(\.jpe?g$)|(\.png$)/,
                    use: 'file-loader',
                    options: {
                        name: 'assets/[name].[hash].[ext]',
                    },
                },
                {
                    test: /(\.jpe?g$)|(\.png$)/,
                    loader: 'url-loader',
                    options: {
                        limit: EMBED_IMAGES_SIZE,
                    },
                },
            ],
        },
    };
};
<|endoftext|>


<commit_before><commit_msg>Get Programming<commit_after><|endoftext|>


<commit_before>define(function (require) {

    var zrUtil = require('zrender/core/util');
    var symbolCreator = require('../../util/symbol');
    var graphic = require('../../util/graphic');
    var listComponentHelper = require('../helper/listComponent');

    var curry = zrUtil.curry;

    var LEGEND_DISABLE_COLOR = '#ccc';

    function dispatchSelectAction(name, api) {
        api.dispatchAction({
            type: 'legendToggleSelect',
            name: name
        });
    }

    function dispatchHighlightAction(seriesModel, dataName, api) {
        seriesModel.get('legendHoverLink') && api.dispatchAction({
            type: 'highlight',
            seriesName: seriesModel.name,
            name: dataName
        });
    }

    function dispatchDownplayAction(seriesModel, dataName, api) {
        seriesModel.get('legendHoverLink') &&api.dispatchAction({
            type: 'downplay',
            seriesName: seriesModel.name,
            name: dataName
        });
    }

    return require('../../echarts').extendComponentView({

        type: 'legend',

        init: function () {
            this._symbolTypeStore = {};
        },

        render: function (legendModel, ecModel, api) {
            var group = this.group;
            group.removeAll();

            if (!legendModel.get('show')) {
                return;
            }

            var selectMode = legendModel.get('selectedMode');
            var itemWidth = legendModel.get('itemWidth');
            var itemHeight = legendModel.get('itemHeight');
            var itemAlign = legendModel.get('align');

            if (itemAlign === 'auto') {
                itemAlign = (legendModel.get('left') === 'right'
                    && legendModel.get('orient') === 'vertical')
                    ? 'right' : 'left';
            }

            var legendItemMap = {};
            var legendDrawedMap = {};
            zrUtil.each(legendModel.getData(), function (itemModel) {
                var seriesName = itemModel.get('name');
                // Use empty string or \n as a newline string
                if (seriesName === '' || seriesName === '\n') {
                    group.add(new graphic.Group({
                        newline: true
                    }));
                }

                var seriesModel = ecModel.getSeriesByName(seriesName)[0];

                legendItemMap[seriesName] = itemModel;

                if (!seriesModel || legendDrawedMap[seriesName]) {
                    // Series not exists
                    return;
                }

                var data = seriesModel.getData();
                var color = data.getVisual('color');

                if (!legendModel.isSelected(seriesName)) {
                    color = LEGEND_DISABLE_COLOR;
                }

                // If color is a callback function
                if (typeof color === 'function') {
                    // Use the first data
                    color = color(seriesModel.getDataParams(0));
                }

                // Using rect symbol defaultly
                var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
                var symbolType = data.getVisual('symbol');

                var itemGroup = this._createItem(
                    seriesName, itemModel, legendModel,
                    legendSymbolType, symbolType,
                    itemWidth, itemHeight, itemAlign, color,
                    selectMode
                );

                itemGroup.on('click', curry(dispatchSelectAction, seriesName, api))
                    .on('mouseover', curry(dispatchHighlightAction, seriesModel, '', api))
                    .on('mouseout', curry(dispatchDownplayAction, seriesModel, '', api));

                legendDrawedMap[seriesName] = true;
            }, this);

            ecModel.eachRawSeries(function (seriesModel) {
                if (seriesModel.legendDataProvider) {
                    var data = seriesModel.legendDataProvider();
                    data.each(function (idx) {
                        var name = data.getName(idx);

                        // Avoid mutiple series use the same data name
                        if (!legendItemMap[name] || legendDrawedMap[name]) {
                            return;
                        }

                        var color = data.getItemVisual(idx, 'color');

                        if (!legendModel.isSelected(name)) {
                            color = LEGEND_DISABLE_COLOR;
                        }

                        var legendSymbolType = 'roundRect';

                        var itemGroup = this._createItem(
                            name, legendItemMap[name], legendModel,
                            legendSymbolType, null,
                            itemWidth, itemHeight, itemAlign, color,
                            selectMode
                        );

                        itemGroup.on('click', curry(dispatchSelectAction, name, api))
                            // FIXME Should not specify the series name
                            .on('mouseover', curry(dispatchHighlightAction, seriesModel, name, api))
                            .on('mouseout', curry(dispatchDownplayAction, seriesModel, name, api));

                        legendDrawedMap[name] = true;
                    }, false, this);
                }
            }, this);

            listComponentHelper.layout(group, legendModel, api);
            // Render background after group is layout
            // FIXME
            listComponentHelper.addBackground(group, legendModel);
        },

        _createItem: function (
            name, itemModel, legendModel,
            legendSymbolType, symbolType,
            itemWidth, itemHeight, itemAlign, color,
            selectMode
        ) {
            var itemGroup = new graphic.Group();

            var textStyleModel = itemModel.getModel('textStyle');

            var itemIcon = itemModel.get('icon');
            // Use user given icon first
            legendSymbolType = itemIcon || legendSymbolType;
            itemGroup.add(symbolCreator.createSymbol(
                legendSymbolType, 0, 0, itemWidth, itemHeight, color
            ));

            // Compose symbols
            // PENDING
            if (!itemIcon && symbolType
                && symbolType !== legendSymbolType
                && symbolType != 'none'
            ) {
                var size = itemHeight * 0.8;
                // Put symbol in the center
                itemGroup.add(symbolCreator.createSymbol(
                    symbolType, (itemWidth - size) / 2, (itemHeight - size) / 2, size, size, color
                ));
            }

            // Text
            var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
            var textAlign = itemAlign;

            var formatter = legendModel.get('formatter');
            if (typeof formatter === 'string' && formatter) {
                name = formatter.replace('{name}', name);
            }
            else if (typeof formatter === 'function') {
                name = formatter(name);
            }

            var text = new graphic.Text({
                style: {
                    text: name,
                    x: textX,
                    y: itemHeight / 2,
                    fill: textStyleModel.getTextColor(),
                    textFont: textStyleModel.getFont(),
                    textAlign: textAlign,
                    textBaseline: 'middle'
                }
            });
            itemGroup.add(text);

            // Add a invisible rect to increase the area of mouse hover
            itemGroup.add(new graphic.Rect({
                shape: itemGroup.getBoundingRect(),
                invisible: true
            }));

            itemGroup.eachChild(function (child) {
                child.silent = !selectMode;
            });

            this.group.add(itemGroup);

            return itemGroup;
        }
    });
});<commit_msg>Unselected legend text is gray. Fix #2615<commit_after>define(function (require) {

    var zrUtil = require('zrender/core/util');
    var symbolCreator = require('../../util/symbol');
    var graphic = require('../../util/graphic');
    var listComponentHelper = require('../helper/listComponent');

    var curry = zrUtil.curry;

    var LEGEND_DISABLE_COLOR = '#ccc';

    function dispatchSelectAction(name, api) {
        api.dispatchAction({
            type: 'legendToggleSelect',
            name: name
        });
    }

    function dispatchHighlightAction(seriesModel, dataName, api) {
        seriesModel.get('legendHoverLink') && api.dispatchAction({
            type: 'highlight',
            seriesName: seriesModel.name,
            name: dataName
        });
    }

    function dispatchDownplayAction(seriesModel, dataName, api) {
        seriesModel.get('legendHoverLink') &&api.dispatchAction({
            type: 'downplay',
            seriesName: seriesModel.name,
            name: dataName
        });
    }

    return require('../../echarts').extendComponentView({

        type: 'legend',

        init: function () {
            this._symbolTypeStore = {};
        },

        render: function (legendModel, ecModel, api) {
            var group = this.group;
            group.removeAll();

            if (!legendModel.get('show')) {
                return;
            }

            var selectMode = legendModel.get('selectedMode');
            var itemAlign = legendModel.get('align');

            if (itemAlign === 'auto') {
                itemAlign = (legendModel.get('left') === 'right'
                    && legendModel.get('orient') === 'vertical')
                    ? 'right' : 'left';
            }

            var legendItemMap = {};
            var legendDrawedMap = {};
            zrUtil.each(legendModel.getData(), function (itemModel) {
                var seriesName = itemModel.get('name');
                // Use empty string or \n as a newline string
                if (seriesName === '' || seriesName === '\n') {
                    group.add(new graphic.Group({
                        newline: true
                    }));
                }

                var seriesModel = ecModel.getSeriesByName(seriesName)[0];

                legendItemMap[seriesName] = itemModel;

                if (!seriesModel || legendDrawedMap[seriesName]) {
                    // Series not exists
                    return;
                }

                var data = seriesModel.getData();
                var color = data.getVisual('color');

                // If color is a callback function
                if (typeof color === 'function') {
                    // Use the first data
                    color = color(seriesModel.getDataParams(0));
                }

                // Using rect symbol defaultly
                var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
                var symbolType = data.getVisual('symbol');

                var itemGroup = this._createItem(
                    seriesName, itemModel, legendModel,
                    legendSymbolType, symbolType,
                    itemAlign, color,
                    selectMode
                );

                itemGroup.on('click', curry(dispatchSelectAction, seriesName, api))
                    .on('mouseover', curry(dispatchHighlightAction, seriesModel, '', api))
                    .on('mouseout', curry(dispatchDownplayAction, seriesModel, '', api));

                legendDrawedMap[seriesName] = true;
            }, this);

            ecModel.eachRawSeries(function (seriesModel) {
                if (seriesModel.legendDataProvider) {
                    var data = seriesModel.legendDataProvider();
                    data.each(function (idx) {
                        var name = data.getName(idx);

                        // Avoid mutiple series use the same data name
                        if (!legendItemMap[name] || legendDrawedMap[name]) {
                            return;
                        }

                        var color = data.getItemVisual(idx, 'color');

                        var legendSymbolType = 'roundRect';

                        var itemGroup = this._createItem(
                            name, legendItemMap[name], legendModel,
                            legendSymbolType, null,
                            itemAlign, color,
                            selectMode
                        );

                        itemGroup.on('click', curry(dispatchSelectAction, name, api))
                            // FIXME Should not specify the series name
                            .on('mouseover', curry(dispatchHighlightAction, seriesModel, name, api))
                            .on('mouseout', curry(dispatchDownplayAction, seriesModel, name, api));

                        legendDrawedMap[name] = true;
                    }, false, this);
                }
            }, this);

            listComponentHelper.layout(group, legendModel, api);
            // Render background after group is layout
            // FIXME
            listComponentHelper.addBackground(group, legendModel);
        },

        _createItem: function (
            name, itemModel, legendModel,
            legendSymbolType, symbolType,
            itemAlign, color, selectMode
        ) {
            var itemWidth = legendModel.get('itemWidth');
            var itemHeight = legendModel.get('itemHeight');

            var isSelected = legendModel.isSelected(name);
            var itemGroup = new graphic.Group();

            var textStyleModel = itemModel.getModel('textStyle');

            var itemIcon = itemModel.get('icon');
            // Use user given icon first
            legendSymbolType = itemIcon || legendSymbolType;
            itemGroup.add(symbolCreator.createSymbol(
                legendSymbolType, 0, 0, itemWidth, itemHeight, isSelected ? color : LEGEND_DISABLE_COLOR
            ));

            // Compose symbols
            // PENDING
            if (!itemIcon && symbolType
                && symbolType !== legendSymbolType
                && symbolType != 'none'
            ) {
                var size = itemHeight * 0.8;
                // Put symbol in the center
                itemGroup.add(symbolCreator.createSymbol(
                    symbolType, (itemWidth - size) / 2, (itemHeight - size) / 2, size, size, color
                ));
            }

            // Text
            var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
            var textAlign = itemAlign;

            var formatter = legendModel.get('formatter');
            if (typeof formatter === 'string' && formatter) {
                name = formatter.replace('{name}', name);
            }
            else if (typeof formatter === 'function') {
                name = formatter(name);
            }

            var text = new graphic.Text({
                style: {
                    text: name,
                    x: textX,
                    y: itemHeight / 2,
                    fill: isSelected ? textStyleModel.getTextColor() : LEGEND_DISABLE_COLOR,
                    textFont: textStyleModel.getFont(),
                    textAlign: textAlign,
                    textBaseline: 'middle'
                }
            });
            itemGroup.add(text);

            // Add a invisible rect to increase the area of mouse hover
            itemGroup.add(new graphic.Rect({
                shape: itemGroup.getBoundingRect(),
                invisible: true
            }));

            itemGroup.eachChild(function (child) {
                child.silent = !selectMode;
            });

            this.group.add(itemGroup);

            return itemGroup;
        }
    });
});<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { Link } from 'react-router-dom'

class HouseholdSidebar extends Component {
  constructor(props) {
    super(props)
  }

  render() {
    return (

        {this.props.households.map(h =>
<Link to={`${this.props.url}/${h.id}`}>{h.name}</Link>
)}

    )
  }
}

export default HouseholdSidebar<commit_msg>Remove constructor from HouseholdSidebar component<commit_after>import React, { Component } from 'react'
import { Link } from 'react-router-dom'

class HouseholdSidebar extends Component {

  render() {
    return (

        {this.props.households.map(h =>
<Link to={`${this.props.url}/${h.id}`}>{h.name}</Link>
)}

    )
  }
}

export default HouseholdSidebar<|endoftext|>


<commit_before>import React from 'react';
import { Link } from 'react-router';

const SignUpComplete = () => {
  return (

Signed up!

You can now <Link to='/login'>log in</Link> with your email address and passowrd.

  );
}

export default SignUpComplete;
<commit_msg>Fix typo in notification about completing signup<commit_after>import React from 'react';
import { Link } from 'react-router';

const SignUpComplete = () => {
  return (

Signed up!

You can now <Link to='/login'>log in</Link> with your email address and password.

  );
}

export default SignUpComplete;
<|endoftext|>


<commit_before>import { LOCATION_CHANGE } from 'connected-react-router';

import mixpanel from 'mixpanel-browser';

import {
  SELECT_EXCHANGE_SOURCES,
  GET_TARGET_FUNDS_ERROR,
  SELECT_TARGET_FUND,
  CHANGE_AGREEMENT_TO_TERMS,
  SIGN_MANDATE_MOBILE_ID_START,
  SIGN_MANDATE_MOBILE_ID_START_SUCCESS,
  SIGN_MANDATE_MOBILE_ID_CANCEL,
  SIGN_MANDATE_SMART_ID_START,
  SIGN_MANDATE_SMART_ID_START_SUCCESS,
  SIGN_MANDATE_ID_CARD_START,
  SIGN_MANDATE_ID_CARD_START_SUCCESS,
  SIGN_MANDATE_START_ERROR,
  SIGN_MANDATE_SUCCESS,
  SIGN_MANDATE_ERROR,
} from '../exchange/constants';

import {
  LOG_OUT,
  MOBILE_AUTHENTICATION_START,
  ID_CARD_AUTHENTICATION_START,
  MOBILE_AUTHENTICATION_SUCCESS,
  ID_CARD_AUTHENTICATION_SUCCESS,
  GET_USER_SUCCESS,
  GET_USER_ERROR,
  GET_USER_CONVERSION_SUCCESS,
} from '../login/constants';

import { UPDATE_USER_SUCCESS } from '../common/user/constants';

function identifyUserForTracking(user) {
  mixpanel.identify(user.id);

  mixpanel.people.set({
    id: user.id,
    distinct_id: user.id,
    $first_name: user.firstName,
    $last_name: user.lastName,
    member_number: user.memberNumber,
    age: user.age,
  });
}

const initialState = {};

const noop = () => null;

export default function trackingReducer(state = initialState, action) {
  const actionType = action.type.split('/')[1];
  switch (action.type) {
    case SELECT_EXCHANGE_SOURCES:
      mixpanel.track(actionType, {
        sourceSelection: action.sourceSelection,
        sourceSelectionExact: !!action.sourceSelectionExact,
      });
      return state;
    case GET_USER_SUCCESS:
      identifyUserForTracking(action.user);
      mixpanel.track(actionType, {
        id: action.user.id,
      });
      return state;
    case SELECT_TARGET_FUND:
      mixpanel.track(actionType, {
        targetFundIsin: action.targetFundIsin,
      });
      return state;
    case SIGN_MANDATE_START_ERROR:
    case SIGN_MANDATE_ERROR:
      mixpanel.track(actionType, {
        error: action.error,
      });
      return state;
    case GET_USER_ERROR:
      mixpanel.track(actionType, {
        userError: action.userError,
      });
      return state;
    case GET_USER_CONVERSION_SUCCESS:
      mixpanel.track(actionType, action.userConversion);
      mixpanel.register({ conversion: action.userConversion });
      return state;
    case LOG_OUT:
    case MOBILE_AUTHENTICATION_START:
    case MOBILE_AUTHENTICATION_SUCCESS:
    case ID_CARD_AUTHENTICATION_START:
    case ID_CARD_AUTHENTICATION_SUCCESS:
    case GET_TARGET_FUNDS_ERROR:
    case CHANGE_AGREEMENT_TO_TERMS:
    case SIGN_MANDATE_MOBILE_ID_START:
    case SIGN_MANDATE_MOBILE_ID_START_SUCCESS:
    case SIGN_MANDATE_SMART_ID_START:
    case SIGN_MANDATE_SMART_ID_START_SUCCESS:
    case SIGN_MANDATE_MOBILE_ID_CANCEL:
    case SIGN_MANDATE_ID_CARD_START:
    case SIGN_MANDATE_SUCCESS:
    case SIGN_MANDATE_ID_CARD_START_SUCCESS:
    case UPDATE_USER_SUCCESS:
      mixpanel.track(actionType);
      return state;
    case LOCATION_CHANGE:
      try {
        mixpanel.track(actionType, { path: action.payload.location.pathname });
      } catch (e) {
        noop(e); // do nothing when mixpanel is not initialized
      }
      return state;
    default:
      return state;
  }
}
<commit_msg>Remove double user conversion tracking<commit_after>import { LOCATION_CHANGE } from 'connected-react-router';

import mixpanel from 'mixpanel-browser';

import {
  SELECT_EXCHANGE_SOURCES,
  GET_TARGET_FUNDS_ERROR,
  SELECT_TARGET_FUND,
  CHANGE_AGREEMENT_TO_TERMS,
  SIGN_MANDATE_MOBILE_ID_START,
  SIGN_MANDATE_MOBILE_ID_START_SUCCESS,
  SIGN_MANDATE_MOBILE_ID_CANCEL,
  SIGN_MANDATE_SMART_ID_START,
  SIGN_MANDATE_SMART_ID_START_SUCCESS,
  SIGN_MANDATE_ID_CARD_START,
  SIGN_MANDATE_ID_CARD_START_SUCCESS,
  SIGN_MANDATE_START_ERROR,
  SIGN_MANDATE_SUCCESS,
  SIGN_MANDATE_ERROR,
} from '../exchange/constants';

import {
  LOG_OUT,
  MOBILE_AUTHENTICATION_START,
  ID_CARD_AUTHENTICATION_START,
  MOBILE_AUTHENTICATION_SUCCESS,
  ID_CARD_AUTHENTICATION_SUCCESS,
  GET_USER_SUCCESS,
  GET_USER_ERROR,
  GET_USER_CONVERSION_SUCCESS,
} from '../login/constants';

import { UPDATE_USER_SUCCESS } from '../common/user/constants';

function identifyUserForTracking(user) {
  mixpanel.identify(user.id);

  mixpanel.people.set({
    id: user.id,
    distinct_id: user.id,
    $first_name: user.firstName,
    $last_name: user.lastName,
    member_number: user.memberNumber,
    age: user.age,
  });
}

const initialState = {};

const noop = () => null;

export default function trackingReducer(state = initialState, action) {
  const actionType = action.type.split('/')[1];
  switch (action.type) {
    case SELECT_EXCHANGE_SOURCES:
      mixpanel.track(actionType, {
        sourceSelection: action.sourceSelection,
        sourceSelectionExact: !!action.sourceSelectionExact,
      });
      return state;
    case GET_USER_SUCCESS:
      identifyUserForTracking(action.user);
      mixpanel.track(actionType, {
        id: action.user.id,
      });
      return state;
    case SELECT_TARGET_FUND:
      mixpanel.track(actionType, {
        targetFundIsin: action.targetFundIsin,
      });
      return state;
    case SIGN_MANDATE_START_ERROR:
    case SIGN_MANDATE_ERROR:
      mixpanel.track(actionType, {
        error: action.error,
      });
      return state;
    case GET_USER_ERROR:
      mixpanel.track(actionType, {
        userError: action.userError,
      });
      return state;
    case GET_USER_CONVERSION_SUCCESS:
      mixpanel.track(actionType);
      mixpanel.register({ conversion: action.userConversion });
      return state;
    case LOG_OUT:
    case MOBILE_AUTHENTICATION_START:
    case MOBILE_AUTHENTICATION_SUCCESS:
    case ID_CARD_AUTHENTICATION_START:
    case ID_CARD_AUTHENTICATION_SUCCESS:
    case GET_TARGET_FUNDS_ERROR:
    case CHANGE_AGREEMENT_TO_TERMS:
    case SIGN_MANDATE_MOBILE_ID_START:
    case SIGN_MANDATE_MOBILE_ID_START_SUCCESS:
    case SIGN_MANDATE_SMART_ID_START:
    case SIGN_MANDATE_SMART_ID_START_SUCCESS:
    case SIGN_MANDATE_MOBILE_ID_CANCEL:
    case SIGN_MANDATE_ID_CARD_START:
    case SIGN_MANDATE_SUCCESS:
    case SIGN_MANDATE_ID_CARD_START_SUCCESS:
    case UPDATE_USER_SUCCESS:
      mixpanel.track(actionType);
      return state;
    case LOCATION_CHANGE:
      try {
        mixpanel.track(actionType, { path: action.payload.location.pathname });
      } catch (e) {
        noop(e); // do nothing when mixpanel is not initialized
      }
      return state;
    default:
      return state;
  }
}
<|endoftext|>


<commit_before>//
// Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//     You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//     See the License for the specific language governing permissions and
// limitations under the License.

(function(scope, shared) {

function ComputedStylePropertyMap(element) {
  this._element = element;
}

ComputedStylePropertyMap.prototype = Object.create(shared.StylePropertyMap.prototype);

ComputedStylePropertyMap.prototype.append = function(property, value) {
  throw new TypeError('ComputedStylePropertyMap is immutable');
};

ComputedStylePropertyMap.prototype.get = function(property) {
  if (typeof property != 'string') {
    throw new TypeError('parameter 1 is not of type \'string\'');
  }
  // TODO: define types
  throw new TypeError('Not implemented yet');
};

function getComputedStyleMap(element) {
  return new ComputedStylePropertyMap(element);
}

scope.getComputedStyleMap = getComputedStyleMap;
scope.ComputedStylePropertyMap = ComputedStylePropertyMap;

})(window, baseClasses)
<commit_msg>switch around scope order<commit_after>//
// Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//     You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//     See the License for the specific language governing permissions and
// limitations under the License.

(function(shared, scope) {

function ComputedStylePropertyMap(element) {
  this._element = element;
}

ComputedStylePropertyMap.prototype = Object.create(shared.StylePropertyMap.prototype);

ComputedStylePropertyMap.prototype.append = function(property, value) {
  throw new TypeError('ComputedStylePropertyMap is immutable');
};

ComputedStylePropertyMap.prototype.get = function(property) {
  if (typeof property != 'string') {
    throw new TypeError('parameter 1 is not of type \'string\'');
  }
  // TODO: define types
  throw new TypeError('Not implemented yet');
};

function getComputedStyleMap(element) {
  return new ComputedStylePropertyMap(element);
}

scope.getComputedStyleMap = getComputedStyleMap;
scope.ComputedStylePropertyMap = ComputedStylePropertyMap;

})(baseClasses, window)
<|endoftext|>


<commit_before>describe('Unauthorized: Currently testing file/folder sharing,', function () {
  // CURRENT TIME
  var timeRightNow = new Date().getTime()
  var OwnCloud = require('../../src')
  var config = require('../config/config.json')

  // LIBRARY INSTANCE
  var oc

  // TESTING CONFIGS
  var testUser = 'testUser' + timeRightNow
  var testGroup = 'testGroup' + timeRightNow
  var testFolder = '/testFolder' + timeRightNow
  var nonExistingFile = 'nonExistingFile' + timeRightNow

  var testFile = '/文件' + timeRightNow + '.txt'

  beforeEach(function () {
    oc = new OwnCloud(config.owncloudURL)
    oc.login(config.username, config.password + timeRightNow)
  })

  it('checking method : shareFileWithLink', function (done) {
    oc.shares.shareFileWithLink(testFile).then(share => {
      expect(share).toBe(null)
      done()
    }).catch(error => {
      expect(error).toMatch('CORS request rejected')
      done()
    })
  })

  it('checking method : shareFileWithUser', function (done) {
    oc.shares.shareFileWithUser(testFile, testUser).then(share => {
      expect(share).toBe(null)
      done()
    }).catch(error => {
      expect(error).toMatch('CORS request rejected')
      done()
    })
  })

  it('checking method : shareFileWithGroup', function (done) {
    oc.shares.shareFileWithGroup(testFile, testGroup, {
      perms: 19
    }).then(share => {
      expect(share).toEqual(null)
      done()
    }).catch(error => {
      expect(error).toMatch('CORS request rejected')
      done()
    })
  })

  it('checking method : isShared', function (done) {
    oc.shares.isShared(nonExistingFile).then(status => {
      expect(status).toBe(null)
      done()
    }).catch(error => {
      expect(error).toMatch('CORS request rejected')
      done()
    })
  })

  it('checking method : getShare', function (done) {
    oc.shares.getShare(1).then(share => {
      expect(share).toBe(null)
      done()
    }).catch(error => {
      expect(error).toMatch('CORS request rejected')
      done()
    })
  })

  it('checking method : getShares', function (done) {
    oc.shares.getShares(1).then(shares => {
      expect(shares).toBe(null)
      done()
    }).catch(error => {
      expect(error).toMatch('CORS request rejected')
      done()
    })
  })

  it('checking method : updateShare', function (done) {
    oc.shares.shareFileWithLink(testFolder).then(share => {
      expect(share).toBe(null)
      done()
    }).catch(error => {
      expect(error).toMatch('CORS request rejected')
      done()
    })
  })

  it('checking method : deleteShare', function (done) {
    oc.shares.deleteShare(123).then(status => {
      expect(status).toBe(null)
      done()
    }).catch(error => {
      expect(error).toMatch('CORS request rejected')
      done()
    })
  })
})
<commit_msg>Correct behavior is to return 401/Unauthized - owncloud/core:stable10 has correct behavior. owncloud/cire:master needs adaption<commit_after>describe('Unauthorized: Currently testing file/folder sharing,', function () {
  // CURRENT TIME
  var timeRightNow = new Date().getTime()
  var OwnCloud = require('../../src')
  var config = require('../config/config.json')

  // LIBRARY INSTANCE
  var oc

  // TESTING CONFIGS
  var testUser = 'testUser' + timeRightNow
  var testGroup = 'testGroup' + timeRightNow
  var testFolder = '/testFolder' + timeRightNow
  var nonExistingFile = 'nonExistingFile' + timeRightNow

  var testFile = '/文件' + timeRightNow + '.txt'

  beforeEach(function () {
    oc = new OwnCloud(config.owncloudURL)
    oc.login(config.username, config.password + timeRightNow)
  })

  it('checking method : shareFileWithLink', function (done) {
    oc.shares.shareFileWithLink(testFile).then(share => {
      expect(share).toBe(null)
      done()
    }).catch(error => {
      expect(error).toMatch('Unauthorised')
      done()
    })
  })

  it('checking method : shareFileWithUser', function (done) {
    oc.shares.shareFileWithUser(testFile, testUser).then(share => {
      expect(share).toBe(null)
      done()
    }).catch(error => {
      expect(error).toMatch('Unauthorised')
      done()
    })
  })

  it('checking method : shareFileWithGroup', function (done) {
    oc.shares.shareFileWithGroup(testFile, testGroup, {
      perms: 19
    }).then(share => {
      expect(share).toEqual(null)
      done()
    }).catch(error => {
      expect(error).toMatch('Unauthorised')
      done()
    })
  })

  it('checking method : isShared', function (done) {
    oc.shares.isShared(nonExistingFile).then(status => {
      expect(status).toBe(null)
      done()
    }).catch(error => {
      expect(error).toMatch('Unauthorised')
      done()
    })
  })

  it('checking method : getShare', function (done) {
    oc.shares.getShare(1).then(share => {
      expect(share).toBe(null)
      done()
    }).catch(error => {
      expect(error).toMatch('Unauthorised')
      done()
    })
  })

  it('checking method : getShares', function (done) {
    oc.shares.getShares(1).then(shares => {
      expect(shares).toBe(null)
      done()
    }).catch(error => {
      expect(error).toMatch('Unauthorised')
      done()
    })
  })

  it('checking method : updateShare', function (done) {
    oc.shares.shareFileWithLink(testFolder).then(share => {
      expect(share).toBe(null)
      done()
    }).catch(error => {
      expect(error).toMatch('Unauthorised')
      done()
    })
  })

  it('checking method : deleteShare', function (done) {
    oc.shares.deleteShare(123).then(status => {
      expect(status).toBe(null)
      done()
    }).catch(error => {
      expect(error).toMatch('Unauthorised')
      done()
    })
  })
})
<|endoftext|>


<commit_before>/*function humanSize(size) {
    var units = ['T', 'G', 'M', 'K'];
    var unit = '';
    while(size >= 1024 && units.length > 0) {
        size /= 1024;
        unit = units.pop();
    }
    return (Math.round(size * 10) / 10) + ' ' +
        unit + 'B';
}*/

function formatBandwidth(size) {
    return size+"MB/s";
}

function toMB(values) {
    return [values[0], values[1] / 1024 / 1024];
}

function loadBytes(cb) {
    $.ajax({ url: "/stats/bytes.json",
	 dataType: 'json',
	 success: function(data) {
	     $("#bytes").before("
Swarm Throughput
");
	     $.plot($("#bytes"), [{
		 label: "Download",
	         data: data.down.map(toMB),
		 color: 'green',
		 lines: { fill: true },
		 hoverable: true,
		 clickable: true
	     }, {
		 label: "Upload",
		 data: data.up.map(toMB),
		 color: 'red',
		 lines: { fill: true },
		 hoverable: true,
		 clickable: true
	     }], {
                yaxis: { min: 0,
			 tickFormatter: formatBandwidth
		       },
                xaxis: { mode: 'time',
			 timeformat: "%H:%M"
		       },
		width: 800,
		height: 300
            });
	    cb();
	 },
	 error: cb
       });
}
function loadPeers(cb) {
    $.ajax({ url: "/stats/peers.json",
	 dataType: 'json',
	 success: function(data) {
	     $("#peers").before("
Tracked Peers
");
	     $.plot($("#peers"), [{
		 label: "Leechers (IPv4)",
	         data: data.leechers4,
		 color: '#cf0000'
	     }, {
		 label: "Seeders (IPv4)",
	         data: data.seeders4,
		 color: '#007f00'
	     }, {
		 label: "Leechers (IPv6)",
	         data: data.leechers6,
		 color: '#ff6f3f'
	     }, {
		 label: "Seeders (IPv6)",
	         data: data.seeders6,
		 color: '#3fff3f'
	     }], {
                yaxis: { min: 0 },
                xaxis: { mode: 'time',
			 timeformat: "%H:%M"
		       },
		width: 800,
		height: 300
            });
	     if (cb)
		 cb();
	 },
	 error: cb
       });
}

loadBytes(loadPeers);
<commit_msg>stats.js: applyTZOffset()<commit_after>/*function humanSize(size) {
    var units = ['T', 'G', 'M', 'K'];
    var unit = '';
    while(size >= 1024 && units.length > 0) {
        size /= 1024;
        unit = units.pop();
    }
    return (Math.round(size * 10) / 10) + ' ' +
        unit + 'B';
}*/

function formatBandwidth(size) {
    return size+"MB/s";
}

function toMB(values) {
    return [values[0], values[1] / 1024 / 1024];
}

var tzOffset = - new Date().getTimezoneOffset() * 60 * 1000;
function applyTZOffset(values) {
    return [values[0] + tzOffset, values[1]];
}

function loadBytes(cb) {
    $.ajax({ url: "/stats/bytes.json",
	 dataType: 'json',
	 success: function(data) {
	     $("#bytes").before("
Swarm Throughput
");
	     $.plot($("#bytes"), [{
		 label: "Download",
	         data: data.down.map(toMB).map(applyTZOffset),
		 color: 'green',
		 lines: { fill: true },
		 hoverable: true,
		 clickable: true
	     }, {
		 label: "Upload",
		 data: data.up.map(toMB).map(applyTZOffset),
		 color: 'red',
		 lines: { fill: true },
		 hoverable: true,
		 clickable: true
	     }], {
                yaxis: { min: 0,
			 tickFormatter: formatBandwidth
		       },
                xaxis: { mode: 'time',
			 timeformat: "%H:%M"
		       },
		width: 800,
		height: 300
            });
	    cb();
	 },
	 error: cb
       });
}
function loadPeers(cb) {
    $.ajax({ url: "/stats/peers.json",
	 dataType: 'json',
	 success: function(data) {
	     $("#peers").before("
Tracked Peers
");
	     $.plot($("#peers"), [{
		 label: "Leechers (IPv4)",
	         data: data.leechers4.map(applyTZOffset),
		 color: '#cf0000'
	     }, {
		 label: "Seeders (IPv4)",
	         data: data.seeders4.map(applyTZOffset),
		 color: '#007f00'
	     }, {
		 label: "Leechers (IPv6)",
	         data: data.leechers6.map(applyTZOffset),
		 color: '#ff6f3f'
	     }, {
		 label: "Seeders (IPv6)",
	         data: data.seeders6.map(applyTZOffset),
		 color: '#3fff3f'
	     }], {
                yaxis: { min: 0 },
                xaxis: { mode: 'time',
			 timeformat: "%H:%M"
		       },
		width: 800,
		height: 300
            });
	     if (cb)
		 cb();
	 },
	 error: cb
       });
}

loadBytes(loadPeers);
<|endoftext|>


<commit_before>var statusUrl = 'http://dispatch32.ngrok.com/api/pebblestatus/IDENTIFIER';

var cache = null;
var index = null;

function redraw() {
  if (cache === null || index === null) {
    simply.text({ title: 'Loading', subtitle: '', body: '' });
  } else if (cache.tasks && index >= cache.tasks.length) {
    simply.text({ title: 'No Tasks', subtitle: '', body: '' });
  } else {
    if (cache.tasks) {
      var item = cache.tasks[index];
      var title = '' + item.code + ' (' + (index + 1) + ' of ' + (cache.tasks.length) + ')';
      var subtitle = item.description;
      simply.text({ title: title, subtitle: subtitle, body: '' });
    } else if (cache.current) {
      var item = cache.current;
      var title = '[' + item.code + ']';
      simply.text({ title: title, subtitle: item.description, body: ''});
    }
  }
}

redraw();
fetchData();

simply.on('singleClick', function(e) {
  if (e.button === 'up') {
    if (index === null) {
      index = 0;
    } else {
      index--;
      if (index < 0) index = 0;
    }
    redraw();
  } else if (e.button === 'down') {
    if (index === null || cache === null || !cache.tasks) {
      index = 0;
    } else {
      index++;
      if (index >= cache.tasks.length) index = cache.tasks.length - 1;
    }
    redraw();
  } else if (e.button === 'select') {
    fetchData();
  }
});

function fetchData() {
  ajax({url: statusUrl}, function(data) {
    var body = JSON.parse(data);
    cache = body;
    index = 0;
    redraw();
  });
}

simply.on('longClick', function(e) {
  if (e.button === 'select') {
    if (cache === null) return;
    if (cache.tasks) {
      var item = cache.tasks[index];
      if (item) {
        ajax({method: 'post',
             url: statusUrl, type: 'json', data: {call: 'start', code: item.code}}, function(data) {
               fetchData();
             });
      }
    } else {
      ajax({method: 'post',
           url: statusUrl, type: 'json', data: {call: 'done'}}, function(data) {
             fetchData();
           });
    }
  } else if (e.button === 'up' || e.button === 'down') {
    if (cache && cache.tasks) {
      var item = cache.tasks[index];
      if (item) {
        ajax({method: 'post',
             url: statusUrl, type: 'json', data: {call: 'close', code: item.code}}, function(data) {
               fetchData();
             });
      }
    } else if (cache && cache.current) {
      ajax({method: 'post',
           url: statusUrl, type: 'json', data: {call: 'close'}}, function(data) {
             fetchData();
           });
    }
  }
});
<commit_msg>Update hard-coded URL<commit_after>var statusUrl = 'http://dispatch.hackmit.org/api/pebblestatus/IDENTIFIER';

var cache = null;
var index = null;

function redraw() {
  if (cache === null || index === null) {
    simply.text({ title: 'Loading', subtitle: '', body: '' });
  } else if (cache.tasks && index >= cache.tasks.length) {
    simply.text({ title: 'No Tasks', subtitle: '', body: '' });
  } else {
    if (cache.tasks) {
      var item = cache.tasks[index];
      var title = '' + item.code + ' (' + (index + 1) + ' of ' + (cache.tasks.length) + ')';
      var subtitle = item.description;
      simply.text({ title: title, subtitle: subtitle, body: '' });
    } else if (cache.current) {
      var item = cache.current;
      var title = '[' + item.code + ']';
      simply.text({ title: title, subtitle: item.description, body: ''});
    }
  }
}

redraw();
fetchData();

simply.on('singleClick', function(e) {
  if (e.button === 'up') {
    if (index === null) {
      index = 0;
    } else {
      index--;
      if (index < 0) index = 0;
    }
    redraw();
  } else if (e.button === 'down') {
    if (index === null || cache === null || !cache.tasks) {
      index = 0;
    } else {
      index++;
      if (index >= cache.tasks.length) index = cache.tasks.length - 1;
    }
    redraw();
  } else if (e.button === 'select') {
    fetchData();
  }
});

function fetchData() {
  ajax({url: statusUrl}, function(data) {
    var body = JSON.parse(data);
    cache = body;
    index = 0;
    redraw();
  });
}

simply.on('longClick', function(e) {
  if (e.button === 'select') {
    if (cache === null) return;
    if (cache.tasks) {
      var item = cache.tasks[index];
      if (item) {
        ajax({method: 'post',
             url: statusUrl, type: 'json', data: {call: 'start', code: item.code}}, function(data) {
               fetchData();
             });
      }
    } else {
      ajax({method: 'post',
           url: statusUrl, type: 'json', data: {call: 'done'}}, function(data) {
             fetchData();
           });
    }
  } else if (e.button === 'up' || e.button === 'down') {
    if (cache && cache.tasks) {
      var item = cache.tasks[index];
      if (item) {
        ajax({method: 'post',
             url: statusUrl, type: 'json', data: {call: 'close', code: item.code}}, function(data) {
               fetchData();
             });
      }
    } else if (cache && cache.current) {
      ajax({method: 'post',
           url: statusUrl, type: 'json', data: {call: 'close'}}, function(data) {
             fetchData();
           });
    }
  }
});
<|endoftext|>


<commit_before>/* This is a modified version of mock-phantom-touch-events.
 *
 * The original mock-phantom-touch-events can be found at https://github.com/gardr/mock-phantom-touch-events
 *
 * mock-phantom-touch-events is licensed under:
 *
 * The MIT License (MIT)
 * Copyright (c) 2013 FINN.no AS
 * 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.
 *
 */

function computedStyle(el, prop) {
    return (
        window.getComputedStyle ? window.getComputedStyle(el) : el.currentStyle
    )[prop.replace(/-(\w)/gi, function (word, letter) {
        return letter.toUpperCase();
    })];
}

function getChildrenSize(container) {
    if (!container) {
        return;
    }
    var children = [].slice.call(container.children, 0).filter(function (el) {
        var pos = computedStyle(el, 'position');
        el.rect = el.getBoundingClientRect(); // store rect for later
        return !(
            (pos === 'absolute' || pos === 'fixed') ||
            (el.rect.width === 0 && el.rect.height === 0)
        );
    });
    if (children.length === 0) {
        return {
            width: 0,
            height: 0
        };
    }

    var totRect = children.reduce(function (tot, el) {
        return (!tot ?
            el.rect : {
                top: Math.min(tot.top, el.rect.top),
                left: Math.min(tot.left, el.rect.left),
                right: Math.max(tot.right, el.rect.right),
                bottom: Math.max(tot.bottom, el.rect.bottom)
            });
    }, null);

    return {
        width: totRect.right - totRect.left,
        height: totRect.bottom - totRect.top
    };
}

/*
    list can be either [[x, y], [x, y]] or [x, y]
*/
function createTouchList(target, list) {
    if (Array.isArray(list) && list[0] && !Array.isArray(list[0])) {
        list = [list];
    }
    list = list.map(function (entry, index) {
        var x = entry[0], y = entry[1], id = entry[2] ? entry[2] : index + 1;
        return createTouch(x, y, target, id);
    });
    return document.createTouchList.apply(document, list);
}

function createTouch(x, y, target, id) {
    return document.createTouch(window, target,
        //identifier
        id || 1,
        //pageX / clientX
        x,
        //pageY / clientY
        y,
        //screenX
        x,
        //screenY
        y
    );
}

//http://stackoverflow.com/questions/7056026/variation-of-e-touches-e-targettouches-and-e-changedtouches
function initTouchEvent(touchEvent, type, touches) {
    var touch1 = touches[0];
    return touchEvent.initTouchEvent(
        //touches
        touches,
        //targetTouches
        touches,
        //changedTouches
        touches,
        //type
        type,
        //view
        window,
        //screenX
        touch1.screenX,
        //screenY
        touch1.screenY,
        //clientX
        touch1.clientX,
        //clientY
        touch1.clientY,
        //ctrlKey
        false,
        //altKey
        false,
        //shiftKey
        false,
        //metaKey
        false
    );
}

function createTouchEvent(elem, type, touches) {
    var touchEvent = document.createEvent('TouchEvent');
    if (Array.isArray(touches)) {
        touches = createTouchList(elem, touches);
    }

    function dispatch(getEvent) {
        initTouchEvent(touchEvent, type, touches);
        if (typeof getEvent === 'function'){
            getEvent.call(elem, touchEvent, elem);
        }
        elem.dispatchEvent(touchEvent);
    }
    dispatch.event = touchEvent;
    return dispatch;
}

function apply(fn, arg, args) {
    return fn.apply(null, [arg].concat(Array.prototype.slice.call(args)));
}

function swipeLeft() {
    return apply(swipe, 'left', arguments);
}

function swipeRight() {
    return apply(swipe, 'right', arguments);
}

function swipeTop(){
    return apply(swipe, 'top', arguments);
}

function swipeBottom(){
    return apply(swipe, 'bottom', arguments);
}

function round(num){
    return Math.round(num);
}

var HORIZONTAL_OFFSET = 45;
var VERTICAL_OFFSET = 10;
function swipe(direction, elem, ms, frames, getEvent) {
    var elemSize = getChildrenSize(elem.parentNode);

    var x;
    var y;
    var from;
    var to;
    var isVertical = direction === 'top' || direction === 'bottom';
    if (isVertical){
        y = elemSize.height;
        x = elemSize.width / 2;

        from = [x*0.95, VERTICAL_OFFSET].map(round);
        to   = [x*1.01, y-VERTICAL_OFFSET].map(round);
    } else {
        // horizontal
        x = elemSize.width;
        y = elemSize.height / 2;
        from = [HORIZONTAL_OFFSET, y*0.98].map(round);
        to   = [x - HORIZONTAL_OFFSET, y*1.01].map(round);
    }

    if (direction === 'right' || direction === 'top') {
        touchActionSequence(elem, from, to, ms, frames, getEvent);
    } else {
        touchActionSequence(elem, to, from, ms, frames, getEvent);
    }
}

function getDiff(fromList, toList){
    return [
        toList[0] - fromList[0],
        toList[1] - fromList[1]
    ];
}

function getXandYFrame(startPoint, diffToWalk, currentProgress){
    return [
        Math.round(
            Math.abs(
                startPoint[0] + (diffToWalk[0] * currentProgress))),
        Math.round(
            Math.abs(
                startPoint[1] + (diffToWalk[1] * currentProgress)))
    ];
}

function touchActionSequence(elem, fromXandY, toXandY, ms, frames, getEvent) {
    frames       = frames || 10;
    ms           = Math.round((ms||1000) / frames);
    // lets find difference from start to end and divide on frames
    var diff     = getDiff(fromXandY, toXandY);
    var counter  = frames;
    var pos             = getXandYFrame(fromXandY, diff, counter/frames);
    var targetElement;

    targetElement   = document.elementFromPoint(pos[0], pos[1]);

    setTimeout(function handler() {
        counter--;
        if (counter) {
            pos = getXandYFrame(fromXandY, diff, counter/frames);
            targetElement = document.elementFromPoint(pos[0], pos[1]);
            createTouchEvent(targetElement||elem, 'touchmove', pos)(getEvent);
            setTimeout(handler, ms);
        } else {
            createTouchEvent(targetElement||elem, 'touchend', [[0, 0]])(getEvent);
        }
    }, ms);
    createTouchEvent(targetElement||elem, 'touchstart', pos)(getEvent);
}

function factory(){
    return {
        _apply: apply,
        _getXandYFrame: getXandYFrame,
        _getDiff: getDiff,
        swipeLeft: swipeLeft,
        swipeRight: swipeRight,
        swipeTop: swipeTop,
        swipeBottom: swipeBottom,
        touchActionSequence: touchActionSequence,
        createTouchEvent: createTouchEvent
    };
}

if (typeof module !== 'undefined' && module.exports){
    module.exports = factory();
} else {
    window.mockPhantomTouchEvents = factory();
}
<commit_msg>Fix 0 identifier bug in mockTouch lib<commit_after>/* This is a modified version of mock-phantom-touch-events.
 *
 * The original mock-phantom-touch-events can be found at https://github.com/gardr/mock-phantom-touch-events
 *
 * mock-phantom-touch-events is licensed under:
 *
 * The MIT License (MIT)
 * Copyright (c) 2013 FINN.no AS
 * 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.
 *
 */

function computedStyle(el, prop) {
    return (
        window.getComputedStyle ? window.getComputedStyle(el) : el.currentStyle
    )[prop.replace(/-(\w)/gi, function (word, letter) {
        return letter.toUpperCase();
    })];
}

function getChildrenSize(container) {
    if (!container) {
        return;
    }
    var children = [].slice.call(container.children, 0).filter(function (el) {
        var pos = computedStyle(el, 'position');
        el.rect = el.getBoundingClientRect(); // store rect for later
        return !(
            (pos === 'absolute' || pos === 'fixed') ||
            (el.rect.width === 0 && el.rect.height === 0)
        );
    });
    if (children.length === 0) {
        return {
            width: 0,
            height: 0
        };
    }

    var totRect = children.reduce(function (tot, el) {
        return (!tot ?
            el.rect : {
                top: Math.min(tot.top, el.rect.top),
                left: Math.min(tot.left, el.rect.left),
                right: Math.max(tot.right, el.rect.right),
                bottom: Math.max(tot.bottom, el.rect.bottom)
            });
    }, null);

    return {
        width: totRect.right - totRect.left,
        height: totRect.bottom - totRect.top
    };
}

/*
    list can be either [[x, y], [x, y]] or [x, y]
*/
function createTouchList(target, list) {
    if (Array.isArray(list) && list[0] && !Array.isArray(list[0])) {
        list = [list];
    }
    list = list.map(function (entry, index) {
        var x = entry[0], y = entry[1], id = entry[2] || index;
        return createTouch(x, y, target, id);
    });
    return document.createTouchList.apply(document, list);
}

function createTouch(x, y, target, id) {
    return document.createTouch(window, target,
        //identifier
        id || 0,
        //pageX / clientX
        x,
        //pageY / clientY
        y,
        //screenX
        x,
        //screenY
        y
    );
}

//http://stackoverflow.com/questions/7056026/variation-of-e-touches-e-targettouches-and-e-changedtouches
function initTouchEvent(touchEvent, type, touches) {
    var touch1 = touches[0];
    return touchEvent.initTouchEvent(
        //touches
        touches,
        //targetTouches
        touches,
        //changedTouches
        touches,
        //type
        type,
        //view
        window,
        //screenX
        touch1.screenX,
        //screenY
        touch1.screenY,
        //clientX
        touch1.clientX,
        //clientY
        touch1.clientY,
        //ctrlKey
        false,
        //altKey
        false,
        //shiftKey
        false,
        //metaKey
        false
    );
}

function createTouchEvent(elem, type, touches) {
    var touchEvent = document.createEvent('TouchEvent');
    if (Array.isArray(touches)) {
        touches = createTouchList(elem, touches);
    }

    function dispatch(getEvent) {
        initTouchEvent(touchEvent, type, touches);
        if (typeof getEvent === 'function'){
            getEvent.call(elem, touchEvent, elem);
        }
        elem.dispatchEvent(touchEvent);
    }
    dispatch.event = touchEvent;
    return dispatch;
}

function apply(fn, arg, args) {
    return fn.apply(null, [arg].concat(Array.prototype.slice.call(args)));
}

function swipeLeft() {
    return apply(swipe, 'left', arguments);
}

function swipeRight() {
    return apply(swipe, 'right', arguments);
}

function swipeTop(){
    return apply(swipe, 'top', arguments);
}

function swipeBottom(){
    return apply(swipe, 'bottom', arguments);
}

function round(num){
    return Math.round(num);
}

var HORIZONTAL_OFFSET = 45;
var VERTICAL_OFFSET = 10;
function swipe(direction, elem, ms, frames, getEvent) {
    var elemSize = getChildrenSize(elem.parentNode);

    var x;
    var y;
    var from;
    var to;
    var isVertical = direction === 'top' || direction === 'bottom';
    if (isVertical){
        y = elemSize.height;
        x = elemSize.width / 2;

        from = [x*0.95, VERTICAL_OFFSET].map(round);
        to   = [x*1.01, y-VERTICAL_OFFSET].map(round);
    } else {
        // horizontal
        x = elemSize.width;
        y = elemSize.height / 2;
        from = [HORIZONTAL_OFFSET, y*0.98].map(round);
        to   = [x - HORIZONTAL_OFFSET, y*1.01].map(round);
    }

    if (direction === 'right' || direction === 'top') {
        touchActionSequence(elem, from, to, ms, frames, getEvent);
    } else {
        touchActionSequence(elem, to, from, ms, frames, getEvent);
    }
}

function getDiff(fromList, toList){
    return [
        toList[0] - fromList[0],
        toList[1] - fromList[1]
    ];
}

function getXandYFrame(startPoint, diffToWalk, currentProgress){
    return [
        Math.round(
            Math.abs(
                startPoint[0] + (diffToWalk[0] * currentProgress))),
        Math.round(
            Math.abs(
                startPoint[1] + (diffToWalk[1] * currentProgress)))
    ];
}

function touchActionSequence(elem, fromXandY, toXandY, ms, frames, getEvent) {
    frames       = frames || 10;
    ms           = Math.round((ms||1000) / frames);
    // lets find difference from start to end and divide on frames
    var diff     = getDiff(fromXandY, toXandY);
    var counter  = frames;
    var pos             = getXandYFrame(fromXandY, diff, counter/frames);
    var targetElement;

    targetElement   = document.elementFromPoint(pos[0], pos[1]);

    setTimeout(function handler() {
        counter--;
        if (counter) {
            pos = getXandYFrame(fromXandY, diff, counter/frames);
            targetElement = document.elementFromPoint(pos[0], pos[1]);
            createTouchEvent(targetElement||elem, 'touchmove', pos)(getEvent);
            setTimeout(handler, ms);
        } else {
            createTouchEvent(targetElement||elem, 'touchend', [[0, 0]])(getEvent);
        }
    }, ms);
    createTouchEvent(targetElement||elem, 'touchstart', pos)(getEvent);
}

function factory(){
    return {
        _apply: apply,
        _getXandYFrame: getXandYFrame,
        _getDiff: getDiff,
        swipeLeft: swipeLeft,
        swipeRight: swipeRight,
        swipeTop: swipeTop,
        swipeBottom: swipeBottom,
        touchActionSequence: touchActionSequence,
        createTouchEvent: createTouchEvent
    };
}

if (typeof module !== 'undefined' && module.exports){
    module.exports = factory();
} else {
    window.mockPhantomTouchEvents = factory();
}
<|endoftext|>


<commit_before>module.exports = (function() {
  let neo4j = require('neo4j-driver').v1;
  let driver = neo4j.driver('bolt://172.23.238.220', neo4j.auth.basic('neo4j', '9455338161'));
  return driver;
}());
<commit_msg>neo4j configuration for seneca updated<commit_after>module.exports = (function() {
  let neo4j = require('neo4j-driver').v1;
  let driver = neo4j.driver('bolt://52.14.238.159', neo4j.auth.basic('neo4j', '9455338161'));
  return driver;
}());
<|endoftext|>


<commit_before>ManageIQ.angular.app.service('mwAddDatasourceService', MwAddDatasourceService);

MwAddDatasourceService.$inject = ['$http', '$q'];

function MwAddDatasourceService($http, $q) {

   var datasources = [
    {id: 'H2', label: 'H2', name: 'H2DS', jndiName: 'java:jboss/datasources/H2DS',
      driverName: 'h2', driverModuleName: 'com.h2database.h2', driverClass: 'org.h2.Driver',
      connectionUrl: ':mem:test;DB_CLOSE_DELAY=-1'},
    {id : 'POSTGRES', label: 'Postgres', name: 'PostgresDS', jndiName: 'java:jboss/datasources/PostgresDS',
      driverName: 'postresql', driverModuleName: 'org.postgresql', driverClass: 'org.postgresql.Driver',
      connectionUrl: '://localhost:5432/postgresdb'},
    {id: 'MSSQL', label: 'Microsoft SQL Server', name: 'MSSQLDS', jndiName: 'java:jboss/datasources/MSSQLDS',
      driverName: 'sqlserver', driverModuleName: 'com.microsoft',
      driverClass: 'com.microsoft.sqlserver.jdbc.SQLServerDriver',
      connectionUrl: '://localhost:1433;DatabaseName=MyDatabase'},
    {id: 'ORACLE', label: 'Oracle', name: 'OracleDS', jndiName: 'java:jboss/datasources/OracleDS',
      driverName: 'oracle', driverModuleName: 'com.oracle', driverClass: 'oracle.jdbc.driver.OracleDriver',
      connectionUrl: ':thin:@localhost:1521:oraclesid'},
    {id: 'DB2', label: 'IBM DB2', name: 'DB2DS', jndiName: 'java:jboss/datasources/DB2DS',
      driverName: 'ibmdb2', driverModuleName: 'com.ibm', driverClass: 'COM.ibm.db2.jdbc.app.DB2Driver',
      connectionUrl: '://db2'},
    {id: 'SYBASE', label: 'Sybase', name: 'SybaseDS', jndiName: 'java:jboss/datasources/SybaseDB',
      driverName: 'sybase', driverModuleName: 'com.sybase', driverClass: 'com.sybase.jdbc.SybDriver',
      connectionUrl: ':Tds:localhost:5000/mydatabase?JCONNECT_VERSION=6'},
     {id: 'MARIADB', label: 'MariaDB', name: 'MariaDBDS', jndiName: 'java:jboss/datasources/MariaDBDS',
       driverName: 'mariadb', driverModuleName: 'org.mariadb', driverClass: 'org.mariadb.jdbc.Driver',
       connectionUrl: '://localhost:3306/db_name'},
    {id: 'MYSQL', label: 'MySql', name: 'MySqlDS', jndiName: 'java:jboss/datasources/MySqlDS',
      driverName: 'mysql', driverModuleName: 'com.mysql', driverClass: 'com.mysql.jdbc.Driver',
      connectionUrl: '://localhost:3306/db_name'}
  ];

  this.getDatasources = function() {
    return Object.freeze(datasources);
  };

  this.determineConnectionUrl = function (dsSelection) {
    var PREFIX = 'jdbc:';
    var driverName = dsSelection.driverName;

    return PREFIX + driverName + dsSelection.connectionUrl;
  };

  this.sendAddDatasource = function(payload) {
    return $http.post('/middleware_server/add_datasource', angular.toJson(payload));
  }
}

<commit_msg>Eliminate angular $q dependency injection if it is not needed by ng services now.<commit_after>ManageIQ.angular.app.service('mwAddDatasourceService', MwAddDatasourceService);

MwAddDatasourceService.$inject = ['$http'];

function MwAddDatasourceService($http) {
  var datasources = [
    {id: 'H2', label: 'H2', name: 'H2DS', jndiName: 'java:jboss/datasources/H2DS',
      driverName: 'h2', driverModuleName: 'com.h2database.h2', driverClass: 'org.h2.Driver',
      connectionUrl: ':mem:test;DB_CLOSE_DELAY=-1'},
    {id : 'POSTGRES', label: 'Postgres', name: 'PostgresDS', jndiName: 'java:jboss/datasources/PostgresDS',
      driverName: 'postresql', driverModuleName: 'org.postgresql', driverClass: 'org.postgresql.Driver',
      connectionUrl: '://localhost:5432/postgresdb'},
    {id: 'MSSQL', label: 'Microsoft SQL Server', name: 'MSSQLDS', jndiName: 'java:jboss/datasources/MSSQLDS',
      driverName: 'sqlserver', driverModuleName: 'com.microsoft',
      driverClass: 'com.microsoft.sqlserver.jdbc.SQLServerDriver',
      connectionUrl: '://localhost:1433;DatabaseName=MyDatabase'},
    {id: 'ORACLE', label: 'Oracle', name: 'OracleDS', jndiName: 'java:jboss/datasources/OracleDS',
      driverName: 'oracle', driverModuleName: 'com.oracle', driverClass: 'oracle.jdbc.driver.OracleDriver',
      connectionUrl: ':thin:@localhost:1521:oraclesid'},
    {id: 'DB2', label: 'IBM DB2', name: 'DB2DS', jndiName: 'java:jboss/datasources/DB2DS',
      driverName: 'ibmdb2', driverModuleName: 'com.ibm', driverClass: 'COM.ibm.db2.jdbc.app.DB2Driver',
      connectionUrl: '://db2'},
    {id: 'SYBASE', label: 'Sybase', name: 'SybaseDS', jndiName: 'java:jboss/datasources/SybaseDB',
      driverName: 'sybase', driverModuleName: 'com.sybase', driverClass: 'com.sybase.jdbc.SybDriver',
      connectionUrl: ':Tds:localhost:5000/mydatabase?JCONNECT_VERSION=6'},
     {id: 'MARIADB', label: 'MariaDB', name: 'MariaDBDS', jndiName: 'java:jboss/datasources/MariaDBDS',
       driverName: 'mariadb', driverModuleName: 'org.mariadb', driverClass: 'org.mariadb.jdbc.Driver',
       connectionUrl: '://localhost:3306/db_name'},
    {id: 'MYSQL', label: 'MySql', name: 'MySqlDS', jndiName: 'java:jboss/datasources/MySqlDS',
      driverName: 'mysql', driverModuleName: 'com.mysql', driverClass: 'com.mysql.jdbc.Driver',
      connectionUrl: '://localhost:3306/db_name'}
  ];

  this.getDatasources = function() {
    return Object.freeze(datasources);
  };

  this.determineConnectionUrl = function (dsSelection) {
    var PREFIX = 'jdbc:';
    var driverName = dsSelection.driverName;

    return PREFIX + driverName + dsSelection.connectionUrl;
  };

  this.sendAddDatasource = function(payload) {
    return $http.post('/middleware_server/add_datasource', angular.toJson(payload));
  }
}

<|endoftext|>


<commit_before>import React from 'react';
import { Link } from 'react-router';
import Project from '../components/Project/Project';
import Loading from '../components/shared/Loading';
import { getSettings } from '../settings';
import $ from 'jquery';
import _ from 'lodash';

const pivotalAPI = 'https://www.pivotaltracker.com/services/v5';

const ProjectContainer = React.createClass({
  getInitialState() {
    return {
      projectName: null,
      entries: null,
      error: false
    };
  },

  componentDidMount() {
    this.fetchData();
  },

  fetchData() {
    this.fetchProjectName().then(projectName => {
      this.fetchProjectMembers().then(projectMembers => {
        this.fetchStories().then(stories => {
          this.fetchPullRequests().then(pullRequests => {
            this.fetchCommits(pullRequests).then(pullRequestsWithCommits => {
              const entries = _.map(stories, story => {
                const commitsWithPivotalStoryId = _.filter(pullRequestsWithCommits, prCommits => {
                  const commitsHaveStoryId =
                    _(prCommits.commitMessages)
                      .filter(message => _.includes(message, story.id))
                      .any();
                  return commitsHaveStoryId;
                });

                const reviewUrls =
                  _(pullRequests)
                    .filter(pullRequest => {
                      const prIds = _.pluck(commitsWithPivotalStoryId, 'pullRequestId');
                      return _.includes(prIds, pullRequest.id);
                    })
                    .pluck('url')
                    .value();

                return (
                  {
                    title: story.name,
                    owners: _.map(story.ownerIds, id => {
                      let owner = _.find(projectMembers, 'id', id);
                      return owner ? owner.name : null;
                    }),
                    estimate: story.estimate,
                    reviewUrls,
                    trackerUrl: story.url,
                    state: _.isEmpty(reviewUrls) ? this.storyType(story) : 'Ready for Review',
                    type: story.type
                  }
                );
              });
              this.setState({ projectName, entries });
            });
          });
        });
      });
    });
  },

  storyType(story) {
    switch (story.state) {
    case 'unstarted':
    case 'planned':
      return 'Unstarted';

    case 'started':
    case 'rejected':
      return 'In Progress';

    case 'Ready for Review':
      return 'Ready for Review';

    case 'finished':
      return 'Merged';

    case 'delivered':
      return 'Delivered';

    case 'accepted':
      return 'Accepted';

    default:
      return story.state;
    }
  },

  fetchProjectName() {
    let { selectedPivotalProjectId, pivotalToken } = getSettings();
    return $.ajax({
      url: `${pivotalAPI}/projects/${selectedPivotalProjectId}`,
      method: 'GET',
      beforeSend: xhr => xhr.setRequestHeader('X-TrackerToken', pivotalToken)
    }).then(data =>
      data.name
    ).fail(() =>
      this.setState({ error: true })
    );
  },

  fetchStories() {
    let { selectedPivotalProjectId, pivotalToken } = getSettings();
    return $.ajax({
      url: `${pivotalAPI}/projects/${selectedPivotalProjectId}/iterations?scope=current`,
      method: 'GET',
      beforeSend: xhr => xhr.setRequestHeader('X-TrackerToken', pivotalToken)
    }).then(data =>
      _(data[0].stories)
        .filter(s => s.story_type !== 'release')
        .map(story => (
          {
            id: story.id,
            state: story.current_state,
            name: story.name,
            type: story.story_type,
            url: story.url,
            ownerIds: story.owner_ids,
            estimate: story.estimate
          }
        ))
        .value()
    ).fail(() => this.setState({ error: true }));
  },

  fetchPullRequests() {
    let { gitHubToken, selectedRepo } = getSettings();
    return new Promise(resolve => {
      if (selectedRepo !== null && selectedRepo !== undefined) {
        $.ajax({
          url: `https://api.github.com/repos/${selectedRepo}/pulls?state=open&access_token=${gitHubToken}`,
          method: 'GET'
        }).then(data =>
          resolve(
            _.map(data, pullRequest => (
              {
                id: pullRequest.id,
                url: pullRequest.html_url,
                commitsUrl: pullRequest.commits_url
              }
            ))
          )
        ).fail(() => {
          this.setState({ error: true });
          resolve();
        });
      } else {
        resolve();
      }
    });
  },

  fetchCommits(pullRequests) {
    let { gitHubToken } = getSettings();
    let urls = _.pluck(pullRequests, 'commitsUrl');
    let requests = _.map(urls, url =>
      $.ajax({
        url: `${url}?access_token=${gitHubToken}`,
        method: 'GET'
      })
    );
    return Promise.all(requests).then(data =>
      _.map(data, (commits, i) => (
        {
          pullRequestId: pullRequests[i].id,
          commitMessages: _(commits).pluck('commit').pluck('message').value()
        }
      ))
    );
  },

  fetchProjectMembers() {
    let { selectedPivotalProjectId, pivotalToken } = getSettings();
    return $.ajax({
      url: `${pivotalAPI}/projects/${selectedPivotalProjectId}/memberships`,
      method: 'GET',
      beforeSend: xhr => xhr.setRequestHeader('X-TrackerToken', pivotalToken)
    }).then(data =>
      _.map(data, item => ({ id: item.person.id, name: item.person.name }))
    ).fail(() => this.setState({ error: true }));
  },

  render() {
    let { projectName, entries, error } = this.state;
    let loading = (_.isEmpty(projectName) || _.isEmpty(entries)) && !error;
    const { selectedRepo } = getSettings();
    const hasSelectedRepo = (selectedRepo !== null && selectedRepo !== undefined);
    return (
      loading ? (
        <Loading />
      ) : (
        error ? (

Error fetching data.

            <Link to='settings'>Configure Settings</Link>

        ) : (
          <Project
            projectName={projectName}
            entries={entries}
            hasSelectedRepo={hasSelectedRepo} />
        )
      )
    );
  }
});

export default ProjectContainer;
<commit_msg>Fetch pull request statuses<commit_after>import React from 'react';
import { Link } from 'react-router';
import Project from '../components/Project/Project';
import Loading from '../components/shared/Loading';
import { getSettings } from '../settings';
import $ from 'jquery';
import _ from 'lodash';

const pivotalAPI = 'https://www.pivotaltracker.com/services/v5';

const ProjectContainer = React.createClass({
  getInitialState() {
    return {
      projectName: null,
      entries: null,
      error: false
    };
  },

  componentDidMount() {
    this.fetchData();
  },

  fetchData() {
    this.fetchProjectName().then(projectName => {
      this.fetchProjectMembers().then(projectMembers => {
        this.fetchStories().then(stories => {
          this.fetchPullRequests().then(pullRequests => {
            this.fetchCommits(pullRequests).then(pullRequestsWithCommits => {
              const entries = _.map(stories, story => {
                const commitsWithPivotalStoryId = _.filter(pullRequestsWithCommits, prCommits => {
                  const commitsHaveStoryId =
                    _(prCommits.commitMessages)
                      .filter(message => _.includes(message, story.id))
                      .any();
                  return commitsHaveStoryId;
                });
                const storyPullRequests =
                  _(pullRequests)
                    .filter(pullRequest => {
                      const prIds = _.pluck(commitsWithPivotalStoryId, 'pullRequestId');
                      return _.includes(prIds, pullRequest.id);
                    })
                    .map(pullRequest => ( {url:pullRequest.url, status: pullRequest.status}))
                    .value();

                return (
                  {
                    title: story.name,
                    owners: _.map(story.ownerIds, id => {
                      let owner = _.find(projectMembers, 'id', id);
                      return owner ? owner.name : null;
                    }),
                    estimate: story.estimate,
                    pullRequests: storyPullRequests,
                    trackerUrl: story.url,
                    state: _.isEmpty(storyPullRequests) ? this.storyType(story) : 'Ready for Review',
                    type: story.type
                  }
                );
              });
              this.setState({ projectName, entries });
            });
          });
        });
      });
    });
  },

  storyType(story) {
    switch (story.state) {
    case 'unstarted':
    case 'planned':
      return 'Unstarted';

    case 'started':
    case 'rejected':
      return 'In Progress';

    case 'Ready for Review':
      return 'Ready for Review';

    case 'finished':
      return 'Merged';

    case 'delivered':
      return 'Delivered';

    case 'accepted':
      return 'Accepted';

    default:
      return story.state;
    }
  },

  fetchProjectName() {
    let { selectedPivotalProjectId, pivotalToken } = getSettings();
    return $.ajax({
      url: `${pivotalAPI}/projects/${selectedPivotalProjectId}`,
      method: 'GET',
      beforeSend: xhr => xhr.setRequestHeader('X-TrackerToken', pivotalToken)
    }).then(data =>
      data.name
    ).fail(() =>
      this.setState({ error: true })
    );
  },

  fetchStories() {
    let { selectedPivotalProjectId, pivotalToken } = getSettings();
    return $.ajax({
      url: `${pivotalAPI}/projects/${selectedPivotalProjectId}/iterations?scope=current`,
      method: 'GET',
      beforeSend: xhr => xhr.setRequestHeader('X-TrackerToken', pivotalToken)
    }).then(data =>
      _(data[0].stories)
        .filter(s => s.story_type !== 'release')
        .map(story => (
          {
            id: story.id,
            state: story.current_state,
            name: story.name,
            type: story.story_type,
            url: story.url,
            ownerIds: story.owner_ids,
            estimate: story.estimate
          }
        ))
        .value()
    ).fail(() => this.setState({ error: true }));
  },

  fetchPullRequests() {
    let { gitHubToken, selectedRepo } = getSettings();
    return new Promise(resolve => {
      if (selectedRepo !== null && selectedRepo !== undefined) {
        $.ajax({
          url: `https://api.github.com/repos/${selectedRepo}/pulls?state=open&access_token=${gitHubToken}`,
          method: 'GET'
        }).then(data => {
          const pullRequestShas = data.map(pullRequest => pullRequest.head.sha);
          const statusRequests = pullRequestShas.map(sha => this.fetchPullRequestStatuses(sha));
          Promise.all(statusRequests).then(statuses => {
            const pullRequestData = data.map((pullRequest, i) => {
              return ({
                id: pullRequest.id,
                url: pullRequest.html_url,
                commitsUrl: pullRequest.commits_url,
                status: statuses[i]
              });
            });
            resolve(pullRequestData);
          });
        }).fail(() => {
          this.setState({ error: true });
          resolve();
        });
      } else {
        resolve();
      }
    });
  },

  fetchPullRequestStatuses(sha) {
    let { selectedRepo } = getSettings();
    return new Promise(resolve => {
      if (selectedRepo !== null && selectedRepo !== undefined) {
        $.ajax({
          url: `https://api.github.com/repos/${selectedRepo}/commits/${sha}/statuses`,
          method: 'GET'
        }).then(data => {
          const state = data.length === 0 ? null : data[0].state;
          resolve(state);  // return only the first (most recent) commit status
        }).fail(() => {
          this.setState({ error: true });
          resolve();
        });
      } else {
        resolve();
      }
    });
  },

  fetchCommits(pullRequests) {
    let { gitHubToken } = getSettings();
    let urls = _.pluck(pullRequests, 'commitsUrl');
    let requests = _.map(urls, url =>
      $.ajax({
        url: `${url}?access_token=${gitHubToken}`,
        method: 'GET'
      })
    );
    return Promise.all(requests).then(data =>
      _.map(data, (commits, i) => (
        {
          pullRequestId: pullRequests[i].id,
          commitMessages: _(commits).pluck('commit').pluck('message').value()
        }
      ))
    );
  },

  fetchProjectMembers() {
    let { selectedPivotalProjectId, pivotalToken } = getSettings();
    return $.ajax({
      url: `${pivotalAPI}/projects/${selectedPivotalProjectId}/memberships`,
      method: 'GET',
      beforeSend: xhr => xhr.setRequestHeader('X-TrackerToken', pivotalToken)
    }).then(data =>
      _.map(data, item => ({ id: item.person.id, name: item.person.name }))
    ).fail(() => this.setState({ error: true }));
  },

  render() {
    let { projectName, entries, error } = this.state;
    let loading = (_.isEmpty(projectName) || _.isEmpty(entries)) && !error;
    const { selectedRepo } = getSettings();
    const hasSelectedRepo = (selectedRepo !== null && selectedRepo !== undefined);
    return (
      loading ? (
        <Loading />
      ) : (
        error ? (

Error fetching data.

            <Link to='settings'>Configure Settings</Link>

        ) : (
          <Project
            projectName={projectName}
            entries={entries}
            hasSelectedRepo={hasSelectedRepo} />
        )
      )
    );
  }
});

export default ProjectContainer;
<|endoftext|>