<commit_before>const Clutter = imports.gi.Clutter;
const Gio = imports.gi.Gio;
const Lang = imports.lang;
const Mainloop = imports.mainloop;
const Meta = imports.gi.Meta;
const Shell = imports.gi.Shell;
const St = imports.gi.St;
const Util = imports.misc.util;

const Main = imports.ui.main;
const PanelMenu = imports.ui.panelMenu;
const PopupMenu = imports.ui.popupMenu;
const CheckBox = imports.ui.checkBox.CheckBox;

const Clipboard = St.Clipboard.get_default();
const CLIPBOARD_TYPE = St.ClipboardType.CLIPBOARD;

const ExtensionUtils = imports.misc.extensionUtils;
const Me = ExtensionUtils.getCurrentExtension();
const Utils = Me.imports.utils;
const Prefs = Me.imports.prefs;
const prettyPrint = Utils.prettyPrint;
const writeRegistry = Utils.writeRegistry;
const readRegistry = Utils.readRegistry;

let TIMEOUT_MS           = 1000;
let MAX_REGISTRY_LENGTH  = 15;
let MAX_ENTRY_LENGTH     = 50;
let DELETE_ENABLED       = true;

let _clipboardTimeoutId = null;
const ClipboardIndicator = Lang.Class({
        Name: 'ClipboardIndicator',
        Extends: PanelMenu.Button,

        clipItemsRadioGroup: [],

        destroy: function () {
            // Disconnect the settings event
            this._settings.disconnect(this._settingsChangedId);

            // Call parent
            this.parent();
        },

        _init: function() {
            this.parent(0.0, "ClipboardIndicator");
            let hbox = new St.BoxLayout({ style_class: 'panel-status-menu-box clipboard-indicator-hbox' });
            let icon = new St.Icon({ icon_name: 'edit-cut-symbolic', //'mail-attachment-symbolic',
                                     style_class: 'system-status-icon clipboard-indicator-icon' });

            hbox.add_child(icon);
            this.actor.add_child(hbox);

            this._loadSettings();
            this._buildMenu();
            this._setupTimeout();
        },

        _buildMenu: function () {
            let that = this;
            this._getCache(function (clipHistory) {
                let lastIdx = clipHistory.length - 1;
                let clipItemsArr = that.clipItemsRadioGroup;

                // Create menu section for items
                that.historySection = new PopupMenu.PopupMenuSection();
                that.menu.addMenuItem(that.historySection);

                // Add cached items
                clipHistory.forEach(function (buffer) {
                    that._addEntry(buffer);
                });

                // Add separator
                that.menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem());

                // Add 'Clear' button which removes all items from cache
                let clearMenuItem = new PopupMenu.PopupMenuItem('Clear History');
                that.menu.addMenuItem(clearMenuItem);
                clearMenuItem.actor.connect('button-press-event', Lang.bind(that, that._removeAll));

                // Add 'Settings' menu item to open settings
                let settingsMenuItem = new PopupMenu.PopupMenuItem('Settings');
                that.menu.addMenuItem(settingsMenuItem);
                settingsMenuItem.actor.connect('button-press-event', Lang.bind(that, that._openSettings));

                if (lastIdx >= 0) {
                    that._selectMenuItem(clipItemsArr[lastIdx]);
                }
            });
        },

        _setEntryLabel: function (menuItem) {
            let buffer     = menuItem.clipContents,
                shortened  = buffer.substr(0,MAX_ENTRY_LENGTH).replace(/\s+/g, ' ');

            if (buffer.length > MAX_ENTRY_LENGTH)
                shortened += '...';

            menuItem.label.set_text(shortened);
        },

        _addEntry: function (buffer, autoSelect, autoSetClip) {
            let menuItem = new PopupMenu.PopupMenuItem('');

            menuItem.clipContents = buffer;
            menuItem.radioGroup = this.clipItemsRadioGroup;
            menuItem.buttonPressId = menuItem.actor.connect('button-press-event',
                                        Lang.bind(menuItem, this._onMenuItemSelected));

            this._setEntryLabel(menuItem);
            this.clipItemsRadioGroup.push(menuItem);

            let icon = new St.Icon({
                icon_name: 'edit-delete-symbolic', //'mail-attachment-symbolic',
                style_class: 'system-status-icon'
            });
            let icoBtn = new St.Button({
                x_fill: true,
                can_focus: true,
                child: icon
            });
            icoBtn.set_x_align(Clutter.ActorAlign.END);
            icoBtn.set_x_expand(true);
            icoBtn.set_y_expand(true);

            menuItem.actor.add_child(icoBtn);
            menuItem.icoBtn = icoBtn;
            menuItem.deletePressId = icoBtn.connect('button-press-event',
                Lang.bind(this, function () {
                    this._removeEntry(menuItem);
                }));

            this.historySection.addMenuItem(menuItem);
            if (autoSelect === true) this._selectMenuItem(menuItem, autoSetClip);
            this._updateCache();
        },

        _removeAll: function () {
            let that = this;
            // We can't actually remove all items, because the clipboard still
            // has data that will be re-captured on next refresh, so we remove
            // all except the currently selected item
            that.historySection._getMenuItems().forEach(function (mItem) {
                if (!mItem.currentlySelected) {
                    let idx = that.clipItemsRadioGroup.indexOf(mItem);
                    mItem.destroy();
                    that.clipItemsRadioGroup.splice(idx,1);
                }
            });
            that._updateCache();
        },

        _removeEntry: function (menuItem) {
            let itemIdx = this.clipItemsRadioGroup.indexOf(menuItem);

            menuItem.destroy();
            this.clipItemsRadioGroup.splice(itemIdx,1);
            this._updateCache();
        },

        _removeOldestEntries: function () {
            let that = this;
            while (that.clipItemsRadioGroup.length > MAX_REGISTRY_LENGTH) {
                let oldest = that.clipItemsRadioGroup.shift();
                oldest.actor.disconnect(oldest.buttonPressId);
                oldest.destroy();
            }

            that._updateCache();
        },

        _onMenuItemSelected: function (autoSet) {
            var that = this;
            that.radioGroup.forEach(function (menuItem) {
                let clipContents = that.clipContents;

                if (menuItem === that && clipContents) {
                    that.setOrnament(PopupMenu.Ornament.DOT);
                    that.icoBtn.visible = false;
                    that.currentlySelected = true;
                    if (autoSet !== false)
                        Clipboard.set_text(CLIPBOARD_TYPE, clipContents);
                }
                else {
                    menuItem.icoBtn.visible = true;
                    menuItem.setOrnament(PopupMenu.Ornament.NONE);
                    menuItem.currentlySelected = false;
                }
            });
        },

        _selectMenuItem: function (menuItem, autoSet) {
            let fn = Lang.bind(menuItem, this._onMenuItemSelected);
            fn(autoSet);
        },

        _getCache: function (cb) {
            return readRegistry(cb);
        },

        _updateCache: function () {
            writeRegistry(this.clipItemsRadioGroup.map(function (menuItem) {
                return menuItem.clipContents;
            }));
        },

        _refreshIndicator: function () {
            let that = this;
            Clipboard.get_text(CLIPBOARD_TYPE, function (clipBoard, text) {
                let registry = that.clipItemsRadioGroup.map(function (menuItem) {
                    return menuItem.clipContents;
                });
                if (text && registry.indexOf(text) < 0) {
                    that._addEntry(text, true, false);
                    that._removeOldestEntries();
                }
            });
        },

        _setupTimeout: function (recurse) {
            let that = this;
            recurse = typeof recurse === 'boolean' ? recurse : true;

            _clipboardTimeoutId = Mainloop.timeout_add(TIMEOUT_MS, function () {
                that._refreshIndicator();
                return recurse;
            });
        },

        _openSettings: function () {
            Util.spawn([
                "gnome-shell-extension-prefs",
                Me.uuid
            ]);
        },

        _loadSettings: function () {
            this._settings = Prefs.SettingsSchema;
            this._settingsChangedId = this._settings.connect('changed',
                                        Lang.bind(this, this._onSettingsChange));
            this._fetchSettings();
        },

        _fetchSettings: function () {
            TIMEOUT_MS           = this._settings.get_int(Prefs.Fields.INTERVAL);
            MAX_REGISTRY_LENGTH  = this._settings.get_int(Prefs.Fields.HISTORY_SIZE);
            MAX_ENTRY_LENGTH     = this._settings.get_int(Prefs.Fields.PREVIEW_SIZE);
            DELETE_ENABLED       = this._settings.get_boolean(Prefs.Fields.DELETE);
        },

        _onSettingsChange: function () {
            var that = this;

            // Load the settings into variables
            that._fetchSettings();

            // Remove old entries in case the registry size changed
            that._removeOldestEntries();

            // Re-set menu-items lables in case preview size changed
            that.historySection._getMenuItems().forEach(function (mItem) {
                that._setEntryLabel(mItem);
            });
        }
    });

function init () {

}

let clipboardIndicator;
function enable () {
    clipboardIndicator = new ClipboardIndicator();
    Main.panel.addToStatusArea('clipboardIndicator', clipboardIndicator, 1);
}

function disable () {
    clipboardIndicator.destroy();
    if (_clipboardTimeoutId) Mainloop.source_remove(_clipboardTimeoutId);
}
<commit_msg>Save timeout id on instance and remove on `.destroy()`<commit_after>const Clutter = imports.gi.Clutter;
const Gio = imports.gi.Gio;
const Lang = imports.lang;
const Mainloop = imports.mainloop;
const Meta = imports.gi.Meta;
const Shell = imports.gi.Shell;
const St = imports.gi.St;
const Util = imports.misc.util;

const Main = imports.ui.main;
const PanelMenu = imports.ui.panelMenu;
const PopupMenu = imports.ui.popupMenu;
const CheckBox = imports.ui.checkBox.CheckBox;

const Clipboard = St.Clipboard.get_default();
const CLIPBOARD_TYPE = St.ClipboardType.CLIPBOARD;

const ExtensionUtils = imports.misc.extensionUtils;
const Me = ExtensionUtils.getCurrentExtension();
const Utils = Me.imports.utils;
const Prefs = Me.imports.prefs;
const prettyPrint = Utils.prettyPrint;
const writeRegistry = Utils.writeRegistry;
const readRegistry = Utils.readRegistry;

let TIMEOUT_MS           = 1000;
let MAX_REGISTRY_LENGTH  = 15;
let MAX_ENTRY_LENGTH     = 50;
let DELETE_ENABLED       = true;

const ClipboardIndicator = Lang.Class({
        Name: 'ClipboardIndicator',
        Extends: PanelMenu.Button,

        _clipboardTimeoutId: null,
        clipItemsRadioGroup: [],

        destroy: function () {
            // Disconnect the settings event
            this._settings.disconnect(this._settingsChangedId);

            // Remove the timeout source
            if (this._clipboardTimeoutId)
                Mainloop.source_remove(this._clipboardTimeoutId);

            // Call parent
            this.parent();
        },

        _init: function() {
            this.parent(0.0, "ClipboardIndicator");
            let hbox = new St.BoxLayout({ style_class: 'panel-status-menu-box clipboard-indicator-hbox' });
            let icon = new St.Icon({ icon_name: 'edit-cut-symbolic', //'mail-attachment-symbolic',
                                     style_class: 'system-status-icon clipboard-indicator-icon' });

            hbox.add_child(icon);
            this.actor.add_child(hbox);

            this._loadSettings();
            this._buildMenu();
            this._setupTimeout();
        },

        _buildMenu: function () {
            let that = this;
            this._getCache(function (clipHistory) {
                let lastIdx = clipHistory.length - 1;
                let clipItemsArr = that.clipItemsRadioGroup;

                // Create menu section for items
                that.historySection = new PopupMenu.PopupMenuSection();
                that.menu.addMenuItem(that.historySection);

                // Add cached items
                clipHistory.forEach(function (buffer) {
                    that._addEntry(buffer);
                });

                // Add separator
                that.menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem());

                // Add 'Clear' button which removes all items from cache
                let clearMenuItem = new PopupMenu.PopupMenuItem('Clear History');
                that.menu.addMenuItem(clearMenuItem);
                clearMenuItem.actor.connect('button-press-event', Lang.bind(that, that._removeAll));

                // Add 'Settings' menu item to open settings
                let settingsMenuItem = new PopupMenu.PopupMenuItem('Settings');
                that.menu.addMenuItem(settingsMenuItem);
                settingsMenuItem.actor.connect('button-press-event', Lang.bind(that, that._openSettings));

                if (lastIdx >= 0) {
                    that._selectMenuItem(clipItemsArr[lastIdx]);
                }
            });
        },

        _setEntryLabel: function (menuItem) {
            let buffer     = menuItem.clipContents,
                shortened  = buffer.substr(0,MAX_ENTRY_LENGTH).replace(/\s+/g, ' ');

            if (buffer.length > MAX_ENTRY_LENGTH)
                shortened += '...';

            menuItem.label.set_text(shortened);
        },

        _addEntry: function (buffer, autoSelect, autoSetClip) {
            let menuItem = new PopupMenu.PopupMenuItem('');

            menuItem.clipContents = buffer;
            menuItem.radioGroup = this.clipItemsRadioGroup;
            menuItem.buttonPressId = menuItem.actor.connect('button-press-event',
                                        Lang.bind(menuItem, this._onMenuItemSelected));

            this._setEntryLabel(menuItem);
            this.clipItemsRadioGroup.push(menuItem);

            let icon = new St.Icon({
                icon_name: 'edit-delete-symbolic', //'mail-attachment-symbolic',
                style_class: 'system-status-icon'
            });
            let icoBtn = new St.Button({
                x_fill: true,
                can_focus: true,
                child: icon
            });
            icoBtn.set_x_align(Clutter.ActorAlign.END);
            icoBtn.set_x_expand(true);
            icoBtn.set_y_expand(true);

            menuItem.actor.add_child(icoBtn);
            menuItem.icoBtn = icoBtn;
            menuItem.deletePressId = icoBtn.connect('button-press-event',
                Lang.bind(this, function () {
                    this._removeEntry(menuItem);
                }));

            this.historySection.addMenuItem(menuItem);
            if (autoSelect === true) this._selectMenuItem(menuItem, autoSetClip);
            this._updateCache();
        },

        _removeAll: function () {
            let that = this;
            // We can't actually remove all items, because the clipboard still
            // has data that will be re-captured on next refresh, so we remove
            // all except the currently selected item
            that.historySection._getMenuItems().forEach(function (mItem) {
                if (!mItem.currentlySelected) {
                    let idx = that.clipItemsRadioGroup.indexOf(mItem);
                    mItem.destroy();
                    that.clipItemsRadioGroup.splice(idx,1);
                }
            });
            that._updateCache();
        },

        _removeEntry: function (menuItem) {
            let itemIdx = this.clipItemsRadioGroup.indexOf(menuItem);

            menuItem.destroy();
            this.clipItemsRadioGroup.splice(itemIdx,1);
            this._updateCache();
        },

        _removeOldestEntries: function () {
            let that = this;
            while (that.clipItemsRadioGroup.length > MAX_REGISTRY_LENGTH) {
                let oldest = that.clipItemsRadioGroup.shift();
                oldest.actor.disconnect(oldest.buttonPressId);
                oldest.destroy();
            }

            that._updateCache();
        },

        _onMenuItemSelected: function (autoSet) {
            var that = this;
            that.radioGroup.forEach(function (menuItem) {
                let clipContents = that.clipContents;

                if (menuItem === that && clipContents) {
                    that.setOrnament(PopupMenu.Ornament.DOT);
                    that.icoBtn.visible = false;
                    that.currentlySelected = true;
                    if (autoSet !== false)
                        Clipboard.set_text(CLIPBOARD_TYPE, clipContents);
                }
                else {
                    menuItem.icoBtn.visible = true;
                    menuItem.setOrnament(PopupMenu.Ornament.NONE);
                    menuItem.currentlySelected = false;
                }
            });
        },

        _selectMenuItem: function (menuItem, autoSet) {
            let fn = Lang.bind(menuItem, this._onMenuItemSelected);
            fn(autoSet);
        },

        _getCache: function (cb) {
            return readRegistry(cb);
        },

        _updateCache: function () {
            writeRegistry(this.clipItemsRadioGroup.map(function (menuItem) {
                return menuItem.clipContents;
            }));
        },

        _refreshIndicator: function () {
            let that = this;
            Clipboard.get_text(CLIPBOARD_TYPE, function (clipBoard, text) {
                let registry = that.clipItemsRadioGroup.map(function (menuItem) {
                    return menuItem.clipContents;
                });
                if (text && registry.indexOf(text) < 0) {
                    that._addEntry(text, true, false);
                    that._removeOldestEntries();
                }
            });
        },

        _setupTimeout: function (recurse) {
            let that = this;
            recurse = typeof recurse === 'boolean' ? recurse : true;

            this._clipboardTimeoutId = Mainloop.timeout_add(TIMEOUT_MS, function () {
                that._refreshIndicator();

                // If the timeout handler returns `false`, the source is
                // automatically removed, so we reset the timeout-id so it won't
                // be removed on `.destroy()`
                if (recurse === false)
                    that._clipboardTimeoutId = null;

                // As long as the timeout handler returns `true`, the handler
                // will be invoked again and again as an interval
                return recurse;
            });
        },

        _openSettings: function () {
            Util.spawn([
                "gnome-shell-extension-prefs",
                Me.uuid
            ]);
        },

        _loadSettings: function () {
            this._settings = Prefs.SettingsSchema;
            this._settingsChangedId = this._settings.connect('changed',
                                        Lang.bind(this, this._onSettingsChange));
            this._fetchSettings();
        },

        _fetchSettings: function () {
            TIMEOUT_MS           = this._settings.get_int(Prefs.Fields.INTERVAL);
            MAX_REGISTRY_LENGTH  = this._settings.get_int(Prefs.Fields.HISTORY_SIZE);
            MAX_ENTRY_LENGTH     = this._settings.get_int(Prefs.Fields.PREVIEW_SIZE);
            DELETE_ENABLED       = this._settings.get_boolean(Prefs.Fields.DELETE);
        },

        _onSettingsChange: function () {
            var that = this;

            // Load the settings into variables
            that._fetchSettings();

            // Remove old entries in case the registry size changed
            that._removeOldestEntries();

            // Re-set menu-items lables in case preview size changed
            that.historySection._getMenuItems().forEach(function (mItem) {
                that._setEntryLabel(mItem);
            });
        }
    });

function init () {

}

let clipboardIndicator;
function enable () {
    clipboardIndicator = new ClipboardIndicator();
    Main.panel.addToStatusArea('clipboardIndicator', clipboardIndicator, 1);
}

function disable () {
    clipboardIndicator.destroy();
}
<|endoftext|>


<commit_before>var vscode = require('vscode');
var loremIpsum = require('lorem-ipsum');

function activate(context) {
  var commands = [
    vscode.commands.registerCommand('lorem-ipsum.line', generateLine),
    vscode.commands.registerCommand('lorem-ipsum.paragraph', generateParagraph),
    vscode.commands.registerCommand('lorem-ipsum.paragraph.multiple', generateMultipleParagraphs)
  ];

  commands.forEach(function (command) {
    context.subscriptions.push(command);
  });
}

function insertText(text) {
  var editor = vscode.window.activeTextEditor;
  editor.edit(function (editBuilder) {
    editBuilder.delete(editor.selection);
  }).then(function () {
    editor.edit(function (editBuilder) {
      editBuilder.insert(editor.selection.start, text);
    });
  });
}

function generateLine() {
  insertText(loremIpsum({
    count: 1,
    units: 'sentences'
  }));
}

function generateParagraph() {
  insertText(loremIpsum({
    count: 1,
    units: 'paragraphs'
  }));
}

async function generateMultipleParagraphs() {
  const items = [];
  for (let i = 2; i <= 10; i++) {
    items.push(i.toString());
  }

  const count = await vscode.window.showQuickPick(items, { placeHolder: 'How many paragrams?' });
  if (!count) {
    return;
  }

  insertText(loremIpsum({
    count: Number.parseInt(count),
    units: 'paragraphs'
  }));
}

exports.activate = activate;
<commit_msg>Fix typo<commit_after>var vscode = require('vscode');
var loremIpsum = require('lorem-ipsum');

function activate(context) {
  var commands = [
    vscode.commands.registerCommand('lorem-ipsum.line', generateLine),
    vscode.commands.registerCommand('lorem-ipsum.paragraph', generateParagraph),
    vscode.commands.registerCommand('lorem-ipsum.paragraph.multiple', generateMultipleParagraphs)
  ];

  commands.forEach(function (command) {
    context.subscriptions.push(command);
  });
}

function insertText(text) {
  var editor = vscode.window.activeTextEditor;
  editor.edit(function (editBuilder) {
    editBuilder.delete(editor.selection);
  }).then(function () {
    editor.edit(function (editBuilder) {
      editBuilder.insert(editor.selection.start, text);
    });
  });
}

function generateLine() {
  insertText(loremIpsum({
    count: 1,
    units: 'sentences'
  }));
}

function generateParagraph() {
  insertText(loremIpsum({
    count: 1,
    units: 'paragraphs'
  }));
}

async function generateMultipleParagraphs() {
  const items = [];
  for (let i = 2; i <= 10; i++) {
    items.push(i.toString());
  }

  const count = await vscode.window.showQuickPick(items, { placeHolder: 'How many paragraphs?' });
  if (!count) {
    return;
  }

  insertText(loremIpsum({
    count: Number.parseInt(count),
    units: 'paragraphs'
  }));
}

exports.activate = activate;
<|endoftext|>


<commit_before>'use strict';

/*
	Angular Controller

	Logic atm is here
*/

/* jshint -W098 */
angular.module('mean.das', ["chart.js"]).controller('DasController', ['$scope', 'Global', 'Speedup',
  function($scope, Global, Speedup) {
    $scope.global = Global;
    $scope.package = {
      name: 'das'
    };

    $scope.labels = ['0-5', '5-10', '10-15', '15-20', '20-25', '25-30', '30+'];
	$scope.series = ['Speedup Distribution'];
	$scope.data = [
		[0, 0, 0, 0, 0, 0, 0]
	];

    $scope.getAllSpeedups = function() {
    	//console.log(Speedup("hi"));
    	/*
    	Speedup.query(function(data) {
    		$scope.speedups = data;
    	});
		/**/
		Speedup.getAll()
			.success(function(data) {
				var speedups = data;

				console.log(speedups);

			})
			.error(function(error) {

			});
    };
    $scope.getAllSpeedups();

  }
]);

<commit_msg>- show values on graph<commit_after>'use strict';

/*
	Angular Controller

	Logic atm is here
*/

/* jshint -W098 */
angular.module('mean.das', ['chart.js']).controller('DasController', ['$scope', 'Global', 'Speedup',
  function($scope, Global, Speedup) {
    $scope.global = Global;
    $scope.package = {
      name: 'das'
    };

    $scope.labels = ['0-5', '5-10', '10-15', '15-20', '20-25', '25-30', '30+'];
	$scope.series = ['Speedup Distribution'];
	$scope.data = [
		[0, 0, 0, 0, 0, 0, 0]
	];

    $scope.getAllSpeedups = function() {
		Speedup.scope = $scope;
		Speedup.getAll()
			.success(function(data) {
				var speedups = data;

				var i = 0;

				for (i=0; i<speedups.length; i++) {
					var speedup = speedups[i];

					console.log(speedup.timeLeft);
					var times = speedup.timeLeft.split(':');
					var totalMinutes = parseInt(times[0]) * 60 + parseInt(times[1]);

					var index = Math.floor(totalMinutes / 5);
					console.log(times);
					console.log(index);
					console.log(parseInt(times[1]));

					index = Math.min(index, $scope.data[0].length-1);
					console.log(index);

					$scope.data[0][index] += 1;
				}

			})
			.error(function(error) {

			});
    };
    $scope.getAllSpeedups();

  }
]);

<|endoftext|>


<commit_before>var React = require("react");
var Router = require('react-router');
var { Route, DefaultRoute, RouteHandler, Link } = Router;

var Header = require("./Header");

var TeacherView = React.createClass({
  getInitialState: function(){
    return {
      teacher: { _id: 0 }
    }
  },
  componentDidMount: function() {
    var teacherView = this;
    var action = '/teachers/' + this.props.params.id;
    var method = 'get';

    var request = $.ajax({
      url:      action,
      method:   method,
      dataType: "json"
    });

    request.done(function(serverData){
      teacherView.setState({
        teacher: serverData.teacher
      });
    });

    request.fail(function(serverData){
      console.log('There was an error getting the teacher')
      console.log(serverData);
    });
  },
  handleUpdateTeacher: function(serverData){
    this.setState({
      teacher: serverData.teacher
    });
  },
  render: function() {
    return (

Welcome, { this.state.teacher.first_name}

        <RouteHandler teacher={this.state.teacher} update={this.handleUpdateTeacher}/>

    );
  },
});

module.exports = TeacherView;
<commit_msg>add debugger to student panel call<commit_after>var React = require("react");
var Router = require('react-router');
var { Route, DefaultRoute, RouteHandler, Link } = Router;

var Header = require("./Header");

var TeacherView = React.createClass({
  getInitialState: function(){
    return {
      teacher: { _id: 0 }
    }
  },
  componentDidMount: function() {
    var teacherView = this;
    var action = '/teachers/' + this.props.params.id;
    var method = 'get';

    var request = $.ajax({
      url:      action,
      method:   method,
      dataType: "json"
    });

    request.done(function(serverData){
      debugger
      teacherView.setState({
        teacher: serverData.teacher
      });
    });

    request.fail(function(serverData){
      console.log('There was an error getting the teacher')
      console.log(serverData);
    });
  },
  handleUpdateTeacher: function(serverData){
    this.setState({
      teacher: serverData.teacher
    });
  },
  render: function() {
    return (

Welcome, { this.state.teacher.first_name}

        <RouteHandler teacher={this.state.teacher} update={this.handleUpdateTeacher}/>

    );
  },
});

module.exports = TeacherView;
<|endoftext|>


<commit_before>const { dbMiddleware } = require('~/database');
const trackRegister = require('~/trackRegister');

module.exports = (router) => {
  for (const method of ['post', 'get']) {
    router[method](
      '/track/:token',
      dbMiddleware(),
      handler,
    );
  }
};

async function handler(ctx) {
  const [item] = await ctx.state.db.query(
    'SELECT id, maxCount, maxAge FROM trackingDevice WHERE token = ?',
    [ctx.params.token],
  );
  if (!item) {
    ctx.status = 404;
  } else {
    const q = ctx.method === 'POST' && ctx.request.type === 'application/x-www-form-urlencoded' ? ctx.request.body : ctx.query;

    const { message } = q;

    const lat = Number.parseFloat(q.lat);
    const lon = Number.parseFloat(q.lon);
    const altitude = q.alt === undefined ? null : Number.parseFloat(q.alt);
    const speed = q.speed === undefined ? null : Number.parseFloat(q.speed);
    const accuracy = q.acc === undefined ? null : Number.parseFloat(q.acc);
    const bearing = q.bearing === undefined ? null : Number.parseFloat(q.bearing);
    const battery = q.battery === undefined ? null : Number.parseFloat(q.battery);
    const gsmSignal = q.gsm_signal === undefined ? null : Number.parseFloat(q.gsm_signal);
    const time = guessTime(q.time);

    if (time === null
        || Number.isNaN(lat) || lat < -90 || lat > 90 || Number.isNaN(lon) || lon < -180 || lon > 180
        || Number.isNaN(battery) || battery !== null && (battery < 0 || battery > 100)
        || Number.isNaN(gsmSignal) || gsmSignal !== null && (gsmSignal < 0 || gsmSignal > 100)
        || Number.isNaN(bearing) || bearing !== null && (bearing < 0 || bearing > 360)
        || Number.isNaN(accuracy) || accuracy !== null && accuracy < 0
        || Number.isNaN(speed) || speed !== null && speed < 0
    ) {
      ctx.status = 400;
      return;
    }

    const now = new Date();

    const { id, maxAge, maxCount } = item;

    const { insertId } = await ctx.state.db.query(
      `INSERT INTO trackingPoint (deviceId, lat, lon, altitude, speed, accuracy, bearing, battery, gsmSignal, message, createdAt)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [id, lat, lon, altitude, speed, accuracy, bearing, battery, gsmSignal, message, time],
    );

    if (maxAge) {
      await ctx.state.db.query(
        'DELETE FROM trackingPoint WHERE deviceId = ? AND TIMESTAMPDIFF(SECOND, createdAt, now()) > ?',
        [id, maxAge],
      );
    }

    if (maxCount) {
      await ctx.state.db.query(
        'DELETE t FROM trackingPoint AS t JOIN (SELECT id FROM trackingPoint WHERE deviceId = ? ORDER BY id DESC LIMIT 18446744073709551615 OFFSET ?) tlimit ON t.id = tlimit.id',
        [id, maxCount + 1],
      );
    }

    const rows = await ctx.state.db.query(
      'SELECT token FROM trackingAccessToken WHERE deviceId = ? AND (timeFrom IS NULL OR timeFrom > ?) AND (timeTo IS NULL OR timeTo < ?)',
      [id, now, now],
    );

    const notify = (type, key) => {
      const websockets = trackRegister.get(key);
      if (websockets) {
        for (const ws of websockets) {
          if (ws.readyState === 1) {
            ws.send(JSON.stringify({
              jsonrpc: '2.0',
              method: 'tracking.addPoint',
              params: {
                // TODO validate if time matches limits
                id: insertId, lat, lon, altitude, speed, accuracy, bearing, battery, gsmSignal, message, [type]: key, ts: time.toISOString(),
              },
            }));
          }
        }
      }
    };

    for (const { token } of rows) {
      notify('token', token);
    }
    notify('deviceId', id);

    ctx.body = { id: insertId };
  }
}

function guessTime(t) {
  const now = new Date();
  const min = new Date();
  min.setMonth(min.getMonth() - 1);
  const max = new Date();
  max.setDate(min.getDate() + 1);

  if (!t) {
    return now;
  }

  const d1 = new Date(t);
  if (max > d1 && d1 > min) {
    return d1;
  }

  const n = Number.parseInt(t, 10);
  if (Number.isNaN(n)) {
    return null;
  }

  const d2 = new Date(t);
  if (max > d2 && d2 > min) {
    return d2;
  }

  const d3 = new Date(t * 1000);
  if (max > d3 && d3 > min) {
    return d3;
  }

  return null;
}
<commit_msg>fixed guessing time<commit_after>const { dbMiddleware } = require('~/database');
const trackRegister = require('~/trackRegister');

module.exports = (router) => {
  for (const method of ['post', 'get']) {
    router[method](
      '/track/:token',
      dbMiddleware(),
      handler,
    );
  }
};

async function handler(ctx) {
  const [item] = await ctx.state.db.query(
    'SELECT id, maxCount, maxAge FROM trackingDevice WHERE token = ?',
    [ctx.params.token],
  );
  if (!item) {
    ctx.status = 404;
  } else {
    const q = ctx.method === 'POST' && ctx.request.type === 'application/x-www-form-urlencoded' ? ctx.request.body : ctx.query;

    const { message } = q;

    const lat = Number.parseFloat(q.lat);
    const lon = Number.parseFloat(q.lon);
    const altitude = q.alt === undefined ? null : Number.parseFloat(q.alt);
    const speed = q.speed === undefined ? null : Number.parseFloat(q.speed);
    const accuracy = q.acc === undefined ? null : Number.parseFloat(q.acc);
    const bearing = q.bearing === undefined ? null : Number.parseFloat(q.bearing);
    const battery = q.battery === undefined ? null : Number.parseFloat(q.battery);
    const gsmSignal = q.gsm_signal === undefined ? null : Number.parseFloat(q.gsm_signal);
    const time = guessTime(q.time);

    if (time === null
        || Number.isNaN(lat) || lat < -90 || lat > 90 || Number.isNaN(lon) || lon < -180 || lon > 180
        || Number.isNaN(battery) || battery !== null && (battery < 0 || battery > 100)
        || Number.isNaN(gsmSignal) || gsmSignal !== null && (gsmSignal < 0 || gsmSignal > 100)
        || Number.isNaN(bearing) || bearing !== null && (bearing < 0 || bearing > 360)
        || Number.isNaN(accuracy) || accuracy !== null && accuracy < 0
        || Number.isNaN(speed) || speed !== null && speed < 0
    ) {
      ctx.status = 400;
      return;
    }

    const now = new Date();

    const { id, maxAge, maxCount } = item;

    const { insertId } = await ctx.state.db.query(
      `INSERT INTO trackingPoint (deviceId, lat, lon, altitude, speed, accuracy, bearing, battery, gsmSignal, message, createdAt)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [id, lat, lon, altitude, speed, accuracy, bearing, battery, gsmSignal, message, time],
    );

    if (maxAge) {
      await ctx.state.db.query(
        'DELETE FROM trackingPoint WHERE deviceId = ? AND TIMESTAMPDIFF(SECOND, createdAt, now()) > ?',
        [id, maxAge],
      );
    }

    if (maxCount) {
      await ctx.state.db.query(
        'DELETE t FROM trackingPoint AS t JOIN (SELECT id FROM trackingPoint WHERE deviceId = ? ORDER BY id DESC LIMIT 18446744073709551615 OFFSET ?) tlimit ON t.id = tlimit.id',
        [id, maxCount + 1],
      );
    }

    const rows = await ctx.state.db.query(
      'SELECT token FROM trackingAccessToken WHERE deviceId = ? AND (timeFrom IS NULL OR timeFrom > ?) AND (timeTo IS NULL OR timeTo < ?)',
      [id, now, now],
    );

    const notify = (type, key) => {
      const websockets = trackRegister.get(key);
      if (websockets) {
        for (const ws of websockets) {
          if (ws.readyState === 1) {
            ws.send(JSON.stringify({
              jsonrpc: '2.0',
              method: 'tracking.addPoint',
              params: {
                // TODO validate if time matches limits
                id: insertId, lat, lon, altitude, speed, accuracy, bearing, battery, gsmSignal, message, [type]: key, ts: time.toISOString(),
              },
            }));
          }
        }
      }
    };

    for (const { token } of rows) {
      notify('token', token);
    }
    notify('deviceId', id);

    ctx.body = { id: insertId };
  }
}

function guessTime(t) {
  const now = new Date();
  const min = new Date();
  min.setMonth(min.getMonth() - 1);
  const max = new Date();
  max.setDate(min.getDate() + 1);

  if (!t) {
    return now;
  }

  const d1 = new Date(t);
  if (max > d1 && d1 > min) {
    return d1;
  }

  const n = Number.parseInt(t, 10);
  if (Number.isNaN(n)) {
    return null;
  }

  const d2 = new Date(n);

  if (max > d2 && d2 > min) {
    return d2;
  }

  const d3 = new Date(n * 1000);
  if (max > d3 && d3 > min) {
    return d3;
  }

  return null;
}
<|endoftext|>


<commit_before>(function(){
  angular.module('ncsaas')
    .service('baseControllerClass', ['$rootScope', 'Flash', baseControllerClass]);

  function baseControllerClass($rootScope, Flash) {
    var ControllerClass = Class.extend({
      _signals: {},

      init:function() {
        this.registerEventHandlers();
      },
      setSignalHandler: function(signalName, handlerFunction) {
        this._signals[signalName] = handlerFunction;
      },
      registerEventHandlers: function() {
        for (var eventName in this._signals) {
          $rootScope.$on(eventName, this._signals[eventName]);
        }
      },
      successFlash: function(message) {
        this.flashMessage('success', message);
      },
      flashMessage: function(type, message) {
        Flash.create(type, message);
      }
    });

    return ControllerClass;
  }
})();

(function(){

  angular.module('ncsaas')
    .service('baseControllerListClass', ['baseControllerClass', baseControllerListClass]);

  function baseControllerListClass(baseControllerClass) {
    /**
     * Use controllerScope.__proto__ = new Controller() in needed controller
     * use this.controllerScope for changes in event handler
     * sеt events in this.setSignalHandler('eventName', this.eventFunction);
     */
    var ControllerListClass = baseControllerClass.extend({
      list: {},
      service: null, // required in init
      searchInput: '',
      searchFieldName: '', // required in init
      controllerScope: null, // required in init
      showgroup: false, // for showing group buttons and checkboxes in list view

      init:function() {
        this.setSignalHandler('currentCustomerUpdated', this.currentCustomerUpdatedHandler.bind(this));
        this._super();
        this.getList();
      },
      getList:function(filter) {
        var vm = this;
        filter = filter || {};
        vm.service.getList(filter).then(function(response) {
          vm.list = response;
        });
      },
      search:function() {
        var vm = this;
        var filter = {};
        filter[vm.searchFieldName] = vm.searchInput;
        this.getList(filter);
      },
      remove:function(model) {
        var vm = this;
        var index = vm.list.indexOf(model);
        var confirmDelete = confirm('Confirm deletion?');
        if (confirmDelete) {
          model.$delete(function() {
            vm.list.splice(index, 1);
          }, vm.handleActionException);
        } else {
          alert('Was not deleted.');
        }
      },
      handleActionException: function(response) {
        if (response.status === 409) {
          var message = response.data.status || response.data.detail;
          alert(message);
        }
      },
      currentCustomerUpdatedHandler: function() {
        var vm = this.controllerScope;
        vm.service.page = 1;
        vm.getList();
      }
    });

    return ControllerListClass;
  }

})();

(function(){

  angular.module('ncsaas')
    .service('baseControllerAddClass', ['$state', 'baseControllerClass', baseControllerAddClass]);

  function baseControllerAddClass($state, baseControllerClass) {
    /**
     * Use controllerScope.__proto__ = new Controller() in needed controller
     * use this.controllerScope for changes in event handler
     * sеt events in this._signals
     */
    var ControllerAddClass = baseControllerClass.extend({
      service: null, // required in init
      instance: null,
      listState: null, // required in init
      errors: {},
      controllerScope: null, // required in init
      detailsState: null,
      redirectToDetailsPage: false,
      successMessage: 'Saved successfully',

      init:function() {
        this.instance = this.service.$create();
        this.activate();
        this._super();
      },
      save:function() {
        var vm = this;
        vm.instance.$save(success, error);
        function success() {
          vm.afterSave();
          vm.successFlash(vm.successMessage);
          if (vm.redirectToDetailsPage) {
            $state.go(vm.detailsState, {uuid: vm.instance.uuid});
          } else {
            $state.go(vm.listState);
          }
        }
        function error(response) {
          vm.errors = response.data;
        }
      },
      cancel: function() {
        var vm = this;
        $state.go(vm.listState);
      },
      afterSave: function() {},
      activate: function() {}
    });

    return ControllerAddClass;
  }

})();

(function() {
  angular.module('ncsaas')
    .service('baseControllerDetailUpdateClass', ['$state', 'baseControllerClass', '$stateParams', baseControllerDetailUpdateClass]);

  function baseControllerDetailUpdateClass($state, baseControllerClass, $stateParams) {
    /**
     * Use controllerScope.__proto__ = new Controller() in needed controller
     * use this.controllerScope for changes in event handler
     * sеt events in this._signals
     */
    var ControllerDetailUpdateClass = baseControllerClass.extend({
      service: null, // required in init
      detailsState: null, // required in init
      listState: null, // required in init for details page
      activeTab: null,
      model: null,

      init:function() {
        this._super();
        this.activate();
      },
      update:function() {
        var vm = this;
        vm.model.$update(success, error);
        function success() {
          vm.afterUpdate();
          $state.go(vm.detailsState, {uuid: vm.model.uuid});
        }
        function error(response) {
          vm.errors = response.data;
        }
      },
      activate:function() {
        var vm = this;
        vm.service.$get($stateParams.uuid).then(function(response) {
          vm.model = response;
        });
      },
      remove:function() {
        var vm = this;
        if (confirm('Confirm deletion?')) {
          vm.model.$delete(
            function() {
              $state.go(vm.listState);
            },
            function(errors) {
              alert(errors.data.detail);
            }
          );
        }
      },
      afterUpdate:function() {}
    });

    return ControllerDetailUpdateClass;
  }
})();<commit_msg>Better wording for a success message<commit_after>(function(){
  angular.module('ncsaas')
    .service('baseControllerClass', ['$rootScope', 'Flash', baseControllerClass]);

  function baseControllerClass($rootScope, Flash) {
    var ControllerClass = Class.extend({
      _signals: {},

      init:function() {
        this.registerEventHandlers();
      },
      setSignalHandler: function(signalName, handlerFunction) {
        this._signals[signalName] = handlerFunction;
      },
      registerEventHandlers: function() {
        for (var eventName in this._signals) {
          $rootScope.$on(eventName, this._signals[eventName]);
        }
      },
      successFlash: function(message) {
        this.flashMessage('success', message);
      },
      flashMessage: function(type, message) {
        Flash.create(type, message);
      }
    });

    return ControllerClass;
  }
})();

(function(){

  angular.module('ncsaas')
    .service('baseControllerListClass', ['baseControllerClass', baseControllerListClass]);

  function baseControllerListClass(baseControllerClass) {
    /**
     * Use controllerScope.__proto__ = new Controller() in needed controller
     * use this.controllerScope for changes in event handler
     * sеt events in this.setSignalHandler('eventName', this.eventFunction);
     */
    var ControllerListClass = baseControllerClass.extend({
      list: {},
      service: null, // required in init
      searchInput: '',
      searchFieldName: '', // required in init
      controllerScope: null, // required in init
      showgroup: false, // for showing group buttons and checkboxes in list view

      init:function() {
        this.setSignalHandler('currentCustomerUpdated', this.currentCustomerUpdatedHandler.bind(this));
        this._super();
        this.getList();
      },
      getList:function(filter) {
        var vm = this;
        filter = filter || {};
        vm.service.getList(filter).then(function(response) {
          vm.list = response;
        });
      },
      search:function() {
        var vm = this;
        var filter = {};
        filter[vm.searchFieldName] = vm.searchInput;
        this.getList(filter);
      },
      remove:function(model) {
        var vm = this;
        var index = vm.list.indexOf(model);
        var confirmDelete = confirm('Confirm deletion?');
        if (confirmDelete) {
          model.$delete(function() {
            vm.list.splice(index, 1);
          }, vm.handleActionException);
        } else {
          alert('Was not deleted.');
        }
      },
      handleActionException: function(response) {
        if (response.status === 409) {
          var message = response.data.status || response.data.detail;
          alert(message);
        }
      },
      currentCustomerUpdatedHandler: function() {
        var vm = this.controllerScope;
        vm.service.page = 1;
        vm.getList();
      }
    });

    return ControllerListClass;
  }

})();

(function(){

  angular.module('ncsaas')
    .service('baseControllerAddClass', ['$state', 'baseControllerClass', baseControllerAddClass]);

  function baseControllerAddClass($state, baseControllerClass) {
    /**
     * Use controllerScope.__proto__ = new Controller() in needed controller
     * use this.controllerScope for changes in event handler
     * sеt events in this._signals
     */
    var ControllerAddClass = baseControllerClass.extend({
      service: null, // required in init
      instance: null,
      listState: null, // required in init
      errors: {},
      controllerScope: null, // required in init
      detailsState: null,
      redirectToDetailsPage: false,
      successMessage: 'Saving succeeded.',

      init:function() {
        this.instance = this.service.$create();
        this.activate();
        this._super();
      },
      save:function() {
        var vm = this;
        vm.instance.$save(success, error);
        function success() {
          vm.afterSave();
          vm.successFlash(vm.successMessage);
          if (vm.redirectToDetailsPage) {
            $state.go(vm.detailsState, {uuid: vm.instance.uuid});
          } else {
            $state.go(vm.listState);
          }
        }
        function error(response) {
          vm.errors = response.data;
        }
      },
      cancel: function() {
        var vm = this;
        $state.go(vm.listState);
      },
      afterSave: function() {},
      activate: function() {}
    });

    return ControllerAddClass;
  }

})();

(function() {
  angular.module('ncsaas')
    .service('baseControllerDetailUpdateClass', ['$state', 'baseControllerClass', '$stateParams', baseControllerDetailUpdateClass]);

  function baseControllerDetailUpdateClass($state, baseControllerClass, $stateParams) {
    /**
     * Use controllerScope.__proto__ = new Controller() in needed controller
     * use this.controllerScope for changes in event handler
     * sеt events in this._signals
     */
    var ControllerDetailUpdateClass = baseControllerClass.extend({
      service: null, // required in init
      detailsState: null, // required in init
      listState: null, // required in init for details page
      activeTab: null,
      model: null,

      init:function() {
        this._super();
        this.activate();
      },
      update:function() {
        var vm = this;
        vm.model.$update(success, error);
        function success() {
          vm.afterUpdate();
          $state.go(vm.detailsState, {uuid: vm.model.uuid});
        }
        function error(response) {
          vm.errors = response.data;
        }
      },
      activate:function() {
        var vm = this;
        vm.service.$get($stateParams.uuid).then(function(response) {
          vm.model = response;
        });
      },
      remove:function() {
        var vm = this;
        if (confirm('Confirm deletion?')) {
          vm.model.$delete(
            function() {
              $state.go(vm.listState);
            },
            function(errors) {
              alert(errors.data.detail);
            }
          );
        }
      },
      afterUpdate:function() {}
    });

    return ControllerDetailUpdateClass;
  }
})();<|endoftext|>


<commit_before>/*#ifndef(UMD)*/
"use strict";
/*global _gpfEmptyFunc*/ // An empty function
/*global _gpfFunc*/ // Create a new function using the source
/*global _gpfMainContext*/ // Main context object
/*global _gpfStringEscapeFor*/ // Make the string content compatible with lang
/*exported _gpfJsonParse*/
/*exported _gpfJsonStringify*/
/*#endif*/

var
    /**
     * The JSON.stringify() method converts a JavaScript value to a JSON string
     *
     * @param {*} value the value to convert to a JSON string
     * @return {String}
     */
    _gpfJsonStringify,

    /**
     * The JSON.parse() method parses a string as JSON
     *
     * @param {*} text The string to parse as JSON
     * @return {Object}
     */
    _gpfJsonParse;

function _gpfObject2Json (object) {
    var
        isArray,
        results,
        property,
        value;
    isArray = object instanceof Array;
    results = [];
    /*jshint -W089*/ // Actually, I want all properties
    for (property in object) {
        if ("function" === typeof object[property]) {
            continue; // ignore
        }
        value = _gpfJsonStringify(object[property]);
        if (isArray) {
            results.push(value);
        } else {
            results.push(_gpfStringEscapeFor(property, "javascript") + ":" + value);
        }
    }
    if (isArray) {
        return "[" + results.join(",") + "]";
    }
    return "{" + results.join(",") + "}";
    /*jshint +W089*/
}

function _gpfJsonStringifyObject (object) {
    return object.toString();
}

if ("undefined" === typeof JSON) {

    var _gpfJsonStringifyMapping = {
        undefined: _gpfEmptyFunc,
        "function": _gpfEmptyFunc,
        number: _gpfJsonStringifyObject,
        "boolean": _gpfJsonStringifyObject,
        string: function (object) {
            return _gpfStringEscapeFor(object, "javascript");
        }
    };

    _gpfJsonStringify = function (object) {
        var mapper = _gpfJsonStringifyMapping[typeof object];
        if (undefined !== mapper) {
            return mapper(object);
        }
        if (null === object) {
            return "null";
        }
        return _gpfObject2Json(object);
    };

    _gpfJsonParse = function (test) {
        return _gpfFunc("return " + test)();
    };

    // Creates the JSON global object
    _gpfMainContext.JSON = {
        stringify: _gpfJsonStringify,
        parse: _gpfJsonParse
    };

} else {

    _gpfJsonStringify = JSON.stringify;
    _gpfJsonParse = JSON.parse;

}
<commit_msg>Exposed internals for testing<commit_after>/*#ifndef(UMD)*/
"use strict";
/*global _gpfEmptyFunc*/ // An empty function
/*global _gpfFunc*/ // Create a new function using the source
/*global _gpfMainContext*/ // Main context object
/*global _gpfStringEscapeFor*/ // Make the string content compatible with lang
/*exported _gpfJsonParse*/
/*exported _gpfJsonStringify*/
/*#endif*/

var
    /**
     * The JSON.stringify() method converts a JavaScript value to a JSON string
     *
     * @param {*} value the value to convert to a JSON string
     * @return {String}
     */
    _gpfJsonStringify,

    /**
     * The JSON.parse() method parses a string as JSON
     *
     * @param {*} text The string to parse as JSON
     * @return {Object}
     */
    _gpfJsonParse;

function _gpfObject2Json (object) {
    var
        isArray,
        results,
        property,
        value;
    isArray = object instanceof Array;
    results = [];
    /*jshint -W089*/ // Actually, I want all properties
    for (property in object) {
        if ("function" === typeof object[property]) {
            continue; // ignore
        }
        value = _gpfJsonStringify(object[property]);
        if (isArray) {
            results.push(value);
        } else {
            results.push(_gpfStringEscapeFor(property, "javascript") + ":" + value);
        }
    }
    if (isArray) {
        return "[" + results.join(",") + "]";
    }
    return "{" + results.join(",") + "}";
    /*jshint +W089*/
}

function _gpfJsonStringifyObject (object) {
    return object.toString();
}

var _gpfJsonStringifyMapping = {
    undefined: _gpfEmptyFunc,
    "function": _gpfEmptyFunc,
    number: _gpfJsonStringifyObject,
    "boolean": _gpfJsonStringifyObject,
    string: function (object) {
        return _gpfStringEscapeFor(object, "javascript");
    }
};

function _gpfJsonStringifyPolyfill (object) {
    var mapper = _gpfJsonStringifyMapping[typeof object];
    if (undefined !== mapper) {
        return mapper(object);
    }
    if (null === object) {
        return "null";
    }
    return _gpfObject2Json(object);
}

function _gpfJsonParsePolyfill (test) {
    return _gpfFunc("return " + test)();
}

// Used only for environments where JSON is not defined
/* istanbul ignore next */
if ("undefined" === typeof JSON) {

    _gpfJsonStringify = _gpfJsonStringifyPolyfill;
    _gpfJsonParse = _gpfJsonParsePolyfill;

    // Creates the JSON global object
    _gpfMainContext.JSON = {
        stringify: _gpfJsonStringify,
        parse: _gpfJsonParse
    };

} else {

    _gpfJsonStringify = JSON.stringify;
    _gpfJsonParse = JSON.parse;

}

/*#ifndef(UMD)*/

gpf.internals._gpfJsonStringifyPolyfill = _gpfJsonStringifyPolyfill;
gpf.internals._gpfJsonParsePolyfill = _gpfJsonParsePolyfill;

/*#endif*/
<|endoftext|>


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

import AppActionCreator from '../../intent/action/AppActionCreator';
import CommandTypeMod from '../../model/CommandType';
import MessageActionCreator from '../../intent/action/MessageActionCreator';
import {Some, None} from 'option-t';
import UIActionCreator from '../../intent/action/UIActionCreator';

const CommandType = CommandTypeMod.type;

export default class SidebarViewController {

    /**
     *  @constructor
     *  @param  {DomainState}   domain
     *  @param  {Element}   element
     */
    constructor(domain, element) {
        if (!element) {
            throw new Error();
        }

        /** @type   {Element}   */
        this._element = element;

        /** @type   {DomainState}   */
        this.domain = domain;

        /*eslint-disable valid-jsdoc */
        /** @type   {Rx.IDisposable}  */
        this._disposeSignout = AppActionCreator.getDispatcher().signout.subscribe(() => {
            this.clearAllNetworks();
            this.showEmptinesse();
        });

        /** @type   {Rx.IDisposable}  */
        this._disposeRenderNetworks = AppActionCreator.getDispatcher().renderNetworksInView.subscribe((networks) => {
            this.hideEmptinesse();
            this.renderNetworks(networks);
        });

        /** @type   {Rx.IDisposable}  */
        this._disposeSelectChannel = UIActionCreator.getDispatcher().selectChannel.subscribe((channelId) => {
            this.selectChannel(channelId);
        });

        /** @type   {Rx.IDisposable}  */
        this._disposeAddedNetwork = domain.networkSet.addedStream().subscribe((network) => {
            this.addNetwork(network);
        });

        /** @type   {Rx.IDisposable}  */
        this._disposeDeletedNetwork = domain.networkSet.deletedStream().subscribe((network) => {
            this.deleteNetwork(network);
        });

        /** @type   {Rx.Observable<number>}    */
        this._obsJoinChannel = MessageActionCreator.getDispatcher().joinChannel.map((data) => {
            return this.joinChannel(data.networkId, data.channel);
        }).filter(function(id){
            return id.isSome;
        }).map(function(id){
            return id.unwrap();
        });
        /*eslint-enable */

        element.addEventListener('click', this);
    }

    /**
     *  @return {number}
     */
    get joinnedChannel() {
        return this._obsJoinChannel;
    }

    /**
     *  @param  {Event} aEvent
     *  @return {void}
     */
    handleEvent(aEvent) {
        switch (aEvent.type) {
            case 'click':
                this.onClick(aEvent);
        }
    }

    /**
     *  @param  {Event} aEvent
     *  @return {void}
     */
    onClick(aEvent) {
        const target = aEvent.target;
        if (!target.matches('.js-sidebar-channel, .js-sidebar-channel > *')) {
            return;
        }

        // This is very heuristic way.
        let button = target;
        if (!target.classList.contains('js-sidebar-channel')) {
            button = target.parentNode;
        }

        const channelId = parseInt(button.getAttribute('data-id'), 10);

        const isCloseButton = target.classList.contains('close');
        if (isCloseButton) {
            this.closeChannel(channelId, button);
        }
        else {
            UIActionCreator.selectChannel(channelId);
        }
    }

    /**
     *  @param  {number}    networkId
     *  @param  {Channel}   channel
     *  @return {!OptionT<number>}
     *      the id which should be selected channel.
     */
    joinChannel(networkId, channel) {
        const network = this._element.querySelector('#network-' + String(networkId));
        if (!network) {
            return new None();
        }

        this.appendChannel(network, channel);

        // FIXME:
        const channels = this._element.querySelectorAll('.chan:not(.query)');
        const $target = $(channels).sort(function(a, b) {
            return $(a).data('id') - $(b).data('id');
        }).last();

        const targetId = $target.get(0).getAttribute('data-id');
        const id = parseInt(targetId, 10);
        return new Some(id);
    }

    /**
     *  @param  {number}    channelId
     *  @param  {Element}   target
     *  @return {void}
     */
    closeChannel(channelId, target) {
        const channelWrap = this.domain.networkSet.getChannelById(channelId);
        if (channelWrap.isNone) {
            return;
        }

        const channel = channelWrap.unwrap();
        const channelType = channel.type;
        const isLobby = (channelType === 'lobby');
        const command = isLobby ? CommandType.QUIT : CommandType.CLOSE;
        if (isLobby) {
            /*eslint-disable no-alert*/
            if (!window.confirm('Disconnect from ' + channel.name + '?')) {
                return;
            }
            /*eslint-enable*/
        }
        MessageActionCreator.inputCommand(channelId, command);

        // FIXME: This visual state should be written in css.
        target.style.opacity = '0.4';
    }

    /**
     *  @return {void}
     */
    clearAllNetworks() {
        let element = this._element.querySelector('.networks');
        element.innerHTML = '';
    }

    /**
     *  @param  {Network}   network
     *  @return {void}
     */
    addNetwork(network) {
        this.hideEmptinesse();
        this.appendNetworks([network]);

        const channelList = network.getChannelList();
        const lastId = channelList[channelList.length - 1].id;
        UIActionCreator.selectChannel(lastId);
    }

    /**
     *  @param  {Network}   network
     *  @return {void}
     */
    deleteNetwork(network) {
        const id = network.id;
        const target = this._element.querySelector('#network-' + String(id));
        if (!!target) {
            target.parentNode.removeChild(target);
        }

        const newTarget = this._element.querySelector('.chan');
        if (!newTarget) {
            this.showEmptinesse();
        }
        else {
            const newId = newTarget.getAttribute('data-id');
            UIActionCreator.selectChannel( parseInt(newId, 10) );
        }
    }

    /**
     *  @return {void}
     */
    showEmptinesse() {
        let element = this._element.querySelector('.empty');
        element.style.display = 'block';
    }

    /**
     *  @return {void}
     */
    hideEmptinesse() {
        let element = this._element.querySelector('.empty');
        element.style.display = 'none';
    }

    /**
     *  @param  {Array<Network>} networks
     *  @return {void}
     */
    renderNetworks(networks) {
        const element = this._element.querySelector('.networks');
        const html = Handlebars.templates.network({
            networks,
        });

        element.innerHTML = html;
    }

    /**
     *  @param  {Array<Network>} networks
     *  @return {void}
     */
    appendNetworks(networks) {
        const element = this._element.querySelector('.networks');
        const html = Handlebars.templates.network({
            networks,
        });

        element.innerHTML = element.innerHTML + html;
    }

    /**
     *  @param  {Element}   network
     *  @param  {Channel}   channel
     *  @return {void}
     */
    appendChannel(network, channel) {
        const html = Handlebars.templates.chan({
            channels: [channel]
        });

        network.innerHTML = network.innerHTML + html;
    }

    /**
     *  @param  {number}    id
     *  @return {void}
     */
    selectChannel(id) {
        const active = this._element.querySelector('.active');
        if (!!active) {
            active.classList.remove('active');
        }

        const selector = '.js-sidebar-channel[data-id="' + String(id) + '"]';
        const target = this._element.querySelector(selector);
        if (!target) {
            return;
        }

        target.classList.add('active');

        const badge = target.querySelector('.badge');
        if (!!badge) {
            badge.classList.remove('highlight');
            // FIXME:
            $(badge).data('count', '');
            badge.textContent = '';
        }
    }
}
<commit_msg>Return Rx.Observable to clean up the signiture.<commit_after>/*global Handlebars:true, $: true */
/**
 * @license MIT License
 *
 * Copyright (c) 2015 Tetsuharu OHZEKI <saneyuki.snyk@gmail.com>
 * Copyright (c) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

import AppActionCreator from '../../intent/action/AppActionCreator';
import CommandTypeMod from '../../model/CommandType';
import MessageActionCreator from '../../intent/action/MessageActionCreator';
import Rx from 'rx';
import UIActionCreator from '../../intent/action/UIActionCreator';

const CommandType = CommandTypeMod.type;

export default class SidebarViewController {

    /**
     *  @constructor
     *  @param  {DomainState}   domain
     *  @param  {Element}   element
     */
    constructor(domain, element) {
        if (!element) {
            throw new Error();
        }

        /** @type   {Element}   */
        this._element = element;

        /** @type   {DomainState}   */
        this.domain = domain;

        /*eslint-disable valid-jsdoc */
        /** @type   {Rx.IDisposable}  */
        this._disposeSignout = AppActionCreator.getDispatcher().signout.subscribe(() => {
            this.clearAllNetworks();
            this.showEmptinesse();
        });

        /** @type   {Rx.IDisposable}  */
        this._disposeRenderNetworks = AppActionCreator.getDispatcher().renderNetworksInView.subscribe((networks) => {
            this.hideEmptinesse();
            this.renderNetworks(networks);
        });

        /** @type   {Rx.IDisposable}  */
        this._disposeSelectChannel = UIActionCreator.getDispatcher().selectChannel.subscribe((channelId) => {
            this.selectChannel(channelId);
        });

        /** @type   {Rx.IDisposable}  */
        this._disposeAddedNetwork = domain.networkSet.addedStream().subscribe((network) => {
            this.addNetwork(network);
        });

        /** @type   {Rx.IDisposable}  */
        this._disposeDeletedNetwork = domain.networkSet.deletedStream().subscribe((network) => {
            this.deleteNetwork(network);
        });

        /** @type   {Rx.Observable<number>}    */
        this._obsJoinChannel = MessageActionCreator.getDispatcher().joinChannel.flatMap((data) => {
            return this.joinChannel(data.networkId, data.channel);
        });
        /*eslint-enable */

        element.addEventListener('click', this);
    }

    /**
     *  @return {number}
     */
    get joinnedChannel() {
        return this._obsJoinChannel;
    }

    /**
     *  @param  {Event} aEvent
     *  @return {void}
     */
    handleEvent(aEvent) {
        switch (aEvent.type) {
            case 'click':
                this.onClick(aEvent);
        }
    }

    /**
     *  @param  {Event} aEvent
     *  @return {void}
     */
    onClick(aEvent) {
        const target = aEvent.target;
        if (!target.matches('.js-sidebar-channel, .js-sidebar-channel > *')) {
            return;
        }

        // This is very heuristic way.
        let button = target;
        if (!target.classList.contains('js-sidebar-channel')) {
            button = target.parentNode;
        }

        const channelId = parseInt(button.getAttribute('data-id'), 10);

        const isCloseButton = target.classList.contains('close');
        if (isCloseButton) {
            this.closeChannel(channelId, button);
        }
        else {
            UIActionCreator.selectChannel(channelId);
        }
    }

    /**
     *  @param  {number}    networkId
     *  @param  {Channel}   channel
     *  @return {!Rx.Observable<number>}
     *      the id which should be selected channel.
     */
    joinChannel(networkId, channel) {
        const network = this._element.querySelector('#network-' + String(networkId));
        if (!network) {
            return Rx.Observable.throw();
        }

        this.appendChannel(network, channel);

        // FIXME:
        const channels = this._element.querySelectorAll('.chan:not(.query)');
        const $target = $(channels).sort(function(a, b) {
            return $(a).data('id') - $(b).data('id');
        }).last();

        const targetId = $target.get(0).getAttribute('data-id');
        const id = parseInt(targetId, 10);
        return Rx.Observable.just(id);
    }

    /**
     *  @param  {number}    channelId
     *  @param  {Element}   target
     *  @return {void}
     */
    closeChannel(channelId, target) {
        const channelWrap = this.domain.networkSet.getChannelById(channelId);
        if (channelWrap.isNone) {
            return;
        }

        const channel = channelWrap.unwrap();
        const channelType = channel.type;
        const isLobby = (channelType === 'lobby');
        const command = isLobby ? CommandType.QUIT : CommandType.CLOSE;
        if (isLobby) {
            /*eslint-disable no-alert*/
            if (!window.confirm('Disconnect from ' + channel.name + '?')) {
                return;
            }
            /*eslint-enable*/
        }
        MessageActionCreator.inputCommand(channelId, command);

        // FIXME: This visual state should be written in css.
        target.style.opacity = '0.4';
    }

    /**
     *  @return {void}
     */
    clearAllNetworks() {
        let element = this._element.querySelector('.networks');
        element.innerHTML = '';
    }

    /**
     *  @param  {Network}   network
     *  @return {void}
     */
    addNetwork(network) {
        this.hideEmptinesse();
        this.appendNetworks([network]);

        const channelList = network.getChannelList();
        const lastId = channelList[channelList.length - 1].id;
        UIActionCreator.selectChannel(lastId);
    }

    /**
     *  @param  {Network}   network
     *  @return {void}
     */
    deleteNetwork(network) {
        const id = network.id;
        const target = this._element.querySelector('#network-' + String(id));
        if (!!target) {
            target.parentNode.removeChild(target);
        }

        const newTarget = this._element.querySelector('.chan');
        if (!newTarget) {
            this.showEmptinesse();
        }
        else {
            const newId = newTarget.getAttribute('data-id');
            UIActionCreator.selectChannel( parseInt(newId, 10) );
        }
    }

    /**
     *  @return {void}
     */
    showEmptinesse() {
        let element = this._element.querySelector('.empty');
        element.style.display = 'block';
    }

    /**
     *  @return {void}
     */
    hideEmptinesse() {
        let element = this._element.querySelector('.empty');
        element.style.display = 'none';
    }

    /**
     *  @param  {Array<Network>} networks
     *  @return {void}
     */
    renderNetworks(networks) {
        const element = this._element.querySelector('.networks');
        const html = Handlebars.templates.network({
            networks,
        });

        element.innerHTML = html;
    }

    /**
     *  @param  {Array<Network>} networks
     *  @return {void}
     */
    appendNetworks(networks) {
        const element = this._element.querySelector('.networks');
        const html = Handlebars.templates.network({
            networks,
        });

        element.innerHTML = element.innerHTML + html;
    }

    /**
     *  @param  {Element}   network
     *  @param  {Channel}   channel
     *  @return {void}
     */
    appendChannel(network, channel) {
        const html = Handlebars.templates.chan({
            channels: [channel]
        });

        network.innerHTML = network.innerHTML + html;
    }

    /**
     *  @param  {number}    id
     *  @return {void}
     */
    selectChannel(id) {
        const active = this._element.querySelector('.active');
        if (!!active) {
            active.classList.remove('active');
        }

        const selector = '.js-sidebar-channel[data-id="' + String(id) + '"]';
        const target = this._element.querySelector(selector);
        if (!target) {
            return;
        }

        target.classList.add('active');

        const badge = target.querySelector('.badge');
        if (!!badge) {
            badge.classList.remove('highlight');
            // FIXME:
            $(badge).data('count', '');
            badge.textContent = '';
        }
    }
}
<|endoftext|>


<commit_before>import { computed } from "ember-metal/computed";
import run from "ember-metal/run_loop";
import jQuery from "ember-views/system/jquery";
import EmberView from "ember-views/views/view";
import { compile } from "ember-template-compiler";

var view;

QUnit.module("Ember.View", {
  teardown() {
    run(function() {
      view.destroy();
    });
  }
});

QUnit.test("should add ember-view to views", function() {
  view = EmberView.create();

  run(function() {
    view.createElement();
  });

  ok(view.$().hasClass('ember-view'), "the view has ember-view");
});

QUnit.test("should not add role attribute unless one is specified", function() {
  view = EmberView.create();

  run(function() {
    view.createElement();
  });

  ok(view.$().attr('role') === undefined, "does not have a role attribute");
});

QUnit.test("should allow tagName to be a computed property [DEPRECATED]", function() {
  view = EmberView.extend({
    tagName: computed(function() {
      return 'span';
    })
  }).create();

  expectDeprecation(function() {
    run(function() {
      view.createElement();
    });
  }, /using a computed property to define tagName will not be permitted/);

  equal(view.element.tagName, 'SPAN', "the view has was created with the correct element");

  run(function() {
    view.set('tagName', 'div');
  });

  equal(view.element.tagName, 'SPAN', "the tagName cannot be changed after initial render");
});

QUnit.test("should re-render if the context is changed", function() {
  view = EmberView.create({
    elementId: 'template-context-test',
    context: { foo: "bar" },
    template: compile("{{foo}}")
  });

  run(function() {
    view.appendTo('#qunit-fixture');
  });

  equal(jQuery('#qunit-fixture #template-context-test').text(), "bar", "precond - renders the view with the initial value");

  run(function() {
    view.set('context', {
      foo: "bang baz"
    });
  });

  equal(jQuery('#qunit-fixture #template-context-test').text(), "bang baz", "re-renders the view with the updated context");
});

QUnit.test("renders a contained view with omitted start tag and tagless parent view context", function() {
  view = EmberView.createWithMixins({
    tagName: 'table',
    template: compile("{{view view.pivot}}"),
    pivot: EmberView.extend({
      tagName: '',
      template: compile("{{view view.row}}"),
      row: EmberView.extend({
        tagName: 'tr'
      })
    })
  });

  run(view, view.append);

  equal(view.element.tagName, 'TABLE', 'container view is table');
  ok(view.$('tr').length, 'inner view is tr');

  run(view, view.rerender);

  equal(view.element.tagName, 'TABLE', 'container view is table');
  ok(view.$('tr').length, 'inner view is tr');
});
<commit_msg>Skipped test for values propagating upstream via templates<commit_after>import { computed } from "ember-metal/computed";
import run from "ember-metal/run_loop";
import jQuery from "ember-views/system/jquery";
import EmberView from "ember-views/views/view";
import { compile } from "ember-template-compiler";

var view;

QUnit.module("Ember.View", {
  teardown() {
    run(function() {
      view.destroy();
    });
  }
});

QUnit.test("should add ember-view to views", function() {
  view = EmberView.create();

  run(function() {
    view.createElement();
  });

  ok(view.$().hasClass('ember-view'), "the view has ember-view");
});

QUnit.test("should not add role attribute unless one is specified", function() {
  view = EmberView.create();

  run(function() {
    view.createElement();
  });

  ok(view.$().attr('role') === undefined, "does not have a role attribute");
});

QUnit.test("should allow tagName to be a computed property [DEPRECATED]", function() {
  view = EmberView.extend({
    tagName: computed(function() {
      return 'span';
    })
  }).create();

  expectDeprecation(function() {
    run(function() {
      view.createElement();
    });
  }, /using a computed property to define tagName will not be permitted/);

  equal(view.element.tagName, 'SPAN', "the view has was created with the correct element");

  run(function() {
    view.set('tagName', 'div');
  });

  equal(view.element.tagName, 'SPAN', "the tagName cannot be changed after initial render");
});

QUnit.test("should re-render if the context is changed", function() {
  view = EmberView.create({
    elementId: 'template-context-test',
    context: { foo: "bar" },
    template: compile("{{foo}}")
  });

  run(function() {
    view.appendTo('#qunit-fixture');
  });

  equal(jQuery('#qunit-fixture #template-context-test').text(), "bar", "precond - renders the view with the initial value");

  run(function() {
    view.set('context', {
      foo: "bang baz"
    });
  });

  equal(jQuery('#qunit-fixture #template-context-test').text(), "bang baz", "re-renders the view with the updated context");
});

QUnit.test("renders a contained view with omitted start tag and tagless parent view context", function() {
  view = EmberView.createWithMixins({
    tagName: 'table',
    template: compile("{{view view.pivot}}"),
    pivot: EmberView.extend({
      tagName: '',
      template: compile("{{view view.row}}"),
      row: EmberView.extend({
        tagName: 'tr'
      })
    })
  });

  run(view, view.append);

  equal(view.element.tagName, 'TABLE', 'container view is table');
  ok(view.$('tr').length, 'inner view is tr');

  run(view, view.rerender);

  equal(view.element.tagName, 'TABLE', 'container view is table');
  ok(view.$('tr').length, 'inner view is tr');
});

QUnit.skip("propagates dependent-key invalidated bindings upstream", function() {
  view = EmberView.create({
    parentProp: 'parent-value',
    template: compile("{{view view.childView childProp=view.parentProp}}"),
    childView: EmberView.createWithMixins({
      template: compile("child template"),
      childProp: Ember.computed('dependencyProp', {
        get(key) {
          return this.get('dependencyProp');
        },
        set(key, value) {
          return this.get('dependencyProp');
        }
      }),
      dependencyProp: 'old-value'
    })
  });

  run(view, view.append);

  equal(view.get('parentProp'), 'parent-value', 'precond - parent value is there');
  var childView = view.get('childView');
  childView.set('dependencyProp', 'new-value');
  equal(childView.get('childProp'), 'new-value', 'pre-cond - new value is propagated to CP');
  equal(view.get('parentProp'), 'new-value', 'new value is propagated across template');
});
<|endoftext|>


<commit_before>(function() {
  'use strict';
  angular.module('civic.events.common')
    .directive('entityCommentForm', entityCommenntFormDirective)
    .controller('EntityCommentFormController', EntityCommentFormController)
    .filter('mentioHighlightEntity', mentioHighlightEntity);

  // @ngInject
  function entityCommenntFormDirective() {
    return {
      restrict: 'E',
      scope: {
        type: '@',
        entityModel: '='
      },
      controller: 'EntityCommentFormController',
      templateUrl: 'app/views/events/common/entityCommentForm.tpl.html'
    };
  }

  // @ngInject
  function EntityCommentFormController($scope,
                                       $stateParams,
                                       Security,
                                       CommentSuggestions,
                                       CommentPreview,
                                       _) {
    var vm = $scope.vm = {};
    vm.isAuthenticated = Security.isAuthenticated();
    vm.currentUser = Security.currentUser;
    vm.isEditor = Security.isEditor();

    vm.mode = 'edit';
    vm.previewLoading = false;
    vm.previewText = '';

    vm.commentMessage = '';

    vm.showMarkdownHelp = false;
    vm.showMacroHelp = false;

    vm.switchMode = function(mode) {
      if (mode === 'preview') {
        if (!_.isUndefined(vm.newComment.text) && vm.newComment.text.length >0) {
          vm.commentMessage = '';
          vm.mode = 'preview';
          vm.previewLoading = true;
          CommentPreview.getPreview(vm.newComment.text)
            .then(function(response) { // success
              vm.previewText = response.html;
              vm.previewLoading = false;
            }, function() { // failure
              vm.previewLoading = false;
              vm.commentMessage = 'Error loading preview.';
            });
        } else {
          vm.commentMessage = 'Please enter Markdown text to preview.';
        }
      } else {
        vm.mode = 'edit';
        vm.previewText = '';
        vm.commentMessage = '';
      }
    };

    vm.newComment = {
      title: '',
      text: ''
    };

    vm.newCommentFields = [
      {
        key: 'text',
        type: 'comment',
        ngModelElAttrs: {
          'msd-elastic': 'true',
          'mentio': '',
          'mentio-id': '"commentForm"'
        },
        controller: /* @ngInject */ function($scope, $filter) {
          $scope.searchUsers = function(term) {
            CommentSuggestions.getUserSuggestions(term).then(function(response) {
              $scope.users = response;
            });
          };

          $scope.getUser = function(user) {
            return '@' + user.display_name;
          };

          $scope.searchEntities = function(term) {
            CommentSuggestions.getEntitySuggestions(term).then(function(response) {
              $scope.entities = _.map(response, function(entity) {
                entity.display_type = $filter('keyToLabel')(entity.type).toUpperCase();
                return entity;
              });
            });
          };

          $scope.getEntity= function(entity) {
            var types = {
              gene: 'G',
              variant: 'V',
              variant_group: 'VG',
              evidence_item: 'EI'
            };
            console.log(entity);
            return '#' + types[entity.type] + entity.id;
          };

          $scope.typedTerm = '';
        },
        data: {
          users: [],
          entities: []
        },
        templateOptions: {
          label: 'Add Comment:',
          rows: 4,
          minimum_length: 3,
          value: vm.newComment.text,
          currentUser: vm.currentUser,
          required: false
        },
        validators: {
          length: {
            expression: function(viewValue, modelValue, scope) {
              var value = viewValue || modelValue;
              return value.length >= scope.to.minimum_length;
            },
            message: '"Comment must be at least " + to.minimum_length + " characters long to submit."'
          }
        }
      }
    ];

    vm.submit = function(comment, resetModel) {
      comment = _.merge(comment, $stateParams);
      $scope.entityModel.submitComment(comment).then(function () {
        console.log('comment submitted.');
        resetModel();
        vm.previewText = '';
        vm.commentMessage = '';
        vm.mode = 'edit';
      }, function() {
        vm.commentMessage = 'Error submitting comment.';
      });
    };

  }

  // version of ment.io's highlight filter which discards the entity token and colon from the query
  // in order to properly highlight matching strings to returned values
  function mentioHighlightEntity() {
    function escapeRegexp (queryToEscape) {
      return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
    }

    return function (matchItem, query, hightlightClass) {
      if (query) {
        if(_.includes(query, ':')) {
          if(_.includes(query, ':')) { query = query.split(':')[1].length > 0 ? _.drop(query.split(':'), 1)[0] : String(); }
        }
        var replaceText = hightlightClass ?
        '$&' :
          '$&';
        return ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), replaceText);
      } else {
        return matchItem;
      }
    };
  }

})();
<commit_msg>removed log statement<commit_after>(function() {
  'use strict';
  angular.module('civic.events.common')
    .directive('entityCommentForm', entityCommenntFormDirective)
    .controller('EntityCommentFormController', EntityCommentFormController)
    .filter('mentioHighlightEntity', mentioHighlightEntity);

  // @ngInject
  function entityCommenntFormDirective() {
    return {
      restrict: 'E',
      scope: {
        type: '@',
        entityModel: '='
      },
      controller: 'EntityCommentFormController',
      templateUrl: 'app/views/events/common/entityCommentForm.tpl.html'
    };
  }

  // @ngInject
  function EntityCommentFormController($scope,
                                       $stateParams,
                                       Security,
                                       CommentSuggestions,
                                       CommentPreview,
                                       _) {
    var vm = $scope.vm = {};
    vm.isAuthenticated = Security.isAuthenticated();
    vm.currentUser = Security.currentUser;
    vm.isEditor = Security.isEditor();

    vm.mode = 'edit';
    vm.previewLoading = false;
    vm.previewText = '';

    vm.commentMessage = '';

    vm.showMarkdownHelp = false;
    vm.showMacroHelp = false;

    vm.switchMode = function(mode) {
      if (mode === 'preview') {
        if (!_.isUndefined(vm.newComment.text) && vm.newComment.text.length >0) {
          vm.commentMessage = '';
          vm.mode = 'preview';
          vm.previewLoading = true;
          CommentPreview.getPreview(vm.newComment.text)
            .then(function(response) { // success
              vm.previewText = response.html;
              vm.previewLoading = false;
            }, function() { // failure
              vm.previewLoading = false;
              vm.commentMessage = 'Error loading preview.';
            });
        } else {
          vm.commentMessage = 'Please enter Markdown text to preview.';
        }
      } else {
        vm.mode = 'edit';
        vm.previewText = '';
        vm.commentMessage = '';
      }
    };

    vm.newComment = {
      title: '',
      text: ''
    };

    vm.newCommentFields = [
      {
        key: 'text',
        type: 'comment',
        ngModelElAttrs: {
          'msd-elastic': 'true',
          'mentio': '',
          'mentio-id': '"commentForm"'
        },
        controller: /* @ngInject */ function($scope, $filter) {
          $scope.searchUsers = function(term) {
            CommentSuggestions.getUserSuggestions(term).then(function(response) {
              $scope.users = response;
            });
          };

          $scope.getUser = function(user) {
            return '@' + user.display_name;
          };

          $scope.searchEntities = function(term) {
            CommentSuggestions.getEntitySuggestions(term).then(function(response) {
              $scope.entities = _.map(response, function(entity) {
                entity.display_type = $filter('keyToLabel')(entity.type).toUpperCase();
                return entity;
              });
            });
          };

          $scope.getEntity= function(entity) {
            var types = {
              gene: 'G',
              variant: 'V',
              variant_group: 'VG',
              evidence_item: 'EI'
            };
            return '#' + types[entity.type] + entity.id;
          };

          $scope.typedTerm = '';
        },
        data: {
          users: [],
          entities: []
        },
        templateOptions: {
          label: 'Add Comment:',
          rows: 4,
          minimum_length: 3,
          value: vm.newComment.text,
          currentUser: vm.currentUser,
          required: false
        },
        validators: {
          length: {
            expression: function(viewValue, modelValue, scope) {
              var value = viewValue || modelValue;
              return value.length >= scope.to.minimum_length;
            },
            message: '"Comment must be at least " + to.minimum_length + " characters long to submit."'
          }
        }
      }
    ];

    vm.submit = function(comment, resetModel) {
      comment = _.merge(comment, $stateParams);
      $scope.entityModel.submitComment(comment).then(function () {
        console.log('comment submitted.');
        resetModel();
        vm.previewText = '';
        vm.commentMessage = '';
        vm.mode = 'edit';
      }, function() {
        vm.commentMessage = 'Error submitting comment.';
      });
    };

  }

  // version of ment.io's highlight filter which discards the entity token and colon from the query
  // in order to properly highlight matching strings to returned values
  function mentioHighlightEntity() {
    function escapeRegexp (queryToEscape) {
      return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
    }

    return function (matchItem, query, hightlightClass) {
      if (query) {
        if(_.includes(query, ':')) {
          if(_.includes(query, ':')) { query = query.split(':')[1].length > 0 ? _.drop(query.split(':'), 1)[0] : String(); }
        }
        var replaceText = hightlightClass ?
        '$&' :
          '$&';
        return ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), replaceText);
      } else {
        return matchItem;
      }
    };
  }

})();
<|endoftext|>