<commit_before>'use strict'

function _process (v, mod) {
  var i
  var r

  if (typeof mod === 'function') {
    r = mod(v)
    if (r !== undefined) {
      v = r
    }
  } else if (Array.isArray(mod)) {
    for (i = 0; i < mod.length; i++) {
      r = mod[i](v)
      if (r !== undefined) {
        v = r
      }
    }
  }

  return v
}

function parseKey (key, val) {
  // detect negative index notation
  if (key[0] === '-' && Array.isArray(val) && /^-\d+$/.test(key)) {
    return val.length + parseInt(key, 10)
  }
  return key
}

function isIndex (k) {
  return /^\d+$/.test(k)
}

function isObject (val) {
  return Object.prototype.toString.call(val) === '[object Object]'
}

function isArrayOrObject (val) {
  return Object(val) === val
}

function isEmptyObject (val) {
  return Object.keys(val).length === 0
}

function parsePath (path, sep) {
  if (path.indexOf('[') >= 0) {
    path = path.replace(/\[/g, '.').replace(/]/g, '')
  }
  return path.split(sep)
}

function DotObject (separator, override, useArray) {
  if (!(this instanceof DotObject)) {
    return new DotObject(separator, override, useArray)
  }

  if (typeof override === 'undefined') override = false
  if (typeof useArray === 'undefined') useArray = true
  this.separator = separator || '.'
  this.override = override
  this.useArray = useArray
  this.keepArray = false

  // contains touched arrays
  this.cleanup = []
}

var dotDefault = new DotObject('.', false, true)
function wrap (method) {
  return function () {
    return dotDefault[method].apply(dotDefault, arguments)
  }
}

DotObject.prototype._fill = function (a, obj, v, mod) {
  var k = a.shift()

  if (a.length > 0) {
    obj[k] = obj[k] ||
      (this.useArray && isIndex(a[0]) ? [] : {})

    if (!isArrayOrObject(obj[k])) {
      if (this.override) {
        obj[k] = {}
      } else {
        if (!(isArrayOrObject(v) && isEmptyObject(v))) {
          throw new Error(
            'Trying to redefine `' + k + '` which is a ' + typeof obj[k]
          )
        }

        return
      }
    }

    this._fill(a, obj[k], v, mod)
  } else {
    if (!this.override &&
      isArrayOrObject(obj[k]) && !isEmptyObject(obj[k])) {
      if (!(isArrayOrObject(v) && isEmptyObject(v))) {
        throw new Error("Trying to redefine non-empty obj['" + k + "']")
      }

      return
    }

    obj[k] = _process(v, mod)
  }
}

/**
 *
 * Converts an object with dotted-key/value pairs to it's expanded version
 *
 * Optionally transformed by a set of modifiers.
 *
 * Usage:
 *
 *   var row = {
 *     'nr': 200,
 *     'doc.name': '  My Document  '
 *   }
 *
 *   var mods = {
 *     'doc.name': [_s.trim, _s.underscored]
 *   }
 *
 *   dot.object(row, mods)
 *
 * @param {Object} obj
 * @param {Object} mods
 */
DotObject.prototype.object = function (obj, mods) {
  var self = this

  Object.keys(obj).forEach(function (k) {
    var mod = mods === undefined ? null : mods[k]
    // normalize array notation.
    var ok = parsePath(k, self.separator).join(self.separator)

    if (ok.indexOf(self.separator) !== -1) {
      self._fill(ok.split(self.separator), obj, obj[k], mod)
      delete obj[k]
    } else if (self.override) {
      obj[k] = _process(obj[k], mod)
    }
  })

  return obj
}

/**
 * @param {String} path dotted path
 * @param {String} v value to be set
 * @param {Object} obj object to be modified
 * @param {Function|Array} mod optional modifier
 */
DotObject.prototype.str = function (path, v, obj, mod) {
  if (path.indexOf(this.separator) !== -1) {
    this._fill(path.split(this.separator), obj, v, mod)
  } else if (!obj.hasOwnProperty(path) || this.override) {
    obj[path] = _process(v, mod)
  }

  return obj
}

/**
 *
 * Pick a value from an object using dot notation.
 *
 * Optionally remove the value
 *
 * @param {String} path
 * @param {Object} obj
 * @param {Boolean} remove
 */
DotObject.prototype.pick = function (path, obj, remove) {
  var i
  var keys
  var val
  var key
  var cp

  keys = parsePath(path, this.separator)
  for (i = 0; i < keys.length; i++) {
    key = parseKey(keys[i], obj)
    if (obj && typeof obj === 'object' && key in obj) {
      if (i === (keys.length - 1)) {
        if (remove) {
          val = obj[key]
          delete obj[key]
          if (Array.isArray(obj)) {
            cp = keys.slice(0, -1).join('.')
            if (this.cleanup.indexOf(cp) === -1) {
              this.cleanup.push(cp)
            }
          }
          return val
        } else {
          return obj[key]
        }
      } else {
        obj = obj[key]
      }
    } else {
      return undefined
    }
  }
  if (remove && Array.isArray(obj)) {
    obj = obj.filter(function (n) { return n !== undefined })
  }
  return obj
}

/**
 *
 * Remove value from an object using dot notation.
 *
 * @param {String} path
 * @param {Object} obj
 * @return {Mixed} The removed value
 */
DotObject.prototype.remove = function (path, obj) {
  var i

  this.cleanup = []
  if (Array.isArray(path)) {
    for (i = 0; i < path.length; i++) {
      this.pick(path[i], obj, true)
    }
    this._cleanup(obj)
    return obj
  } else {
    return this.pick(path, obj, true)
  }
}

DotObject.prototype._cleanup = function (obj) {
  var ret
  var i
  var keys
  var root
  if (this.cleanup.length) {
    for (i = 0; i < this.cleanup.length; i++) {
      keys = this.cleanup[i].split('.')
      root = keys.splice(0, -1).join('.')
      ret = root ? this.pick(root, obj) : obj
      ret = ret[keys[0]].filter(function (v) { return v !== undefined })
      this.set(this.cleanup[i], ret, obj)
    }
    this.cleanup = []
  }
}

// alias method
DotObject.prototype.del = DotObject.prototype.remove

/**
 *
 * Move a property from one place to the other.
 *
 * If the source path does not exist (undefined)
 * the target property will not be set.
 *
 * @param {String} source
 * @param {String} target
 * @param {Object} obj
 * @param {Function|Array} mods
 * @param {Boolean} merge
 */
DotObject.prototype.move = function (source, target, obj, mods, merge) {
  if (typeof mods === 'function' || Array.isArray(mods)) {
    this.set(target, _process(this.pick(source, obj, true), mods), obj, merge)
  } else {
    merge = mods
    this.set(target, this.pick(source, obj, true), obj, merge)
  }

  return obj
}

/**
 *
 * Transfer a property from one object to another object.
 *
 * If the source path does not exist (undefined)
 * the property on the other object will not be set.
 *
 * @param {String} source
 * @param {String} target
 * @param {Object} obj1
 * @param {Object} obj2
 * @param {Function|Array} mods
 * @param {Boolean} merge
 */
DotObject.prototype.transfer = function (source, target, obj1, obj2, mods, merge) {
  if (typeof mods === 'function' || Array.isArray(mods)) {
    this.set(target,
      _process(
        this.pick(source, obj1, true),
        mods
      ), obj2, merge)
  } else {
    merge = mods
    this.set(target, this.pick(source, obj1, true), obj2, merge)
  }

  return obj2
}

/**
 *
 * Copy a property from one object to another object.
 *
 * If the source path does not exist (undefined)
 * the property on the other object will not be set.
 *
 * @param {String} source
 * @param {String} target
 * @param {Object} obj1
 * @param {Object} obj2
 * @param {Function|Array} mods
 * @param {Boolean} merge
 */
DotObject.prototype.copy = function (source, target, obj1, obj2, mods, merge) {
  if (typeof mods === 'function' || Array.isArray(mods)) {
    this.set(target,
      _process(
        // clone what is picked
        JSON.parse(
          JSON.stringify(
            this.pick(source, obj1, false)
          )
        ),
        mods
      ), obj2, merge)
  } else {
    merge = mods
    this.set(target, this.pick(source, obj1, false), obj2, merge)
  }

  return obj2
}

/**
 *
 * Set a property on an object using dot notation.
 *
 * @param {String} path
 * @param {Mixed} val
 * @param {Object} obj
 * @param {Boolean} merge
 */
DotObject.prototype.set = function (path, val, obj, merge) {
  var i
  var k
  var keys
  var key

  // Do not operate if the value is undefined.
  if (typeof val === 'undefined') {
    return obj
  }
  keys = parsePath(path, this.separator)

  for (i = 0; i < keys.length; i++) {
    key = keys[i]
    if (i === (keys.length - 1)) {
      if (merge && isObject(val) && isObject(obj[key])) {
        for (k in val) {
          if (val.hasOwnProperty(k)) {
            obj[key][k] = val[k]
          }
        }
      } else if (merge && Array.isArray(obj[key]) && Array.isArray(val)) {
        for (var j = 0; j < val.length; j++) {
          obj[keys[i]].push(val[j])
        }
      } else {
        obj[key] = val
      }
    } else if (
      // force the value to be an object
      !obj.hasOwnProperty(key) ||
      (!isObject(obj[key]) && !Array.isArray(obj[key]))
    ) {
      // initialize as array if next key is numeric
      if (/^\d+$/.test(keys[i + 1])) {
        obj[key] = []
      } else {
        obj[key] = {}
      }
    }
    obj = obj[key]
  }
  return obj
}

/**
 *
 * Transform an object
 *
 * Usage:
 *
 *   var obj = {
 *     "id": 1,
  *    "some": {
  *      "thing": "else"
  *    }
 *   }
 *
 *   var transform = {
 *     "id": "nr",
  *    "some.thing": "name"
 *   }
 *
 *   var tgt = dot.transform(transform, obj)
 *
 * @param {Object} recipe Transform recipe
 * @param {Object} obj Object to be transformed
 * @param {Array} mods modifiers for the target
 */
DotObject.prototype.transform = function (recipe, obj, tgt) {
  obj = obj || {}
  tgt = tgt || {}
  Object.keys(recipe).forEach(function (key) {
    this.set(recipe[key], this.pick(key, obj), tgt)
  }.bind(this))
  return tgt
}

/**
 *
 * Convert object to dotted-key/value pair
 *
 * Usage:
 *
 *   var tgt = dot.dot(obj)
 *
 *   or
 *
 *   var tgt = {}
 *   dot.dot(obj, tgt)
 *
 * @param {Object} obj source object
 * @param {Object} tgt target object
 * @param {Array} path path array (internal)
 */
DotObject.prototype.dot = function (obj, tgt, path) {
  tgt = tgt || {}
  path = path || []
  Object.keys(obj).forEach(function (key) {
    if (
      (
        isArrayOrObject(obj[key]) &&
        (
          (isObject(obj[key]) && !isEmptyObject(obj[key])) ||
          (Array.isArray(obj[key]) && (!this.keepArray && (obj[key].length !== 0)))
        )
      )
    ) {
      return this.dot(obj[key], tgt, path.concat(key))
    } else {
      tgt[path.concat(key).join(this.separator)] = obj[key]
    }
  }.bind(this))
  return tgt
}

DotObject.pick = wrap('pick')
DotObject.move = wrap('move')
DotObject.transfer = wrap('transfer')
DotObject.transform = wrap('transform')
DotObject.copy = wrap('copy')
DotObject.object = wrap('object')
DotObject.str = wrap('str')
DotObject.set = wrap('set')
DotObject.del = DotObject.remove = wrap('remove')
DotObject.dot = wrap('dot')

;['override', 'overwrite'].forEach(function (prop) {
  Object.defineProperty(DotObject, prop, {
    get: function () {
      return dotDefault.override
    },
    set: function (val) {
      dotDefault.override = !!val
    }
  })
})

;['useArray', 'keepArray'].forEach(function (prop) {
  Object.defineProperty(DotObject, prop, {
    get: function () {
      return dotDefault[prop]
    },
    set: function (val) {
      dotDefault[prop] = val
    }
  })
})

DotObject._process = _process
<commit_msg>added option for reindexing array<commit_after>'use strict'

function _process (v, mod) {
  var i
  var r

  if (typeof mod === 'function') {
    r = mod(v)
    if (r !== undefined) {
      v = r
    }
  } else if (Array.isArray(mod)) {
    for (i = 0; i < mod.length; i++) {
      r = mod[i](v)
      if (r !== undefined) {
        v = r
      }
    }
  }

  return v
}

function parseKey (key, val) {
  // detect negative index notation
  if (key[0] === '-' && Array.isArray(val) && /^-\d+$/.test(key)) {
    return val.length + parseInt(key, 10)
  }
  return key
}

function isIndex (k) {
  return /^\d+$/.test(k)
}

function isObject (val) {
  return Object.prototype.toString.call(val) === '[object Object]'
}

function isArrayOrObject (val) {
  return Object(val) === val
}

function isEmptyObject (val) {
  return Object.keys(val).length === 0
}

function parsePath (path, sep) {
  if (path.indexOf('[') >= 0) {
    path = path.replace(/\[/g, '.').replace(/]/g, '')
  }
  return path.split(sep)
}

function DotObject (separator, override, useArray) {
  if (!(this instanceof DotObject)) {
    return new DotObject(separator, override, useArray)
  }

  if (typeof override === 'undefined') override = false
  if (typeof useArray === 'undefined') useArray = true
  this.separator = separator || '.'
  this.override = override
  this.useArray = useArray
  this.keepArray = false

  // contains touched arrays
  this.cleanup = []
}

var dotDefault = new DotObject('.', false, true)
function wrap (method) {
  return function () {
    return dotDefault[method].apply(dotDefault, arguments)
  }
}

DotObject.prototype._fill = function (a, obj, v, mod) {
  var k = a.shift()

  if (a.length > 0) {
    obj[k] = obj[k] ||
      (this.useArray && isIndex(a[0]) ? [] : {})

    if (!isArrayOrObject(obj[k])) {
      if (this.override) {
        obj[k] = {}
      } else {
        if (!(isArrayOrObject(v) && isEmptyObject(v))) {
          throw new Error(
            'Trying to redefine `' + k + '` which is a ' + typeof obj[k]
          )
        }

        return
      }
    }

    this._fill(a, obj[k], v, mod)
  } else {
    if (!this.override &&
      isArrayOrObject(obj[k]) && !isEmptyObject(obj[k])) {
      if (!(isArrayOrObject(v) && isEmptyObject(v))) {
        throw new Error("Trying to redefine non-empty obj['" + k + "']")
      }

      return
    }

    obj[k] = _process(v, mod)
  }
}

/**
 *
 * Converts an object with dotted-key/value pairs to it's expanded version
 *
 * Optionally transformed by a set of modifiers.
 *
 * Usage:
 *
 *   var row = {
 *     'nr': 200,
 *     'doc.name': '  My Document  '
 *   }
 *
 *   var mods = {
 *     'doc.name': [_s.trim, _s.underscored]
 *   }
 *
 *   dot.object(row, mods)
 *
 * @param {Object} obj
 * @param {Object} mods
 */
DotObject.prototype.object = function (obj, mods) {
  var self = this

  Object.keys(obj).forEach(function (k) {
    var mod = mods === undefined ? null : mods[k]
    // normalize array notation.
    var ok = parsePath(k, self.separator).join(self.separator)

    if (ok.indexOf(self.separator) !== -1) {
      self._fill(ok.split(self.separator), obj, obj[k], mod)
      delete obj[k]
    } else if (self.override) {
      obj[k] = _process(obj[k], mod)
    }
  })

  return obj
}

/**
 * @param {String} path dotted path
 * @param {String} v value to be set
 * @param {Object} obj object to be modified
 * @param {Function|Array} mod optional modifier
 */
DotObject.prototype.str = function (path, v, obj, mod) {
  if (path.indexOf(this.separator) !== -1) {
    this._fill(path.split(this.separator), obj, v, mod)
  } else if (!obj.hasOwnProperty(path) || this.override) {
    obj[path] = _process(v, mod)
  }

  return obj
}

/**
 *
 * Pick a value from an object using dot notation.
 *
 * Optionally remove the value
 *
 * @param {String} path
 * @param {Object} obj
 * @param {Boolean} remove
 */
DotObject.prototype.pick = function (path, obj, remove, reindexRemove) {
  var i
  var keys
  var val
  var key
  var cp

  keys = parsePath(path, this.separator)
  for (i = 0; i < keys.length; i++) {
    key = parseKey(keys[i], obj)
    if (obj && typeof obj === 'object' && key in obj) {
      if (i === (keys.length - 1)) {
        if (remove) {
          val = obj[key]
          if (reindexRemove) {
            obj.splice(key, 1)
          } else {
            delete obj[key]
          }
          if (Array.isArray(obj)) {
            cp = keys.slice(0, -1).join('.')
            if (this.cleanup.indexOf(cp) === -1) {
              this.cleanup.push(cp)
            }
          }
          return val
        } else {
          return obj[key]
        }
      } else {
        obj = obj[key]
      }
    } else {
      return undefined
    }
  }
  if (remove && Array.isArray(obj)) {
    obj = obj.filter(function (n) { return n !== undefined })
  }
  return obj
}

/**
 *
 * Remove value from an object using dot notation.
 *
 * @param {String} path
 * @param {Object} obj
 * @return {Mixed} The removed value
 */
DotObject.prototype.remove = function (path, obj, reindexRemove) {
  var i

  this.cleanup = []
  if (Array.isArray(path)) {
    for (i = 0; i < path.length; i++) {
      this.pick(path[i], obj, true, reindexRemove)
    }
    this._cleanup(obj)
    return obj
  } else {
    return this.pick(path, obj, true, reindexRemove)
  }
}

DotObject.prototype._cleanup = function (obj) {
  var ret
  var i
  var keys
  var root
  if (this.cleanup.length) {
    for (i = 0; i < this.cleanup.length; i++) {
      keys = this.cleanup[i].split('.')
      root = keys.splice(0, -1).join('.')
      ret = root ? this.pick(root, obj) : obj
      ret = ret[keys[0]].filter(function (v) { return v !== undefined })
      this.set(this.cleanup[i], ret, obj)
    }
    this.cleanup = []
  }
}

// alias method
DotObject.prototype.del = DotObject.prototype.remove

/**
 *
 * Move a property from one place to the other.
 *
 * If the source path does not exist (undefined)
 * the target property will not be set.
 *
 * @param {String} source
 * @param {String} target
 * @param {Object} obj
 * @param {Function|Array} mods
 * @param {Boolean} merge
 */
DotObject.prototype.move = function (source, target, obj, mods, merge) {
  if (typeof mods === 'function' || Array.isArray(mods)) {
    this.set(target, _process(this.pick(source, obj, true), mods), obj, merge)
  } else {
    merge = mods
    this.set(target, this.pick(source, obj, true), obj, merge)
  }

  return obj
}

/**
 *
 * Transfer a property from one object to another object.
 *
 * If the source path does not exist (undefined)
 * the property on the other object will not be set.
 *
 * @param {String} source
 * @param {String} target
 * @param {Object} obj1
 * @param {Object} obj2
 * @param {Function|Array} mods
 * @param {Boolean} merge
 */
DotObject.prototype.transfer = function (source, target, obj1, obj2, mods, merge) {
  if (typeof mods === 'function' || Array.isArray(mods)) {
    this.set(target,
      _process(
        this.pick(source, obj1, true),
        mods
      ), obj2, merge)
  } else {
    merge = mods
    this.set(target, this.pick(source, obj1, true), obj2, merge)
  }

  return obj2
}

/**
 *
 * Copy a property from one object to another object.
 *
 * If the source path does not exist (undefined)
 * the property on the other object will not be set.
 *
 * @param {String} source
 * @param {String} target
 * @param {Object} obj1
 * @param {Object} obj2
 * @param {Function|Array} mods
 * @param {Boolean} merge
 */
DotObject.prototype.copy = function (source, target, obj1, obj2, mods, merge) {
  if (typeof mods === 'function' || Array.isArray(mods)) {
    this.set(target,
      _process(
        // clone what is picked
        JSON.parse(
          JSON.stringify(
            this.pick(source, obj1, false)
          )
        ),
        mods
      ), obj2, merge)
  } else {
    merge = mods
    this.set(target, this.pick(source, obj1, false), obj2, merge)
  }

  return obj2
}

/**
 *
 * Set a property on an object using dot notation.
 *
 * @param {String} path
 * @param {Mixed} val
 * @param {Object} obj
 * @param {Boolean} merge
 */
DotObject.prototype.set = function (path, val, obj, merge) {
  var i
  var k
  var keys
  var key

  // Do not operate if the value is undefined.
  if (typeof val === 'undefined') {
    return obj
  }
  keys = parsePath(path, this.separator)

  for (i = 0; i < keys.length; i++) {
    key = keys[i]
    if (i === (keys.length - 1)) {
      if (merge && isObject(val) && isObject(obj[key])) {
        for (k in val) {
          if (val.hasOwnProperty(k)) {
            obj[key][k] = val[k]
          }
        }
      } else if (merge && Array.isArray(obj[key]) && Array.isArray(val)) {
        for (var j = 0; j < val.length; j++) {
          obj[keys[i]].push(val[j])
        }
      } else {
        obj[key] = val
      }
    } else if (
      // force the value to be an object
      !obj.hasOwnProperty(key) ||
      (!isObject(obj[key]) && !Array.isArray(obj[key]))
    ) {
      // initialize as array if next key is numeric
      if (/^\d+$/.test(keys[i + 1])) {
        obj[key] = []
      } else {
        obj[key] = {}
      }
    }
    obj = obj[key]
  }
  return obj
}

/**
 *
 * Transform an object
 *
 * Usage:
 *
 *   var obj = {
 *     "id": 1,
  *    "some": {
  *      "thing": "else"
  *    }
 *   }
 *
 *   var transform = {
 *     "id": "nr",
  *    "some.thing": "name"
 *   }
 *
 *   var tgt = dot.transform(transform, obj)
 *
 * @param {Object} recipe Transform recipe
 * @param {Object} obj Object to be transformed
 * @param {Array} mods modifiers for the target
 */
DotObject.prototype.transform = function (recipe, obj, tgt) {
  obj = obj || {}
  tgt = tgt || {}
  Object.keys(recipe).forEach(function (key) {
    this.set(recipe[key], this.pick(key, obj), tgt)
  }.bind(this))
  return tgt
}

/**
 *
 * Convert object to dotted-key/value pair
 *
 * Usage:
 *
 *   var tgt = dot.dot(obj)
 *
 *   or
 *
 *   var tgt = {}
 *   dot.dot(obj, tgt)
 *
 * @param {Object} obj source object
 * @param {Object} tgt target object
 * @param {Array} path path array (internal)
 */
DotObject.prototype.dot = function (obj, tgt, path) {
  tgt = tgt || {}
  path = path || []
  Object.keys(obj).forEach(function (key) {
    if (
      (
        isArrayOrObject(obj[key]) &&
        (
          (isObject(obj[key]) && !isEmptyObject(obj[key])) ||
          (Array.isArray(obj[key]) && (!this.keepArray && (obj[key].length !== 0)))
        )
      )
    ) {
      return this.dot(obj[key], tgt, path.concat(key))
    } else {
      tgt[path.concat(key).join(this.separator)] = obj[key]
    }
  }.bind(this))
  return tgt
}

DotObject.pick = wrap('pick')
DotObject.move = wrap('move')
DotObject.transfer = wrap('transfer')
DotObject.transform = wrap('transform')
DotObject.copy = wrap('copy')
DotObject.object = wrap('object')
DotObject.str = wrap('str')
DotObject.set = wrap('set')
DotObject.del = DotObject.remove = wrap('remove')
DotObject.dot = wrap('dot')

;['override', 'overwrite'].forEach(function (prop) {
  Object.defineProperty(DotObject, prop, {
    get: function () {
      return dotDefault.override
    },
    set: function (val) {
      dotDefault.override = !!val
    }
  })
})

;['useArray', 'keepArray'].forEach(function (prop) {
  Object.defineProperty(DotObject, prop, {
    get: function () {
      return dotDefault[prop]
    },
    set: function (val) {
      dotDefault[prop] = val
    }
  })
})

DotObject._process = _process
<|endoftext|>


<commit_before>'use babel';

import { CompositeDisposable } from 'atom';
import path from 'path';
import config from './settings';
import childProcess from 'child_process';

module.exports = {
  config,
  subscriptions: null,

  activate() {
    this.subscriptions = new CompositeDisposable;
    this.subscriptions.add(atom.commands.add('atom-workspace', {
      'elm-format:file': () => this.formatCurrentFile(),
    }));
    this.subscriptions.add(atom.workspace.observeTextEditors(e => this.handleEvents(e)));
  },

  handleEvents(editor) {
    editor.getBuffer().onWillSave(() => {
      if (atom.config.get('elm-format.formatOnSave') && this.isElmEditor(editor)) {
        this.format(editor);
      }
    });
  },

  deactivate() {
    this.subscriptions.dispose();
  },

  error(str) {
    if (atom.config.get('elm-format.showErrorNotifications')) {
      atom.notifications.addError(str);
    }
  },

  success(str) {
    if (atom.config.get('elm-format.showNotifications')) {
      atom.notifications.addSuccess(str);
    }
  },

  formatCurrentFile() {
    const editor = atom.workspace.getActiveTextEditor();
    if (!editor) {
      return;
    }
    if (this.isElmEditor(editor)) {
      this.format(editor);
    } else {
      atom.notifications.addInfo('Not an Elm file', {
        dismissable: false,
        detail: 'I only know how to format .elm-files, sorry!',
      });
    }
  },

  isElmEditor(editor) {
    return editor && editor.getPath && editor.getPath() &&
      path.extname(editor.getPath()) === '.elm';
  },

  format(editor) {
    try {
      const { status, stdout } = childProcess.spawnSync(
        atom.config.get('elm-format.binary'),
        ['--stdin'], { input: editor.getText() });
      if (status === 0) {
        const cursorPosition = editor.getCursorScreenPosition();
        // const marker = editor.markScreenRange([cursorPosition, cursorPosition], {
        //   invalidate: 'never', persistent: false
        // });
        editor.buffer.setTextViaDiff(stdout.toString());
        // editor.setCursorScreenPosition(marker.getStartScreenPosition());
        // marker.destroy();
        editor.setCursorScreenPosition(cursorPosition);

        this.success('Formatted file');
      } else {
        this.error(`elm-format exited with code ${status}`);
      }
    } catch (exception) {
      this.error(`elm-format exception: ${exception}`);
    }
  },
};
<commit_msg>Remove commented code<commit_after>'use babel';

import { CompositeDisposable } from 'atom';
import path from 'path';
import config from './settings';
import childProcess from 'child_process';

module.exports = {
  config,
  subscriptions: null,

  activate() {
    this.subscriptions = new CompositeDisposable;
    this.subscriptions.add(atom.commands.add('atom-workspace', {
      'elm-format:file': () => this.formatCurrentFile(),
    }));
    this.subscriptions.add(atom.workspace.observeTextEditors(e => this.handleEvents(e)));
  },

  handleEvents(editor) {
    editor.getBuffer().onWillSave(() => {
      if (atom.config.get('elm-format.formatOnSave') && this.isElmEditor(editor)) {
        this.format(editor);
      }
    });
  },

  deactivate() {
    this.subscriptions.dispose();
  },

  error(str) {
    if (atom.config.get('elm-format.showErrorNotifications')) {
      atom.notifications.addError(str);
    }
  },

  success(str) {
    if (atom.config.get('elm-format.showNotifications')) {
      atom.notifications.addSuccess(str);
    }
  },

  formatCurrentFile() {
    const editor = atom.workspace.getActiveTextEditor();
    if (!editor) {
      return;
    }
    if (this.isElmEditor(editor)) {
      this.format(editor);
    } else {
      atom.notifications.addInfo('Not an Elm file', {
        dismissable: false,
        detail: 'I only know how to format .elm-files, sorry!',
      });
    }
  },

  isElmEditor(editor) {
    return editor && editor.getPath && editor.getPath() &&
      path.extname(editor.getPath()) === '.elm';
  },

  format(editor) {
    try {
      const { status, stdout } = childProcess.spawnSync(
        atom.config.get('elm-format.binary'),
        ['--stdin'], { input: editor.getText() });
      if (status === 0) {
        const cursorPosition = editor.getCursorScreenPosition();
        editor.buffer.setTextViaDiff(stdout.toString());
        editor.setCursorScreenPosition(cursorPosition);

        this.success('Formatted file');
      } else {
        this.error(`elm-format exited with code ${status}`);
      }
    } catch (exception) {
      this.error(`elm-format exception: ${exception}`);
    }
  },
};
<|endoftext|>


<commit_before>'use strict'

const _ = require('lodash')
const _h = require('../_helpers')

exports.handler = async (event, context) => {
  if (event.source === 'aws.events') { return }

  try {
    const user = await _h.user(event)
    const eId = event.pathParameters && event.pathParameters.id ? _h.strToId(event.pathParameters.id) : null
    const props = _.get(event, 'queryStringParameters.props', '').split(',').filter((x) => !!x)
    var fields = {}
    var result = {}

    if (props.length > 0) {
      props.forEach((f) => {
        if (f === '_thumbnail') {
          fields[`private.photo.s3`] = true
          fields[`public.photo.s3`] = true
        } else {
          fields[`private.${f}`] = true
          fields[`public.${f}`] = true
        }
      })
      fields['access'] = true
    }

    if (eId) {
      const entity = await user.db.collection('entity').findOne({ _id: eId }, { projection: fields })
      if (!entity) { return _h.error([404, 'Entity not found']) }

      result = await _h.claenupEntity(entity, user)

      if (!result) { return _h.error([403, 'No accessible properties']) }
    } else {
      const sort = _.get(event, 'queryStringParameters.sort', '').split(',').filter(x => !!x)
      const limit = _.toSafeInteger(_.get(event, 'queryStringParameters.limit')) || 100
      const skip = _.toSafeInteger(_.get(event, 'queryStringParameters.skip')) || 0
      const query = _.get(event, 'queryStringParameters.q', '').split(' ').filter(x => !!x)
      var sortFields = {}
      var filter = {}

      _.forIn(_.get(event, 'queryStringParameters'), (v, k) => {
        if (k.includes('.')) {
          const fieldArray = k.split('.')
          let field = _.get(fieldArray, 0)
          let type = _.get(fieldArray, 1)
          let operator = _.get(fieldArray, 2)
          let value

          switch (type) {
            case 'reference':
              value = _h.strToId(v)
              break
            case 'boolean':
              value = v.toLowerCase() === 'true'
              break
            case 'integer':
              value = _.toNumber(v)
              break
            case 'size':
              value = _.toNumber(v)
              break
            case 'decimal':
              value = _.toNumber(v)
              break
            case 'date':
              value = new Date(v)
              break
            case 'datetime':
              value = new Date(v)
              break
            default:
              if (operator === 'regex' && v.includes('/')) {
                value = new RegExp(v.split('/')[1], v.split('/')[2])
              } else if (operator === 'exists') {
                value = v.toLowerCase() === 'true'
              } else {
                value = v
              }
          }

          if (['gt', 'gte', 'lt', 'lte', 'ne', 'regex', 'exists'].includes(operator)) {
            _.set(filter, [`private.${field}.${type}`, `$${operator}`], value)
          } else {
            filter[`private.${field}.${type}`] = value
          }
        }
      })

      if (user.id) {
        filter.access = { '$in': [_h.strToId(user.id), 'public'] }
      } else {
        filter.access = 'public'
      }

      if (query.length > 0) {
        let queries = query.map((q) => {
          return { 'search.private': new RegExp(q.toLowerCase()) }
        })
        filter['$and'] = queries
      }

      if (sort.length > 0) {
        sort.forEach((f) => {
          if (f.startsWith('-')) {
            sortFields[`private.${f.substring(1)}`] = -1
          } else {
            sortFields[`private.${f}`] = 1
          }
        })
      } else {
        sortFields = { _id: 1 }
      }

      const findedEntities = await user.db.collection('entity').find(filter, { projection: fields })
      const count = await findedEntities.count()
      const entities = await findedEntities.sort(sortFields).skip(skip).limit(limit).toArray()

      let cleanedEntities = []
      for (let i = 0; i < entities.length; i++) {
        const entity = await _h.claenupEntity(entities[i], user)
        if (entity) {
          cleanedEntities.push(entity)
        }
      }

      result = {
        count: count,
        entities: cleanedEntities
      }
    }

    return _h.json(result)
  } catch (e) {
    return _h.error(e)
  }
}
<commit_msg>Update Entity GET response structure<commit_after>'use strict'

const _ = require('lodash')
const _h = require('../_helpers')

exports.handler = async (event, context) => {
  if (event.source === 'aws.events') { return }

  try {
    const user = await _h.user(event)
    const eId = event.pathParameters && event.pathParameters.id ? _h.strToId(event.pathParameters.id) : null
    const props = _.get(event, 'queryStringParameters.props', '').split(',').filter((x) => !!x)
    var fields = {}
    var result = {}

    if (props.length > 0) {
      props.forEach((f) => {
        if (f === '_thumbnail') {
          fields[`private.photo.s3`] = true
          fields[`public.photo.s3`] = true
        } else {
          fields[`private.${f}`] = true
          fields[`public.${f}`] = true
        }
      })
      fields['access'] = true
    }

    if (eId) {
      const entity = await user.db.collection('entity').findOne({ _id: eId }, { projection: fields })
      if (!entity) { return _h.error([404, 'Entity not found']) }

      const cleanedEntity = await _h.claenupEntity(entity, user)

      if (!cleanedEntity) { return _h.error([403, 'No accessible properties']) }

      result = {
        filter: { _id: eId },
        props: props,
        entity: cleanedEntity
      }
    } else {
      const sort = _.get(event, 'queryStringParameters.sort', '').split(',').filter(x => !!x)
      const limit = _.toSafeInteger(_.get(event, 'queryStringParameters.limit')) || 100
      const skip = _.toSafeInteger(_.get(event, 'queryStringParameters.skip')) || 0
      const query = _.get(event, 'queryStringParameters.q', '').split(' ').filter(x => !!x)
      var sortFields = {}
      var filter = {}

      _.forIn(_.get(event, 'queryStringParameters'), (v, k) => {
        if (k.includes('.')) {
          const fieldArray = k.split('.')
          let field = _.get(fieldArray, 0)
          let type = _.get(fieldArray, 1)
          let operator = _.get(fieldArray, 2)
          let value

          switch (type) {
            case 'reference':
              value = _h.strToId(v)
              break
            case 'boolean':
              value = v.toLowerCase() === 'true'
              break
            case 'integer':
              value = _.toNumber(v)
              break
            case 'size':
              value = _.toNumber(v)
              break
            case 'decimal':
              value = _.toNumber(v)
              break
            case 'date':
              value = new Date(v)
              break
            case 'datetime':
              value = new Date(v)
              break
            default:
              if (operator === 'regex' && v.includes('/')) {
                value = new RegExp(v.split('/')[1], v.split('/')[2])
              } else if (operator === 'exists') {
                value = v.toLowerCase() === 'true'
              } else {
                value = v
              }
          }

          if (['gt', 'gte', 'lt', 'lte', 'ne', 'regex', 'exists'].includes(operator)) {
            _.set(filter, [`private.${field}.${type}`, `$${operator}`], value)
          } else {
            filter[`private.${field}.${type}`] = value
          }
        }
      })

      if (user.id) {
        filter.access = { '$in': [_h.strToId(user.id), 'public'] }
      } else {
        filter.access = 'public'
      }

      if (query.length > 0) {
        let queries = query.map((q) => {
          return { 'search.private': new RegExp(q.toLowerCase()) }
        })
        filter['$and'] = queries
      }

      if (sort.length > 0) {
        sort.forEach((f) => {
          if (f.startsWith('-')) {
            sortFields[`private.${f.substring(1)}`] = -1
          } else {
            sortFields[`private.${f}`] = 1
          }
        })
      } else {
        sortFields = { _id: 1 }
      }

      const findedEntities = await user.db.collection('entity').find(filter, { projection: fields })
      const count = await findedEntities.count()
      const entities = await findedEntities.sort(sortFields).skip(skip).limit(limit).toArray()

      let cleanedEntities = []
      for (let i = 0; i < entities.length; i++) {
        const entity = await _h.claenupEntity(entities[i], user)
        if (entity) {
          cleanedEntities.push(entity)
        }
      }

      result = {
        count: count,
        filter: filter,
        props: props,
        entities: cleanedEntities
      }
    }

    return _h.json(result)
  } catch (e) {
    return _h.error(e)
  }
}
<|endoftext|>


<commit_before>(function () {
    "use strict";

    describe("Testing permissions module :", function () {

        beforeEach(function () {
            module("mflAdminAppConfig");
            module("mfl.auth.services");
            module("mfl.auth.permissions");
        });

        describe("Testing permission checker service: ", function () {
            var loginService;

            beforeEach(inject(["mfl.auth.services.login",
                function (ls) {
                    loginService = ls;
                }
            ]));

            it("should not allow non-loggedin users", function () {
                spyOn(loginService, "isLoggedIn").andReturn(false);
                inject(["mfl.auth.permissions.checker", function (permChecker) {
                    expect(permChecker.hasPermission("hello")).toBe(false);
                }]);
            });

            it("should not allow loggedin users without permission", function () {
                spyOn(loginService, "isLoggedIn").andReturn(true);
                spyOn(loginService, "getUser").andReturn({all_permissions: []});

                inject(["mfl.auth.permissions.checker", function (permChecker) {
                    expect(permChecker.hasPermission("hello")).toBe(false);
                }]);
            });

            it("should allow loggedin users with permission", function () {
                spyOn(loginService, "isLoggedIn").andReturn(true);
                spyOn(loginService, "getUser").andReturn({all_permissions: ["hello"]});

                inject(["mfl.auth.permissions.checker", function (permChecker) {
                    expect(permChecker.hasPermission("hello")).toBe(true);
                }]);
            });

            it("should allow if permission is not a valid string", function () {
                spyOn(loginService, "isLoggedIn").andReturn(true);
                spyOn(loginService, "getUser").andReturn({all_permissions: []});

                inject(["mfl.auth.permissions.checker", function (permChecker) {
                    expect(permChecker.hasPermission()).toBe(true);
                    expect(permChecker.hasPermission("")).toBe(true);
                    expect(permChecker.hasPermission({})).toBe(true);
                }]);
            });

        });

        describe("Testing require-permission directive :", function () {
            var compile, rootscope, loginService, permChecker;

            beforeEach(inject(["$compile", "$rootScope", "mfl.auth.permissions.checker",
                "mfl.auth.services.login",
                function (c, r, pc, ls) {
                    compile = c;
                    rootscope = r;
                    permChecker = pc;
                    loginService = ls;
                }
            ]));

            it("should not do anything without permission", function () {
               spyOn(loginService, "isLoggedIn").andReturn(true);

                var element = angular.element(
                    "

asd

"
                );
                compile(element)(rootscope);
                expect(element.html()).toEqual(
                    "

asd

"
                );

                element = angular.element(
                    "

asd

"
                );
                compile(element)(rootscope);
                expect(element.html()).toEqual(
                    "

asd

"
                );

                element = angular.element(
                    "

asd

"
                );
                compile(element)(rootscope);
                expect(element.html()).toEqual(
                    "

asd

"
                );
            });

            it("should allow element", function () {
                spyOn(loginService, "isLoggedIn").andReturn(true);
                spyOn(loginService, "getUser").andReturn({all_permissions: ["view_counties"]});

                var element = angular.element(
                    "

asd

"
                );
                compile(element)(rootscope);
                expect(element.html()).toEqual("
asd
");
            });

            it("should remove element if not logged in", function () {
                var tags = ["requires-permission", "x-requires-permission", "data-requires-permission"];
                tags.forEach(function (tag) {
                    var element = angular.element(
                        "

YEAH

"
                    );
                    compile(element)(rootscope);
                    expect(element.html()).toEqual("

");
                });
            });

            it("should remove element if logged in but without permission", function () {
                spyOn(loginService, "isLoggedIn").andReturn(true);
                spyOn(loginService, "getUser").andReturn({all_permissions: []});
                var tags = ["requires-permission", "x-requires-permission", "data-requires-permission"];
                tags.forEach(function (tag) {
                    var element = angular.element(
                        "

YEAH

"
                    );
                    compile(element)(rootscope);
                    expect(element.html()).toEqual("

");
                });
            });

        });

    });
})();
<commit_msg>Fix jshint issues<commit_after>(function () {
    "use strict";

    describe("Testing permissions module :", function () {

        beforeEach(function () {
            module("mflAdminAppConfig");
            module("mfl.auth.services");
            module("mfl.auth.permissions");
        });

        describe("Testing permission checker service: ", function () {
            var loginService;

            beforeEach(inject(["mfl.auth.services.login",
                function (ls) {
                    loginService = ls;
                }
            ]));

            it("should not allow non-loggedin users", function () {
                spyOn(loginService, "isLoggedIn").andReturn(false);
                inject(["mfl.auth.permissions.checker", function (permChecker) {
                    expect(permChecker.hasPermission("hello")).toBe(false);
                }]);
            });

            it("should not allow loggedin users without permission", function () {
                spyOn(loginService, "isLoggedIn").andReturn(true);
                spyOn(loginService, "getUser").andReturn({all_permissions: []});

                inject(["mfl.auth.permissions.checker", function (permChecker) {
                    expect(permChecker.hasPermission("hello")).toBe(false);
                }]);
            });

            it("should allow loggedin users with permission", function () {
                spyOn(loginService, "isLoggedIn").andReturn(true);
                spyOn(loginService, "getUser").andReturn({all_permissions: ["hello"]});

                inject(["mfl.auth.permissions.checker", function (permChecker) {
                    expect(permChecker.hasPermission("hello")).toBe(true);
                }]);
            });

            it("should allow if permission is not a valid string", function () {
                spyOn(loginService, "isLoggedIn").andReturn(true);
                spyOn(loginService, "getUser").andReturn({all_permissions: []});

                inject(["mfl.auth.permissions.checker", function (permChecker) {
                    expect(permChecker.hasPermission()).toBe(true);
                    expect(permChecker.hasPermission("")).toBe(true);
                    expect(permChecker.hasPermission({})).toBe(true);
                }]);
            });

        });

        describe("Testing require-permission directive :", function () {
            var compile, rootscope, loginService, permChecker;

            beforeEach(inject(["$compile", "$rootScope", "mfl.auth.permissions.checker",
                "mfl.auth.services.login",
                function (c, r, pc, ls) {
                    compile = c;
                    rootscope = r;
                    permChecker = pc;
                    loginService = ls;
                }
            ]));

            it("should not do anything without permission", function () {
               spyOn(loginService, "isLoggedIn").andReturn(true);

                var element = angular.element(
                    "

asd

"
                );
                compile(element)(rootscope);
                expect(element.html()).toEqual(
                    "
" +
                    "
asd

"
                );

                element = angular.element(
                    "

asd

"
                );
                compile(element)(rootscope);
                expect(element.html()).toEqual(
                    "
" +
                    "
asd

"
                );

                element = angular.element(
                    "

asd

"
                );
                compile(element)(rootscope);
                expect(element.html()).toEqual(
                    "

asd

"
                );
            });

            it("should allow element", function () {
                spyOn(loginService, "isLoggedIn").andReturn(true);
                spyOn(loginService, "getUser").andReturn({all_permissions: ["view_counties"]});

                var element = angular.element(
                    "

asd

"
                );
                compile(element)(rootscope);
                expect(element.html()).toEqual("" +
                    "
asd
");
            });

            it("should remove element if not logged in", function () {
                var tags = [
                    "requires-permission",
                    "x-requires-permission",
                    "data-requires-permission"
                ];
                tags.forEach(function (tag) {
                    var element = angular.element(
                        "

YEAH

"
                    );
                    compile(element)(rootscope);
                    expect(element.html()).toEqual(
                        "

");
                });
            });

            it("should remove element if logged in but without permission", function () {
                spyOn(loginService, "isLoggedIn").andReturn(true);
                spyOn(loginService, "getUser").andReturn({all_permissions: []});
                var tags = [
                    "requires-permission", "x-requires-permission", "data-requires-permission"
                ];
                tags.forEach(function (tag) {
                    var element = angular.element(
                        "

YEAH

"
                    );
                    compile(element)(rootscope);
                    expect(element.html()).toEqual(
                        "

");
                });
            });

        });

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


<commit_before>angular.module('DeviceWall')
  .controller('MainController', function($rootScope, $scope, $window, $http, $timeout, DeviceList, lodash, appConfig, $log, socket) {
    var _ = lodash;
    $log.debug('loading main controller');
    $scope.indicatorWaiting = {show: true};
    $scope.config = appConfig;
    $scope.deviceList = DeviceList.toArray();

    // selected device uuid list? TODO refactor whole selected devices list feature, this is not nice, really.
    $scope.uuids = {};

    if (appConfig.singleUser) {
      $scope.user = {
        id: 'singleuser',
        displayName: 'singleuser'
      };
    } else {
      // this is weird, just weiirrddd, TODO refactor away
      $scope.user = {
        id: $window.localStorage.getItem('name'),
        displayName: $window.localStorage.getItem('name')
      };
    }
    $scope.url = '';
    // maybe there is an old url in localstorage already..
    if ($window.localStorage.getItem('url') !== null) {
      $scope.url = $window.localStorage.getItem('url');
    }

    $scope.btnGo =              {show: true};
    $scope.btnStopAllTesting =  {show: false};
    $scope.btnStopTesting =     {show: false};

    // TODO maybe better error notification
    $scope.tooltipError = {
      show: false,
      content: ''
    };

    $scope.popupWindow = null;

    // TODO maybe https://docs.angularjs.org/api/ng/service/$filter
    $scope.getDeviceDisabled = function(userId) {
      return userId ? true : false;
    };

    $scope.submitUrl = function() {
      $log.debug('Submit url ', $scope.url.value);
      if ($scope.url.value.length <= 4) {
        $scope.tooltipError = {
          show: true,
          content: 'Invalid url'
        };
        return;
      }
      var uuids = [];
      _.each($scope.uuids, function(val, key) {
        if(val) {
          uuids.push(key);
        }
      });

      var formData = {
        url: $scope.url.value,
        labels: _.pluck(_.where($scope.deviceList, { selected: true }), 'label'),
        user: $scope.user
      };

      $window.localStorage.setItem('url', $scope.url.value);
      $scope.tooltipError.show = false;
      socket.emit('start', formData);
      setButtonsStatus(false);
    };

    $scope.url = {
      value: '',
      click: function() {
        if (!$scope.url.value || $scope.url.value === '') {
          $scope.url.value = 'http://www.';
        }
      }
    };

    $scope.selectAll = function(status) {
      _.each(DeviceList.toArray(), function(device) {
        device.selected = status;
        DeviceList.update(device);
      });
      $scope.deviceList = DeviceList.toArray();
    };

    $scope.updateDeviceList = function() {
      $log.debug('update devices');
      $log.debug($scope.deviceList);
      /*
      _.each(Devices.toArray(), function(device) {
        socket.emit('update', device);
      });
      */
    };
    $scope.clientFieldChanged = function(model) {
      socket.emit('save', model);
    };

    /***************** Create service from socket actions **/
    // TODO move socket stuff from controller to service
    socket.on('connect',  function () {
      $log.debug("Connected");
      $scope.indicatorWaiting = {show: false};
      socket.emit('list', 'list', function(data) {
        $log.debug("socket::list", data);
        var instancesRunning = false;
        _.each(data, function(device) {
          // device selected by default
          device.selected = true;
          if (device.userId) {
            instancesRunning = true;
          }
          DeviceList.add(device);
        });
        $scope.deviceList = DeviceList.toArray();
        if (instancesRunning) {
          setButtonsStatus(false);
        }
      });
    });

    socket.on('update', function (data) {
      $log.debug("socket::update");
      $scope.$apply(function() {
        _.each(data, function(device) {
          if (DeviceList.has(device)) {
            DeviceList.update(device);
          } else {
            device.selected = true;
            DeviceList.add(device);
          }
        });
        $scope.deviceList = DeviceList.toArray();
      });
    });

    socket.on('start', function (data) {
      $log.debug("socket::start", data);
      if (data.user.id === $scope.user.id) {
        setButtonsStatus(false);
        if ($scope.openUrl) {
          $log.debug('Opening a popup view');
          if ($scope.popupWindow && !$scope.popupWindow.closed) {
            $scope.popupWindow.location.href = data.url;
            $scope.popupWindow.focus();
          } else {
            $scope.popupWindow = $window.open(data.url, '_blank');
          }
        }
      }
    });

    socket.on('server-stop', function(data) {
      $log.debug('socket::server-stop');
      if (data.user.id === $scope.user.id) {
        setButtonsStatus(true);
      }
      if (data.reason) {
        $log.debug('some err', data.reason);
        $scope.tooltipError.content = data.reason;
        $scope.tooltipError.show = true;
      }
    });

    socket.on('stopall', function() {
      $log.debug('socket::stopall');
      setButtonsStatus(true);
    });

    $scope.stopTesting = function() {
      $log.debug('stop testing');
      function getUserDevices() {
        var userDevices = [];
        _.each($scope.deviceList, function(device) {
          if (device.userId === $scope.user.id) {
            userDevices.push(device.uuid);
          }
        });
        return userDevices;
      }
      socket.emit('stop', {user: $scope.user, labels: getUserDevices()});
      $scope.btnStopTesting.show = false;
    };

    $scope.stopAllTesting = function() {
      $log.debug('stop All testing');
      socket.emit('stopall');
    };

    $scope.removeDevice = function(device) {
      socket.emit('remove', {labels: [device.label]});
      DeviceList.remove(device);
      $scope.deviceList = DeviceList.toArray();
    };

    // simple helper for buttons
    function setButtonsStatus(status) {
      $scope.btnStopAllTesting.show = !status;
      $scope.btnStopTesting.show = !status;
      $scope.btnGo.show = true;
    }

    $scope.showDeviceView = function() {
      $window.location.href = $window.location.protocol + '//' + $window.location.hostname + ':' +  appConfig.port;
    };

    $scope.toggleAccordion = function($event){
      var $el = $($event.target);
      $el.parent().toggleClass('collapsed');
    };

    $scope.$watch('deviceList', checkGoButtonStatus, true);
    $scope.$watch('openUrl', checkGoButtonStatus);

    function checkGoButtonStatus(oldVal, newVal, scope) {
      var enabledGoButton = false;
      _.each(scope.deviceList, function(device) {
        if (device.selected) {
          enabledGoButton = true;
        }
        if (enabledGoButton === false && scope.openUrl) {
          enabledGoButton = true;
        }
      });
      $scope.btnGo.disabled = !enabledGoButton;
    }
  })

  .filter('batteryTitle', function() {
    return function(status) {
      var returnString = 'no battery information available';
      if (status && status.level) {
        returnString = 'Level: ' + status.level + ' %' + (status.isPlugged ? ', plugged' : '');
      }
      return returnString;
    };
  }).filter('batteryStyle', function() {
      return function(status) {
        if (status && status.level) {
          var position = (status.level * 0.8 + 10) + '%';
          var stop1 = (status.isPlugged ? '#0f0' : '#fff') + ' ' + position;
          var stop2 = (status.isPlugged ? '#0c0' : '#ccc') + ' ' + position;
          return 'background-image: -webkit-linear-gradient(left, ' + stop1 + ', ' + stop2 + ');';
        }
        return '';
      };

  })
  .factory('DeviceList', function(lodash) {
    var _ = lodash;
    return {
      deviceList: {},
      add: function(device) {
        if (_.has(this.deviceList, device.label)) {
          this.update(device);
        } else {
          this.deviceList[device.label] = device;
        }
      },
      update: function(device) {
        if (_.has(this.deviceList, device.label)) {
          this.deviceList[device.label] = angular.extend(this.deviceList[device.label], device);
        }
      },
      remove: function(device) {
        if (_.has(this.deviceList, device.label)) {
          delete this.deviceList[device.label];
        }
      },
      has: function(device) {
        return _.has(this.deviceList, device.label);
      },
      toArray: function() {
        var keys = Object.keys(this.deviceList);
        var deviceList = this.deviceList;
        return _.map(keys, function(key) {
          return deviceList[key];
        });
      }
    };

  }) // catch
    .directive('blurevent', [function() {
      return {
        restrict: 'A', // only activate on element attribute
        link: function(scope, element) {
          element.on('blur', function() {
            scope.clientFieldChanged(scope.device);
          });
        }
      };
    }])
  .filter('unsafe', function($sce) {
      return function(val) {
          return $sce.trustAsHtml(val);
      };
  });<commit_msg>refactor gobutton check<commit_after>angular.module('DeviceWall')
  .controller('MainController', function($rootScope, $scope, $window, $http, $timeout, DeviceList, lodash, appConfig, $log, socket) {
    var _ = lodash;
    $log.debug('loading main controller');
    $scope.indicatorWaiting = {show: true};
    $scope.config = appConfig;
    $scope.deviceList = DeviceList.toArray();

    // selected device uuid list? TODO refactor whole selected devices list feature, this is not nice, really.
    $scope.uuids = {};

    if (appConfig.singleUser) {
      $scope.user = {
        id: 'singleuser',
        displayName: 'singleuser'
      };
    } else {
      // this is weird, just weiirrddd, TODO refactor away
      $scope.user = {
        id: $window.localStorage.getItem('name'),
        displayName: $window.localStorage.getItem('name')
      };
    }
    $scope.url = '';
    // maybe there is an old url in localstorage already..
    if ($window.localStorage.getItem('url') !== null) {
      $scope.url = $window.localStorage.getItem('url');
    }

    $scope.btnGo =              {show: true};
    $scope.btnStopAllTesting =  {show: false};
    $scope.btnStopTesting =     {show: false};

    // TODO maybe better error notification
    $scope.tooltipError = {
      show: false,
      content: ''
    };

    $scope.popupWindow = null;

    // TODO maybe https://docs.angularjs.org/api/ng/service/$filter
    $scope.getDeviceDisabled = function(userId) {
      return userId ? true : false;
    };

    $scope.submitUrl = function() {
      $log.debug('Submit url ', $scope.url.value);
      if ($scope.url.value.length <= 4) {
        $scope.tooltipError = {
          show: true,
          content: 'Invalid url'
        };
        return;
      }
      var uuids = [];
      _.each($scope.uuids, function(val, key) {
        if(val) {
          uuids.push(key);
        }
      });

      var formData = {
        url: $scope.url.value,
        labels: _.pluck(_.where($scope.deviceList, { selected: true }), 'label'),
        user: $scope.user
      };

      $window.localStorage.setItem('url', $scope.url.value);
      $scope.tooltipError.show = false;
      socket.emit('start', formData);
      setButtonsStatus(false);
    };

    $scope.url = {
      value: '',
      click: function() {
        if (!$scope.url.value || $scope.url.value === '') {
          $scope.url.value = 'http://www.';
        }
      }
    };

    $scope.selectAll = function(status) {
      _.each(DeviceList.toArray(), function(device) {
        device.selected = status;
        DeviceList.update(device);
      });
      $scope.deviceList = DeviceList.toArray();
    };

    $scope.updateDeviceList = function() {
      $log.debug('update devices');
      $log.debug($scope.deviceList);
      /*
      _.each(Devices.toArray(), function(device) {
        socket.emit('update', device);
      });
      */
    };
    $scope.clientFieldChanged = function(model) {
      socket.emit('save', model);
    };

    /***************** Create service from socket actions **/
    // TODO move socket stuff from controller to service
    socket.on('connect',  function () {
      $log.debug("Connected");
      $scope.indicatorWaiting = {show: false};
      socket.emit('list', 'list', function(data) {
        $log.debug("socket::list", data);
        var instancesRunning = false;
        _.each(data, function(device) {
          // device selected by default
          device.selected = true;
          if (device.userId) {
            instancesRunning = true;
          }
          DeviceList.add(device);
        });
        $scope.deviceList = DeviceList.toArray();
        if (instancesRunning) {
          setButtonsStatus(false);
        }
      });
    });

    socket.on('update', function (data) {
      $log.debug("socket::update");
      $scope.$apply(function() {
        _.each(data, function(device) {
          if (DeviceList.has(device)) {
            DeviceList.update(device);
          } else {
            device.selected = true;
            DeviceList.add(device);
          }
        });
        $scope.deviceList = DeviceList.toArray();
      });
    });

    socket.on('start', function (data) {
      $log.debug("socket::start", data);
      if (data.user.id === $scope.user.id) {
        setButtonsStatus(false);
        if ($scope.openUrl) {
          $log.debug('Opening a popup view');
          if ($scope.popupWindow && !$scope.popupWindow.closed) {
            $scope.popupWindow.location.href = data.url;
            $scope.popupWindow.focus();
          } else {
            $scope.popupWindow = $window.open(data.url, '_blank');
          }
        }
      }
    });

    socket.on('server-stop', function(data) {
      $log.debug('socket::server-stop');
      if (data.user.id === $scope.user.id) {
        setButtonsStatus(true);
      }
      if (data.reason) {
        $log.debug('some err', data.reason);
        $scope.tooltipError.content = data.reason;
        $scope.tooltipError.show = true;
      }
    });

    socket.on('stopall', function() {
      $log.debug('socket::stopall');
      setButtonsStatus(true);
    });

    $scope.stopTesting = function() {
      $log.debug('stop testing');
      function getUserDevices() {
        var userDevices = [];
        _.each($scope.deviceList, function(device) {
          if (device.userId === $scope.user.id) {
            userDevices.push(device.uuid);
          }
        });
        return userDevices;
      }
      socket.emit('stop', {user: $scope.user, labels: getUserDevices()});
      $scope.btnStopTesting.show = false;
    };

    $scope.stopAllTesting = function() {
      $log.debug('stop All testing');
      socket.emit('stopall');
    };

    $scope.removeDevice = function(device) {
      socket.emit('remove', {labels: [device.label]});
      DeviceList.remove(device);
      $scope.deviceList = DeviceList.toArray();
    };

    // simple helper for buttons
    function setButtonsStatus(status) {
      $scope.btnStopAllTesting.show = !status;
      $scope.btnStopTesting.show = !status;
      $scope.btnGo.show = true;
    }

    $scope.showDeviceView = function() {
      $window.location.href = $window.location.protocol + '//' + $window.location.hostname + ':' +  appConfig.port;
    };

    $scope.toggleAccordion = function($event){
      var $el = $($event.target);
      $el.parent().toggleClass('collapsed');
    };

    $scope.$watch('deviceList', checkGoButtonStatus, true);
    $scope.$watch('openUrl', checkGoButtonStatus);

    function checkGoButtonStatus(oldVal, newVal, scope) {
      var disableGoButton = true;
      _.each(scope.deviceList, function(device) {
        if (device.selected) {
          disableGoButton = false;
        }
      });
      if (disableGoButton && scope.openUrl) {
        disableGoButton = false;
      }
      $scope.btnGo.disabled = disableGoButton;
    }
  })

  .filter('batteryTitle', function() {
    return function(status) {
      var returnString = 'no battery information available';
      if (status && status.level) {
        returnString = 'Level: ' + status.level + ' %' + (status.isPlugged ? ', plugged' : '');
      }
      return returnString;
    };
  }).filter('batteryStyle', function() {
      return function(status) {
        if (status && status.level) {
          var position = (status.level * 0.8 + 10) + '%';
          var stop1 = (status.isPlugged ? '#0f0' : '#fff') + ' ' + position;
          var stop2 = (status.isPlugged ? '#0c0' : '#ccc') + ' ' + position;
          return 'background-image: -webkit-linear-gradient(left, ' + stop1 + ', ' + stop2 + ');';
        }
        return '';
      };

  })
  .factory('DeviceList', function(lodash) {
    var _ = lodash;
    return {
      deviceList: {},
      add: function(device) {
        if (_.has(this.deviceList, device.label)) {
          this.update(device);
        } else {
          this.deviceList[device.label] = device;
        }
      },
      update: function(device) {
        if (_.has(this.deviceList, device.label)) {
          this.deviceList[device.label] = angular.extend(this.deviceList[device.label], device);
        }
      },
      remove: function(device) {
        if (_.has(this.deviceList, device.label)) {
          delete this.deviceList[device.label];
        }
      },
      has: function(device) {
        return _.has(this.deviceList, device.label);
      },
      toArray: function() {
        var keys = Object.keys(this.deviceList);
        var deviceList = this.deviceList;
        return _.map(keys, function(key) {
          return deviceList[key];
        });
      }
    };

  }) // catch
    .directive('blurevent', [function() {
      return {
        restrict: 'A', // only activate on element attribute
        link: function(scope, element) {
          element.on('blur', function() {
            scope.clientFieldChanged(scope.device);
          });
        }
      };
    }])
  .filter('unsafe', function($sce) {
      return function(val) {
          return $sce.trustAsHtml(val);
      };
  });<|endoftext|>


<commit_before>define(['mixedice', 'eventmap', './component', './log'], function(mixedice, EventMap, Component, Log) {
  'use strict';

  /**
   * @module lyria/gameobject
   */

  //Lyria.GameObject
  return (function() {

    // Constructor
    var GameObject = function() {
      mixedice([this, GameObject.prototype], new EventMap());

      var self = this;

      this.components = {};
      this.className = 'gameobject';

      this.template = {};
      this.template.source = '

';

      this.on('update', function(dt) {
        if (_.isEmpty(self.components)) {
          return;
        }

        _.each(self.components, function(key, value) {
          value.trigger('update', dt);
        });
      });
    };

    /**
     * Refreshes the game object
     *
     * @param {Object} val
     */
    GameObject.prototype.refresh = function(val) {
      if (val == null && this.template) {
        val = this.template.data;
      }

      if (this.template && this.template.source) {
        this.content = this.template.source(val);
      }

      this.trigger('refresh');
    };

    GameObject.prototype.add = function(component) {
      if (component instanceof Component) {
        this.components[component.name] = component;
      }
    };

    GameObject.prototype.execute = function(functionBody) {
      functionBody.apply(this, this);
    };

    GameObject.prototype.log = function(text) {
      Log.i('GameObject: ' + text);
    };

    return GameObject;

  })();

});<commit_msg>Updated documentation for lyria/gameobject<commit_after>define(['mixedice', 'eventmap', './component', './log'], function(mixedice, EventMap, Component, Log) {
  'use strict';

  /**
   * @module lyria/gameobject
   * @requires mixedice
   * @requires eventmap
   * @requires lyria/component
   * @requires lyria/log
   */

  return (function() {

    /**
     * @class
     * @alias module:lyria/gameobject
     *
     */
    var GameObject = function() {
      mixedice([this, GameObject.prototype], new EventMap());

      var self = this;

      this.components = {};
      this.className = 'gameobject';

      this.template = {};
      this.template.source = '

';

      this.on('update', function(dt) {
        if (_.isEmpty(self.components)) {
          return;
        }

        _.each(self.components, function(key, value) {
          value.trigger('update', dt);
        });
      });
    };

    /**
     * Refreshes the game object
     *
     * @param {Object} val
     */
    GameObject.prototype.refresh = function(val) {
      if (val == null && this.template) {
        val = this.template.data;
      }

      if (this.template && this.template.source) {
        this.content = this.template.source(val);
      }

      this.trigger('refresh');
    };

    /**
     *
     * @param {module:lyria/component} component
     */
    GameObject.prototype.add = function(component) {
      if (component instanceof Component) {
        this.components[component.name] = component;
      }
    };

    /**
     *
     * @param {Function} functionBody
     */
    GameObject.prototype.execute = function(functionBody) {
      functionBody.apply(this, this);
    };

    /**
     * Logs from the game object itself
     *
     * @param {String} text
     */
    GameObject.prototype.log = function(text) {
      Log.i('GameObject: ' + text);
    };

    return GameObject;

  })();

});<|endoftext|>


<commit_before>/**
 * @author a.demeshko
 * created on 12/29/15
 */
(function () {
    'use strict';

    angular.module('BlurAdmin.pages.torrents')
        .service('torrentsList', torrentsList);
    /** @ngInject */
    function torrentsList($q, $http) {

        var tabs = [{
            label: 'all',
            name: 'All',
            statusIds: []
        }, {
            label: 'active',
            name: 'Active',
            statusIds: [1, 2, 3, 4, 5, 6]
        }, {
            label: 'finished',
            name: 'Finished',
            statusIds: [5, 6]
        }, {
            label: 'downloading',
            name: 'Downloading',
            statusIds: [3, 4]
        }, {
            label: 'paused',
            name: 'Paused',
            statusIds: [0]
        }, {
            label: 'error',
            name: 'Error',
            statusIds: []
        }];
        function runRequest(req) {
            var deferredQ = $q.defer();
            $http.get(req).then(function (response) {
                deferredQ.resolve(response.data.torrents);
            }, function (error) {
                console.error(error);
                deferredQ.reject(Error("Failed to get '" + req + "'! [" + error + "]"));
            });
            return deferredQ.promise;
        };

        return {
            getTorrents: function () {
                console.log("get torrents");
                return runRequest('/api/transmission/torrents');
            },
            deleteTorrents: function (list, deleteData = false) {
                console.log("delete torrents " + list);
                return runRequest('/api/transmission/delete_torrents/' + (list.length == 0 ? 'none' : list) + '/' + deleteData);
            },
            stopTorrents: function (list) {
                console.log("stop torrents " + list);
                return runRequest('/api/transmission/stop_torrents/' + (list.length == 0 ? 'none' : list));
            },
            startTorrents: function (list) {
                console.log("start torrents " + list);
                return runRequest('/api/transmission/start_torrents/' + (list.length == 0 ? 'none' : list));
            },
            getTabs: function () {
                return tabs;
            },
            filterByLabel: function (torrents, label) {
                torrents.sort(function (a, b) {
                    if (a.date > b.date) return 1;
                    if (a.date < b.date) return -1;
                }).reverse();
                return torrents.filter(function (t) {
                    if (label == 'all')
                        return true;
                    else {
                        var tab = $.grep(tabs, function (e) { return e.label == label; })[0];
                        return (tab.statusIds.indexOf(t.status) > -1);
                    }
                });
            },
            filterById: function (torrents, id) {
                torrents.sort(function (a, b) {
                    if (a.date > b.date) return 1;
                    if (a.date < b.date) return -1;
                }).reverse();
                return torrents.filter(function (m) {
                    return m.id == id;
                })[0];
            }
        }

    }

})();<commit_msg>fix deleteTorrents default param<commit_after>/**
 * @author a.demeshko
 * created on 12/29/15
 */
(function () {
    'use strict';

    angular.module('BlurAdmin.pages.torrents')
        .service('torrentsList', torrentsList);
    /** @ngInject */
    function torrentsList($q, $http) {

        var tabs = [{
            label: 'all',
            name: 'All',
            statusIds: []
        }, {
            label: 'active',
            name: 'Active',
            statusIds: [1, 2, 3, 4, 5, 6]
        }, {
            label: 'finished',
            name: 'Finished',
            statusIds: [5, 6]
        }, {
            label: 'downloading',
            name: 'Downloading',
            statusIds: [3, 4]
        }, {
            label: 'paused',
            name: 'Paused',
            statusIds: [0]
        }, {
            label: 'error',
            name: 'Error',
            statusIds: []
        }];
        function runRequest(req) {
            var deferredQ = $q.defer();
            $http.get(req).then(function (response) {
                deferredQ.resolve(response.data.torrents);
            }, function (error) {
                console.error(error);
                deferredQ.reject(Error("Failed to get '" + req + "'! [" + error + "]"));
            });
            return deferredQ.promise;
        };

        return {
            getTorrents: function () {
                console.log("get torrents");
                return runRequest('/api/transmission/torrents');
            },
            deleteTorrents: function (list, deleteData) {
                deleteData = typeof deleteData !== 'undefined' ? deleteData : false;
                console.log("delete torrents " + list);
                return runRequest('/api/transmission/delete_torrents/' + (list.length == 0 ? 'none' : list) + '/' + deleteData);
            },
            stopTorrents: function (list) {
                console.log("stop torrents " + list);
                return runRequest('/api/transmission/stop_torrents/' + (list.length == 0 ? 'none' : list));
            },
            startTorrents: function (list) {
                console.log("start torrents " + list);
                return runRequest('/api/transmission/start_torrents/' + (list.length == 0 ? 'none' : list));
            },
            getTabs: function () {
                return tabs;
            },
            filterByLabel: function (torrents, label) {
                torrents.sort(function (a, b) {
                    if (a.date > b.date) return 1;
                    if (a.date < b.date) return -1;
                }).reverse();
                return torrents.filter(function (t) {
                    if (label == 'all')
                        return true;
                    else {
                        var tab = $.grep(tabs, function (e) { return e.label == label; })[0];
                        return (tab.statusIds.indexOf(t.status) > -1);
                    }
                });
            },
            filterById: function (torrents, id) {
                torrents.sort(function (a, b) {
                    if (a.date > b.date) return 1;
                    if (a.date < b.date) return -1;
                }).reverse();
                return torrents.filter(function (m) {
                    return m.id == id;
                })[0];
            }
        }

    }

})();<|endoftext|>


<commit_before>angular.module('cloudmedic.prescriptions', [
    'ui.router',
    'chart.js',
    'cloudmedic.resources'
])
.config(function config($stateProvider) {
    $stateProvider.state('prescriptions', {
        url: '/prescriptions',
        views: {
            "main": {
                controller: 'PrescriptionsCtrl',
                templateUrl: 'prescriptions/prescriptions.tpl.html'
            }
        },
        resolve: {
            security: function ($q, auth) {
                if (!auth.status.token || !auth.status.token.userRole.contains('SysAdmin') && !auth.status.token.userRole.contains('Physician') && !auth.status.token.userRole.contains('Nurse')) {
                    return $q.reject("Not Authorized");
                }
            },
            prescriptions: function (Prescriptions) {
                return Prescriptions.query().$promise;
            }
        },
        data: { pageTitle: 'Prescriptions' }
    });
})
.controller('PrescriptionsCtrl', function ($scope, $window, $state, prescriptions, Prescriptions, localizedNotifications, $modal) {
    $scope.prescriptions = prescriptions;
    $scope.prescriptionsRemover = new Prescriptions();

    $scope.orderByField = 'MedicationCode';
    $scope.reverseSort = false;

    $scope.removePrescription = function (prescription) {
        localizedNotifications.removeForCurrent();
        $modal.open({
            templateUrl: "app.confirm.tpl.html",
            controller: function ($scope) {
                $scope.confirmText = "You will not be able to recover this prescription!";
                $scope.confirmButton = "Yes, delete prescription!";
            }
        }).result.then(function () {
            $scope.prescriptionsRemover.$remove({ id: prescription.PrescriptionId }).then(function () {
                localizedNotifications.addForNext('delete.success', 'success', { entityType: 'Prescription' });
                $state.go("prescriptions", null, { reload: true });
            });
        });
    };
})
.controller('PreAddCtrl', function ($scope, $state, $http,$modalInstance, Prescriptions, Users, localizedNotifications, MedId, MedName) {
    $scope.prescriptionsData = {
        MedicationId: MedId,
        MedicationName: MedName,
        Frequency: "",
        Dosage: "",
        Notes:"",
        isSubmitting: false,
        PatientId: "",
        PatientName:""
    };

    $scope.search = function () {
        $scope.Candidates = Users.search({ Name: $scope.prescriptionsData.PatientName });
    };
    $scope.prescriptionsCreator = new Prescriptions();

    // Prescription creation method
    $scope.create = function () {
        localizedNotifications.removeForCurrent();
        $scope.prescriptionsData.isSubmitting = true;
        $scope.prescriptionsCreator.MedicationId = $scope.prescriptionsData.MedicationId;
        $scope.prescriptionsCreator.PatientId = $scope.prescriptionsData.PatientId[0];
        $scope.prescriptionsCreator.Frequency = $scope.prescriptionsData.Frequency;
        $scope.prescriptionsCreator.Dosage = $scope.prescriptionsData.Dosage;
        $scope.prescriptionsCreator.Notes = $scope.prescriptionsData.Notes;
        $scope.prescriptionsCreator.$create().then(function () {
            localizedNotifications.addForNext('create.success', 'success', { entityType: 'Prescription' });
            $modalInstance.close();
        }, function () {
            $scope.prescriptionsData.isSubmitting = false;
        });
    };

});<commit_msg>Added new function to the prescription.js file to send the start and end dates when creating a prescription.<commit_after>angular.module('cloudmedic.prescriptions', [
    'ui.router',
    'chart.js',
    'cloudmedic.resources'
])
.config(function config($stateProvider) {
    $stateProvider.state('prescriptions', {
        url: '/prescriptions',
        views: {
            "main": {
                controller: 'PrescriptionsCtrl',
                templateUrl: 'prescriptions/prescriptions.tpl.html'
            }
        },
        resolve: {
            security: function ($q, auth) {
                if (!auth.status.token || !auth.status.token.userRole.contains('SysAdmin') && !auth.status.token.userRole.contains('Physician') && !auth.status.token.userRole.contains('Nurse')) {
                    return $q.reject("Not Authorized");
                }
            },
            prescriptions: function (Prescriptions) {
                return Prescriptions.query().$promise;
            }
        },
        data: { pageTitle: 'Prescriptions' }
    });
})
.controller('PrescriptionsCtrl', function ($scope, $window, $state, prescriptions, Prescriptions, localizedNotifications, $modal) {
    $scope.prescriptions = prescriptions;
    $scope.prescriptionsRemover = new Prescriptions();

    $scope.orderByField = 'MedicationCode';
    $scope.reverseSort = false;

    $scope.removePrescription = function (prescription) {
        localizedNotifications.removeForCurrent();
        $modal.open({
            templateUrl: "app.confirm.tpl.html",
            controller: function ($scope) {
                $scope.confirmText = "You will not be able to recover this prescription!";
                $scope.confirmButton = "Yes, delete prescription!";
            }
        }).result.then(function () {
            $scope.prescriptionsRemover.$remove({ id: prescription.PrescriptionId }).then(function () {
                localizedNotifications.addForNext('delete.success', 'success', { entityType: 'Prescription' });
                $state.go("prescriptions", null, { reload: true });
            });
        });
    };
})
.controller('PreAddCtrl', function ($scope, $state, $http,$modalInstance, Prescriptions, Users, localizedNotifications, MedId, MedName) {
    $scope.prescriptionsData = {
        MedicationId: MedId,
        MedicationName: MedName,
        Frequency: "",
        Dosage: "",
        Notes:"",
        isSubmitting: false,
        PatientId: "",
        PatientName:""
    };

    $scope.search = function () {
        $scope.Candidates = Users.search({ Name: $scope.prescriptionsData.PatientName });
    };
    $scope.Creator = new Prescriptions();

    // Prescription creation method
    $scope.create = function () {
        localizedNotifications.removeForCurrent();
        $scope.prescriptionsData.isSubmitting = true;
        $scope.Creator.MedicationId = $scope.prescriptionsData.MedicationId;
        $scope.Creator.PatientId = $scope.prescriptionsData.PatientId[0];
        $scope.Creator.Frequency = $scope.prescriptionsData.Frequency;
        $scope.Creator.Dosage = $scope.prescriptionsData.Dosage;
        $scope.Creator.Notes = $scope.prescriptionsData.Notes;
        $scope.Creator.StartDate = new Date();
        $scope.Creator.EndDate = $scope.SelectedYear + '-' + pad($scope.SelectedMonth, 2) + '-' + pad($scope.SelectedDay, 2);
        $scope.Creator.$create().then(function () {
            localizedNotifications.addForNext('create.success', 'success', { entityType: 'Prescription' });
            $modalInstance.close();
        }, function () {
            $scope.prescriptionsData.isSubmitting = false;
        });
    };

    // Date of Birth dropdown menu value generator
    var numberOfYears = (new Date()).getYear();
    var years = $.map($(Array(numberOfYears)), function (val, i) { return i + 1900; });
    var days = $.map($(Array(31)), function (val, i) { return i + 1; });
    var isLeapYear = function () {
        var year = $scope.SelectedYear || 0;
        return ((year % 400 === 0 || year % 100 !== 0) && (year % 4 === 0)) ? 1 : 0;
    };
    var getNumberOfDaysInMonth = function () {
        var selectedMonth = $scope.SelectedMonth || 0;
        return 31 - ((selectedMonth === 2) ? (3 - isLeapYear()) : ((selectedMonth - 1) % 7 % 2));
    };

    $scope.UpdateNumberOfDays = function () {
        $scope.NumberOfDays = getNumberOfDaysInMonth();
    };
    $scope.NumberOfDays = 31;
    $scope.Years = years;
    $scope.Days = days;
    $scope.Months = MONTHS;
});
// adds leading zeroes
function pad(num, size) {
    var s = "00" + num;
    return s.substr(s.length - size);
}<|endoftext|>


<commit_before>Ext.define("Hatimeria.core.google.Map", {
    config: {
        address: null,
        renderTo: null
    },
    /**
     * Constructor
     *
     * @param {} config
     */
    constructor: function(config)
    {
        this.initConfig(config);
        this.geocoder = new google.maps.Geocoder();

        return this;
    },

    render: function()
    {
        this.geocoder.geocode( {
            'address': this.config.address
            }, Ext.bind(this.handleGoogleResponse, this));
    },

    getContainer: function()
    {
        return document.getElementById(this.config.renderTo);
    },

    handleGoogleResponse: function(results, status)
    {
        if (status == google.maps.GeocoderStatus.OK) {
            var latlng = new google.maps.LatLng(-34.397, 150.644);
            var myOptions = {
                zoom: 9,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            var map = new google.maps.Map(this.getContainer(), myOptions);
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    }
})<commit_msg>fixes wrong namespace<commit_after>Ext.define("Hatimeria.google.Map", {
    config: {
        address: null,
        renderTo: null
    },
    /**
     * Constructor
     *
     * @param {} config
     */
    constructor: function(config)
    {
        this.initConfig(config);
        this.geocoder = new google.maps.Geocoder();

        return this;
    },

    render: function()
    {
        this.geocoder.geocode( {
            'address': this.config.address
            }, Ext.bind(this.handleGoogleResponse, this));
    },

    getContainer: function()
    {
        return document.getElementById(this.config.renderTo);
    },

    handleGoogleResponse: function(results, status)
    {
        if (status == google.maps.GeocoderStatus.OK) {
            var latlng = new google.maps.LatLng(-34.397, 150.644);
            var myOptions = {
                zoom: 9,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            var map = new google.maps.Map(this.getContainer(), myOptions);
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    }
})<|endoftext|>


<commit_before>exports.run = async function(client, repository) {
  const repoName = repository.name;
  const repoOwner = repository.owner.login;
  const func = client.pullRequests.getAll({
    owner: repoOwner, repo: repoName, per_page: 100
  });
  const pullRequests = await client.getAll(client, [], func);
  pullRequests.forEach(async(p, index) => {
    setTimeout(() => {
      exports.check(client, p.number, repoName, repoOwner);
    }, index * 500);
  });
};

exports.check = async function(client, number, repoName, repoOwner) {
  const pull = await client.pullRequests.get({
    owner: repoOwner, repo: repoName, number: number
  });
  const mergeable = pull.data.mergeable;
  const author = pull.data.user.login;
  const comment = client.templates.get("mergeConflictWarning").replace("[username]", author)
  .replace("[repoOwner]", repoOwner).replace("[repoName]", repoName);
  const commits = await client.pullRequests.getCommits({
    owner: repoOwner, repo: repoName, number: number, per_page: 100
  });
  const lastCommitTime = Date.parse(commits.data.slice(-1).pop().commit.committer.date);
  const comments = await client.issues.getComments({
    owner: repoOwner, repo: repoName, number: number, per_page: 100
  });
  const labelComment = comments.data.find((c) => {
    const synchCheck = lastCommitTime < Date.parse(c.updated_at);
    return c.body.includes(comment) && synchCheck && c.user.login === client.cfg.username;
  });
  if (!labelComment && mergeable === false) {
    client.newComment(pull.data, pull.data.base.repo, comment);
  } else if (mergeable) {
    const oldComments = comments.data.filter((c) => {
      return c.body.includes(comment) && c.user.login === client.cfg.username;
    }).map(c => c.id);
    oldComments.forEach((c) => {
      client.issues.deleteComment({
        owner: repoOwner, repo: repoName, id: c
      });
    });
  }
};
<commit_msg>pull requests: Refactor merge conflicts to check for inactive label.<commit_after>exports.run = async function(client, repository) {
  const repoName = repository.name;
  const repoOwner = repository.owner.login;
  const func = client.pullRequests.getAll({
    owner: repoOwner, repo: repoName, per_page: 100
  });
  const pullRequests = await client.getAll(client, [], func);
  pullRequests.forEach(async(p, index) => {
    setTimeout(() => {
      exports.check(client, p.number, repoName, repoOwner);
    }, index * 500);
  });
};

exports.check = async function(client, number, repoName, repoOwner) {
  const pull = await client.pullRequests.get({
    owner: repoOwner, repo: repoName, number: number
  });
  const mergeable = pull.data.mergeable;
  const author = pull.data.user.login;
  const comment = client.templates.get("mergeConflictWarning").replace("[username]", author)
  .replace("[repoOwner]", repoOwner).replace("[repoName]", repoName);
  const comments = await client.issues.getComments({
    owner: repoOwner, repo: repoName, number: number, per_page: 100
  });
  const warnings = comments.data.filter((c) => {
    return c.body.includes(comment) && c.user.login === client.cfg.username;
  });
  if (mergeable && warnings.length) {
    warnings.forEach((c) => {
      client.issues.deleteComment({
        owner: repoOwner, repo: repoName, id: c.id
      });
    });
  } else if (mergeable === false) {
    const commits = await client.pullRequests.getCommits({
      owner: repoOwner, repo: repoName, number: number, per_page: 100
    });
    const lastCommitTime = Date.parse(commits.data.slice(-1).pop().commit.committer.date);
    const labelComment = warnings.find(c => lastCommitTime < Date.parse(c.updated_at));
    const labels = await client.issues.get({
      owner: repoOwner, repo: repoName, number: number
    });
    const inactive = labels.data.find(l => l.name === client.cfg.inactiveLabel);
    if (!labelComment && !inactive) client.newComment(pull.data, pull.data.base.repo, comment);
  }
};
<|endoftext|>