<commit_before>/*
 *     Copyright (c) 2011-2015 CoNWeT Lab., Universidad Politécnica de Madrid
 *
 *     This file is part of Wirecloud Platform.
 *
 *     Wirecloud Platform is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU Affero General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 *
 *     Wirecloud is distributed in the hope that it will be useful, but WITHOUT
 *     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 *     License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Wirecloud Platform.  If not, see
 *     <http://www.gnu.org/licenses/>.
 *
 */

/*global StyledElements*/

(function () {

    "use strict";

    /**
     * Este componente permite crear un contenedor en el que añadir otros
     * componentes.
     *
     * @param options
     * @param events
     */
    var Container = function Container(options, events) {
        var defaultOptions = {
            'extending': false,
            'class': '',
            'useFullHeight': false
        };
        options = StyledElements.Utils.merge(defaultOptions, options);

        // Necesario para permitir herencia
        if (options.extending) {
            return;
        }

        StyledElements.StyledElement.call(this, events);

        this.useFullHeight = options.useFullHeight;
        this.wrapperElement = document.createElement("div");
        this.children = [];

        if (options.id) {
            this.wrapperElement.setAttribute("id", options.id);
        }

        this.wrapperElement.className = StyledElements.Utils.prependWord(options['class'], "container");
    };
    Container.prototype = new StyledElements.StyledElement();

    Container.prototype.appendChild = function appendChild(element, refElement) {
        if (element instanceof StyledElements.StyledElement) {
            element.insertInto(this.wrapperElement, refElement);
            this.children.push(element);

            return element;
        }

        if (typeof element === "string") {
            element = document.createTextNode(element);
        }

        if (refElement instanceof StyledElements.StyledElement) {
            refElement = refElement.wrapperElement;
        }

        if (refElement != null) {
            this.wrapperElement.insertBefore(element, refElement);
        } else {
            this.wrapperElement.appendChild(element);
        }

        return element;
    };

    Container.prototype.removeChild = function removeChild(element) {
        var index;

        if (element instanceof StyledElements.StyledElement) {
            index = this.children.indexOf(element);
            this.children.splice(index, 1);
            this.wrapperElement.removeChild(element.wrapperElement);
        } else {
            this.wrapperElement.removeChild(element);
        }

        return this;
    };

    Container.prototype.repaint = function repaint(temporal) {
        temporal = temporal !== undefined ? temporal : false;

        if (this.useFullHeight) {
            if (this.wrapperElement.classList.contains('hidden')) {
                this.wrapperElement.style.height = "";
                return;
            }

            var height = this._getUsableHeight();
            if (height == null) {
                return; // nothing to do
            }

            this.wrapperElement.style.height = (height + "px");
        }

        for (var i = 0; i < this.children.length; i++) {
            this.children[i].repaint(temporal);
        }

        if (this.disabledLayer != null) {
            this.disabledLayer.style.height = this.wrapperElement.scrollHeight + 'px';
            this.disabledLayer.style.lineHeight = this.wrapperElement.clientHeight + 'px';
        }
    };

    /**
     * Elimina el contenido de este contenedor.
     */
    Container.prototype.clear = function clear() {
        this.children = [];
        this.wrapperElement.innerHTML = "";
        if (this.disabledLayer != null) {
            this.wrapperElement.appendChild(this.disabledLayer);
        }
    };

    /**
     * Devuelve true si este Componente está deshabilitado.
     */
    Container.prototype.isDisabled = function isDisabled() {
        return this.disabledLayer != null;
    };

    /**
     * Deshabilita/habilita este contenedor. Cuando un contenedor
     */
    Container.prototype.setDisabled = function setDisabled(disabled) {
        if (this.isDisabled() == disabled) {
            // Nothing to do
            return;
        }

        if (disabled) {
            this.disabledLayer = document.createElement('div');
            this.disabledLayer.className = 'disable-layer';

            this.disabled_icon = document.createElement('i');
            this.disabled_icon.className = 'disable-icon icon-spin icon-spinner';
            this.disabledLayer.appendChild(this.disabled_icon);

            this.wrapperElement.appendChild(this.disabledLayer);
            this.wrapperElement.classList.add('disabled');
            this.disabledLayer.style.height = this.wrapperElement.scrollHeight + 'px';
            this.disabledLayer.style.lineHeight = this.wrapperElement.clientHeight + 'px';
        } else {
            this.wrapperElement.classList.remove('disabled');
            this.disabledLayer.parentNode.removeChild(this.disabledLayer);
            this.disabledLayer = null;
            this.disable_icon = null;
        }
        this.enabled = !disabled;
    };

    Container.prototype.enable = function enable() {
        this.setDisabled(false);
    };

    Container.prototype.disable = function disable() {
        this.setDisabled(true);
    };

    StyledElements.Container = Container;

})();
<commit_msg>Modified the method 'clear' of styled-container to allow cascading<commit_after>/*
 *     Copyright (c) 2011-2015 CoNWeT Lab., Universidad Politécnica de Madrid
 *
 *     This file is part of Wirecloud Platform.
 *
 *     Wirecloud Platform is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU Affero General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 *
 *     Wirecloud is distributed in the hope that it will be useful, but WITHOUT
 *     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 *     License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Wirecloud Platform.  If not, see
 *     <http://www.gnu.org/licenses/>.
 *
 */

/*global StyledElements*/

(function () {

    "use strict";

    /**
     * Este componente permite crear un contenedor en el que añadir otros
     * componentes.
     *
     * @param options
     * @param events
     */
    var Container = function Container(options, events) {
        var defaultOptions = {
            'extending': false,
            'class': '',
            'useFullHeight': false
        };
        options = StyledElements.Utils.merge(defaultOptions, options);

        // Necesario para permitir herencia
        if (options.extending) {
            return;
        }

        StyledElements.StyledElement.call(this, events);

        this.useFullHeight = options.useFullHeight;
        this.wrapperElement = document.createElement("div");
        this.children = [];

        if (options.id) {
            this.wrapperElement.setAttribute("id", options.id);
        }

        this.wrapperElement.className = StyledElements.Utils.prependWord(options['class'], "container");
    };
    Container.prototype = new StyledElements.StyledElement();

    Container.prototype.appendChild = function appendChild(element, refElement) {
        if (element instanceof StyledElements.StyledElement) {
            element.insertInto(this.wrapperElement, refElement);
            this.children.push(element);

            return element;
        }

        if (typeof element === "string") {
            element = document.createTextNode(element);
        }

        if (refElement instanceof StyledElements.StyledElement) {
            refElement = refElement.wrapperElement;
        }

        if (refElement != null) {
            this.wrapperElement.insertBefore(element, refElement);
        } else {
            this.wrapperElement.appendChild(element);
        }

        return element;
    };

    Container.prototype.removeChild = function removeChild(element) {
        var index;

        if (element instanceof StyledElements.StyledElement) {
            index = this.children.indexOf(element);
            this.children.splice(index, 1);
            this.wrapperElement.removeChild(element.wrapperElement);
        } else {
            this.wrapperElement.removeChild(element);
        }

        return this;
    };

    Container.prototype.repaint = function repaint(temporal) {
        temporal = temporal !== undefined ? temporal : false;

        if (this.useFullHeight) {
            if (this.wrapperElement.classList.contains('hidden')) {
                this.wrapperElement.style.height = "";
                return;
            }

            var height = this._getUsableHeight();
            if (height == null) {
                return; // nothing to do
            }

            this.wrapperElement.style.height = (height + "px");
        }

        for (var i = 0; i < this.children.length; i++) {
            this.children[i].repaint(temporal);
        }

        if (this.disabledLayer != null) {
            this.disabledLayer.style.height = this.wrapperElement.scrollHeight + 'px';
            this.disabledLayer.style.lineHeight = this.wrapperElement.clientHeight + 'px';
        }
    };

    /**
     * Elimina el contenido de este contenedor.
     */
    Container.prototype.clear = function clear() {
        this.children = [];
        this.wrapperElement.innerHTML = "";

        if (this.disabledLayer != null) {
            this.wrapperElement.appendChild(this.disabledLayer);
        }

        return this;
    };

    /**
     * Devuelve true si este Componente está deshabilitado.
     */
    Container.prototype.isDisabled = function isDisabled() {
        return this.disabledLayer != null;
    };

    /**
     * Deshabilita/habilita este contenedor. Cuando un contenedor
     */
    Container.prototype.setDisabled = function setDisabled(disabled) {
        if (this.isDisabled() == disabled) {
            // Nothing to do
            return;
        }

        if (disabled) {
            this.disabledLayer = document.createElement('div');
            this.disabledLayer.className = 'disable-layer';

            this.disabled_icon = document.createElement('i');
            this.disabled_icon.className = 'disable-icon icon-spin icon-spinner';
            this.disabledLayer.appendChild(this.disabled_icon);

            this.wrapperElement.appendChild(this.disabledLayer);
            this.wrapperElement.classList.add('disabled');
            this.disabledLayer.style.height = this.wrapperElement.scrollHeight + 'px';
            this.disabledLayer.style.lineHeight = this.wrapperElement.clientHeight + 'px';
        } else {
            this.wrapperElement.classList.remove('disabled');
            this.disabledLayer.parentNode.removeChild(this.disabledLayer);
            this.disabledLayer = null;
            this.disable_icon = null;
        }
        this.enabled = !disabled;
    };

    Container.prototype.enable = function enable() {
        this.setDisabled(false);
    };

    Container.prototype.disable = function disable() {
        this.setDisabled(true);
    };

    StyledElements.Container = Container;

})();
<|endoftext|>


<commit_before>export default {
  libiary: {},
    externals: {},
    browser_support: {
      DEVELOPMENT: [ 'last 2 versions' ],
      PRODUCTION: [ 'last 2 versions' ]
    },
    build_path: './dist',
    base64: {
      enable: true,
      limit: 10000
    },
    supportIE8: false,
}<commit_msg>use commonjs exports syntax<commit_after>module.exports = {
  libiary: {},
    externals: {},
    browser_support: {
      DEVELOPMENT: [ 'last 2 versions' ],
      PRODUCTION: [ 'last 2 versions' ]
    },
    build_path: './dist',
    base64: {
      enable: true,
      limit: 10000
    },
    supportIE8: false,
};<|endoftext|>


<commit_before>/* globals Meteor, Tracker, RocketChat, UserPresence*/
'use strict';

const { ipcRenderer, shell } = require('electron');
const Notification = require('./lib/Notification');
const SpellCheck = require('./lib/SpellCheck');
const path = require('path');
const i18n = require('../i18n/index');

window.Notification = Notification;
window.i18n = i18n;

const defaultWindowOpen = window.open;

function customWindowOpen (url, frameName, features) {
    if (url.indexOf('meet.jit.si') !== -1) {
        features = ((features) ? (features + ",") : "") +
            "nodeIntegration=true,preload=" + path.join(__dirname, 'jitsi-preload.js');
        return defaultWindowOpen(url, frameName, features);
    } else {
        return defaultWindowOpen(url, frameName, features);
    }
}

window.open = customWindowOpen;

const events = ['unread-changed', 'get-sourceId', 'user-status-manually-set'];

events.forEach(function (e) {
    window.addEventListener(e, function (event) {
        ipcRenderer.sendToHost(e, event.detail);
    });
});

const userPresenceControl = () => {
    const INTERVAL = 10000; // 10s
    setInterval(() => {
        try {
            const idleTime = ipcRenderer.sendSync('getSystemIdleTime');
            if (idleTime < INTERVAL) {
                UserPresence.setOnline();
            }
        } catch (e) {
            console.error(`Error getting system idle time: ${e}`);
        }
    }, INTERVAL);
};

const changeSidebarColor = () => {
    const sidebar = document.querySelector('.sidebar');
    const fullpage = document.querySelector('.full-page');
    if (sidebar) {
        const sidebarItem = sidebar.querySelector('.sidebar-item');
        let itemColor;
        if (sidebarItem) {
            itemColor = window.getComputedStyle(sidebarItem);
        }
        const { color, background } = window.getComputedStyle(sidebar);
        ipcRenderer.sendToHost('sidebar-background', {color: itemColor || color, background: background});
    } else if (fullpage) {
        const { color, background } = window.getComputedStyle(fullpage);
        ipcRenderer.sendToHost('sidebar-background', {color: color, background: background});
    } else {
        window.requestAnimationFrame(changeSidebarColor);

    }
};

ipcRenderer.on('request-sidebar-color', () => {
    changeSidebarColor();
});

window.addEventListener('load', function () {
    Meteor.startup(function () {
        Tracker.autorun(function () {
            const siteName = RocketChat.settings.get('Site_Name');
            if (siteName) {
                ipcRenderer.sendToHost('title-changed', siteName);
            }
        });
    });
    userPresenceControl();
});

window.onload = function () {
    const $ = require('./vendor/jquery-3.1.1');
    function checkExternalUrl (e) {
        const href = $(this).attr('href');
        // Check href matching current domain
        if (RegExp(`^${location.protocol}\/\/${location.host}`).test(href)) {
            return;
        }

        // Check if is file upload link
        if (/^\/file-upload\//.test(href) && !this.hasAttribute('download')) {
            this.setAttribute('download', '');
            this.click();
        }

        // Check href matching relative URL
        if (!/^([a-z]+:)?\/\//.test(href)) {
            return;
        }

        if (/^file:\/\/.+/.test(href)) {
            const item = href.slice(6);
            shell.showItemInFolder(item);
            e.preventDefault();
        } else {
            shell.openExternal(href);
            e.preventDefault();
        }
    }

    $(document).on('click', 'a', checkExternalUrl);

    $('#reload').click(function () {
        ipcRenderer.sendToHost('reload-server');
        $(this).hide();
        $(this).parent().find('.loading-animation').show();
    });
};

// Prevent redirect to url when dragging in
document.addEventListener('dragover', e => e.preventDefault());
document.addEventListener('drop', e => e.preventDefault());

const spellChecker = new SpellCheck();
spellChecker.enable();
<commit_msg>Support On-premise Jitsi Screen Sharing <commit_after>/* globals Meteor, Tracker, RocketChat, UserPresence*/
'use strict';

const { ipcRenderer, shell } = require('electron');
const Notification = require('./lib/Notification');
const SpellCheck = require('./lib/SpellCheck');
const path = require('path');
const i18n = require('../i18n/index');

window.Notification = Notification;
window.i18n = i18n;

const defaultWindowOpen = window.open;

function customWindowOpen (url, frameName, features) {
    const jitsiDomain = RocketChat.settings.get('Jitsi_Domain');
    if (url.indexOf(jitsiDomain) !== -1) {
        features = ((features) ? (features + ",") : "") +
            "nodeIntegration=true,preload=" + path.join(__dirname, 'jitsi-preload.js');
        return defaultWindowOpen(url, frameName, features);
    } else {
        return defaultWindowOpen(url, frameName, features);
    }
}

window.open = customWindowOpen;

const events = ['unread-changed', 'get-sourceId', 'user-status-manually-set'];

events.forEach(function (e) {
    window.addEventListener(e, function (event) {
        ipcRenderer.sendToHost(e, event.detail);
    });
});

const userPresenceControl = () => {
    const INTERVAL = 10000; // 10s
    setInterval(() => {
        try {
            const idleTime = ipcRenderer.sendSync('getSystemIdleTime');
            if (idleTime < INTERVAL) {
                UserPresence.setOnline();
            }
        } catch (e) {
            console.error(`Error getting system idle time: ${e}`);
        }
    }, INTERVAL);
};

const changeSidebarColor = () => {
    const sidebar = document.querySelector('.sidebar');
    const fullpage = document.querySelector('.full-page');
    if (sidebar) {
        const sidebarItem = sidebar.querySelector('.sidebar-item');
        let itemColor;
        if (sidebarItem) {
            itemColor = window.getComputedStyle(sidebarItem);
        }
        const { color, background } = window.getComputedStyle(sidebar);
        ipcRenderer.sendToHost('sidebar-background', {color: itemColor || color, background: background});
    } else if (fullpage) {
        const { color, background } = window.getComputedStyle(fullpage);
        ipcRenderer.sendToHost('sidebar-background', {color: color, background: background});
    } else {
        window.requestAnimationFrame(changeSidebarColor);

    }
};

ipcRenderer.on('request-sidebar-color', () => {
    changeSidebarColor();
});

window.addEventListener('load', function () {
    Meteor.startup(function () {
        Tracker.autorun(function () {
            const siteName = RocketChat.settings.get('Site_Name');
            if (siteName) {
                ipcRenderer.sendToHost('title-changed', siteName);
            }
        });
    });
    userPresenceControl();
});

window.onload = function () {
    const $ = require('./vendor/jquery-3.1.1');
    function checkExternalUrl (e) {
        const href = $(this).attr('href');
        // Check href matching current domain
        if (RegExp(`^${location.protocol}\/\/${location.host}`).test(href)) {
            return;
        }

        // Check if is file upload link
        if (/^\/file-upload\//.test(href) && !this.hasAttribute('download')) {
            this.setAttribute('download', '');
            this.click();
        }

        // Check href matching relative URL
        if (!/^([a-z]+:)?\/\//.test(href)) {
            return;
        }

        if (/^file:\/\/.+/.test(href)) {
            const item = href.slice(6);
            shell.showItemInFolder(item);
            e.preventDefault();
        } else {
            shell.openExternal(href);
            e.preventDefault();
        }
    }

    $(document).on('click', 'a', checkExternalUrl);

    $('#reload').click(function () {
        ipcRenderer.sendToHost('reload-server');
        $(this).hide();
        $(this).parent().find('.loading-animation').show();
    });
};

// Prevent redirect to url when dragging in
document.addEventListener('dragover', e => e.preventDefault());
document.addEventListener('drop', e => e.preventDefault());

const spellChecker = new SpellCheck();
spellChecker.enable();
<|endoftext|>


<commit_before>/**
 * Script for separating distribution data from season data file
 * Currently this works on the season files generated by parse-season step so as to
 * not disturb anything working (and also to avoid reparsing the csvs again)
 *
 * In its final form, this step will go inside parse-season
 */

const fs = require('fs')
const path = require('path')

// Variables and paths
const seasonDataDir = './src/assets/data'
const outDir = './src/assets/data/distributions'

// Take season id from command line
let seasonInFile = process.argv[2]

// Get rid of point values from a prediction object
const filterPrediction = prediction => {
  const takeOnlyBins = p => {
    return {
      bins: p.bins
    }
  }
  if (prediction) {
    return {
      series: prediction.series.map(takeOnlyBins),
      peakTime: takeOnlyBins(prediction.peakTime),
      onsetTime: takeOnlyBins(prediction.onsetTime),
      peakValue: takeOnlyBins(prediction.peakValue)
    }
  } else {
    return null
  }
}

// Extract bin data for all regions in given season data
const extractDistributions = seasonData => {
  return seasonData.regions.map(reg => {
    return {
      seasonId: seasonData.seasonId,
      regionId: reg.id,
      models: reg.models.map(mod => {
        return {
          id: mod.id,
          predictions: mod.predictions.map(filterPrediction)
        }
      })
    }
  })
}

let seasonData = JSON.parse(fs.readFileSync(seasonInFile), 'utf8')
extractDistributions(seasonData).forEach(regionData => {
  let outputFile = path.join(outDir, `season-${regionData.seasonId}-${regionData.regionId}.json`)
  fs.writeFile(outputFile, JSON.stringify(regionData), err => {
    if (err)
      throw err
    console.log(` Distributions file written at ${outputFile}`)
  })
})
<commit_msg>Fix linter issue<commit_after>/**
 * Script for separating distribution data from season data file
 * Currently this works on the season files generated by parse-season step so as to
 * not disturb anything working (and also to avoid reparsing the csvs again)
 *
 * In its final form, this step will go inside parse-season
 */

const fs = require('fs')
const path = require('path')

// Variables and paths
const outDir = './src/assets/data/distributions'

// Take season id from command line
let seasonInFile = process.argv[2]

// Get rid of point values from a prediction object
const filterPrediction = prediction => {
  const takeOnlyBins = p => {
    return {
      bins: p.bins
    }
  }
  if (prediction) {
    return {
      series: prediction.series.map(takeOnlyBins),
      peakTime: takeOnlyBins(prediction.peakTime),
      onsetTime: takeOnlyBins(prediction.onsetTime),
      peakValue: takeOnlyBins(prediction.peakValue)
    }
  } else {
    return null
  }
}

// Extract bin data for all regions in given season data
const extractDistributions = seasonData => {
  return seasonData.regions.map(reg => {
    return {
      seasonId: seasonData.seasonId,
      regionId: reg.id,
      models: reg.models.map(mod => {
        return {
          id: mod.id,
          predictions: mod.predictions.map(filterPrediction)
        }
      })
    }
  })
}

let seasonData = JSON.parse(fs.readFileSync(seasonInFile), 'utf8')
extractDistributions(seasonData).forEach(regionData => {
  let outputFile = path.join(outDir, `season-${regionData.seasonId}-${regionData.regionId}.json`)
  fs.writeFile(outputFile, JSON.stringify(regionData), err => {
    if (err) {
      throw err
    }
    console.log(` Distributions file written at ${outputFile}`)
  })
})
<|endoftext|>


<commit_before>/*global BackboneWizard, Marionette*/

BackboneWizard.Routers = BackboneWizard.Routers || {};

(function () {
    'use strict';

    BackboneWizard.Routers.WizardRouter = Marionette.AppRouter.extend({
        appRoutes: {
            '': 'index',
            'verify': 'showVerify',
            'payment': 'showPayment',
            'success': 'showSuccess'
        }
    });

})();
<commit_msg>Create Routers module.<commit_after>/*global Marionette, app*/
'use strict';

app.module('Routers', function (Routers, app, Backbone, Marionette) {

    this.WizardRouter = Marionette.AppRouter.extend({
        appRoutes: {
            '': 'index',
            'verify': 'showVerify',
            'payment': 'showPayment',
            'success': 'showSuccess'
        }
    });

});
<|endoftext|>


<commit_before>var Bullet = Class.extend({
    init: function (args) {
        var geometry = new THREE.SphereGeometry(8, 8, 8);
        var material = new THREE.MeshLambertMaterial({
            side: THREE.DoubleSide,
            map: THREE.ImageUtils.loadTexture('assets/textures/evilBox.png')
        });

        this.mesh = new THREE.Mesh(geometry, material);
        this.collider = new SAT.Circle(new SAT.Vector(this.mesh.position.x-8,this.mesh.position.z-8),8);

    },
    velocity: 10,
    collisionRemaining: 3,
    collisionCooldown: 0,
    direction: new THREE.Vector3(0, 0, 0),
    setTarget: function (target) {
        var playerVector = new THREE.Vector3().copy(target.position);
        var enemyVector = this.mesh.position;
        this.direction = playerVector.sub(enemyVector).normalize();
        return this.direction;
    },
    shoot: function (startVector) {
        this.mesh.position.set(startVector.x, startVector.y, startVector.z);
        basicScene.world.bullets.push(this);
        basicScene.world.mesh.add(this.mesh);
    },
    shootPlayer: function(position){
        this.mesh.position.set(position.x,16,position.z);
        var playerVector = new THREE.Vector3().copy(basicScene.user.mesh.position);
        var enemyVector = this.mesh.position;
        this.direction = playerVector.sub(enemyVector).normalize();
        basicScene.world.playerTargetedBullets.push(this);
        basicScene.world.mesh.add(this.mesh);
    },
    fly: function () {
        this.collider.pos.x = this.mesh.position.x;
        this.collider.pos.y = this.mesh.position.z;

        var position = this.mesh.position;
        var direction = new THREE.Vector3().copy(this.direction);
        direction.multiplyScalar(this.velocity);

        if(this.collisionCooldown <= 0 && this.collisionRemaining > 0) {
            var obstacles = basicScene.world.obstacles;

            for (var i = 0; i < obstacles.length; i++) {
                var response = new SAT.Response();
                var col = SAT.testPolygonCircle(obstacles[i].toPolygon(), this.collider, response);

                if (col) {
                    this.direction.negate();
                    this.mesh.position.add(new THREE.Vector3(response.overlapV.x, 0, response.overlapV.y));
                    this.mesh.position.add(new THREE.Vector3(response.overlapV.x, 0, response.overlapV.y));
                    this.collisionCooldown = 10;
                    this.collisionRemaining -= 1;
                }
            }
        } else if(this.collisionRemaining == 0){
            this.die();
        } else {
            this.collisionCooldown -=1
        }

        this.mesh.position.add(direction)
    },
    die: function () {
        removeA(basicScene.world.bullets, this);
        basicScene.world.mesh.remove(this.mesh);

        function removeA(arr) {
            var what, a = arguments, L = a.length, ax;
            while (L > 1 && arr.length) {
                what = a[--L];
                while ((ax = arr.indexOf(what)) !== -1) {
                    arr.splice(ax, 1);
                }
            }
            return arr;
        }
    },
    onPlayerHit: function(){
        this.die();
    }
});<commit_msg>Correcting bullets physix<commit_after>var Bullet = Class.extend({
    init: function (args) {
        var geometry = new THREE.SphereGeometry(8, 8, 8);
        var material = new THREE.MeshLambertMaterial({
            side: THREE.DoubleSide,
            map: THREE.ImageUtils.loadTexture('assets/textures/evilBox.png')
        });

        this.mesh = new THREE.Mesh(geometry, material);
        this.collider = new SAT.Circle(new SAT.Vector(this.mesh.position.x-8,this.mesh.position.z-8),8);

    },
    velocity: 10,
    collisionRemaining: 3,
    collisionCooldown: 0,
    direction: new THREE.Vector3(0, 0, 0),
    setTarget: function (target) {
        var playerVector = new THREE.Vector3().copy(target.position);
        var enemyVector = this.mesh.position;
        this.direction = playerVector.sub(enemyVector).normalize();
        return this.direction;
    },
    shoot: function (startVector) {
        this.mesh.position.set(startVector.x, startVector.y, startVector.z);
        basicScene.world.bullets.push(this);
        basicScene.world.mesh.add(this.mesh);
    },
    shootPlayer: function(position){
        this.mesh.position.set(position.x,16,position.z);
        var playerVector = new THREE.Vector3().copy(basicScene.user.mesh.position);
        var enemyVector = this.mesh.position;
        this.direction = playerVector.sub(enemyVector).normalize();
        basicScene.world.playerTargetedBullets.push(this);
        basicScene.world.mesh.add(this.mesh);
    },
    fly: function () {
        this.collider.pos.x = this.mesh.position.x;
        this.collider.pos.y = this.mesh.position.z;

        var position = this.mesh.position;
        var direction = new THREE.Vector3().copy(this.direction);
        direction.multiplyScalar(this.velocity);

        if(this.collisionCooldown <= 0 && this.collisionRemaining > 0) {
            var obstacles = basicScene.world.obstacles;

            for (var i = 0; i < obstacles.length; i++) {
                var response = new SAT.Response();
                var col = SAT.testPolygonCircle(obstacles[i].toPolygon(), this.collider, response);

                if (col) {
                    if(response.overlapV.x != 0) this.direction.x *= -1;
                    else this.direction.z *= -1;
                    this.mesh.position.add(new THREE.Vector3(response.overlapV.x, 0, response.overlapV.y));
                    console.log(response.overlapV)
                    this.collisionCooldown = 10;
                    this.collisionRemaining -= 1;
                }
            }
        } else if(this.collisionRemaining == 0){
            this.die();
        } else {
            this.collisionCooldown -=1
        }

        this.mesh.position.add(direction)
    },
    die: function () {
        removeA(basicScene.world.bullets, this);
        basicScene.world.mesh.remove(this.mesh);

        function removeA(arr) {
            var what, a = arguments, L = a.length, ax;
            while (L > 1 && arr.length) {
                what = a[--L];
                while ((ax = arr.indexOf(what)) !== -1) {
                    arr.splice(ax, 1);
                }
            }
            return arr;
        }
    },
    onPlayerHit: function(){
        this.die();
    }
});<|endoftext|>


<commit_before>var assert = require('assert');
var http = require('http');
var WebSocket = require('ws');
var zetta = require('../');
var zettacluster = require('zetta-cluster');
var Scout = require('./fixture/example_scout');
var VirtualDevice = require('../lib/virtual_device');
var LedJSON = require('./fixture/virtual_device.json');

var mockSocket = {
  on: function(){},
  subscribe: function(topic, cb){
    if(cb) {
      cb();
    }
  },
  unsubscribe: function(){}
};

describe('Virtual Device', function() {
  var base = null;
  var cluster = null;
  var device = null;
  var socket = null;
  var deviceJson = null;
  var vdevice = null;

  var startPort = 2600;

  beforeEach(function(done) {
    cluster = zettacluster({ zetta: zetta })
      .server('cloud')
      .server('detroit1', [Scout], ['cloud'])
      .on('ready', function() {
        socket = cluster.servers['cloud'].httpServer.peers['detroit1'];
        if (!socket) {
          done(new Error('socket not found'));
        }

        var did = Object.keys(cluster.servers['detroit1'].runtime._jsDevices)[0];
        device = cluster.servers['detroit1'].runtime._jsDevices[did];
        var id = cluster.servers['detroit1'].id;
        base = 'localhost:' + cluster.servers['cloud']._testPort + '/servers/' + cluster.servers['cloud'].locatePeer(id) + '/devices/' + did;

        http.get('http://' + base, function(res) {
          var buffer = [];
          var len = 0;
          res.on('readable', function() {
            var data;
            while (data = res.read()) {
              buffer.push(data);
              len += data.length;
            }
          });
          res.on('end', function() {
            var buf = Buffer.concat(buffer, len);
            deviceJson = JSON.parse(buf.toString());
            vdevice = new VirtualDevice(deviceJson, socket);
            vdevice.on('ready', function() {
              setTimeout(done, 100);
            });
          });
          res.on('error', function(err) {
            done(err);
          });
        })
      })
      .run(function(err){
        if (err) {
          return done(err);
        }
      });
  });

  afterEach(function(done) {
    cluster.stop();
    setTimeout(done, 10); // fix issues with server not being closed before a new one starts
  });

  describe('.call method', function() {

    it('call should work without a callback function', function(done) {
      vdevice.call('change')
      var timer = setTimeout(function() {
        done(new Error('Faied to recv transition call on detroit device'));
      }, 100);

      device.on('change', function() {
        clearTimeout(timer);
        done();
      });
    });

    it('call should work without arguments', function(done) {
      vdevice.call('change', function(err) {
        assert.equal(err, null);
      });
      var timer = setTimeout(function() {
        done(new Error('Faied to recv transition call on detroit device'));
      }, 100);

      device.on('change', function() {
        clearTimeout(timer);
        done();
      });
    });

    it('call should work with arguments', function(done) {
      vdevice.call('test', 321, function(err) {
        assert.equal(err, null);
      });
      var timer = setTimeout(function() {
        done(new Error('Faied to recv transition call on detroit device'));
      }, 100);

      device.on('test', function() {
        clearTimeout(timer);
        assert.equal(device.value, 321);
        done();
      });
    });

    it('call should work with arguments, after peer reconnects', function(done) {

      var timer = setTimeout(function() {
        done(new Error('Faied to recv transition call on detroit device'));
      }, 1500);

      vdevice.call('test', 999, function(err) {
        assert.equal(err, null);

        clearTimeout(timer);
        assert.equal(device.value, 999);

        var socket = cluster.servers['cloud'].httpServer.peers['detroit1'];
        socket.close();

        setTimeout(function() {
          vdevice.call('test', 222, function(err) {
            assert.equal(err, null);
          });
          var timer = setTimeout(function() {
            done(new Error('Faied to recv transition call on detroit device'));
          }, 1500);

          device.on('test', function() {
            clearTimeout(timer);
            assert.equal(device.value, 222);
            done();
          });
        }, 1500);
      });

    });
  });

  describe('Device log monitor stream', function() {

    it('should update virtual devices state when detroit device updates', function(done) {
      assert.equal(vdevice.state, 'ready');
      device.call('change', function() {
        assert.equal(device.state, 'changed');
        setTimeout(function() {
          assert.equal(vdevice.state, 'changed');
          done();
        }, 100);
      });
    });

    it('should update virtual devices state when virtual device calls transition', function(done) {
      assert.equal(vdevice.state, 'ready');
      vdevice.call('change', function() {
        assert.equal(device.state, 'changed');
        setTimeout(function() {
          assert.equal(vdevice.state, 'changed');
          done();
        }, 100);
      });
    });

  });

  describe('Device monitor streams on properties', function() {

    it('should update virtual device when value increments locally', function(done) {
      assert.equal(vdevice.bar, 0);
      assert.equal(device.bar, 0);
      device.incrementStreamValue();
      assert.equal(device.bar, 1);
      setTimeout(function() {
        assert.equal(vdevice.bar, 1);
        done();
      }, 100);
    });

    it('should implement .createReadStream() for object stream', function(done) {
      vdevice.createReadStream('bar').on('data', function(msg) {
        assert.equal(msg.data, 1);
        done();
      });

      setTimeout(function(){
        device.incrementStreamValue();
      }, 10);
    })

    it('should implement .createReadStream() for binary stream', function(done) {
      vdevice.createReadStream('foobar').on('data', function(buf) {
        assert.deepEqual(buf, new Buffer([1]));
        done();
      });
      setTimeout(function(){
        device.incrementFooBar();
      }, 10);
    })

    it('should recv data event after a client ws disconnected on the same topic', function(done) {

      var url = 'ws://localhost:' + cluster.servers['cloud']._testPort + '/servers/detroit1/events?topic=testdriver%2F' + device.id + '%2Fbar';

      var recv = 0;
      var wsRecv = 0;
      vdevice.streams.bar.on('data', function(data) {
        recv++;
      });

      device.incrementStreamValue();

      setTimeout(function() {
        assert.equal(recv, 1);
        var socket = new WebSocket(url);
        socket.on('message', function() {
          wsRecv++;
        });
        socket.on('open', function() {
          device.incrementStreamValue();
          setTimeout(function() {
            assert.equal(recv, 2);
            assert.equal(wsRecv, 1);

            socket.close();
            device.incrementStreamValue();
            setTimeout(function() {
              assert.equal(recv, 3);
              assert.equal(wsRecv, 1);
              done();
            }, 300);
          },300);
        });
        socket.on('error', done);

      }, 300);
    });

  });

  describe('Device binary streams', function() {

    it('should only subscribe to a binary stream if used', function(done) {
      var topic = device.type + '/' + device.id + '/foobar';
      assert.equal(cluster.servers['detroit1'].pubsub._listeners[topic], undefined);
      vdevice.streams.foobar.on('data', function() {});
      setTimeout(function() {
        assert.notEqual(cluster.servers['detroit1'].pubsub._listeners[topic], undefined);
        done();
      }, 100);
    });

    it('should pass binary data from local device to virtual', function(done) {
      var recv = 0;
      vdevice.streams.foobar.on('data', function(data) {
        recv++;
        assert.deepEqual(data, new Buffer([recv]));
      });

      setTimeout(function() {
        device.incrementFooBar();
        device.incrementFooBar();
        device.incrementFooBar();

        setTimeout(function() {
          assert.equal(recv, 3);
          done();
        }, 100);
      }, 100);
    });

  });

  describe('basic unit tests', function() {

    var device = null;
    beforeEach(function() {
      device = new VirtualDevice(LedJSON , mockSocket);
    });

    it('wires up logs, properties, and actions', function() {
      assert.equal(device.state, 'off');
      assert.equal(Object.keys(device.streams).length, 2);
    });

    it('will change properties with update.', function() {
      device._update({ properties: {state: 'on'}});
      assert.equal(device.state, 'on');
    });

    it('will return the proper action given a name', function() {
      var action = device._getAction('turn-on');
      assert.ok(action);
      assert.equal(action.name, 'turn-on');
      assert.equal(action.fields.length, 1);
    });

    it('will return link given a title', function() {
      var link = device._getLinkWithTitle('state');
      assert.ok(link);
      assert.equal(link.title, 'state');
      assert.equal(link.rel[0], 'monitor');
      assert.equal(link.rel[1], 'http://rels.zettajs.io/object-stream');
    });

    it('will return an array of links if searched for by rel', function() {
      var links = device._getLinksWithRel('http://rels.zettajs.io/object-stream');
      assert.ok(links);
      assert.equal(links.length, 2);
      assert.ok(Array.isArray(links));
    });

    it('will parse out a topic for a particular link', function() {
      var link = device._getLinkWithTitle('state');
      var topic = device._getTopic(link);
      assert.equal(topic, 'led/0eaf8607-5b8c-45ee-afae-9a5f9e1f34e2/state');
    });

    it('will encode transition arguments into an object', function() {
      var action = device._getAction('turn-on');
      var data = device._encodeData(action, {});
      assert.ok(data);
      assert.equal(Object.keys(data)[0], 'action');
      assert.equal(data.action, 'turn-on');
    });
  });

});

<commit_msg>Added failing test for virtual_device for _update called with proper formatted args<commit_after>var assert = require('assert');
var http = require('http');
var WebSocket = require('ws');
var zetta = require('../');
var zettacluster = require('zetta-cluster');
var Scout = require('./fixture/example_scout');
var VirtualDevice = require('../lib/virtual_device');
var LedJSON = require('./fixture/virtual_device.json');

var mockSocket = {
  on: function(){},
  subscribe: function(topic, cb){
    if(cb) {
      cb();
    }
  },
  unsubscribe: function(){}
};

describe('Virtual Device', function() {
  var base = null;
  var cluster = null;
  var device = null;
  var socket = null;
  var deviceJson = null;
  var vdevice = null;

  var startPort = 2600;

  beforeEach(function(done) {
    cluster = zettacluster({ zetta: zetta })
      .server('cloud')
      .server('detroit1', [Scout], ['cloud'])
      .on('ready', function() {
        socket = cluster.servers['cloud'].httpServer.peers['detroit1'];
        if (!socket) {
          done(new Error('socket not found'));
        }

        var did = Object.keys(cluster.servers['detroit1'].runtime._jsDevices)[0];
        device = cluster.servers['detroit1'].runtime._jsDevices[did];
        var id = cluster.servers['detroit1'].id;
        base = 'localhost:' + cluster.servers['cloud']._testPort + '/servers/' + cluster.servers['cloud'].locatePeer(id) + '/devices/' + did;

        http.get('http://' + base, function(res) {
          var buffer = [];
          var len = 0;
          res.on('readable', function() {
            var data;
            while (data = res.read()) {
              buffer.push(data);
              len += data.length;
            }
          });
          res.on('end', function() {
            var buf = Buffer.concat(buffer, len);
            deviceJson = JSON.parse(buf.toString());
            vdevice = new VirtualDevice(deviceJson, socket);
            vdevice.on('ready', function() {
              setTimeout(done, 100);
            });
          });
          res.on('error', function(err) {
            done(err);
          });
        })
      })
      .run(function(err){
        if (err) {
          return done(err);
        }
      });
  });

  afterEach(function(done) {
    cluster.stop();
    setTimeout(done, 10); // fix issues with server not being closed before a new one starts
  });

  describe('.call method', function() {

    it('call should work without a callback function', function(done) {
      vdevice.call('change')
      var timer = setTimeout(function() {
        done(new Error('Faied to recv transition call on detroit device'));
      }, 100);

      device.on('change', function() {
        clearTimeout(timer);
        done();
      });
    });

    it('_update should always be called with data.actions in proper format', function(done) {
      var called = 0;
      var orig = vdevice._update;
      vdevice._update = function(data) {
        called++;
        assert(Array.isArray(data.actions));
        data.actions.forEach(function(action) {
          assert(action.class);
          assert(action.name);
          assert(action.method);
          assert(action.href);
          assert(action.fields);
        });
        orig.apply(vdevice, arguments);

        // _update is called twice on transitions. Once for the return of the transition http POST and again
        // for the log topic update.
        if (called === 2) {
          done();
        }
      };

      vdevice.call('change');
    });

    it('call should work without arguments', function(done) {
      vdevice.call('change', function(err) {
        assert.equal(err, null);
      });
      var timer = setTimeout(function() {
        done(new Error('Faied to recv transition call on detroit device'));
      }, 100);

      device.on('change', function() {
        clearTimeout(timer);
        done();
      });
    });

    it('call should work with arguments', function(done) {
      vdevice.call('test', 321, function(err) {
        assert.equal(err, null);
      });
      var timer = setTimeout(function() {
        done(new Error('Faied to recv transition call on detroit device'));
      }, 100);

      device.on('test', function() {
        clearTimeout(timer);
        assert.equal(device.value, 321);
        done();
      });
    });

    it('call should work with arguments, after peer reconnects', function(done) {

      var timer = setTimeout(function() {
        done(new Error('Faied to recv transition call on detroit device'));
      }, 1500);

      vdevice.call('test', 999, function(err) {
        assert.equal(err, null);

        clearTimeout(timer);
        assert.equal(device.value, 999);

        var socket = cluster.servers['cloud'].httpServer.peers['detroit1'];
        socket.close();

        setTimeout(function() {
          vdevice.call('test', 222, function(err) {
            assert.equal(err, null);
          });
          var timer = setTimeout(function() {
            done(new Error('Faied to recv transition call on detroit device'));
          }, 1500);

          device.on('test', function() {
            clearTimeout(timer);
            assert.equal(device.value, 222);
            done();
          });
        }, 1500);
      });

    });
  });

  describe('Device log monitor stream', function() {

    it('should update virtual devices state when detroit device updates', function(done) {
      assert.equal(vdevice.state, 'ready');
      device.call('change', function() {
        assert.equal(device.state, 'changed');
        setTimeout(function() {
          assert.equal(vdevice.state, 'changed');
          done();
        }, 100);
      });
    });

    it('should update virtual devices state when virtual device calls transition', function(done) {
      assert.equal(vdevice.state, 'ready');
      vdevice.call('change', function() {
        assert.equal(device.state, 'changed');
        setTimeout(function() {
          assert.equal(vdevice.state, 'changed');
          done();
        }, 100);
      });
    });

  });

  describe('Device monitor streams on properties', function() {

    it('should update virtual device when value increments locally', function(done) {
      assert.equal(vdevice.bar, 0);
      assert.equal(device.bar, 0);
      device.incrementStreamValue();
      assert.equal(device.bar, 1);
      setTimeout(function() {
        assert.equal(vdevice.bar, 1);
        done();
      }, 100);
    });

    it('should implement .createReadStream() for object stream', function(done) {
      vdevice.createReadStream('bar').on('data', function(msg) {
        assert.equal(msg.data, 1);
        done();
      });

      setTimeout(function(){
        device.incrementStreamValue();
      }, 10);
    })

    it('should implement .createReadStream() for binary stream', function(done) {
      vdevice.createReadStream('foobar').on('data', function(buf) {
        assert.deepEqual(buf, new Buffer([1]));
        done();
      });
      setTimeout(function(){
        device.incrementFooBar();
      }, 10);
    })

    it('should recv data event after a client ws disconnected on the same topic', function(done) {

      var url = 'ws://localhost:' + cluster.servers['cloud']._testPort + '/servers/detroit1/events?topic=testdriver%2F' + device.id + '%2Fbar';

      var recv = 0;
      var wsRecv = 0;
      vdevice.streams.bar.on('data', function(data) {
        recv++;
      });

      device.incrementStreamValue();

      setTimeout(function() {
        assert.equal(recv, 1);
        var socket = new WebSocket(url);
        socket.on('message', function() {
          wsRecv++;
        });
        socket.on('open', function() {
          device.incrementStreamValue();
          setTimeout(function() {
            assert.equal(recv, 2);
            assert.equal(wsRecv, 1);

            socket.close();
            device.incrementStreamValue();
            setTimeout(function() {
              assert.equal(recv, 3);
              assert.equal(wsRecv, 1);
              done();
            }, 300);
          },300);
        });
        socket.on('error', done);

      }, 300);
    });

  });

  describe('Device binary streams', function() {

    it('should only subscribe to a binary stream if used', function(done) {
      var topic = device.type + '/' + device.id + '/foobar';
      assert.equal(cluster.servers['detroit1'].pubsub._listeners[topic], undefined);
      vdevice.streams.foobar.on('data', function() {});
      setTimeout(function() {
        assert.notEqual(cluster.servers['detroit1'].pubsub._listeners[topic], undefined);
        done();
      }, 100);
    });

    it('should pass binary data from local device to virtual', function(done) {
      var recv = 0;
      vdevice.streams.foobar.on('data', function(data) {
        recv++;
        assert.deepEqual(data, new Buffer([recv]));
      });

      setTimeout(function() {
        device.incrementFooBar();
        device.incrementFooBar();
        device.incrementFooBar();

        setTimeout(function() {
          assert.equal(recv, 3);
          done();
        }, 100);
      }, 100);
    });

  });

  describe('basic unit tests', function() {

    var device = null;
    beforeEach(function() {
      device = new VirtualDevice(LedJSON , mockSocket);
    });

    it('wires up logs, properties, and actions', function() {
      assert.equal(device.state, 'off');
      assert.equal(Object.keys(device.streams).length, 2);
    });

    it('will change properties with update.', function() {
      device._update({ properties: {state: 'on'}});
      assert.equal(device.state, 'on');
    });

    it('will return the proper action given a name', function() {
      var action = device._getAction('turn-on');
      assert.ok(action);
      assert.equal(action.name, 'turn-on');
      assert.equal(action.fields.length, 1);
    });

    it('will return link given a title', function() {
      var link = device._getLinkWithTitle('state');
      assert.ok(link);
      assert.equal(link.title, 'state');
      assert.equal(link.rel[0], 'monitor');
      assert.equal(link.rel[1], 'http://rels.zettajs.io/object-stream');
    });

    it('will return an array of links if searched for by rel', function() {
      var links = device._getLinksWithRel('http://rels.zettajs.io/object-stream');
      assert.ok(links);
      assert.equal(links.length, 2);
      assert.ok(Array.isArray(links));
    });

    it('will parse out a topic for a particular link', function() {
      var link = device._getLinkWithTitle('state');
      var topic = device._getTopic(link);
      assert.equal(topic, 'led/0eaf8607-5b8c-45ee-afae-9a5f9e1f34e2/state');
    });

    it('will encode transition arguments into an object', function() {
      var action = device._getAction('turn-on');
      var data = device._encodeData(action, {});
      assert.ok(data);
      assert.equal(Object.keys(data)[0], 'action');
      assert.equal(data.action, 'turn-on');
    });
  });

});

<|endoftext|>


<commit_before>'use strict';

define([
	'canjs',
    'underscore'
],
	function (can, _) {

		can.mustache.registerHelper('checkState', function (options) {
			return options.context.attr('viewState') === 'list'
				? options.fn()
				: options.inverse();
		});

		can.mustache.registerHelper('isPrimitive', function (observer, primitive, options) {
			return observer() === primitive ? options.fn() : options.inverse();
		});

		can.mustache.registerHelper('getArrayObjValue', function (array, index, key) {
			return array() ? array().attr(index + '.' + key) : '';
		});

		can.mustache.registerHelper('sortedBy', function (collection, prop, options) {
			if (collection && collection.length) {
				var sorted = _.sortBy(collection, function (member) {
					return member.attr(prop);
				});

				return _.map(sorted, function (member) {
					return options.fn(member);
				}).join('');
			}
		});

		can.mustache.registerHelper('createForm', function (id, className) {
			return '

';
		});

		can.mustache.registerHelper('checkSelected', function (id, anotherId) {
			return id() === anotherId() ? 'selected' : '';
		});

		can.mustache.registerHelper('checkRelation', function (id, relId, options) {
			return id() === relId() ? options.fn() : options.inverse();
		});

		can.mustache.registerHelper('getBoxName', function (index) {
			var classes = ['bg-light-blue', 'bg-red', 'bg-green', 'bg-yellow', 'bg-maroon', 'bg-purple', 'bg-aqua'];
			return classes[index() % classes.length]
		});

		can.mustache.registerHelper('make3Col', function (index) {
			return (index() + 1) % 3 === 0 ? '

' : '';
		});

        can.mustache.registerHelper('checkLanguages', function (languages, name, description) {
            console.log(languages().attr());
        });

		can.mustache.registerHelper('getJobType', function (jobType) {
			var jobTypes = ['Врач', 'Фармацевт'];
			return jobTypes[jobType()-1];
		});

		can.mustache.registerHelper('getSpeciality', function (speciality_doc, speciality_apt, jobType) {
			var result = null;
			var specialities_doc = ['педиатр', 'терапевт', 'кардиолог', 'семейный врач', 'гастроэнтеролог', 'невропатолог', 'аллерголог', 'дерматолог', 'пульмонолог', 'офтальмолог', 'инфекционист', 'ЛОР'];
			var specialities_apt = ['провизор', 'заведующий аптекой', 'менеджер по закупкам'];

			if ( jobType() == 1) {
				result = specialities_doc[speciality_doc()-1];
			} else if ( jobType() == 2 ) {
				result = specialities_apt[speciality_apt()-1];
			}
			return result;
		});

		can.mustache.registerHelper('getInstitutionTypes', function (institutions) {
			var institutionTypes = ['Поликлиника', 'Стационар', 'Сетевая аптека', 'Несетевая аптека'];

			var result = '';

			if ( institutions() ) {
				for (var institution in institutions().attr()) {
					result += institutionTypes[institutions().attr()[institution] - 1] + ',';
				}

				result = result.substring(0, result.length - 1);
			}

			return result;
		});

		can.mustache.registerHelper('getSocialNetworks', function (networks) {
			var networkTypes = ['Facebook', 'Vkontakte', 'Odnoklassniki', 'Twitter'];

			var result = '';

			if (networks().attr().length > 0) {
				for (var network in networks().attr()) {
					result += networkTypes[networks().attr()[network] - 1] + ',';
				}

				result = result.substring(0, result.length - 1);
			}

			return result;
		});

		can.mustache.registerHelper('acceptRejectHelper', function (value) {

			var result = '';
			if (value() == 1) {
				result = 'Да'
			} else if (value() == 2) {
				result = 'Нет'
			} else {
				result = 'Нет ответа'
			}

			return result;
		});
	}
);<commit_msg>viewHelper networks fix<commit_after>'use strict';

define([
	'canjs',
    'underscore'
],
	function (can, _) {

		can.mustache.registerHelper('checkState', function (options) {
			return options.context.attr('viewState') === 'list'
				? options.fn()
				: options.inverse();
		});

		can.mustache.registerHelper('isPrimitive', function (observer, primitive, options) {
			return observer() === primitive ? options.fn() : options.inverse();
		});

		can.mustache.registerHelper('getArrayObjValue', function (array, index, key) {
			return array() ? array().attr(index + '.' + key) : '';
		});

		can.mustache.registerHelper('sortedBy', function (collection, prop, options) {
			if (collection && collection.length) {
				var sorted = _.sortBy(collection, function (member) {
					return member.attr(prop);
				});

				return _.map(sorted, function (member) {
					return options.fn(member);
				}).join('');
			}
		});

		can.mustache.registerHelper('createForm', function (id, className) {
			return '

';
		});

		can.mustache.registerHelper('checkSelected', function (id, anotherId) {
			return id() === anotherId() ? 'selected' : '';
		});

		can.mustache.registerHelper('checkRelation', function (id, relId, options) {
			return id() === relId() ? options.fn() : options.inverse();
		});

		can.mustache.registerHelper('getBoxName', function (index) {
			var classes = ['bg-light-blue', 'bg-red', 'bg-green', 'bg-yellow', 'bg-maroon', 'bg-purple', 'bg-aqua'];
			return classes[index() % classes.length]
		});

		can.mustache.registerHelper('make3Col', function (index) {
			return (index() + 1) % 3 === 0 ? '

' : '';
		});

        can.mustache.registerHelper('checkLanguages', function (languages, name, description) {
            console.log(languages().attr());
        });

		can.mustache.registerHelper('getJobType', function (jobType) {
			var jobTypes = ['Врач', 'Фармацевт'];
			return jobTypes[jobType()-1];
		});

		can.mustache.registerHelper('getSpeciality', function (speciality_doc, speciality_apt, jobType) {
			var result = null;
			var specialities_doc = ['педиатр', 'терапевт', 'кардиолог', 'семейный врач', 'гастроэнтеролог', 'невропатолог', 'аллерголог', 'дерматолог', 'пульмонолог', 'офтальмолог', 'инфекционист', 'ЛОР'];
			var specialities_apt = ['провизор', 'заведующий аптекой', 'менеджер по закупкам'];

			if ( jobType() == 1) {
				result = specialities_doc[speciality_doc()-1];
			} else if ( jobType() == 2 ) {
				result = specialities_apt[speciality_apt()-1];
			}
			return result;
		});

		can.mustache.registerHelper('getInstitutionTypes', function (institutions) {
			var institutionTypes = ['Поликлиника', 'Стационар', 'Сетевая аптека', 'Несетевая аптека'];

			var result = '';

			if ( institutions() ) {
				for (var institution in institutions().attr()) {
					result += institutionTypes[institutions().attr()[institution] - 1] + ',';
				}

				result = result.substring(0, result.length - 1);
			}

			return result;
		});

		can.mustache.registerHelper('getSocialNetworks', function (networks) {
			var networkTypes = ['Facebook', 'Vkontakte', 'Odnoklassniki', 'Twitter'];

			var result = '';

			if (networks && networks().attr().length > 0) {
				for (var network in networks().attr()) {
					result += networkTypes[networks().attr()[network] - 1] + ',';
				}

				result = result.substring(0, result.length - 1);
			}

			return result;
		});

		can.mustache.registerHelper('acceptRejectHelper', function (value) {

			var result = '';
			if (value() == 1) {
				result = 'Да'
			} else if (value() == 2) {
				result = 'Нет'
			} else {
				result = 'Нет ответа'
			}

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


<commit_before>(function () {
    angular.module("TodoApp").controller("TodoController", TodoController);

    function TodoController($http, $rootScope, $filter, $localStorage, $scope, todoService) {
        var vm = this;
        var deregisters = [];
        $http.defaults.transformRequest.push(function (config) {
            vm.loading = true;
            return config;
        });
        $http.defaults.transformResponse.push(function (response) {
            vm.loading = false;
            return response;
        });

        deregisters.push($rootScope.$on("todosChanged", reloadTodoList));
        deregisters.push($rootScope.$on("errorResponse", handleError));
        $scope.$on("$destroy", destroyThis);

        vm.loading = false;
        vm.items = [];

        vm.sortableOptions = {
            placeholder: "app",
            activate: function(x,y){
                y.item.addClass("dragging");
            },
            deactivate: function(x,y){
                y.item.removeClass("dragging");
            }
        };

        vm.submitForm = function () {
            /** @namespace vm.newTodoForm */
            if (vm.newTodoForm.$valid) {
                todoService.createTodo(vm.newTodo);
                vm.newTodo = "";
            }
        };

        vm.todoUpdated = function (todo) {
            todoService.updateTodo(todo);
        };

        vm.todoDeleted = function (todo) {
            todoService.deleteTodo(todo.id);
        };

        vm.todoCompleteDeleted = function(){
            $filter("filter")(vm.items, {isComplete: true}).forEach(vm.todoDeleted);
        };

        function getTodoList() {
            if ($localStorage.items !== undefined) {
                vm.items = $localStorage.items;
            }
            reloadTodoList();
        }

        function reloadTodoList() {
            todoService.getTodoList().success(function (data) {
                data.forEach(function (newTodo) {
                    if ($filter("filter")(vm.items, newTodo).length > 0) {
                        //   do nothing, it there and it matches
                    } else if ($filter("filter")(vm.items, {id: newTodo.id}).length > 0) {
                        var oldTodo = $filter("filter")(vm.items, {id: newTodo.id})[0];
                        var index = vm.items.indexOf(oldTodo);
                        vm.items[index] = newTodo;
                    } else {
                        vm.items.push(newTodo);
                    }

                });
                vm.items = vm.items.filter(function (oldTodo) {
                    return $filter("filter")(data, {id: oldTodo.id}).length > 0;
                });

                $localStorage.items = vm.items;
            });
        }

        function handleError(event, text, status) {
            vm.error = "Failed to do action. Server returned " + status + " - " + text;
        }

        function destroyThis() {
            deregisters.forEach(function (eventDereg) {
                eventDereg();
            });
        }

        vm.onDropComplete = function (index, obj) {
            var otherObj = vm.items[index];
            var otherIndex = vm.items.indexOf(obj);
            vm.items[index] = obj;
            vm.items[otherIndex] = otherObj;
        };
        getTodoList();
    }
})();
<commit_msg>Added toast to show errors<commit_after>(function () {
    angular.module("TodoApp").controller("TodoController", TodoController);

    function TodoController($http, $rootScope, $mdToast, $filter, $localStorage, $scope, todoService) {
        var vm = this;
        vm.errors = [];
        var deregisters = [];
        $http.defaults.transformRequest.push(function (config) {
            vm.loading = true;
            return config;
        });
        $http.defaults.transformResponse.push(function (response) {
            vm.loading = false;
            return response;
        });

        deregisters.push($rootScope.$on("todosChanged", reloadTodoList));
        deregisters.push($rootScope.$on("errorResponse", handleError));
        $scope.$on("$destroy", destroyThis);

        vm.loading = false;
        vm.items = [];

        vm.sortableOptions = {
            placeholder: "app",
            activate: function (x, y) {
                y.item.addClass("dragging");
            },
            deactivate: function (x, y) {
                y.item.removeClass("dragging");
            }
        };

        vm.submitForm = function () {
            /** @namespace vm.newTodoForm */
            if (vm.newTodoForm.$valid) {
                todoService.createTodo(vm.newTodo);
                vm.newTodo = "";
            }
        };

        vm.todoUpdated = function (todo) {
            todoService.updateTodo(todo);
        };

        vm.todoDeleted = function (todo) {
            todoService.deleteTodo(todo.id);
        };

        vm.todoCompleteDeleted = function () {
            $filter("filter")(vm.items, {isComplete: true}).forEach(vm.todoDeleted);
        };

        function getTodoList() {
            if ($localStorage.items !== undefined) {
                vm.items = $localStorage.items;
            }
            reloadTodoList();
        }

        function reloadTodoList() {
            todoService.getTodoList().success(function (data) {
                data.forEach(function (newTodo) {
                    if ($filter("filter")(vm.items, newTodo).length > 0) {
                        //   do nothing, it there and it matches
                    } else if ($filter("filter")(vm.items, {id: newTodo.id}).length > 0) {
                        var oldTodo = $filter("filter")(vm.items, {id: newTodo.id})[0];
                        var index = vm.items.indexOf(oldTodo);
                        vm.items[index] = newTodo;
                    } else {
                        vm.items.push(newTodo);
                    }

                });
                vm.items = vm.items.filter(function (oldTodo) {
                    return $filter("filter")(data, {id: oldTodo.id}).length > 0;
                });

                $localStorage.items = vm.items;
            });
        }

        function handleError(event, text, status) {
            //vm.errors.push("Failed to do action. Server returned " + status + " - " + text);
            var error = "Failed to do action. Server returned " + status + " - " + text;
            $mdToast.show($mdToast.simple().content(error));
        }

        function destroyThis() {
            deregisters.forEach(function (eventDereg) {
                eventDereg();
            });
        }

        vm.onDropComplete = function (index, obj) {
            var otherObj = vm.items[index];
            var otherIndex = vm.items.indexOf(obj);
            vm.items[index] = obj;
            vm.items[otherIndex] = otherObj;
        };
        getTodoList();
    }
})();
<|endoftext|>


<commit_before>/**
 * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
 * This file is licensed under the terms of the MIT License (see LICENSE.md).
 */

import BalloonBlockEditorBase from '@ckeditor/ckeditor5-editor-balloon/src/ballooneditor';
import Alignment from '@ckeditor/ckeditor5-alignment/src/alignment';
import Autoformat from '@ckeditor/ckeditor5-autoformat/src/autoformat';
import BlockQuote from '@ckeditor/ckeditor5-block-quote/src/blockquote';
import Bold from '@ckeditor/ckeditor5-basic-styles/src/bold';
import CKFinder from '@ckeditor/ckeditor5-ckfinder/src/ckfinder';
import EasyImage from '@ckeditor/ckeditor5-easy-image/src/easyimage';
import Essentials from '@ckeditor/ckeditor5-essentials/src/essentials';
import FontFamily from '@ckeditor/ckeditor5-font/src/fontfamily';
import FontSize from '@ckeditor/ckeditor5-font/src/fontsize';
import Heading from '@ckeditor/ckeditor5-heading/src/heading';
import Highlight from '@ckeditor/ckeditor5-highlight/src/highlight';
import Image from '@ckeditor/ckeditor5-image/src/image';
import ImageCaption from '@ckeditor/ckeditor5-image/src/imagecaption';
import ImageStyle from '@ckeditor/ckeditor5-image/src/imagestyle';
import ImageToolbar from '@ckeditor/ckeditor5-image/src/imagetoolbar';
import ImageUpload from '@ckeditor/ckeditor5-image/src/imageupload';
import Italic from '@ckeditor/ckeditor5-basic-styles/src/italic';
import Link from '@ckeditor/ckeditor5-link/src/link';
import List from '@ckeditor/ckeditor5-list/src/list';
// import MediaEmbed from '@ckeditor/ckeditor5-media-embed/src/mediaembed';
import Paragraph from '@ckeditor/ckeditor5-paragraph/src/paragraph';
import PasteFromOffice from '@ckeditor/ckeditor5-paste-from-office/src/pastefromoffice';
import PresenceList from '@ckeditor/ckeditor5-real-time-collaboration/src/presencelist';
import RealTimeCollaborativeComments from '@ckeditor/ckeditor5-real-time-collaboration/src/realtimecollaborativecomments';
import RealTimeCollaborativeTrackChanges from '@ckeditor/ckeditor5-real-time-collaboration/src/realtimecollaborativetrackchanges';
import RemoveFormat from '@ckeditor/ckeditor5-remove-format/src/removeformat';
import Strikethrough from '@ckeditor/ckeditor5-basic-styles/src/strikethrough';
// import Table from '@ckeditor/ckeditor5-table/src/table';
// import TableToolbar from '@ckeditor/ckeditor5-table/src/tabletoolbar';
import Underline from '@ckeditor/ckeditor5-basic-styles/src/underline';
import UploadAdapter from '@ckeditor/ckeditor5-adapter-ckfinder/src/uploadadapter';
import BlockToolbar from '@ckeditor/ckeditor5-ui/src/toolbar/block/blocktoolbar';
import Autosave from '@ckeditor/ckeditor5-autosave/src/autosave'

import MathpreviewPlugin from 'ckeditor5-math-preview/src/mathpreview';

class CommentEditor extends BalloonBlockEditorBase {}
class PostEditor extends BalloonBlockEditorBase {}
class PostEditorCollaboration extends BalloonBlockEditorBase {}

// Tables and MediaEmbeds are commented out for now, but will be added back in as soon as some minor
// minor issues are debugged.

// NOTE: If you make changes to this file, you must:
// 1. navigate in your terminal to the corresponding folder ('cd ./public/lesswrong-editor')
// 2. 'yarn run build'
// 3. navigate back to main folder (i.e. 'cd ../..')
// 4. run 'yarn add ./public/lesswrong-editor'.

const postEditorPlugins = [
	Autosave,
	Alignment,
	Autoformat,
	BlockToolbar,
	BlockQuote,
	Bold,
	CKFinder,
	EasyImage,
	Essentials,
	FontFamily,
	FontSize,
	Heading,
	Highlight,
	Image,
	ImageCaption,
	ImageStyle,
	ImageToolbar,
  ImageUpload,
	Italic,
	Link,
	List,
	// MediaEmbed,
	Paragraph,
	PasteFromOffice,
	RemoveFormat,
	Strikethrough,
	// Table,
	// TableToolbar,
	Underline,
	UploadAdapter,
	MathpreviewPlugin
];

PostEditor.builtinPlugins = [
  ...postEditorPlugins
];

PostEditorCollaboration.builtinPlugins = [
  ...postEditorPlugins,
	RealTimeCollaborativeComments,
  RealTimeCollaborativeTrackChanges,
  PresenceList
];

const postEditorConfig = {
	blockToolbar: [
		'heading',
		'|',
		'bulletedList',
		'numberedList',
		'imageUpload',
		'blockQuote',
		// 'insertTable',         these don't work yet, although I aim to fix them soon – Ray
		// 'mediaEmbed',
		'|',
		'undo',
		'redo',
		'|',
		'trackChanges'
	],
	toolbar: [
		'bold',
		'italic',
		'underline',
		'strikethrough',
		'highlight',
		'|',
		'alignment',
		'|',
		'link',
		'|',
    'mathpreview',
    'comment',
	],
	image: {
		toolbar: [
      // 'imageStyle:alignLeft',
      // 'imageStyle:alignCenter',
      // 'imageStyle:alignRight',
      'imageTextAlternative',
			'comment',
    ],
    // styles: [ 'full', 'alignLeft', 'alignCenter', 'alignRight', ]
	},
	// table: {
	// 	contentToolbar: [
	// 		'tableColumn',
	// 		'tableRow',
	// 		'mergeTableCells'
	// 	],
	// 	tableToolbar: [ 'comment' ]
	// },
	// mediaEmbed: {
	// 	toolbar: [ 'comment' ]
	// },
};

PostEditor.defaultConfig = {
  ...postEditorConfig
};

PostEditorCollaboration.defaultConfig = {
  ...postEditorConfig
};

CommentEditor.builtinPlugins = [
	Autosave,
	Alignment,
	Autoformat,
	BlockQuote,
	Bold,
	CKFinder,
	EasyImage,
	Essentials,
	Heading,
	Image,
	ImageCaption,
  ImageStyle,
	ImageToolbar,
	ImageUpload,
	Italic,
	Link,
	List,
	Paragraph,
	PasteFromOffice,
	RemoveFormat,
	Strikethrough,
	// Table,
	Underline,
	UploadAdapter,
	MathpreviewPlugin
];

CommentEditor.defaultConfig = {
	toolbar: [
    'heading',
		'bold',
		'italic',
    'underline',
		'|',
		'bulletedList',
		'numberedList',
		'blockQuote',
		'|',
		'link',
		'|',
		'mathpreview'
	],
	image: {
		toolbar: [
			'imageTextAlternative'
		]
	},
	// table: {
	// 	contentToolbar: [
	// 		'tableColumn',
	// 		'tableRow',
	// 		'mergeTableCells'
	// 	],
	// 	tableToolbar: [ 'comment' ]
	// },
};

export const Editors = { CommentEditor, PostEditor, PostEditorCollaboration };
<commit_msg>remove imageStyle<commit_after>/**
 * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
 * This file is licensed under the terms of the MIT License (see LICENSE.md).
 */

import BalloonBlockEditorBase from '@ckeditor/ckeditor5-editor-balloon/src/ballooneditor';
import Alignment from '@ckeditor/ckeditor5-alignment/src/alignment';
import Autoformat from '@ckeditor/ckeditor5-autoformat/src/autoformat';
import BlockQuote from '@ckeditor/ckeditor5-block-quote/src/blockquote';
import Bold from '@ckeditor/ckeditor5-basic-styles/src/bold';
import CKFinder from '@ckeditor/ckeditor5-ckfinder/src/ckfinder';
import EasyImage from '@ckeditor/ckeditor5-easy-image/src/easyimage';
import Essentials from '@ckeditor/ckeditor5-essentials/src/essentials';
import FontFamily from '@ckeditor/ckeditor5-font/src/fontfamily';
import FontSize from '@ckeditor/ckeditor5-font/src/fontsize';
import Heading from '@ckeditor/ckeditor5-heading/src/heading';
import Highlight from '@ckeditor/ckeditor5-highlight/src/highlight';
import Image from '@ckeditor/ckeditor5-image/src/image';
import ImageCaption from '@ckeditor/ckeditor5-image/src/imagecaption';
import ImageStyle from '@ckeditor/ckeditor5-image/src/imagestyle';
import ImageToolbar from '@ckeditor/ckeditor5-image/src/imagetoolbar';
import ImageUpload from '@ckeditor/ckeditor5-image/src/imageupload';
import Italic from '@ckeditor/ckeditor5-basic-styles/src/italic';
import Link from '@ckeditor/ckeditor5-link/src/link';
import List from '@ckeditor/ckeditor5-list/src/list';
// import MediaEmbed from '@ckeditor/ckeditor5-media-embed/src/mediaembed';
import Paragraph from '@ckeditor/ckeditor5-paragraph/src/paragraph';
import PasteFromOffice from '@ckeditor/ckeditor5-paste-from-office/src/pastefromoffice';
import PresenceList from '@ckeditor/ckeditor5-real-time-collaboration/src/presencelist';
import RealTimeCollaborativeComments from '@ckeditor/ckeditor5-real-time-collaboration/src/realtimecollaborativecomments';
import RealTimeCollaborativeTrackChanges from '@ckeditor/ckeditor5-real-time-collaboration/src/realtimecollaborativetrackchanges';
import RemoveFormat from '@ckeditor/ckeditor5-remove-format/src/removeformat';
import Strikethrough from '@ckeditor/ckeditor5-basic-styles/src/strikethrough';
// import Table from '@ckeditor/ckeditor5-table/src/table';
// import TableToolbar from '@ckeditor/ckeditor5-table/src/tabletoolbar';
import Underline from '@ckeditor/ckeditor5-basic-styles/src/underline';
import UploadAdapter from '@ckeditor/ckeditor5-adapter-ckfinder/src/uploadadapter';
import BlockToolbar from '@ckeditor/ckeditor5-ui/src/toolbar/block/blocktoolbar';
import Autosave from '@ckeditor/ckeditor5-autosave/src/autosave'

import MathpreviewPlugin from 'ckeditor5-math-preview/src/mathpreview';

class CommentEditor extends BalloonBlockEditorBase {}
class PostEditor extends BalloonBlockEditorBase {}
class PostEditorCollaboration extends BalloonBlockEditorBase {}

// Tables and MediaEmbeds are commented out for now, but will be added back in as soon as some minor
// minor issues are debugged.

// NOTE: If you make changes to this file, you must:
// 1. navigate in your terminal to the corresponding folder ('cd ./public/lesswrong-editor')
// 2. 'yarn run build'
// 3. navigate back to main folder (i.e. 'cd ../..')
// 4. run 'yarn add ./public/lesswrong-editor'.

const postEditorPlugins = [
	Autosave,
	Alignment,
	Autoformat,
	BlockToolbar,
	BlockQuote,
	Bold,
	CKFinder,
	EasyImage,
	Essentials,
	FontFamily,
	FontSize,
	Heading,
	Highlight,
	Image,
	ImageCaption,
	ImageStyle,
	ImageToolbar,
  ImageUpload,
	Italic,
	Link,
	List,
	// MediaEmbed,
	Paragraph,
	PasteFromOffice,
	RemoveFormat,
	Strikethrough,
	// Table,
	// TableToolbar,
	Underline,
	UploadAdapter,
	MathpreviewPlugin
];

PostEditor.builtinPlugins = [
  ...postEditorPlugins
];

PostEditorCollaboration.builtinPlugins = [
  ...postEditorPlugins,
	RealTimeCollaborativeComments,
  RealTimeCollaborativeTrackChanges,
  PresenceList
];

const postEditorConfig = {
	blockToolbar: [
		'heading',
		'|',
		'bulletedList',
		'numberedList',
		'imageUpload',
		'blockQuote',
		// 'insertTable',         these don't work yet, although I aim to fix them soon – Ray
		// 'mediaEmbed',
		'|',
		'undo',
		'redo',
		'|',
		'trackChanges'
	],
	toolbar: [
		'bold',
		'italic',
		'underline',
		'strikethrough',
		'highlight',
		'|',
		'alignment',
		'|',
		'link',
		'|',
    'mathpreview',
    'comment',
	],
	image: {
		toolbar: [
      'imageTextAlternative',
			'comment',
    ],
	},
	// table: {
	// 	contentToolbar: [
	// 		'tableColumn',
	// 		'tableRow',
	// 		'mergeTableCells'
	// 	],
	// 	tableToolbar: [ 'comment' ]
	// },
	// mediaEmbed: {
	// 	toolbar: [ 'comment' ]
	// },
};

PostEditor.defaultConfig = {
  ...postEditorConfig
};

PostEditorCollaboration.defaultConfig = {
  ...postEditorConfig
};

CommentEditor.builtinPlugins = [
	Autosave,
	Alignment,
	Autoformat,
	BlockQuote,
	Bold,
	CKFinder,
	EasyImage,
	Essentials,
	Heading,
	Image,
	ImageCaption,
  ImageStyle,
	ImageToolbar,
	ImageUpload,
	Italic,
	Link,
	List,
	Paragraph,
	PasteFromOffice,
	RemoveFormat,
	Strikethrough,
	// Table,
	Underline,
	UploadAdapter,
	MathpreviewPlugin
];

CommentEditor.defaultConfig = {
	toolbar: [
    'heading',
		'bold',
		'italic',
    'underline',
		'|',
		'bulletedList',
		'numberedList',
		'blockQuote',
		'|',
		'link',
		'|',
		'mathpreview'
	],
	image: {
		toolbar: [
			'imageTextAlternative'
		]
	},
	// table: {
	// 	contentToolbar: [
	// 		'tableColumn',
	// 		'tableRow',
	// 		'mergeTableCells'
	// 	],
	// 	tableToolbar: [ 'comment' ]
	// },
};

export const Editors = { CommentEditor, PostEditor, PostEditorCollaboration };
<|endoftext|>


<commit_before>/* eslint-disable no-console */
/* global it describe Nightmare */
module.exports.test = function meh(uitestctx) {
  describe('Module test: users:new_user', function bar() {
    const { config, helpers: { namegen, openApp }, meta: { testVersion } } = uitestctx;

    this.timeout(Number(config.test_timeout));
    const nightmare = new Nightmare(config.nightmare);

    let pgroup = null;
    const user = namegen();

    describe('Login > Create new user > Logout > Login as new user > Logout > Login > Edit new user and confirm changes', () => {
      const flogin = function buh(un, pw) {
        it(`should login as ${un}/${pw}`, (done) => {
          nightmare
            .wait(config.select.username)
            .insert(config.select.username, un)
            .insert(config.select.password, pw)
            .click('#clickable-login')
            .wait(555)
            .wait(() => {
              let rvalue = false;
              const success = document.querySelector('#clickable-logout');
              const fail = document.querySelector('span[class^="loginError"]');
              if (fail) {
                throw new Error(fail.textContent);
              } else if (success) {
                rvalue = true;
              }
              return rvalue;
            })
            .wait(555)
            .then(() => { done(); })
            .catch(done);
        });
      };
      const flogout = function sma() {
        it('should logout', (done) => {
          nightmare
            .click('#clickable-logout')
            .wait('#clickable-login')
            .wait(parseInt(process.env.FOLIO_UI_DEBUG, 10) ? parseInt(config.debug_sleep, 10) : 555) // debugging
            .then(() => { done(); })
            .catch(done);
        });
      };

      it('should load login page', (done) => {
        nightmare
          .on('page', (type = 'alert', message) => {
            throw new Error(message);
          })
          .goto(config.url)
          .wait(Number(config.login_wait))
          .then(() => { done(); })
          .catch(done);
      });

      flogin(config.username, config.password);

      it('should open app and find version tag', (done) => {
        nightmare
          .use(openApp(nightmare, config, done, 'users', testVersion))
          .then(result => result);
      });
      it('should extract a patron group value', (done) => {
        nightmare
          .wait('#clickable-users-module')
          .click('#clickable-users-module')
          .wait('#clickable-newuser')
          .wait(555)
          .click('#clickable-newuser')
          .wait('#adduser_group > option:nth-of-type(3)')
          .evaluate(() => document.querySelector('#adduser_group > option:nth-of-type(3)').value)
          .then((result) => {
            pgroup = result;
            done();
          })
          .catch(done);
      });
      it(`should create a user: ${user.id}/${user.password}`, (done) => {
        nightmare
          .insert('#adduser_username', user.id)
          .insert('#pw', user.password)
          .select('#useractive', 'true')
          .insert('#adduser_firstname', user.firstname)
          .insert('#adduser_lastname', user.lastname)
          .insert('#adduser_email', user.email)
          .insert('#adduser_dateofbirth', '1980-05-04')
          .select('#adduser_group', pgroup)
          .insert('#adduser_enrollmentdate', '2017-01-01')
          .insert('#adduser_expirationdate', '2020-01-01')
          .insert('#adduser_barcode', user.barcode)
          .xclick('id("form-user")//button[contains(.,"New")]')
          .wait(555)
          .click('input[id^="PrimaryAddress"]')
          .insert('input[name="Country"]', user.address.country)
          .insert('input[name*="addressLine1"]', user.address.address)
          .insert('input[name*="city"]', user.address.city)
          .insert('input[name*="stateRegion"]', user.address.state)
          .insert('input[name*="zipCode"]', user.address.zip)
          .select('select[name*="addressType"]', 'Home')
          .click('#clickable-createnewuser')
          .wait('#clickable-newuser')
          .wait(parseInt(process.env.FOLIO_UI_DEBUG, 10) ? parseInt(config.debug_sleep, 10) : 3000) // debugging
          .then(() => { done(); })
          .catch(done);
      });
      flogout();
      flogin(user.id, user.password);
      flogout();
      flogin(config.username, config.password);
      it(`should change username for ${user.id}`, (done) => {
        nightmare
          .wait('#clickable-users-module')
          .click('#clickable-users-module')
          .wait('#input-user-search')
          .insert('#input-user-search', user.id)
          .wait(`div[title="${user.id}"]`)
          .click(`div[title="${user.id}"]`)
          .wait('#clickable-edituser')
          .click('#clickable-edituser')
          .wait('#adduser_username')
          .wait(555)
          .click('#adduser_username')
          .type('#adduser_username', null)
          .wait(555)
          .insert('#adduser_username', `${user.id}x`)
          .select('#adduser_group', pgroup)
          .wait(555)
          .click('#clickable-updateuser')
          .wait(555)
          .wait((uid) => {
            let rvalue = false;
            const xp = document.evaluate(`//div[.="${uid}"]`, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
            if (xp.singleNodeValue !== null) {
              rvalue = true;
            }
            return rvalue;
          }, `${user.id}x`)
          .wait(parseInt(process.env.FOLIO_UI_DEBUG, 10) ? parseInt(config.debug_sleep, 10) : 555) // debugging
          .then(() => { done(); })
          .catch(done);
      });
      flogout();
      it(`Should login as ${user.id}x/${user.password}`, (done) => {
        nightmare
          .wait('#input-username')
          .wait(222)
          .insert('#input-username', `${user.id}x`)
          .insert('#input-password', user.password)
          .click('#clickable-login')
          .wait('#clickable-logout')
          .click('#clickable-logout')
          .wait(parseInt(process.env.FOLIO_UI_DEBUG, 10) ? parseInt(config.debug_sleep, 10) : 555) // debugging
          .end()
          .then(() => { done(); })
          .catch(done);
      });
    });
  });
};
<commit_msg>Cleanup<commit_after>/* eslint-disable no-console */
/* global it describe Nightmare */
module.exports.test = function meh(uitestctx) {
  describe('Module test: users:new_user', function bar() {
    const { config, helpers: { namegen, openApp }, meta: { testVersion } } = uitestctx;

    this.timeout(Number(config.test_timeout));
    const nightmare = new Nightmare(config.nightmare);

    let pgroup = null;
    const user = namegen();

    describe('Login > Create new user > Logout > Login as new user > Logout > Login > Edit new user and confirm changes', () => {
      const flogin = function buh(un, pw) {
        it(`should login as ${un}/${pw}`, (done) => {
          nightmare
            .wait(config.select.username)
            .insert(config.select.username, un)
            .insert(config.select.password, pw)
            .click('#clickable-login')
            .wait(555)
            .wait(() => {
              let rvalue = false;
              const success = document.querySelector('#clickable-logout');
              const fail = document.querySelector('span[class^="loginError"]');
              if (fail) {
                throw new Error(fail.textContent);
              } else if (success) {
                rvalue = true;
              }
              return rvalue;
            })
            .wait(555)
            .then(() => { done(); })
            .catch(done);
        });
      };
      const flogout = function sma() {
        it('should logout', (done) => {
          nightmare
            .click('#clickable-logout')
            .wait('#clickable-login')
            .wait(parseInt(process.env.FOLIO_UI_DEBUG, 10) ? parseInt(config.debug_sleep, 10) : 555) // debugging
            .then(() => { done(); })
            .catch(done);
        });
      };

      it('should load login page', (done) => {
        nightmare
          .on('page', (type, message) => {
            throw new Error(message);
          })
          .goto(config.url)
          .wait(Number(config.login_wait))
          .then(() => { done(); })
          .catch(done);
      });

      flogin(config.username, config.password);

      it('should open app and find version tag', (done) => {
        nightmare
          .use(openApp(nightmare, config, done, 'users', testVersion))
          .then(result => result);
      });
      it('should extract a patron group value', (done) => {
        nightmare
          .wait('#clickable-users-module')
          .click('#clickable-users-module')
          .wait('#clickable-newuser')
          .wait(555)
          .click('#clickable-newuser')
          .wait('#adduser_group > option:nth-of-type(3)')
          .evaluate(() => document.querySelector('#adduser_group > option:nth-of-type(3)').value)
          .then((result) => {
            pgroup = result;
            done();
          })
          .catch(done);
      });
      it(`should create a user: ${user.id}/${user.password}`, (done) => {
        nightmare
          .insert('#adduser_username', user.id)
          .insert('#pw', user.password)
          .select('#useractive', 'true')
          .insert('#adduser_firstname', user.firstname)
          .insert('#adduser_lastname', user.lastname)
          .insert('#adduser_email', user.email)
          .insert('#adduser_dateofbirth', '1980-05-04')
          .select('#adduser_group', pgroup)
          .insert('#adduser_enrollmentdate', '2017-01-01')
          .insert('#adduser_expirationdate', '2020-01-01')
          .insert('#adduser_barcode', user.barcode)
          .xclick('id("form-user")//button[contains(.,"New")]')
          .wait(555)
          .click('input[id^="PrimaryAddress"]')
          .insert('input[name="Country"]', user.address.country)
          .insert('input[name*="addressLine1"]', user.address.address)
          .insert('input[name*="city"]', user.address.city)
          .insert('input[name*="stateRegion"]', user.address.state)
          .insert('input[name*="zipCode"]', user.address.zip)
          .select('select[name*="addressType"]', 'Home')
          .click('#clickable-createnewuser')
          .wait('#clickable-newuser')
          .wait(parseInt(process.env.FOLIO_UI_DEBUG, 10) ? parseInt(config.debug_sleep, 10) : 3000) // debugging
          .then(() => { done(); })
          .catch(done);
      });
      flogout();
      flogin(user.id, user.password);
      flogout();
      flogin(config.username, config.password);
      it(`should change username for ${user.id}`, (done) => {
        nightmare
          .wait('#clickable-users-module')
          .click('#clickable-users-module')
          .wait('#input-user-search')
          .insert('#input-user-search', user.id)
          .wait(`div[title="${user.id}"]`)
          .click(`div[title="${user.id}"]`)
          .wait('#clickable-edituser')
          .click('#clickable-edituser')
          .wait('#adduser_username')
          .wait(555)
          .click('#adduser_username')
          .type('#adduser_username', null)
          .wait(555)
          .insert('#adduser_username', `${user.id}x`)
          .select('#adduser_group', pgroup)
          .wait(555)
          .click('#clickable-updateuser')
          .wait(555)
          .wait((uid) => {
            let rvalue = false;
            const xp = document.evaluate(`//div[.="${uid}"]`, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
            if (xp.singleNodeValue !== null) {
              rvalue = true;
            }
            return rvalue;
          }, `${user.id}x`)
          .wait(parseInt(process.env.FOLIO_UI_DEBUG, 10) ? parseInt(config.debug_sleep, 10) : 555) // debugging
          .then(() => { done(); })
          .catch(done);
      });
      flogout();
      it(`Should login as ${user.id}x/${user.password}`, (done) => {
        nightmare
          .wait('#input-username')
          .wait(222)
          .insert('#input-username', `${user.id}x`)
          .insert('#input-password', user.password)
          .click('#clickable-login')
          .wait('#clickable-logout')
          .click('#clickable-logout')
          .wait(parseInt(process.env.FOLIO_UI_DEBUG, 10) ? parseInt(config.debug_sleep, 10) : 555) // debugging
          .end()
          .then(() => { done(); })
          .catch(done);
      });
    });
  });
};
<|endoftext|>


<commit_before><commit_msg>Futher change to subscription script<commit_after><|endoftext|>


<commit_before>function readTitle(title) {
	speakEnglish("This is article " + title + " in Wikipedia.");
}

readTitle("Bicycle");

var autoNext = true;

var curid = 0; // current paragraph.

// nextId returns the next id of the reading paragraph.
function getId(node) {
	id = $(node).attr("id").substring(2);
	return parseInt(id);
}

function speakParaWithId(id) {
	speakPara($("#p-" + id.toString()));
}

var scrollToElement = function(node, ms){
    var speed = (ms) ? ms : 600;
    $('html,body').animate({
        scrollTop: node.offset().top - 100
    }, speed);
}

// Speak paragraph #id.
function speakPara(node) {
	if (typeof node == "undefined") {
		return
	}
	scrollToElement(node, 600);
	$("p").css("color", "#444");
	curid = getId(node);
	play();

	console.log("Paragraph: " + curid);
	node.css("color", "red");
	// console.log($me.text());
	cancelSpeak();
	speakParagraph(node.text(), function (event) {
		pause();
		node.css("color", "#444");
		console.log("DONE!");
		console.log(autoNext);
		if (autoNext) {
			curid++;
			speakPara($("#p-" + curid.toString()));
		}
	});
}

var elPlay = $("#icon-play");

elPlay.click(function (event) {
	if (elPlay.hasClass("fa-play")) {
		play();
		speakParaWithId(curid);
	} else {
		doStop();
	}
});

function play() {
	elPlay.removeClass("fa-play");
	elPlay.addClass("fa-pause");
}

function pause() {
	elPlay.removeClass("fa-pause");
	elPlay.addClass("fa-play");
}

// ACTIONS
function doNext() {
	curid ++;
	speakParaWithId(curid);
}

function doPrev() {
	if (curid > 0) {
		curid--;
		speakParaWithId(curid);
	}
}

function doStop() {
	console.log("STOP");
	pause();
	cancelSpeak();
}

function doStart() {
	play();
	speakParaWithId(curid);
}

function doSearch(term) {
	para = "You want to search for " + term + "." +
		" Found an article. Do you want to hear this?.";
	// writelog(para);
	speakParagraph(para);
}

function initAnnyang() {
	if (annyang) {

	  // Let's define our first command. First the text we expect, and then the function it should call
	  var commands = {
	  	'show me *entry': doSearch,
	  	// 'list': search,
	  	//'help': help,
	  	// 'help me': help
	  	"next": doNext,
	  	"back": doPrev,
	  	"stop": doStop,
	  	"start": doStart,
	  };
	  // Add our commands to annyang
	  annyang.addCommands(commands);

	  // Start listening. You can call this here, or attach this call to an event, button, etc.
	  annyang.start();
	}
}

function goHome() {
	window.location = "/";
}

function no() {
	console.log("NO");
}

function yes() {
	console.log("YES");
}

function initGestures() {
	console.log("Init gestures");
	var gestures = new Array();
	// gestures["L"] = "46";

	gestures["H"] = "267012";
	// gestures["?"] = "6701232";
	gestures["P"] = "670123456";

	gestures["N"] = "616";
	gestures["Y"] = "21076234567";
	gestures["S"] = "432101234";

	$('body').gestures(gestures, function (data) {
		// document.getElementById('outputbox').innerHTML += data;
		// document.getElementById('outputbox').innerHTML = data;
		console.log("GESTURE");
		if (data !== "") {
			console.log(data);
			// speakEnglish(data);
			switch(data) {
			    case "H":
			        goHome();
			        break;

			     case "S":
			        doStart();
			        break;

			     case "P":
			        doStop();
			        break;

			    case "N":
			        no();
			        break;
			    case "Y":
			        yes();
			        break;

			    default:
			}
		}
	});
}

function initPad() {
	// setup a new canvas for drawing wait for device init
   	//  setTimeout(function(){
	// newCanvas();
	$(".content").pad("#8e44ad");
    // }, 1000);
}

function init() {
	initAnnyang();
	initGestures();
	initPad();
}

$("p").click(function (event) {
	speakPara($(this));
});

init();
speakParaWithId(curid);
<commit_msg>Add some voice commands<commit_after>function readTitle(title) {
	speakEnglish("This is article " + title + " in Wikipedia.");
}

readTitle("Bicycle");

var autoNext = true;

var curid = 0; // current paragraph.

// nextId returns the next id of the reading paragraph.
function getId(node) {
	id = $(node).attr("id").substring(2);
	return parseInt(id);
}

function speakParaWithId(id) {
	speakPara($("#p-" + id.toString()));
}

var scrollToElement = function(node, ms){
    var speed = (ms) ? ms : 600;
    $('html,body').animate({
        scrollTop: node.offset().top - 100
    }, speed);
}

// Speak paragraph #id.
function speakPara(node) {
	if (typeof node == "undefined") {
		return
	}
	scrollToElement(node, 600);
	$("p").css("color", "#444");
	curid = getId(node);
	play();

	console.log("Paragraph: " + curid);
	node.css("color", "red");
	// console.log($me.text());
	cancelSpeak();
	speakParagraph(node.text(), function (event) {
		pause();
		node.css("color", "#444");
		console.log("DONE!");
		console.log(autoNext);
		if (autoNext) {
			curid++;
			speakPara($("#p-" + curid.toString()));
		}
	});
}

var elPlay = $("#icon-play");

elPlay.click(function (event) {
	if (elPlay.hasClass("fa-play")) {
		play();
		speakParaWithId(curid);
	} else {
		doStop();
	}
});

function play() {
	elPlay.removeClass("fa-play");
	elPlay.addClass("fa-pause");
}

function pause() {
	elPlay.removeClass("fa-pause");
	elPlay.addClass("fa-play");
}

// ACTIONS
function doNext() {
	curid ++;
	speakParaWithId(curid);
}

function doPrev() {
	if (curid > 0) {
		curid--;
		speakParaWithId(curid);
	}
}

function doStop() {
	console.log("STOP");
	pause();
	cancelSpeak();
}

function doStart() {
	play();
	speakParaWithId(curid);
}

function doSearch(term) {
	para = "You want to search for " + term + "." +
		" Found an article. Do you want to hear this?.";
	// writelog(para);
	speakParagraph(para);
}

function initAnnyang() {
	if (annyang) {

	  // Let's define our first command. First the text we expect, and then the function it should call
	  var commands = {
	  	'show me *entry': doSearch,
	  	// 'list': search,
	  	//'help': help,
	  	// 'help me': help
	  	"next": doNext,
	  	"back": doPrev,
	  	"stop": doStop,
	  	"start": doStart,
	  };
	  // Add our commands to annyang
	  annyang.addCommands(commands);

	  // Start listening. You can call this here, or attach this call to an event, button, etc.
	  annyang.start();
	}
}

function goHome() {
	cancelSpeak();
	window.location = "/";
}

function no() {
	console.log("NO");
}

function yes() {
	console.log("YES");
}

function initGestures() {
	console.log("Init gestures");
	var gestures = new Array();
	// gestures["L"] = "46";

	gestures["H"] = "267012";
	// gestures["?"] = "6701232";
	gestures["P"] = "670123456";

	gestures["N"] = "616";
	gestures["B"] = "260123401234";
	// gestures["Y"] = "21076234567";
	gestures["S"] = "432101234";

	$('body').gestures(gestures, function (data) {
		// document.getElementById('outputbox').innerHTML += data;
		// document.getElementById('outputbox').innerHTML = data;
		console.log("GESTURE");
		if (data !== "") {
			console.log(data);
			// speakEnglish(data);
			switch(data) {
			    case "H":
			        goHome();
			        break;

			     case "S":
			        doStart();
			        break;

			     case "P":
			        doStop();
			        break;

			    case "N":
			        doNext();
			        break;
			    case "B":
			        doPrev();
			        break;

			    default:
			}
		}
	});
}

function initPad() {
	// setup a new canvas for drawing wait for device init
   	//  setTimeout(function(){
	// newCanvas();
	$(".content").pad("#8e44ad");
    // }, 1000);
}

function init() {
	initAnnyang();
	initGestures();
	initPad();
}

$("p").click(function (event) {
	speakPara($(this));
});

init();
speakParaWithId(curid);
<|endoftext|>