<commit_before>function Character(_character) {
    Component.call(this, _character);
    try {
        this.setMaxHealth(_character.maxHealth);
        this.setHealth(_character.health); //percentage of maxHealth (0 to 100)
        this.setDamage(_character.damage);
        this.healBar;
        this.move = {
            right: false,
            left: false,
            up: false,
            down: false
        };
        this.isDead = false;
    } catch (e) {
        throw (e);
    }
    this.start();
}

Character.prototype = Object.create(Component.prototype);

Character.prototype.setMaxHealth = function (value = 100) {
    this.maxHealth = value;
    //CANNOT BE NEGATIVE
};

Character.prototype.setHealth = function (value = 100) {
    this.health = value;
    //CANNOT BE NEGATIVE
};

Character.prototype.setDamage = function (value = 0) {
    this.damage = value;
    //CANNOT BE NEGATIVE
};

Character.prototype.kill = function () {
    this.healBar.maxHealth.destroy();
    this.healBar.health.destroy();
    this.healBar.damage.destroy();
    this.figure.destroy();
    this.isDead = true;
    delete this.healBar;
};

Character.prototype.receiveDamage = function (damage) {
    this.damage = this.damage + damage;
    this.health = ((this.maxHealth - this.damage) * 100) / this.maxHealth;
    this.healBar.health.w = 96 * this.health / 100; //96 is the initial width of the healbar;
    if ((96 * this.health / 100) <= 0) {
        this.healBar.health.color('rgba (0,0,0,0)');
        this.kill();
    }
};

Character.prototype.start = function () {
    this.healBar = new HealBar(this);
    this.isDead = false;
    this.figure = Crafty.e(this.reference + ', 2D, Canvas' /*, Color,*/ + ', Gravity, Collision, balotelliRun, SpriteAnimation')
        .attr({
            x: 100,
            y: 100,
            w: this.width,
            h: this.height
        })
        /*.color(this.color)*/
        .gravity('Floor')
        .collision()
        .reel('running', 500, [
            [0, 0],
            [1, 0],
            [2, 0],
            [3, 0],
            [4, 0],
            [5, 0],
            [6, 0],
            [7, 0],
            [8, 0],
            [9, 0]
        ]) // setup animation
        .animate('running', -1).bind('KeyDown', (e) => {
            // Default movement booleans to false
            this.move.right = this.move.left = this.move.down = this.move.up = false;
            // If keys are down, set the direction
            if (e.key == Crafty.keys.RIGHT_ARROW || e.key == Crafty.keys.D) {
                this.move.right = true;
            }
            if (e.key == Crafty.keys.LEFT_ARROW || e.key == Crafty.keys.A) {
                this.move.left = true;
            }
            if (e.keyCode === Crafty.keys.UA) this.move.up = true;
            if (e.keyCode === Crafty.keys.DA) this.move.down = true;
        })
        .bind('Moved', (from) => {
            this.healBar.maxHealth.x = this.figure.x - this.figure.w / 2;
            this.healBar.maxHealth.y = this.figure.y - this.figure.h + 30;
            this.healBar.health.x = this.healBar.maxHealth.x + 2;
            this.healBar.health.y = this.healBar.maxHealth.y + 2;
            this.healBar.damage.x = this.healBar.maxHealth.x + 2;
            this.healBar.damage.y = this.healBar.maxHealth.y + 2;
            if (this.figure.hit("limitLeft")) {
                this.figure.attr({
                    x: 1,
                    y: this.figure.y
                });
                this.figure.flip("X");
            }
            if (this.figure.hit("limitRight")) {
                this.figure.attr({
                    x: 719,
                    y: this.figure.y
                });
                this.figure.unflip("X");
            }
            if (this.figure.hit("LimitTop")) {
                this.figure.attr({
                    x: this.figure.x,
                    y: -1
                });
            }
            if (this.move.right) {
                this.figure.unflip("X");
            }
            if (this.move.left) {
                this.figure.flip("X");
            }
        });
};<commit_msg>Changes in attrs posX and posY of Character class, added Speeds attrs<commit_after>function Character(_character) {
    Component.call(this, _character);
    try {
        this.setSpeed(_character.speed);
        this.setSpeedJump(_character.speedJump);
        this.setMaxHealth(_character.maxHealth);
        this.setHealth(_character.health); //percentage of maxHealth (0 to 100)
        this.setDamage(_character.damage);
        this.healBar;
        this.move = {
            right: false,
            left: false,
            up: false,
            down: false
        };
        this.isDead = false;
    } catch (e) {
        throw (e);
    }
    this.start();
}

Character.prototype = Object.create(Component.prototype);

Character.prototype.setMaxHealth = function (value = 100) {
    this.maxHealth = value;
    //CANNOT BE NEGATIVE
};

Character.prototype.setSpeed = function (value = 100) {
    this.speed = value;
    //CANNOT BE NEGATIVE
};

Character.prototype.setSpeedJump = function (value = 100) {
    this.speedJump = value;
    //CANNOT BE NEGATIVE
};

Character.prototype.setHealth = function (value = 100) {
    this.health = value;
    //CANNOT BE NEGATIVE
};

Character.prototype.setDamage = function (value = 0) {
    this.damage = value;
    //CANNOT BE NEGATIVE
};

Character.prototype.kill = function () {
    this.healBar.maxHealth.destroy();
    this.healBar.health.destroy();
    this.healBar.damage.destroy();
    this.figure.destroy();
    this.isDead = true;
    delete this.healBar;
};

Character.prototype.receiveDamage = function (damage) {
    this.damage = this.damage + damage;
    this.health = ((this.maxHealth - this.damage) * 100) / this.maxHealth;
    this.healBar.health.w = 96 * this.health / 100; //96 is the initial width of the healbar;
    if ((96 * this.health / 100) <= 0) {
        this.healBar.health.color('rgba (0,0,0,0)');
        this.kill();
    }
};

Character.prototype.start = function () {
    this.healBar = new HealBar(this);
    this.isDead = false;
    this.figure = Crafty.e(this.reference + ', 2D, Canvas' /*, Color,*/ + ', Gravity, Collision, balotelliRun, SpriteAnimation')
        .attr({
            x: this.posX,
            y: this.posY,
            w: this.width,
            h: this.height
        })
        /*.color(this.color)*/
        .gravity('Floor')
        .collision()
        .reel('running', 500, [
            [0, 0],
            [1, 0],
            [2, 0],
            [3, 0],
            [4, 0],
            [5, 0],
            [6, 0],
            [7, 0],
            [8, 0],
            [9, 0]
        ]) // setup animation
        .animate('running', -1).bind('KeyDown', (e) => {
            // Default movement booleans to false
            this.move.right = this.move.left = this.move.down = this.move.up = false;
            // If keys are down, set the direction
            if (e.key == Crafty.keys.RIGHT_ARROW || e.key == Crafty.keys.D) {
                this.move.right = true;
            }
            if (e.key == Crafty.keys.LEFT_ARROW || e.key == Crafty.keys.A) {
                this.move.left = true;
            }
            if (e.keyCode === Crafty.keys.UA) this.move.up = true;
            if (e.keyCode === Crafty.keys.DA) this.move.down = true;
        })
        .bind('Moved', (from) => {
            this.posX = this.figure.x;
            this.posY = this.figure.y;
            this.healBar.maxHealth.x = this.figure.x - this.figure.w / 2;
            this.healBar.maxHealth.y = this.figure.y - this.figure.h + 30;
            this.healBar.health.x = this.healBar.maxHealth.x + 2;
            this.healBar.health.y = this.healBar.maxHealth.y + 2;
            this.healBar.damage.x = this.healBar.maxHealth.x + 2;
            this.healBar.damage.y = this.healBar.maxHealth.y + 2;
            if (this.figure.hit("limitLeft")) {
                this.figure.attr({
                    x: 1,
                    y: this.figure.y
                });
            }
            if (this.figure.hit("limitRight")) {
                this.figure.attr({
                    x: 719,
                    y: this.figure.y
                });
            }
            if (this.figure.hit("LimitTop")) {
                this.figure.attr({
                    x: this.figure.x,
                    y: -1
                });
            }
            if (this.move.right) {
                this.figure.unflip("X");
            }
            if (this.move.left) {
                this.figure.flip("X");
            }
        });
};<|endoftext|>


<commit_before>/* global alert */
var $ = require('jquery')

var yo = require('yo-yo')
const copy = require('clipboard-copy')

var parseContracts = require('../contract/contractParser')
var publishOnSwarm = require('../contract/publishOnSwarm')
var modalDialog = require('../ui/modaldialog')

// -------------- styling ----------------------
var csjs = require('csjs-inject')
var remix = require('ethereum-remix')
var styleGuide = remix.ui.styleGuide
var styles = styleGuide()

var css = csjs`
  .compileTabView {
    padding: 2%;
  }
  .contract {
    display: block;
    margin: 3% 0;
  }
  .compileContainer  {
    ${styles.displayBox}
    margin-bottom: 2%;
  }
  .autocompileContainer {
    width: 90px;
    display: flex;
    align-items: center;
  }
  .autocompile {}
  .autocompileTitle {
    font-weight: bold;
    margin: 1% 0;
  }
  .autocompileText {
    margin: 1% 0;
    font-size: 12px;
    overflow: hidden;
    word-break: normal;
    line-height: initial;
  }
  .warnCompilationSlow {
    color: ${styles.colors.orange};
    margin-left: 1%;
  }
  .compileButtons {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
  }
  .name {
    display: flex;
  }
  .size {
    display: flex;
  }
  .compileButton {
    ${styles.button}
    width: 120px;
    min-width: 110px;
    margin-right: 1%;
    font-size: 12px;
  }
  .container {
    ${styles.displayBox}
    margin: 0;
    display: flex;
    align-items: center;
  }
  .contractNames {
    ${styles.dropdown}
    margin-right: 5%;
  }
  .contractButtons {
    display: flex;
    cursor: pointer;
    justify-content: center;
    text-align: center;
  }
  .details {
    ${styles.button}
  }
  .publish {
    ${styles.button}
    margin-left: 2%;
  }
  .log {
    display: flex;
    flex-direction: column;
    align-items: baseline
  }
  .key {
    margin-right: 5px;
    color: grey;
    text-transform: uppercase;
    width: 100%;
  }
  .value {
    display: flex;
    width: 100%;
    margin-top: 1.5%;
  }
  .copyDetails {
    margin-left: 2%;
    font-size: 14px;
    cursor: pointer;
    color: ${styles.colors.grey};
    opacity: .3;
  }
  .copyDetails:hover {
    opacity: 1;
  }
  .detailsJSON {
    padding: 8px 0;
    background-color: ${styles.colors.white};
    border: none;
    color: ${styles.colors.grey};
  }
  .icon {
    margin-right: 3%;
  }
  .spinningIcon {
    margin-right: .3em;
    animation: spin 2s linear infinite;
  }
  .bouncingIcon {
    margin-right: .3em;
    animation: bounce 2s infinite;
  }
  @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
  }
  @-webkit-keyframes bounce {
  0% {
    margin-bottom: 0;
    color: ${styles.colors.transparent};
  }
  70% {
    margin-bottom: 0;
    color: ${styles.colors.grey};
  }
  100% {
    margin-bottom: 0;
    color: ${styles.colors.transparent};
  }
}
`

module.exports = compileTab

function compileTab (container, appAPI, appEvents, opts) {
  if (typeof container === 'string') container = document.querySelector(container)
  if (!container) throw new Error('no container given')

  // Containers
  var warnCompilationSlow = yo`<i title="Copy Address" style="display:none" class="${css.warnCompilationSlow} fa fa-exclamation-triangle" aria-hidden="true"></i>`
  var compileIcon = yo`<i class="fa fa-refresh ${css.icon}" aria-hidden="true"></i>`
  var compileContainer = yo`

${compileIcon} Start to compile

            <input class="${css.autocompile}" id="autoCompile" type="checkbox" checked title="Auto compile">
            Auto compile

          ${warnCompilationSlow}

  `

  compileContainer.querySelector('#compile').addEventListener('click', () => {
    appAPI.runCompiler()
  })

  var compileTimeout = null
  function scheduleCompilation () {
    if (!appAPI.config.get('autoCompile')) {
      return
    }

    if (compileTimeout) {
      window.clearTimeout(compileTimeout)
    }
    compileTimeout = window.setTimeout(() => {
      appAPI.runCompiler()
    }, 300)
  }

  appEvents.editor.register('contentChanged', () => {
    scheduleCompilation()
  })

  appEvents.editor.register('sessionSwitched', () => {
    scheduleCompilation()
  })

  // ----------------- autoCompile -----------------
  var autoCompileInput = compileContainer.querySelector('#autoCompile')
  var autoCompile = true
  if (appAPI.config.exists('autoCompile')) {
    autoCompile = appAPI.config.get('autoCompile')
  }
  appAPI.config.set('autoCompile', autoCompile)
  autoCompileInput.setAttribute('checked', autoCompile)

  autoCompileInput.addEventListener('change', function () {
    appAPI.config.set('autoCompile', autoCompileInput.checked)
  })

  // REGISTER EVENTS

  // compilationDuration
  appEvents.compiler.register('compilationDuration', function tabHighlighting (speed) {
    if (speed > 1000) {
      warnCompilationSlow.setAttribute('title', `Last compilation took ${speed}ms. We suggest to turn off autocompilation.`)
      warnCompilationSlow.style.display = 'inline-block'
    } else {
      warnCompilationSlow.style.display = 'none'
    }
  })
  // loadingCompiler
  appEvents.editor.register('contentChanged', function changedFile () {
    var compileTab = document.querySelector('.compileView')
    compileTab.style.color = styles.colors.red
    compileIcon.classList.add(`${css.bouncingIcon}`)
  })
  appEvents.compiler.register('loadingCompiler', function start () {
    compileIcon.classList.add(`${css.spinningIcon}`)
    warnCompilationSlow.style.display = 'none'
    compileIcon.setAttribute('title', 'compiler is loading, please wait a few moments.')
  })
  appEvents.compiler.register('compilationFinished', function finish () {
    var compileTab = document.querySelector('.compileView')
    compileTab.style.color = styles.colors.black
    compileIcon.style.color = styles.colors.black
    compileIcon.classList.remove(`${css.spinningIcon}`)
    compileIcon.classList.remove(`${css.bouncingIcon}`)
    compileIcon.setAttribute('title', 'idle')
  })
  appEvents.compiler.register('compilationStarted', function start () {
    compileIcon.classList.remove(`${css.bouncingIcon}`)
    compileIcon.classList.add(`${css.spinningIcon}`)
    compileIcon.setAttribute('title', 'compiling...')
  })
  appEvents.compiler.register('compilerLoaded', function loaded () {
    compileIcon.classList.remove(`${css.spinningIcon}`)
    compileIcon.setAttribute('title', '')
  })

  var el = yo`

      ${compileContainer}
      ${contractNames(container, appAPI, appEvents, opts)}

  `
  container.appendChild(el)

  /* ------------------------------------------------
    section CONTRACT DROPDOWN, DETAILS AND PUBLISH
  ------------------------------------------------ */

  function contractNames (container, appAPI, appEvents, opts) {
    var contractsDetails = {}
    appEvents.compiler.register('compilationFinished', function (success, data, source) {
      // reset the contractMetadata list (used by the publish action)
      contractsDetails = {}
      // refill the dropdown list
      getContractNames(success, data)
      // hightlight the tab if error
      if (success) {
        document.querySelector('#righthand-panel #menu .compileView').style.color = ''
      } else {
        document.querySelector('#righthand-panel #menu .compileView').style.color = styles.colors.red
      }
      // display warning error if any
      var errorContainer = container.querySelector('.error')
      errorContainer.innerHTML = ''
      if (data['error']) {
        appAPI.compilationMessage(data['error'], $(errorContainer))
      }
      if (data['errors']) {
        data['errors'].forEach(function (err) {
          appAPI.compilationMessage(err, $(errorContainer))
        })
      }
      if (errorContainer.innerHTML === '') {
        appAPI.compilationMessage('Compilation successful without warning', $(errorContainer), {type: 'success'})
      }
    })

    var el = yo`

        <select class="${css.contractNames}" disabled></select>

 { details() }}>Details

 { publish(appAPI) }}>Publish

    `

    // HELPERS

    // GET NAMES OF ALL THE CONTRACTS
    function getContractNames (success, data) {
      var contractNames = document.querySelector(`.${css.contractNames.classNames[0]}`)
      contractNames.innerHTML = ''
      if (success) {
        contractNames.removeAttribute('disabled')
        for (var name in data.contracts) {
          contractsDetails[name] = parseContracts(name, data.contracts[name], appAPI.currentCompiledSourceCode())
          var contractName = yo`
            <option>

${name}

            </option>`
          contractNames.appendChild(contractName)
        }
        appAPI.resetDapp(contractsDetails)
      } else {
        contractNames.setAttribute('disabled', true)
        appAPI.resetDapp({})
      }
    }

    function details () {
      var select = el.querySelector('select')
      if (select.children.length > 0 && select.selectedIndex >= 0) {
        var contractName = select.children[select.selectedIndex].innerText
        var details = contractsDetails[contractName]
        var keys = Object.keys(contractsDetails[contractName])
        var log = yo`<div class="${css.detailsJSON}"></div>`
        keys.map(x => {
          var copyDetails = yo`<span class="${css.copyDetails}"><i title="Copy value to clipboard" class="fa fa-clipboard" onclick=${() => { copy(details[x]) }} aria-hidden="true"></i></span>`
          log.appendChild(yo`

${x} ${copyDetails}

${JSON.stringify(details[x], null, 4)}

            `)
        })
        modalDialog(contractName, log, {label: 'OK'}, {label: ''})
      }
    }

    function publish (appAPI) {
      var selectContractNames = document.querySelector(`.${css.contractNames.classNames[0]}`)
      if (selectContractNames.children.length > 0 && selectContractNames.selectedIndex >= 0) {
        var contract = contractsDetails[selectContractNames.children[selectContractNames.selectedIndex].innerText]
        publishOnSwarm(contract, appAPI, function (err) {
          if (err) {
            alert('Failed to publish metadata: ' + err)
          } else {
            alert('Metadata published successfully')
          }
        })
      }
    }
    return el
  }
}
<commit_msg>Display strings<commit_after>/* global alert */
var $ = require('jquery')

var yo = require('yo-yo')
const copy = require('clipboard-copy')

var parseContracts = require('../contract/contractParser')
var publishOnSwarm = require('../contract/publishOnSwarm')
var modalDialog = require('../ui/modaldialog')

// -------------- styling ----------------------
var csjs = require('csjs-inject')
var remix = require('ethereum-remix')
var styleGuide = remix.ui.styleGuide
var styles = styleGuide()

var css = csjs`
  .compileTabView {
    padding: 2%;
  }
  .contract {
    display: block;
    margin: 3% 0;
  }
  .compileContainer  {
    ${styles.displayBox}
    margin-bottom: 2%;
  }
  .autocompileContainer {
    width: 90px;
    display: flex;
    align-items: center;
  }
  .autocompile {}
  .autocompileTitle {
    font-weight: bold;
    margin: 1% 0;
  }
  .autocompileText {
    margin: 1% 0;
    font-size: 12px;
    overflow: hidden;
    word-break: normal;
    line-height: initial;
  }
  .warnCompilationSlow {
    color: ${styles.colors.orange};
    margin-left: 1%;
  }
  .compileButtons {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
  }
  .name {
    display: flex;
  }
  .size {
    display: flex;
  }
  .compileButton {
    ${styles.button}
    width: 120px;
    min-width: 110px;
    margin-right: 1%;
    font-size: 12px;
  }
  .container {
    ${styles.displayBox}
    margin: 0;
    display: flex;
    align-items: center;
  }
  .contractNames {
    ${styles.dropdown}
    margin-right: 5%;
  }
  .contractButtons {
    display: flex;
    cursor: pointer;
    justify-content: center;
    text-align: center;
  }
  .details {
    ${styles.button}
  }
  .publish {
    ${styles.button}
    margin-left: 2%;
  }
  .log {
    display: flex;
    flex-direction: column;
    align-items: baseline
  }
  .key {
    margin-right: 5px;
    color: grey;
    text-transform: uppercase;
    width: 100%;
  }
  .value {
    display: flex;
    width: 100%;
    margin-top: 1.5%;
  }
  .copyDetails {
    margin-left: 2%;
    font-size: 14px;
    cursor: pointer;
    color: ${styles.colors.grey};
    opacity: .3;
  }
  .copyDetails:hover {
    opacity: 1;
  }
  .detailsJSON {
    padding: 8px 0;
    background-color: ${styles.colors.white};
    border: none;
    color: ${styles.colors.grey};
  }
  .icon {
    margin-right: 3%;
  }
  .spinningIcon {
    margin-right: .3em;
    animation: spin 2s linear infinite;
  }
  .bouncingIcon {
    margin-right: .3em;
    animation: bounce 2s infinite;
  }
  @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
  }
  @-webkit-keyframes bounce {
  0% {
    margin-bottom: 0;
    color: ${styles.colors.transparent};
  }
  70% {
    margin-bottom: 0;
    color: ${styles.colors.grey};
  }
  100% {
    margin-bottom: 0;
    color: ${styles.colors.transparent};
  }
}
`

module.exports = compileTab

function compileTab (container, appAPI, appEvents, opts) {
  if (typeof container === 'string') container = document.querySelector(container)
  if (!container) throw new Error('no container given')

  // Containers
  var warnCompilationSlow = yo`<i title="Copy Address" style="display:none" class="${css.warnCompilationSlow} fa fa-exclamation-triangle" aria-hidden="true"></i>`
  var compileIcon = yo`<i class="fa fa-refresh ${css.icon}" aria-hidden="true"></i>`
  var compileContainer = yo`

${compileIcon} Start to compile

            <input class="${css.autocompile}" id="autoCompile" type="checkbox" checked title="Auto compile">
            Auto compile

          ${warnCompilationSlow}

  `

  compileContainer.querySelector('#compile').addEventListener('click', () => {
    appAPI.runCompiler()
  })

  var compileTimeout = null
  function scheduleCompilation () {
    if (!appAPI.config.get('autoCompile')) {
      return
    }

    if (compileTimeout) {
      window.clearTimeout(compileTimeout)
    }
    compileTimeout = window.setTimeout(() => {
      appAPI.runCompiler()
    }, 300)
  }

  appEvents.editor.register('contentChanged', () => {
    scheduleCompilation()
  })

  appEvents.editor.register('sessionSwitched', () => {
    scheduleCompilation()
  })

  // ----------------- autoCompile -----------------
  var autoCompileInput = compileContainer.querySelector('#autoCompile')
  var autoCompile = true
  if (appAPI.config.exists('autoCompile')) {
    autoCompile = appAPI.config.get('autoCompile')
  }
  appAPI.config.set('autoCompile', autoCompile)
  autoCompileInput.setAttribute('checked', autoCompile)

  autoCompileInput.addEventListener('change', function () {
    appAPI.config.set('autoCompile', autoCompileInput.checked)
  })

  // REGISTER EVENTS

  // compilationDuration
  appEvents.compiler.register('compilationDuration', function tabHighlighting (speed) {
    if (speed > 1000) {
      warnCompilationSlow.setAttribute('title', `Last compilation took ${speed}ms. We suggest to turn off autocompilation.`)
      warnCompilationSlow.style.display = 'inline-block'
    } else {
      warnCompilationSlow.style.display = 'none'
    }
  })
  // loadingCompiler
  appEvents.editor.register('contentChanged', function changedFile () {
    var compileTab = document.querySelector('.compileView')
    compileTab.style.color = styles.colors.red
    compileIcon.classList.add(`${css.bouncingIcon}`)
  })
  appEvents.compiler.register('loadingCompiler', function start () {
    compileIcon.classList.add(`${css.spinningIcon}`)
    warnCompilationSlow.style.display = 'none'
    compileIcon.setAttribute('title', 'compiler is loading, please wait a few moments.')
  })
  appEvents.compiler.register('compilationFinished', function finish () {
    var compileTab = document.querySelector('.compileView')
    compileTab.style.color = styles.colors.black
    compileIcon.style.color = styles.colors.black
    compileIcon.classList.remove(`${css.spinningIcon}`)
    compileIcon.classList.remove(`${css.bouncingIcon}`)
    compileIcon.setAttribute('title', 'idle')
  })
  appEvents.compiler.register('compilationStarted', function start () {
    compileIcon.classList.remove(`${css.bouncingIcon}`)
    compileIcon.classList.add(`${css.spinningIcon}`)
    compileIcon.setAttribute('title', 'compiling...')
  })
  appEvents.compiler.register('compilerLoaded', function loaded () {
    compileIcon.classList.remove(`${css.spinningIcon}`)
    compileIcon.setAttribute('title', '')
  })

  var el = yo`

      ${compileContainer}
      ${contractNames(container, appAPI, appEvents, opts)}

  `
  container.appendChild(el)

  /* ------------------------------------------------
    section CONTRACT DROPDOWN, DETAILS AND PUBLISH
  ------------------------------------------------ */

  function contractNames (container, appAPI, appEvents, opts) {
    var contractsDetails = {}
    appEvents.compiler.register('compilationFinished', function (success, data, source) {
      // reset the contractMetadata list (used by the publish action)
      contractsDetails = {}
      // refill the dropdown list
      getContractNames(success, data)
      // hightlight the tab if error
      if (success) {
        document.querySelector('#righthand-panel #menu .compileView').style.color = ''
      } else {
        document.querySelector('#righthand-panel #menu .compileView').style.color = styles.colors.red
      }
      // display warning error if any
      var errorContainer = container.querySelector('.error')
      errorContainer.innerHTML = ''
      if (data['error']) {
        appAPI.compilationMessage(data['error'], $(errorContainer))
      }
      if (data['errors']) {
        data['errors'].forEach(function (err) {
          appAPI.compilationMessage(err, $(errorContainer))
        })
      }
      if (errorContainer.innerHTML === '') {
        appAPI.compilationMessage('Compilation successful without warning', $(errorContainer), {type: 'success'})
      }
    })

    var el = yo`

        <select class="${css.contractNames}" disabled></select>

 { details() }}>Details

 { publish(appAPI) }}>Publish

    `

    // HELPERS

    // GET NAMES OF ALL THE CONTRACTS
    function getContractNames (success, data) {
      var contractNames = document.querySelector(`.${css.contractNames.classNames[0]}`)
      contractNames.innerHTML = ''
      if (success) {
        contractNames.removeAttribute('disabled')
        for (var name in data.contracts) {
          contractsDetails[name] = parseContracts(name, data.contracts[name], appAPI.currentCompiledSourceCode())
          var contractName = yo`
            <option>

${name}

            </option>`
          contractNames.appendChild(contractName)
        }
        appAPI.resetDapp(contractsDetails)
      } else {
        contractNames.setAttribute('disabled', true)
        appAPI.resetDapp({})
      }
    }

    function details () {
      var select = el.querySelector('select')
      if (select.children.length > 0 && select.selectedIndex >= 0) {
        var contractName = select.children[select.selectedIndex].innerText
        var details = contractsDetails[contractName]
        var keys = Object.keys(contractsDetails[contractName])
        var log = yo`<div class="${css.detailsJSON}"></div>`
        keys.map(x => {
          var copyDetails = yo`<span class="${css.copyDetails}"><i title="Copy value to clipboard" class="fa fa-clipboard" onclick=${() => { copy(details[x]) }} aria-hidden="true"></i></span>`
          log.appendChild(yo`

${x} ${copyDetails}

              ${insertValue(details, x)}

            `)
        })
        modalDialog(contractName, log, {label: 'OK'}, {label: ''})
      }
    }

    function insertValue(details, x) {
      var value = yo`<pre class="${css.value}"></pre>`
      console.log(x)
      if (x ==='bytecode'||x ==='metadataHash'||x ==='swarmLocation'||x==='Runtime Bytecode'||x==='Opcodes') {
        var node = yo`<div>${JSON.stringify((details[x].slice(1, 40)+'...'), null, 4)}</div>`
        value.appendChild(node)
      } else {
        var node = yo`<div>${JSON.stringify(details[x], null, 4)}</div>`
        value.appendChild(node)
      }
      return value
    }

    function publish (appAPI) {
      var selectContractNames = document.querySelector(`.${css.contractNames.classNames[0]}`)
      if (selectContractNames.children.length > 0 && selectContractNames.selectedIndex >= 0) {
        var contract = contractsDetails[selectContractNames.children[selectContractNames.selectedIndex].innerText]
        publishOnSwarm(contract, appAPI, function (err) {
          if (err) {
            alert('Failed to publish metadata: ' + err)
          } else {
            alert('Metadata published successfully')
          }
        })
      }
    }
    return el
  }
}
<|endoftext|>


<commit_before>var Registry = require("../core/registry");
var ChannelTool = require("./tools/channelTool");
var MouseTool = require("./tools/mouseTool");
var Features = require("../core/features");
var PanTool = require("./tools/panTool");
var PanAndZoom = require("./PanAndZoom");
var SelectTool = require("./tools/selectTool");
var SimpleQueue = require("../utils/SimpleQueue");
var PositionTool = require("./tools/positionTool");

class ViewManager {
    constructor(view) {
        this.view = view;
        this.tools = {};
        this.middleMouseTool = new PanTool();
        this.rightMouseTool = new SelectTool();
        let reference = this;
        this.updateQueue = new SimpleQueue(function(){
            reference.view.refresh();
        }, 20);
        window.onkeydown = function(event){
            let key = event.keyCode || event.which;
            if (key == 46 || key == 8){
                event.preventDefault();
            }
        }
        this.view.setKeyDownFunction(function(event){
            let key = event.keyCode || event.which;
            if (key== 46 || key == 8){
                reference.view.deleteSelectedFeatures();
            }
        });

        this.view.setResizeFunction(function() {
            reference.updateGrid();
            reference.updateDevice(Registry.currentDevice);
        });

        let func = function(event) {
            reference.adjustZoom(event.deltaY, reference.getEventPosition(event));
        };
        this.view.setMouseWheelFunction(func);
        this.minZoom = .0001;
        this.maxZoom = 5;
        this.setupTools();
        this.activateTool("Chamber");
    }

    addDevice(device, refresh = true) {
        this.view.addDevice(device);
        this.__addAllDeviceLayers(device, false);
        this.refresh(refresh);
    }

    __addAllDeviceLayers(device, refresh = true) {
        for (let i = 0; i < device.layers.length; i++) {
            let layer = device.layers[i];
            this.addLayer(layer, i, false);
        }
    }

    __removeAllDeviceLayers(device, refresh = true) {
        for (let i = 0; i < device.layers.length; i++) {
            let layer = device.layers[i];
            this.removeLayer(layer, i, false);
        }
    }

    removeDevice(device, refresh = true) {
        this.view.removeDevice(device);
        this.__removeAllDeviceLayers(device, false);
        this.refresh(refresh);
    }

    updateDevice(device, refresh = true) {
        this.view.updateDevice(device);
        this.refresh(refresh);
    }

    addFeature(feature, refresh = true) {
        if (this.__isFeatureInCurrentDevice(feature)) {
            this.view.addFeature(feature);
            this.refresh(refresh);
        }
    }

    updateFeature(feature, refresh = true) {
        if (this.__isFeatureInCurrentDevice(feature)) {
            this.view.updateFeature(feature);
            this.refresh(refresh);
        }
    }

    removeFeature(feature, refresh = true) {
        if (this.__isFeatureInCurrentDevice(feature)) {
            this.view.removeFeature(feature);
            this.refresh(refresh);
        }
    }

    addLayer(layer, index, refresh = true) {
        if (this.__isLayerInCurrentDevice(layer)) {
            this.view.addLayer(layer, index, false);
            this.__addAllLayerFeatures(layer, false);
            this.refresh(refresh);
        }
    }

    updateLayer(layer, index, refresh = true) {
        if (this.__isLayerInCurrentDevice(layer)) {
            this.view.updateLayer(layer);
            this.refresh(refresh);
        }
    }

    removeLayer(layer, index, refresh = true) {
        if (this.__isLayerInCurrentDevice(layer)) {
            this.view.removeLayer(layer, index);
            this.__removeAllLayerFeatures(layer);
            this.refresh(refresh);
        }
    }

    layersToSVGStrings(){
        return this.view.layersToSVGStrings();
    }

    __addAllLayerFeatures(layer, refresh = true) {
        for (let key in layer.features) {
            let feature = layer.features[key];
            this.addFeature(feature, false);
            this.refresh(refresh)
        }
    }

    __updateAllLayerFeatures(layer, refresh = true){
        for (let key in layer.features) {
            let feature = layer.features[key];
            this.updateFeature(feature, false);
            this.refresh(refresh);
        }
    }

    __removeAllLayerFeatures(layer, refresh = true) {
        for (let key in layer.features) {
            let feature = layer.features[key];
            this.removeFeature(feature, false);
            this.refresh(refresh);
        }
    }

    updateLayer(layer, refresh = true) {
        if (this.__isLayerInCurrentDevice(layer)) {
            this.view.updateLayer(layer);
            this.refresh(refresh);
        }
    }

    updateActiveLayer(refresh = true){
        this.view.setActiveLayer(Registry.currentDevice.layers.indexOf(Registry.currentLayer));
        this.refresh(refresh);
    }

    removeGrid(refresh = true) {
        if (this.__hasCurrentGrid()) {
            this.view.removeGrid();
            this.refresh(refresh);
        }
    }

    updateGrid(refresh = true) {
        if (this.__hasCurrentGrid()) {
            this.view.updateGrid(Registry.currentGrid);
            this.refresh(refresh);
        }
    }

    clear(){
        this.view.clear();
    }

    setZoom(zoom, refresh = true) {
        if (zoom > this.maxZoom) zoom = this.maxZoom;
        else if (zoom < this.minZoom) zoom = this.minZoom;
        this.view.setZoom(zoom);
        this.updateGrid(false);
        this.updateDevice(Registry.currentDevice, false);
        this.__updateViewTarget(false);
        this.refresh(refresh);
    }

    removeTarget(){
        this.view.removeTarget();
    }

    updateTarget(featureType, position, refresh = true){
        this.view.addTarget(featureType, position);
        this.refresh(refresh);
    }

    __updateViewTarget(refresh = true){
        this.view.updateTarget();
        this.refresh(refresh);
    }

    adjustZoom(delta, point, refresh = true) {
        let belowMin = (this.view.getZoom() >= this.maxZoom && delta < 0);
        let aboveMax = (this.view.getZoom() <= this.minZoom && delta > 0);
        if (!aboveMax && !belowMin) {
            this.view.adjustZoom(delta, point);
            this.updateGrid(false);
            this.updateDevice(Registry.currentDevice, false);
            this.__updateViewTarget(false);
        } else {
            //console.log("Too big or too small!");
        }
        this.refresh(refresh);
    }

    setCenter(center, refresh = true) {
        this.view.setCenter(center);
        this.updateGrid(false);
        this.updateDevice(Registry.currentDevice, false);
        this.refresh(refresh);
    }

    moveCenter(delta, refresh = true) {
        this.view.moveCenter(delta);
        this.updateGrid(false);
        this.updateDevice(Registry.currentDevice, false);
        this.refresh(refresh);
    }

    refresh(refresh = true) {
        //this.view.refresh();
        this.updateQueue.run();
    }

    getEventPosition(event) {
        return this.view.getProjectPosition(event.clientX, event.clientY);
    }

    __hasCurrentGrid() {
        if (Registry.currentGrid) return true;
        else return false;
    }

    __isLayerInCurrentDevice(layer) {
        if (Registry.currentDevice && layer.device == Registry.currentDevice) return true;
        else return false;
    }

    __isFeatureInCurrentDevice(feature) {
        if (Registry.currentDevice && this.__isLayerInCurrentDevice(feature.layer)) return true;
        else return false;
    }

    constructMouseDownEvent(tool1, tool2, tool3) {
        return this.constructMouseEvent(tool1.down, tool2.down, tool3.down);
    }

    constructMouseMoveEvent(tool1, tool2, tool3) {
        return this.constructMouseEvent(tool1.move, tool2.move, tool3.move);
    }

    constructMouseUpEvent(tool1, tool2, tool3) {
        return this.constructMouseEvent(tool1.up, tool2.up, tool3.up);
    }

    getDeviceCenter() {
        let dev = Registry.currentDevice;
        let width = dev.params.getValue("width");
        let height = dev.params.getValue("height");
        return new paper.Point(width/2, height/2);
    }

    computeOptimalZoom() {

    }

    removeFeaturesByPaperElements(paperElements){
        if (paperElements.length > 0){
            for (let i =0; i < paperElements.length; i ++){
                let paperFeature = paperElements[i];
                Registry.currentDevice.removeFeatureByID(paperFeature.featureID);
            }
            this.currentSelection = [];
        }
    }

    static __eventButtonsToWhich(num){
        if (num == 1){
            return 1;
        } else if (num ==2){
            return 3;
        } else if (num == 4){
            return 2;
        } else if (num == 3){
            return 2;
        }
    }

    constructMouseEvent(func1, func2, func3) {
        return function(event) {
            let target;
            if (event.buttons){
                target = ViewManager.__eventButtonsToWhich(event.buttons);
            } else {
                target = event.which;
            }
            if (target == 2) func2(event);
            else if (target == 3) func3(event);
            else if(target == 1 || target == 0) func1(event);
        }
    }

    snapToGrid(point) {
        if (Registry.currentGrid) return Registry.currentGrid.getClosestGridPoint(point);
        else return point;
    }

    hitFeature(point){
        return this.view.hitFeature(point);
    }

    hitFeaturesWithViewElement(element){
        return this.view.hitFeaturesWithViewElement(element);
    }

    __updateViewMouseEvents(){
        this.view.setMouseDownFunction(this.constructMouseDownEvent(this.leftMouseTool, this.middleMouseTool, this.rightMouseTool));
        this.view.setMouseUpFunction(this.constructMouseUpEvent(this.leftMouseTool, this.middleMouseTool, this.rightMouseTool));
        this.view.setMouseMoveFunction(this.constructMouseMoveEvent(this.leftMouseTool, this.middleMouseTool, this.rightMouseTool));
    }

    activateTool(toolString){
        this.leftMouseTool = this.tools[toolString];
        this.__updateViewMouseEvents();
    }

    setupTools(){
        this.tools["Chamber"] = new ChannelTool(Features.Chamber);
        this.tools["Channel"] = new ChannelTool(Features.Channel);
        this.tools["CircleValve"] = new PositionTool(Features.CircleValve);
        this.tools["Port"] = new PositionTool(Features.Port);
        this.tools["Via"] = new PositionTool(Features.Via);
    }
}

module.exports = ViewManager;<commit_msg>fix initial tool<commit_after>var Registry = require("../core/registry");
var ChannelTool = require("./tools/channelTool");
var MouseTool = require("./tools/mouseTool");
var Features = require("../core/features");
var PanTool = require("./tools/panTool");
var PanAndZoom = require("./PanAndZoom");
var SelectTool = require("./tools/selectTool");
var SimpleQueue = require("../utils/SimpleQueue");
var PositionTool = require("./tools/positionTool");

class ViewManager {
    constructor(view) {
        this.view = view;
        this.tools = {};
        this.middleMouseTool = new PanTool();
        this.rightMouseTool = new SelectTool();
        let reference = this;
        this.updateQueue = new SimpleQueue(function(){
            reference.view.refresh();
        }, 20);
        window.onkeydown = function(event){
            let key = event.keyCode || event.which;
            if (key == 46 || key == 8){
                event.preventDefault();
            }
        }
        this.view.setKeyDownFunction(function(event){
            let key = event.keyCode || event.which;
            if (key== 46 || key == 8){
                reference.view.deleteSelectedFeatures();
            }
        });

        this.view.setResizeFunction(function() {
            reference.updateGrid();
            reference.updateDevice(Registry.currentDevice);
        });

        let func = function(event) {
            reference.adjustZoom(event.deltaY, reference.getEventPosition(event));
        };
        this.view.setMouseWheelFunction(func);
        this.minZoom = .0001;
        this.maxZoom = 5;
        this.setupTools();
        this.activateTool("Channel");
    }

    addDevice(device, refresh = true) {
        this.view.addDevice(device);
        this.__addAllDeviceLayers(device, false);
        this.refresh(refresh);
    }

    __addAllDeviceLayers(device, refresh = true) {
        for (let i = 0; i < device.layers.length; i++) {
            let layer = device.layers[i];
            this.addLayer(layer, i, false);
        }
    }

    __removeAllDeviceLayers(device, refresh = true) {
        for (let i = 0; i < device.layers.length; i++) {
            let layer = device.layers[i];
            this.removeLayer(layer, i, false);
        }
    }

    removeDevice(device, refresh = true) {
        this.view.removeDevice(device);
        this.__removeAllDeviceLayers(device, false);
        this.refresh(refresh);
    }

    updateDevice(device, refresh = true) {
        this.view.updateDevice(device);
        this.refresh(refresh);
    }

    addFeature(feature, refresh = true) {
        if (this.__isFeatureInCurrentDevice(feature)) {
            this.view.addFeature(feature);
            this.refresh(refresh);
        }
    }

    updateFeature(feature, refresh = true) {
        if (this.__isFeatureInCurrentDevice(feature)) {
            this.view.updateFeature(feature);
            this.refresh(refresh);
        }
    }

    removeFeature(feature, refresh = true) {
        if (this.__isFeatureInCurrentDevice(feature)) {
            this.view.removeFeature(feature);
            this.refresh(refresh);
        }
    }

    addLayer(layer, index, refresh = true) {
        if (this.__isLayerInCurrentDevice(layer)) {
            this.view.addLayer(layer, index, false);
            this.__addAllLayerFeatures(layer, false);
            this.refresh(refresh);
        }
    }

    updateLayer(layer, index, refresh = true) {
        if (this.__isLayerInCurrentDevice(layer)) {
            this.view.updateLayer(layer);
            this.refresh(refresh);
        }
    }

    removeLayer(layer, index, refresh = true) {
        if (this.__isLayerInCurrentDevice(layer)) {
            this.view.removeLayer(layer, index);
            this.__removeAllLayerFeatures(layer);
            this.refresh(refresh);
        }
    }

    layersToSVGStrings(){
        return this.view.layersToSVGStrings();
    }

    __addAllLayerFeatures(layer, refresh = true) {
        for (let key in layer.features) {
            let feature = layer.features[key];
            this.addFeature(feature, false);
            this.refresh(refresh)
        }
    }

    __updateAllLayerFeatures(layer, refresh = true){
        for (let key in layer.features) {
            let feature = layer.features[key];
            this.updateFeature(feature, false);
            this.refresh(refresh);
        }
    }

    __removeAllLayerFeatures(layer, refresh = true) {
        for (let key in layer.features) {
            let feature = layer.features[key];
            this.removeFeature(feature, false);
            this.refresh(refresh);
        }
    }

    updateLayer(layer, refresh = true) {
        if (this.__isLayerInCurrentDevice(layer)) {
            this.view.updateLayer(layer);
            this.refresh(refresh);
        }
    }

    updateActiveLayer(refresh = true){
        this.view.setActiveLayer(Registry.currentDevice.layers.indexOf(Registry.currentLayer));
        this.refresh(refresh);
    }

    removeGrid(refresh = true) {
        if (this.__hasCurrentGrid()) {
            this.view.removeGrid();
            this.refresh(refresh);
        }
    }

    updateGrid(refresh = true) {
        if (this.__hasCurrentGrid()) {
            this.view.updateGrid(Registry.currentGrid);
            this.refresh(refresh);
        }
    }

    clear(){
        this.view.clear();
    }

    setZoom(zoom, refresh = true) {
        if (zoom > this.maxZoom) zoom = this.maxZoom;
        else if (zoom < this.minZoom) zoom = this.minZoom;
        this.view.setZoom(zoom);
        this.updateGrid(false);
        this.updateDevice(Registry.currentDevice, false);
        this.__updateViewTarget(false);
        this.refresh(refresh);
    }

    removeTarget(){
        this.view.removeTarget();
    }

    updateTarget(featureType, position, refresh = true){
        this.view.addTarget(featureType, position);
        this.refresh(refresh);
    }

    __updateViewTarget(refresh = true){
        this.view.updateTarget();
        this.refresh(refresh);
    }

    adjustZoom(delta, point, refresh = true) {
        let belowMin = (this.view.getZoom() >= this.maxZoom && delta < 0);
        let aboveMax = (this.view.getZoom() <= this.minZoom && delta > 0);
        if (!aboveMax && !belowMin) {
            this.view.adjustZoom(delta, point);
            this.updateGrid(false);
            this.updateDevice(Registry.currentDevice, false);
            this.__updateViewTarget(false);
        } else {
            //console.log("Too big or too small!");
        }
        this.refresh(refresh);
    }

    setCenter(center, refresh = true) {
        this.view.setCenter(center);
        this.updateGrid(false);
        this.updateDevice(Registry.currentDevice, false);
        this.refresh(refresh);
    }

    moveCenter(delta, refresh = true) {
        this.view.moveCenter(delta);
        this.updateGrid(false);
        this.updateDevice(Registry.currentDevice, false);
        this.refresh(refresh);
    }

    refresh(refresh = true) {
        //this.view.refresh();
        this.updateQueue.run();
    }

    getEventPosition(event) {
        return this.view.getProjectPosition(event.clientX, event.clientY);
    }

    __hasCurrentGrid() {
        if (Registry.currentGrid) return true;
        else return false;
    }

    __isLayerInCurrentDevice(layer) {
        if (Registry.currentDevice && layer.device == Registry.currentDevice) return true;
        else return false;
    }

    __isFeatureInCurrentDevice(feature) {
        if (Registry.currentDevice && this.__isLayerInCurrentDevice(feature.layer)) return true;
        else return false;
    }

    constructMouseDownEvent(tool1, tool2, tool3) {
        return this.constructMouseEvent(tool1.down, tool2.down, tool3.down);
    }

    constructMouseMoveEvent(tool1, tool2, tool3) {
        return this.constructMouseEvent(tool1.move, tool2.move, tool3.move);
    }

    constructMouseUpEvent(tool1, tool2, tool3) {
        return this.constructMouseEvent(tool1.up, tool2.up, tool3.up);
    }

    getDeviceCenter() {
        let dev = Registry.currentDevice;
        let width = dev.params.getValue("width");
        let height = dev.params.getValue("height");
        return new paper.Point(width/2, height/2);
    }

    computeOptimalZoom() {

    }

    removeFeaturesByPaperElements(paperElements){
        if (paperElements.length > 0){
            for (let i =0; i < paperElements.length; i ++){
                let paperFeature = paperElements[i];
                Registry.currentDevice.removeFeatureByID(paperFeature.featureID);
            }
            this.currentSelection = [];
        }
    }

    static __eventButtonsToWhich(num){
        if (num == 1){
            return 1;
        } else if (num ==2){
            return 3;
        } else if (num == 4){
            return 2;
        } else if (num == 3){
            return 2;
        }
    }

    constructMouseEvent(func1, func2, func3) {
        return function(event) {
            let target;
            if (event.buttons){
                target = ViewManager.__eventButtonsToWhich(event.buttons);
            } else {
                target = event.which;
            }
            if (target == 2) func2(event);
            else if (target == 3) func3(event);
            else if(target == 1 || target == 0) func1(event);
        }
    }

    snapToGrid(point) {
        if (Registry.currentGrid) return Registry.currentGrid.getClosestGridPoint(point);
        else return point;
    }

    hitFeature(point){
        return this.view.hitFeature(point);
    }

    hitFeaturesWithViewElement(element){
        return this.view.hitFeaturesWithViewElement(element);
    }

    __updateViewMouseEvents(){
        this.view.setMouseDownFunction(this.constructMouseDownEvent(this.leftMouseTool, this.middleMouseTool, this.rightMouseTool));
        this.view.setMouseUpFunction(this.constructMouseUpEvent(this.leftMouseTool, this.middleMouseTool, this.rightMouseTool));
        this.view.setMouseMoveFunction(this.constructMouseMoveEvent(this.leftMouseTool, this.middleMouseTool, this.rightMouseTool));
    }

    activateTool(toolString){
        this.leftMouseTool = this.tools[toolString];
        this.__updateViewMouseEvents();
    }

    setupTools(){
        this.tools["Chamber"] = new ChannelTool(Features.Chamber);
        this.tools["Channel"] = new ChannelTool(Features.Channel);
        this.tools["CircleValve"] = new PositionTool(Features.CircleValve);
        this.tools["Port"] = new PositionTool(Features.Port);
        this.tools["Via"] = new PositionTool(Features.Via);
    }
}

module.exports = ViewManager;<|endoftext|>


<commit_before>Services.factory("Notifications", ["$filter", "$rootScope","$timeout", function ($filter, $rootScope, $timeout)
{
    var highlighted = false;
    var unread = 0;

    $rootScope.$on("highlighted", function (evt, message)
    {
        highlighted = true;
        setTitle(message.channel.name);
        notify(message.channel.name, message.user.nickName, message.line);
    });

    $rootScope.$on("unread", function (evt, message)
    {
        unread++;
        if (highlighted == false)
        {
            setTitle(message.channel.name, unread);
        }
    });

    $rootScope.$on("read", function (evt)
    {
        setTitle();
        highlighted = false;
        unread = 0;
    });

    var setTitle = function (channel, messages)
    {
        $timeout(function ()
        {
            if (channel == null)
            {
                document.title = "Coldstorm";
            } else if (messages == null)
            {
                document.title = "(***) " + channel + " | Coldstorm";
            } else
            {
                document.title = "(" + messages + ") " + channel + " | Coldstorm";
            }
        }, 300);
    }

    var supportsNotifications = false;

    var notify = function (channel, author, message)
    {
        if (supportsNotifications)
        {
            if (window.webkitNotifications.checkPermission() == 0)
            {
                window.webkitNotifications.createNotification("../../favicon.png", "Coldstorm" + " (" + channel + ") ",
                    "[" + $filter("date")(new Date(), "HH:mm") + "] " + author + ": " + message).show();
            }
        }
    }

    var checkNotifications = function ()
    {
        if (window.webkitNotifications)
        {
            supportsNotifications = true;
        } else
        {
            supportsNotifications = false;
        }
    }

    $rootScope.requestNotifications = function ()
    {
        checkNotifications();
        if (supportsNotifications)
        {
            if (window.webkitNotifications.checkPermission() != 0)
            {
                window.webkitNotifications.requestPermission();
            }
        }
    }
}])<commit_msg>Fix favicon in desktop notifications<commit_after>Services.factory("Notifications", ["$filter", "$rootScope","$timeout", function ($filter, $rootScope, $timeout)
{
    var highlighted = false;
    var unread = 0;

    $rootScope.$on("highlighted", function (evt, message)
    {
        highlighted = true;
        setTitle(message.channel.name);
        notify(message.channel.name, message.user.nickName, message.line);
    });

    $rootScope.$on("unread", function (evt, message)
    {
        unread++;
        if (highlighted == false)
        {
            setTitle(message.channel.name, unread);
        }
    });

    $rootScope.$on("read", function (evt)
    {
        setTitle();
        highlighted = false;
        unread = 0;
    });

    var setTitle = function (channel, messages)
    {
        $timeout(function ()
        {
            if (channel == null)
            {
                document.title = "Coldstorm";
            } else if (messages == null)
            {
                document.title = "(***) " + channel + " | Coldstorm";
            } else
            {
                document.title = "(" + messages + ") " + channel + " | Coldstorm";
            }
        }, 300);
    }

    var supportsNotifications = false;

    var notify = function (channel, author, message)
    {
        if (supportsNotifications)
        {
            if (window.webkitNotifications.checkPermission() == 0)
            {
                window.webkitNotifications.createNotification("../../../favicon.png", "Coldstorm" + " (" + channel + ") ",
                    "[" + $filter("date")(new Date(), "HH:mm") + "] " + author + ": " + message).show();
            }
        }
    }

    var checkNotifications = function ()
    {
        if (window.webkitNotifications)
        {
            supportsNotifications = true;
        } else
        {
            supportsNotifications = false;
        }
    }

    $rootScope.requestNotifications = function ()
    {
        checkNotifications();
        if (supportsNotifications)
        {
            if (window.webkitNotifications.checkPermission() != 0)
            {
                window.webkitNotifications.requestPermission();
            }
        }
    }
}])<|endoftext|>


<commit_before>/**
 * This file contains the marker positions and additional information for the map
 */
var app = app || {};

(function () {
    'use strict';

	app.markers = [
		// Mainhall
		{
			name: 'Megablast',
			coord: [-54, -100],
			desc: 'Music-Player for the main hall.',
			url: 'http://megablast.cbrp3.c-base.org/',
			icon: app.audio_icon
		},
		{
			name: 'DMX-DMON',
			coord: [-54, -113.0],
			desc: 'DMX light control for the main hall.',
			url: 'http://baseos.cbrp3.c-base.org/dmxdmon/',
			icon: app.lightbulb_icon
		},
		{
			name: 'Bar',
			coord: [-30.0, -112.0],
			desc: 'A place to get cold beverages.',
			url: '',
			icon: app.bar_icon
		},
		{
			name: 'Matelight',
			coord: [-69.0, -80.0],
			desc: 'Mate bottle based pixel display.',
			url: 'http://matelight.cbrp3.c-base.org/',
			icon: app.videogames_icon
		},
		{
			name: 'Klotür',
			coord: [5.0, -142.5],
			desc: 'The Twitteraccount of an Object that caused a Shitstorm',
			url: 'https://twitter.com/klotuer',
			icon: app.twitter_icon
		},
		// C_leuse
		{
			name: 'c_leuse lightcontrol',
			coord: [-5.0, -35.0],
			desc: 'control of photon emitters in airlock',
			url: 'https://c-beam.cbrp3.c-base.org/c_leuse',
			icon: app.lightbulb_icon
		},
		{
			name: 'c_leuse soundcontrol',
			coord: [-5.0, -45.0],
			desc: 'no webinterface. only physical interface',
			url: 'https://jaseg.net/how-to-build-a-very-serious-volume-knob-from-a-1950ies-variac-and-an-arduino.html',
			icon: app.audio_icon
		},
		// Nerdarea
		{
			name: 'Hyperblast',
			coord: [-47.0, 6.0],
			desc: 'Music-Player in the Nördarea.',
			url: 'http://hyperblast.cbrp3.c-base.org/',
			icon: app.audio_icon
		},

		// c-lab
		{
			name: 'Labblaster',
			coord: [-55.0, 130.0],
			desc: 'Music player for the c-lab',
			url: 'http://baseos.cbrp3.c-base.org/tinyblast/',
			icon: app.audio_icon
		},
		{
			name: '3D-Printer Cams',
			coord: [-30.0, 115.0],
			desc: 'Webcams and Webinterface of the 3D-Printers',
			url: 'http://3dp.cbrp3.c-base.org/',
			icon: app.video_icon
		}

	];

})();

<commit_msg>added location information of a physical interface<commit_after>/**
 * This file contains the marker positions and additional information for the map
 */
var app = app || {};

(function () {
    'use strict';

	app.markers = [
		// Mainhall
		{
			name: 'Megablast',
			coord: [-54, -100],
			desc: 'Music-Player for the main hall.',
			url: 'http://megablast.cbrp3.c-base.org/',
			icon: app.audio_icon
		},
		{
			name: 'DMX-DMON',
			coord: [-54, -113.0],
			desc: 'DMX light control for the main hall.',
			url: 'http://baseos.cbrp3.c-base.org/dmxdmon/',
			icon: app.lightbulb_icon
		},
		{
			name: 'Bar',
			coord: [-30.0, -112.0],
			desc: 'A place to get cold beverages.',
			url: '',
			icon: app.bar_icon
		},
		{
			name: 'Matelight',
			coord: [-69.0, -80.0],
			desc: 'Mate bottle based pixel display.',
			url: 'http://matelight.cbrp3.c-base.org/',
			icon: app.videogames_icon
		},
		{
			name: 'Klotür',
			coord: [5.0, -142.5],
			desc: 'The Twitteraccount of an Object that caused a Shitstorm',
			url: 'https://twitter.com/klotuer',
			icon: app.twitter_icon
		},
		// C_leuse
		{
			name: 'c_leuse lightcontrol',
			coord: [-5.0, -35.0],
			desc: 'control of photon emitters in airlock',
			url: 'https://c-beam.cbrp3.c-base.org/c_leuse',
			icon: app.lightbulb_icon
		},
		{
			name: 'c_leuse soundcontrol',
			coord: [-5.0, -45.0],
			desc: 'no webinterface. only physical interface at the bar',
			url: 'https://jaseg.net/how-to-build-a-very-serious-volume-knob-from-a-1950ies-variac-and-an-arduino.html',
			icon: app.audio_icon
		},
		// Nerdarea
		{
			name: 'Hyperblast',
			coord: [-47.0, 6.0],
			desc: 'Music-Player in the Nördarea.',
			url: 'http://hyperblast.cbrp3.c-base.org/',
			icon: app.audio_icon
		},

		// c-lab
		{
			name: 'Labblaster',
			coord: [-55.0, 130.0],
			desc: 'Music player for the c-lab',
			url: 'http://baseos.cbrp3.c-base.org/tinyblast/',
			icon: app.audio_icon
		},
		{
			name: '3D-Printer Cams',
			coord: [-30.0, 115.0],
			desc: 'Webcams and Webinterface of the 3D-Printers',
			url: 'http://3dp.cbrp3.c-base.org/',
			icon: app.video_icon
		}

	];

})();

<|endoftext|>


<commit_before>;(function() {
	/*
	 * Alloy JavaScript Library v@VERSION@
	 * http://alloy.liferay.com/
	 *
	 * Copyright (c) 2010 Liferay Inc.
	 * http://alloy.liferay.com/LICENSE.txt
	 *
	 * Nate Cavanaugh (nathan.cavanaugh@liferay.com)
	 * Eduardo Lundgren (eduardo.lundgren@liferay.com)
	 *
	 * Attribution/Third-party licenses
	 * http://alloy.liferay.com/ATTRIBUTION.txt
	 *
	 * Date: @DATE@
	 * Revision: @REVISION@
	 */

	YUI.AUI_config = YUI.AUI_config || {};

	var defaults = YUI.AUI_config;

	YUI.prototype.ready = function() {
		var instance = this;

		var slice = Array.prototype.slice;
		var args = slice.call(arguments, 0), index = args.length - 1;

		var fn = args[index];

		var modules = slice.call(arguments, 0, index);

		modules.push('event');

		modules.push(
			function(instance) {
				var args = arguments;

				instance.on(
					'domready',
					function() {
						fn.apply(this, args);
					}
				);
			}
		);

		instance.use.apply(instance, modules);
	};

	var ALLOY;

	try {
		ALLOY = A;
	}
	catch (e) {
		ALLOY = YUI(defaults);
	}

	ALLOY.Env._guidp = ['aui', ALLOY.version, ALLOY.Env._yidx].join('-').replace(/\./g, '-');

	var originalConfig = ALLOY.config;

	ALLOY.config = ALLOY.merge(originalConfig, YUI.AUI_config);

	YUI.AUI = function(o) {
		var instance = this;

		if (o || instance instanceof AUI) {
			var args = ALLOY.Array(arguments);

			args.unshift(ALLOY.config);

			var newInstance = YUI.apply(ALLOY.config.win, args);

			AUI._uaExtensions(newInstance);

			return newInstance;
		}

		return ALLOY;
	};

	var AUI = YUI.AUI;

	window.AUI = AUI;

	var UA = ALLOY.UA;

	ALLOY.mix(AUI, YUI, true, null, 2);

	ALLOY.mix(
		AUI,
		{
			__version: '@VERSION',

			defaults: defaults,

			html5shiv: function(frag) {
				var instance = this;
				var doc = frag || document;

				if (UA.ie && doc && doc.createElement) {
					var elements = AUI.HTML5_ELEMENTS, length = elements.length;

					while (length--) {
						doc.createElement(elements[length]);
					}
				}

				return frag;
			},

			setDefaults: function(defaults) {
				var instance = this;

				ALLOY.mix(AUI.defaults, defaults, true, null, 0, true);
				ALLOY.mix(ALLOY.config, defaults, true, null, 0, true);
			},

			HTML5_ELEMENTS: 'abbr,article,aside,audio,canvas,command,datalist,details,figure,figcaption,footer,header,hgroup,keygen,mark,meter,nav,output,progress,section,source,summary,time,video'.split(',')
		},
		true
	);

	/*
	* HTML5 Compatability for IE
	*/

	AUI.html5shiv();

	/*
		UA extensions
	*/

	AUI._uaExtensions = function(A) {
		var p = navigator.platform;
		var u = navigator.userAgent;
		var b = /(Firefox|Opera|Chrome|Safari|KDE|iCab|Flock|IE)/.exec(u);
		var os = /(Win|Mac|Linux|iPhone|iPad|Sun|Solaris)/.exec(p);
		var versionDefaults = [0,0];

		b = (!b || !b.length) ? (/(Mozilla)/.exec(u) || ['']) : b;
		os = (!os || !os.length) ? [''] : os;

		UA = A.merge(
			UA,
			{
				gecko: /Gecko/.test(u) && !/like Gecko/.test(u),
				webkit: /WebKit/.test(u),

				aol: /America Online Browser/.test(u),
				camino: /Camino/.test(u),
				firefox: /Firefox/.test(u),
				flock: /Flock/.test(u),
				icab: /iCab/.test(u),
				konqueror: /KDE/.test(u),
				mozilla: /mozilla/.test(u),
				ie: /MSIE/.test(u),
				netscape: /Netscape/.test(u),
				opera: /Opera/.test(u),
				chrome: /Chrome/.test(u),
				safari: /Safari/.test(u) && !(/Chrome/.test(u)),
				browser: b[0].toLowerCase(),

				win: /Win/.test(p),
				mac: /Mac/.test(p),
				linux: /Linux/.test(p),
				iphone: (p == 'iPhone'),
				ipad: (p == 'iPad'),
				sun: /Solaris|SunOS/.test(p),
				os: os[0].toLowerCase(),

				platform: p,
				agent: u
			}
		);

		UA.version = {
			string: ''
		};

		if (UA.ie) {
			UA.version.string = (/MSIE ([^;]+)/.exec(u) || versionDefaults)[1];
		}
		else if (UA.firefox) {
			UA.version.string = (/Firefox\/(.+)/.exec(u) || versionDefaults)[1];
		}
		else if (UA.safari) {
			UA.version.string = (/Version\/([^\s]+)/.exec(u) || versionDefaults)[1];
		}
		else if (UA.opera) {
			UA.version.string = (/Opera\/([^\s]+)/.exec(u) || versionDefaults)[1];
		}

		UA.version.number = parseFloat(UA.version.string) || versionDefaults[0];
		UA.version.major = (/([^\.]+)/.exec(UA.version.string) || versionDefaults)[1];

		UA[UA.browser + UA.version.major] = true;

		UA.renderer = '';

		if (UA.ie) {
			UA.renderer = 'trident';
		}
		else if (UA.gecko) {
			UA.renderer = 'gecko';
		}
		else if (UA.webkit) {
			UA.renderer = 'webkit';
		}
		else if (UA.opera) {
			UA.renderer = 'presto';
		}

		A.UA = UA;

		/*
		* Browser selectors
		*/

		var selectors = [
			UA.renderer,
			UA.browser,
			UA.browser + UA.version.major,
			UA.os,
			'js'
		];

		if (UA.os == 'macintosh') {
			selectors.push('mac');
		}
		else if (UA.os == 'windows') {
			selectors.push('win');
		}

		if (UA.mobile) {
			selectors.push('mobile');
		}

		if (UA.secure) {
			selectors.push('secure');
		}

		UA.selectors = selectors.join(' ');

		var documentElement = document.documentElement;

		if (!documentElement._yuid) {
			documentElement.className += ' ' + UA.selectors;

			A.stamp(documentElement);
		}
	};

	AUI._uaExtensions(ALLOY);
})();<commit_msg>AUI-85 - Apply guid extensions to all new instances<commit_after>;(function() {
	/*
	 * Alloy JavaScript Library v@VERSION@
	 * http://alloy.liferay.com/
	 *
	 * Copyright (c) 2010 Liferay Inc.
	 * http://alloy.liferay.com/LICENSE.txt
	 *
	 * Nate Cavanaugh (nathan.cavanaugh@liferay.com)
	 * Eduardo Lundgren (eduardo.lundgren@liferay.com)
	 *
	 * Attribution/Third-party licenses
	 * http://alloy.liferay.com/ATTRIBUTION.txt
	 *
	 * Date: @DATE@
	 * Revision: @REVISION@
	 */

	YUI.AUI_config = YUI.AUI_config || {};

	var defaults = YUI.AUI_config;

	YUI.prototype.ready = function() {
		var instance = this;

		var slice = Array.prototype.slice;
		var args = slice.call(arguments, 0), index = args.length - 1;

		var fn = args[index];

		var modules = slice.call(arguments, 0, index);

		modules.push('event');

		modules.push(
			function(instance) {
				var args = arguments;

				instance.on(
					'domready',
					function() {
						fn.apply(this, args);
					}
				);
			}
		);

		instance.use.apply(instance, modules);
	};

	var ALLOY;

	try {
		ALLOY = A;
	}
	catch (e) {
		ALLOY = YUI(defaults);
	}

	var guidExtensions = function(A) {
		A.Env._guidp = ['aui', A.version, A.Env._yidx].join('-').replace(/\./g, '-');
	};

	guidExtensions(ALLOY);

	var originalConfig = ALLOY.config;

	ALLOY.config = ALLOY.merge(originalConfig, YUI.AUI_config);

	YUI.AUI = function(o) {
		var instance = this;

		if (o || instance instanceof AUI) {
			var args = ALLOY.Array(arguments);

			args.unshift(ALLOY.config);

			var newInstance = YUI.apply(ALLOY.config.win, args);

			AUI._uaExtensions(newInstance);
			AUI._guidExtensions(newInstance);

			return newInstance;
		}

		return ALLOY;
	};

	var AUI = YUI.AUI;

	AUI._guidExtensions = guidExtensions;

	window.AUI = AUI;

	var UA = ALLOY.UA;

	ALLOY.mix(AUI, YUI, true, null, 2);

	ALLOY.mix(
		AUI,
		{
			__version: '@VERSION',

			defaults: defaults,

			html5shiv: function(frag) {
				var instance = this;
				var doc = frag || document;

				if (UA.ie && doc && doc.createElement) {
					var elements = AUI.HTML5_ELEMENTS, length = elements.length;

					while (length--) {
						doc.createElement(elements[length]);
					}
				}

				return frag;
			},

			setDefaults: function(defaults) {
				var instance = this;

				ALLOY.mix(AUI.defaults, defaults, true, null, 0, true);
				ALLOY.mix(ALLOY.config, defaults, true, null, 0, true);
			},

			HTML5_ELEMENTS: 'abbr,article,aside,audio,canvas,command,datalist,details,figure,figcaption,footer,header,hgroup,keygen,mark,meter,nav,output,progress,section,source,summary,time,video'.split(',')
		},
		true
	);

	/*
	* HTML5 Compatability for IE
	*/

	AUI.html5shiv();

	/*
		UA extensions
	*/

	AUI._uaExtensions = function(A) {
		var p = navigator.platform;
		var u = navigator.userAgent;
		var b = /(Firefox|Opera|Chrome|Safari|KDE|iCab|Flock|IE)/.exec(u);
		var os = /(Win|Mac|Linux|iPhone|iPad|Sun|Solaris)/.exec(p);
		var versionDefaults = [0,0];

		b = (!b || !b.length) ? (/(Mozilla)/.exec(u) || ['']) : b;
		os = (!os || !os.length) ? [''] : os;

		UA = A.merge(
			UA,
			{
				gecko: /Gecko/.test(u) && !/like Gecko/.test(u),
				webkit: /WebKit/.test(u),

				aol: /America Online Browser/.test(u),
				camino: /Camino/.test(u),
				firefox: /Firefox/.test(u),
				flock: /Flock/.test(u),
				icab: /iCab/.test(u),
				konqueror: /KDE/.test(u),
				mozilla: /mozilla/.test(u),
				ie: /MSIE/.test(u),
				netscape: /Netscape/.test(u),
				opera: /Opera/.test(u),
				chrome: /Chrome/.test(u),
				safari: /Safari/.test(u) && !(/Chrome/.test(u)),
				browser: b[0].toLowerCase(),

				win: /Win/.test(p),
				mac: /Mac/.test(p),
				linux: /Linux/.test(p),
				iphone: (p == 'iPhone'),
				ipad: (p == 'iPad'),
				sun: /Solaris|SunOS/.test(p),
				os: os[0].toLowerCase(),

				platform: p,
				agent: u
			}
		);

		UA.version = {
			string: ''
		};

		if (UA.ie) {
			UA.version.string = (/MSIE ([^;]+)/.exec(u) || versionDefaults)[1];
		}
		else if (UA.firefox) {
			UA.version.string = (/Firefox\/(.+)/.exec(u) || versionDefaults)[1];
		}
		else if (UA.safari) {
			UA.version.string = (/Version\/([^\s]+)/.exec(u) || versionDefaults)[1];
		}
		else if (UA.opera) {
			UA.version.string = (/Opera\/([^\s]+)/.exec(u) || versionDefaults)[1];
		}

		UA.version.number = parseFloat(UA.version.string) || versionDefaults[0];
		UA.version.major = (/([^\.]+)/.exec(UA.version.string) || versionDefaults)[1];

		UA[UA.browser + UA.version.major] = true;

		UA.renderer = '';

		if (UA.ie) {
			UA.renderer = 'trident';
		}
		else if (UA.gecko) {
			UA.renderer = 'gecko';
		}
		else if (UA.webkit) {
			UA.renderer = 'webkit';
		}
		else if (UA.opera) {
			UA.renderer = 'presto';
		}

		A.UA = UA;

		/*
		* Browser selectors
		*/

		var selectors = [
			UA.renderer,
			UA.browser,
			UA.browser + UA.version.major,
			UA.os,
			'js'
		];

		if (UA.os == 'macintosh') {
			selectors.push('mac');
		}
		else if (UA.os == 'windows') {
			selectors.push('win');
		}

		if (UA.mobile) {
			selectors.push('mobile');
		}

		if (UA.secure) {
			selectors.push('secure');
		}

		UA.selectors = selectors.join(' ');

		var documentElement = document.documentElement;

		if (!documentElement._yuid) {
			documentElement.className += ' ' + UA.selectors;

			A.stamp(documentElement);
		}
	};

	AUI._uaExtensions(ALLOY);
})();<|endoftext|>


<commit_before>'use strict';
import angular from 'angular';
import $ from 'jquery';
import db from '../db';

const index = {
  'folderList': '.row > .col-md-6:first-child > ul',
  'taskList': '.row > .col-md-6:nth-child(2) > ul',
  'editTaskBody': '#editTaskModal > .modal-dialog > .modal-content > .container-fluid > .row > .modal-body'
}

const TaskCtrl = ($scope) => {

  setTimeout(() => {
    let folder = getActiveFolder();
    return configHelper
    .getTasks(folder.name, folder.path)
    .then(tasks => {
      $scope.tasks = tasks;
      $scope.safeApply();
    })
    .catch(err => {
      console.log(err.message);
    });
  }, 0);

  $('form').submit((event) => {
    event.preventDefault();
  })

  $('#taskSave').on('click', (event) => {

    let folder = getActiveFolder();
    let matchAll = ($('#taskMatch').val() === 'all');

    var values = {
      'matchAll':   matchAll
    };

    values.rules = [];

    $.each($('#formTask').serializeArray(), function(i, field) {
      values[field.name] = field.value;
    });

    $('li > select').parent().each((index, value) => {

      let selects = $(value).find('select');
      values.rules.push({
        'type':       $(selects[0]).val(),
        'comparator': $(selects[1]).val(),
        'reference':  $(value).find('input').val()
      });
    });
    console.log(folder);
    return configHelper
    .saveTask(folder.name, folder.path, values)
    .then(() => {
      console.log('Task Saved!');
    })
    .catch(err => {
      throw err;
    });

  });

  $('form').submit((event) => {
    event.preventDefault();
  })

  $('#taskSave').on('click', (event) => {

    let folder = getActiveFolder();
    let matchAll = ($('#taskMatch').val() === 'all');

    var values = {
      'folderName': folder.name,
      'folderPath': folder.path,
      'matchAll':   matchAll
    };

    values.rules = [];
    $.each($('#formTask').serializeArray(), function(i, field) {
        values[field.name] = field.value;
    });

    $('li > select').parent().each((index, value) => {

      let selects = $(value).find('select');
      values.rules.push({
        'type':       $(selects[0]).val(),
        'comparator': $(selects[1]).val(),
        'reference':  $(value).find('input').val()
      });
    });

    ipc.send('tasks', {query: 'add', values});

  });

  $scope.safeApply = function(fn) {
    var phase = this.$root.$$phase;
    if(phase === '$apply' || phase === '$digest') {
      if(fn && (typeof(fn) === 'function')) {
        fn();
      }
    } else {
      this.$apply(fn);
    }
  };
}

function getActiveFolder() {
  console.log($(index.folderList).children().find('.activeFolder'));
  let folderName = $('.activeFolder').find('h3').html();
  let folderPath = $('.activeFolder').find('p').find('i').html();
  setTimeout(() => {console.log($('.activeFolder'))}, 0);

  return {
    'name': folderName,
    'path': folderPath
  }
}

module.exports = TaskCtrl;<commit_msg>replace use of configHelper with lowdb in tasks controller<commit_after>'use strict';
import angular from 'angular';
import $ from 'jquery';
import db from '../db';
import uuid from 'node-uuid';

const index = {
  'folderList': '.row > .col-md-6:first-child > ul',
  'taskList': '.row > .col-md-6:nth-child(2) > ul',
  'editTaskBody': '#editTaskModal > .modal-dialog > .modal-content > .container-fluid > .row > .modal-body'
}

const TaskCtrl = ($scope) => {

  setTimeout(function() {
    let folder = getActiveFolder();
    $scope.tasks = db('folders').find({folder}).tasks;
    $scope.safeApply();
  }, 0);

  $('#taskSave').on('click', (event) => {

    let folder = getActiveFolder();
    let matchAll = ($('#taskMatch').val() === 'all');

    var values = {
      'id':         uuid(),
      'matchAll':   matchAll
    };

    values.rules = [];

    $.each($('#formTask').serializeArray(), function(i, field) {
      values[field.name] = field.value;
    });

    $('li > select').parent().each((index, value) => {

      let selects = $(value).find('select');
      values.rules.push({
        'type':       $(selects[0]).val(),
        'comparator': $(selects[1]).val(),
        'reference':  $(value).find('input').val()
      });
    });

    db('folders')
    .find({folder})
    .tasks.push(values);
  });

  $('form').submit((event) => {
    event.preventDefault();
  })

  $scope.safeApply = function(fn) {
    var phase = this.$root.$$phase;
    if(phase === '$apply' || phase === '$digest') {
      if(fn && (typeof(fn) === 'function')) {
        fn();
      }
    } else {
      this.$apply(fn);
    }
  };
}

function getActiveFolder() {
  console.log($(index.folderList).children().find('.activeFolder'));
  let folderName = $('.activeFolder').find('h3').html();
  let folderPath = $('.activeFolder').find('p').find('i').html();
  setTimeout(() => {console.log($('.activeFolder'))}, 0);

  return {
    'name': folderName,
    'path': folderPath
  }
}

module.exports = TaskCtrl;<|endoftext|>


<commit_before>var express 		= require('express');
var bodyParser     	= require('body-parser');
var morgan         	= require('morgan');
var methodOverride 	= require('method-override');

var soap 			= require('soap');

var app 			= express();

//var misc = require('./public/javascripts/val_login');

app.use(express.static(__dirname + '/public'));     	// set the static files location /public/img will be /img for users
app.use(morgan('dev'));	                  				// log every request to the console
app.use(bodyParser.urlencoded({ extended: false }));    // parse application/x-www-form-urlencoded
app.use(bodyParser.json());    							// parse application/json
app.use(methodOverride());

app.get('/', function (req, res) {
  res.render('login.jade')
})

var url = 'http://ws.espol.edu.ec/saac/wsandroid.asmx?WSDL';
app.post('/inicio', function (req, res){
	var args = {authUser: req.body.Email, authContrasenia: req.body.Password};
	soap.createClient(url, function(err, client) {
	  	client.autenticacion(args, function(err, result) {
	  		re = result.autenticacionResult;
	  		if(re){
	  			res.render('perfil.jade',req.body.Email);
	  		}
	  		else{
	  			var f = misc.x();
	  			console.log(f);
	  			res.redirect('/');
	  		}

	  	});
	});
})

app.listen(8080);<commit_msg>appj<commit_after>var express 		= require('express');
var bodyParser     	= require('body-parser');
var morgan         	= require('morgan');
var methodOverride 	= require('method-override');

var soap 			= require('soap');

var app 			= express();

//var misc = require('./public/javascripts/val_login');

app.use(express.static(__dirname + '/public'));     	// set the static files location /public/img will be /img for users
app.use(morgan('dev'));	                  				// log every request to the console
app.use(bodyParser.urlencoded({ extended: false }));    // parse application/x-www-form-urlencoded
app.use(bodyParser.json());    							// parse application/json
app.use(methodOverride());

app.get('/', function (req, res) {
  res.render('login.jade')
})

var url = 'http://ws.espol.edu.ec/saac/wsandroid.asmx?WSDL';
app.post('/inicio', function (req, res){
	var args = {authUser: req.body.Email, authContrasenia: req.body.Password};
	soap.createClient(url, function(err, client) {
	  	client.autenticacion(args, function(err, result) {
	  		re = result.autenticacionResult;
	  		if(re){
	  			res.render('perfil.jade',req.body.Email);
	  		}
	  		else{
	  			//var f = misc.x();
	  			//console.log(f);
	  			res.redirect('/?error=' + 1);
	  		}

	  	});
	});
})

app.listen(8080);<|endoftext|>


<commit_before>throw ''
<commit_msg>Performance optimizations<commit_after>throw''
<|endoftext|>


<commit_before>import {compose} from 'compose'
import Portal from 'widget/portal'
import PropTypes from 'prop-types'
import React from 'react'
import withForwardedRef from 'ref'

class AutoFocus extends React.Component {
    focusHolderRef = React.createRef()
    state = {completed: false}

    render() {
        const {completed} = this.state
        return completed
            ? null
            : <Portal type='global'>

            </Portal>
    }

    shouldComponentUpdate(nextProps) {
        const {enabled} = nextProps
        return !!enabled
    }

    componentDidMount() {
        const {enabled} = this.props
        if (enabled) {
            const focusHolderElement = this.focusHolderRef.current
            focusHolderElement && focusHolderElement.focus()
            this.update()
        }
    }

    componentDidUpdate() {
        this.update()
    }

    update() {
        const {forwardedRef, enabled} = this.props
        const focusHolderElement = this.focusHolderRef.current
        const element = forwardedRef.current
        if (!enabled || !element || !focusHolderElement) {
            return
        }

        if (document.activeElement !== focusHolderElement) {
            this.setState({completed: true})
            return
        }

        element.focus()
        if (document.activeElement === element) {
            this.setState({completed: true})
        }
    }
}

export default compose(
    AutoFocus,
    withForwardedRef()
)

AutoFocus.propTypes = {
    enabled: PropTypes.any,
    forwardedRef: PropTypes.object
}

<commit_msg>Prevented content to shift 1px down when using AutoFocus component.<commit_after>import {compose} from 'compose'
import Portal from 'widget/portal'
import PropTypes from 'prop-types'
import React from 'react'
import withForwardedRef from 'ref'

class AutoFocus extends React.Component {
    focusHolderRef = React.createRef()
    state = {completed: false}

    render() {
        const {completed} = this.state
        return completed
            ? null
            : <Portal type='global'>

            </Portal>
    }

    shouldComponentUpdate(nextProps) {
        const {enabled} = nextProps
        return !!enabled
    }

    componentDidMount() {
        const {enabled} = this.props
        if (enabled) {
            const focusHolderElement = this.focusHolderRef.current
            focusHolderElement && focusHolderElement.focus()
            this.update()
        }
    }

    componentDidUpdate() {
        this.update()
    }

    update() {
        const {forwardedRef, enabled} = this.props
        const focusHolderElement = this.focusHolderRef.current
        const element = forwardedRef.current
        if (!enabled || !element || !focusHolderElement) {
            return
        }

        if (document.activeElement !== focusHolderElement) {
            this.setState({completed: true})
            return
        }

        element.focus()
        if (document.activeElement === element) {
            this.setState({completed: true})
        }
    }
}

export default compose(
    AutoFocus,
    withForwardedRef()
)

AutoFocus.propTypes = {
    enabled: PropTypes.any,
    forwardedRef: PropTypes.object
}

<|endoftext|>


<commit_before>//= require ./fixtures

describe('RestrictedNotesPageContainer', function() {
  var dom = window.shared.ReactHelpers.dom;
  var createEl = window.shared.ReactHelpers.createEl;
  var merge = window.shared.ReactHelpers.merge;

  var SpecSugar = window.shared.SpecSugar;
  var Fixtures = window.shared.Fixtures;
  var RestrictedNotesPageContainer = window.shared.RestrictedNotesPageContainer;

  var helpers = {
    renderInto: function(el, props) {
      var mergedProps = merge(props || {}, {
        nowMomentFn: moment.utc,
        serializedData: Fixtures.studentProfile,
      });
      return ReactDOM.render(createEl(RestrictedNotesPageContainer, mergedProps), el);
    },

    createMockApi: function(){
      var mockApi = jasmine.createSpyObj('api', ['saveNotes']);
      mockApi.saveNotes.and.returnValue(
        $.Deferred().resolve({
          id: 9999,
          text: 'hi',
          is_restricted: true,
          event_note_type_id: 301,
          student_id: 23,
          educator_id: 1
        })
      );
      return mockApi;
    },

    takeNotesAndSave: function(el, uiParams) {
      $(el).find('.btn.take-notes').click();
      SpecSugar.changeTextValue($(el).find('textarea'), uiParams.text);
      $(el).find('.btn.note-type:contains(' + uiParams.eventNoteTypeText + ')').click();
      $(el).find('.btn.save').click();
    },
  };

  SpecSugar.withTestEl('high-level integration tests', function() {
    it('saves notes as restricted', function() {
      var el = this.testEl;
      var mockApi = helpers.createMockApi();
      helpers.renderInto(el, {api: mockApi});

      helpers.takeNotesAndSave(el, {
        text: "hi",
        eventNoteTypeText: "MTSS Meeting"
      });

      // 23 is the student id, and MTSS Meeting has id 301.
      expect(mockApi.saveNotes).toHaveBeenCalledWith(23, {
        eventNoteTypeId: 301,
        text: 'hi',
        is_restricted: true,
        eventNoteAttachments: []
      });
    });
  });
});
<commit_msg>Clean up da specs<commit_after>//= require ./fixtures

describe('RestrictedNotesPageContainer', function() {
  var dom = window.shared.ReactHelpers.dom;
  var createEl = window.shared.ReactHelpers.createEl;
  var merge = window.shared.ReactHelpers.merge;

  var SpecSugar = window.shared.SpecSugar;
  var Fixtures = window.shared.Fixtures;
  var RestrictedNotesPageContainer = window.shared.RestrictedNotesPageContainer;

  var helpers = {
    renderInto: function(el, props) {
      var mergedProps = merge(props || {}, {
        nowMomentFn: moment.utc,
        serializedData: Fixtures.studentProfile,
      });
      return ReactDOM.render(createEl(RestrictedNotesPageContainer, mergedProps), el);
    },

    createMockApi: function(){
      var mockApi = jasmine.createSpyObj('api', ['saveNotes']);
      mockApi.saveNotes.and.returnValue(
        $.Deferred().resolve({
          id: 9999,
          text: 'hi',
          is_restricted: true,
          event_note_type_id: 301,
          student_id: 23,
          educator_id: 1,
          attachments: []
        })
      );
      return mockApi;
    },

    takeNotesAndSave: function(el, uiParams) {
      $(el).find('.btn.take-notes').click();
      SpecSugar.changeTextValue($(el).find('textarea'), uiParams.text);
      $(el).find('.btn.note-type:contains(' + uiParams.eventNoteTypeText + ')').click();
      $(el).find('.btn.save').click();
    },
  };

  SpecSugar.withTestEl('high-level integration tests', function() {
    it('saves notes as restricted', function() {
      var el = this.testEl;
      var mockApi = helpers.createMockApi();
      helpers.renderInto(el, {api: mockApi});

      helpers.takeNotesAndSave(el, {
        text: "hi",
        eventNoteTypeText: "MTSS Meeting"
      });

      // 23 is the student id, and MTSS Meeting has id 301.
      expect(mockApi.saveNotes).toHaveBeenCalledWith(23, {
        eventNoteTypeId: 301,
        text: 'hi',
        is_restricted: true,
        eventNoteAttachments: []
      });
    });
  });
});
<|endoftext|>


<commit_before>'use strict'

const url = require('url');
const AWS = require('aws-sdk');
const fs = require('fs');

const awsDefaultConfig = { region: 'us-east-1' };
const defaultInstanceType = 't1.micro';
const usrData = new Buffer(fs.readFileSync('./script/Startup.sh')).toString('base64');

class AwsClient {

    constructor(conf) {
        let config = conf || awsDefaultConfig;
        this.ec2 = new AWS.EC2(config);
        this.cloudWatch = new AWS.CloudWatch(config);

        this.ec2Params = {
            ImageId: 'ami-1624987f',
            InstanceType: defaultInstanceType,
            Monitoring: {
                Enabled: true
            },
            KeyName: 'MinecraftServerKey',
            NetworkInterfaces: [
                {
                    AssociatePublicIpAddress: true,
                    Groups: [
                        'sg-0626ad63',
                        'sg-ab3ba0d6'
                    ],
                    DeviceIndex: 0,
                    SubnetId: 'subnet-1aab8632'
                }
            ],
            UserData: usrData,
            MinCount: 1,
            MaxCount: 1
        };
    }

    getMetric(metric) {

    }

    createEc2Instance(instanceType, callback) {
        let params = this.ec2Params;
        params.InstanceType = instanceType || defaultInstanceType;

        this.ec2.runInstances(params, function(err, data) {
            if (err) {
                console.log("Could not create instance", err);
                return;
            }
            var instanceId = data.Instances[0].InstanceId;

            if(callback) {
                callback(instanceId);
            }
        });
    }

    getEc2BootStatus() {

    }
}

module.exports = AwsClient;<commit_msg>Updated ec2 image to be correct<commit_after>'use strict'

const url = require('url');
const AWS = require('aws-sdk');
const fs = require('fs');

const awsDefaultConfig = { region: 'us-east-1' };
const defaultInstanceType = 't1.micro';
const usrData = new Buffer(fs.readFileSync('./script/Startup.sh')).toString('base64');

class AwsClient {

    constructor(conf) {
        let config = conf || awsDefaultConfig;
        this.ec2 = new AWS.EC2(config);
        this.cloudWatch = new AWS.CloudWatch(config);

        this.ec2Params = {
            ImageId: 'ami-b73b63a0',
            InstanceType: defaultInstanceType,
            Monitoring: {
                Enabled: true
            },
            KeyName: 'MinecraftServerKey',
            NetworkInterfaces: [
                {
                    AssociatePublicIpAddress: true,
                    Groups: [
                        'sg-0626ad63',
                        'sg-ab3ba0d6'
                    ],
                    DeviceIndex: 0,
                    SubnetId: 'subnet-1aab8632'
                }
            ],
            UserData: usrData,
            MinCount: 1,
            MaxCount: 1
        };
    }

    getMetric(metric) {

    }

    createEc2Instance(instanceType, callback) {
        let params = this.ec2Params;
        params.InstanceType = instanceType || defaultInstanceType;

        this.ec2.runInstances(params, function(err, data) {
            if (err) {
                console.log("Could not create instance", err);
                return;
            }
            var instanceId = data.Instances[0].InstanceId;

            if(callback) {
                callback(instanceId);
            }
        });
    }

    getEc2BootStatus() {

    }
}

module.exports = AwsClient;<|endoftext|>


<commit_before>/**
 * @license Angulartics v0.17.2
 * (c) 2013 Luis Farzati http://luisfarzati.github.io/angulartics
 * Google Tag Manager Plugin Contributed by http://github.com/danrowe49
 * License: MIT
 */

(function(angular){
'use strict';

/**
 * @ngdoc overview
 * @name angulartics.google.analytics
 * Enables analytics support for Google Tag Manager (http://google.com/tagmanager)
 */

angular.module('angulartics.google.tagmanager', ['angulartics'])
.config(['$analyticsProvider', function($analyticsProvider){

	/**
	* Send content views to the dataLayer
	*
	* @param {string} path Required 'content name' (string) describes the content loaded
	*/

	$analyticsProvider.registerPageTrack(function(path){
		var dataLayer = window.dataLayer = window.dataLayer || [];
		dataLayer.push({
			'event': 'content-view',
			'content-name': path
		});
	});

	/**
   * Send interactions to the dataLayer, i.e. for event tracking in Google Analytics
   * @name eventTrack
   *
   * @param {string} action Required 'action' (string) associated with the event
   * @param {object} properties Comprised of the mandatory field 'category' (string) and optional  fields 'label' (string), 'value' (integer) and 'noninteraction' (boolean)
   */

	$analyticsProvider.registerEventTrack(function(action, properties){
		var dataLayer = window.dataLayer = window.dataLayer || [];
		dataLayer.push({
			'event': 'interaction',
			'target': properties.category,
			'action': action,
			'target-properties': properties.label,
			'value': properties.value,
			'interaction-type': properties.noninteraction
		});

	});
}]);

})(angular);
<commit_msg>Allow set event name for Google Tag Manager<commit_after>/**
 * @license Angulartics v0.17.2
 * (c) 2013 Luis Farzati http://luisfarzati.github.io/angulartics
 * Google Tag Manager Plugin Contributed by http://github.com/danrowe49
 * License: MIT
 */

(function(angular){
'use strict';

/**
 * @ngdoc overview
 * @name angulartics.google.analytics
 * Enables analytics support for Google Tag Manager (http://google.com/tagmanager)
 */

angular.module('angulartics.google.tagmanager', ['angulartics'])
.config(['$analyticsProvider', function($analyticsProvider){

	/**
	* Send content views to the dataLayer
	*
	* @param {string} path Required 'content name' (string) describes the content loaded
	*/

	$analyticsProvider.registerPageTrack(function(path){
		var dataLayer = window.dataLayer = window.dataLayer || [];
		dataLayer.push({
			'event': 'content-view',
			'content-name': path
		});
	});

	/**
   * Send interactions to the dataLayer, i.e. for event tracking in Google Analytics
   * @name eventTrack
   *
   * @param {string} action Required 'action' (string) associated with the event
   * @param {object} properties Comprised of the mandatory field 'category' (string) and optional  fields 'label' (string), 'value' (integer) and 'noninteraction' (boolean)
   */

	$analyticsProvider.registerEventTrack(function(action, properties){
		var dataLayer = window.dataLayer = window.dataLayer || [];
		properties = properties || {};
		dataLayer.push({
			'event': properties.event || 'interaction',
			'target': properties.category,
			'action': action,
			'target-properties': properties.label,
			'value': properties.value,
			'interaction-type': properties.noninteraction
		});

	});
}]);

})(angular);
<|endoftext|>


<commit_before>/*global jQuery:false */
(function($) {
	'use strict';
	$.fn.simpleDatePicker = function(opts) {
		var simpleDatePicker = {
			wrapper: null,
			init: function(wrapper, opts){
				this.wrapper = wrapper;
				this.opts = $.extend({
					maxAge: 120,
					minAge: 1,
					year: (new Date()).getFullYear()
				},opts);

				this.date = $(this.wrapper).find('[date]');
				this.year = $(this.wrapper).find('[year]');
				this.month = $(this.wrapper).find('[month]');
				this.day = $(this.wrapper).find('[day]');

				this.populateYearOptions();

				this.year.on('change', $.proxy(this.change, this));
				this.month.on('change', $.proxy(this.change, this));
				this.day.on('change', $.proxy(this.change, this));
			},
			parseFromDateInput: function(){
				var valArr = this.date.val().split('-');
				if (valArr.length == 3) {
					valArr = $.map(valArr, function(val){
						val = parseInt(val);
						return val > 0 ? val : -1;
					});
				} else {
					valArr = [-1,-1,-1];
					this.date.val('');
				}
				this.year.val(valArr[0]);
				this.year.val(valArr[1]);
				this.year.val(valArr[2]);
			},
			change: function(){
				if (parseInt(this.year.val()) > 0) {
					this.month.removeAttr('disabled');
				}else{
					this.month.val(-1);
					this.month.attr('disabled','disabled');
				}
				if (parseInt(this.month.val()) > 0) {
					this.day.removeAttr('disabled');
					if (this.day.val() == -1) {
						this.populateDayOptions();
					}
				}else{
					this.day.val(-1);
					this.day.attr('disabled','disabled');
				}
				// debugger;
				if (parseInt(this.day.val()) > 0) {
					this.date.val(this.formatedDate());
				} else {
					this.date.val('');
				}
			},
			formatedDate: function(){
				return this.pad(this.year.val(), 4)+'-'+this.pad(this.month.val(), 2)+'-'+this.pad(this.day.val(), 2);
			},
			populateDayOptions: function(){
				var days = this.daysInMonth(this.year.val(), this.month.val());
				this.day.find('option:not([value="-1"])').remove();
				$(this.day).append($.map(this.arrayRange(days), function(val){
					return $('<option />').val(val).text(val);
				}));
			},
			populateYearOptions: function(){
				var from = this.opts.year - this.opts.minAge;
				var to = from - this.opts.maxAge;
				$(this.year).append($.map(this.arrayRange(to, from).reverse(), function(val){
					return $('<option />').val(val).text(val);
				}));
			},
			arrayRange: function (start, edge, step) {
			  // If only one number was passed in make it the edge and 0 the start.
			  if (arguments.length == 1) {
			    edge = start;
			    start = 0;
			  }

			  // Validate the edge and step numbers.
			  edge = edge || 0;
			  step = step || 1;

			  // Create the array of numbers, stopping befor the edge.
			  for (var ret = []; (edge - start) * step > 0; start += step) {
			    ret.push(start);
			  }
			  return ret;
			},
			daysInMonth: function (year,month) {
				return new Date(year, month, 0).getDate();
			},
			pad: function (num, size) {
				var s = '000000000' + num;
				return s.substr(s.length-size);
			}
		};
		if (this.length>1) {
			var objects = [];
			$(this).each(function(){
				var instance = Object.create(simpleDatePicker);
				instance.init(this,opts);
				objects.push(instance);
			});
			return objects;
		} else {
			var instance = Object.create(simpleDatePicker);
			instance.init(this,opts);
			return instance;
		}
	};
})(jQuery);
<commit_msg>change pattern of plugin<commit_after>/*global jQuery:false */
(function($){
	function Plugin(element, options) {
		this.wrapper = $(element);
		this.opts = $.extend({
			maxAge: 120,
			minAge: 1,
			year: (new Date()).getFullYear()
		},options);
		this.init();
	}
	Plugin.prototype.init = function() {
		this.date = $(this.wrapper).find('[date]');
		this.year = $(this.wrapper).find('[year]');
		this.month = $(this.wrapper).find('[month]');
		this.day = $(this.wrapper).find('[day]');
		this.populateYearOptions();
		this.year.on('change', $.proxy(this.change, this));
		this.month.on('change', $.proxy(this.change, this));
		this.day.on('change', $.proxy(this.change, this));
	};
	Plugin.prototype.parseFromDateInput = function(){
		var valArr = this.date.val().split('-');
		if (valArr.length == 3) {
			valArr = $.map(valArr, function(val){
				val = parseInt(val);
				return val > 0 ? val : -1;
			});
		} else {
			valArr = [-1,-1,-1];
			this.date.val('');
		}
		this.year.val(valArr[0]);
		this.year.val(valArr[1]);
		this.year.val(valArr[2]);
	};
	Plugin.prototype.change = function(){
		if (parseInt(this.year.val()) > 0) {
			this.month.removeAttr('disabled');
		}else{
			this.month.val(-1);
			this.month.attr('disabled','disabled');
		}
		if (parseInt(this.month.val()) > 0) {
			this.day.removeAttr('disabled');
			if (this.day.val() == -1) {
				this.populateDayOptions();
			}
		}else{
			this.day.val(-1);
			this.day.attr('disabled','disabled');
		}
		// debugger;
		if (parseInt(this.day.val()) > 0) {
			this.date.val(this.formatedDate());
		} else {
			this.date.val('');
		}
	};
	Plugin.prototype.formatedDate = function(){
		return this.pad(this.year.val(), 4)+'-'+this.pad(this.month.val(), 2)+'-'+this.pad(this.day.val(), 2);
	};
	Plugin.prototype.populateDayOptions = function(){
		var days = this.daysInMonth(this.year.val(), this.month.val());
		this.day.find('option:not([value="-1"])').remove();
		$(this.day).append($.map(this.arrayRange(days), function(val){
			return $('<option />').val(val).text(val);
		}));
	};
	Plugin.prototype.populateYearOptions = function(){
		var from = this.opts.year - this.opts.minAge;
		var to = from - this.opts.maxAge;
		$(this.year).append($.map(this.arrayRange(to, from).reverse(), function(val){
			return $('<option />').val(val).text(val);
		}));
	};
	Plugin.prototype.arrayRange = function (start, edge, step) {
		// If only one number was passed in make it the edge and 0 the start.
		if (arguments.length == 1) {
			edge = start;
			start = 0;
		}
		// Validate the edge and step numbers.
		edge = edge || 0;
		step = step || 1;
		// Create the array of numbers, stopping befor the edge.
		for (var ret = []; (edge - start) * step > 0; start += step) {
			ret.push(start);
		}
		return ret;
	};
	Plugin.prototype.daysInMonth = function (year,month) {
		return new Date(year, month, 0).getDate();
	};
	Plugin.prototype.pad = function (num, size) {
		var s = '000000000' + num;
		return s.substr(s.length-size);
	};
	$.fn.simpleDatePicker = function ( options ) {
		return $(this).each(function () {
			$.data(this, 'simpleDatePicker', new Plugin( this, options ));
		});
	};
})(jQuery);
<|endoftext|>