<commit_before>module.exports = [
  'abuse',
  'accessibility',
  'account',
  'accounting',
  'accounts',
  'admin',
  'administracion',
  'administration',
  'administrator',
  'administrators',
  'admins',
  'admissions',
  'adops',
  'adventure',
  'advertise',
  'advertising',
  'advertisingsales',
  'advisor',
  'adwords',
  'affiliates',
  'agents',
  'alarm',
  'alarms',
  'alert',
  'alerts',
  'alexa',
  'all',
  'all-employees',
  'all-pms',
  'all-staff',
  'all-team',
  'all.employees',
  'all.staff',
  'all.users',
  'allemployees',
  'allhands',
  'allstaff',
  'allstudents',
  'allteachers',
  'allteam',
  'allusers',
  'alpha',
  'alphas',
  'alumni',
  'analytics',
  'announce',
  'announcements',
  'api',
  'app',
  'application',
  'apps',
  'associates-all',
  'auctions',
  'available',
  'backend-dev',
  'beta',
  'billing',
  'biz',
  'bizdev',
  'board',
  'booking',
  'bookings',
  'brand',
  'branding',
  'brands',
  'brandsolutions',
  'bugs',
  'build',
  'bursar',
  'busdev',
  'business',
  'business_team',
  'businessdevelopment',
  'caltrain',
  'campaign',
  'campaigns',
  'campusteam',
  'captain',
  'captains',
  'career',
  'careers',
  'ceo',
  'ceos',
  'channel-sales',
  'chatter',
  'citymanagers',
  'client',
  'co-op',
  'coach',
  'commercial',
  'commissions',
  'community',
  'company',
  'company.wide',
  'compete',
  'compliance',
  'connect',
  'consultant',
  'contact',
  'contacto',
  'content',
  'contractor',
  'contractors',
  'core',
  'coreteam',
  'corporate',
  'creative',
  'crew',
  'customercare',
  'customerfeedback',
  'customers',
  'customerservice',
  'customersuccess',
  'data',
  'database',
  'dean',
  'demo',
  'departures',
  'deploy',
  'design',
  'dev',
  'developer',
  'developers',
  'development',
  'devnull',
  'devops',
  'devs',
  'devteam',
  'digsitesvalue',
  'director',
  'directors',
  'directory',
  'dns',
  'docs',
  'domainmanagement',
  'domains',
  'download',
  'ecommerce',
  'editor',
  'editorial',
  'editors',
  'email',
  'emergency',
  'employees',
  'eng',
  'eng-all',
  'engagement',
  'engineering',
  'enq',
  'enquire',
  'enquiries',
  'enquiry',
  'enterprise',
  'error',
  'events',
  'everybody',
  'everyone',
  'exec',
  'executive',
  'executives',
  'exim',
  'expert',
  'experts',
  'export',
  'fbl',
  'feedback',
  'finance',
  'founders',
  'friends',
  'frontend',
  'ftp',
  'fulltime',
  'global',
  'graphics',
  'group',
  'growth',
  'head',
  'head.office',
  'headoffice',
  'headteacher',
  'hello',
  'help',
  'helpdesk',
  'hosting',
  'hostmaster',
  'hq',
  'hr',
  'ideas',
  'info',
  'information',
  'informativo',
  'infra',
  'inoc',
  'insidesales',
  'integration',
  'internal',
  'interns',
  'invest',
  'investorrelations',
  'investors',
  'ispfeedback',
  'ispsupport',
  'ithelp',
  'jira',
  'jobs',
  'leaders',
  'leadership',
  'leadership-team',
  'legal',
  'list',
  'list-request',
  'london',
  'lunch',
  'mail',
  'maildaemon',
  'mailerdaemon',
  'management',
  'management-group',
  'management.team',
  'management_team',
  'managers',
  'marketing',
  'marketing-ops',
  'marketing-team',
  'marketingteam',
  'master',
  'media',
  'meetup',
  'members',
  'mentors',
  'mgmt',
  'misc',
  'mktg',
  'mobile',
  'newbiz',
  'newbusiness',
  'news',
  'newsletter',
  'newyork',
  'nntp',
  'no-reply',
  'noc',
  'noreply',
  'northamerica',
  'notifications',
  'null',
  'ny',
  'nyc',
  'office',
  'officeadmin',
  'officestaff',
  'offtopic',
  'ooo',
  'operations',
  'ops',
  'orders',
  'parents',
  'partner',
  'partners',
  'partnerships',
  'payment',
  'payments',
  'paypal',
  'payroll',
  'people',
  'phish',
  'phishing',
  'post',
  'postbox',
  'postfix',
  'postmaster',
  'pr',
  'press',
  'principal',
  'privacy',
  'product',
  'product.growth',
  'product.management',
  'product.managers',
  'product.team',
  'program',
  'projectmanagers',
  'qa',
  'random',
  'reception',
  'recruit',
  'recruiting',
  'registrar',
  'remove',
  'reports',
  'request',
  'residents',
  'root',
  'sales',
  'sales-team',
  'salesengineers',
  'salesforce',
  'salesteam',
  'school',
  'schooloffice',
  'secretary',
  'security',
  'seo',
  'service',
  'services',
  'sf',
  'sfo',
  'shopping',
  'site',
  'smtp',
  'social',
  'socialclub',
  'software',
  'solutions',
  'spam',
  'staff',
  'stats',
  'strategy',
  'students',
  'subscribe',
  'success',
  'suggestions',
  'support',
  'sysadmin',
  'team',
  'teamleads',
  'tech',
  'techops',
  'techsupport',
  'test',
  'theoffice',
  'todos',
  'twitter',
  'undisclosed-recipients',
  'unsubscribe',
  'us',
  'usa',
  'usenet',
  'users',
  'uucp',
  'ux',
  'vendor',
  'vendors',
  'volunteer',
  'volunteers',
  'watercooler',
  'web',
  'webadmin',
  'webmaster',
  'webteam',
  'welcome',
  'whois',
  'women',
  'www'
];
<commit_msg>Update index.js<commit_after>module.exports = [
  'abuse',
  'accessibility',
  'account',
  'accounting',
  'accounts',
  'admin',
  'administracion',
  'administration',
  'administrator',
  'administrators',
  'admins',
  'admissions',
  'adops',
  'adventure',
  'advertise',
  'advertising',
  'advertisingsales',
  'advisor',
  'adwords',
  'affiliates',
  'agents',
  'alarm',
  'alarms',
  'alert',
  'alerts',
  'alexa',
  'all',
  'all-employees',
  'all-pms',
  'all-staff',
  'all-team',
  'all.employees',
  'all.staff',
  'all.users',
  'allemployees',
  'allhands',
  'allstaff',
  'allstudents',
  'allteachers',
  'allteam',
  'allusers',
  'alpha',
  'alphas',
  'alumni',
  'analytics',
  'announce',
  'announcements',
  'api',
  'app',
  'application',
  'apps',
  'associates-all',
  'auctions',
  'available',
  'backend-dev',
  'beta',
  'billing',
  'biz',
  'bizdev',
  'board',
  'booking',
  'bookings',
  'brand',
  'branding',
  'brands',
  'brandsolutions',
  'bugs',
  'build',
  'bursar',
  'busdev',
  'business',
  'business_team',
  'businessdevelopment',
  'caltrain',
  'campaign',
  'campaigns',
  'campusteam',
  'captain',
  'captains',
  'career',
  'careers',
  'ceo',
  'ceos',
  'channel-sales',
  'chatter',
  'citymanagers',
  'client',
  'co-op',
  'coach',
  'commercial',
  'commissions',
  'community',
  'communications',
  'company',
  'company.wide',
  'compete',
  'compliance',
  'connect',
  'consultant',
  'contact',
  'contacto',
  'content',
  'contractor',
  'contractors',
  'core',
  'coreteam',
  'corporate',
  'corporatesales',
  'creative',
  'crew',
  'customercare',
  'customerfeedback',
  'customers',
  'customerservice',
  'customersuccess',
  'data',
  'database',
  'dean',
  'demo',
  'departures',
  'deploy',
  'design',
  'dev',
  'developer',
  'developers',
  'development',
  'devnull',
  'devops',
  'devs',
  'devteam',
  'digsitesvalue',
  'director',
  'directors',
  'directory',
  'dns',
  'docs',
  'domainmanagement',
  'domains',
  'download',
  'ecommerce',
  'editor',
  'editorial',
  'editors',
  'email',
  'emergency',
  'employees',
  'eng',
  'eng-all',
  'engagement',
  'engineering',
  'enq',
  'enquire',
  'enquiries',
  'enquiry',
  'enterprise',
  'error',
  'events',
  'everybody',
  'everyone',
  'exec',
  'executive',
  'executives',
  'exim',
  'expert',
  'experts',
  'export',
  'fbl',
  'feedback',
  'finance',
  'founders',
  'friends',
  'frontend',
  'ftp',
  'fulltime',
  'global',
  'graphics',
  'group',
  'growth',
  'head',
  'head.office',
  'headoffice',
  'headteacher',
  'hello',
  'help',
  'helpdesk',
  'hosting',
  'hostmaster',
  'hq',
  'hr',
  'ideas',
  'info',
  'information',
  'informativo',
  'infra',
  'inoc',
  'insidesales',
  'integration',
  'internal',
  'interns',
  'invest',
  'investorrelations',
  'investors',
  'ispfeedback',
  'ispsupport',
  'ithelp',
  'jira',
  'jobs',
  'leaders',
  'leadership',
  'leadership-team',
  'legal',
  'list',
  'list-request',
  'london',
  'lunch',
  'mail',
  'maildaemon',
  'mailerdaemon',
  'management',
  'management-group',
  'management.team',
  'management_team',
  'managers',
  'marketing',
  'marketing-ops',
  'marketing-team',
  'marketingteam',
  'master',
  'media',
  'meetup',
  'members',
  'mentors',
  'mgmt',
  'misc',
  'mktg',
  'mobile',
  'newbiz',
  'newbusiness',
  'news',
  'newsletter',
  'newyork',
  'nntp',
  'no-reply',
  'noc',
  'noreply',
  'northamerica',
  'notifications',
  'null',
  'ny',
  'nyc',
  'office',
  'officeadmin',
  'officestaff',
  'offtopic',
  'ooo',
  'operations',
  'ops',
  'orders',
  'parents',
  'partner',
  'partners',
  'partnerships',
  'payment',
  'payments',
  'paypal',
  'payroll',
  'people',
  'phish',
  'phishing',
  'post',
  'postbox',
  'postfix',
  'postmaster',
  'pr',
  'press',
  'principal',
  'privacy',
  'product',
  'product.growth',
  'product.management',
  'product.managers',
  'product.team',
  'program',
  'projectmanagers',
  'qa',
  'random',
  'reception',
  'recruit',
  'recruiting',
  'registrar',
  'remove',
  'reports',
  'request',
  'residents',
  'root',
  'sales',
  'sales-team',
  'salesengineers',
  'salesforce',
  'salesteam',
  'school',
  'schooloffice',
  'secretary',
  'security',
  'seo',
  'service',
  'services',
  'sf',
  'sfo',
  'shopping',
  'site',
  'smtp',
  'social',
  'socialclub',
  'software',
  'solutions',
  'spam',
  'staff',
  'stats',
  'strategy',
  'students',
  'subscribe',
  'success',
  'suggestions',
  'support',
  'sysadmin',
  'team',
  'teamleads',
  'tech',
  'techops',
  'techsupport',
  'test',
  'theoffice',
  'todos',
  'twitter',
  'undisclosed-recipients',
  'unsubscribe',
  'us',
  'usa',
  'usenet',
  'users',
  'uucp',
  'ux',
  'vendor',
  'vendors',
  'volunteer',
  'volunteers',
  'watercooler',
  'web',
  'webadmin',
  'webmaster',
  'webteam',
  'welcome',
  'whois',
  'women',
  'www'
];
<|endoftext|>


<commit_before>define(function(require, exports, module) {
    "use strict";

    var app = require("app");
    var AbstractView = require("modules/view/AbstractView");
    var BacknumberDateNewsView = require("modules/view/backnumber/BacknumberDateNewsView");
    var BusinessUtil = require("modules/util/BusinessUtil");
    var DateUtil = require("modules/util/DateUtil");

    /**
     *  バックナンバーページで見る各日付の記事のView
     *
     *  @class
     *  @exports BacknumberDateView
     *  @constructor
     */
    var BacknumberDateView = AbstractView.extend({
        /**
         *  テンプレートファイル
         */
        template : require("ldsh!templates/{mode}/backnumber/backnumberDate"),
        date : null,
        newsView: null,

        /**
         *  ViewのテンプレートHTMLの描画処理が完了する前に呼び出される。
         */
        beforeRendered : function() {
            this.showNewsView();
        },

        /**
         *  ViewのテンプレートHTMLの描画処理が完了した後に呼び出される。
         */
        afterRendered : function() {
            app.ga.trackPageView("BackNoList","新聞アプリ/バックナンバー記事一覧ページ");

            this.updateDateLabel();
        },

        /**
         *  初期化処理
         */
        initialize : function(options) {
            console.assert(options && options.date, 'Please pass the date value');

            options = options || {};

            var date = options.date;

            if (!(date instanceof Date)) {
                date = Date.parse(date);
            }
            if (!date) {
                date = new Date();
            }

            this.date = date;

            // 最終配信日以前の日付を指定された場合は、最終配信日に移動する
            var currentPublishDate = BusinessUtil.getCurrentPublishDate();
            if (DateUtil.formatDate(this.date, "yyyy-MM-dd") > DateUtil.formatDate(currentPublishDate, "yyyy-MM-dd")) {
                this.date = currentPublishDate;
                app.router.navigate("backnumber/" + DateUtil.formatDate(this.date, "yyyy-MM-dd"), {
                    trigger: true,
                    replace: false
                });
            }
        },

        events : {
            'click [data-backnumber-list]': 'onClickBackToList',
            'click [data-backnumber-day-prev]': 'onClickDayPrev',
            'click [data-backnumber-day-next]': 'onClickDayNext'
        },

        /**
         *  一覧から探すボタンを押したら呼ばれる
         *
         *  @param {Event} evt
         */
        onClickBackToList : function(evt) {
            app.router.go("backnumber");
            evt.preventDefault();
        },

        /**
         *  前の日へ戻るボタンを押したら呼ばれる
         *
         *  @param {Event} evt
         */
        onClickDayPrev : function(evt) {
            var dateParam = DateUtil.formatDate(DateUtil.addDay(this.date, -1), "yyyy-MM-dd");
            app.router.navigate("backnumber/" + dateParam, {
                trigger: true,
                replace: false
            });
        },

        /**
         *  次の日へ進むボタンを押したら呼ばれる
         *
         *  @param {Event} evt
         */
        onClickDayNext : function(evt) {
            var dateParam = DateUtil.formatDate(DateUtil.addDay(this.date, 1), "yyyy-MM-dd");
            app.router.navigate("backnumber/" + dateParam, {
                trigger: true,
                replace: false
            });
        },

        /**
         *  記事一覧画面を表示する
         */
        showNewsView : function() {
            console.assert(this.date, 'date shoud be specified');

            this.newsView = new BacknumberDateNewsView({
                date: this.date
            });
            this.setView('#backnumber-news', this.newsView);
        },

        /**
         *  日付の表示を更新する
         */
        updateDateLabel : function() {
            $(".backnumber-nav__month .date--year").html(DateUtil.formatDate(this.date, "yyyy"));
            $(".backnumber-nav__month .date--month").html(DateUtil.formatDate(this.date, "MM"));
            $(".backnumber-nav__month .date--day").html(DateUtil.formatDate(this.date, "dd"));
            $(".backnumber-nav__month .date--weekday").html(DateUtil.formatDate(this.date, "ddd"));

            // 最新配信日の場合は「次の日」を非表示にする
            if (DateUtil.formatDate(this.date, "yyyy-MM-dd") == DateUtil.formatDate(BusinessUtil.getCurrentPublishDate(), "yyyy-MM-dd")) {
                $("[data-backnumber-day-next]").css("visibility", "hidden");
            }
        }
    });
    module.exports = BacknumberDateView;
});
<commit_msg>NAM-356 新聞：バックナンバー　過去記事表示処理<commit_after>define(function(require, exports, module) {
    "use strict";

    var app = require("app");
    var AbstractView = require("modules/view/AbstractView");
    var BacknumberDateNewsView = require("modules/view/backnumber/BacknumberDateNewsView");
    var BusinessUtil = require("modules/util/BusinessUtil");
    var DateUtil = require("modules/util/DateUtil");

    /**
     *  バックナンバーページで見る各日付の記事のView
     *
     *  @class
     *  @exports BacknumberDateView
     *  @constructor
     */
    var BacknumberDateView = AbstractView.extend({
        /**
         *  テンプレートファイル
         */
        template : require("ldsh!templates/{mode}/backnumber/backnumberDate"),
        date : null,
        newsView: null,

        /**
         *  ViewのテンプレートHTMLの描画処理が完了する前に呼び出される。
         */
        beforeRendered : function() {
            this.showNewsView();
        },

        /**
         *  ViewのテンプレートHTMLの描画処理が完了した後に呼び出される。
         */
        afterRendered : function() {
            app.ga.trackPageView("BackNoList","新聞アプリ/バックナンバー記事一覧ページ");

            this.updateDateLabel();
        },

        /**
         *  初期化処理
         */
        initialize : function(options) {
            console.assert(options && options.date, 'Please pass the date value');

            options = options || {};

            var date = options.date;

            if (!(date instanceof Date)) {
                date = Date.parse(date);
            }
            if (!date) {
                date = new Date();
            }

            this.date = date;

            // 最終配信日より後の日付を指定された場合は、最終配信日に移動する
            var currentPublishDate = BusinessUtil.getCurrentPublishDate();
            if (DateUtil.formatDate(this.date, "yyyy-MM-dd") > DateUtil.formatDate(currentPublishDate, "yyyy-MM-dd")) {
                this.date = currentPublishDate;
                app.router.navigate("backnumber/" + DateUtil.formatDate(this.date, "yyyy-MM-dd"), {
                    trigger: true,
                    replace: false
                });
            }
        },

        events : {
            'click [data-backnumber-list]': 'onClickBackToList',
            'click [data-backnumber-day-prev]': 'onClickDayPrev',
            'click [data-backnumber-day-next]': 'onClickDayNext'
        },

        /**
         *  一覧から探すボタンを押したら呼ばれる
         *
         *  @param {Event} evt
         */
        onClickBackToList : function(evt) {
            app.router.go("backnumber");
            evt.preventDefault();
        },

        /**
         *  前の日へ戻るボタンを押したら呼ばれる
         *
         *  @param {Event} evt
         */
        onClickDayPrev : function(evt) {
            var dateParam = DateUtil.formatDate(DateUtil.addDay(this.date, -1), "yyyy-MM-dd");
            app.router.navigate("backnumber/" + dateParam, {
                trigger: true,
                replace: false
            });
        },

        /**
         *  次の日へ進むボタンを押したら呼ばれる
         *
         *  @param {Event} evt
         */
        onClickDayNext : function(evt) {
            var dateParam = DateUtil.formatDate(DateUtil.addDay(this.date, 1), "yyyy-MM-dd");
            app.router.navigate("backnumber/" + dateParam, {
                trigger: true,
                replace: false
            });
        },

        /**
         *  記事一覧画面を表示する
         */
        showNewsView : function() {
            console.assert(this.date, 'date shoud be specified');

            this.newsView = new BacknumberDateNewsView({
                date: this.date
            });
            this.setView('#backnumber-news', this.newsView);
        },

        /**
         *  日付の表示を更新する
         */
        updateDateLabel : function() {
            $(".backnumber-nav__month .date--year").html(DateUtil.formatDate(this.date, "yyyy"));
            $(".backnumber-nav__month .date--month").html(DateUtil.formatDate(this.date, "MM"));
            $(".backnumber-nav__month .date--day").html(DateUtil.formatDate(this.date, "dd"));
            $(".backnumber-nav__month .date--weekday").html(DateUtil.formatDate(this.date, "ddd"));

            // 最新配信日の場合は「次の日」を非表示にする
            if (DateUtil.formatDate(this.date, "yyyy-MM-dd") == DateUtil.formatDate(BusinessUtil.getCurrentPublishDate(), "yyyy-MM-dd")) {
                $("[data-backnumber-day-next]").css("visibility", "hidden");
            }
        }
    });
    module.exports = BacknumberDateView;
});
<|endoftext|>


<commit_before>var express = require('express');
var bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.json({ type: 'application/json' }));

var postgres = require('./lib/postgres');

// Create the express router object for Photos
var photoRouter = express.Router();

// A GET to the root of a resource returns a list of that resource
photoRouter.get('/', function(req, res) { });

// A POST to the root of a resource should create a new object
photoRouter.post('/', function(req, res) { });

// We specify a param in our path for the GET of a specific object
photoRouter.get('/:id', function(req, res) { });

// Similar to the GET on an object, to update it we can PATCH
photoRouter.patch('/:id', function(req, res) { });

// Delete a specific object
photoRouter.delete('/:id', function(req, res) { });

// Attach the routers for their respective paths
app.use('/photo', photoRouter);

module.exports = app;<commit_msg>updated the photoRouter<commit_after>var express = require('express');
var bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.json({ type: 'application/json' }));

var postgres = require('./lib/postgres');

function lookupPhoto(req, res, next) {
  var photoId = req.params.id;

// Create the express router object for Photos
var photoRouter = express.Router();
photoRouter.get('/', function(req, res) { });
photoRouter.post('/', function(req, res) {
	var sql = 'Insert into photo (description, filepath, album_id) VALEs ($1, $2, $3) RETURNING id';
	var data = [
    req.body.description,
    req.body.filepath,
    req.body.album_id
  ];

	postgres.client.query(sql, data, function(err, result) {
	    if (err) {
	      console.error(err);
	      res.statusCode = 500;
	      return res.json({
	        errors: ['Could not create photo']
	      });
	    }

// A GET to the root of a resource returns a list of that resource
photoRouter.get('/', function(req, res) { });

// A POST to the root of a resource should create a new object
photoRouter.post('/', function(req, res) { });

// We specify a param in our path for the GET of a specific object
photoRouter.get('/:id', function(req, res) { });

// Similar to the GET on an object, to update it we can PATCH
photoRouter.patch('/:id', function(req, res) { });

// Delete a specific object
photoRouter.delete('/:id', function(req, res) { });

// Attach the routers for their respective paths
app.use('/photo', photoRouter);

module.exports = app;<|endoftext|>


<commit_before>define(function(require, exports, module) {
    "use strict";

    var app = require("app");
    var PostingArticleRegistView = require("modules/view/posting/news/ArticleRegistView");
    var OpeArticleRegistConfirmView = require("modules/view/ope/news/OpeArticleRegistConfirmView");
    var ArticleRegistFileItemView = require("modules/view/posting/news/ArticleRegistFileItemView");
    var vexDialog = require("vexDialog");
    var Code = require("modules/util/Code");

    /**
     * 記事新規登録・編集画面のViewクラス
     *
     * @class 記事新規登録・編集画面のViewクラス
     * @exports OpeArticleRegistView
     * @constructor
     */
    var OpeArticleRegistView = PostingArticleRegistView.extend({
        /**
         * 編集時にデータを各フォームにセットする
         * @memberOf OpeArticleRegistView#
         */
        setData: function () {
            $("#articleRegistTitle").text("記事編集");
            if (this.model.get("type") === "2") {
                $("#articleCategory").val("5");
            } else {
                $("#articleCategory").val(this.model.get("type"));
            }
            $("#articleTitle").val(this.model.get("title"));
            $("#articleDate1").val(this.model.get("startDate"));
            if (this.model.get("endDate")) {
                $("#articleMultiDate").attr("checked","checked");
                $("#articleDate2").val(this.model.get("endDate"));
            }
            $("#articleTime1").val(this.model.get("startTime"));
            $("#articleTime2").val(this.model.get("endTime"));
            $("#articlePlace").val(this.model.get("place"));
            $("#articleDetail").val(this.model.get("description"));
            $("#articleNickname").val(this.model.get("nickname"));
            $("#articleContact").val(this.model.get("contactInfo"));
            $("#articleRangeDate1").val(this.model.get("publishedAt"));
            $("#articleRangeDate2").val(this.model.get("depublishedAt"));
            if (this.model.get("isRecommend")) {
                $("#articleRecommendCheck").attr("checked","checked");
            }
            if (this.model.get("type") !== "2") {
                this.imgArray = [];
                if (this.model.get("imageUrl")) {
                    this.imgArray.push({
                        fileName:this.model.get("imageUrl"),
                        imageComment:this.model.get("imageComment")
                    });
                }
                if (this.model.get("imageUrl2")) {
                    this.imgArray.push({
                        fileName: this.model.get("imageUrl2"),
                        imageComment: this.model.get("imageComment2")
                    });
                }
                if (this.model.get("imageUrl3")) {
                    this.imgArray.push({
                        fileName: this.model.get("imageUrl3"),
                        imageComment: this.model.get("imageComment3")
                    });
                }
                this.imgArrayLength = this.imgArray.length;
                if (this.imgArrayLength === 0) {
                    this.insertView("#fileArea", new ArticleRegistFileItemView()).render();
                    this.hideLoading();
                } else if (this.imgArrayLength >= 3) {
                    $("#addFileForm").hide();
                }
                var index = 0;
                _.each(this.imgArray,$.proxy(function(img) {
                    var view = new ArticleRegistFileItemView();
                    view.imageUrl = this.model.get("imagePath") + "/" + img.fileName;
                    view.imageComment = img.imageComment;
                    this.insertView("#fileArea", view).render();
                    // 全ての画像の読み込み処理が完了したタイミングでローディングマスクを解除したいため
                    // 子要素で画像読み込み完了時に発火したchangeイベントを拾って最後の画像読み込み完了時にhideLoadingする
                    view.$el.find("#previewFile").on("change",$.proxy(function() {
                        index++;
                        if (index >= this.imgArrayLength) {
                            this.hideLoading();
                            // 全ての画像読み込み完了した場合は、もうchageイベントは拾わない
                            $("img#previewFile").off("change");
                        }
                    },this));
                },this));
            } else {
                this.hideLoading();
            }
        },
        /**
         * モデルにデータをセットする関数
         * @memberOf OpeArticleRegistView#
         */
        setInputValue : function() {
            var type = this.model.get("type");
            if (type === "1" || type === "7" || type === "8") {
                this.model.set("publishedAt", $("#articleRangeDate1").val());
                this.model.set("depublishedAt", $("#articleRangeDate2").val());
            } else {
                PostingArticleRegistView.prototype.setInputValue.apply(this, arguments);
            }
            this.model.set("isRecommend", $("#articleRecommendCheck").is(":checked") ? "true" : null);
        },
        /**
         * バリデーションチェックがOKとなり、登録処理が開始された際に呼び出されるコールバック関数。
         * @memberOf OpeArticleRegistView#
         */
        onSubmit : function() {
            // 登録処理を開始する
            this.setInputValue();
            $("#articleRegistPage").hide();
            this.setView("#articleRegistConfirmWrapperPage", new OpeArticleRegistConfirmView({
                model : this.model,
                recommendArticle : this.recommendArticle,
                publishedAt : this.model.get("publishedAt"),
                thumbImageByteArray : this.thumbImageByteArray
            })).render();
            $("#contents__primary").scrollTop(0);
        },
        /**
         * バリデーションチェック
         * @memberOf OpeArticleRegistView#
         * @return {String} バリデーションメッセージ
         */
        validate : function() {
            if (this.model && this.model.get("type") === "2") {
                return null;
            }

            if ($("#articleMultiDate").is(":checked")) {
                if ($("#articleDate1").val() > $("#articleDate2").val()) {
                    return "日時の日付が開始と終了で逆になっています。";
                }
            }
            if ($("#articleTime1").val() && $("#articleTime2").val() &&
                    $("#articleTime1").val() > $("#articleTime2").val()) {
                return "日時の時間が開始と終了で逆になっています。";
            }
            if ($("#articleRangeDate1").val() && $("#articleRangeDate2").val() &&
                    $("#articleRangeDate1").val() > $("#articleRangeDate2").val()) {
                return "掲載期間の日付が開始と終了で逆になっています。";
            }

            var articleCategory = $("#articleCategory").val();
            if (articleCategory === "6" && !$(this.el).find("#previewFile").attr("src")) {
                return "写真投稿は写真の登録が必須です。";
            }

            return null;
        },
        /**
         * キャンセルボタン押下時のコールバック関数
         */
        onClickArticleCancelButton : function() {
            if (this.backFunction) {
                this.backFunction();
            } else {
                app.router.go("ope-top", this.targetDate);
            }
        },

        /**
         * ViewのテンプレートHTMLの描画処理が完了した後に呼び出される。
         * @memberOf OpeArticleRegistView#
         */
        afterRendered : function() {
            $("#snap-content").scrollTop(0);

            // 記事カテゴリ選択肢
            var mapCategory = _.indexBy(Code.ARTICLE_CATEGORY_LIST, "key");
            _.each(Code.ARTICLE_CATEGORY_LIST_BY_MODE[app.config.basic.mode], function(key) {
                var category = mapCategory[key];
                var option = $("<option>");
                option.attr("value", category.key);
                option.text((category.valueByMode ? category.valueByMode[app.config.basic.mode] : null) ||
                        category.value);
                option.data("site", category.value);
                $("#articleCategory").append(option);
            });

            if (this.model) {
                // 編集時
                this.setData();
            } else {
                var tomorrow = DateUtil.addDay(new Date(), 1);
                $("#articleRangeDate1").val(DateUtil.formatDate(tomorrow, "yyyy-MM-dd"));
                this.insertView("#fileArea", new ArticleRegistFileItemView()).render();

                // 記事カテゴリ初期値
                if (this.articleCategory) {
                    $("#articleCategory").val(this.articleCategory);
                }
                // レポートを書く場合
                if (this.parentModel) {
                    $("#articleTitle").val(this.parentModel.get("title") + "の報告");
                    $("#articleDate1").val(this.parentModel.get("startDate"));
                    if (this.parentModel.get("endDate")) {
                        $("#articleMultiDate").attr("checked", "checked");
                        $("#articleDate2").val(this.parentModel.get("endDate"));
                    }
                    $("#articleTime1").val(this.parentModel.get("startTime"));
                    $("#articleTime2").val(this.parentModel.get("endTime"));
                    $("#articlePlace").val(this.parentModel.get("place"));
                    $("#articleContact").val(this.parentModel.get("contactInfo"));
                }
            }

            if (this.model.get("type") === "1" || this.model.get("type") === "7" || this.model.get("type") === "8") {
                this.isMinpoArticle = this.model.isMinpoScraping();
                this.showImage();
                this.afterRenderCommon();
                this.hideLoading();
            }
            this.chageMultiDateCheckbox();
            this.onChangeCategory();
            this.$el.find("a").attr("href", "javascript:void(0)");
        },

        /**
         * このViewが表示している記事に関連する画像データの取得と表示を行う。
         * @memberOf OpeArticleRegistView#
         */
        showImage : function() {
            var self = this;
            var imageElems = $(this.el).find("img");

            if (this.isMinpoArticle) {
                // この記事のimg要素にはWebDAVのパスが設定されているため、取得しにいく
                _.each(imageElems, function(imageElement) {
                    var imageUrl = $(imageElement).attr("src");
                    this.showPIOImage($(imageElement), {
                        imageUrl : imageUrl
                    }, true, $.proxy(this.onClickImage, this));
                }.bind(this));
            } else {
                this.setColorbox(imageElems);
            }

            var articleImage = $(this.el).find(".articleDetailImage");

            if (this.model.get("imageUrl")) {
                articleImage.on("error", function() {
                    articleImage.hide();
                });
                var imageUrl = this.model.get("imageUrl");
                this.showPIOImage(articleImage, {
                    imageUrl : imageUrl
                }, true, $.proxy(this.onClickImage, this));
            } else {
                // ArticleListViewでiscrollを初期化する際に
                // 記事内のimgの読み込みを待機しているので
                // このimgは決して読み込まれないことを通知する
                articleImage.trigger('error', "this image will never be loaded");
                $(this.el).find(".articleDetailImageArea").hide();
            }

            if (this.model.get("imageUrl")) {
                $(this.el).find("#nehan-articleDetailImage").parent().css("width", "auto");
                $(this.el).find("#nehan-articleDetailImage").parent().css("height", "auto");
                $(this.el).find("#nehan-articleDetailImage").css("width", "auto");
                $(this.el).find("#nehan-articleDetailImage").css("height", "auto");
            }
        },

        /**
         * Viewの秒が処理の後の、記事表示処理で共通する処理を行う。
         *

         * 以下の処理を行う。
         *

         *
お気に入りボタンの表示・非表示判定

         *
タグの表示

         *
画像クリックイベントのバインド
 画像クリック時に、対象画像の保存処理を行うためのイベントをバインドする。

         *

         * @memberOf OpeArticleRegistView#
         */
        afterRenderCommon : function() {
            // 既にお気に入り登録されている記事のお気に入りボタンを非表示にする
            if (this.model.get("isFavorite")) {
                this.$el.find('[data-favorite-register-button]').hide();
            } else {
                this.$el.find('[data-favorite-delete-button]').hide();
            }
            if (this.model.get("isMyRecommend")) {
                this.$el.find('[data-recommend-register-button]').hide();
            } else {
                this.$el.find('[data-recommend-delete-button]').hide();
            }
            $(".panzoom-elements").panzoom({
                minScale : 1,
                contain : "invert"
            });
        },

        /**
         * colorboxの設定を行う
         * @param {Array} imageElems img要素の配列
         * @memberOf OpeArticleRegistView#
         */
        setColorbox : function(imageElems) {
            imageElems.each(function() {
                if ($(this).attr("src")) {
                    $(this).wrap("");
                }
            });
            $(this.el).find(".expansionPicture").colorbox({
                closeButton : false,
                current : "",
                photo : true,
                maxWidth : "83%",
                maxHeight : "100%",
                onComplete : $.proxy(function() {
                    $("#cboxOverlay").append("<button id='cboxCloseButton' class='small button'>閉じる</button>");
                    $("#cboxOverlay").append("<button id='cboxSaveButton' class='small button'>画像を保存</button>");
                    $("#cboxCloseButton").click(function() {
                        $.colorbox.close();
                    });
                    $("#cboxSaveButton").click($.proxy(this.onClickImage, this));
                }, this),
                onClosed : function() {
                    $("#cboxSaveButton").remove();
                    $("#cboxCloseButton").remove();
                }
            });
        }
    });
    module.exports = OpeArticleRegistView;
});
<commit_msg>NAM-1126　管理アプリ：RSS収集記事も編集出来るようにする<commit_after>define(function(require, exports, module) {
    "use strict";

    var app = require("app");
    var PostingArticleRegistView = require("modules/view/posting/news/ArticleRegistView");
    var OpeArticleRegistConfirmView = require("modules/view/ope/news/OpeArticleRegistConfirmView");
    var ArticleRegistFileItemView = require("modules/view/posting/news/ArticleRegistFileItemView");
    var vexDialog = require("vexDialog");
    var Code = require("modules/util/Code");

    /**
     * 記事新規登録・編集画面のViewクラス
     *
     * @class 記事新規登録・編集画面のViewクラス
     * @exports OpeArticleRegistView
     * @constructor
     */
    var OpeArticleRegistView = PostingArticleRegistView.extend({
        /**
         * 編集時にデータを各フォームにセットする
         * @memberOf OpeArticleRegistView#
         */
        setData: function () {
            $("#articleRegistTitle").text("記事編集");
            if (this.model.get("type") === "2") {
                $("#articleCategory").val("5");
            } else {
                $("#articleCategory").val(this.model.get("type"));
            }
            $("#articleTitle").val(this.model.get("title"));
            $("#articleDate1").val(this.model.get("startDate"));
            if (this.model.get("endDate")) {
                $("#articleMultiDate").attr("checked","checked");
                $("#articleDate2").val(this.model.get("endDate"));
            }
            $("#articleTime1").val(this.model.get("startTime"));
            $("#articleTime2").val(this.model.get("endTime"));
            $("#articlePlace").val(this.model.get("place"));
            $("#articleDetail").val(this.model.get("description"));
            $("#articleNickname").val(this.model.get("nickname"));
            $("#articleContact").val(this.model.get("contactInfo"));
            $("#articleRangeDate1").val(this.model.get("publishedAt"));
            $("#articleRangeDate2").val(this.model.get("depublishedAt"));
            if (this.model.get("isRecommend")) {
                $("#articleRecommendCheck").attr("checked","checked");
            }
            if (this.model.get("type") !== "2") {
                this.imgArray = [];
                if (this.model.get("imageUrl")) {
                    this.imgArray.push({
                        fileName:this.model.get("imageUrl"),
                        imageComment:this.model.get("imageComment")
                    });
                }
                if (this.model.get("imageUrl2")) {
                    this.imgArray.push({
                        fileName: this.model.get("imageUrl2"),
                        imageComment: this.model.get("imageComment2")
                    });
                }
                if (this.model.get("imageUrl3")) {
                    this.imgArray.push({
                        fileName: this.model.get("imageUrl3"),
                        imageComment: this.model.get("imageComment3")
                    });
                }
                this.imgArrayLength = this.imgArray.length;
                if (this.imgArrayLength === 0) {
                    this.insertView("#fileArea", new ArticleRegistFileItemView()).render();
                    this.hideLoading();
                } else if (this.imgArrayLength >= 3) {
                    $("#addFileForm").hide();
                }
                var index = 0;
                _.each(this.imgArray,$.proxy(function(img) {
                    var view = new ArticleRegistFileItemView();
                    view.imageUrl = this.model.get("imagePath") + "/" + img.fileName;
                    view.imageComment = img.imageComment;
                    this.insertView("#fileArea", view).render();
                    // 全ての画像の読み込み処理が完了したタイミングでローディングマスクを解除したいため
                    // 子要素で画像読み込み完了時に発火したchangeイベントを拾って最後の画像読み込み完了時にhideLoadingする
                    view.$el.find("#previewFile").on("change",$.proxy(function() {
                        index++;
                        if (index >= this.imgArrayLength) {
                            this.hideLoading();
                            // 全ての画像読み込み完了した場合は、もうchageイベントは拾わない
                            $("img#previewFile").off("change");
                        }
                    },this));
                },this));
            } else {
                this.hideLoading();
            }
        },
        /**
         * モデルにデータをセットする関数
         * @memberOf OpeArticleRegistView#
         */
        setInputValue : function() {
            var type = this.model.get("type");
            if (type === "1" || type === "7" || type === "8") {
                this.model.set("publishedAt", $("#articleRangeDate1").val());
                this.model.set("depublishedAt", $("#articleRangeDate2").val());
            } else {
                PostingArticleRegistView.prototype.setInputValue.apply(this, arguments);
            }
            this.model.set("isRecommend", $("#articleRecommendCheck").is(":checked") ? "true" : null);
        },
        /**
         * バリデーションチェックがOKとなり、登録処理が開始された際に呼び出されるコールバック関数。
         * @memberOf OpeArticleRegistView#
         */
        onSubmit : function() {
            // 登録処理を開始する
            this.setInputValue();
            $("#articleRegistPage").hide();
            this.setView("#articleRegistConfirmWrapperPage", new OpeArticleRegistConfirmView({
                model : this.model,
                recommendArticle : this.recommendArticle,
                publishedAt : this.model.get("publishedAt"),
                thumbImageByteArray : this.thumbImageByteArray
            })).render();
            $("#contents__primary").scrollTop(0);
        },
        /**
         * バリデーションチェック
         * @memberOf OpeArticleRegistView#
         * @return {String} バリデーションメッセージ
         */
        validate : function() {
            if (this.model && this.model.get("type") === "2") {
                return null;
            }

            if ($("#articleMultiDate").is(":checked")) {
                if ($("#articleDate1").val() > $("#articleDate2").val()) {
                    return "日時の日付が開始と終了で逆になっています。";
                }
            }
            if ($("#articleTime1").val() && $("#articleTime2").val() &&
                    $("#articleTime1").val() > $("#articleTime2").val()) {
                return "日時の時間が開始と終了で逆になっています。";
            }
            if ($("#articleRangeDate1").val() && $("#articleRangeDate2").val() &&
                    $("#articleRangeDate1").val() > $("#articleRangeDate2").val()) {
                return "掲載期間の日付が開始と終了で逆になっています。";
            }

            var articleCategory = $("#articleCategory").val();
            if (articleCategory === "6" && !$(this.el).find("#previewFile").attr("src")) {
                return "写真投稿は写真の登録が必須です。";
            }

            return null;
        },
        /**
         * キャンセルボタン押下時のコールバック関数
         */
        onClickArticleCancelButton : function() {
            if (this.backFunction) {
                this.backFunction();
            } else {
                app.router.go("ope-top", this.targetDate);
            }
        },

        /**
         * ViewのテンプレートHTMLの描画処理が完了した後に呼び出される。
         * @memberOf OpeArticleRegistView#
         */
        afterRendered : function() {
            $("#snap-content").scrollTop(0);

            // 記事カテゴリ選択肢
            var mapCategory = _.indexBy(Code.ARTICLE_CATEGORY_LIST, "key");
            _.each(Code.ARTICLE_CATEGORY_LIST_BY_MODE[app.config.basic.mode], function(key) {
                var category = mapCategory[key];
                var option = $("<option>");
                option.attr("value", category.key);
                option.text((category.valueByMode ? category.valueByMode[app.config.basic.mode] : null) ||
                        category.value);
                option.data("site", category.value);
                $("#articleCategory").append(option);
            });

            if (this.model) {
                // 編集時
                this.setData();
            } else {
                var tomorrow = DateUtil.addDay(new Date(), 1);
                $("#articleRangeDate1").val(DateUtil.formatDate(tomorrow, "yyyy-MM-dd"));
                this.insertView("#fileArea", new ArticleRegistFileItemView()).render();

                // 記事カテゴリ初期値
                if (this.articleCategory) {
                    $("#articleCategory").val(this.articleCategory);
                }
                // レポートを書く場合
                if (this.parentModel) {
                    $("#articleTitle").val(this.parentModel.get("title") + "の報告");
                    $("#articleDate1").val(this.parentModel.get("startDate"));
                    if (this.parentModel.get("endDate")) {
                        $("#articleMultiDate").attr("checked", "checked");
                        $("#articleDate2").val(this.parentModel.get("endDate"));
                    }
                    $("#articleTime1").val(this.parentModel.get("startTime"));
                    $("#articleTime2").val(this.parentModel.get("endTime"));
                    $("#articlePlace").val(this.parentModel.get("place"));
                    $("#articleContact").val(this.parentModel.get("contactInfo"));
                }
            }

            if (this.model.get("type") === "1" || this.model.get("type") === "7" || this.model.get("type") === "8") {
                this.isMinpoArticle = this.model.isMinpoScraping();
                this.showImage();
                this.afterRenderCommon();
                this.hideLoading();
            }
            this.chageMultiDateCheckbox();
            this.onChangeCategory();
            this.$el.find("a").on("click", function(ev) {
                    ev.preventDefault();
            });
        },

        /**
         * このViewが表示している記事に関連する画像データの取得と表示を行う。
         * @memberOf OpeArticleRegistView#
         */
        showImage : function() {
            var self = this;
            var imageElems = $(this.el).find("img");

            if (this.isMinpoArticle) {
                // この記事のimg要素にはWebDAVのパスが設定されているため、取得しにいく
                _.each(imageElems, function(imageElement) {
                    var imageUrl = $(imageElement).attr("src");
                    this.showPIOImage($(imageElement), {
                        imageUrl : imageUrl
                    }, true, $.proxy(this.onClickImage, this));
                }.bind(this));
            } else {
                this.setColorbox(imageElems);
            }

            var articleImage = $(this.el).find(".articleDetailImage");

            if (this.model.get("imageUrl")) {
                articleImage.on("error", function() {
                    articleImage.hide();
                });
                var imageUrl = this.model.get("imageUrl");
                this.showPIOImage(articleImage, {
                    imageUrl : imageUrl
                }, true, $.proxy(this.onClickImage, this));
            } else {
                // ArticleListViewでiscrollを初期化する際に
                // 記事内のimgの読み込みを待機しているので
                // このimgは決して読み込まれないことを通知する
                articleImage.trigger('error', "this image will never be loaded");
                $(this.el).find(".articleDetailImageArea").hide();
            }

            if (this.model.get("imageUrl")) {
                $(this.el).find("#nehan-articleDetailImage").parent().css("width", "auto");
                $(this.el).find("#nehan-articleDetailImage").parent().css("height", "auto");
                $(this.el).find("#nehan-articleDetailImage").css("width", "auto");
                $(this.el).find("#nehan-articleDetailImage").css("height", "auto");
            }
        },

        /**
         * Viewの秒が処理の後の、記事表示処理で共通する処理を行う。
         *

         * 以下の処理を行う。
         *

         *
お気に入りボタンの表示・非表示判定

         *
タグの表示

         *
画像クリックイベントのバインド
 画像クリック時に、対象画像の保存処理を行うためのイベントをバインドする。

         *

         * @memberOf OpeArticleRegistView#
         */
        afterRenderCommon : function() {
            // 既にお気に入り登録されている記事のお気に入りボタンを非表示にする
            if (this.model.get("isFavorite")) {
                this.$el.find('[data-favorite-register-button]').hide();
            } else {
                this.$el.find('[data-favorite-delete-button]').hide();
            }
            if (this.model.get("isMyRecommend")) {
                this.$el.find('[data-recommend-register-button]').hide();
            } else {
                this.$el.find('[data-recommend-delete-button]').hide();
            }
            $(".panzoom-elements").panzoom({
                minScale : 1,
                contain : "invert"
            });
        },

        /**
         * colorboxの設定を行う
         * @param {Array} imageElems img要素の配列
         * @memberOf OpeArticleRegistView#
         */
        setColorbox : function(imageElems) {
            imageElems.each(function() {
                if ($(this).attr("src")) {
                    $(this).wrap("");
                }
            });
            $(this.el).find(".expansionPicture").colorbox({
                closeButton : false,
                current : "",
                photo : true,
                maxWidth : "83%",
                maxHeight : "100%",
                onComplete : $.proxy(function() {
                    $("#cboxOverlay").append("<button id='cboxCloseButton' class='small button'>閉じる</button>");
                    $("#cboxOverlay").append("<button id='cboxSaveButton' class='small button'>画像を保存</button>");
                    $("#cboxCloseButton").click(function() {
                        $.colorbox.close();
                    });
                    $("#cboxSaveButton").click($.proxy(this.onClickImage, this));
                }, this),
                onClosed : function() {
                    $("#cboxSaveButton").remove();
                    $("#cboxCloseButton").remove();
                }
            });
        }
    });
    module.exports = OpeArticleRegistView;
});
<|endoftext|>


<commit_before>
// placeholder for now - should talk when merged to properly integrate this with
// existing "board" and "players" implementations
function Board(players) {
  this.players = players; // just a placeholder for now - on merge should combine
  this.spaces = [];
}

// class definitions for any space on the board -
// properties, utilities, free parking, go, etc.
function Space(name) {
  this.name = name;
  this.occupier = null;
}
// every space needs a landing action
Space.prototype.perform_landing_action = function(){
  console.log("You landed on " + this.name);
};

function Property(name, cost, property_group) {
  Space.call(this, name);
  this.cost = cost;
  this.mortage = .5*cost;
  this.property_group = property_group; // "red", "blue", "railroad", etc.
  this.owner = null;
}
Property.prototype = Object.create(Space.prototype); // subclassing space

// rent should be array with following format:
// [1 owned, 2 owned ... (3 owned, 4 owned)]
function UtilityProperty(name, cost, property_group, rent) {
  this.rent = rent;
  Property.call(this, this.name, this.cost, this.property_group);
}
UtilityProperty.prototype = Object.create(Property.prototype);
UtilityProperty.prototype.perform_landing_action = function(player) {
};

// rent should be array with following format:
// [rent, 1 house, 2 houses, 3 houses, 4 houses, hotel]
function HousingProperty(name, cost, property_group, rent) {
  this.rent = rent;
  Property.call(this, this.name, this.cost, this.property_group);
}
HousingProperty.prototype = Object.create(Property.prototype);
HousingProperty.prototype.perform_landing_action = function(player) {
};

function Chance() {}
Chance.prototype = Object.create(Space.prototype);
Chance.prototype.perform_landing_action = function(player) {
};

function CommunityChest() {}
CommunityChest.prototype = Object.create(Space.prototype);
Chance.prototype.perform_landing_action = function(player) {
};

function FreeParking() {}
FreeParking.prototype = Object.create(Space.prototype);
FreeParking.prototype.perform_landing_action = function(player) {
};

function Jail() {}
GoToJail.prototype = Object.create(Space.prototype);
GoToJail.prototype.perform_landing_action = function(player) {
};

function GoToJail() {}
GoToJail.prototype = Object.create(Space.prototype);
GoToJail.prototype.perform_landing_action = function(player) {
};

function Tax() {
  this.tax_amount = 0; // give default value of 0, should be overridden
}
Tax.prototype = Object.create(Space.prototype);
Tax.prototype.perform_landing_action = function(player) {
  this.player.money -= this.tax_amount;
};

function IncomeTax() {
  this.tax_amount = 200;
}
IncomeTax.prototype = Object.create(Tax.prototype);

function SuperTax() {
  this.tax_amount = 100;
}
SuperTax.prototype = Object.create(Tax.prototype);

function Go() {}
Go.prototype = Object.create(Space.prototype);
Go.prototype.perform_landing_action = function(player) {
  this.player.money += 400;
};

// end of space class definitions

// now let's build the board
var board;
function build_board() {
  board = new Board();
  build_spaces(board);
}

// order is important
// todo: finish filling in all the board spaces w/ data
function build_spaces(board) {
  var props = properties_list();
  board.spaces = [

    // first row
    new Go(),
    new property_for_index(0, props),
    new CommunityChest(),
    new property_for_index(1, props),
    new IncomeTax(),
    new property_for_index(22, props),
    new property_for_index(2, props),
    new Chance(),
    property_for_index(3, props),
    property_for_index(4, props),
    new Jail()

    // todo: rows 2-4
  ];
}

// indices correlate to order in below function properties_list()
function property_for_index(index, props) {
  if (index <= 21) {
    return new HousingProperty(props[index][0], props[index][2], props[index][1], props[index][4]);
  } else if (index <= 25) {
    return new UtilityProperty(props[index][0], props[index][2], props[index][3]);
  } else {
    return new UtilityProperty(props[index][0], props[index][2], NULL);
  }
}

/* housing properties: [name, color, cost, house cost, [rent, 1, 2, 3, 4, hotel]]
 railroads: [name, "Railroad", cost, [1, 2, 3, 4]]
 utilities: [name, "Utility", cost]
*/
function properties_list() {
  return [
    ["Mediterranean Ave", "Dark Purple", 60, 50, [2, 10, 30, 90, 160, 250]],
    ["Baltic Ave", "Dark Purple", 60, 50, [4, 20, 60, 180, 320, 450]],

    ["Oriental Ave", "Light Blue", 100, 50, [6, 30, 90, 270, 400, 550]],
    ["Vermont Ave", "Light Blue", 100, 50, [6, 30, 90, 270, 400, 550]],
    ["Connecticut Ave", "Light Blue", 120, 50, [8, 40, 100, 300, 450, 600]],

    ["St. Charles Place", "Pink", 140, 100, [10, 50, 150, 450, 625, 750]], // 5
    ["States Ave", "Pink", 140, 100, [10, 50, 150, 450, 625, 750]],
    ["Virginia Ave", "Pink", 160, 100 [12, 60, 180, 500, 700, 900]],

    ["St. James Place", "Orange", 180, 100, [14, 70, 200, 550, 750, 950]],
    ["Tennessee Ave", "Orange", 180, 100, [14, 70, 200, 550, 750, 950]],
    ["New York Ave", "Orange", 200, 100, [16, 80, 220, 600, 800, 1000]], // 10

    ["Kentucky Ave", "Red", 220, 150, [18, 90, 250, 700, 875, 1050]],
    ["Indiana Ave", "Red", 220, 150, [18, 90, 250, 700, 875, 1050]],
    ["Illinois Ave", "Red", 240, 150, [20, 100, 300, 750, 925, 1100]],

    ["Atlantic Ave", "Yellow", 260, 150, [22, 110, 330, 800, 975, 1150]],
    ["Ventnor Ave", "Yellow", 260, 150, [22, 110, 330, 800, 975, 1150]], // 15
    ["Marvin Gardens", "Yellow", 280, 150, [24, 120, 360, 850, 1025, 1200]],

    ["Pacific Ave", "Green", 300, 200, [26, 130, 390, 900, 1100, 1275]],
    ["North Carolina Ave", "Green", 300, 200, [26, 130, 390, 900, 1100, 1275]],
    ["Pennsylvaniva Ave", "Green", 320, 200, [28, 150, 450, 1000, 1200, 1400]],

    ["Park Place", "Blue", 350, 200, [35, 175, 500, 1100, 1300, 1500]], // 20
    ["Boardwalk", "Blue", 400, 200, [50, 200, 600, 1400, 1700, 2000]],

    ["Reading Railroad", "Railroad", 200, [25, 50, 100, 200]],
    ["Pennsylvania Railroad", "Railroad", 200, [25, 50, 100, 200]],
    ["B. & O. Railroad", "Railroad", 200, [25, 50, 100, 200]],
    ["Shortline Railroad", "Railroad", 200, [25, 50, 100, 200]], // 25

    ["Electric Company", "Utility", 150],
    ["WaterWorks", "Utility", 150]
  ];

}

window.onload = function() {
  build_board();
};
<commit_msg>removing go landing action (passing handled elsewhere)<commit_after>
// placeholder for now - should talk when merged to properly integrate this with
// existing "board" and "players" implementations
function Board(players) {
  this.players = players; // just a placeholder for now - on merge should combine
  this.spaces = [];
}

// class definitions for any space on the board -
// properties, utilities, free parking, go, etc.
function Space(name) {
  this.name = name;
  this.occupier = null;
}
// every space needs a landing action
Space.prototype.perform_landing_action = function(){
  console.log("You landed on " + this.name);
};

function Property(name, cost, property_group) {
  Space.call(this, name);
  this.cost = cost;
  this.mortage = .5*cost;
  this.property_group = property_group; // "red", "blue", "railroad", etc.
  this.owner = null;
}
Property.prototype = Object.create(Space.prototype); // subclassing space

// rent should be array with following format:
// [1 owned, 2 owned ... (3 owned, 4 owned)]
function UtilityProperty(name, cost, property_group, rent) {
  this.rent = rent;
  Property.call(this, this.name, this.cost, this.property_group);
}
UtilityProperty.prototype = Object.create(Property.prototype);
UtilityProperty.prototype.perform_landing_action = function(player) {
};

// rent should be array with following format:
// [rent, 1 house, 2 houses, 3 houses, 4 houses, hotel]
function HousingProperty(name, cost, property_group, rent) {
  this.rent = rent;
  Property.call(this, this.name, this.cost, this.property_group);
}
HousingProperty.prototype = Object.create(Property.prototype);
HousingProperty.prototype.perform_landing_action = function(player) {
};

function Chance() {}
Chance.prototype = Object.create(Space.prototype);
Chance.prototype.perform_landing_action = function(player) {
};

function CommunityChest() {}
CommunityChest.prototype = Object.create(Space.prototype);
Chance.prototype.perform_landing_action = function(player) {
};

function FreeParking() {}
FreeParking.prototype = Object.create(Space.prototype);
FreeParking.prototype.perform_landing_action = function(player) {
};

function Jail() {}
GoToJail.prototype = Object.create(Space.prototype);
GoToJail.prototype.perform_landing_action = function(player) {
};

function GoToJail() {}
GoToJail.prototype = Object.create(Space.prototype);
GoToJail.prototype.perform_landing_action = function(player) {
};

function Tax() {
  this.tax_amount = 0; // give default value of 0, should be overridden
}
Tax.prototype = Object.create(Space.prototype);
Tax.prototype.perform_landing_action = function(player) {
  this.player.money -= this.tax_amount;
};

function IncomeTax() {
  this.tax_amount = 200;
}
IncomeTax.prototype = Object.create(Tax.prototype);

function SuperTax() {
  this.tax_amount = 100;
}
SuperTax.prototype = Object.create(Tax.prototype);

function Go() {}
Go.prototype = Object.create(Space.prototype);

// end of space class definitions

// now let's build the board
var board;
function build_board() {
  board = new Board();
  build_spaces(board);
}

// order is important
// todo: finish filling in all the board spaces w/ data
function build_spaces(board) {
  var props = properties_list();
  board.spaces = [

    // first row
    new Go(),
    new property_for_index(0, props),
    new CommunityChest(),
    new property_for_index(1, props),
    new IncomeTax(),
    new property_for_index(22, props),
    new property_for_index(2, props),
    new Chance(),
    property_for_index(3, props),
    property_for_index(4, props),
    new Jail()

    // todo: rows 2-4
  ];
}

// indices correlate to order in below function properties_list()
function property_for_index(index, props) {
  if (index <= 21) {
    return new HousingProperty(props[index][0], props[index][2], props[index][1], props[index][4]);
  } else if (index <= 25) {
    return new UtilityProperty(props[index][0], props[index][2], props[index][3]);
  } else {
    return new UtilityProperty(props[index][0], props[index][2], NULL);
  }
}

/* housing properties: [name, color, cost, house cost, [rent, 1, 2, 3, 4, hotel]]
 railroads: [name, "Railroad", cost, [1, 2, 3, 4]]
 utilities: [name, "Utility", cost]
*/
function properties_list() {
  return [
    ["Mediterranean Ave", "Dark Purple", 60, 50, [2, 10, 30, 90, 160, 250]],
    ["Baltic Ave", "Dark Purple", 60, 50, [4, 20, 60, 180, 320, 450]],

    ["Oriental Ave", "Light Blue", 100, 50, [6, 30, 90, 270, 400, 550]],
    ["Vermont Ave", "Light Blue", 100, 50, [6, 30, 90, 270, 400, 550]],
    ["Connecticut Ave", "Light Blue", 120, 50, [8, 40, 100, 300, 450, 600]],

    ["St. Charles Place", "Pink", 140, 100, [10, 50, 150, 450, 625, 750]], // 5
    ["States Ave", "Pink", 140, 100, [10, 50, 150, 450, 625, 750]],
    ["Virginia Ave", "Pink", 160, 100 [12, 60, 180, 500, 700, 900]],

    ["St. James Place", "Orange", 180, 100, [14, 70, 200, 550, 750, 950]],
    ["Tennessee Ave", "Orange", 180, 100, [14, 70, 200, 550, 750, 950]],
    ["New York Ave", "Orange", 200, 100, [16, 80, 220, 600, 800, 1000]], // 10

    ["Kentucky Ave", "Red", 220, 150, [18, 90, 250, 700, 875, 1050]],
    ["Indiana Ave", "Red", 220, 150, [18, 90, 250, 700, 875, 1050]],
    ["Illinois Ave", "Red", 240, 150, [20, 100, 300, 750, 925, 1100]],

    ["Atlantic Ave", "Yellow", 260, 150, [22, 110, 330, 800, 975, 1150]],
    ["Ventnor Ave", "Yellow", 260, 150, [22, 110, 330, 800, 975, 1150]], // 15
    ["Marvin Gardens", "Yellow", 280, 150, [24, 120, 360, 850, 1025, 1200]],

    ["Pacific Ave", "Green", 300, 200, [26, 130, 390, 900, 1100, 1275]],
    ["North Carolina Ave", "Green", 300, 200, [26, 130, 390, 900, 1100, 1275]],
    ["Pennsylvaniva Ave", "Green", 320, 200, [28, 150, 450, 1000, 1200, 1400]],

    ["Park Place", "Blue", 350, 200, [35, 175, 500, 1100, 1300, 1500]], // 20
    ["Boardwalk", "Blue", 400, 200, [50, 200, 600, 1400, 1700, 2000]],

    ["Reading Railroad", "Railroad", 200, [25, 50, 100, 200]],
    ["Pennsylvania Railroad", "Railroad", 200, [25, 50, 100, 200]],
    ["B. & O. Railroad", "Railroad", 200, [25, 50, 100, 200]],
    ["Shortline Railroad", "Railroad", 200, [25, 50, 100, 200]], // 25

    ["Electric Company", "Utility", 150],
    ["WaterWorks", "Utility", 150]
  ];

}

window.onload = function() {
  build_board();
};
<|endoftext|>


<commit_before>function(vis){
    // Add some useful state to the vis object (for use in the mouse
    // callbacks below).
    vis.dragging = {};
    vis.dragging.on = false;
    vis.dragging.last = [-1, -1];
    vis.dragging.from = -1;

    // A D3 selection representing the currently selected range.
    vis.selection = null;

    // For the "recompute" action (a middle click on the selection).
    vis.middle_clicking = false;

    // The current dataset.
    vis.dataset = {values: null};

    // The number of bins we are working with.
    //
    // TODO(choudhury): this should be controllable externally somehow.  Ask
    // Jeff H. about whether we might store "extra" parameters in a special
    // field of the Vega object.
    vis.bins = 100;

    // The total number of records in the current dataset.
    vis.count = 0;

    // The bounds of the data range.
    vis.lo = null;
    vis.hi = null;

    // This function creates a synthetic dataset made from completely random
    // values.  It's mainly a debugging tool.
    var getSyntheticData = function(){
        var dat = [];
        for(var i=0; i<100; i++){
            var o = {
                bin: i,
                value: Math.random(),
                state: "unselected"
            };
            dat.push(o);
        }

        return { values: dat };
    };

    // This function queries the database for the high and low values in the
    // dataset.
    var getDataBounds = function(callback){
        // NOTE:  This function is a perfect example of where iced coffee
        // script's await/defer mechanism would be nice :-\.
        $.ajax({
            url: '/service/mongo/mongo/xdata/flickr_paris',
            data: {
                sort: JSON.stringify([['date',1]]),
                fields: JSON.stringify(['date']),
                limit: 1
            },
            dataType: 'json',
            success: function(response){
                vis.lo = +response.result.data[0].date.$date;

                $.ajax({
                    url: '/service/mongo/mongo/xdata/flickr_paris',
                    data: {
                        sort: JSON.stringify([['date',-1]]),
                        fields: JSON.stringify(['date']),
                        limit: 1
                    },
                    dataType: 'json',
                    success: function(response){
                        vis.hi = +response.result.data[0].date.$date;

                        if(callback !== undefined){
                            callback();
                        }
                    }
                });
            }
        });
    };

    // This function queries the database for the count of data items falling
    // between "lo" and "hi", divided up into "bins" bins.
    var getDBdata = function(lo, hi, bins, callback){
        vis.dataset.values = new Array(bins);
        vis.count = 0;

        var completed = 0;
        var callback_maker = function(which){
            return function(response){
                if(response.error != null){
                    console.log("error: could not complete database request for range " + which);
                    console.log(response.error);
                    return;
                }

                vis.dataset.values[which] = {
                    bin: (which + 1) / bins,
                    count: +response.result.count,
                    state: "unselected"
                };

                vis.count += +response.result.count;

                completed++;
                if(completed === bins){
                    for(var i=0; i<vis.bins; i++){
                        vis.dataset.values[i].value = vis.dataset.values[i].count / vis.count;
                    }

                    if(callback !== undefined){
                        console.log("calling callback");
                        callback();
                    }
                }
            };
        };

        var binsize = (hi - lo) / bins;

        for(var i=0; i<bins; i++){
            // Issue an ajax call to retrieve the count of items falling in the
            // range [lo+i*binsize, lo+(i+1)*binsize).
            var mongostring = JSON.stringify({date: {$gte: {$date: lo + binsize*i}, $lt: {$date: lo + binsize*(i+1)}}});
            $.ajax({
                url: '/service/mongo/mongo/xdata/flickr_paris',
                data: {
                    query: mongostring,
                    limit: 0,
                    fill: false
                },
                dataType: 'json',
                success: callback_maker(i),
                done: function(){ console.log("aww"); }
            });
        }
    };

    // Initialize the data by calling the database retrieval function.
    getDataBounds(function(){
        console.log("lo: " + vis.lo);
        console.log("hi: " + vis.hi);
        getDBdata(vis.lo, vis.hi, vis.bins, function(){
            vis.data(vis.dataset).update();
        });
    });

    // Select the invisible container bars, for use in the mouse callbacks.
    var bars = d3.select(vis.el()).select(".mark-1").selectAll("rect");

    // Utility function to mark a bar as being part of the growing
    // selection.
    var select = function(d){
        d.state = "selected";
        return d;
    }

    // Utility function to remove a bar from the selection.
    var unselect = function(d){
        d.state = "unselected";
        return d;
    }

    bars.on("mousedown.bars", function(d, i){
        // Ignore middle clicks.
        var e = d3.event;
        if(e.button === 1){
            return;
       }

        // Cancel any existing selection.
        if(vis.selection){
            vis.selection.on("mousedown.selection", null);
            vis.selection.on("mouseup.selection", null);
            vis.selection = null;
        }

        // Enable dragging mode.
        vis.dragging.on = true;
        vis.dragging.left = vis.dragging.right = i;
        vis.dragging.from = -1;

        // Mark all bars as being unselected.
        bars.style('opacity', 0.0)
            .datum(unselect);

        // Mark the *clicked* bar as selected.
        d3.select(bars[0][i])
            .style('fill', 'red')
            .style('opacity', 0.3)
            .datum(select);
    });

    bars.on("mouseup.bars", function (d, i){
        // Ignore middle clicks.
        var e = d3.event;
        if(e.button === 1){
            return;
        }

        // Turn off dragging mode.
        vis.dragging.on = false;

        // Select out the nodes in the selection.
        vis.selection = d3.selectAll(bars[0].slice(vis.dragging.left, vis.dragging.right+1));

        // Add a pair of mouseclick handlers to this selection - middle
        // clicking on it will trigger a "recomputation" of the histogram
        // over the selection.
        //
        // We can't make this a "click" listener, because in browsers
        // besides Chrome, a non-left button click does not generate a click
        // event.
        vis.selection.on("mousedown.selection", function(){
            var e = d3.event;
            if(e.button === 1){
                vis.middle_clicking = true;
            }
        });

        vis.selection.on("mouseup.selection", function(){
            var e = d3.event;
            if(e.button === 1 && vis.middle_clicking){
                vis.middle_clicking = false;

                console.log("recompute: " + vis.dragging.left + " -> " + vis.dragging.right);

                // Consult the database for new values.
                var binsize = (vis.hi - vis.lo) / vis.bins;
                getDBdata(vis.lo + vis.dragging.left*binsize, vis.lo + (vis.dragging.right+1)*binsize, vis.bins, function(){
                    vis.data(vis.dataset).update();
                });
            }
        });
    });

    bars.on("mouseover", function(d, i){
        var bar = d3.select(this);
        if(d.state == 'selected'){
            bar.style('fill', 'red')
        .style('opacity', 0.5);
        }
        else if(d.state == 'unselected'){
            bar.style('fill', 'black')
        .style('opacity',0.3);
        }
        else{
            console.log("d.state must be selected or unselected - was " + d.state);
            throw 0;
        }

    if(vis.dragging.on){
        var target = -1;
        if(i < vis.dragging.left){
            // Dragging outside the pack, to the left.
            for(var j=i; j<=vis.dragging.left; j++){
                var e = d3.select(bars[0][j]);
                e.style('opacity', 0.3)
                    .style('fill', 'red')
                    .datum(select);
            }
            vis.dragging.left = i;
            vis.dragging.from = 0;
        }
        else if(i > vis.dragging.right){
            // Dragging outside the pack, to the right.
            for(var j=vis.dragging.right+1; j<=i; j++){
                var e = d3.select(bars[0][j]);
                e.style('opacity', 0.3)
                    .style('fill', 'red')
                    .datum(select);
            }
            vis.dragging.right = i;
            vis.dragging.from = 1;
        }
        else{
            // Dragging inside the pack.
            if(vis.dragging.from === 0){
                // Shrinking the selection from the left.
                for(var j=vis.dragging.left; j<i; j++){
                    var e = d3.select(bars[0][j]);
                    e.style('opacity', 0.0)
                        .style('fill', 'black')
                        .datum(unselect);
                }
                vis.dragging.left = i;
            }
            else if(vis.dragging.from === 1){
                // Shrinking the selection from the right.
                for(var j=i+1; j<=vis.dragging.right; j++){
                    var e = d3.select(bars[0][j]);
                    e.style('opacity', 0.0)
                        .style('fill', 'black')
                        .datum(unselect);
                }
                vis.dragging.right = i;
            }
            else{
                console.log("error - vis.dragging.from must be 0 or 1");
                throw 0;
            }
        }
    }
    });

    bars.on('mouseout', function(d){
        if(!vis.dragging.on){
            if(d.state === 'unselected'){
                d3.select(this).style('opacity',0.0);
            }
            else if(d.state === 'selected'){
                d3.select(this).style('opacity',0.3);
            }
        }
    });
}
<commit_msg>Added check to avoid division by zero.<commit_after>function(vis){
    // Add some useful state to the vis object (for use in the mouse
    // callbacks below).
    vis.dragging = {};
    vis.dragging.on = false;
    vis.dragging.last = [-1, -1];
    vis.dragging.from = -1;

    // A D3 selection representing the currently selected range.
    vis.selection = null;

    // For the "recompute" action (a middle click on the selection).
    vis.middle_clicking = false;

    // The current dataset.
    vis.dataset = {values: null};

    // The number of bins we are working with.
    //
    // TODO(choudhury): this should be controllable externally somehow.  Ask
    // Jeff H. about whether we might store "extra" parameters in a special
    // field of the Vega object.
    vis.bins = 100;

    // The total number of records in the current dataset.
    vis.count = 0;

    // The bounds of the data range.
    vis.lo = null;
    vis.hi = null;

    // This function creates a synthetic dataset made from completely random
    // values.  It's mainly a debugging tool.
    var getSyntheticData = function(){
        var dat = [];
        for(var i=0; i<100; i++){
            var o = {
                bin: i,
                value: Math.random(),
                state: "unselected"
            };
            dat.push(o);
        }

        return { values: dat };
    };

    // This function queries the database for the high and low values in the
    // dataset.
    var getDataBounds = function(callback){
        // NOTE:  This function is a perfect example of where iced coffee
        // script's await/defer mechanism would be nice :-\.
        $.ajax({
            url: '/service/mongo/mongo/xdata/flickr_paris',
            data: {
                sort: JSON.stringify([['date',1]]),
                fields: JSON.stringify(['date']),
                limit: 1
            },
            dataType: 'json',
            success: function(response){
                vis.lo = +response.result.data[0].date.$date;

                $.ajax({
                    url: '/service/mongo/mongo/xdata/flickr_paris',
                    data: {
                        sort: JSON.stringify([['date',-1]]),
                        fields: JSON.stringify(['date']),
                        limit: 1
                    },
                    dataType: 'json',
                    success: function(response){
                        vis.hi = +response.result.data[0].date.$date;

                        if(callback !== undefined){
                            callback();
                        }
                    }
                });
            }
        });
    };

    // This function queries the database for the count of data items falling
    // between "lo" and "hi", divided up into "bins" bins.
    var getDBdata = function(lo, hi, bins, callback){
        vis.dataset.values = new Array(bins);
        vis.count = 0;

        var completed = 0;
        var callback_maker = function(which){
            return function(response){
                if(response.error != null){
                    console.log("error: could not complete database request for range " + which);
                    console.log(response.error);
                    return;
                }

                vis.dataset.values[which] = {
                    bin: (which + 1) / bins,
                    count: +response.result.count,
                    state: "unselected"
                };

                vis.count += +response.result.count;

                completed++;
                if(completed === bins){
                    for(var i=0; i<vis.bins; i++){
                        vis.dataset.values[i].value = vis.dataset.values[i].count / (vis.count === 0 ? 1 : vis.count);
                    }

                    if(callback !== undefined){
                        console.log("calling callback");
                        callback();
                    }
                }
            };
        };

        var binsize = (hi - lo) / bins;

        for(var i=0; i<bins; i++){
            // Issue an ajax call to retrieve the count of items falling in the
            // range [lo+i*binsize, lo+(i+1)*binsize).
            var mongostring = JSON.stringify({date: {$gte: {$date: lo + binsize*i}, $lt: {$date: lo + binsize*(i+1)}}});
            $.ajax({
                url: '/service/mongo/mongo/xdata/flickr_paris',
                data: {
                    query: mongostring,
                    limit: 0,
                    fill: false
                },
                dataType: 'json',
                success: callback_maker(i),
                done: function(){ console.log("aww"); }
            });
        }
    };

    // Initialize the data by calling the database retrieval function.
    getDataBounds(function(){
        console.log("lo: " + vis.lo);
        console.log("hi: " + vis.hi);
        getDBdata(vis.lo, vis.hi, vis.bins, function(){
            vis.data(vis.dataset).update();
        });
    });

    // Select the invisible container bars, for use in the mouse callbacks.
    var bars = d3.select(vis.el()).select(".mark-1").selectAll("rect");

    // Utility function to mark a bar as being part of the growing
    // selection.
    var select = function(d){
        d.state = "selected";
        return d;
    }

    // Utility function to remove a bar from the selection.
    var unselect = function(d){
        d.state = "unselected";
        return d;
    }

    bars.on("mousedown.bars", function(d, i){
        // Ignore middle clicks.
        var e = d3.event;
        if(e.button === 1){
            return;
       }

        // Cancel any existing selection.
        if(vis.selection){
            vis.selection.on("mousedown.selection", null);
            vis.selection.on("mouseup.selection", null);
            vis.selection = null;
        }

        // Enable dragging mode.
        vis.dragging.on = true;
        vis.dragging.left = vis.dragging.right = i;
        vis.dragging.from = -1;

        // Mark all bars as being unselected.
        bars.style('opacity', 0.0)
            .datum(unselect);

        // Mark the *clicked* bar as selected.
        d3.select(bars[0][i])
            .style('fill', 'red')
            .style('opacity', 0.3)
            .datum(select);
    });

    bars.on("mouseup.bars", function (d, i){
        // Ignore middle clicks.
        var e = d3.event;
        if(e.button === 1){
            return;
        }

        // Turn off dragging mode.
        vis.dragging.on = false;

        // Select out the nodes in the selection.
        vis.selection = d3.selectAll(bars[0].slice(vis.dragging.left, vis.dragging.right+1));

        // Add a pair of mouseclick handlers to this selection - middle
        // clicking on it will trigger a "recomputation" of the histogram
        // over the selection.
        //
        // We can't make this a "click" listener, because in browsers
        // besides Chrome, a non-left button click does not generate a click
        // event.
        vis.selection.on("mousedown.selection", function(){
            var e = d3.event;
            if(e.button === 1){
                vis.middle_clicking = true;
            }
        });

        vis.selection.on("mouseup.selection", function(){
            var e = d3.event;
            if(e.button === 1 && vis.middle_clicking){
                vis.middle_clicking = false;

                console.log("recompute: " + vis.dragging.left + " -> " + vis.dragging.right);

                // Consult the database for new values.
                var binsize = (vis.hi - vis.lo) / vis.bins;
                getDBdata(vis.lo + vis.dragging.left*binsize, vis.lo + (vis.dragging.right+1)*binsize, vis.bins, function(){
                    vis.data(vis.dataset).update();
                });
            }
        });
    });

    bars.on("mouseover", function(d, i){
        var bar = d3.select(this);
        if(d.state == 'selected'){
            bar.style('fill', 'red')
        .style('opacity', 0.5);
        }
        else if(d.state == 'unselected'){
            bar.style('fill', 'black')
        .style('opacity',0.3);
        }
        else{
            console.log("d.state must be selected or unselected - was " + d.state);
            throw 0;
        }

    if(vis.dragging.on){
        var target = -1;
        if(i < vis.dragging.left){
            // Dragging outside the pack, to the left.
            for(var j=i; j<=vis.dragging.left; j++){
                var e = d3.select(bars[0][j]);
                e.style('opacity', 0.3)
                    .style('fill', 'red')
                    .datum(select);
            }
            vis.dragging.left = i;
            vis.dragging.from = 0;
        }
        else if(i > vis.dragging.right){
            // Dragging outside the pack, to the right.
            for(var j=vis.dragging.right+1; j<=i; j++){
                var e = d3.select(bars[0][j]);
                e.style('opacity', 0.3)
                    .style('fill', 'red')
                    .datum(select);
            }
            vis.dragging.right = i;
            vis.dragging.from = 1;
        }
        else{
            // Dragging inside the pack.
            if(vis.dragging.from === 0){
                // Shrinking the selection from the left.
                for(var j=vis.dragging.left; j<i; j++){
                    var e = d3.select(bars[0][j]);
                    e.style('opacity', 0.0)
                        .style('fill', 'black')
                        .datum(unselect);
                }
                vis.dragging.left = i;
            }
            else if(vis.dragging.from === 1){
                // Shrinking the selection from the right.
                for(var j=i+1; j<=vis.dragging.right; j++){
                    var e = d3.select(bars[0][j]);
                    e.style('opacity', 0.0)
                        .style('fill', 'black')
                        .datum(unselect);
                }
                vis.dragging.right = i;
            }
            else{
                console.log("error - vis.dragging.from must be 0 or 1");
                throw 0;
            }
        }
    }
    });

    bars.on('mouseout', function(d){
        if(!vis.dragging.on){
            if(d.state === 'unselected'){
                d3.select(this).style('opacity',0.0);
            }
            else if(d.state === 'selected'){
                d3.select(this).style('opacity',0.3);
            }
        }
    });
}
<|endoftext|>


<commit_before>function BrowserSyncReloaderPlugin(options) {
    options = options || {};

    if(!options.browserSync)
        throw new Error("'options.browserSync' must be defined...")

    this.browserSync = options.browserSync;
}

BrowserSyncReloaderPluginnpm .prototype.apply = function(compiler) {
    var self = this;

    compiler.plugin('done', function (stats) {
        self.browserSync.reload();
    })
}

module.exports = BrowserSyncReloaderPlugin;<commit_msg>fix npm type<commit_after>function BrowserSyncReloaderPlugin(options) {
    options = options || {};

    if(!options.browserSync)
        throw new Error("'options.browserSync' must be defined...")

    this.browserSync = options.browserSync;
}

BrowserSyncReloaderPlugin.prototype.apply = function(compiler) {
    var self = this;

    compiler.plugin('done', function (stats) {
        self.browserSync.reload();
    })
}

module.exports = BrowserSyncReloaderPlugin;
<|endoftext|>


<commit_before>module.exports.solve          = solve;
module.exports.getInDegree    = getInDegree;
module.exports.getEdges       = getEdges;
module.exports.addMissingKeys = addMissingKeys;

function solve(g) {
    let graph    = addMissingKeys(g);
    let edges    = getEdges(graph);
    let inDegree = getInDegree(graph, edges);

    // Create a queue and enqueue vertices with in-degree of 0
    let queue    = [];

    for(let key in graph) {
        if(inDegree[key] == 0) {
            queue.push(key);
        }
    }

    // Count of visited vertices to compare against graph's length
    // Useful for detecting circular dependency in the graph
    let count    = 0;
    let topOrder = [];

    while(queue.length > 0) {
        // Extract front of queue and add it to topological order
        let u = queue.shift();
        topOrder.unshift(u);

        // Iterate through dependant nodes of popped node
        // and decrease their in-degree by 1
        for(let [index, value] of graph[u].entries()) {
            inDegree[value]--;
            // If in-degree is 0, add it to queue
            if(inDegree[value] == 0) {
                queue.unshift(value);
            }
        }

        count++;
    }

    if(count !== Object.keys(graph).length) {
        throw new Error('There is a circular dependency in the graph');
    } else {
        return topOrder;
    }
}

function getInDegree(graph, edges) {
    // Creating a map to store in-degrees of all vertices
    let inDegree = {};

    for(let key in graph) {
        inDegree[key] = 0;
    }

    // Traverse the edges list and increase in-degrees per
    for(let [src, dest] of edges) {
        inDegree[dest]++;
    }

    return inDegree;
}

function getEdges(graph) {
    let edges = [];
    for(let key in graph) {
        let edge = [];
        // If graph node has any in-degrees add the pair to edge list
        for(let item of graph[key]) {
            if(graph[key].length > 0) {
                edges.push([key, item]);
            }
        }
    }
    return edges;
}

function addMissingKeys(graph) {
    // Add all the missing keys to the graph as nodes with no in-degrees
    for(let key in graph) {
        for(let [index, value] of graph[key].entries()) {
            if(graph[value] === undefined) {
                graph[value] = [];
            }
        }
    }

    return graph;
}<commit_msg>fixed getInDegree() wrong result with incomplete graph<commit_after>module.exports.solve          = solve;
module.exports.addMissingKeys = addMissingKeys;
module.exports.getEdges       = getEdges;
module.exports.getInDegree    = getInDegree;

function solve(g) {
    let graph    = addMissingKeys(g);
    let edges    = getEdges(graph);
    let inDegree = getInDegree(graph);

    // Create a queue and enqueue vertices with in-degree of 0
    let queue    = [];

    for(let key in graph) {
        if(inDegree[key] == 0) {
            queue.push(key);
        }
    }

    // Count of visited vertices to compare against graph's length
    // Useful for detecting circular dependency in the graph
    let count    = 0;
    let topOrder = [];

    while(queue.length > 0) {
        // Extract front of queue and add it to topological order
        let u = queue.shift();
        topOrder.unshift(u);

        // Iterate through dependant nodes of popped node
        // and decrease their in-degree by 1
        for(let [index, value] of graph[u].entries()) {
            inDegree[value]--;
            // If in-degree is 0, add it to queue
            if(inDegree[value] == 0) {
                queue.unshift(value);
            }
        }

        count++;
    }

    if(count !== Object.keys(graph).length) {
        throw new Error('There is a circular dependency in the graph');
    } else {
        return topOrder;
    }
}

function addMissingKeys(graph) {
    // Add all the missing keys to the graph as nodes with no in-degrees
    for(let key in graph) {
        for(let [index, value] of graph[key].entries()) {
            if(graph[value] === undefined) {
                graph[value] = [];
            }
        }
    }

    return graph;
}

function getEdges(graph) {
    let edges = [];
    for(let key in graph) {
        let edge = [];
        // If graph node has any in-degrees add the pair to edge list
        for(let item of graph[key]) {
            if(graph[key].length > 0) {
                edges.push([key, item]);
            }
        }
    }
    return edges;
}

function getInDegree(graph) {
    // Creating a map to store in-degrees of all vertices
    let inDegree = {};

    for(let key in graph) {
        for(let indeg of graph[key]) {
            // Traverse the graph and fill in-degrees. Since complete graph has keys
            // with no in-degrees, add them as nodes with 0 in-degrees
            inDegree[indeg] = inDegree[indeg] === undefined ? 1 : ++inDegree[indeg];
            inDegree[key]   = inDegree[key] || 0;
        }
    }

    return inDegree;
}
<|endoftext|>