<commit_before>'use strict';

module.exports = Application;

var util          = require('util');
var path          = require('path');
var fs            = require('fs');
var _             = require('underscore');
var child_process = require('child_process');
var Promise       = require('bluebird');

var qforms  = require('../../../../qforms');
var server  = require('../../../../server');
var Model   = require('../Model');

util.inherits(Application, Model);

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function Application(data, appInfo) {
    var self = this;
    Application.super_.call(this, data);
    self.appInfo            = appInfo;
    self.dirPath            = self.appInfo.dirPath;
    self.viewFilePath       = path.join(
        server.get('public'),
        'viewer/class/Controller/ModelController/ApplicationController/view',
        'ApplicationView.ejs'
    );
    self.customViewFilePath = path.join(self.dirPath, self.name + '.ejs');
    self.createCollections  = ['databases', 'dataSources'];
    self.fillCollections    = ['dataSources'];
    self.pages              = {};
    self.css                = [];
    self.text               = qforms.text[self.data['@attributes'].lang || 'en'];
    self.databases          = {};
    self.dataSources        = {};
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.create = function(appFilePath) {
    return qforms.helper.getAppInfo(appFilePath).then(function(appInfo) {
        return qforms.helper.readFile(appInfo.filePath).then(function (content) {
            var data = JSON.parse(content);
            var customClassFilePath = path.join(appInfo.dirPath, appInfo.name + '.backend.js');
            return qforms.helper.getFileContent(customClassFilePath).then(function (content) {
                if (content) {
                    var customClass = eval(content);
                    return new customClass(data, appInfo);
                } else {
                    return new Application(data, appInfo);
                }
            });
        });
    });
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.prototype._buildMenu = function(context) {
    var self = this;
    return Promise.try(function() {
        var menu = {};
        var pageNames = Object.keys(self.data.pageLinks).filter(function (pageName) {
            return context.user ? self.authorizePage(context.user, pageName) : true;
        });
        return Promise.each(pageNames, function(pageName) {
            var pageLink = self.data.pageLinks[pageName];
            var pageLinkMenu = pageLink['@attributes'].menu;
            if (pageLinkMenu) {
                var pageFilePath = path.join(self.appInfo.dirPath, pageLink['@attributes'].fileName);
                var pageFile = new qforms.JsonFile(pageFilePath);
                return pageFile.read().then(function() {
                    if (!menu[pageLinkMenu]) {
                        menu[pageLinkMenu] = [];
                    }
                    menu[pageLinkMenu].push({
                        page   : pageLink['@attributes'].name,
                        caption: pageFile.data['@attributes'].caption
                    });
                });
            }
        }).then(function () {
            return menu;
        });
    });
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.prototype.init = function() {
    var self = this;
    return Application.super_.prototype.init.call(self).then(function () {
        return self._createStartupPages2().then(function () {
            return qforms.helper.getFilePaths(self.appInfo.dirPath, '', 'css');
        }).then(function(filePaths) {
            self.css = filePaths.map(function(filePath) {
                return 'view/' + self.appInfo.dirName + '/' + self.appInfo.fileName + '/' + filePath;
            });
        });
    });
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.prototype.deinit = function() {
    var self = this;
    console.log('Application.prototype.deinit: ' + self.name);
    return Promise.each(Object.keys(self.databases), function (name) {
        var database = self.databases[name];
        return database.deinit();
    });
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.prototype._createPage = function(pageName) {
    var self = this;
    return Promise.try(function () {
        var relFilePath  = self.data.pageLinks[pageName]['@attributes'].fileName;
        var pageFilePath = path.join(self.dirPath, relFilePath);
        return qforms.helper.readFile(pageFilePath);
    }).then(function (content) {
        var data = JSON.parse(content);
        return qforms.Page.create(data, self);
    }).then(function (page) {
        return page.init().then(function () {
            return page;
        });
    });
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.prototype.authorizePage = function(user, pageName) {
    var self = this;
    return true;
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.prototype.getPage = function(context, pageName) {
    var self = this;
    return Promise.try(function () {
        if (context.user && self.authorizePage(context.user, pageName) === false) {
            throw new Error('Authorization error');
        }
        if (self.pages[pageName]) {
            return self.pages[pageName];
        } else {
            return self._createPage(pageName).then(function (page) {
                self.pages[pageName] = page;
                return page;
            });
        }
    });
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.prototype._createStartupPages2 = function() {
    var self = this;
    return Promise.try(function () {
        if (self.data.pageLinks) {
            var pageNames = Object.keys(self.data.pageLinks).filter(function (pageName) {
                return self.data.pageLinks[pageName]['@attributes'].startup === 'true';
            });
            return Promise.each(pageNames, function(pageName) {
                var pageLink = self.data.pageLinks[pageName];
                var pageName = pageLink['@attributes'].name;
                return self._createPage(pageName).then(function (page) {
                    self.pages[pageName] = page;
                });
            });
        }
    });
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.prototype.fill = function(context) {
    var self = this;
    return Application.super_.prototype.fill.call(self, context).then(function (response) {
        delete response.user;
        delete response.password;
        delete response.authentication;
        response.env    = server.get('env');
        response.text   = self.text;
        response.params = self.getParams(context);
        return self._buildMenu(context).then(function (menu) {
            response.menu  = menu;
            response.pages = {};
            var startupPageNames = Object.keys(self.data.pageLinks).filter(function (pageName) {
                return self.data.pageLinks[pageName]['@attributes'].startup === 'true';
            });
            return Promise.each(startupPageNames, function (pageName) {
                return self.getPage(context, pageName).then(function (page) {
                    return page.fill(context).then(function (_response) {
                        response.pages[pageName] = _response;
                    });
                });
            });
        }).then(function () {
            return response;
        });
    });
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.prototype.authenticate2 = function(context, username, password) {
    var self = this;
    return Promise.resolve(username === self.data['@attributes'].user && password === self.data['@attributes'].password);
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.prototype.authentication = function() {
    var self = this;
    return self.data['@attributes'].authentication === 'true';
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.prototype.getUsers2 = function(context) {
    return Promise.resolve(null);
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.prototype.getParams = function(context) {
    var self = this;
    var params = {};
    _.extend(params, context.params);
    if (context.querytime) {
        _.extend(params, context.querytime.params);
    }
    if (context.user) {
        params['username'] = context.user.name;
    }
    return params;
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.prototype.createContext = Application.createContext =  function(context) {
    var self = this;
    if (context === undefined) {
        context = {};
    }
    if (context.params === undefined) {
        context.params = {};
    }
    if (context.querytime === undefined) {
        context.querytime = {};
    }
    if (context.querytime.params === undefined) {
        context.querytime.params = {};
    }
    if (context.req) {
        var route = [context.req.params.appDirName, context.req.params.appFileName].join('/');
        if (context.req.session.user && context.req.session.user[route]) {
            context.user = context.req.session.user[route];
        }
    }
    if (context.connections === undefined) {
        context.connections = {};
    }
    return context;
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.prototype.destroyContext = Application.destroyContext = function(context) {
    var self = this;
    for (var name in context.connections) {
        //console.log('release connection: ' + name);
        context.connections[name].release();
    }
};<commit_msg>_createStartupPages2<commit_after>'use strict';

module.exports = Application;

var util          = require('util');
var path          = require('path');
var fs            = require('fs');
var _             = require('underscore');
var child_process = require('child_process');
var Promise       = require('bluebird');

var qforms  = require('../../../../qforms');
var server  = require('../../../../server');
var Model   = require('../Model');

util.inherits(Application, Model);

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function Application(data, appInfo) {
    var self = this;
    Application.super_.call(this, data);
    self.appInfo            = appInfo;
    self.dirPath            = self.appInfo.dirPath;
    self.viewFilePath       = path.join(
        server.get('public'),
        'viewer/class/Controller/ModelController/ApplicationController/view',
        'ApplicationView.ejs'
    );
    self.customViewFilePath = path.join(self.dirPath, self.name + '.ejs');
    self.createCollections  = ['databases', 'dataSources'];
    self.fillCollections    = ['dataSources'];
    self.pages              = {};
    self.css                = [];
    self.text               = qforms.text[self.data['@attributes'].lang || 'en'];
    self.databases          = {};
    self.dataSources        = {};
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.create = function(appFilePath) {
    return qforms.helper.getAppInfo(appFilePath).then(function(appInfo) {
        return qforms.helper.readFile(appInfo.filePath).then(function (content) {
            var data = JSON.parse(content);
            var customClassFilePath = path.join(appInfo.dirPath, appInfo.name + '.backend.js');
            return qforms.helper.getFileContent(customClassFilePath).then(function (content) {
                if (content) {
                    var customClass = eval(content);
                    return new customClass(data, appInfo);
                } else {
                    return new Application(data, appInfo);
                }
            });
        });
    });
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.prototype._buildMenu = function(context) {
    var self = this;
    return Promise.try(function() {
        var menu = {};
        var pageNames = Object.keys(self.data.pageLinks).filter(function (pageName) {
            return context.user ? self.authorizePage(context.user, pageName) : true;
        });
        return Promise.each(pageNames, function(pageName) {
            var pageLink = self.data.pageLinks[pageName];
            var pageLinkMenu = pageLink['@attributes'].menu;
            if (pageLinkMenu) {
                var pageFilePath = path.join(self.appInfo.dirPath, pageLink['@attributes'].fileName);
                var pageFile = new qforms.JsonFile(pageFilePath);
                return pageFile.read().then(function() {
                    if (!menu[pageLinkMenu]) {
                        menu[pageLinkMenu] = [];
                    }
                    menu[pageLinkMenu].push({
                        page   : pageLink['@attributes'].name,
                        caption: pageFile.data['@attributes'].caption
                    });
                });
            }
        }).then(function () {
            return menu;
        });
    });
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.prototype.init = function() {
    var self = this;
    return Application.super_.prototype.init.call(self).then(function () {
        return self._createStartupPages().then(function () {
            return qforms.helper.getFilePaths(self.appInfo.dirPath, '', 'css');
        }).then(function(filePaths) {
            self.css = filePaths.map(function(filePath) {
                return 'view/' + self.appInfo.dirName + '/' + self.appInfo.fileName + '/' + filePath;
            });
        });
    });
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.prototype.deinit = function() {
    var self = this;
    console.log('Application.prototype.deinit: ' + self.name);
    return Promise.each(Object.keys(self.databases), function (name) {
        var database = self.databases[name];
        return database.deinit();
    });
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.prototype._createPage = function(pageName) {
    var self = this;
    return Promise.try(function () {
        var relFilePath  = self.data.pageLinks[pageName]['@attributes'].fileName;
        var pageFilePath = path.join(self.dirPath, relFilePath);
        return qforms.helper.readFile(pageFilePath);
    }).then(function (content) {
        var data = JSON.parse(content);
        return qforms.Page.create(data, self);
    }).then(function (page) {
        return page.init().then(function () {
            return page;
        });
    });
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.prototype.authorizePage = function(user, pageName) {
    var self = this;
    return true;
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.prototype.getPage = function(context, pageName) {
    var self = this;
    return Promise.try(function () {
        if (context.user && self.authorizePage(context.user, pageName) === false) {
            throw new Error('Authorization error');
        }
        if (self.pages[pageName]) {
            return self.pages[pageName];
        } else {
            return self._createPage(pageName).then(function (page) {
                self.pages[pageName] = page;
                return page;
            });
        }
    });
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.prototype._createStartupPages = function() {
    var self = this;
    return Promise.try(function () {
        if (self.data.pageLinks) {
            var pageNames = Object.keys(self.data.pageLinks).filter(function (pageName) {
                return self.data.pageLinks[pageName]['@attributes'].startup === 'true';
            });
            return Promise.each(pageNames, function(pageName) {
                var pageLink = self.data.pageLinks[pageName];
                var pageName = pageLink['@attributes'].name;
                return self._createPage(pageName).then(function (page) {
                    self.pages[pageName] = page;
                });
            });
        }
    });
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.prototype.fill = function(context) {
    var self = this;
    return Application.super_.prototype.fill.call(self, context).then(function (response) {
        delete response.user;
        delete response.password;
        delete response.authentication;
        response.env    = server.get('env');
        response.text   = self.text;
        response.params = self.getParams(context);
        return self._buildMenu(context).then(function (menu) {
            response.menu  = menu;
            response.pages = {};
            var startupPageNames = Object.keys(self.data.pageLinks).filter(function (pageName) {
                return self.data.pageLinks[pageName]['@attributes'].startup === 'true';
            });
            return Promise.each(startupPageNames, function (pageName) {
                return self.getPage(context, pageName).then(function (page) {
                    return page.fill(context).then(function (_response) {
                        response.pages[pageName] = _response;
                    });
                });
            });
        }).then(function () {
            return response;
        });
    });
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.prototype.authenticate2 = function(context, username, password) {
    var self = this;
    return Promise.resolve(username === self.data['@attributes'].user && password === self.data['@attributes'].password);
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.prototype.authentication = function() {
    var self = this;
    return self.data['@attributes'].authentication === 'true';
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.prototype.getUsers2 = function(context) {
    return Promise.resolve(null);
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.prototype.getParams = function(context) {
    var self = this;
    var params = {};
    _.extend(params, context.params);
    if (context.querytime) {
        _.extend(params, context.querytime.params);
    }
    if (context.user) {
        params['username'] = context.user.name;
    }
    return params;
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.prototype.createContext = Application.createContext =  function(context) {
    var self = this;
    if (context === undefined) {
        context = {};
    }
    if (context.params === undefined) {
        context.params = {};
    }
    if (context.querytime === undefined) {
        context.querytime = {};
    }
    if (context.querytime.params === undefined) {
        context.querytime.params = {};
    }
    if (context.req) {
        var route = [context.req.params.appDirName, context.req.params.appFileName].join('/');
        if (context.req.session.user && context.req.session.user[route]) {
            context.user = context.req.session.user[route];
        }
    }
    if (context.connections === undefined) {
        context.connections = {};
    }
    return context;
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Application.prototype.destroyContext = Application.destroyContext = function(context) {
    var self = this;
    for (var name in context.connections) {
        //console.log('release connection: ' + name);
        context.connections[name].release();
    }
};<|endoftext|>


<commit_before>function ExpensesController(Expense, $location, $state) {
  var ctrl = this;

  ctrl.expenses = Expense.query();

  ctrl.deleteExpense = function(expense){
    expense.$delete(function(){
      $state.go($state.current, {reload: true});
    });
  };
};

angular
  .module('app')
  .controller('ExpensesController', ExpensesController)<commit_msg>Added function getTotal<commit_after>function ExpensesController(Expense, $location, $state) {
  var ctrl = this;

  ctrl.expenses = Expense.query();

  ctrl.getTotal = function(){
    var total = 0;
    for (var i = 0; i< ctrl.expenses.length; i++) {
      total += ctrl.expenses[i].amount;
    };
    return total;
  }

  ctrl.deleteExpense = function(expense){
    expense.$delete(function(){
      $state.go($state.current, {reload: true});
    });
  };
};

angular
  .module('app')
  .controller('ExpensesController', ExpensesController)<|endoftext|>


<commit_before>mumuki.load(() => {
  const $userMenuHeader = $('.mu-user-menu-header');

  $userMenuHeader.click(() => {
    $('.mu-user-menu').toggleClass('hidden-sm-screen');
    $('#mu-user-menu-header-icon').toggleClass('fa-chevron-up fa-chevron-down');
  });

  if (document.querySelector('.mu-profile-info') !== null) {
    $userMenuHeader.click();
  }
});
<commit_msg>Avoid reloading when clicking on Profile from profile view<commit_after>mumuki.load(() => {
  const $userMenuHeader = $('.mu-user-menu-header');
  let onUserProfile = document.querySelector('.mu-profile-info') !== null;

  $userMenuHeader.click(() => {
    $('.mu-user-menu').toggleClass('hidden-sm-screen');
    $('#mu-user-menu-header-icon').toggleClass('fa-chevron-up fa-chevron-down');
  });

  if (onUserProfile) {
    $userMenuHeader.click();
  }

  $('.mu-user-menu-item .active').click((e) => {
    if (onUserProfile) {
      e.preventDefault();
      $userMenuHeader.click();
    }
  });
});
<|endoftext|>


<commit_before>'use strict';

var _  = require('mano').i18n.bind('Sections')
  , d  = require('d')
  , db = require('mano').db
  , ns = require('mano').domjs.ns;

require('./form-section-base');

module.exports = Object.defineProperty(db.FormSectionGroup.prototype, 'toDOMForm',
	d(function (document/*, options */) {
		var mainFormResolvent, actionUrl, options, url, self;
		mainFormResolvent = this.getFormResolvent();
		options = Object(arguments[1]);
		url = options.url || ns.url;
		actionUrl = url(this.constructor.actionUrl);
		self = this;
		if (this.buildActionUrl) {
			actionUrl = this.master.constructor.prototype === this.master ?
					url(this.constructor.actionUrl + '-add') :
					url(this.constructor.actionUrl, this.master.__id__);
		}
		return ns.section(
			{ class: 'section-primary' },
			ns.form({ id: this.domId, method: 'post',
					action: actionUrl,
					class: ns._if(ns.eq(
					this.status,
					1
				), 'completed')
				},
				ns.h2(this.constructor.label),
				ns.hr(),
				mainFormResolvent.formResolvent,
				ns.div({ id: mainFormResolvent.affectedSectionId }, ns.list(this.sections,
					function (subSection) {
						var formResolvent, legacy;
						formResolvent = subSection.getFormResolvent();
						legacy = subSection.getLegacy(self.domId, options);
						return ns.div({ class: 'sub-section', id: subSection.domId },
							ns.h3(subSection.constructor.label),
							formResolvent.formResolvent,
							ns.fieldset(
								{ id: formResolvent.affectedSectionId, class: 'form-elements',
									dbjs: subSection.master, names: subSection.formPropertyNames,
									controls: legacy.controls }
							), formResolvent.legacyScript, legacy.legacy);
					})),
				ns.p({ class: 'submit-placeholder input' },
					ns.input({ type: 'submit' }, _("Submit"))),
				ns.p(
					{ class: 'button-scroll-top' },
					ns.a({ onclick: 'window.scroll(0, 0)' },
						ns.span({ class: 'fa fa-arrow-up' }, "Back to top"))
				)
				),
			mainFormResolvent.legacyScript
		);
	}));
<commit_msg>#249 passed context as arg<commit_after>'use strict';

var _  = require('mano').i18n.bind('Sections')
  , d  = require('d')
  , db = require('mano').db
  , ns = require('mano').domjs.ns;

require('./form-section-base');

module.exports = Object.defineProperty(db.FormSectionGroup.prototype, 'toDOMForm',
	d(function (document/*, options */) {
		var mainFormResolvent, actionUrl, options, url;
		mainFormResolvent = this.getFormResolvent();
		options = Object(arguments[1]);
		url = options.url || ns.url;
		actionUrl = url(this.constructor.actionUrl);
		if (this.buildActionUrl) {
			actionUrl = this.master.constructor.prototype === this.master ?
					url(this.constructor.actionUrl + '-add') :
					url(this.constructor.actionUrl, this.master.__id__);
		}
		return ns.section(
			{ class: 'section-primary' },
			ns.form({ id: this.domId, method: 'post',
					action: actionUrl,
					class: ns._if(ns.eq(
					this.status,
					1
				), 'completed')
				},
				ns.h2(this.constructor.label),
				ns.hr(),
				mainFormResolvent.formResolvent,
				ns.div({ id: mainFormResolvent.affectedSectionId }, ns.list(this.sections,
					function (subSection) {
						var formResolvent, legacy;
						formResolvent = subSection.getFormResolvent();
						legacy = subSection.getLegacy(this.domId, options);
						return ns.div({ class: 'sub-section', id: subSection.domId },
							ns.h3(subSection.constructor.label),
							formResolvent.formResolvent,
							ns.fieldset(
								{ id: formResolvent.affectedSectionId, class: 'form-elements',
									dbjs: subSection.master, names: subSection.formPropertyNames,
									controls: legacy.controls }
							), formResolvent.legacyScript, legacy.legacy);
					}, this)),
				ns.p({ class: 'submit-placeholder input' },
					ns.input({ type: 'submit' }, _("Submit"))),
				ns.p(
					{ class: 'button-scroll-top' },
					ns.a({ onclick: 'window.scroll(0, 0)' },
						ns.span({ class: 'fa fa-arrow-up' }, "Back to top"))
				)
				),
			mainFormResolvent.legacyScript
		);
	}));
<|endoftext|>


<commit_before>/**
 * settings_view.js
 * @flow
 */

import React from "react";
import { Tabs } from "antd";
import Model from "oxalis/model";
import UserSettingsView from "oxalis/view/settings/user_settings_view";
import DatasetSettingsView from "oxalis/view/settings/dataset_settings_view";

const TabPane = Tabs.TabPane;

const SettingsView = ({ oldModel, isPublicViewMode }:{oldModel: Model, isPublicViewMode: boolean}) =>
  <Tabs defaultActiveKey="1">
    <TabPane tab="Tracing" key="1"><UserSettingsView oldModel={oldModel} isPublicViewMode={isPublicViewMode} /></TabPane>
    <TabPane tab="Dataset" key="2"><DatasetSettingsView /></TabPane>
  </Tabs>;

export default SettingsView;
<commit_msg>prevent inactive tabs from rendering #1709<commit_after>/**
 * settings_view.js
 * @flow
 */

import React from "react";
import { Tabs } from "antd";
import Model from "oxalis/model";
import UserSettingsView from "oxalis/view/settings/user_settings_view";
import DatasetSettingsView from "oxalis/view/settings/dataset_settings_view";

const TabPane = Tabs.TabPane;

const SettingsView = ({ oldModel, isPublicViewMode }:{oldModel: Model, isPublicViewMode: boolean}) =>
  <Tabs defaultActiveKey="1" destroyInactiveTabPane={true}>
    <TabPane tab="Tracing" key="1"><UserSettingsView oldModel={oldModel} isPublicViewMode={isPublicViewMode} /></TabPane>
    <TabPane tab="Dataset" key="2"><DatasetSettingsView /></TabPane>
  </Tabs>;

export default SettingsView;
<|endoftext|>


<commit_before>import Icon from '@conveyal/woonerf/components/icon'
import React, {Component, PropTypes} from 'react'
import { Row, Col, Button, Panel, Label, Glyphicon, ButtonGroup, ListGroup, ListGroupItem } from 'react-bootstrap'
import { LinkContainer } from 'react-router-bootstrap'

import GtfsValidationViewer from '../validation/GtfsValidationViewer'
import FeedVersionReport from './FeedVersionReport'
import VersionDateLabel from './VersionDateLabel'
import NotesViewer from '../NotesViewer'
import ConfirmModal from '../../../common/components/ConfirmModal'
import ActiveGtfsPlusVersionSummary from '../../../gtfsplus/containers/ActiveGtfsPlusVersionSummary'
import {isModuleEnabled, getComponentMessages, getMessage} from '../../../common/util/config'

export default class FeedVersionViewer extends Component {
  static propTypes = {
    version: PropTypes.object,
    feedSource: PropTypes.object,
    versions: PropTypes.array,
    feedVersionIndex: PropTypes.number,
    versionSection: PropTypes.string,
    isPublic: PropTypes.bool,
    hasVersions: PropTypes.bool,
    listView: PropTypes.bool,
    newNotePosted: PropTypes.func,
    notesRequested: PropTypes.func,
    fetchValidationResult: PropTypes.func,
    downloadFeedClicked: PropTypes.func,
    loadFeedVersionForEditing: PropTypes.func,
    user: PropTypes.object,
    validationJob: PropTypes.object
  }

  _onFetchValidation = () => this.props.fetchValidationResult(this.props.version)

  render () {
    const {
      feedVersionIndex,
      listView,
      newNotePosted,
      notesRequested,
      validationJob,
      version,
      versionSection,
      user
    } = this.props
    const messages = getComponentMessages('FeedVersionViewer')

    if (!version) return
{getMessage(messages, 'noVersionsExist')}

    if (listView) {
      // List view of feed versions
      return (
        <Row>
          <Col xs={12} sm={12}>
            <VersionList {...this.props} />
          </Col>
        </Row>
      )
    }
    return (
      <Row>
        <Col xs={12} sm={3}>
          <VersionSectionSelector
            version={version}
            feedVersionIndex={feedVersionIndex}
            validationJob={validationJob}
            versionSection={versionSection} />
        </Col>
        <Col xs={12} sm={9}>
          {!versionSection
            ? <FeedVersionReport {...this.props} />
            : versionSection === 'issues'
            ? <GtfsValidationViewer
              validationResult={version.validationResult}
              version={version}
              fetchValidationResult={this._onFetchValidation} />
            : versionSection === 'gtfsplus' && isModuleEnabled('gtfsplus')
            ? <ActiveGtfsPlusVersionSummary
              version={version} />
            : versionSection === 'comments'
            ? <NotesViewer
              type='feed-version'
              stacked
              user={user}
              version={version}
              notes={version.notes}
              noteCount={version.noteCount}
              notesRequested={notesRequested}
              newNotePosted={newNotePosted} />
            : null
          }
        </Col>
      </Row>
    )
  }
}

export class VersionButtonToolbar extends Component {
  static propTypes = {
    version: PropTypes.object,
    versions: PropTypes.array,
    feedVersionIndex: PropTypes.number,
    isPublic: PropTypes.bool,
    hasVersions: PropTypes.bool,
    downloadFeedClicked: PropTypes.func,
    deleteFeedVersionConfirmed: PropTypes.func,
    loadFeedVersionForEditing: PropTypes.func,
    validationJob: PropTypes.object
  }

  _onClickDownload = () => this.props.downloadFeedClicked(this.props.version, this.props.isPublic)

  _onClickLoadIntoEditor = (evt) => {
    const {loadFeedVersionForEditing, version} = this.props
    const messages = getComponentMessages('FeedVersionViewer')
    this.refs.confirm.open({
      title: getMessage(messages, 'load'),
      body: getMessage(messages, 'confirmLoad'),
      onConfirm: () => { loadFeedVersionForEditing(version) }
    })
  }

  _onClickDeleteVersion = (evt) => {
    const {deleteFeedVersionConfirmed, version} = this.props
    const messages = getComponentMessages('FeedVersionViewer')
    this.refs.confirm.open({
      title: `${getMessage(messages, 'delete')} ${getMessage(messages, 'version')}`,
      body: getMessage(messages, 'confirmDelete'),
      onConfirm: () => { deleteFeedVersionConfirmed(version) }
    })
  }

  render () {
    const {
      deleteDisabled,
      deleteFeedVersionConfirmed,
      editDisabled,
      hasVersions,
      isPublic,
      size
    } = this.props
    const messages = getComponentMessages('FeedVersionViewer')
    return (

        <ConfirmModal ref='confirm' />
        <ButtonGroup className='pull-right'>

          {/* "Download Feed" Button */}
          <Button
            bsSize={size}
            disabled={!hasVersions}
            onClick={this._onClickDownload}>
            <Glyphicon glyph='download' />
             {getMessage(messages, 'download')}
             {getMessage(messages, 'version')}
          </Button>

          {/* "Load for Editing" Button */}
          {isModuleEnabled('editor') && !isPublic
            ? <Button
              bsSize={size}
              disabled={editDisabled || !hasVersions}
              onClick={this._onClickLoadIntoEditor}>
              <Glyphicon glyph='pencil' />
               {getMessage(messages, 'load')}
            </Button>
            : null
          }

          {/* "Delete Version" Button */}
          {!isPublic
            ? <Button
              bsSize={size}
              disabled={deleteDisabled || !hasVersions || typeof deleteFeedVersionConfirmed === 'undefined'}
              onClick={this._onClickDeleteVersion}>

                <Icon type='trash' />
                 {getMessage(messages, 'delete')}
                 {getMessage(messages, 'version')}

            </Button>
            : null
          }
        </ButtonGroup>

    )
  }
}

class VersionSectionSelector extends Component {
  static propTypes = {
    validationJob: PropTypes.object,
    version: PropTypes.object,
    feedVersionIndex: PropTypes.number,
    versionSection: PropTypes.string
  }

  _renderIssuesLabel (version) {
    const color = this.props.validationJob
      ? 'warning'
      : version.validationSummary.loadStatus !== 'SUCCESS'
      ? 'danger'
      : version.validationSummary.errorCount
      ? 'warning'
      : 'success'
    const text = this.props.validationJob
      ? processing <Icon className='fa-spin' type='refresh' />
      : version.validationSummary.loadStatus !== 'SUCCESS'
      ? 'critical error'
      : version.validationSummary.errorCount
    return (

        {text}

    )
  }

  render () {
    const { version } = this.props
    return (
      <Panel>
        <ListGroup fill>
          <LinkContainer to={`/feed/${version.feedSource.id}/version/${this.props.feedVersionIndex}`} active={!this.props.versionSection}>
            <ListGroupItem><Icon type='info-circle' /> Version summary</ListGroupItem>
          </LinkContainer>
          <LinkContainer to={`/feed/${version.feedSource.id}/version/${this.props.feedVersionIndex}/issues`} active={this.props.versionSection === 'issues'}>
            <ListGroupItem>
              <Icon type='exclamation-triangle' /> Validation issues {this._renderIssuesLabel(version)}
            </ListGroupItem>
          </LinkContainer>
          {isModuleEnabled('gtfsplus')
            ? <LinkContainer to={`/feed/${version.feedSource.id}/version/${this.props.feedVersionIndex}/gtfsplus`} active={this.props.versionSection === 'gtfsplus'}>
              <ListGroupItem>
                <Icon type='plus' /> GTFS+ for this version
              </ListGroupItem>
            </LinkContainer>
            : null
          }
          <LinkContainer to={`/feed/${version.feedSource.id}/version/${this.props.feedVersionIndex}/comments`} active={this.props.versionSection === 'comments'}>
            <ListGroupItem><Glyphicon glyph='comment' /> Version comments {version.noteCount}</ListGroupItem>
          </LinkContainer>
        </ListGroup>
      </Panel>
    )
  }
}

class VersionList extends Component {
  static propTypes = {
    versions: PropTypes.array
  }

  render () {
    return <Panel header={
List of feed versions
}>
      <ListGroup fill>
        {this.props.versions
          ? this.props.versions.map(v => {
            return (
              <ListGroupItem key={v.id}>
                {v.name}
                {' '}

                  <VersionDateLabel version={v} />

                <VersionButtonToolbar
                  version={v}
                  size='xsmall'
                  {...this.props} />
              </ListGroupItem>
            )
          })
          : <ListGroupItem>
            No versions
          </ListGroupItem>
        }
      </ListGroup>
    </Panel>
  }
}
<commit_msg>refactor(FeedVersionViewer): fix text on feed version button<commit_after>import Icon from '@conveyal/woonerf/components/icon'
import React, {Component, PropTypes} from 'react'
import { Row, Col, Button, Panel, Label, Glyphicon, ButtonGroup, ListGroup, ListGroupItem } from 'react-bootstrap'
import { LinkContainer } from 'react-router-bootstrap'

import GtfsValidationViewer from '../validation/GtfsValidationViewer'
import FeedVersionReport from './FeedVersionReport'
import VersionDateLabel from './VersionDateLabel'
import NotesViewer from '../NotesViewer'
import ConfirmModal from '../../../common/components/ConfirmModal'
import ActiveGtfsPlusVersionSummary from '../../../gtfsplus/containers/ActiveGtfsPlusVersionSummary'
import {isModuleEnabled, getComponentMessages, getMessage} from '../../../common/util/config'

export default class FeedVersionViewer extends Component {
  static propTypes = {
    version: PropTypes.object,
    feedSource: PropTypes.object,
    versions: PropTypes.array,
    feedVersionIndex: PropTypes.number,
    versionSection: PropTypes.string,
    isPublic: PropTypes.bool,
    hasVersions: PropTypes.bool,
    listView: PropTypes.bool,
    newNotePosted: PropTypes.func,
    notesRequested: PropTypes.func,
    fetchValidationResult: PropTypes.func,
    downloadFeedClicked: PropTypes.func,
    loadFeedVersionForEditing: PropTypes.func,
    user: PropTypes.object,
    validationJob: PropTypes.object
  }

  _onFetchValidation = () => this.props.fetchValidationResult(this.props.version)

  render () {
    const {
      feedVersionIndex,
      listView,
      newNotePosted,
      notesRequested,
      validationJob,
      version,
      versionSection,
      user
    } = this.props
    const messages = getComponentMessages('FeedVersionViewer')

    if (!version) return
{getMessage(messages, 'noVersionsExist')}

    if (listView) {
      // List view of feed versions
      return (
        <Row>
          <Col xs={12} sm={12}>
            <VersionList {...this.props} />
          </Col>
        </Row>
      )
    }
    return (
      <Row>
        <Col xs={12} sm={3}>
          <VersionSectionSelector
            version={version}
            feedVersionIndex={feedVersionIndex}
            validationJob={validationJob}
            versionSection={versionSection} />
        </Col>
        <Col xs={12} sm={9}>
          {!versionSection
            ? <FeedVersionReport {...this.props} />
            : versionSection === 'issues'
            ? <GtfsValidationViewer
              validationResult={version.validationResult}
              version={version}
              fetchValidationResult={this._onFetchValidation} />
            : versionSection === 'gtfsplus' && isModuleEnabled('gtfsplus')
            ? <ActiveGtfsPlusVersionSummary
              version={version} />
            : versionSection === 'comments'
            ? <NotesViewer
              type='feed-version'
              stacked
              user={user}
              version={version}
              notes={version.notes}
              noteCount={version.noteCount}
              notesRequested={notesRequested}
              newNotePosted={newNotePosted} />
            : null
          }
        </Col>
      </Row>
    )
  }
}

export class VersionButtonToolbar extends Component {
  static propTypes = {
    version: PropTypes.object,
    versions: PropTypes.array,
    feedVersionIndex: PropTypes.number,
    isPublic: PropTypes.bool,
    hasVersions: PropTypes.bool,
    downloadFeedClicked: PropTypes.func,
    deleteFeedVersionConfirmed: PropTypes.func,
    loadFeedVersionForEditing: PropTypes.func,
    validationJob: PropTypes.object
  }

  _onClickDownload = () => this.props.downloadFeedClicked(this.props.version, this.props.isPublic)

  _onClickLoadIntoEditor = (evt) => {
    const {loadFeedVersionForEditing, version} = this.props
    const messages = getComponentMessages('FeedVersionViewer')
    this.refs.confirm.open({
      title: getMessage(messages, 'load'),
      body: getMessage(messages, 'confirmLoad'),
      onConfirm: () => { loadFeedVersionForEditing(version) }
    })
  }

  _onClickDeleteVersion = (evt) => {
    const {deleteFeedVersionConfirmed, version} = this.props
    const messages = getComponentMessages('FeedVersionViewer')
    this.refs.confirm.open({
      title: `${getMessage(messages, 'delete')} ${getMessage(messages, 'version')}`,
      body: getMessage(messages, 'confirmDelete'),
      onConfirm: () => { deleteFeedVersionConfirmed(version) }
    })
  }

  render () {
    const {
      deleteDisabled,
      deleteFeedVersionConfirmed,
      editDisabled,
      hasVersions,
      isPublic,
      size
    } = this.props
    const messages = getComponentMessages('FeedVersionViewer')
    return (

        <ConfirmModal ref='confirm' />
        <ButtonGroup className='pull-right'>

          {/* "Download Feed" Button */}
          <Button
            bsSize={size}
            disabled={!hasVersions}
            onClick={this._onClickDownload}>
            <Glyphicon glyph='download' />
             {getMessage(messages, 'download')}
             {getMessage(messages, 'version')}
          </Button>

          {/* "Load for Editing" Button */}
          {isModuleEnabled('editor') && !isPublic
            ? <Button
              bsSize={size}
              disabled={editDisabled || !hasVersions}
              onClick={this._onClickLoadIntoEditor}>
              <Glyphicon glyph='pencil' />
               {getMessage(messages, 'load')}
               {getMessage(messages, 'version')}
            </Button>
            : null
          }

          {/* "Delete Version" Button */}
          {!isPublic
            ? <Button
              bsSize={size}
              disabled={deleteDisabled || !hasVersions || typeof deleteFeedVersionConfirmed === 'undefined'}
              onClick={this._onClickDeleteVersion}>

                <Icon type='trash' />
                 {getMessage(messages, 'delete')}
                 {getMessage(messages, 'version')}

            </Button>
            : null
          }
        </ButtonGroup>

    )
  }
}

class VersionSectionSelector extends Component {
  static propTypes = {
    validationJob: PropTypes.object,
    version: PropTypes.object,
    feedVersionIndex: PropTypes.number,
    versionSection: PropTypes.string
  }

  _renderIssuesLabel (version) {
    const color = this.props.validationJob
      ? 'warning'
      : version.validationSummary.loadStatus !== 'SUCCESS'
      ? 'danger'
      : version.validationSummary.errorCount
      ? 'warning'
      : 'success'
    const text = this.props.validationJob
      ? processing <Icon className='fa-spin' type='refresh' />
      : version.validationSummary.loadStatus !== 'SUCCESS'
      ? 'critical error'
      : version.validationSummary.errorCount
    return (

        {text}

    )
  }

  render () {
    const { version } = this.props
    return (
      <Panel>
        <ListGroup fill>
          <LinkContainer to={`/feed/${version.feedSource.id}/version/${this.props.feedVersionIndex}`} active={!this.props.versionSection}>
            <ListGroupItem><Icon type='info-circle' /> Version summary</ListGroupItem>
          </LinkContainer>
          <LinkContainer to={`/feed/${version.feedSource.id}/version/${this.props.feedVersionIndex}/issues`} active={this.props.versionSection === 'issues'}>
            <ListGroupItem>
              <Icon type='exclamation-triangle' /> Validation issues {this._renderIssuesLabel(version)}
            </ListGroupItem>
          </LinkContainer>
          {isModuleEnabled('gtfsplus')
            ? <LinkContainer to={`/feed/${version.feedSource.id}/version/${this.props.feedVersionIndex}/gtfsplus`} active={this.props.versionSection === 'gtfsplus'}>
              <ListGroupItem>
                <Icon type='plus' /> GTFS+ for this version
              </ListGroupItem>
            </LinkContainer>
            : null
          }
          <LinkContainer to={`/feed/${version.feedSource.id}/version/${this.props.feedVersionIndex}/comments`} active={this.props.versionSection === 'comments'}>
            <ListGroupItem><Glyphicon glyph='comment' /> Version comments {version.noteCount}</ListGroupItem>
          </LinkContainer>
        </ListGroup>
      </Panel>
    )
  }
}

class VersionList extends Component {
  static propTypes = {
    versions: PropTypes.array
  }

  render () {
    return <Panel header={
List of feed versions
}>
      <ListGroup fill>
        {this.props.versions
          ? this.props.versions.map(v => {
            return (
              <ListGroupItem key={v.id}>
                {v.name}
                {' '}

                  <VersionDateLabel version={v} />

                <VersionButtonToolbar
                  version={v}
                  size='xsmall'
                  {...this.props} />
              </ListGroupItem>
            )
          })
          : <ListGroupItem>
            No versions
          </ListGroupItem>
        }
      </ListGroup>
    </Panel>
  }
}
<|endoftext|>


<commit_before>
import React, { PureComponent, PropTypes } from 'react';
import isNumeric from 'validator/lib/isNumeric';
import IconButton from 'material-ui/IconButton';
import TextField from 'material-ui/TextField';

const textFieldStyle = {
  display: 'inline-block',
  width: '4rem',
  padding: '0 1rem',
};

class GeographySearch extends React.PureComponent {

  constructor(props) {
    super(props);
    this.state = {
      distance: '',
      zipcode: ''
    }
  }

  static propTypes = {
    addItem: PropTypes.func.isRequired,
  }

  handleInputChange = (event, type, value) => {

    if (typeof type === 'string' && (type === 'zipcode' || type === 'distance')) {
      if (isNumeric(value)) {

        this.setState(Object.assign({},
          this.state,
          { [type]: value }
        ));
      }
    }
  }

  addItem = (event) => {

    if (typeof event === 'object' && typeof event.preventDefault === 'function') {
      event.preventDefault();
    }

    this.props.addItem('geographies', {
      distance: this.state.distance,
      zipcode: this.state.zipcode
    });

    this.setState(Object.assign({},
      this.state,
      {
        distance: '',
        zipcode: ''
      }
    ));
  }

  render() {

    const { distance, zipcode, ...state } = this.state;
    const { addItem, handleInputChange } = this;

    return (
      <form
        onSubmit={addItem}
      >
        Within
        <TextField
          floatingLabelText="miles"
          type="number"
          value={distance}
          style={textFieldStyle}
          underlineShow={false}
          onChange={ (event) => { handleInputChange(event, 'distance', event.target.value) } }
        />
        of
        <TextField
          floatingLabelText="Zipcode"
          type="number"
          value={zipcode}
          style={textFieldStyle}
          underlineShow={false}
          onChange={ (event) => { handleInputChange(event, 'zipcode', event.target.value) } }
        />
        <IconButton
          iconClassName='material-icons'
          type="submit"
        >search</IconButton>
      </form>
    )
  }
}

export default GeographySearch;
<commit_msg>Fixing zipcode input field bug from https://trello.com/c/eqESrsPu<commit_after>
import React, { PureComponent, PropTypes } from 'react';
import isNumeric from 'validator/lib/isNumeric';
import IconButton from 'material-ui/IconButton';
import TextField from 'material-ui/TextField';

const textFieldStyle = {
  display: 'inline-block',
  width: '4rem',
  padding: '0 1rem',
};

class GeographySearch extends React.PureComponent {

  constructor(props) {
    super(props);
    this.state = {
      distance: '',
      zipcode: ''
    }
  }

  static propTypes = {
    addItem: PropTypes.func.isRequired,
  }

  handleInputChange = (event, type, value) => {

    if (typeof type === 'string' && (type === 'zipcode' || type === 'distance')) {
      if (isNumeric(value) || value === '') {

        this.setState(Object.assign({},
          this.state,
          { [type]: value }
        ));
      }
    }
  }

  addItem = (event) => {

    if (typeof event === 'object' && typeof event.preventDefault === 'function') {
      event.preventDefault();
    }

    this.props.addItem('geographies', {
      distance: this.state.distance,
      zipcode: this.state.zipcode
    });

    this.setState(Object.assign({},
      this.state,
      {
        distance: '',
        zipcode: ''
      }
    ));
  }

  render() {

    const { distance, zipcode, ...state } = this.state;
    const { addItem, handleInputChange } = this;

    return (
      <form
        onSubmit={addItem}
      >
        Within
        <TextField
          floatingLabelText="miles"
          type="number"
          value={distance}
          style={textFieldStyle}
          underlineShow={false}
          onChange={ (event) => { handleInputChange(event, 'distance', event.target.value) } }
        />
        of
        <TextField
          floatingLabelText="Zipcode"
          type="number"
          value={zipcode}
          style={textFieldStyle}
          underlineShow={false}
          onChange={ (event) => { handleInputChange(event, 'zipcode', event.target.value) } }
        />
        <IconButton
          iconClassName='material-icons'
          type="submit"
        >search</IconButton>
      </form>
    )
  }
}

export default GeographySearch;
<|endoftext|>


<commit_before>

var sourceCode = (function() {

var currentAsatWarnings = [];
var currentCatWarnings = [];
var currentMessageWarnings = [];
var currentTooltip;
var curLine = -1;
var	localD;
var	localCurPath;

function highlight(lineNumber, type){
	var childs = $( '.CodeMirror-code').children()
	var child = childs[lineNumber - 1];

	$(child).find('.CodeMirror-gutter-wrapper').find('.CodeMirror-linenumber').css( 'cursor', 'crosshair' );
	$(child).css( 'cursor', 'crosshair' );
	switch(type) {
		case 'CheckStyle':
			$(child).css('background','#386938');
			$(child).find('.CodeMirror-gutter-wrapper').find('.CodeMirror-linenumber').css('background','#386938');
			break;
		case 'PMD':
			$(child).css('background','#88120a');
			$(child).find('.CodeMirror-gutter-wrapper').find('.CodeMirror-linenumber').css('background','#88120a');
			break;
		case 'FindBugs':
			$(child).css('background','#043e70');
			$(child).find('.CodeMirror-gutter-wrapper').find('.CodeMirror-linenumber').css('background','#043e70');
			break;
	}
}

function setLabels(lineNumber, type, cat, message) {
	console.log("Labeling");
	var childs = $( '.CodeMirror-code').children()
	var child = childs[lineNumber - 1];
			currentAsatWarnings.push(type);
			currentCatWarnings.push(cat);
			currentMessageWarnings.push(message);
		if( curLine != lineNumber)  {
			 console.log("if case");
			 console.log(child);
			 /*
			 * Creates a tooltip that will be shown on hover over a node
			 */
			curLine = lineNumber;
			var tooltip = d3.select("#chart-and-code")
			    .append("div")
				.attr("class","d3-tip2")
				.style("width", 300)
			    .style("position", "absolute")
			    .style("z-index", "10")
			    .style("visibility", "hidden");

			var textInTooltip = "Line " + curLine + ": ";
			for(var i = 0; i < currentAsatWarnings.length; i++) {
				textInTooltip += "
-" + currentAsatWarnings[i] + "
-" + currentCatWarnings[i] + "
-" + currentMessageWarnings[i] + "
"
			}
			$(child).mouseenter(function(){
				tooltip.html(textInTooltip);
                tooltip.style("visibility", "visible");
			});
			$(child).mousemove(function(){
				tooltip.style("top", (event.pageY - 130) + "px").style("left", (event.pageX - 280) + "px");
			});
			$(child).mouseleave(function(){
				tooltip.style("visibility", "hidden");
			});

			currentAsatWarnings = [];
			currentCatWarnings = [];
			currentMessageWarnings = [];
		}
}
function setBackButton(d, curPath){
		var packagePath = curPath.substring(0, curPath.lastIndexOf("/") + 1);
		packagePath = packagePath.substring(0, packagePath.length - 2);
        var pathFirstPart = packagePath.substring(0, packagePath.lastIndexOf("/") + 1);
        var pathSecondPart = packagePath.split(/[/ ]+/).pop();
        $('#current-path').html(pathFirstPart + " " + pathSecondPart + "");

		$('#back-div').click(function() {
    		$('input.updateContent').attr('disabled',false);
    		$('#current-path').html(packagePath);
		  	sourceCode.hide();
		});
	}
function displayCode(pathID){
	for ( var i = 0; i < codeExport.length; i++){

		if (codeExport[i].path == pathID){
			var value = codeExport[i].code.substring(1, codeExport[i].code.length -2);
		}

	}
	var editor = CodeMirror(document.body.getElementsByTagName("article")[0], {
	    value: value,
	    lineNumbers: true,
	    mode: "javascript",
	    keyMap: "sublime",
		readOnly: "nocursor",
	    autoCloseBrackets: true,
	    matchBrackets: true,
	    showCursorWhenSelecting: true,
	    theme: "monokai",
	    tabSize: 2
	});
	}

return {

	readAllCode: function(){
	},
	show: function(d, curPath){
		localD = d;
		localCurPath = curPath;
		currentAsatWarnings = [];
		currentCatWarnings = [];
		currentMessageWarnings = [];
		curLine = -1;

		$('input.relative').attr('disabled','disabled');
		$('#normalButton').attr('disabled','disabled');
		var chartDiv = document.getElementById("code-div");
		chartDiv.style.visibility = 'visible';
		document.getElementById("chart").style.visibility = 'hidden';
		document.getElementById('normalColourLabel').style.textDecoration = 'line-through';
		document.getElementById('relativeLabel').style.textDecoration = 'line-through';

		displayCode(d.filePath);
		var warnings = getWarningLines(d.fileName);
		for( var i =0 ; i < warnings.warningList.length; i ++ ){
			highlight(warnings.warningList[i].line, warnings.warningList[i].type);
		}
		setBackButton(d, curPath);
		var warnings = getWarningLines(d.fileName);
		for( var i =0 ; i < warnings.warningList.length; i ++ ){
			setLabels(warnings.warningList[i].line, warnings.warningList[i].type, warnings.warningList[i].cat, warnings.warningList[i].message);
		}
	},
	hide: function(){
		$('input.relative').removeAttr("disabled");
		document.getElementById('relativeLabel').style.textDecoration = 'none';
		var myNode = document.getElementById("code-article");
		while (myNode.firstChild) {
			myNode.removeChild(myNode.firstChild);
		}
		var chartDiv = document.getElementById("code-div");
			chartDiv.style.visibility = 'hidden';
			document.getElementById("chart").style.visibility = 'visible';
	},
	fullReload: function(){
		sourceCode.hide();
		sourceCode.show(localD, localCurPath);
		$('.CodeMirror').width(opts.width).height(opts.height - 30);
	}
}

}());<commit_msg>Buttons set right for source code visualization<commit_after>

var sourceCode = (function() {

var currentAsatWarnings = [];
var currentCatWarnings = [];
var currentMessageWarnings = [];
var currentTooltip;
var curLine = -1;
var	localD;
var	localCurPath;

function highlight(lineNumber, type){
	var childs = $( '.CodeMirror-code').children()
	var child = childs[lineNumber - 1];

	$(child).find('.CodeMirror-gutter-wrapper').find('.CodeMirror-linenumber').css( 'cursor', 'crosshair' );
	$(child).css( 'cursor', 'crosshair' );
	switch(type) {
		case 'CheckStyle':
			$(child).css('background','#386938');
			$(child).find('.CodeMirror-gutter-wrapper').find('.CodeMirror-linenumber').css('background','#386938');
			break;
		case 'PMD':
			$(child).css('background','#88120a');
			$(child).find('.CodeMirror-gutter-wrapper').find('.CodeMirror-linenumber').css('background','#88120a');
			break;
		case 'FindBugs':
			$(child).css('background','#043e70');
			$(child).find('.CodeMirror-gutter-wrapper').find('.CodeMirror-linenumber').css('background','#043e70');
			break;
	}
}

function setLabels(lineNumber, type, cat, message) {
	console.log("Labeling");
	var childs = $( '.CodeMirror-code').children()
	var child = childs[lineNumber - 1];
			currentAsatWarnings.push(type);
			currentCatWarnings.push(cat);
			currentMessageWarnings.push(message);
		if( curLine != lineNumber)  {
			 console.log("if case");
			 console.log(child);
			 /*
			 * Creates a tooltip that will be shown on hover over a node
			 */
			curLine = lineNumber;
			var tooltip = d3.select("#chart-and-code")
			    .append("div")
				.attr("class","d3-tip2")
				.style("width", 300)
			    .style("position", "absolute")
			    .style("z-index", "10")
			    .style("visibility", "hidden");

			var textInTooltip = "Line " + curLine + ": ";
			for(var i = 0; i < currentAsatWarnings.length; i++) {
				textInTooltip += "
-" + currentAsatWarnings[i] + "
-" + currentCatWarnings[i] + "
-" + currentMessageWarnings[i] + "
"
			}
			$(child).mouseenter(function(){
				tooltip.html(textInTooltip);
                tooltip.style("visibility", "visible");
			});
			$(child).mousemove(function(){
				tooltip.style("top", (event.pageY - 130) + "px").style("left", (event.pageX - 280) + "px");
			});
			$(child).mouseleave(function(){
				tooltip.style("visibility", "hidden");
			});

			currentAsatWarnings = [];
			currentCatWarnings = [];
			currentMessageWarnings = [];
		}
}
function displayCode(pathID){
	for ( var i = 0; i < codeExport.length; i++){

		if (codeExport[i].path == pathID){
			var value = codeExport[i].code.substring(1, codeExport[i].code.length -2);
		}

	}
	var editor = CodeMirror(document.body.getElementsByTagName("article")[0], {
	    value: value,
	    lineNumbers: true,
	    mode: "javascript",
	    keyMap: "sublime",
		readOnly: "nocursor",
	    autoCloseBrackets: true,
	    matchBrackets: true,
	    showCursorWhenSelecting: true,
	    theme: "monokai",
	    tabSize: 2
	});
	}

return {

	readAllCode: function(){
	},
	show: function(d, curPath){
		localD = d;
		localCurPath = curPath;
		currentAsatWarnings = [];
		currentCatWarnings = [];
		currentMessageWarnings = [];
		curLine = -1;

		$('input.relative').attr('disabled','disabled');
		$('#normalButton').attr('disabled','disabled');
		var chartDiv = document.getElementById("code-div");

		chartDiv.style.visibility = 'visible';
		document.getElementById("chart").style.visibility = 'hidden';
		document.getElementById('normalColourLabel').style.textDecoration = 'line-through';
		document.getElementById('relativeLabel').style.textDecoration = 'line-through';

		displayCode(d.filePath);
		var warnings = getWarningLines(d.fileName);
		for( var i =0 ; i < warnings.warningList.length; i ++ ){
			highlight(warnings.warningList[i].line, warnings.warningList[i].type);
		}
		var warnings = getWarningLines(d.fileName);
		for( var i =0 ; i < warnings.warningList.length; i ++ ){
			setLabels(warnings.warningList[i].line, warnings.warningList[i].type, warnings.warningList[i].cat, warnings.warningList[i].message);
		}
	},
	hide: function(){
		$('input.relative').removeAttr("disabled");
		$('#normalButton').removeAttr("disabled");
		$("#normalButton").prop('checked', true);
        $("#asatButton").prop('checked', false);
		document.getElementById('relativeLabel').style.textDecoration = 'none';
		document.getElementById('normalColourLabel').style.textDecoration = 'none';
		var myNode = document.getElementById("code-article");
		while (myNode.firstChild) {
			myNode.removeChild(myNode.firstChild);
		}
		var chartDiv = document.getElementById("code-div");
			chartDiv.style.visibility = 'hidden';
			document.getElementById("chart").style.visibility = 'visible';
	},
	fullReload: function(){
		sourceCode.hide();
		sourceCode.show(localD, localCurPath);
		$('.CodeMirror').width(opts.width).height(opts.height - 30);
	}
}

}());<|endoftext|>


<commit_before>var guestControllers = angular.module('guestControllers', ['ngStorage', 'ngSanitize'])

guestControllers.controller('ListController', ['$scope', '$http', '$localStorage', '$timeout', '$sce',
function($scope, $http, $localStorage, $timeout, $sce) {
	$http.get('js/data.json').success(function(data) {
		// Data from json file
		$scope.guests = [];

		$scope.guestOrder = 'name';
		$scope.guestSearch = '';
		$scope.instruction = 'Please, start typing';

		// To store the string from user input
		$scope.dataField = '';

		$scope.listBtnText = 'Add Guests';
		$scope.$storage = $localStorage.$default({
			guestsList : $scope.guests
		});

		// var ref = new Firebase("https://eventstone.firebaseio.com");

		$scope.$storage.x = '';

		// List of all user events
		$scope.visualize = function() {
			var showGuest = true;
			if ($scope.guestSearch.length > 0) {
				showGuest = false;
			}
			return showGuest;
		};

		$scope.clearField = function(field) {
			field = '';
		};

		$scope.submitUserInput = function(field) {
			var arr = field.split("+");
			var newA = [];
			var length = arr.length;

			// Check if last element is empty and remove it
			if ((arr[arr.length - 1]).length === 0) {
				length = arr.length - 1;
			}
			// Check if name/ticket number starts with a space and remove space
			var prefix = '\n';
			var splicedA = {};
			for (var i = 0; i < length; i++) {
				if ((arr[i].slice(0, prefix.length)) == prefix) {
					splicedA = arr[i].slice(1, arr[i].length);
				} else {
					splicedA = arr[i];
				}
				newA.push({
					name : splicedA,
					icon : 'x',
					// id : $scope.dateString(),
					checkedIn : false,
					btnText : 'Check-in',
					guestStatus : 'Not checked-in'
				});
			}

			// Two test guests always in the system. Check for them
			if ($scope.$storage.guestsList.length <= 1) {
				$scope.$storage.guestsList = '';
			}
			Array.prototype.push.apply($scope.$storage.guestsList, newA);
			$scope.$storage.guestsList.sort();
			// field= "";
		};

		$scope.$storage.xx = "";

		$scope.deleteStored = function() {
			if (!(angular.equals($scope.$storage.guestsList, data))) {
				$scope.$storage.backUpGuestList = {};
				$scope.$storage.backUpGuestList = $scope.$storage.guestsList;
				$scope.$storage.guestsList = {};
				$scope.$storage.guestsList = data;
			}
		};

		$scope.removeElement = function(list, idx) {
			if (list.length <= 2) {
			} else {
				if (idx > list.length - 1) {
				} else {
					if (isNaN(idx)) {
					} else {
						delete list[idx];
						for (var i = idx; i < list.length; i++) {
							list[i] = list[i + 1];
						}
						list.length = list.length - 1;
					}
				}
			}
		};

		$scope.dateString = function() {
			var d = new Date();
			return d.getFullYear() + "" + ('0' + (d.getMonth() + 1)).slice(-2) + "" + ('0' + d.getDate()).slice(-2);
		};

		$scope.checkedIn = function(x) {
			if ($scope.$storage.guestsList[x].checkedIn == true) {
			} else {
				var d = new Date();
				var ds = d.toLocaleTimeString();
				// + " on " + (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear();
				$scope.$storage.guestsList[x].guestStatus = 'Checked in ' + ds;
			}
		};

		$scope.$storage.titleArr = ["Heading", "Heading", "Heading", "Heading", "Heading", "Heading", "Heading", "Heading", "Heading", "Heading", "Heading", "Heading", "Heading", "Heading", "Heading"];

		$scope.backUpTxt = function() {
			if ($scope.backUp) {
				return 'Hide Backup list';
				;
			} else {
				return 'View Backup list';
			}
		};

		$scope.backUp = false;
		$scope.backUpBtn = function() {
			$scope.backUp = !$scope.backUp;
		};
		//
		// Import/Export
		// All event lists: Previous list

		// Generate ticket numbers sequencially
		$scope.generateTicketNums = function() {
			if ($scope.$storage.totalTickets.length <= 0) {
				alert("You must enter the number of tickets to generate");
			} else {
				$scope.dataFieldNum = "";
				var numbDigits = 10 - $scope.$storage.prefix.length;
				var firstNum = " ";
				while (firstNum.length > numbDigits || firstNum.length < numbDigits) {
					firstNum = parseInt(Math.random().toString().slice(2, numbDigits + 2));
				}
				for (var i = 0; i < $scope.$storage.totalTickets; i++) {
					$scope.dataFieldNum = ($scope.$storage.prefix + "" + (firstNum + 1)) + " +" + $scope.dataFieldNum;
					firstNum--;
				}
				// $scope.$storage.guestsList = Object.assign([], $scope.testObj);
				$scope.submitUserInput($scope.dataFieldNum);
				$scope.$storage.prefix = '';
				$scope.$storage.totalTickets = '';
				$scope.dataFieldNum = '';
			}
		};

		// $scope.addGTab = true;

		$scope.init = function() {
			function startTime() {
				var today = new Date();
				var h = today.getHours();
				var m = today.getMinutes();
				var s = today.getSeconds();
				m = checkTime(m);
				s = checkTime(s);
				document.getElementById('txt').innerHTML = h + ":" + m + ":" + s;
				var t = setTimeout(startTime, 500);
			}

			function checkTime(i) {
				if (i < 10) {
					i = "0" + i
				};// add zero in front of numbers < 10
				return i;
			}

			startTime();
		}
		$timeout($scope.init);

		// Paste from excel file
		$scope.addPastedExcel = function() {
			var rows = $scope.dataFieldExcel.split('\n');
			var obj = [];
			cart = [];
			for (var i = 0; i < rows.length; i++) {
				var arr = rows[i].split('\t');
				function a() {
					var wholeRow = "";
					var element = {};
					for (var i = 0; i < arr.length; i++) {
						wholeRow = wholeRow + arr[i] + "     ";
						element[i] = arr[i];
					}
					element.guestStatus = 'Not checked-in';
					cart.push(element);
					return wholeRow;
				}

				obj.push(a());
			}
			$scope.testObj = cart;
			$scope.$storage.guestsList = Object.assign([], $scope.testObj);

			$scope.$storage.showExcelList = true;
		};

		// To be used to hide the side icon before printing
		$scope.showListIcon = true;
		$scope.printGuestList = function() {
			var printContents = document.getElementById("GList").innerHTML;
			var popupWin = window.open('', '_blank', 'width=1700,height=2200');
			popupWin.document.open();
			popupWin.document.write('<link rel="stylesheet" media="all" href="css/style.css"><link href="css/limestone.css" rel="stylesheet"  media="all">' + printContents + '');
			popupWin.document.close();
		};

		$scope.ran = function() {
			$scope.rand = Math.random().toString().slice(2, 7);
		};

		$scope.addByPasting = true;

		$scope.restoreFromBackUp = function() {
			if ($scope.$storage.backUpGuestList.length > 0) {
				$scope.$storage.guestsList = {};
				Array.prototype.push.apply($scope.$storage.guestsList, $scope.$storage.backUpGuestList);
			} else {

			}
		};

		$scope.listreplace = true;
		$scope.replaceList = function() {
			$scope.listreplace = !$scope.listreplace;
		};

		$scope.popolateReplace = true;
		$scope.replacePop = function() {
			$scope.popolateReplace = !$scope.popolateReplace;
		};

		$scope.printpage = function() {
			var originalContents = document.body.innerHTML;
			var printReport = document.getElementById('content').innerHTML;
			document.body.innerHTML = printReport;
			window.print();
			document.body.innerHTML = originalContents;
		};

		// Live screens
		$scope.firstLiveScreen = true;
		$scope.secondLiveScreen, $scope.thirdLiveScreen, $scope.fourthLiveScreen = false;

		// Live screen check in message
		$scope.liveMsgStatus = false;
		$scope.liveMsg = function() {
			$timeout(function() {
				$scope.liveMsgStatus = false;
			}, 5000);
		};

		// Live screen check in message
		$scope.guestAddFeedback = false;
		$scope.guestAddMsg = function() {
			$timeout(function() {
				$scope.guestAddFeedback = false;
			}, 5000);
		};

		//
		// $scope.checkIns = "0";
		// $scope.noCheckIns = "0";

		$scope.checkIns = function() {
			var checkIns = 0;
			for (var i = 0; i < $scope.$storage.guestsList.length; i++) {
				if ($scope.$storage.guestsList[i].checkedIn == true) {
					checkIns = checkIns + 1;
				}
			}
			return checkIns;
		};

		$scope.noCheckIns = function() {
			return $scope.$storage.guestsList.length - $scope.checkIns() - 2;
		};

		$scope.randomName = function() {
			var arrOfNames1 = ["Jason", "Jim", "Bird", "Shari", "Lily", "Shukla", "Jake", "Kurt", "Sylvia", "Smith", "Luke", "Brent", "Tony", "Chi", "Chen", "Yang", "Ada", "Oluchi", "Maj"];

			var arrOfNames2 = ["Rachel", "Neal", "Miller", "Heidecker", "Gill", "Gina", "Eva", "Sam", "John", "Bob", "Ben", "Sonita", "Brenda", "Ahmed", "Musa", "Oraye", "Ade", "Tito", "Itoro"];

			var arrOfNames3 = ["Monisha", "Peter", "Baraniuk", "Michael", "Linda", "Beni", "Asya", "Charlse", "Russel", "Brian", "Tim", "Ken", "Ugo", "Uche", "Uchi", "Zhed", "Luois", "Riel", "Emma"];

			var arrOfNames4 = ["Yan", "Chan", "Feng", "Stewart", "Raymond", "Vincent", "Zhang", "Lv", "Uchibeke", "Shirley", "Kun", "Myers", "Jimmy", "Luo", "Silong", "Kiki", "Todd", "Sloan"];

			// To lazy to count the array with the least number of names. Writes code to do it
			var sz = Math.min(arrOfNames1.length, arrOfNames2.length, arrOfNames3.length, arrOfNames4.length);

			var arrOfArrs = [arrOfNames1, arrOfNames2, arrOfNames3, arrOfNames4];

			var randomArr = Math.floor((Math.random() * (arrOfArrs.length)) + 0);
			var randomIndex = Math.floor((Math.random() * (sz - 1)) + 0);
			var arrToUse = arrOfArrs[randomArr];
			var name = arrToUse[randomIndex] + " ";
			randomArr = Math.floor((Math.random() * (arrOfArrs.length - 1)) + 0);
			randomIndex = Math.floor((Math.random() * (sz - 1)) + 0);
			arrToUse = arrOfArrs[randomArr];
			name = name + arrToUse[randomIndex];
			$scope.dataField = $scope.dataField + name + ",";
		};
	});
}]);
<commit_msg>Changed implementation of delete<commit_after>var guestControllers = angular.module('guestControllers', ['ngStorage', 'ngSanitize'])

guestControllers.controller('ListController', ['$scope', '$http', '$localStorage', '$timeout', '$sce',
function($scope, $http, $localStorage, $timeout, $sce) {
	$http.get('js/data.json').success(function(data) {
		// Data from json file
		$scope.guests = [];

		$scope.guestOrder = 'name';
		$scope.guestSearch = '';
		$scope.instruction = 'Please, start typing';

		// To store the string from user input
		$scope.dataField = '';

		$scope.listBtnText = 'Add Guests';
		$scope.$storage = $localStorage.$default({
			guestsList : $scope.guests
		});

		// var ref = new Firebase("https://eventstone.firebaseio.com");

		$scope.$storage.x = '';

		// List of all user events
		$scope.visualize = function() {
			var showGuest = true;
			if ($scope.guestSearch.length > 0) {
				showGuest = false;
			}
			return showGuest;
		};

		$scope.clearField = function(field) {
			field = '';
		};

		$scope.submitUserInput = function(field) {
			var arr = field.split("+");
			var newA = [];
			var length = arr.length;

			// Check if last element is empty and remove it
			if ((arr[arr.length - 1]).length === 0) {
				length = arr.length - 1;
			}
			// Check if name/ticket number starts with a space and remove space
			var prefix = '\n';
			var splicedA = {};
			for (var i = 0; i < length; i++) {
				if ((arr[i].slice(0, prefix.length)) == prefix) {
					splicedA = arr[i].slice(1, arr[i].length);
				} else {
					splicedA = arr[i];
				}
				newA.push({
					name : splicedA,
					icon : 'x',
					// id : $scope.dateString(),
					checkedIn : false,
					btnText : 'Check-in',
					guestStatus : 'Not checked-in'
				});
			}

			// Two test guests always in the system. Check for them
			if ($scope.$storage.guestsList.length <= 1) {
				$scope.$storage.guestsList = '';
			}
			Array.prototype.push.apply($scope.$storage.guestsList, newA);
			$scope.$storage.guestsList.sort();
			// field= "";
		};

		$scope.$storage.xx = "";

		$scope.deleteStored = function() {
			if (!(angular.equals($scope.$storage.guestsList, $scope.guests ))) {
				$scope.$storage.backUpGuestList = {};
				$scope.$storage.backUpGuestList = $scope.$storage.guestsList;
				$scope.$storage.guestsList = {};
				$scope.$storage.guestsList = $scope.guests ;
			}
		};

		$scope.removeElement = function(list, idx) {
			if (list.length <= 2) {
			} else {
				if (idx > list.length - 1) {
				} else {
					if (isNaN(idx)) {
					} else {
						delete list[idx];
						for (var i = idx; i < list.length; i++) {
							list[i] = list[i + 1];
						}
						list.length = list.length - 1;
					}
				}
			}
		};

		$scope.dateString = function() {
			var d = new Date();
			return d.getFullYear() + "" + ('0' + (d.getMonth() + 1)).slice(-2) + "" + ('0' + d.getDate()).slice(-2);
		};

		$scope.checkedIn = function(x) {
			if ($scope.$storage.guestsList[x].checkedIn == true) {
			} else {
				var d = new Date();
				var ds = d.toLocaleTimeString();
				// + " on " + (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear();
				$scope.$storage.guestsList[x].guestStatus = 'Checked in ' + ds;
			}
		};

		$scope.$storage.titleArr = ["Heading", "Heading", "Heading", "Heading", "Heading", "Heading", "Heading", "Heading", "Heading", "Heading", "Heading", "Heading", "Heading", "Heading", "Heading"];

		$scope.backUpTxt = function() {
			if ($scope.backUp) {
				return 'Hide Backup list';
				;
			} else {
				return 'View Backup list';
			}
		};

		$scope.backUp = false;
		$scope.backUpBtn = function() {
			$scope.backUp = !$scope.backUp;
		};
		//
		// Import/Export
		// All event lists: Previous list

		// Generate ticket numbers sequencially
		$scope.generateTicketNums = function() {
			if ($scope.$storage.totalTickets.length <= 0) {
				alert("You must enter the number of tickets to generate");
			} else {
				$scope.dataFieldNum = "";
				var numbDigits = 10 - $scope.$storage.prefix.length;
				var firstNum = " ";
				while (firstNum.length > numbDigits || firstNum.length < numbDigits) {
					firstNum = parseInt(Math.random().toString().slice(2, numbDigits + 2));
				}
				for (var i = 0; i < $scope.$storage.totalTickets; i++) {
					$scope.dataFieldNum = ($scope.$storage.prefix + "" + (firstNum + 1)) + " +" + $scope.dataFieldNum;
					firstNum--;
				}
				// $scope.$storage.guestsList = Object.assign([], $scope.testObj);
				$scope.submitUserInput($scope.dataFieldNum);
				$scope.$storage.prefix = '';
				$scope.$storage.totalTickets = '';
				$scope.dataFieldNum = '';
			}
		};

		// $scope.addGTab = true;

		$scope.init = function() {
			function startTime() {
				var today = new Date();
				var h = today.getHours();
				var m = today.getMinutes();
				var s = today.getSeconds();
				m = checkTime(m);
				s = checkTime(s);
				document.getElementById('txt').innerHTML = h + ":" + m + ":" + s;
				var t = setTimeout(startTime, 500);
			}

			function checkTime(i) {
				if (i < 10) {
					i = "0" + i
				};// add zero in front of numbers < 10
				return i;
			}

			startTime();
		}
		$timeout($scope.init);

		// Paste from excel file
		$scope.addPastedExcel = function() {
			var rows = $scope.dataFieldExcel.split('\n');
			var obj = [];
			cart = [];
			for (var i = 0; i < rows.length; i++) {
				var arr = rows[i].split('\t');
				function a() {
					var wholeRow = "";
					var element = {};
					for (var i = 0; i < arr.length; i++) {
						wholeRow = wholeRow + arr[i] + "     ";
						element[i] = arr[i];
					}
					element.guestStatus = 'Not checked-in';
					cart.push(element);
					return wholeRow;
				}

				obj.push(a());
			}
			$scope.testObj = cart;
			$scope.$storage.guestsList = Object.assign([], $scope.testObj);

			$scope.$storage.showExcelList = true;
		};

		// To be used to hide the side icon before printing
		$scope.showListIcon = true;
		$scope.printGuestList = function() {
			var printContents = document.getElementById("GList").innerHTML;
			var popupWin = window.open('', '_blank', 'width=1700,height=2200');
			popupWin.document.open();
			popupWin.document.write('<link rel="stylesheet" media="all" href="css/style.css"><link href="css/limestone.css" rel="stylesheet"  media="all">' + printContents + '');
			popupWin.document.close();
		};

		$scope.ran = function() {
			$scope.rand = Math.random().toString().slice(2, 7);
		};

		$scope.addByPasting = true;

		$scope.restoreFromBackUp = function() {
			if ($scope.$storage.backUpGuestList.length > 0) {
				$scope.$storage.guestsList = {};
				Array.prototype.push.apply($scope.$storage.guestsList, $scope.$storage.backUpGuestList);
			} else {

			}
		};

		$scope.listreplace = true;
		$scope.replaceList = function() {
			$scope.listreplace = !$scope.listreplace;
		};

		$scope.popolateReplace = true;
		$scope.replacePop = function() {
			$scope.popolateReplace = !$scope.popolateReplace;
		};

		$scope.printpage = function() {
			var originalContents = document.body.innerHTML;
			var printReport = document.getElementById('content').innerHTML;
			document.body.innerHTML = printReport;
			window.print();
			document.body.innerHTML = originalContents;
		};

		// Live screens
		$scope.firstLiveScreen = true;
		$scope.secondLiveScreen, $scope.thirdLiveScreen, $scope.fourthLiveScreen = false;

		// Live screen check in message
		$scope.liveMsgStatus = false;
		$scope.liveMsg = function() {
			$timeout(function() {
				$scope.liveMsgStatus = false;
			}, 5000);
		};

		// Live screen check in message
		$scope.guestAddFeedback = false;
		$scope.guestAddMsg = function() {
			$timeout(function() {
				$scope.guestAddFeedback = false;
			}, 5000);
		};

		//
		// $scope.checkIns = "0";
		// $scope.noCheckIns = "0";

		$scope.checkIns = function() {
			var checkIns = 0;
			for (var i = 0; i < $scope.$storage.guestsList.length; i++) {
				if ($scope.$storage.guestsList[i].checkedIn == true) {
					checkIns = checkIns + 1;
				}
			}
			return checkIns;
		};

		$scope.noCheckIns = function() {
			return $scope.$storage.guestsList.length - $scope.checkIns() - 2;
		};

		$scope.randomName = function() {
			var arrOfNames1 = ["Jason", "Jim", "Bird", "Shari", "Lily", "Shukla", "Jake", "Kurt", "Sylvia", "Smith", "Luke", "Brent", "Tony", "Chi", "Chen", "Yang", "Ada", "Oluchi", "Maj"];

			var arrOfNames2 = ["Rachel", "Neal", "Miller", "Heidecker", "Gill", "Gina", "Eva", "Sam", "John", "Bob", "Ben", "Sonita", "Brenda", "Ahmed", "Musa", "Oraye", "Ade", "Tito", "Itoro"];

			var arrOfNames3 = ["Monisha", "Peter", "Baraniuk", "Michael", "Linda", "Beni", "Asya", "Charlse", "Russel", "Brian", "Tim", "Ken", "Ugo", "Uche", "Uchi", "Zhed", "Luois", "Riel", "Emma"];

			var arrOfNames4 = ["Yan", "Chan", "Feng", "Stewart", "Raymond", "Vincent", "Zhang", "Lv", "Uchibeke", "Shirley", "Kun", "Myers", "Jimmy", "Luo", "Silong", "Kiki", "Todd", "Sloan"];

			// To lazy to count the array with the least number of names. Writes code to do it
			var sz = Math.min(arrOfNames1.length, arrOfNames2.length, arrOfNames3.length, arrOfNames4.length);

			var arrOfArrs = [arrOfNames1, arrOfNames2, arrOfNames3, arrOfNames4];

			var randomArr = Math.floor((Math.random() * (arrOfArrs.length)) + 0);
			var randomIndex = Math.floor((Math.random() * (sz - 1)) + 0);
			var arrToUse = arrOfArrs[randomArr];
			var name = arrToUse[randomIndex] + " ";
			randomArr = Math.floor((Math.random() * (arrOfArrs.length - 1)) + 0);
			randomIndex = Math.floor((Math.random() * (sz - 1)) + 0);
			arrToUse = arrOfArrs[randomArr];
			name = name + arrToUse[randomIndex];
			$scope.dataField = $scope.dataField + name + ",";
		};
	});
}]);
<|endoftext|>


<commit_before>import React from 'react';
import {NavLink} from 'fluxible-router';
import ContentUtil from '../util/ContentUtil';
import {connectToStores} from 'fluxible-addons-react';
import SlideControl from '../SlideModes/SlideControl';
import expandContentPanel from '../../../../actions/deckpagelayout/expandContentPanel';
import restoreDeckPageLayout from '../../../../actions/deckpagelayout/restoreDeckPageLayout';
import {Microservices} from '../../../../configs/microservices';
import ContentActionsFooterStore from '../../../../stores/ContentActionsFooterStore.js';

class ContentActionsFooter extends React.Component {
    constructor(props) {
        super(props);
        //this.state={expanded: 0};
        this.state = this.props.ContentActionsFooterStore.state; //expanded: 0
    }
    handleExpandClick(){
        this.context.executeAction(expandContentPanel, {});
        this.state.expanded = 1;
        return false;
    }
    handleCollapseClick(){
        this.context.executeAction(restoreDeckPageLayout, {});
        this.state.expanded = 0;
        return false;
    }
    getPresentationHref(){
        let presLocation = '/Presentation/' + this.props.ContentStore.selector.id + '/';
        if(this.props.ContentStore.selector.stype === 'slide'){
            // presLocation += this.props.ContentStore.selector.sid + '/';
            presLocation += '#/slide-' + this.props.ContentStore.selector.sid;
        }
        return presLocation;
    }
    handlePresentationClick(e){
        if(process.env.BROWSER){
            e.preventDefault();
            window.open(this.getPresentationHref());
        }
    }
    /*
    getPrintHref(){
        return '/PresentationPrint/' + this.props.ContentStore.selector.id + '/?print-pdf';
    }
    handlePrintClick(e){
        if(process.env.BROWSER){
            e.preventDefault();
            window.open(this.getPrintHref());
        }
    }*/
    getPDFHref(){

        if (this.props.ContentStore.selector.id !== undefined && this.props.ContentStore.selector.id !== '' && this.props.ContentStore.selector.id !== 0)
        {
            //console.log(this.props.ContentStore.selector.id);
            let splittedId =  this.props.ContentStore.selector.id.split('-'); //separates deckId and revision
            let pdfHref = Microservices.pdf.uri + '/exportPDF/' + splittedId[0];
            return pdfHref;
        }
        else
        {
            // in adddeck this.props.ContentStore.selector.id is 0
            return Microservices.pdf.uri + '/exportPDF/';
        }
    }

    handleDownloadClick(e){

        if(process.env.BROWSER){
            e.preventDefault();
            window.open(this.getPDFHref());
        }

    }

    render() {
        return (

                    {this.props.ContentStore.selector.stype === 'slide' ?

 : ''}

                    {this.props.ContentStore.selector.stype === 'slide' ? <SlideControl mode={this.props.ContentStore.mode}/> : ''}

                            <NavLink onClick={this.handlePresentationClick.bind(this)} href={this.getPresentationHref()} target="_blank">
                                <button className="ui button" type="button" aria-label="Presentation Mode" data-tooltip="Presentation Mode">

                                </button>
                            </NavLink>

                           <NavLink onClick={this.handleDownloadClick.bind(this)} href={this.getPDFHref()} target="_blank">
                            <button className="ui button" type="button" aria-label="Print" data-tooltip="Print" >

                            </button>
                            </NavLink>
                            <NavLink onClick={this.handleDownloadClick.bind(this)} href={this.getPDFHref()} target="_blank">
                                <button className="ui button" type="button" aria-label="Download" data-tooltip="Download" >

                                </button>
                            </NavLink>
                            <button className="ui disabled button" type="button" aria-label="Share" data-tooltip="Share">

                            </button>
                            {/* {this.state.expanded ? <button className="ui button" onClick={this.handleCollapseClick.bind(this)} title="Reset Layout"></button> : <button className="ui button" onClick={this.handleExpandClick.bind(this)} title="Expand Content"></button>} */}
                            {this.state.expanded ? <button className="ui button" onClick={this.handleCollapseClick.bind(this)}  aria-label="Reset Layout" data-tooltip="Reset Layout"></button> : <button className="ui button" onClick={this.handleExpandClick.bind(this)} aria-label="Expand Content" data-tooltip="Expand Content"></button>}

        );
    }
}
/*                            <NavLink onClick={this.handlePrintClick.bind(this)} href={this.getPrintHref()} target="_blank">
                                <button className="ui button">

                                </button>
                            </NavLink>
                            */

ContentActionsFooter.contextTypes = {
    executeAction: React.PropTypes.func.isRequired
};

ContentActionsFooter = connectToStores(ContentActionsFooter, [ContentActionsFooterStore], (context, props) => {
    return {
        ContentActionsFooterStore: context.getStore(ContentActionsFooterStore).getState()
    };
});
export default ContentActionsFooter;
<commit_msg>SWIK-819: Modified behaviour of Download button to generate ePub instead of PDF (PDF still available on print button).<commit_after>import React from 'react';
import {NavLink} from 'fluxible-router';
import ContentUtil from '../util/ContentUtil';
import {connectToStores} from 'fluxible-addons-react';
import SlideControl from '../SlideModes/SlideControl';
import expandContentPanel from '../../../../actions/deckpagelayout/expandContentPanel';
import restoreDeckPageLayout from '../../../../actions/deckpagelayout/restoreDeckPageLayout';
import {Microservices} from '../../../../configs/microservices';
import ContentActionsFooterStore from '../../../../stores/ContentActionsFooterStore.js';

class ContentActionsFooter extends React.Component {
    constructor(props) {
        super(props);
        //this.state={expanded: 0};
        this.state = this.props.ContentActionsFooterStore.state; //expanded: 0
    }
    handleExpandClick(){
        this.context.executeAction(expandContentPanel, {});
        this.state.expanded = 1;
        return false;
    }
    handleCollapseClick(){
        this.context.executeAction(restoreDeckPageLayout, {});
        this.state.expanded = 0;
        return false;
    }
    getPresentationHref(){
        let presLocation = '/Presentation/' + this.props.ContentStore.selector.id + '/';
        if(this.props.ContentStore.selector.stype === 'slide'){
            // presLocation += this.props.ContentStore.selector.sid + '/';
            presLocation += '#/slide-' + this.props.ContentStore.selector.sid;
        }
        return presLocation;
    }
    handlePresentationClick(e){
        if(process.env.BROWSER){
            e.preventDefault();
            window.open(this.getPresentationHref());
        }
    }
    /*
    getPrintHref(){
        return '/PresentationPrint/' + this.props.ContentStore.selector.id + '/?print-pdf';
    }
    handlePrintClick(e){
        if(process.env.BROWSER){
            e.preventDefault();
            window.open(this.getPrintHref());
        }
    }*/

    handlePrintClick(e){

        if(process.env.BROWSER){
            e.preventDefault();
            window.open(this.getExportHref('PDF'));
        }

    }

    getExportHref(type){
        if (type !== 'EPub' && type !== 'PDF') {
          return;
        }
        if (this.props.ContentStore.selector.id !== undefined && this.props.ContentStore.selector.id !== '' && this.props.ContentStore.selector.id !== 0)
        {
            //console.log(this.props.ContentStore.selector.id);
            let splittedId =  this.props.ContentStore.selector.id.split('-'); //separates deckId and revision
            let pdfHref = Microservices.pdf.uri + '/export' + type + '/' + splittedId[0];
            return pdfHref;
        }
        else
        {
            // in adddeck this.props.ContentStore.selector.id is 0
            return Microservices.pdf.uri + '/export' + type + '/';
        }
    }

    handleDownloadClick(e){

        if(process.env.BROWSER){
            e.preventDefault();
            window.open(this.getExportHref('EPub'));
        }

    }

    render() {
        return (

                    {this.props.ContentStore.selector.stype === 'slide' ?

 : ''}

                    {this.props.ContentStore.selector.stype === 'slide' ? <SlideControl mode={this.props.ContentStore.mode}/> : ''}

                            <NavLink onClick={this.handlePresentationClick.bind(this)} href={this.getPresentationHref()} target="_blank">
                                <button className="ui button" type="button" aria-label="Presentation Mode" data-tooltip="Presentation Mode">

                                </button>
                            </NavLink>

                           <NavLink onClick={this.handlePrintClick.bind(this)} href={this.getExportHref('PDF')} target="_blank">
                            <button className="ui button" type="button" aria-label="Print" data-tooltip="Print" >

                            </button>
                            </NavLink>
                            <NavLink onClick={this.handleDownloadClick.bind(this)} href={this.getExportHref('EPub')} target="_blank">
                                <button className="ui button" type="button" aria-label="Download" data-tooltip="Download" >

                                </button>
                            </NavLink>
                            <button className="ui disabled button" type="button" aria-label="Share" data-tooltip="Share">

                            </button>
                            {/* {this.state.expanded ? <button className="ui button" onClick={this.handleCollapseClick.bind(this)} title="Reset Layout"></button> : <button className="ui button" onClick={this.handleExpandClick.bind(this)} title="Expand Content"></button>} */}
                            {this.state.expanded ? <button className="ui button" onClick={this.handleCollapseClick.bind(this)}  aria-label="Reset Layout" data-tooltip="Reset Layout"></button> : <button className="ui button" onClick={this.handleExpandClick.bind(this)} aria-label="Expand Content" data-tooltip="Expand Content"></button>}

        );
    }
}
/*                            <NavLink onClick={this.handlePrintClick.bind(this)} href={this.getPrintHref()} target="_blank">
                                <button className="ui button">

                                </button>
                            </NavLink>
                            */

ContentActionsFooter.contextTypes = {
    executeAction: React.PropTypes.func.isRequired
};

ContentActionsFooter = connectToStores(ContentActionsFooter, [ContentActionsFooterStore], (context, props) => {
    return {
        ContentActionsFooterStore: context.getStore(ContentActionsFooterStore).getState()
    };
});
export default ContentActionsFooter;
<|endoftext|>


<commit_before>import Ember from 'ember';
/**
  The Products Index Page.

  **To Override:** You'll need to run the routes generator:

  ```bash
  ember g yebo-ember-storefront-routes
  ```

  This will install all of the Yebo Ember Storefront route files into your
  host application at `app/routes/yebo/*.js`, ready to be extended or
  overriden.

  @class ProductsIndex
  @namespace Route
  @extends Ember.Component
*/
export default Ember.Route.extend({
  model: function() {
    return Ember.RSVP.hash({
      products: this.yebo.store.findAll('product'),
      taxonomies: this.yebo.store.findAll('taxonomy')
    });
  }
});
<commit_msg>Change the list call to call the service method<commit_after>import Ember from 'ember';
/**
  The Products Index Page.

  **To Override:** You'll need to run the routes generator:

  ```bash
  ember g yebo-ember-storefront-routes
  ```

  This will install all of the Yebo Ember Storefront route files into your
  host application at `app/routes/yebo/*.js`, ready to be extended or
  overriden.

  @class ProductsIndex
  @namespace Route
  @extends Ember.Component
*/
export default Ember.Route.extend({
  model: function() {
    return Ember.RSVP.hash({
      // products: this.yebo.store.findAll('product'),
      products: this.get('yebo.products').search(),
      taxonomies: this.yebo.store.findAll('taxonomy')
    });
  }
});
<|endoftext|>


<commit_before>'use strict';

const models = require('../../models');
const fs = require('fs-extra');
const env = require('../../config/envVariables.js');
const Boom = require('boom');

// File Upload Route Configs
let files = {
	add: (req, res) => {
		models.File.create({
				ArtistId: req.payload.ArtistId,
				AlbumReleaseId: req.payload.ArtistId,
				identifier: req.payload.identifier,
				name: req.payload.name,
				size: req.payload.size,
				type: req.payload.type
            })
            .then((file) => {
				res(file).code(200);
			});
    },
	getAll: (req, res) => {
        models.File.findAll(
			{
				limit: 50
			}
		)
        .then((files) => {
	    	res(files).code(200);
		});
    },
    create: (request, reply) => {
        let data = request.payload;
        if (data.file) {
            let name = Date.now() + '-' + data.file.hapi.filename;
            let path = __dirname + '/' + request.params.path + '/' + name;
            let file = fs.createWriteStream(path);

            file.on('error', (err) => {
                console.error(err);
            });

            data.file.pipe(file);

            data.file.on('end', (err) => {
                let response = {
					file: {
						name: name,
						size: request.params.size,
						type: data.file.hapi.headers['content-type']
					},
                    headers: data.file.hapi.headers,
                    status: 200,
                    statusText: 'File uploaded successfully!'
                };
                reply(JSON.stringify(response));
            });
        }
        else {
            let response = {
                filename: data.file.hapi.filename,
                headers: data.file.hapi.headers,
                status: 400,
                statusText: 'There was an error uploading your file. Max sure the dimensions are 800px by 530px.'
            };
            reply(JSON.stringify(response));
        }
    },
	delete: (req, res) => {
        models.File.destroy({
                where: {
                    id: req.params.id
                }
            })
            .then((file) => {
                if (file) {
                    res().code(200);
                }
                else {
                    res().code(404);
                }
            });
    }
};

module.exports = files;
<commit_msg>Server bug fix<commit_after>'use strict';

const models = require('../../models');
const fs = require('fs-extra');
const env = require('../../config/envVariables.js');
const Boom = require('boom');

// File Upload Route Configs
let files = {
	add: (req, res) => {
		models.File.create({
				ArtistId: req.payload.ArtistId,
				AlbumReleaseId: req.payload.AlbumReleaseId,
				identifier: req.payload.identifier,
				name: req.payload.name,
				size: req.payload.size,
				type: req.payload.type
            })
            .then((file) => {
				res(file).code(200);
			});
    },
	getAll: (req, res) => {
        models.File.findAll(
			{
				limit: 50
			}
		)
        .then((files) => {
	    	res(files).code(200);
		});
    },
    create: (request, reply) => {
        let data = request.payload;
        if (data.file) {
            let name = Date.now() + '-' + data.file.hapi.filename;
            let path = __dirname + '/' + request.params.path + '/' + name;
            let file = fs.createWriteStream(path);

            file.on('error', (err) => {
                console.error(err);
            });

            data.file.pipe(file);

            data.file.on('end', (err) => {
                let response = {
					file: {
						name: name,
						size: request.params.size,
						type: data.file.hapi.headers['content-type']
					},
                    headers: data.file.hapi.headers,
                    status: 200,
                    statusText: 'File uploaded successfully!'
                };
                reply(JSON.stringify(response));
            });
        }
        else {
            let response = {
                filename: data.file.hapi.filename,
                headers: data.file.hapi.headers,
                status: 400,
                statusText: 'There was an error uploading your file. Max sure the dimensions are 800px by 530px.'
            };
            reply(JSON.stringify(response));
        }
    },
	delete: (req, res) => {
        models.File.destroy({
                where: {
                    id: req.params.id
                }
            })
            .then((file) => {
                if (file) {
                    res().code(200);
                }
                else {
                    res().code(404);
                }
            });
    }
};

module.exports = files;
<|endoftext|>