<commit_before>/*
 * Copyright 2016 Technische Universitaet Darmstadt
 *
 *  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.
 */

define([
    'angular',
    'highcharts',
    'ngHighcharts',
    'drilldown',
    'angularMoment',
    'bootstrap'
], function (angular) {
    'use strict';

    angular.module('myApp.chart', ['play.routing', 'highcharts-ng', 'angularMoment', 'myApp.source', 'myApp.chartconfig', 'myApp.sourcefactory']);
    angular.module('myApp.chart').controller('ChartController', ['$scope', '$compile', '$timeout', 'playRoutes', 'moment', 'appData', 'sourceShareService', 'util', 'chartConfig','ObserverService',
        function ($scope, $compile, $timeout, playRoutes, moment, appData, sourceShareService, util, chartConfig, ObserverService) {

            /*
             There is an issue with the bar chart: Sometimes the document count is 0 which cannot be plotted.
             A workaround is to set these 0 values to null which is done in the getDrilldown() method.
             */
            var PSEUDO_ZERO_VALUE = null;

            $scope.loadedDocuments = {};

            $scope.observer = ObserverService;

            $scope.observer_subscribe = function(history) { $scope.history = history};
            $scope.observer.subscribeHistory($scope.observer_subscribe, "timeline");

            /**
             * We use this wrapper in order to override the drilldown method. This is necessary
             * because we don't want to drilldown on a bar click. Instead, the bar click fetches
             * documents of the clicked time range.
             * When clicking the corresponding labels, however, drilldown will be executed
             */
            (function (H) {
                H.wrap(H.Point.prototype, 'doDrilldown', function (p, hold, x) {
                    var UNDEFINED;
                    // x is defined when clicked on a category
                    if (x !== UNDEFINED) {
                        p.call(this, hold, x);
                    } else {
                        fetchDocumentsForRange(this.options.drilldown.toString());
                    }
                });
            })(Highcharts);

            /**
             * This function is used for initially fetching the first n documents which belong to
             * the selected time range. All further document fetching will be done in the document
             * list via the corresponding button.
             *
             * @param range - The range delivers the information for which time frame data
             * shall be loaded (e. g. can be values like '1970-1979', '1970', 'Jan 1980').
             */
            function fetchDocumentsForRange(range) {
                /*
                 First, identify, whether a decade, a year or a month bar was clicked
                 and build the criterion on the fly.
                 */
                var decadeRexExp = new RegExp('^[0-9]{4}-[0-9]{4}$');
                var yearRexExp = new RegExp('^[0-9]{4}$');
                var monthRexExp = new RegExp('^([a-zA-Z0-9_-]){3,5} [0-9]{4}$');
                var dayRexExp = new RegExp('^[0-9]{1,2}.[0-9]{1,2}.[0-9]{4}$');
                // sourceShareService.documentListInfo = 'Documents for ' + range;
                // Check if a decade was clicked
                if (range.match(decadeRexExp)) {
                    sourceShareService.fromYear = parseInt(range.substring(0, 4));
                    sourceShareService.toYear = parseInt(range.substring(5, 9));
                    // Retrieve the documents. First, however, reset the sourceShareService
                    sourceShareService.reset(sourceShareService.CATEGORY_DECADE);
                    //sourceShareService.fetchNextDocs();
                }
                // Check if a year was clicked
                else if (range.match(yearRexExp)) {
                    sourceShareService.fromYear = range.match(yearRexExp)[0];
                    // Retrieve the documents
                    sourceShareService.reset(sourceShareService.CATEGORY_YEAR);
                    //sourceShareService.fetchNextDocs();
                }
                // Check if a month was clicked
                else if (range.match(monthRexExp)) {
                    var posOfSpace = range.indexOf(' ');
                    var monthAbbreviation = range.substring(0, posOfSpace);
                    sourceShareService.fromYear = range.substring(posOfSpace + 1, range.length);
                    // +1 because the backend expects January to be 1
                    sourceShareService.month = monthAbbreviations.indexOf(monthAbbreviation) + 1;
                    // Retrieve the documents
                    sourceShareService.reset(sourceShareService.CATEGORY_MONTH);
                    //sourceShareService.fetchNextDocs();
                }
                // Check if a day was clicked
                else if (range.match(dayRexExp)) {
                    // This is a hack to get the right day out of moment; without the "12", DST breaks the date
                    var day = moment(range + " 12", "D.M.YYYY H").unix();
                    sourceShareService.day = day;
                    sourceShareService.reset(sourceShareService.CATEGORY_DAY);
                    //sourceShareService.fetchNextDocs();
                }

                //put click to history
                $scope.observer.addItem({
                    type: 'time',
                    data: {
                        name: range
                    }
                });
            }

            /*
             The click on a label above a bar. I (Patrick) did not find a way to implement
             the click event using Highcharts. Thus, this solution is a little bit cumbersome
             because first, the corresponding label below the bar has to be found, then the
             text (time range) extracted and only then can the documents be fetched.
             */
            $(document).on('click', '#chartBarchart .stack-label', function () {
                // + 1 because nth-child is 1-based
                var x = parseInt($(this).attr('data-x')) + 1;
                var range = $("#chartBarchart .highcharts-xaxis-labels text:nth-child(" + x + ")")[0].childNodes[0];
                // We have to handle decade / year and month / day differently, as month / day are within
                // an additional tspan tag; this is for year / month
                if (range.data != undefined) {
                    range = range.data;
                }
                // For month / day
                else {
                    range = range.innerHTML;
                }
                fetchDocumentsForRange(range);

            });

            // set language related options
            Highcharts.setOptions(chartConfig.highchartsOptions);

            // set general options for the chart
            $scope.chartConfig = chartConfig.chartConfig;

            /**
             * This function loads the data with the amount of documents and
             * creates a bar chart that represents this data.
             */
            function loadAndDrawChart() {
                playRoutes.controllers.DocumentController.getFrequencySeries().get().then(function (response) {
                    var documentData = countDocuments(response.data);
                    $scope.chartConfig.series = [{
                        name: "Kissinger Cables",
                        data: getSeriesData(documentData)
                    }];
                    $scope.chartConfig.options.drilldown = getDrilldown(documentData, "Kissinger Cables");
                });
            }

            /**
             * This function creates the data for the initial barchart.
             *
             * @param countDocuments - The result of the function countDocuments.
             * @return The data for the initial bar chart.
             */
            function getSeriesData(countDocuments) {
                var seriesData = [];
                for (var i = 0; i < countDocuments.length; i++) {
                    seriesData.push({
                        name: countDocuments[i].name,
                        y: countDocuments[i].y,
                        drilldown: countDocuments[i].name
                    });
                }
                return seriesData;
            }

            /**
             * This function creates the drilldown with the given data.
             *
             * @param countDocuments - The result of the function countDocuments.
             * @param {String} name - The name of the series.
             * @return The drilldown for the bar chart.
             */
            function getDrilldown(countDocuments, name) {
                var drilldown = {
                    series: []
                };
                // Iterate over decades.
                for (var a = 0; a < countDocuments.length; a++) {
                    drilldown.series.push({
                        id: countDocuments[a].name,
                        name: name + ' ' + countDocuments[a].name,
                        data: countDocuments[a].data
                    });
                    // Iterate over years.
                    for (var b = 0; b < countDocuments[a].data.length; b++) {
                        var nameB = countDocuments[a].data[b].name;
                        if (countDocuments[a].data[b].y == 0) {
                            countDocuments[a].data[b].drilldown = null;
                            // Replace 0 with null (see comment above PSEUDO_ZERO_VALUE)
                            countDocuments[a].data[b].y = PSEUDO_ZERO_VALUE;
                        }
                        drilldown.series.push({
                            id: nameB,
                            name: name + ' ' + nameB,
                            data: countDocuments[a].subdata[b].data
                        });
                        // Iterate over months.
                        for (var c = 0; c < countDocuments[a].subdata[b].data.length; c++) {
                            var nameC = countDocuments[a].subdata[b].data[c].name;
                            if (countDocuments[a].subdata[b].data[c].y == 0) {
                                countDocuments[a].subdata[b].data[c].drilldown = null;
                                countDocuments[a].subdata[b].data[c].y = PSEUDO_ZERO_VALUE;  // Replace 0 with null
                            }
                            drilldown.series.push({
                                id: nameC,
                                name: name + ' ' + nameC,
                                data: countDocuments[a].subdata[b].subdata[c].data,
                                point: {
                                    events: {
                                        click: function () {
                                            fetchDocumentsForRange(this.series.data[this.x].name);
                                        },
                                    }
                                }
                            });
                            // Replace 0 with null
                            for (var i = 0; i < countDocuments[a].subdata[b].subdata[c].data.length; i++) {
                                if (countDocuments[a].subdata[b].subdata[c].data[i].y == 0) {
                                    countDocuments[a].subdata[b].subdata[c].data[i].y = PSEUDO_ZERO_VALUE;
                                }
                            }
                        }
                    }
                }
                return drilldown;
            }

            /**
             * This function returns the amount of days the month 'month' in the
             * year 'year' has.
             *
             * @param {Number} month - The month. A number from the set [1,12].
             * @param {Number} year - The year.
             * @return The amount of days the given month has in the given year.
             */
            function daysInMonth(month, year) {
                return new Date(year, month, 0).getDate();
            }

            /**
             * This function counts how many documents in the given data are on
             * which decade, year, month and day.
             *
             * @param data - An array containing arrays which contain the time
             *               in milliseconds and the amount of documents at this
             *               time.
             * @return A structur that contains the amount of documents on the
             *         decades, years, months and days.
             */
            function countDocuments(data) {
                var documentCount = [];
                var firstDecade = getDecade(data[0][0]);
                var numberOfdecades = (getDecade(data[data.length - 1][0]) - firstDecade) / 10;
                // Iterate over all decades, years, months and days and set
                // the amount of documents to 0.
                for (var decade = 0; decade <= numberOfdecades; decade++) {
                    // Push decade.
                    documentCount.push({
                        name: (firstDecade + 10 * decade) + '-' + (firstDecade + 9 + 10 * decade),
                        y: 0,
                        data: [],
                        subdata: []
                    });
                    for (var year = 0; year < 10; year++) {
                        // Push year.
                        documentCount[decade].data.push({
                            name: firstDecade + 10 * decade + year,
                            y: 0,
                            drilldown: firstDecade + 10 * decade + year
                        });
                        documentCount[decade].subdata.push({
                            data: [],
                            subdata: []
                        })
                        for (var month = 0; month < 12; month++) {
                            // Push month.
                            documentCount[decade].subdata[year].data.push({
                                name: chartConfig.monthAbbreviations[month] + ' ' + (firstDecade + 10 * decade + year),
                                y: 0,
                                drilldown: chartConfig.monthAbbreviations[month] + ' ' + (firstDecade + 10 * decade + year)
                            });
                            documentCount[decade].subdata[year].subdata.push({
                                data: [],
                                subdata: []
                            });
                            var numberOfDays = daysInMonth(month + 1, year);
                            for (var day = 0; day < numberOfDays; day++) {
                                // Push day.
                                documentCount[decade].subdata[year].subdata[month].data.push({
                                    name: (day + 1) + '.' + (month + 1) + '.' + (firstDecade + 10 * decade + year),
                                    y: 0
                                });
                            }

                        }
                    }
                }
                // Insert the amount of documents into documentCount.
                for (var i = 0; i < data.length; i++) {
                    var docs = data[i][1];
                    var date = new Date(data[i][0]);
                    var year = date.getFullYear();
                    var decade = year - (year % 10);
                    var decadeIndex = (decade - firstDecade) / 10;
                    var month = date.getMonth();  // Element of [0,11].
                    var day = date.getDate();  // Element of [1,31].
                    documentCount[decadeIndex].y += docs;
                    documentCount[decadeIndex].data[year - decade].y += docs;
                    documentCount[decadeIndex].subdata[year - decade].data[month].y += docs;
                    documentCount[decadeIndex].subdata[year - decade].subdata[month].data[day - 1].y += docs;
                }
                return documentCount;
            }

            /**
             * This function returns the decade (the year the decade starts)
             * from the given date. The date is in unix time * 1000.
             *
             * @param {Number} date - The date which decade is requested.
             * @return The decade (the year it starts) of the given date.
             */
            function getDecade(date) {
                var d = new Date(date);
                d = d.getFullYear() - (d.getFullYear() % 10);
                return d;
            }

            // draw the chart
            loadAndDrawChart();

        }])
    ;
})
;<commit_msg>removed unused time filter code<commit_after>/*
 * Copyright 2016 Technische Universitaet Darmstadt
 *
 *  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.
 */

define([
    'angular',
    'highcharts',
    'ngHighcharts',
    'drilldown',
    'angularMoment',
    'bootstrap'
], function (angular) {
    'use strict';

    angular.module('myApp.chart', ['play.routing', 'highcharts-ng', 'angularMoment', 'myApp.source', 'myApp.chartconfig', 'myApp.sourcefactory']);
    angular.module('myApp.chart').controller('ChartController', ['$scope', '$compile', '$timeout', 'playRoutes', 'moment', 'appData', 'sourceShareService', 'util', 'chartConfig','ObserverService',
        function ($scope, $compile, $timeout, playRoutes, moment, appData, sourceShareService, util, chartConfig, ObserverService) {

            /*
             There is an issue with the bar chart: Sometimes the document count is 0 which cannot be plotted.
             A workaround is to set these 0 values to null which is done in the getDrilldown() method.
             */
            var PSEUDO_ZERO_VALUE = null;

            $scope.loadedDocuments = {};

            $scope.observer = ObserverService;

            $scope.observer_subscribe = function(history) { $scope.history = history};
            $scope.observer.subscribeHistory($scope.observer_subscribe, "timeline");

            /**
             * We use this wrapper in order to override the drilldown method. This is necessary
             * because we don't want to drilldown on a bar click. Instead, the bar click fetches
             * documents of the clicked time range.
             * When clicking the corresponding labels, however, drilldown will be executed
             */
            (function (H) {
                H.wrap(H.Point.prototype, 'doDrilldown', function (p, hold, x) {
                    var UNDEFINED;
                    // x is defined when clicked on a category
                    if (x !== UNDEFINED) {
                        p.call(this, hold, x);
                    } else {
                        addTimeFilter(this.options.drilldown.toString());
                    }
                });
            })(Highcharts);

            /**
             * Add time range filter to observer
             *
             * @param range - The range delivers the information for which time frame data
             * shall be loaded (e. g. can be values like '1970-1979', '1970', 'Jan 1980').
             */
            function addTimeFilter(range) {
                $scope.observer.addItem({
                    type: 'time',
                    data: {
                        name: range
                    }
                });
            }

            /*
             The click on a label above a bar. I (Patrick) did not find a way to implement
             the click event using Highcharts. Thus, this solution is a little bit cumbersome
             because first, the corresponding label below the bar has to be found, then the
             text (time range) extracted and only then can the documents be fetched.
             */
            $(document).on('click', '#chartBarchart .stack-label', function () {
                // + 1 because nth-child is 1-based
                var x = parseInt($(this).attr('data-x')) + 1;
                var range = $("#chartBarchart .highcharts-xaxis-labels text:nth-child(" + x + ")")[0].childNodes[0];
                // We have to handle decade / year and month / day differently, as month / day are within
                // an additional tspan tag; this is for year / month
                if (range.data != undefined) {
                    range = range.data;
                }
                // For month / day
                else {
                    range = range.innerHTML;
                }
                addTimeFilter(range);

            });

            // set language related options
            Highcharts.setOptions(chartConfig.highchartsOptions);

            // set general options for the chart
            $scope.chartConfig = chartConfig.chartConfig;

            /**
             * This function loads the data with the amount of documents and
             * creates a bar chart that represents this data.
             */
            function loadAndDrawChart() {
                playRoutes.controllers.DocumentController.getFrequencySeries().get().then(function (response) {
                    var documentData = countDocuments(response.data);
                    $scope.chartConfig.series = [{
                        name: "Kissinger Cables",
                        data: getSeriesData(documentData)
                    }];
                    $scope.chartConfig.options.drilldown = getDrilldown(documentData, "Kissinger Cables");
                });
            }

            /**
             * This function creates the data for the initial barchart.
             *
             * @param countDocuments - The result of the function countDocuments.
             * @return The data for the initial bar chart.
             */
            function getSeriesData(countDocuments) {
                var seriesData = [];
                for (var i = 0; i < countDocuments.length; i++) {
                    seriesData.push({
                        name: countDocuments[i].name,
                        y: countDocuments[i].y,
                        drilldown: countDocuments[i].name
                    });
                }
                return seriesData;
            }

            /**
             * This function creates the drilldown with the given data.
             *
             * @param countDocuments - The result of the function countDocuments.
             * @param {String} name - The name of the series.
             * @return The drilldown for the bar chart.
             */
            function getDrilldown(countDocuments, name) {
                var drilldown = {
                    series: []
                };
                // Iterate over decades.
                for (var a = 0; a < countDocuments.length; a++) {
                    drilldown.series.push({
                        id: countDocuments[a].name,
                        name: name + ' ' + countDocuments[a].name,
                        data: countDocuments[a].data
                    });
                    // Iterate over years.
                    for (var b = 0; b < countDocuments[a].data.length; b++) {
                        var nameB = countDocuments[a].data[b].name;
                        if (countDocuments[a].data[b].y == 0) {
                            countDocuments[a].data[b].drilldown = null;
                            // Replace 0 with null (see comment above PSEUDO_ZERO_VALUE)
                            countDocuments[a].data[b].y = PSEUDO_ZERO_VALUE;
                        }
                        drilldown.series.push({
                            id: nameB,
                            name: name + ' ' + nameB,
                            data: countDocuments[a].subdata[b].data
                        });
                        // Iterate over months.
                        for (var c = 0; c < countDocuments[a].subdata[b].data.length; c++) {
                            var nameC = countDocuments[a].subdata[b].data[c].name;
                            if (countDocuments[a].subdata[b].data[c].y == 0) {
                                countDocuments[a].subdata[b].data[c].drilldown = null;
                                countDocuments[a].subdata[b].data[c].y = PSEUDO_ZERO_VALUE;  // Replace 0 with null
                            }
                            drilldown.series.push({
                                id: nameC,
                                name: name + ' ' + nameC,
                                data: countDocuments[a].subdata[b].subdata[c].data,
                                point: {
                                    events: {
                                        click: function () {
                                            addTimeFilter(this.series.data[this.x].name);
                                        },
                                    }
                                }
                            });
                            // Replace 0 with null
                            for (var i = 0; i < countDocuments[a].subdata[b].subdata[c].data.length; i++) {
                                if (countDocuments[a].subdata[b].subdata[c].data[i].y == 0) {
                                    countDocuments[a].subdata[b].subdata[c].data[i].y = PSEUDO_ZERO_VALUE;
                                }
                            }
                        }
                    }
                }
                return drilldown;
            }

            /**
             * This function returns the amount of days the month 'month' in the
             * year 'year' has.
             *
             * @param {Number} month - The month. A number from the set [1,12].
             * @param {Number} year - The year.
             * @return The amount of days the given month has in the given year.
             */
            function daysInMonth(month, year) {
                return new Date(year, month, 0).getDate();
            }

            /**
             * This function counts how many documents in the given data are on
             * which decade, year, month and day.
             *
             * @param data - An array containing arrays which contain the time
             *               in milliseconds and the amount of documents at this
             *               time.
             * @return A structur that contains the amount of documents on the
             *         decades, years, months and days.
             */
            function countDocuments(data) {
                var documentCount = [];
                var firstDecade = getDecade(data[0][0]);
                var numberOfdecades = (getDecade(data[data.length - 1][0]) - firstDecade) / 10;
                // Iterate over all decades, years, months and days and set
                // the amount of documents to 0.
                for (var decade = 0; decade <= numberOfdecades; decade++) {
                    // Push decade.
                    documentCount.push({
                        name: (firstDecade + 10 * decade) + '-' + (firstDecade + 9 + 10 * decade),
                        y: 0,
                        data: [],
                        subdata: []
                    });
                    for (var year = 0; year < 10; year++) {
                        // Push year.
                        documentCount[decade].data.push({
                            name: firstDecade + 10 * decade + year,
                            y: 0,
                            drilldown: firstDecade + 10 * decade + year
                        });
                        documentCount[decade].subdata.push({
                            data: [],
                            subdata: []
                        })
                        for (var month = 0; month < 12; month++) {
                            // Push month.
                            documentCount[decade].subdata[year].data.push({
                                name: chartConfig.monthAbbreviations[month] + ' ' + (firstDecade + 10 * decade + year),
                                y: 0,
                                drilldown: chartConfig.monthAbbreviations[month] + ' ' + (firstDecade + 10 * decade + year)
                            });
                            documentCount[decade].subdata[year].subdata.push({
                                data: [],
                                subdata: []
                            });
                            var numberOfDays = daysInMonth(month + 1, year);
                            for (var day = 0; day < numberOfDays; day++) {
                                // Push day.
                                documentCount[decade].subdata[year].subdata[month].data.push({
                                    name: (day + 1) + '.' + (month + 1) + '.' + (firstDecade + 10 * decade + year),
                                    y: 0
                                });
                            }

                        }
                    }
                }
                // Insert the amount of documents into documentCount.
                for (var i = 0; i < data.length; i++) {
                    var docs = data[i][1];
                    var date = new Date(data[i][0]);
                    var year = date.getFullYear();
                    var decade = year - (year % 10);
                    var decadeIndex = (decade - firstDecade) / 10;
                    var month = date.getMonth();  // Element of [0,11].
                    var day = date.getDate();  // Element of [1,31].
                    documentCount[decadeIndex].y += docs;
                    documentCount[decadeIndex].data[year - decade].y += docs;
                    documentCount[decadeIndex].subdata[year - decade].data[month].y += docs;
                    documentCount[decadeIndex].subdata[year - decade].subdata[month].data[day - 1].y += docs;
                }
                return documentCount;
            }

            /**
             * This function returns the decade (the year the decade starts)
             * from the given date. The date is in unix time * 1000.
             *
             * @param {Number} date - The date which decade is requested.
             * @return The decade (the year it starts) of the given date.
             */
            function getDecade(date) {
                var d = new Date(date);
                d = d.getFullYear() - (d.getFullYear() % 10);
                return d;
            }

            // draw the chart
            loadAndDrawChart();

        }])
    ;
})
;<|endoftext|>


<commit_before>var express = require('express'),
    path    = require('path'),
   	fs		= require('fs');

function JSONAuth(filePath) {
    var userList = null;

    filePath = path.join(process.cwd(), filePath || 'user.json');

    if (!fs.existsSync(filePath)) {
    	throw new Error('File ' + filePath + ' not found!');
    }

    userList = require(filePath);

    return JSONAuth.plain(userList);
}

JSONAuth.plain = function (list) {
    return express.basicAuth(function (user, passwd) {
        return list[user] && passwd === list[user];
    });
}

module.exports = JSONAuth;
<commit_msg>fix tabulation<commit_after>var express = require('express'),
    path    = require('path'),
    fs      = require('fs');

function JSONAuth(filePath) {
    var userList = null;

    filePath = path.join(process.cwd(), filePath || 'user.json');

    if (!fs.existsSync(filePath)) {
        throw new Error('File ' + filePath + ' not found!');
    }

    userList = require(filePath);

    return JSONAuth.plain(userList);
}

JSONAuth.plain = function (list) {
    return express.basicAuth(function (user, passwd) {
        return list[user] && passwd === list[user];
    });
}

module.exports = JSONAuth;
<|endoftext|>


<commit_before>/*
 * Create references
 */
var gulp = require('gulp');
var glob = require('glob');
var pkg = require('./package.json');
var common = require('./common.js');

/************************
 * Auto load all gulp plugins
 ************************/
var gulpLoadPlugins = require("gulp-load-plugins");
var plug = gulpLoadPlugins();

/************************
 * Load common utilities for gulp
 ************************/
var gutil = plug.loadUtils(['colors', 'env', 'log', 'date']);

/************************
 * Could use a staging/development switch.
 * Run `gulp --staging`
 ************************/
var type = gutil.env.staging ? 'staging' : 'development';
gutil.log('Building for', gutil.colors.magenta(type));
gutil.beep();

/************************
 * Lint the code
 ************************/
gulp.task('jshint', function () {
    return gulp.src(pkg.paths.js)
        .pipe(plug.jshint('.jshintrc'))
//        .pipe(plug.jshint.reporter('default'));
        .pipe(plug.jshint.reporter('jshint-stylish'));
});

/************************
 * Create $templateCache from the html templates
 ************************/
gulp.task('templatecache', function () {
    gulp.src(pkg.paths.htmltemplates)
        .pipe(plug.angularTemplatecache('templates.js', {
            module: 'app.core',
            standalone: false,
            root: 'app/'
        }))
        .pipe(gulp.dest(pkg.paths.dev));
});

/************************
 * Minify and bundle the JavaScript
 ************************/
gulp.task('js', ['jshint', 'templatecache'], function () {
    var source = [].concat(pkg.paths.js, pkg.paths.dev + 'templates.js');
    return gulp.src(source)
        .pipe(plug.size({showFiles: true}))
        .pipe(plug.sourcemaps.init())

        // Annotate before uglify so the code get's min'd properly.
        .pipe(plug.ngAnnotate({
            // true helps add where @ngInject is not used. It infers.
            // Doesn't work with resolve, must be explicit there
            add: true
        }))
        .pipe(plug.uglify({
//            sourceMap: true,
//            banner: '/*! <%= pkg.name %> <%= gutil.date("mmm d, yyyy h:MM:ss TT Z") %> */\n',
            mangle: true
        }))
        .pipe(plug.concat('all.min.js', {newLine: ';'}))
        .pipe(plug.sourcemaps.write('./'))
        .pipe(plug.header(commentHeader))
        .pipe(gulp.dest(pkg.paths.dev))
        .pipe(plug.size({showFiles: true}));
});

/************************
 * Copy the Vendor JavaScript
 ************************/
gulp.task('vendorjs', function () {
    var source = [].concat(pkg.paths.vendorjs,
        pkg.paths.vendorjs.map(function (path) {
            return path + '.map';
        }));
    source.push('../client/components/jquery/dist/jquery.min.map');
//    console.log(source);
    return gulp.src(source)
        .pipe(gulp.dest(pkg.paths.dev + 'vendor'));
});

/************************
 * Minify and bundle the CSS
 ************************/
gulp.task('css', function () {
    return gulp.src(pkg.paths.css)
//        .pipe(plug.size({showFiles: true}))
        .pipe(plug.concat('all.min.css')) // Before bytediff or after
        .pipe(plug.bytediff.start())
        .pipe(plug.minifyCss({}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
//        .pipe(plug.concat('all.min.css')) // Before bytediff or after
        .pipe(gulp.dest(pkg.paths.dev + 'content'));
//        .pipe(plug.size({showFiles: true}));
});

/************************
 * Minify and bundle the Vendor CSS
 ************************/
gulp.task('vendorcss', function () {
    return gulp.src(pkg.paths.vendorcss)
        .pipe(plug.concat('vendor.min.css'))
        .pipe(plug.bytediff.start())
        .pipe(plug.minifyCss({}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(gulp.dest(pkg.paths.dev + 'content'));
});

/************************
 * Copy fonts
 ************************/
gulp.task('fonts', function () {
    return gulp.src(pkg.paths.fonts)
        .pipe(gulp.dest(pkg.paths.dev + 'fonts'));
});

/************************
 * Compress images
 ************************/
gulp.task('images', function () {
    return gulp.src(pkg.paths.images)
        .pipe(plug.cache(plug.imagemin({optimizationLevel: 3})))
        .pipe(gulp.dest(pkg.paths.dev + 'content/images'));
});

/************************
 * Inject all the files into the new index.html
 ************************/
gulp.task('htmlinject', ['js', 'vendorjs', 'css', 'vendorcss', 'images', 'fonts'], function () {
    var target = gulp.src('../client/index.html');
    var v = pkg.paths.vendorjssequence.map(function (file) {
        return pkg.paths.dev + 'vendor/' + file;
    });
    var sources = {
        css: gulp.src([pkg.paths.dev + 'content/all.min.css'], {read: false}),
        vendorcss: gulp.src([pkg.paths.dev + 'content/vendor.min.css'], {read: false}),
        js: gulp.src([pkg.paths.dev + 'all.min.js']),
        vendorjs: gulp.src(v)
    };
    var ignorePath = '/../client';

    target
//        .pipe(plug.rename('index.html'))
        .pipe(plug.inject(sources.vendorcss, {starttag: '<!-- inject:vendor:{{ext}} -->', ignorePath: ignorePath}))
        .pipe(plug.inject(sources.css, {ignorePath: ignorePath}))
        .pipe(plug.inject(sources.js, {ignorePath: ignorePath}))
        .pipe(plug.inject(sources.vendorjs, {starttag: '<!-- inject:vendor:{{ext}} -->', ignorePath: ignorePath}))
//        .pipe(gulp.dest('../client/'));
        .pipe(gulp.dest(pkg.paths.dev));
});

/************************
 * Bundle the JS, CSS, and compress images.
 * Then copy files to dev and show a toast.
 ************************/
gulp.task('default', ['htmlinject'], function () {
    // Prepare files for dev
    return gulp.src(pkg.paths.dev)
        .pipe(plug.notify({
            onLast: true,
            message: "linted, bundled, and images compressed!"
        }));
});

/************************
 * Bundle the JS, CSS, and compress images.
 * Then copy files to staging and show a toast.
 ************************/
gulp.task('stage', ['default'], function () {
    // Copy the files to staging
    return gulp.src(pkg.paths.dev)
        .pipe(gulp.dest(pkg.paths.stage))
        // Notify we are done
        .pipe(plug.notify({
            onLast: true,
            message: "staged!"
        }));
});

/************************
 * Remove all files from the output folder
 ************************/
gulp.task('cleanOutput', function () {
    return gulp.src([
        pkg.paths.dev,
        pkg.paths.stage
    ])
        .pipe(plug.clean({force: true}));
});

/************************
 * Watch js files
 ************************/
gulp.task('watchjs', function () {
    var js = ['gulpfile.js'].concat(pkg.paths.js);
    var watcher = gulp.watch(js, ['js', 'vendorjs']);

    watcher.on('change', function (event) {
        console.log('*** File ' + event.path + ' was ' + event.type + ', running tasks...');
    });
});

/************************
 * Watch css files
 ************************/
gulp.task('watchcss', function () {
    var css = ['gulpfile.js'].concat(pkg.paths.css, pkg.paths.vendorcss);
    var watcher = gulp.watch(css, ['css', 'vendorcss']);

    watcher.on('change', function (event) {
        console.log('*** File ' + event.path + ' was ' + event.type + ', running tasks...');
    });
});

/************************
 * Watch all files
 ************************/
gulp.task('watch', ['watchcss', 'watchjs'], function () {
});<commit_msg>modular: fixed source map and added sizing using bytediff for js<commit_after>/*
 * Create references
 */
var gulp = require('gulp');
var glob = require('glob');
var pkg = require('./package.json');
var common = require('./common.js');

/************************
 * Auto load all gulp plugins
 ************************/
var gulpLoadPlugins = require("gulp-load-plugins");
var plug = gulpLoadPlugins();

/************************
 * Load common utilities for gulp
 ************************/
var gutil = plug.loadUtils(['colors', 'env', 'log', 'date']);

/************************
 * Could use a staging/development switch.
 * Run `gulp --staging`
 ************************/
var type = gutil.env.staging ? 'staging' : 'development';
gutil.log('Building for', gutil.colors.magenta(type));
gutil.beep();

/************************
 * Lint the code
 ************************/
gulp.task('jshint', function () {
    return gulp.src(pkg.paths.js)
        .pipe(plug.jshint('.jshintrc'))
//        .pipe(plug.jshint.reporter('default'));
        .pipe(plug.jshint.reporter('jshint-stylish'));
});

/************************
 * Create $templateCache from the html templates
 ************************/
gulp.task('templatecache', function () {
    gulp.src(pkg.paths.htmltemplates)
        .pipe(plug.angularTemplatecache('templates.js', {
            module: 'app.core',
            standalone: false,
            root: 'app/'
        }))
        .pipe(gulp.dest(pkg.paths.dev));
});

/************************
 * Minify and bundle the JavaScript
 ************************/
gulp.task('js', ['jshint', 'templatecache'], function () {
    var source = [].concat(pkg.paths.js, pkg.paths.dev + 'templates.js');
    return gulp.src(source)
//        .pipe(plug.size({showFiles: true}))
        .pipe(plug.sourcemaps.init())
        .pipe(plug.concat('all.min.js', {newLine: ';'}))
        // Annotate before uglify so the code get's min'd properly.
        .pipe(plug.ngAnnotate({
            // true helps add where @ngInject is not used. It infers.
            // Doesn't work with resolve, so we must be explicit there
            add: true
        }))
        .pipe(plug.bytediff.start())
        .pipe(plug.uglify({mangle: true}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(plug.sourcemaps.write('./'))
        .pipe(gulp.dest(pkg.paths.dev));
//        .pipe(plug.size({showFiles: true}));
});

/************************
 * Copy the Vendor JavaScript
 ************************/
gulp.task('vendorjs', function () {
    var source = [].concat(pkg.paths.vendorjs,
        pkg.paths.vendorjs.map(function (path) {
            return path + '.map';
        }));
    source.push('../client/components/jquery/dist/jquery.min.map');
//    console.log(source);
    return gulp.src(source)
        .pipe(gulp.dest(pkg.paths.dev + 'vendor'));
});

/************************
 * Minify and bundle the CSS
 ************************/
gulp.task('css', function () {
    return gulp.src(pkg.paths.css)
//        .pipe(plug.size({showFiles: true}))
        .pipe(plug.concat('all.min.css')) // Before bytediff or after
        .pipe(plug.bytediff.start())
        .pipe(plug.minifyCss({}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
//        .pipe(plug.concat('all.min.css')) // Before bytediff or after
        .pipe(gulp.dest(pkg.paths.dev + 'content'));
//        .pipe(plug.size({showFiles: true}));
});

/************************
 * Minify and bundle the Vendor CSS
 ************************/
gulp.task('vendorcss', function () {
    return gulp.src(pkg.paths.vendorcss)
        .pipe(plug.concat('vendor.min.css'))
        .pipe(plug.bytediff.start())
        .pipe(plug.minifyCss({}))
        .pipe(plug.bytediff.stop(common.bytediffFormatter))
        .pipe(gulp.dest(pkg.paths.dev + 'content'));
});

/************************
 * Copy fonts
 ************************/
gulp.task('fonts', function () {
    return gulp.src(pkg.paths.fonts)
        .pipe(gulp.dest(pkg.paths.dev + 'fonts'));
});

/************************
 * Compress images
 ************************/
gulp.task('images', function () {
    return gulp.src(pkg.paths.images)
        .pipe(plug.cache(plug.imagemin({optimizationLevel: 3})))
        .pipe(gulp.dest(pkg.paths.dev + 'content/images'));
});

/************************
 * Inject all the files into the new index.html
 ************************/
gulp.task('htmlinject', ['js', 'vendorjs', 'css', 'vendorcss', 'images', 'fonts'], function () {
    var target = gulp.src('../client/index.html');
    var v = pkg.paths.vendorjssequence.map(function (file) {
        return pkg.paths.dev + 'vendor/' + file;
    });
    var sources = {
        css: gulp.src([pkg.paths.dev + 'content/all.min.css'], {read: false}),
        vendorcss: gulp.src([pkg.paths.dev + 'content/vendor.min.css'], {read: false}),
        js: gulp.src([pkg.paths.dev + 'all.min.js']),
        vendorjs: gulp.src(v)
    };
    var ignorePath = '/../client';

    target
//        .pipe(plug.rename('index.html'))
        .pipe(plug.inject(sources.vendorcss, {starttag: '<!-- inject:vendor:{{ext}} -->', ignorePath: ignorePath}))
        .pipe(plug.inject(sources.css, {ignorePath: ignorePath}))
        .pipe(plug.inject(sources.js, {ignorePath: ignorePath}))
        .pipe(plug.inject(sources.vendorjs, {starttag: '<!-- inject:vendor:{{ext}} -->', ignorePath: ignorePath}))
//        .pipe(gulp.dest('../client/'));
        .pipe(gulp.dest(pkg.paths.dev));
});

/************************
 * Bundle the JS, CSS, and compress images.
 * Then copy files to dev and show a toast.
 ************************/
gulp.task('default', ['htmlinject'], function () {
    // Prepare files for dev
    return gulp.src(pkg.paths.dev)
        .pipe(plug.notify({
            onLast: true,
            message: "linted, bundled, and images compressed!"
        }));
});

/************************
 * Bundle the JS, CSS, and compress images.
 * Then copy files to staging and show a toast.
 ************************/
gulp.task('stage', ['default'], function () {
    // Copy the files to staging
    return gulp.src(pkg.paths.dev)
        .pipe(gulp.dest(pkg.paths.stage))
        // Notify we are done
        .pipe(plug.notify({
            onLast: true,
            message: "staged!"
        }));
});

/************************
 * Remove all files from the output folder
 ************************/
gulp.task('cleanOutput', function () {
    return gulp.src([
        pkg.paths.dev,
        pkg.paths.stage
    ])
        .pipe(plug.clean({force: true}));
});

/************************
 * Watch js files
 ************************/
gulp.task('watchjs', function () {
    var js = ['gulpfile.js'].concat(pkg.paths.js);
    var watcher = gulp.watch(js, ['js', 'vendorjs']);

    watcher.on('change', function (event) {
        console.log('*** File ' + event.path + ' was ' + event.type + ', running tasks...');
    });
});

/************************
 * Watch css files
 ************************/
gulp.task('watchcss', function () {
    var css = ['gulpfile.js'].concat(pkg.paths.css, pkg.paths.vendorcss);
    var watcher = gulp.watch(css, ['css', 'vendorcss']);

    watcher.on('change', function (event) {
        console.log('*** File ' + event.path + ' was ' + event.type + ', running tasks...');
    });
});

/************************
 * Watch all files
 ************************/
gulp.task('watch', ['watchcss', 'watchjs'], function () {
});<|endoftext|>


<commit_before>var Iso = require('../../../')

var Router = require('react-router')
var React = require('react')

var routes = require('../src/routes.jsx')

var alt = require('../src/alt')

// Once we bootstrap the stores, we run react-router using
// Router.HistoryLocation
// the element is created and we just render it into the container
// and our application is now live
Iso.bootstrap(function (state, _, container) {
  alt.bootstrap(JSON.stringify(state))

  Router.run(routes, Router.HistoryLocation, function (Handler) {
    var node = React.createElement(Handler)
    React.render(node, container)
  })
})
<commit_msg>fix `alt.bootstrap` since `state` is already serialized<commit_after>var Iso = require('../../../')

var Router = require('react-router')
var React = require('react')

var routes = require('../src/routes.jsx')

var alt = require('../src/alt')

// Once we bootstrap the stores, we run react-router using
// Router.HistoryLocation
// the element is created and we just render it into the container
// and our application is now live
Iso.bootstrap(function (state, _, container) {
  alt.bootstrap(state)

  Router.run(routes, Router.HistoryLocation, function (Handler) {
    var node = React.createElement(Handler)
    React.render(node, container)
  })
})
<|endoftext|>


<commit_before>angular.module('ghost').directive('relatedPosts', ['$http', RelatedPostsDirective]);

function RelatedPostsDirective($http){
	return {
		template: '
 0"> Related posts
'+
                	'
[[post.title]]
'+
           		 '

',
		restrict: 'E',
		scope: {
			tags: '@',
			slug: '@'
		},
		link: function(scope, element, attrs){
			scope.relatedPosts = [];
			var posts = [];
			$http({ url: '/ghost/api/v0.1/posts?tags='+scope.tags, method: 'GET'})
				.then(function(res){
					for (var i = res.data.posts.length - 1; i >= 0; i--) {
						var post = res.data.posts[i];
						if(post.slug != scope.slug)
							posts.push(post);
					};
					scope.relatedPosts = posts;
				});

		}
	}

}<commit_msg>Added encoding to tags when searching for related posts, fixes #1<commit_after>angular.module('ghost').directive('relatedPosts', ['$http', RelatedPostsDirective]);

function RelatedPostsDirective($http){
	return {
		template: '
 0"> Related posts
'+
                	'
[[post.title]]
'+
           		 '

',
		restrict: 'E',
		scope: {
			tags: '@',
			slug: '@'
		},
		link: function(scope, element, attrs){
			scope.relatedPosts = [];
			var posts = [];
			var encodedTags = encodeURIComponent(scope.tags);
			$http({ url: '/ghost/api/v0.1/posts?tags='+encodedTags, method: 'GET'})
				.then(function(res){
					for (var i = res.data.posts.length - 1; i >= 0; i--) {
						var post = res.data.posts[i];
						if(post.slug != scope.slug)
							posts.push(post);
					};
					scope.relatedPosts = posts;
				});

		}
	}

}<|endoftext|>


<commit_before>
$(document).ready(function() {
  $('.akvo_map').each(function() {
    var mapId = $(this).attr('id');
    var mapElement = document.getElementById(mapId);
    var mapOpts = window[mapId];
    var objectId = mapOpts.objectId;

    var googleMap = {
      canvas: mapElement,
      options: {
        zoom: mapOpts.zoom,
        center: new google.maps.LatLng(mapOpts.Lat, mapOpts.Lng),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        scrollwheel: false,
        streetViewControl: false
      },
      load: function() {
        var map = new google.maps.Map(this.canvas, this.options);
        var marker = new google.maps.Marker({
          icon: '/rsr/media/core/img/blueMarker.png',
          map: map,
          position: this.options.center,
          clickable: false
        });
      }
    };
    googleMap.load();

    var akvoMap = {
      resourceURL: 'http://akvo.dev/api/v1/project_location/?format=jsonp&project=' + objectId + '&callback=?',

      load: function() {
        $.getJSON(this.resourceURL, function(data) {
          console.log(data.objects);
          $.each(data.objects, function(i, location) {
            console.log(location.city);
          });
        });

      }
    };
    akvoMap.load();

  });
});

/*

$(document).ready(function() {
  $('.akvo_map').each(function() {
    var mapElement = $(this).get();
    var mapId = $(this).attr('id');
    var opts = window[mapId];

    var options =  {
      zoom: 3,
            center: new google.maps.LatLng(11.09447,
                                           -2.098178),
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            scrollwheel: false,
            streetViewControl: false
        };

    var load = function() {
      var map = new google.maps.Map(this.mapElement, this.options);
      var marker = new google.maps.Marker({

                    icon: '/rsr/media/core/img/blueMarker.png',

                map: map,
                position: this.options.center,
                clickable: false
            });
      alert("Hi there");
    }();

    // alert("mapId: " + opts.type);
    // var opts = mapId;

    // var resouceUrl = "http://akvo.dev/api/v1/project_location/?format=jsonp&project=436";

    // alert("Type was: " + opts.type);
    // var opts = akvoMaps_12345;
    // alert("Id was: " + objectId);
    // alert( this.id + ". Opts was: " + opts.type);
  });

  // alert("Jquery ready from maps");
});

*/<commit_msg>Maps works with multiple items<commit_after>
$(document).ready(function() {
  $('.akvo_map').each(function() {
    var mapId = $(this).attr('id');
    var mapElement = document.getElementById(mapId);
    var mapOpts = window[mapId];
    var objectId = mapOpts.objectId;

    var options = {
      zoom: mapOpts.zoom,
      center: new google.maps.LatLng(mapOpts.Lat, mapOpts.Lng),
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      scrollwheel: false,
      streetViewControl: false
      };

    var map = new google.maps.Map(mapElement, options);

    // var googleMap = {
    //   canvas: mapElement,
    //   options: {
    //     zoom: mapOpts.zoom,
    //     center: new google.maps.LatLng(mapOpts.Lat, mapOpts.Lng),
    //     mapTypeId: google.maps.MapTypeId.ROADMAP,
    //     scrollwheel: false,
    //     streetViewControl: false
    //   },
    //   load: function() {
    //     var map = new google.maps.Map(this.canvas, this.options);
    //     var marker = new google.maps.Marker({
    //       icon: '/rsr/media/core/img/blueMarker.png',
    //       map: map,
    //       position: this.options.center,
    //       clickable: false
    //     });
    //   }
    // };
    // googleMap.load();

    var akvoMap = {
      // resourceURL: 'http://akvo.dev/api/v1/project_location/?format=jsonp&project=' + objectId + '&callback=?',
      resourceURL: 'http://akvo.dev/api/v1/project/' + objectId + '/?format=json&depth=1&callback=?',

      load: function(callback) {
        $.getJSON(this.resourceURL, function(data) {
          var items = [];
          var title = data.title;
          $.each(data.locations, function(i, location) {
            items.push({
              'project': location.project,
              'latitude': location.latitude,
              'longitude': location.longitude,
              'primary': location.primary,
              'city': location.city
            });
          });
          callback(items);
        });
      }
    };

    akvoMap.load(function(locations){
      $.each(locations, function(index, location){
        console.log(location.city);
        var marker = new google.maps.Marker({
          icon: '/rsr/media/core/img/blueMarker.png',
          map: map,
          position: new google.maps.LatLng(location.latitude, location.longitude),
          clickable: false
        });
      });
    });

  });
});

/*

$(document).ready(function() {
  $('.akvo_map').each(function() {
    var mapElement = $(this).get();
    var mapId = $(this).attr('id');
    var opts = window[mapId];

    var options =  {
      zoom: 3,
            center: new google.maps.LatLng(11.09447,
                                           -2.098178),
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            scrollwheel: false,
            streetViewControl: false
        };

    var load = function() {
      var map = new google.maps.Map(this.mapElement, this.options);
      var marker = new google.maps.Marker({

                    icon: '/rsr/media/core/img/blueMarker.png',

                map: map,
                position: this.options.center,
                clickable: false
            });
      alert("Hi there");
    }();

    // alert("mapId: " + opts.type);
    // var opts = mapId;

    // var resouceUrl = "http://akvo.dev/api/v1/project_location/?format=jsonp&project=436";

    // alert("Type was: " + opts.type);
    // var opts = akvoMaps_12345;
    // alert("Id was: " + objectId);
    // alert( this.id + ". Opts was: " + opts.type);
  });

  // alert("Jquery ready from maps");
});

*/<|endoftext|>


<commit_before>/**
 * 这里是书籍列表模块
 * @type {[type]}
 */
var bookListModule = angular.module("BookListModule", []);
bookListModule.controller('BookListCtrl', function($scope, $http, $state, $stateParams) {
    $scope.filterOptions = {
        filterText: "",
        useExternalFilter: true
    };
    $scope.totalServerItems = 0;
    $scope.pagingOptions = {
        pageSizes: [5, 10, 20],
        pageSize: 5,
        currentPage: 1
    };
    $scope.setPagingData = function(data, page, pageSize) {
        var pagedData = data.slice((page - 1) * pageSize, page * pageSize);
        $scope.books = pagedData;
        $scope.totalServerItems = data.length;
        if (!$scope.$$phase) {
            $scope.$apply();
        }
    };

    //这里可以根据路由上传递过来的bookType参数加载不同的数据
    console.log($stateParams);
    $scope.getPagedDataAsync = function(pageSize, page, searchText) {
        setTimeout(function() {
            var data;
            if (searchText) {
                var ft = searchText.toLowerCase();
                $http.get('data/books' + $stateParams.bookType + '.json')
                    .success(function(largeLoad) {
                        data = largeLoad.filter(function(item) {
                            return JSON.stringify(item).toLowerCase().indexOf(ft) != -1;
                        });
                        $scope.setPagingData(data, page, pageSize);
                    });
            } else {
                $http.get('data/books' + $stateParams.bookType + '.json')
                    .success(function(largeLoad) {
                        $scope.setPagingData(largeLoad, page, pageSize);
                    });
            }
        }, 100);
    };

    $scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);

    $scope.$watch('pagingOptions', function(newVal, oldVal) {
        if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) {
            $scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
        }
    }, true);
    $scope.$watch('filterOptions', function(newVal, oldVal) {
        if (newVal !== oldVal) {
            $scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
        }
    }, true);

    $scope.gridOptions = {
        data: 'books',
        rowTemplate: '

' +
            '

' +
            '

' +
            '

',
        multiSelect: false,
        enableCellSelection: true,
        enableRowSelection: false,
        enableCellEdit: true,
        enablePinning: true,
        columnDefs: [{
            field: 'index',
            displayName: '序号',
            width: 60,
            pinnable: false,
            sortable: false
        }, {
            field: 'name',
            displayName: '书名',
            enableCellEdit: true,
            width: 200
        }, {
            field: 'author',
            displayName: '作者',
            enableCellEdit: true,
            width: 100
        }, {
            field: 'pubTime',
            displayName: '出版日期',
            enableCellEdit: true,
            width: 120
        }, {
            field: 'price',
            displayName: '定价',
            enableCellEdit: true,
            width: 120,
            cellFilter: 'currency:"￥"'
        }, {
            field: 'bookId',
            displayName: '操作',
            enableCellEdit: false,
            sortable: false,
            pinnable: false,
            cellTemplate: '
详情
'
        }],
        enablePaging: true,
        showFooter: true,
        totalServerItems: 'totalServerItems',
        pagingOptions: $scope.pagingOptions,
        filterOptions: $scope.filterOptions
    };
});

/**
 * 这里是书籍详情模块
 * @type {[type]}
 */
var bookDetailModule = angular.module("BookDetailModule", []);
bookDetailModule.controller('BookDetailCtrl', function($scope, $http, $state, $stateParams) {
    console.log($stateParams);
    //请模仿上面的代码，用$http到后台获取数据，把这里的例子实现完整
    //不能直接传递过去???
});

/**
*  验证登录loginModule
*
* Description
*/
var loginModule = angular.module('LoginMoudle', []);
loginModule.controller('loginController', function($scope, $http,$location){
    $scope.userInfo = {
        "email":"",
        "password":""
    };
    $scope.submit = function(isValid){
        if(isValid){
            //$http 异步验证用户名密码是否正确
            // 如何控制登录成功跳转 ui-sref="booklist({bookType:0})"
            //$location.toXXXX = booklist({bookType:0});
            $http.get("data/userInfo.json")
                .success(function(response){
                    for (var i = 0; i < response.length; i++) {
                        if($scope.userInfo.email == response[i].email && $scope.userInfo.password == response[i].password){
                            //booklist({bookType:0})
                            return ;
                        }
                    }

                })
                .error(function(){
                    console.log("$http error")
                });

        }
    }

});

/**
*  验证注册registerModule
*
* Description
*/
var registerModule = angular.module('RegisterMoudle', []);
registerModule.controller('registerController', function($scope, $http,$filter){
    $scope.userInfo = {
        "email":"",
        "password":"",
        "password2":""
    };
    $scope.register = function(isValid){
        if(isValid){
            //$http 异步验证用户名密码是否存在
            //nodejs 是否能操作写入文件
            $http.get("data/userInfo.json")
                .success(function(response){
                    for (var i = 0; i < response.length; i++) {
                        if($scope.userInfo.email == response[i].email && $scope.userInfo.password == response[i].password){
                            $scope.info = "用户已存在";
                        }else{
                            console.log("注册成功！")
                            //ui-sref="index"
                        }
                    }

                })
                .error(function(){
                    console.log("$http error")
                });
        }
    }

});
<commit_msg>ng-BookStore $loaction<commit_after>/**
 * 这里是书籍列表模块
 * @type {[type]}
 */
var bookListModule = angular.module("BookListModule", []);
bookListModule.controller('BookListCtrl', function($scope, $http, $state, $stateParams) {
    $scope.filterOptions = {
        filterText: "",
        useExternalFilter: true
    };
    $scope.totalServerItems = 0;
    $scope.pagingOptions = {
        pageSizes: [5, 10, 20],
        pageSize: 5,
        currentPage: 1
    };
    $scope.setPagingData = function(data, page, pageSize) {
        var pagedData = data.slice((page - 1) * pageSize, page * pageSize);
        $scope.books = pagedData;
        $scope.totalServerItems = data.length;
        if (!$scope.$$phase) {
            $scope.$apply();
        }
    };

    //这里可以根据路由上传递过来的bookType参数加载不同的数据
    console.log($stateParams);
    $scope.getPagedDataAsync = function(pageSize, page, searchText) {
        setTimeout(function() {
            var data;
            if (searchText) {
                var ft = searchText.toLowerCase();
                $http.get('data/books' + $stateParams.bookType + '.json')
                    .success(function(largeLoad) {
                        data = largeLoad.filter(function(item) {
                            return JSON.stringify(item).toLowerCase().indexOf(ft) != -1;
                        });
                        $scope.setPagingData(data, page, pageSize);
                    });
            } else {
                $http.get('data/books' + $stateParams.bookType + '.json')
                    .success(function(largeLoad) {
                        $scope.setPagingData(largeLoad, page, pageSize);
                    });
            }
        }, 100);
    };

    $scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);

    $scope.$watch('pagingOptions', function(newVal, oldVal) {
        if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) {
            $scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
        }
    }, true);
    $scope.$watch('filterOptions', function(newVal, oldVal) {
        if (newVal !== oldVal) {
            $scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
        }
    }, true);

    $scope.gridOptions = {
        data: 'books',
        rowTemplate: '

' +
            '

' +
            '

' +
            '

',
        multiSelect: false,
        enableCellSelection: true,
        enableRowSelection: false,
        enableCellEdit: true,
        enablePinning: true,
        columnDefs: [{
            field: 'index',
            displayName: '序号',
            width: 60,
            pinnable: false,
            sortable: false
        }, {
            field: 'name',
            displayName: '书名',
            enableCellEdit: true,
            width: 200
        }, {
            field: 'author',
            displayName: '作者',
            enableCellEdit: true,
            width: 100
        }, {
            field: 'pubTime',
            displayName: '出版日期',
            enableCellEdit: true,
            width: 120
        }, {
            field: 'price',
            displayName: '定价',
            enableCellEdit: true,
            width: 120,
            cellFilter: 'currency:"￥"'
        }, {
            field: 'bookId',
            displayName: '操作',
            enableCellEdit: false,
            sortable: false,
            pinnable: false,
            cellTemplate: '
详情
'
        }],
        enablePaging: true,
        showFooter: true,
        totalServerItems: 'totalServerItems',
        pagingOptions: $scope.pagingOptions,
        filterOptions: $scope.filterOptions
    };
});

/**
 * 这里是书籍详情模块
 * @type {[type]}
 */
var bookDetailModule = angular.module("BookDetailModule", []);
bookDetailModule.controller('BookDetailCtrl', function($scope, $http, $state, $stateParams) {
    console.log($stateParams);
    //请模仿上面的代码，用$http到后台获取数据，把这里的例子实现完整
    //不能直接传递过去???
});

/**
*  验证登录loginModule
*
* Description
*/
var loginModule = angular.module('LoginMoudle', []);
loginModule.controller('loginController', function($scope, $http,$location){
    $scope.userInfo = {
        "email":"",
        "password":""
    };
    $scope.submit = function(isValid){
        if(isValid){
            //$http 异步验证用户名密码是否正确
            // 如何控制登录成功跳转 ui-sref="booklist({bookType:0})"
            //$location.toXXXX = booklist({bookType:0});
            $http.get("data/userInfo.json")
                .success(function(response){
                    for (var i = 0; i < response.length; i++) {
                        if($scope.userInfo.email == response[i].email && $scope.userInfo.password == response[i].password){
                            $location.path("/booklist");
                            console.log($location)
                            return ;
                        }
                    }

                })
                .error(function(){
                    console.log("$http error")
                });

        }
    }

});

/**
*  验证注册registerModule
*
* Description
*/
var registerModule = angular.module('RegisterMoudle', []);
registerModule.controller('registerController', function($scope, $http,$filter){
    $scope.userInfo = {
        "email":"",
        "password":"",
        "password2":""
    };
    $scope.register = function(isValid){
        if(isValid){
            //$http 异步验证用户名密码是否存在
            //nodejs 是否能操作写入文件
            $http.get("data/userInfo.json")
                .success(function(response){
                    for (var i = 0; i < response.length; i++) {
                        if($scope.userInfo.email == response[i].email && $scope.userInfo.password == response[i].password){
                            $scope.info = "用户已存在";
                        }else{
                            console.log("注册成功！")
                            $location.path("/register");
                            console.log($location)
                        }
                    }

                })
                .error(function(){
                    console.log("$http error")
                });
        }
    }

});
<|endoftext|>


<commit_before>'use strict';

var cBlock = {"start":"/*", "end":"*/", "ignore":"*"};
module.exports = {
  ".coffee":      {"name": "coffeescript", "symbol": "#"},
  ".litcoffee":   {"name": "coffeescript", "symbol": "#", "literate": true},
  "Cakefile":     {"name": "coffeescript", "symbol": "#"},
  ".rb":          {"name": "ruby", "symbol": "#"},
  ".py":          {"name": "python", "symbol": "#"},
  ".jl":          {"name": "julia", "symbol": "#", "block": {"start": "#=", "end": "=#", "ignore": "#"}},
  ".tex":         {"name": "tex", "symbol": "%"},
  ".latex":       {"name": "tex", "symbol": "%"},
  ".js":          {"name": "javascript", "symbol": "//", "block": cBlock},
  ".java":        {"name": "java", "symbol": "//", "block": cBlock},
  ".groovy":      {"name": "groovy", "symbol": "//", "block": cBlock},
  ".scss":        {"name": "scss", "symbol": "//"},
  ".cpp":         {"name": "cpp", "symbol": "//", "block": cBlock},
  ".cc":          {"name": "cpp", "symbol": "//", "block": cBlock},
  ".php":         {"name": "php", "symbol": "//"},
  ".hs":          {"name": "haskell", "symbol": "--"},
  ".erl":         {"name": "erlang", "symbol": "%"},
  ".hrl":         {"name": "erlang", "symbol": "%"},
  ".md":          {"name": "markdown", "symbol": ""},
  ".markdown":    {"name": "markdown", "symbol": ""},
  ".less":        {"name": "scss", "symbol": "//", "block": cBlock},
  ".c":           {"name": "c", "symbol":"//", "block": cBlock},
  ".h":           {"name": "objectivec", "symbol": "//", "block": cBlock},
  ".m":           {"name": "objectivec", "symbol": "//", "block": cBlock},
  ".mm":          {"name": "objectivec", "symbol": "//", "block": cBlock},
  ".m4":          {"name": "m4", "symbol": "#"},
  ".scala":       {"name": "scala", "symbol": "//"},
  ".cs":          {"name": "cs", "symbol": "//"},
  ".as":          {"name": "actionscript", "symbol": "//"},
  ".scpt":        {"name": "applescript", "symbol": "--"},
  ".applescript": {"name": "applescript", "symbol": "--"},
  ".sh":          {"name": "bash", "symbol": "#"},
  ".clj":         {"name": "clojure", "symbol": ";"},
  ".cmake":       {"name": "cmake", "symbol": "#"},
  ".d":           {"name": "d", "symbol": "//"},
  ".p":           {"name": "delphi", "symbol": "//"},
  ".pp":          {"name": "delphi", "symbol": "//"},
  ".pas":         {"name": "delphi", "symbol": "//"},
  ".bat":         {"name": "dos", "symbol": "@?rem"},
  ".btm":         {"name": "dos", "symbol": "@?rem"},
  ".cmd":         {"name": "dos", "symbol": "@?rem"},
  ".go":          {"name": "go", "symbol": "//", "block": cBlock},
  ".ini":         {"name": "ini", "symbol": ";"},
  ".lisp":        {"name": "lisp", "symbol": ";"},
  ".mel":         {"name": "mel", "symbol": "//"},
  ".pl":          {"name": "perl", "symbol": "#"},
  ".pm":          {"name": "perl", "symbol": "#"},
  ".pod":         {"name": "perl", "symbol": "#"},
  ".t":           {"name": "perl", "symbol": "#"},
  ".r":           {"name": "r", "symbol": "#"},
  ".rc":          {"name": "rust", "symbol": "//"},
  ".rs":          {"name": "rust", "symbol": "//"},
  ".sql":         {"name": "sql", "symbol": "--"},
  ".pks":         {"name": "pks", "symbol": "--", "block": cBlock},
  ".pkb":         {"name": "pkb", "symbol": "--", "block": cBlock},
  ".vala":        {"name": "vala", "symbol": "//"},
  ".vapi":        {"name": "vala", "symbol": "//"},
  ".vbe":         {"name": "vbscript", "symbol": "'"},
  ".vbs":         {"name": "vbscript", "symbol": "'"},
  ".wsc":         {"name": "vbscript", "symbol": "'"},
  ".wsf":         {"name": "vbscript", "symbol": "'"},
  ".vhdl":        {"name": "vhdl", "symbol": "--"},
  ".bas":         {"name": "basic", "symbol": "REM"},
  ".ps1":         {"name": "powershell", "symbol": "#", "block": {"start":"<#", "end":"#>", "ignore":"#"} },
  ".lua":         {"name": "lua", "symbol": "--", "block": {"start": "--[[", "end":"--]]"} },
  ".hx":          {"name": "haxe", "symbol": "//", "block": cBlock},
  ".eg":          {"name": "earl-grey", "symbol": ";;"},
  ".jade":        {"name": "jade", "symbol": "//"},
  ".styl":        {"name": "stylus", "symbol": "//"},
  ".ts":          {"name": "typescript", "symbol": "//", "block": cBlock}
};
<commit_msg>Add HTML<commit_after>'use strict';

var cBlock = {"start":"/*", "end":"*/", "ignore":"*"};
module.exports = {
  ".coffee":      {"name": "coffeescript", "symbol": "#"},
  ".litcoffee":   {"name": "coffeescript", "symbol": "#", "literate": true},
  "Cakefile":     {"name": "coffeescript", "symbol": "#"},
  ".rb":          {"name": "ruby", "symbol": "#"},
  ".py":          {"name": "python", "symbol": "#"},
  ".jl":          {"name": "julia", "symbol": "#", "block": {"start": "#=", "end": "=#", "ignore": "#"}},
  ".tex":         {"name": "tex", "symbol": "%"},
  ".latex":       {"name": "tex", "symbol": "%"},
  ".js":          {"name": "javascript", "symbol": "//", "block": cBlock},
  ".java":        {"name": "java", "symbol": "//", "block": cBlock},
  ".groovy":      {"name": "groovy", "symbol": "//", "block": cBlock},
  ".scss":        {"name": "scss", "symbol": "//"},
  ".cpp":         {"name": "cpp", "symbol": "//", "block": cBlock},
  ".cc":          {"name": "cpp", "symbol": "//", "block": cBlock},
  ".php":         {"name": "php", "symbol": "//"},
  ".hs":          {"name": "haskell", "symbol": "--"},
  ".erl":         {"name": "erlang", "symbol": "%"},
  ".hrl":         {"name": "erlang", "symbol": "%"},
  ".md":          {"name": "markdown", "symbol": ""},
  ".markdown":    {"name": "markdown", "symbol": ""},
  ".less":        {"name": "scss", "symbol": "//", "block": cBlock},
  ".c":           {"name": "c", "symbol":"//", "block": cBlock},
  ".h":           {"name": "objectivec", "symbol": "//", "block": cBlock},
  ".m":           {"name": "objectivec", "symbol": "//", "block": cBlock},
  ".mm":          {"name": "objectivec", "symbol": "//", "block": cBlock},
  ".m4":          {"name": "m4", "symbol": "#"},
  ".scala":       {"name": "scala", "symbol": "//"},
  ".cs":          {"name": "cs", "symbol": "//"},
  ".as":          {"name": "actionscript", "symbol": "//"},
  ".scpt":        {"name": "applescript", "symbol": "--"},
  ".applescript": {"name": "applescript", "symbol": "--"},
  ".sh":          {"name": "bash", "symbol": "#"},
  ".clj":         {"name": "clojure", "symbol": ";"},
  ".cmake":       {"name": "cmake", "symbol": "#"},
  ".d":           {"name": "d", "symbol": "//"},
  ".p":           {"name": "delphi", "symbol": "//"},
  ".pp":          {"name": "delphi", "symbol": "//"},
  ".pas":         {"name": "delphi", "symbol": "//"},
  ".bat":         {"name": "dos", "symbol": "@?rem"},
  ".btm":         {"name": "dos", "symbol": "@?rem"},
  ".cmd":         {"name": "dos", "symbol": "@?rem"},
  ".go":          {"name": "go", "symbol": "//", "block": cBlock},
  ".ini":         {"name": "ini", "symbol": ";"},
  ".lisp":        {"name": "lisp", "symbol": ";"},
  ".mel":         {"name": "mel", "symbol": "//"},
  ".pl":          {"name": "perl", "symbol": "#"},
  ".pm":          {"name": "perl", "symbol": "#"},
  ".pod":         {"name": "perl", "symbol": "#"},
  ".t":           {"name": "perl", "symbol": "#"},
  ".r":           {"name": "r", "symbol": "#"},
  ".rc":          {"name": "rust", "symbol": "//"},
  ".rs":          {"name": "rust", "symbol": "//"},
  ".sql":         {"name": "sql", "symbol": "--"},
  ".pks":         {"name": "pks", "symbol": "--", "block": cBlock},
  ".pkb":         {"name": "pkb", "symbol": "--", "block": cBlock},
  ".vala":        {"name": "vala", "symbol": "//"},
  ".vapi":        {"name": "vala", "symbol": "//"},
  ".vbe":         {"name": "vbscript", "symbol": "'"},
  ".vbs":         {"name": "vbscript", "symbol": "'"},
  ".wsc":         {"name": "vbscript", "symbol": "'"},
  ".wsf":         {"name": "vbscript", "symbol": "'"},
  ".vhdl":        {"name": "vhdl", "symbol": "--"},
  ".bas":         {"name": "basic", "symbol": "REM"},
  ".ps1":         {"name": "powershell", "symbol": "#", "block": {"start":"<#", "end":"#>", "ignore":"#"} },
  ".lua":         {"name": "lua", "symbol": "--", "block": {"start": "--[[", "end":"--]]"} },
  ".hx":          {"name": "haxe", "symbol": "//", "block": cBlock},
  ".eg":          {"name": "earl-grey", "symbol": ";;"},
  ".jade":        {"name": "jade", "symbol": "//"},
  ".styl":        {"name": "stylus", "symbol": "//"},
  ".ts":          {"name": "typescript", "symbol": "//", "block": cBlock},
  ".html":        {"name": "html", "symbol": "//", "block": {"start": "<!--", "end": "-->", "ignore": "-"} }
};
<|endoftext|>


<commit_before>'use strict';

import PIXI from 'pixi.js';
import TWEEN from 'tween.js';
import GRAD from './gradient.jpg';

export default class ArcGraph extends PIXI.DisplayObjectContainer {

  constructor(...args) {

    super(...args);

    this.percent = 0;
  	this.rotation = Math.PI * .7; // easier than doing math in drawArc => moveto (but also buggered things up)
  	this.pivot = new PIXI.Point(.5, .5);
    this.lineWidth = 12;

    this.blurFilter = new PIXI.BlurFilter();
    this.bar = new PIXI.Graphics();
    this.tween = new TWEEN.Tween(this);
    this.grad = this.addGradient();
    this.grad2 = this.addGradient();

    this.addBackground();

    this.blurFilter.blurX = 20;
    this.blurFilter.blurY = 20;

    this.addChild(this.grad);
    this.addChild(this.grad2);
    this.addChild(this.bar);

    this.grad.filters = [this.blurFilter];
    this.grad.mask = this.bar;
    this.grad2.mask = this.bar;

    this.setDecimal(1);

    window.test = this;

  }

  setPercent(perc) {
  	this.setDecimal(perc/100);
  }

  setDecimal(decimal) {

    if(decimal > 1) {
      decimal = 1;
    }

    this.tween.to({percent: decimal}, 1000);

    this.tween.onUpdate(this.drawArc.bind(this));

    this.tween.start();
  }

  addGradient() {

    this.gradTexture = new PIXI.Texture.fromImage(GRAD);
    var grad = new PIXI.Sprite(this.gradTexture);
    grad.pivot = new PIXI.Point(240, 240);
    grad.rotation = Math.PI * -.7;
    grad.width = 240;
    grad.height = 240;
    grad.position = new PIXI.Point(-15, 20);

    return grad;
  }

  addBackground() {
  	var bg = new PIXI.Graphics();

  	bg.lineStyle(this.lineWidth, 0x000000);
	  bg.drawCircle(0, 0, 100);
	  bg.lineStyle(this.lineWidth, 0x444444);
	  bg.arc(0,0,100, (Math.PI * 2) * .8, 0,  false);

    this.addChild(bg);

  }

  drawArc() {
    var angle = (Math.PI * 1.6) * this.percent;

  	this.bar.clear();
  	this.bar.moveTo(100,0); // move to origin to avoid extra lines, needs to be positioned properly
    //console.log(100 * Math.cos(angle), 100 * Math.sin(angle));
  	this.bar.lineStyle(this.lineWidth, 0xFF00FF);
    this.bar.arc(0, 0, 100,
    	0,
    	angle
    );

    this.blurFilter.blurX = (15 * this.percent) + 5;
    this.blurFilter.blurY = (15 * this.percent) + 5;

  }

}
<commit_msg>refactor graph with better math and options<commit_after>'use strict';

import PIXI from 'pixi.js';
import TWEEN from 'tween.js';
import GRAD from './gradient.jpg';

var options = {
  barSize : 1,
  lineWidth : 15,
  tweenLength : 1000,
  blurFactor : 20,
  radius : 100,
  percent : 100
}

const BAR_START = (Math.PI * 2) * .4;
const BAR_END = (Math.PI * 2) * 1.1;

export default class ArcGraph extends PIXI.DisplayObjectContainer {

  /**
   * ArcGraph
   * @param  {...[type]} args
   * @return {null}
   */
  constructor(...args) {

    super(...args);

    // Add all our globals
    this.tween = new TWEEN.Tween(this);
    this.gradTexture = new PIXI.Texture.fromImage(GRAD);
    this.blurFilter = new PIXI.BlurFilter();
    this.bg = this.addBackground();
    this.grad = this.addGradient();
    this.grad2 = this.addGradient();
    this.bar = new PIXI.Graphics();

    // add assets to stage
    this.addChild(this.bg);
    this.addChild(this.bar);
    this.addChild(this.grad);
    this.addChild(this.grad2);

    // First masked gradient
    this.grad.filters = [this.blurFilter];
    this.grad.mask = this.bar;

    // Second masked gradient
    this.grad2.blendMode = PIXI.blendModes.ADD;
    this.grad2.mask = this.bar;

    // Start an animation
    this.percent = .3;
    this.setPercent(options.percent);

  }

  /**
   * Set graph in %
   * @param {number} perc 0-100
   */
  setPercent(perc) {
  	this.setDecimal(perc/100);
  }

  /**
   * Set graph as .
   * @param {number} decimal 0-100
   */
  setDecimal(decimal) {

    if(decimal > 1) {
      decimal = 1;
    }

    this.tween.to({percent: decimal}, options.tweenLength);

    this.tween.onUpdate(this.drawArc.bind(this));

    this.tween.start();
  }

  /**
   * Get a gradient sprite
   */
  addGradient() {
    var grad = new PIXI.Sprite(this.gradTexture);

    grad.width = options.radius * 2 + options.blurFactor * 2;
    grad.height = options.radius * 2 + options.blurFactor * 2;
    grad.position = new PIXI.Point(-options.blurFactor / 2, -options.blurFactor / 2)

    return grad;
  }

  /**
   * Get a background graphics
   */
  addBackground() {
  	var bg = new PIXI.Graphics();

    var cy = options.radius + options.lineWidth;
    var cx = cy;

  	bg.lineStyle(options.lineWidth, 0x000000);
	  bg.drawCircle(cx, cy, options.radius);
	  bg.lineStyle(options.lineWidth, 0x444444);
	  bg.arc(cx,cy,options.radius, BAR_START, BAR_END, true);

    return bg;

  }

  /**
   * Update a graphics
   * @return {null}
   */
  drawArc() {

    var angle = ((BAR_END - BAR_START) * this.percent) + BAR_START;
    var blurDescale = .7;
    var cy = options.radius + options.lineWidth;
    var cx = cy;

  	this.bar.clear();
  	this.bar.lineStyle(options.lineWidth, 0xFF00FF);
    // Move to origin
    this.bar.moveTo(options.radius * Math.cos(BAR_START) + cx, options.radius * Math.sin(BAR_START) + cy);
    //this.bar.lineTo(options.radius * Math.cos(angle) + cx, options.radius * Math.sin(angle) + cy);

    this.bar.arc(cx, cy, options.radius, BAR_START, angle, false);

    // descale blur to prevent blue clipping
    this.blurFilter.blurX = (options.blurFactor * blurDescale) * this.percent;
    this.blurFilter.blurY = (options.blurFactor * blurDescale) * this.percent;

  }

}
<|endoftext|>


<commit_before>import { ORMAdapter } from 'denali';
import { fromNode } from 'bluebird';
import forIn from 'lodash/forIn';
import forEach from 'lodash/forEach';
import snakeCase from 'lodash/snakeCase';
import upperFirst from 'lodash/upperFirst';

export default class NodeORM2Adapter extends ORMAdapter {

  static find(type, query /* , options */) {
    let OrmModel = this.ormModels[type];
    return fromNode((cb) => {
      if ([ 'number', 'string' ].includes(typeof query)) {
        OrmModel.get(query, cb);
      } else {
        OrmModel.find(query, cb);
      }
    });
  }

  static createRecord(type, data /* , options */) {
    let OrmModel = this.ormModels[type];
    return fromNode((cb) => {
      OrmModel.create(data, cb);
    });
  }

  static buildRecord(type, data /* , options */) {
    let OrmModel = this.ormModels[type];
    return new OrmModel(data);
  }

  static idFor(model) {
    return model.record.id;
  }

  static getAttribute(model, property) {
    return model.record[property];
  }

  static setAttribute(model, property, value) {
    model.record[property] = value;
    return true;
  }

  static deleteAttribute(model, property) {
    model.record[property] = null;
    return true;
  }

  static getRelated(model, relationship) {
    return fromNode((cb) => {
      model.record[`get${ upperFirst(relationship) }`](cb);
    });
  }

  static setRelated(model, relationship, relatedRecords) {
    return fromNode((cb) => {
      model.record[`set${ upperFirst(relationship) }`](relatedRecords, cb);
    });
  }

  static addRelated(model, relationship, relatedRecord) {
    return fromNode((cb) => {
      model.record[`add${ upperFirst(relationship) }`](relatedRecord, cb);
    });
  }

  static removeRelated(model, relationship, relatedRecord) {
    return fromNode((cb) => {
      let args = [ cb ];
      if (relatedRecord) {
        args.unshift([ relatedRecord ]);
      }
      model.record[`remove${ upperFirst(relationship) }`](...args);
    });
  }

  static saveRecord(model) {
    return fromNode(model.record.save.bind(model.record));
  }

  static deleteRecord(model) {
    return fromNode(model.record.remove.bind(model.record));
  }

  static define(Model) {
    let attributes = {};
    Model.eachAttribute((key, attribute) => {
      if (attribute.isAttribute) {
        attributes[key] = {
          mapsTo: this.serializeKey(key),
          type: attribute.type
        };
      }
    });
    return this.db.define(Model.type, attributes);
  }

  static defineRelationships(DenaliModel, AdapterModel) {
    let relationships = {};
    forIn(DenaliModel, (value, key) => {
      if (value.isRelationship) {
        relationships[this.serializeKey(key)] = value;
      }
    });
    forEach(relationships, (config, key) => {
      let RelatedAdapterModel = this.adapterModels[config.relatedType];
      if (config.hasOne) {
        AdapterModel.hasOne(key, RelatedAdapterModel);
      } else {
        AdapterModel.hasMany(key, RelatedAdapterModel);
      }
    });
  }

  static serializeKey(key) {
    return snakeCase(key);
  }

}
<commit_msg>fix: update to leverage denali's new defineModels convention<commit_after>import { ORMAdapter } from 'denali';
import { fromNode } from 'bluebird';
import snakeCase from 'lodash/snakeCase';
import upperFirst from 'lodash/upperFirst';

export default class NodeORM2Adapter extends ORMAdapter {

  static find(type, query /* , options */) {
    let OrmModel = this.ormModels[type];
    return fromNode((cb) => {
      if ([ 'number', 'string' ].includes(typeof query)) {
        OrmModel.get(query, cb);
      } else {
        OrmModel.find(query, cb);
      }
    });
  }

  static createRecord(type, data /* , options */) {
    let OrmModel = this.ormModels[type];
    return fromNode((cb) => {
      OrmModel.create(data, cb);
    });
  }

  static buildRecord(type, data /* , options */) {
    let OrmModel = this.ormModels[type];
    return new OrmModel(data);
  }

  static idFor(model) {
    return model.record.id;
  }

  static getAttribute(model, property) {
    return model.record[property];
  }

  static setAttribute(model, property, value) {
    model.record[property] = value;
    return true;
  }

  static deleteAttribute(model, property) {
    model.record[property] = null;
    return true;
  }

  static getRelated(model, relationship) {
    return fromNode((cb) => {
      model.record[`get${ upperFirst(relationship) }`](cb);
    });
  }

  static setRelated(model, relationship, relatedRecords) {
    return fromNode((cb) => {
      model.record[`set${ upperFirst(relationship) }`](relatedRecords, cb);
    });
  }

  static addRelated(model, relationship, relatedRecord) {
    return fromNode((cb) => {
      model.record[`add${ upperFirst(relationship) }`](relatedRecord, cb);
    });
  }

  static removeRelated(model, relationship, relatedRecord) {
    return fromNode((cb) => {
      let args = [ cb ];
      if (relatedRecord) {
        args.unshift([ relatedRecord ]);
      }
      model.record[`remove${ upperFirst(relationship) }`](...args);
    });
  }

  static saveRecord(model) {
    return fromNode(model.record.save.bind(model.record));
  }

  static deleteRecord(model) {
    return fromNode(model.record.remove.bind(model.record));
  }

  static defineModels(models) {
    // Don't define abstract base classes
    models = models.filter((Model) => !(Model.hasOwnProperty('abstract') && Model.abstract));

    this.ormModels = {};

    // Define models
    models.forEach((Model) => {
      let attributes = {};
      Model.eachAttribute((key, attribute) => {
        attributes[key] = {
          mapsTo: this.keyToColumn(key),
          type: this.denaliTypeToORMType(attribute.type)
        };
      });
      this.ormModels[Model.type] = this.db.define(Model.type, attributes);
    });

    // Define relationships between models
    models.forEach((Model) => {
      Model.eachRelationship((key, relationship) => {
        let Related = this.ormModels[relationship.relatedType];
        if (relationship.hasOne) {
          Model.hasOne(key, Related);
        } else {
          Model.hasMany(key, Related);
        }
      });
    });
  }

  static denaliTypeToORMType(denaliType) {
    return denaliType;
  }

  static keyToColumn(key) {
    return snakeCase(key);
  }

}
<|endoftext|>


<commit_before>/**
 * Module Name: Flashy
 * Description: Makes pages with flashing text and that innit.
 */

var _ = require('underscore')._;

var flashy = function(dbot) {
    this.colourMap = {
        'red': 'FF0000',
        'green': '00FF00',
        'blue': '0000FF'
    };

    this.commands = {
        '~flashy': function(event) {
            var colour = event.input[1];
            var text = event.input[2];

            if(_.has(this.colourMap, colour)) {
                dbot.t('url', {
                    'host': dbot.config.web.webHost,
                    'port': dbot.config.web.webPort,
                    'path': 'flashy/' + colour + '/' + encodeURIComponent(text)
                });
            } else {
                event.reply('no such colour brah');
            }
        }
    };

    this.commands['~flashy'].regex = [/^~flashy ([\d\w-]+[\d\w\s-]*)[ ]?=[ ]?(.+)$/, 3];
};

exports.fetch = function(dbot) {
    return new flashy(dbot);
};
<commit_msg>forgot event.reply (flashy)<commit_after>/**
 * Module Name: Flashy
 * Description: Makes pages with flashing text and that innit.
 */

var _ = require('underscore')._;

var flashy = function(dbot) {
    this.colourMap = {
        'red': 'FF0000',
        'green': '00FF00',
        'blue': '0000FF'
    };

    this.commands = {
        '~flashy': function(event) {
            var colour = event.input[1];
            var text = event.input[2];

            if(_.has(this.colourMap, colour)) {
                event.reply(dbot.t('url', {
                    'host': dbot.config.web.webHost,
                    'port': dbot.config.web.webPort,
                    'path': 'flashy/' + colour + '/' + encodeURIComponent(text)
                }));
            } else {
                event.reply('no such colour brah');
            }
        }
    };

    this.commands['~flashy'].regex = [/^~flashy ([\d\w-]+[\d\w\s-]*)[ ]?=[ ]?(.+)$/, 3];
};

exports.fetch = function(dbot) {
    return new flashy(dbot);
};
<|endoftext|>