<commit_before>var chownr = require('chownr')
var tar = require('tar-stream')
var pump = require('pump')
var mkdirp = require('mkdirp-classic')
var fs = require('fs')
var path = require('path')
var os = require('os')

var win32 = os.platform() === 'win32'

var noop = function () {}

var echo = function (name) {
  return name
}

var normalize = !win32 ? echo : function (name) {
  return name.replace(/\\/g, '/').replace(/[:?<>|]/g, '_')
}

var statAll = function (fs, stat, cwd, ignore, entries, sort) {
  var queue = entries || ['.']

  return function loop (callback) {
    if (!queue.length) return callback()
    var next = queue.shift()
    var nextAbs = path.join(cwd, next)

    stat(nextAbs, function (err, stat) {
      if (err) return callback(err)

      if (!stat.isDirectory()) return callback(null, next, stat)

      fs.readdir(nextAbs, function (err, files) {
        if (err) return callback(err)

        if (sort) files.sort()
        for (var i = 0; i < files.length; i++) {
          if (!ignore(path.join(cwd, next, files[i]))) queue.push(path.join(next, files[i]))
        }

        callback(null, next, stat)
      })
    })
  }
}

var strip = function (map, level) {
  return function (header) {
    header.name = header.name.split('/').slice(level).join('/')

    var linkname = header.linkname
    if (linkname && (header.type === 'link' || path.isAbsolute(linkname))) {
      header.linkname = linkname.split('/').slice(level).join('/')
    }

    return map(header)
  }
}

exports.pack = function (cwd, opts) {
  if (!cwd) cwd = '.'
  if (!opts) opts = {}

  var xfs = opts.fs || fs
  var ignore = opts.ignore || opts.filter || noop
  var map = opts.map || noop
  var mapStream = opts.mapStream || echo
  var statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd, ignore, opts.entries, opts.sort)
  var strict = opts.strict !== false
  var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask()
  var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0
  var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0
  var pack = opts.pack || tar.pack()
  var finish = opts.finish || noop

  if (opts.strip) map = strip(map, opts.strip)

  if (opts.readable) {
    dmode |= parseInt(555, 8)
    fmode |= parseInt(444, 8)
  }
  if (opts.writable) {
    dmode |= parseInt(333, 8)
    fmode |= parseInt(222, 8)
  }

  var onsymlink = function (filename, header) {
    xfs.readlink(path.join(cwd, filename), function (err, linkname) {
      if (err) return pack.destroy(err)
      header.linkname = normalize(linkname)
      pack.entry(header, onnextentry)
    })
  }

  var onstat = function (err, filename, stat) {
    if (err) return pack.destroy(err)
    if (!filename) {
      if (opts.finalize !== false) pack.finalize()
      return finish(pack)
    }

    if (stat.isSocket()) return onnextentry() // tar does not support sockets...

    var header = {
      name: normalize(filename),
      mode: (stat.mode | (stat.isDirectory() ? dmode : fmode)) & umask,
      mtime: stat.mtime,
      size: stat.size,
      type: 'file',
      uid: stat.uid,
      gid: stat.gid
    }

    if (stat.isDirectory()) {
      header.size = 0
      header.type = 'directory'
      header = map(header) || header
      return pack.entry(header, onnextentry)
    }

    if (stat.isSymbolicLink()) {
      header.size = 0
      header.type = 'symlink'
      header = map(header) || header
      return onsymlink(filename, header)
    }

    // TODO: add fifo etc...

    header = map(header) || header

    if (!stat.isFile()) {
      if (strict) return pack.destroy(new Error('unsupported type for ' + filename))
      return onnextentry()
    }

    var entry = pack.entry(header, onnextentry)
    if (!entry) return

    var rs = mapStream(xfs.createReadStream(path.join(cwd, filename)), header)

    rs.on('error', function (err) { // always forward errors on destroy
      entry.destroy(err)
    })

    pump(rs, entry)
  }

  var onnextentry = function (err) {
    if (err) return pack.destroy(err)
    statNext(onstat)
  }

  onnextentry()

  return pack
}

var head = function (list) {
  return list.length ? list[list.length - 1] : null
}

var processGetuid = function () {
  return process.getuid ? process.getuid() : -1
}

var processUmask = function () {
  return process.umask ? process.umask() : 0
}

exports.extract = function (cwd, opts) {
  if (!cwd) cwd = '.'
  if (!opts) opts = {}

  var xfs = opts.fs || fs
  var ignore = opts.ignore || opts.filter || noop
  var map = opts.map || noop
  var mapStream = opts.mapStream || echo
  var own = opts.chown !== false && !win32 && processGetuid() === 0
  var extract = opts.extract || tar.extract()
  var stack = []
  var now = new Date()
  var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask()
  var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0
  var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0
  var strict = opts.strict !== false

  if (opts.strip) map = strip(map, opts.strip)

  if (opts.readable) {
    dmode |= parseInt(555, 8)
    fmode |= parseInt(444, 8)
  }
  if (opts.writable) {
    dmode |= parseInt(333, 8)
    fmode |= parseInt(222, 8)
  }

  var utimesParent = function (name, cb) { // we just set the mtime on the parent dir again everytime we write an entry
    var top
    while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop()
    if (!top) return cb()
    xfs.utimes(top[0], now, top[1], cb)
  }

  var utimes = function (name, header, cb) {
    if (opts.utimes === false) return cb()

    if (header.type === 'directory') return xfs.utimes(name, now, header.mtime, cb)
    if (header.type === 'symlink') return utimesParent(name, cb) // TODO: how to set mtime on link?

    xfs.utimes(name, now, header.mtime, function (err) {
      if (err) return cb(err)
      utimesParent(name, cb)
    })
  }

  var chperm = function (name, header, cb) {
    var link = header.type === 'symlink'

    /* eslint-disable node/no-deprecated-api */
    var chmod = link ? xfs.lchmod : xfs.chmod
    var chown = link ? xfs.lchown : xfs.chown
    /* eslint-enable node/no-deprecated-api */

    if (!chmod) return cb()

    var mode = (header.mode | (header.type === 'directory' ? dmode : fmode)) & umask
    chmod(name, mode, function (err) {
      if (err) return cb(err)
      if (!own) return cb()
      if (!chown) return cb()
      chown(name, header.uid, header.gid, cb)
    })
  }

  extract.on('entry', function (header, stream, next) {
    header = map(header) || header
    header.name = normalize(header.name)
    var name = path.join(cwd, path.join('/', header.name))

    if (ignore(name, header)) {
      stream.resume()
      return next()
    }

    var stat = function (err) {
      if (err) return next(err)
      utimes(name, header, function (err) {
        if (err) return next(err)
        if (win32) return next()
        chperm(name, header, next)
      })
    }

    var onsymlink = function () {
      if (win32) return next() // skip symlinks on win for now before it can be tested
      xfs.unlink(name, function () {
        xfs.symlink(header.linkname, name, stat)
      })
    }

    var onlink = function () {
      if (win32) return next() // skip links on win for now before it can be tested
      xfs.unlink(name, function () {
        var srcpath = path.join(cwd, path.join('/', header.linkname))

        xfs.link(srcpath, name, function (err) {
          if (err && err.code === 'EPERM' && opts.hardlinkAsFilesFallback) {
            stream = xfs.createReadStream(srcpath)
            return onfile()
          }

          stat(err)
        })
      })
    }

    var onfile = function () {
      var ws = xfs.createWriteStream(name)
      var rs = mapStream(stream, header)

      ws.on('error', function (err) { // always forward errors on destroy
        rs.destroy(err)
      })

      pump(rs, ws, function (err) {
        if (err) return next(err)
        ws.on('close', stat)
      })
    }

    if (header.type === 'directory') {
      stack.push([name, header.mtime])
      return mkdirfix(name, {
        fs: xfs, own: own, uid: header.uid, gid: header.gid
      }, stat)
    }

    var dir = path.dirname(name)

    validate(xfs, dir, path.join(cwd, '.'), function (err, valid) {
      if (err) return next(err)
      if (!valid) return next(new Error(dir + ' is not a valid path'))

      mkdirfix(dir, {
        fs: xfs, own: own, uid: header.uid, gid: header.gid
      }, function (err) {
        if (err) return next(err)

        switch (header.type) {
          case 'file': return onfile()
          case 'link': return onlink()
          case 'symlink': return onsymlink()
        }

        if (strict) return next(new Error('unsupported type for ' + name + ' (' + header.type + ')'))

        stream.resume()
        next()
      })
    })
  })

  if (opts.finish) extract.on('finish', opts.finish)

  return extract
}

function validate (fs, name, root, cb) {
  if (name === root) return cb(null, true)
  fs.lstat(name, function (err, st) {
    if (err && err.code !== 'ENOENT') return cb(err)
    if (err || st.isDirectory()) return validate(fs, path.join(name, '..'), root, cb)
    cb(null, false)
  })
}

function mkdirfix (name, opts, cb) {
  mkdirp(name, { fs: opts.fs }, function (err, made) {
    if (!err && made && opts.own) {
      chownr(made, opts.uid, opts.gid, cb)
    } else {
      cb(err)
    }
  })
}
<commit_msg>Makes tar-fs able to pack files that are actively being written to. (#88)<commit_after>var chownr = require('chownr')
var tar = require('tar-stream')
var pump = require('pump')
var mkdirp = require('mkdirp-classic')
var fs = require('fs')
var path = require('path')
var os = require('os')

var win32 = os.platform() === 'win32'

var noop = function () {}

var echo = function (name) {
  return name
}

var normalize = !win32 ? echo : function (name) {
  return name.replace(/\\/g, '/').replace(/[:?<>|]/g, '_')
}

var statAll = function (fs, stat, cwd, ignore, entries, sort) {
  var queue = entries || ['.']

  return function loop (callback) {
    if (!queue.length) return callback()
    var next = queue.shift()
    var nextAbs = path.join(cwd, next)

    stat(nextAbs, function (err, stat) {
      if (err) return callback(err)

      if (!stat.isDirectory()) return callback(null, next, stat)

      fs.readdir(nextAbs, function (err, files) {
        if (err) return callback(err)

        if (sort) files.sort()
        for (var i = 0; i < files.length; i++) {
          if (!ignore(path.join(cwd, next, files[i]))) queue.push(path.join(next, files[i]))
        }

        callback(null, next, stat)
      })
    })
  }
}

var strip = function (map, level) {
  return function (header) {
    header.name = header.name.split('/').slice(level).join('/')

    var linkname = header.linkname
    if (linkname && (header.type === 'link' || path.isAbsolute(linkname))) {
      header.linkname = linkname.split('/').slice(level).join('/')
    }

    return map(header)
  }
}

exports.pack = function (cwd, opts) {
  if (!cwd) cwd = '.'
  if (!opts) opts = {}

  var xfs = opts.fs || fs
  var ignore = opts.ignore || opts.filter || noop
  var map = opts.map || noop
  var mapStream = opts.mapStream || echo
  var statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd, ignore, opts.entries, opts.sort)
  var strict = opts.strict !== false
  var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask()
  var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0
  var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0
  var pack = opts.pack || tar.pack()
  var finish = opts.finish || noop

  if (opts.strip) map = strip(map, opts.strip)

  if (opts.readable) {
    dmode |= parseInt(555, 8)
    fmode |= parseInt(444, 8)
  }
  if (opts.writable) {
    dmode |= parseInt(333, 8)
    fmode |= parseInt(222, 8)
  }

  var onsymlink = function (filename, header) {
    xfs.readlink(path.join(cwd, filename), function (err, linkname) {
      if (err) return pack.destroy(err)
      header.linkname = normalize(linkname)
      pack.entry(header, onnextentry)
    })
  }

  var onstat = function (err, filename, stat) {
    if (err) return pack.destroy(err)
    if (!filename) {
      if (opts.finalize !== false) pack.finalize()
      return finish(pack)
    }

    if (stat.isSocket()) return onnextentry() // tar does not support sockets...

    var header = {
      name: normalize(filename),
      mode: (stat.mode | (stat.isDirectory() ? dmode : fmode)) & umask,
      mtime: stat.mtime,
      size: stat.size,
      type: 'file',
      uid: stat.uid,
      gid: stat.gid
    }

    if (stat.isDirectory()) {
      header.size = 0
      header.type = 'directory'
      header = map(header) || header
      return pack.entry(header, onnextentry)
    }

    if (stat.isSymbolicLink()) {
      header.size = 0
      header.type = 'symlink'
      header = map(header) || header
      return onsymlink(filename, header)
    }

    // TODO: add fifo etc...

    header = map(header) || header

    if (!stat.isFile()) {
      if (strict) return pack.destroy(new Error('unsupported type for ' + filename))
      return onnextentry()
    }

    var entry = pack.entry(header, onnextentry)
    if (!entry) return

    var rs = mapStream(xfs.createReadStream(path.join(cwd, filename), { start: 0, end: header.size > 0 ? header.size - 1 : header.size }), header)

    rs.on('error', function (err) { // always forward errors on destroy
      entry.destroy(err)
    })

    pump(rs, entry)
  }

  var onnextentry = function (err) {
    if (err) return pack.destroy(err)
    statNext(onstat)
  }

  onnextentry()

  return pack
}

var head = function (list) {
  return list.length ? list[list.length - 1] : null
}

var processGetuid = function () {
  return process.getuid ? process.getuid() : -1
}

var processUmask = function () {
  return process.umask ? process.umask() : 0
}

exports.extract = function (cwd, opts) {
  if (!cwd) cwd = '.'
  if (!opts) opts = {}

  var xfs = opts.fs || fs
  var ignore = opts.ignore || opts.filter || noop
  var map = opts.map || noop
  var mapStream = opts.mapStream || echo
  var own = opts.chown !== false && !win32 && processGetuid() === 0
  var extract = opts.extract || tar.extract()
  var stack = []
  var now = new Date()
  var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask()
  var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0
  var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0
  var strict = opts.strict !== false

  if (opts.strip) map = strip(map, opts.strip)

  if (opts.readable) {
    dmode |= parseInt(555, 8)
    fmode |= parseInt(444, 8)
  }
  if (opts.writable) {
    dmode |= parseInt(333, 8)
    fmode |= parseInt(222, 8)
  }

  var utimesParent = function (name, cb) { // we just set the mtime on the parent dir again everytime we write an entry
    var top
    while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop()
    if (!top) return cb()
    xfs.utimes(top[0], now, top[1], cb)
  }

  var utimes = function (name, header, cb) {
    if (opts.utimes === false) return cb()

    if (header.type === 'directory') return xfs.utimes(name, now, header.mtime, cb)
    if (header.type === 'symlink') return utimesParent(name, cb) // TODO: how to set mtime on link?

    xfs.utimes(name, now, header.mtime, function (err) {
      if (err) return cb(err)
      utimesParent(name, cb)
    })
  }

  var chperm = function (name, header, cb) {
    var link = header.type === 'symlink'

    /* eslint-disable node/no-deprecated-api */
    var chmod = link ? xfs.lchmod : xfs.chmod
    var chown = link ? xfs.lchown : xfs.chown
    /* eslint-enable node/no-deprecated-api */

    if (!chmod) return cb()

    var mode = (header.mode | (header.type === 'directory' ? dmode : fmode)) & umask
    chmod(name, mode, function (err) {
      if (err) return cb(err)
      if (!own) return cb()
      if (!chown) return cb()
      chown(name, header.uid, header.gid, cb)
    })
  }

  extract.on('entry', function (header, stream, next) {
    header = map(header) || header
    header.name = normalize(header.name)
    var name = path.join(cwd, path.join('/', header.name))

    if (ignore(name, header)) {
      stream.resume()
      return next()
    }

    var stat = function (err) {
      if (err) return next(err)
      utimes(name, header, function (err) {
        if (err) return next(err)
        if (win32) return next()
        chperm(name, header, next)
      })
    }

    var onsymlink = function () {
      if (win32) return next() // skip symlinks on win for now before it can be tested
      xfs.unlink(name, function () {
        xfs.symlink(header.linkname, name, stat)
      })
    }

    var onlink = function () {
      if (win32) return next() // skip links on win for now before it can be tested
      xfs.unlink(name, function () {
        var srcpath = path.join(cwd, path.join('/', header.linkname))

        xfs.link(srcpath, name, function (err) {
          if (err && err.code === 'EPERM' && opts.hardlinkAsFilesFallback) {
            stream = xfs.createReadStream(srcpath)
            return onfile()
          }

          stat(err)
        })
      })
    }

    var onfile = function () {
      var ws = xfs.createWriteStream(name)
      var rs = mapStream(stream, header)

      ws.on('error', function (err) { // always forward errors on destroy
        rs.destroy(err)
      })

      pump(rs, ws, function (err) {
        if (err) return next(err)
        ws.on('close', stat)
      })
    }

    if (header.type === 'directory') {
      stack.push([name, header.mtime])
      return mkdirfix(name, {
        fs: xfs, own: own, uid: header.uid, gid: header.gid
      }, stat)
    }

    var dir = path.dirname(name)

    validate(xfs, dir, path.join(cwd, '.'), function (err, valid) {
      if (err) return next(err)
      if (!valid) return next(new Error(dir + ' is not a valid path'))

      mkdirfix(dir, {
        fs: xfs, own: own, uid: header.uid, gid: header.gid
      }, function (err) {
        if (err) return next(err)

        switch (header.type) {
          case 'file': return onfile()
          case 'link': return onlink()
          case 'symlink': return onsymlink()
        }

        if (strict) return next(new Error('unsupported type for ' + name + ' (' + header.type + ')'))

        stream.resume()
        next()
      })
    })
  })

  if (opts.finish) extract.on('finish', opts.finish)

  return extract
}

function validate (fs, name, root, cb) {
  if (name === root) return cb(null, true)
  fs.lstat(name, function (err, st) {
    if (err && err.code !== 'ENOENT') return cb(err)
    if (err || st.isDirectory()) return validate(fs, path.join(name, '..'), root, cb)
    cb(null, false)
  })
}

function mkdirfix (name, opts, cb) {
  mkdirp(name, { fs: opts.fs }, function (err, made) {
    if (!err && made && opts.own) {
      chownr(made, opts.uid, opts.gid, cb)
    } else {
      cb(err)
    }
  })
}
<|endoftext|>


<commit_before>/*
Gordon Williams (gw@pur3.co.uk)

If we're running in an iframe, this gets enabled and allows the IDE
to work by passing messages using window.postMessage.

Use embed.js on the client side to link this in.
*/

(function() {
  if (typeof window == "undefined" || typeof window.parent == undefined) return;
  console.log("Running in a frame - enabling frame messaging support");

  var callbacks = {
    connected : undefined,
    receive : undefined,
    written : undefined,
    disconnected : undefined,
    ports : undefined
  };

  window.addEventListener('message', function(e) {
    var event = e.data;
    //console.log("IDE MESSAGE ---------------------------------------");
    //console.log(event);
    //console.log("-----------------------------------------------");
    if (typeof event!="object" || event.for!="ide") return;
    switch (event.type) {
      case "ports": if (callbacks.ports) {
        callbacks.ports(event.data);
        callbacks.ports = undefined;
      } break;
      case "connect":
        if (Espruino.Core.Serial.isConnected())
          console.error("serial_frame: already connected");

        Espruino.Core.MenuPortSelector.connectToPort(event.data, function() {
          console.log("serial_frame: connected");
        });
        break;
      case "connected": if (callbacks.connected) {
        callbacks.connected({ok:true});
        callbacks.connected = undefined;
      } break;
      case "disconnected": if (callbacks.disconnected) {
        callbacks.disconnected();
        callbacks.disconnected = undefined;
      } break;
      case "written": if (callbacks.written) {
        callbacks.written();
        callbacks.written = undefined;
      } break;
      case "receive": if (callbacks.receive) {
        if (typeof event.data!="string")
          console.error("serial_frame: receive event expecting data string");
        callbacks.receive(Espruino.Core.Utils.stringToArrayBuffer(event.data));
      } break;
      case "setMaxWriteLength": {
        // Set the maximum amount of data we're allowed to write in one go
        device.maxWriteLength = parseInt(event.data);
      } break;
      default:
        console.error("Unknown event type ",event.type);
        break;
    }
  });

  function post(msg) {
    msg.from="ide";
    window.parent.postMessage(msg,"*");
  }

  var device = {
    "name" : "window.postMessage",
    "init" : function() {
      post({type:"init"});
    },
    "getPorts": function(callback) {
      post({type:"getPorts"});
      var timeout = setTimeout(function() {
        timeout = undefined;
        callbacks.ports = undefined;
        callback([], false/*instantPorts*/);
        console.error("serial_frame: getPorts timeout");
      },100);
      callbacks.ports = function(d) {
        if (!timeout) {
          console.error("serial_frame: ports received after timeout");
          return;
        }
        clearTimeout(timeout);
        timeout = undefined;
        callback(d, false/*instantPorts*/);
      };
    },
    "open": function(path, openCallback, receiveCallback, disconnectCallback) {
      callbacks.connected = openCallback;
      callbacks.receive = receiveCallback;
      callbacks.disconnected = disconnectCallback;
      post({type:"connect",data:path});
    },
    "write": function(d, callback) {
      callbacks.written = callback;
      post({type:"write",data:d});
    },
    "close": function() {
      post({type:"disconnect"});
    },
  };
  Espruino.Core.Serial.devices.push(device);
})();
<commit_msg>Fix errors when running in IFRAME but *not* implementing serial (eg. WebBLE)<commit_after>/*
Gordon Williams (gw@pur3.co.uk)

If we're running in an iframe, this gets enabled and allows the IDE
to work by passing messages using window.postMessage.

Use embed.js on the client side to link this in.
*/

(function() {
  if (typeof window == "undefined" || typeof window.parent == undefined) return;
  console.log("serial_frame: Running in a frame - enabling frame messaging");
  var ENABLED = true;

  var callbacks = {
    connected : undefined,
    receive : undefined,
    written : undefined,
    disconnected : undefined,
    ports : undefined
  };

  window.addEventListener('message', function(e) {
    var event = e.data;
    //console.log("IDE MESSAGE ---------------------------------------");
    //console.log(event);
    //console.log("-----------------------------------------------");
    if (typeof event!="object" || event.for!="ide") return;
    switch (event.type) {
      case "initialised": {
        // response to init. Could disable if we don't get this?
      } break;
      case "ports": if (callbacks.ports) {
        callbacks.ports(event.data);
        callbacks.ports = undefined;
      } break;
      case "connect":
        if (Espruino.Core.Serial.isConnected())
          console.error("serial_frame: already connected");

        Espruino.Core.MenuPortSelector.connectToPort(event.data, function() {
          console.log("serial_frame: connected");
        });
        break;
      case "connected": if (callbacks.connected) {
        callbacks.connected({ok:true});
        callbacks.connected = undefined;
      } break;
      case "disconnected": if (callbacks.disconnected) {
        callbacks.disconnected();
        callbacks.disconnected = undefined;
      } break;
      case "written": if (callbacks.written) {
        callbacks.written();
        callbacks.written = undefined;
      } break;
      case "receive": if (callbacks.receive) {
        if (typeof event.data!="string")
          console.error("serial_frame: receive event expecting data string");
        callbacks.receive(Espruino.Core.Utils.stringToArrayBuffer(event.data));
      } break;
      case "setMaxWriteLength": {
        // Set the maximum amount of data we're allowed to write in one go
        device.maxWriteLength = parseInt(event.data);
      } break;
      default:
        console.error("Unknown event type ",event.type);
        break;
    }
  });

  function post(msg) {
    msg.from="ide";
    window.parent.postMessage(msg,"*");
  }

  var device = {
    "name" : "window.postMessage",
    "init" : function() {
      post({type:"init"});
    },
    "getPorts": function(callback) {
      if (!ENABLED) {
        callback([], true/*instantPorts*/);
        return;
      }
      post({type:"getPorts"});
      var timeout = setTimeout(function() {
        timeout = undefined;
        callbacks.ports = undefined;
        callback([], false/*instantPorts*/);
        console.error("serial_frame: getPorts timeout, disabling");
        ENABLED = false;
      },100);
      callbacks.ports = function(d) {
        if (!timeout) {
          console.error("serial_frame: ports received after timeout");
          return;
        }
        clearTimeout(timeout);
        timeout = undefined;
        callback(d, false/*instantPorts*/);
      };
    },
    "open": function(path, openCallback, receiveCallback, disconnectCallback) {
      callbacks.connected = openCallback;
      callbacks.receive = receiveCallback;
      callbacks.disconnected = disconnectCallback;
      post({type:"connect",data:path});
    },
    "write": function(d, callback) {
      callbacks.written = callback;
      post({type:"write",data:d});
    },
    "close": function() {
      post({type:"disconnect"});
    },
  };
  Espruino.Core.Serial.devices.push(device);
})();
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp'),
    fs = require('fs'),
    babel = require('babel'),
    istanbul = require('istanbul'),
    mocha = require('gulp-mocha'),
    parseVLQ = require('parse-base64vlq-mappings'),
    sourceStore = istanbul.Store.create('memory'),

getDataURI = function (sourceMap) {
    return 'data:application/json;base64,' + new Buffer(unescape(encodeURIComponent(sourceMap)), 'binary').toString('base64');
},

fixSourceMapContent = function (sourceMap, source) {
    var map = JSON.parse(sourceMap);

    map.sourcesContent = [source];
    return JSON.stringify(map);
},

betterIndent = function (string, loc) {
    var size = string.length,
        newloc = size - (size % 4) + 8;

    if (newloc < loc) {
        newloc = loc;
    }

    return string + (new Array(newloc - size + 1)).join(' ');
},

addSourceComments = function (source) {
    var sourceComment = source.match(/\n\/\/# sourceMappingURL=data:application\/json;base64,(.+)/),
        sourceMap,
        oldlines,
        lines = source.split(/\n/),
        mappings = [],
        loc,
        line,
        outputs = [];

    if (sourceComment) {
        sourceMap = JSON.parse(new Buffer(sourceComment[1], 'base64').toString('utf8'));
        oldlines = sourceMap.sourcesContent[0].split(/\n/);
        parseVLQ(sourceMap.mappings).forEach(function (P) {
            mappings[P.generated.line] = P.original.line;
        });
        mappings.forEach(function (V, I) {
            if (!V || !I || outputs[V]) {
                loc -= 8;
                return;
            }

            // Mapping once
            outputs[V] = 1;

            // Do not comment when transform nothing
            if (oldlines[V-1] === lines[I-1]) {
                return;
            }

            line = betterIndent(lines[I-1], loc);
            loc = line.length;

            // Add comment to hint original code
            lines[I-1] = line + '// ' + ((V!==I) ? ('Line ' + V + ': ') : '') + oldlines[V-1];
        });
        source = lines.join('\n').replace(/\/\/# sourceMappingURL=.+/, '// SourceMap was distributed to comments by gulp-jsx-coverage');
    }

    return source;
},

// Never use node-jsx or other transform in your testing code!
initIstanbulHookHack = function (options) {
    var Module = require('module'),
        instrumenter = new istanbul.Instrumenter(options.istanbul);

    global[options.istanbul.coverageVariable] = {};
    sourceStore.dispose();

    Module._extensions['.js'] = function (module, filename) {
        var src = fs.readFileSync(filename, {encoding: 'utf8'}),
            babelFiles = Object.assign({
                include: /\.jsx?$/,
                exclude: /node_modules/
            }, options.transpile ? options.transpile.babel : undefined),
            coffeeFiles = Object.assign({
                include: /\.coffee$/,
                exclude: /^$/
            }, options.transpile ? options.transpile.coffee : undefined),
            tmp;

        if (filename.match(babelFiles.include) && !filename.match(babelFiles.exclude)) {
            try {
                src = babel.transform(src, Object.assign({
                    filename: filename
                }, options.babel)).code;
            } catch (e) {
                throw new Error('Error when transform es6/jsx ' + filename + ': ' + e.toString());
            }
        }

        if (filename.match(coffeeFiles.include) && !filename.match(coffeeFiles.exclude)) {
            try {
                tmp = require('coffee-script').compile(src, options.coffee);
                src = tmp.js + '\n//# sourceMappingURL=' + getDataURI(fixSourceMapContent(tmp.v3SourceMap, src));
            } catch (e) {
                throw new Error('Error when transform coffee ' + filename + ': ' + e.toString());
            }
        }

        // Don't instrument files that aren't meant to be
        if (!filename.match(options.istanbul.exclude)) {
            sourceStore.set(filename, addSourceComments(src));
            try {
                src = instrumenter.instrumentSync(src, filename);
            } catch (e) {
                throw new Error('Error when instrument ' + filename + ': ' + e.toString());
            }
        }

        module._compile(src, filename);
    };
};

module.exports.createTask = function (options) {
    return function () {
        var init = initIstanbulHookHack(options),
            Collector = istanbul.Collector;

        return gulp.src(options.src)
        .pipe(mocha(options.mocha))
        .on('end', function () {
            var collector = new Collector();

            collector.add(global[options.istanbul.coverageVariable]);

            options.coverage.reporters.forEach(function (R) {
                istanbul.Report.create(R, {
                    sourceStore: sourceStore,
                    dir: options.coverage.directory
                }).writeReport(collector, true);
            });

            if ('function' === (typeof options.cleanup)) {
                options.cleanup(this);
            }
        });
    };
};

require('object.assign').shim();
<commit_msg>make it possible to use other tester<commit_after>'use strict';

var gulp = require('gulp'),
    fs = require('fs'),
    babel = require('babel'),
    istanbul = require('istanbul'),
    mocha = require('gulp-mocha'),
    parseVLQ = require('parse-base64vlq-mappings'),
    sourceStore = istanbul.Store.create('memory'),

getDataURI = function (sourceMap) {
    return 'data:application/json;base64,' + new Buffer(unescape(encodeURIComponent(sourceMap)), 'binary').toString('base64');
},

fixSourceMapContent = function (sourceMap, source) {
    var map = JSON.parse(sourceMap);

    map.sourcesContent = [source];
    return JSON.stringify(map);
},

betterIndent = function (string, loc) {
    var size = string.length,
        newloc = size - (size % 4) + 8;

    if (newloc < loc) {
        newloc = loc;
    }

    return string + (new Array(newloc - size + 1)).join(' ');
},

addSourceComments = function (source) {
    var sourceComment = source.match(/\n\/\/# sourceMappingURL=data:application\/json;base64,(.+)/),
        sourceMap,
        oldlines,
        lines = source.split(/\n/),
        mappings = [],
        loc,
        line,
        outputs = [];

    if (sourceComment) {
        sourceMap = JSON.parse(new Buffer(sourceComment[1], 'base64').toString('utf8'));
        oldlines = sourceMap.sourcesContent[0].split(/\n/);
        parseVLQ(sourceMap.mappings).forEach(function (P) {
            mappings[P.generated.line] = P.original.line;
        });
        mappings.forEach(function (V, I) {
            if (!V || !I || outputs[V]) {
                loc -= 8;
                return;
            }

            // Mapping once
            outputs[V] = 1;

            // Do not comment when transform nothing
            if (oldlines[V-1] === lines[I-1]) {
                return;
            }

            line = betterIndent(lines[I-1], loc);
            loc = line.length;

            // Add comment to hint original code
            lines[I-1] = line + '// ' + ((V!==I) ? ('Line ' + V + ': ') : '') + oldlines[V-1];
        });
        source = lines.join('\n').replace(/\/\/# sourceMappingURL=.+/, '// SourceMap was distributed to comments by gulp-jsx-coverage');
    }

    return source;
},

// Never use node-jsx or other transform in your testing code!
initIstanbulHookHack = function (options) {
    var Module = require('module'),
        instrumenter = new istanbul.Instrumenter(options.istanbul);

    global[options.istanbul.coverageVariable] = {};
    sourceStore.dispose();

    Module._extensions['.js'] = function (module, filename) {
        var src = fs.readFileSync(filename, {encoding: 'utf8'}),
            babelFiles = Object.assign({
                include: /\.jsx?$/,
                exclude: /node_modules/
            }, options.transpile ? options.transpile.babel : undefined),
            coffeeFiles = Object.assign({
                include: /\.coffee$/,
                exclude: /^$/
            }, options.transpile ? options.transpile.coffee : undefined),
            tmp;

        if (filename.match(babelFiles.include) && !filename.match(babelFiles.exclude)) {
            try {
                src = babel.transform(src, Object.assign({
                    filename: filename
                }, options.babel)).code;
            } catch (e) {
                throw new Error('Error when transform es6/jsx ' + filename + ': ' + e.toString());
            }
        }

        if (filename.match(coffeeFiles.include) && !filename.match(coffeeFiles.exclude)) {
            try {
                tmp = require('coffee-script').compile(src, options.coffee);
                src = tmp.js + '\n//# sourceMappingURL=' + getDataURI(fixSourceMapContent(tmp.v3SourceMap, src));
            } catch (e) {
                throw new Error('Error when transform coffee ' + filename + ': ' + e.toString());
            }
        }

        // Don't instrument files that aren't meant to be
        if (!filename.match(options.istanbul.exclude)) {
            sourceStore.set(filename, addSourceComments(src));
            try {
                src = instrumenter.instrumentSync(src, filename);
            } catch (e) {
                throw new Error('Error when instrument ' + filename + ': ' + e.toString());
            }
        }

        module._compile(src, filename);
    };
},

GJC = {
    initIstanbulHook: function (options) {
        initIstanbulHookHack(options);
    },
    colloectIstanbulCoverage: function (options) {
        return function () {
            var Collector = istanbul.Collector,
                collector = new Collector();

            collector.add(global[options.istanbul.coverageVariable]);

            options.coverage.reporters.forEach(function (R) {
                istanbul.Report.create(R, {
                    sourceStore: sourceStore,
                    dir: options.coverage.directory
                }).writeReport(collector, true);
            });

            if ('function' === (typeof options.cleanup)) {
                options.cleanup(this);
            }
        }
    },
    createTask: function (options) {
        return function () {
            GJC.initIstanbulHook(options);

            return gulp.src(options.src)
            .pipe(mocha(options.mocha))
            .on('end', GJC.colloectIstanbulCoverage(options));
        };
    }
};

module.exports = GJC;

require('object.assign').shim();
<|endoftext|>


<commit_before>'use strict';
const fs = require('fs.extra');
const electron = require('electron');
const tableify = require('tableify');
const {dialog} = require('electron');
const LineByLineReader = require('line-by-line');

const JSONParsed = [];
const app = electron.app;
let loadFile;
let win;
// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')();
// prevent window being garbage collected
let mainWindow;
function createMainWindow() {
	win = new electron.BrowserWindow({
		width: 600,
		height: 400
	});

	win.on('closed', onClosed);

// menu functions be here
}
function onClosed() {
// dereference the window
// for multiple windows store them in an array
	mainWindow = null;
}
function funcLoad() {
	loadFile = dialog.showOpenDialog({properties: ['openFile']});
	if (/\.[log]+$/i.test(loadFile) === true) {
		readLine();
		win.loadURL(`file:///${loadFile}`);
	} else {
		console.log('Please load a .log file.');
	}
}
function readLine() {
	const loadPls = loadFile;
	const lr = new LineByLineReader(loadPls[0]);

	lr.on('error', err => {
		return console.log(err);
	});

	lr.on('line', line => {
		const lineParse = JSON.parse(line);
		JSONParsed.push(lineParse);
// console.log(JSONParsed);
		const html = tableify(lineParse) + '
';
		fs.appendFile(`${process.resourcesPath}/index2.html`, html, err => {
			if (err) {
				return console.log(err);
			}
		});
	});
	fs.appendFile(`${process.resourcesPath}/index2.html`, '<link href="https://fonts.googleapis.com/css?family=Lato:400,400italic,700" rel="stylesheet" type="text/css">', err => {
		if (err) {
			return console.log(err);
		}
	});
	lr.on('end', () => {
		console.log('done!');
		console.log('The file was saved!');
		win.loadURL(`file://${process.resourcesPath}/index2.html`);
	});
	return win;
}

function funcSave() {
	dialog.showSaveDialog(fileName => {
		if (fileName === undefined) {
			console.log('You didn\'t save the file');
			return;
		}
// fileName is a string that contains the path and filename created in the save file dialog.
		fs.copy(`${process.resourcesPath}/index2.html`, fileName, err => {
			if (err) {
				console.log(err.message);
			}
		});
	}
);
}
function funcSaveJSON() {
	dialog.showSaveDialog(fileName => {
		if (fileName === undefined) {
			console.log('You didn\'t save the file');
			return;
		}
		const JSONParsedSave = JSON.stringify(JSONParsed);
		fs.writeFile(fileName, JSONParsedSave, err => {
			if (err) {
				console.log(err.message);
			}
		});
	});
}
app.on('window-all-closed', () => {
	if (process.platform !== 'darwin') {
		app.quit();
	}
	fs.writeFile(`${process.resourcesPath}/index2.html`, '', err => {
		if (err) {
			return console.log(err);
		}
	});
});
app.on('activate', () => {
	if (!mainWindow) {
		mainWindow = createMainWindow();
	}
});

app.on('ready', () => {
	mainWindow = createMainWindow();
});

const {Menu} = require('electron');

const template = [
	{
		label: 'File',
		submenu: [
	{label: 'Save as HTML', click: funcSave},
	{label: 'Save as JSON', click: funcSaveJSON},
	{label: 'Load', click: funcLoad}

		]
	},
	{
		label: 'Edit',
		submenu: [
			{
				role: 'selectall'
			}
		]
	},
	{
		label: 'View',
		submenu: [
			{
				label: 'Reload',
				accelerator: 'CmdOrCtrl+R',
				click(item, focusedWindow) {
					if (focusedWindow) {
						focusedWindow.reload();
					}
				}
			},
			{
				role: 'togglefullscreen'
			}
		]
	},
	{
		role: 'window',
		submenu: [
			{
				role: 'minimize'
			},
			{
				role: 'close'
			}
		]
	},
	{
		role: 'help',
		submenu: [
			{
				label: 'Learn More',
				click() {
					require('electron').shell.openExternal('http://electron.atom.io');
				}
			}
		]
	}
];

if (process.platform === 'darwin') {
	const name = require('electron').remote.app.getName();

	template.unshift({
		label: name,
		submenu: [
			{
				role: 'about'
			},
			{
				type: 'separator'
			},
			{
				role: 'services',
				submenu: []
			},
			{
				type: 'separator'
			},
			{
				role: 'hide'
			},
			{
				role: 'hideothers'
			},
			{
				role: 'unhide'
			},
			{
				type: 'separator'
			},
			{
				role: 'quit'
			}
		]
	});
// Edit menu.
	template[1].submenu.push(
		{
			type: 'separator'
		},
		{
			label: 'Speech',
			submenu: [
				{
					role: 'startspeaking'
				},
				{
					role: 'stopspeaking'
				}
			]
		}
);
// Window menu.
	template[3].submenu = [
		{
			label: 'Close',
			accelerator: 'CmdOrCtrl+W',
			role: 'close'
		},
		{
			label: 'Minimize',
			accelerator: 'CmdOrCtrl+M',
			role: 'minimize'
		},
		{
			label: 'Zoom',
			role: 'zoom'
		},
		{
			type: 'separator'
		},
		{
			label: 'Bring All to Front',
			role: 'front'
		}
	];
}

const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
<commit_msg>made loading multiple files without closing in-between work properly<commit_after>'use strict';
const fs = require('fs.extra');
const electron = require('electron');
const tableify = require('tableify');
const {dialog} = require('electron');
const LineByLineReader = require('line-by-line');

const JSONParsed = [];
const app = electron.app;
let loadFile;
let win;
// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')();
// prevent window being garbage collected
let mainWindow;
function createMainWindow() {
	win = new electron.BrowserWindow({
		width: 600,
		height: 400
	});

	win.on('closed', onClosed);

// menu functions be here
}
function onClosed() {
// dereference the window
// for multiple windows store them in an array
	mainWindow = null;
}
function funcLoad() {
	loadFile = dialog.showOpenDialog({properties: ['openFile']});
	if (/\.[log]+$/i.test(loadFile) === true) {
		fs.writeFile(`${process.resourcesPath}/index2.html`, '', err => {
		if (err) {
			return console.log(err);
		}
	});
		readLine();
		win.loadURL(`file:///${loadFile}`);
	} else {
		console.log('Please load a .log file.');
	}
}
function readLine() {
	const loadPls = loadFile;
	const lr = new LineByLineReader(loadPls[0]);

	lr.on('error', err => {
		return console.log(err);
	});

	lr.on('line', line => {
		const lineParse = JSON.parse(line);
		JSONParsed.push(lineParse);
// console.log(JSONParsed);
		const html = tableify(lineParse) + '
';
		fs.appendFile(`${process.resourcesPath}/index2.html`, html, err => {
			if (err) {
				return console.log(err);
			}
		});
	});
	fs.appendFile(`${process.resourcesPath}/index2.html`, '<link href="https://fonts.googleapis.com/css?family=Lato:400,400italic,700" rel="stylesheet" type="text/css">', err => {
		if (err) {
			return console.log(err);
		}
	});
	lr.on('end', () => {
		console.log('done!');
		console.log('The file was saved!');
		win.loadURL(`file://${process.resourcesPath}/index2.html`);
	});
	return win;
}

function funcSave() {
	dialog.showSaveDialog(fileName => {
		if (fileName === undefined) {
			console.log('You didn\'t save the file');
			return;
		}
// fileName is a string that contains the path and filename created in the save file dialog.
		fs.copy(`${process.resourcesPath}/index2.html`, fileName, err => {
			if (err) {
				console.log(err.message);
			}
		});
	}
);
}
function funcSaveJSON() {
	dialog.showSaveDialog(fileName => {
		if (fileName === undefined) {
			console.log('You didn\'t save the file');
			return;
		}
		const JSONParsedSave = JSON.stringify(JSONParsed);
		fs.writeFile(fileName, JSONParsedSave, err => {
			if (err) {
				console.log(err.message);
			}
		});
	});
}
app.on('window-all-closed', () => {
	if (process.platform !== 'darwin') {
		app.quit();
	}
	fs.writeFile(`${process.resourcesPath}/index2.html`, '', err => {
		if (err) {
			return console.log(err);
		}
	});
});
app.on('activate', () => {
	if (!mainWindow) {
		mainWindow = createMainWindow();
	}
});

app.on('ready', () => {
	mainWindow = createMainWindow();
});

const {Menu} = require('electron');

const template = [
	{
		label: 'File',
		submenu: [
	{label: 'Save as HTML', click: funcSave},
	{label: 'Save as JSON', click: funcSaveJSON},
	{label: 'Load', click: funcLoad}

		]
	},
	{
		label: 'Edit',
		submenu: [
			{
				role: 'selectall'
			}
		]
	},
	{
		label: 'View',
		submenu: [
			{
				label: 'Reload',
				accelerator: 'CmdOrCtrl+R',
				click(item, focusedWindow) {
					if (focusedWindow) {
						focusedWindow.reload();
					}
				}
			},
			{
				role: 'togglefullscreen'
			}
		]
	},
	{
		role: 'window',
		submenu: [
			{
				role: 'minimize'
			},
			{
				role: 'close'
			}
		]
	},
	{
		role: 'help',
		submenu: [
			{
				label: 'Learn More',
				click() {
					require('electron').shell.openExternal('http://electron.atom.io');
				}
			}
		]
	}
];

if (process.platform === 'darwin') {
	const name = require('electron').remote.app.getName();

	template.unshift({
		label: name,
		submenu: [
			{
				role: 'about'
			},
			{
				type: 'separator'
			},
			{
				role: 'services',
				submenu: []
			},
			{
				type: 'separator'
			},
			{
				role: 'hide'
			},
			{
				role: 'hideothers'
			},
			{
				role: 'unhide'
			},
			{
				type: 'separator'
			},
			{
				role: 'quit'
			}
		]
	});
// Edit menu.
	template[1].submenu.push(
		{
			type: 'separator'
		},
		{
			label: 'Speech',
			submenu: [
				{
					role: 'startspeaking'
				},
				{
					role: 'stopspeaking'
				}
			]
		}
);
// Window menu.
	template[3].submenu = [
		{
			label: 'Close',
			accelerator: 'CmdOrCtrl+W',
			role: 'close'
		},
		{
			label: 'Minimize',
			accelerator: 'CmdOrCtrl+M',
			role: 'minimize'
		},
		{
			label: 'Zoom',
			role: 'zoom'
		},
		{
			type: 'separator'
		},
		{
			label: 'Bring All to Front',
			role: 'front'
		}
	];
}

const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
<|endoftext|>


<commit_before>var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  //First what client do is emit current chat data
  /**
   *  chatData = {
   *    userName,
   *    rommName
   *  }
   */
  socket.on('enter room', function(chatData){
    socket.chatData = chatData;

    socket.join(socket.chatData.roomName);

    sendMessageFromServer(socket.chatData.userName + " connected.");

     socket.on('chat message', function(data){
       socket.broadcast.to(socket.chatData.roomName).emit('chat message', data);
     });

     socket.on('name change', function(newName){
       var oldName = socket.chatData.userName;
       socket.chatData.userName = newName;
       sendMessageFromServer(oldName + " changes name to " + newName + ".");
     });

     socket.on('disconnect', function(data){
       sendMessageFromServer(socket.chatData.userName + " disconnected.");
     });
  });
});

http.listen(process.env.PORT || 5000, function(){
  console.log('listening on *:' + process.env.PORT || 5000);
});

var sendMessageFromServer = function(content){
  socket.broadcast.to(socket.chatData.roomName).emit('chat message', {
      key: (new Date()).getTime(),
      sender: "Chat",
      content: content,
      power: 0,
      isServerMsg: true
  })
}<commit_msg>Fixed sendMessageFromServer<commit_after>var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  //First what client do is emit current chat data
  /**
   *  chatData = {
   *    userName,
   *    rommName
   *  }
   */
  socket.on('enter room', function(chatData){
    socket.chatData = chatData;

    socket.join(socket.chatData.roomName);

    sendMessageFromServer(socket, socket.chatData.userName + " connected.");

     socket.on('chat message', function(data){
       socket.broadcast.to(socket.chatData.roomName).emit('chat message', data);
     });

     socket.on('name change', function(newName){
       var oldName = socket.chatData.userName;
       socket.chatData.userName = newName;
       sendMessageFromServer(socket, oldName + " changes name to " + newName + ".");
     });

     socket.on('disconnect', function(data){
       sendMessageFromServer(socket, socket.chatData.userName + " disconnected.");
     });
  });
});

http.listen(process.env.PORT || 5000, function(){
  console.log('listening on *:' + process.env.PORT || 5000);
});

var sendMessageFromServer = function(socket, content){
  socket.broadcast.to(socket.chatData.roomName).emit('chat message', {
      key: (new Date()).getTime(),
      sender: "Chat",
      content: content,
      power: 0,
      isServerMsg: true
  })
}<|endoftext|>


<commit_before>/* eslint-env node */
'use strict'

module.exports = {
  name: 'ember-test-utils',

  included: function (app) {
    this._super.included(app)
  },

  treeForAddon (tree) {
    const environment = this.app.env
    const config = this.pkg['ember-test-utils'] || {}
    const excludeFromEnvironments = config.excludeFromEnvironments || []

    if (excludeFromEnvironments.indexOf(environment) !== -1) {
      return null
    }

    return this._super.treeForAddon.call(this, tree)
  }
}
<commit_msg>remove included hook from index.js<commit_after>/* eslint-env node */
'use strict'

module.exports = {
  name: 'ember-test-utils',

  treeForAddon (tree) {
    const environment = this.app.env
    const config = this.pkg['ember-test-utils'] || {}
    const excludeFromEnvironments = config.excludeFromEnvironments || []

    if (excludeFromEnvironments.indexOf(environment) !== -1) {
      return null
    }

    return this._super.treeForAddon.call(this, tree)
  }
}
<|endoftext|>


<commit_before>var color = require('stylecow-color');

module.exports = function (stylecow) {

	stylecow.addTask({
		disable: {
			explorer: 9.0
		},
		Declaration: {
			background: fixer,
			"background-image": fixer
		}
	});
};

function fixer (declaration) {
	var fn = declaration.search({type: 'Function', name: 'linear-gradient'});

	if (fn.length === 1) {
		var filter = getFilter(fn[0].getContent());

		if (filter) {
			declaration.parent({type: 'Rule'}).addOldMsFilter(filter);
		}
	}
}

function getFilter (params) {
	var direction, reverse;

	switch (params.shift()) {
		case 'to bottom':
		case '90deg':
			direction = 'vertical';
			reverse = false;
			break;

		case 'to top':
		case '-90deg':
			direction = 'vertical';
			reverse = true;
			break;

		case 'to right':
		case '180deg':
		case '-180deg':
			direction = 'horizontal';
			reverse = false;
			break;

		case 'to left':
		case '0deg':
		case '360deg':
			direction = 'vertical';
			reverse = true;
			break;

		default:
			return;
	}

	if (direction && params.length === 2) {
		params[0] = color.RGBA_HEX(color.toRGBA(params[0]));
		params[1] = color.RGBA_HEX(color.toRGBA(params[1]));

		if (reverse) {
			params.reverse();
		}

		if (direction === 'horizontal') {
			return 'progid:DXImageTransform.Microsoft.gradient(startColorStr="#' + params[0] + '", endColorStr="#' + params[1] + '", GradientType=1)';
		}

		return 'progid:DXImageTransform.Microsoft.gradient(startColorStr="#' + params[0] + '", endColorStr="#' + params[1] + '")';
	}
}
<commit_msg>changes for v4<commit_after>var color = require('stylecow-color');

module.exports = function (stylecow) {

	stylecow.addTask({
		disable: {
			explorer: 9.0
		},
		Declaration: {
			background: fixer,
			"background-image": fixer
		}
	});

	function fixer (declaration) {
		var fn = declaration.searchFirst({type: 'Function', name: 'linear-gradient'});

		if (fn) {
			var filter = getFilter(fn.toArray());

			if (filter) {
				stylecow.utils.addMsFilter(declaration.parent({type: 'Block'}), filter);
			}
		}
	}
};

function getFilter (params) {
	var direction, reverse;

	switch (params.shift()) {
		case 'top':
		case 'to bottom':
		case '90deg':
			direction = 'vertical';
			reverse = false;
			break;

		case 'bottom':
		case 'to top':
		case '-90deg':
			direction = 'vertical';
			reverse = true;
			break;

		case 'left':
		case 'to right':
		case '180deg':
		case '-180deg':
			direction = 'horizontal';
			reverse = false;
			break;

		case 'right':
		case 'to left':
		case '0deg':
		case '360deg':
			direction = 'vertical';
			reverse = true;
			break;

		default:
			return;
	}

	if (direction && params.length === 2) {
		params[0] = color.RGBA_HEX(color.toRGBA(params[0]));
		params[1] = color.RGBA_HEX(color.toRGBA(params[1]));

		if (reverse) {
			params.reverse();
		}

		if (direction === 'horizontal') {
			return 'progid:DXImageTransform.Microsoft.gradient(startColorStr="#' + params[0] + '", endColorStr="#' + params[1] + '", GradientType=1)';
		}

		return 'progid:DXImageTransform.Microsoft.gradient(startColorStr="#' + params[0] + '", endColorStr="#' + params[1] + '")';
	}
}
<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

var Funnel = require('broccoli-funnel');
var mergeTrees = require('broccoli-merge-trees');

module.exports = {
  name: 'ember-google-publisher-tags',

  contentFor: function(type, config) {
    if (type === 'head-footer' && !this.app.options.gptIframeJail) {
      return `
<script type='text/javascript'>
  var googletag = googletag || {};
  googletag.cmd = googletag.cmd || [];
  (function() {
    var gads = document.createElement('script');
    gads.async = true;
    gads.type = 'text/javascript';
    var useSSL = 'https:' == document.location.protocol;
    gads.src = (useSSL ? 'https:' : 'http:') +
      '//www.googletagservices.com/tag/js/gpt.js';
    var node = document.getElementsByTagName('script')[0];
    node.parentNode.insertBefore(gads, node);
  })();
</script>
      `;
    }
  },

  config: function(env, config) {
    if (this.app) {
      // TODO: `this.app` check is necessary for "ember serve", but not "ember build": why?
      this.app.options.gptIframeJail = config.gpt && config.gpt.iframeJail;
    }
  },

  treeForPublic: function(tree) {
    if (this.app.options.gptIframeJail) {
      var assetsTree = new Funnel('public');
      return mergeTrees([tree, assetsTree], {
        overwrite: true
      });
    }
  }
};
<commit_msg>Fix iframeJail option when serving an app in ember@2.16.0+<commit_after>/* jshint node: true */
'use strict';

module.exports = {
  name: 'ember-google-publisher-tags',

  contentFor: function(type, config) {
    if (type === 'head-footer' && !this.gptIframeJail) {
      return `
<script type='text/javascript'>
  var googletag = googletag || {};
  googletag.cmd = googletag.cmd || [];
  (function() {
    var gads = document.createElement('script');
    gads.async = true;
    gads.type = 'text/javascript';
    var useSSL = 'https:' == document.location.protocol;
    gads.src = (useSSL ? 'https:' : 'http:') +
      '//www.googletagservices.com/tag/js/gpt.js';
    var node = document.getElementsByTagName('script')[0];
    node.parentNode.insertBefore(gads, node);
  })();
</script>
      `;
    }
  },

  config: function(env, config) {
    this.gptIframeJail = config.gpt && config.gpt.iframeJail;
  },

  treeForPublic: function(tree) {
    if (this.gptIframeJail) {
      return tree;
    }
  }
};
<|endoftext|>


<commit_before>/* @flow weak */

const bunyan = require('bunyan')
const fse = require('fs-extra')
const os = require('os')
const path = require('path')
const _ = require('lodash')

const LOG_DIR = path.join(
  process.env.COZY_DESKTOP_DIR || os.homedir(),
  '.cozy-desktop'
)
const LOG_FILENAME = 'logs.txt'
const LOG_FILE = path.join(LOG_DIR, LOG_FILENAME)

fse.ensureDirSync(LOG_DIR)

const defaultLogger = bunyan.createLogger({
  name: 'Cozy Desktop',
  level: 'trace',
  serializers: {
    err: bunyan.stdSerializers.err
  },
  streams: [
    {
      type: 'rotating-file',
      path: LOG_FILE,
      period: '1d',
      count: 7
    }
  ]
})

if (process.env.DEBUG) {
  const logPath = 'debug.log'
  if (fse.existsSync(logPath)) fse.unlinkSync(logPath)
  defaultLogger.addStream({ type: 'file', path: logPath, level: 'trace' })
}
if (process.env.TESTDEBUG) {
  defaultLogger.addStream({
    type: 'raw',
    level: process.env.TESTDEBUG,
    stream: {
      write: function(msg) {
        // eslint-disable-next-line no-console
        console.log(
          msg.component,
          msg.path || '',
          msg.msg,
          _.omit(msg, [
            'component',
            'pid',
            'name',
            'hostname',
            'level',
            'time',
            'v',
            'msg'
          ])
        )
      }
    }
  })
}

function logger(options) {
  return defaultLogger.child(options, true)
}

logger.defaultLogger = defaultLogger
logger.LOG_DIR = LOG_DIR
logger.LOG_FILENAME = LOG_FILENAME
logger.LOG_FILE = LOG_FILE
module.exports = logger
<commit_msg>core/logger: Expose Logger type<commit_after>/* @flow weak */

const bunyan = require('bunyan')
const fse = require('fs-extra')
const os = require('os')
const path = require('path')
const _ = require('lodash')

/*::
export type Logger = bunyan.Logger
*/

const LOG_DIR = path.join(
  process.env.COZY_DESKTOP_DIR || os.homedir(),
  '.cozy-desktop'
)
const LOG_FILENAME = 'logs.txt'
const LOG_FILE = path.join(LOG_DIR, LOG_FILENAME)

fse.ensureDirSync(LOG_DIR)

const defaultLogger = bunyan.createLogger({
  name: 'Cozy Desktop',
  level: 'trace',
  serializers: {
    err: bunyan.stdSerializers.err
  },
  streams: [
    {
      type: 'rotating-file',
      path: LOG_FILE,
      period: '1d',
      count: 7
    }
  ]
})

if (process.env.DEBUG) {
  const logPath = 'debug.log'
  if (fse.existsSync(logPath)) fse.unlinkSync(logPath)
  defaultLogger.addStream({ type: 'file', path: logPath, level: 'trace' })
}
if (process.env.TESTDEBUG) {
  defaultLogger.addStream({
    type: 'raw',
    level: process.env.TESTDEBUG,
    stream: {
      write: function(msg) {
        // eslint-disable-next-line no-console
        console.log(
          msg.component,
          msg.path || '',
          msg.msg,
          _.omit(msg, [
            'component',
            'pid',
            'name',
            'hostname',
            'level',
            'time',
            'v',
            'msg'
          ])
        )
      }
    }
  })
}

function logger(options) {
  return defaultLogger.child(options, true)
}

logger.defaultLogger = defaultLogger
logger.LOG_DIR = LOG_DIR
logger.LOG_FILENAME = LOG_FILENAME
logger.LOG_FILE = LOG_FILE
module.exports = logger
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var processor = require('./helpers/processor');
var bot = require('./helpers/yemekciBot');
var constants = require('./constants/fileConstants');
var redis = require('redis');
var schedule = require('node-schedule');

// schedule.scheduleJob('0 0 11 1/1 * ? *', function(){
//   var today = new Date();
//   bot.sendLunch(today);
//   bot.sendLunchToTwitter(today);
// });
//
// schedule.scheduleJob('0 30 16 1/1 * ? *', function(){
//   var today = new Date();
//   bot.sendDinner(today);
//   bot.sendDinnerToTwitter(today);
// });

schedule.scheduleJob('*/10 * * * * *', function(){
  var today = new Date();
  bot.sendLunch(today);
  bot.sendLunchToTwitter(today);
});

schedule.scheduleJob('*/15 * * * * *', function(){
  var today = new Date();
  bot.sendDinner(today);
  bot.sendDinnerToTwitter(today);
});

var client = redis.createClient();

app.set('port', (process.env.PORT || 5000));

app.use(express.static(__dirname + '/public'));

// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.get('/', function(request, res) {
  res.setHeader('Content-Type', 'application/json');
  processor.getJSONMonthlyYemekList(function(data) {
    res.send(data);
  });
});

app.get('/import', function(request, res) {
  res.setHeader('Content-Type', 'application/json');
  processor.getJSONMonthlyYemekList(function(data) {
    data = JSON.parse(data)
    Object.keys(data).forEach(function(key,index) {
      client.set(key, JSON.stringify(data[key]));
      console.log(key + " saved")
    });
    res.send(data);
  });
});

app.get('/send/lunch', function(request, res) {
  var today = new Date();
  bot.sendLunch(today);
  res.send("gönderildi");
});

app.get('/send/dinner', function(request, res) {
  var today = new Date();
  bot.sendDinner(today);
  res.send("gönderildi");

});

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});
<commit_msg>schedullar finalized<commit_after>var express = require('express');
var app = express();
var processor = require('./helpers/processor');
var bot = require('./helpers/yemekciBot');
var constants = require('./constants/fileConstants');
var redis = require('redis');
var schedule = require('node-schedule');

schedule.scheduleJob('0 0 11 1/1 * ? *', function(){
  var today = new Date();
  bot.sendLunch(today);
  bot.sendLunchToTwitter(today);
});

schedule.scheduleJob('0 30 16 1/1 * ? *', function(){
  var today = new Date();
  bot.sendDinner(today);
  bot.sendDinnerToTwitter(today);
});

var client = redis.createClient();

app.set('port', (process.env.PORT || 5000));

app.use(express.static(__dirname + '/public'));

// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.get('/', function(request, res) {
  res.setHeader('Content-Type', 'application/json');
  processor.getJSONMonthlyYemekList(function(data) {
    res.send(data);
  });
});

app.get('/import', function(request, res) {
  res.setHeader('Content-Type', 'application/json');
  processor.getJSONMonthlyYemekList(function(data) {
    data = JSON.parse(data)
    Object.keys(data).forEach(function(key,index) {
      client.set(key, JSON.stringify(data[key]));
      console.log(key + " saved")
    });
    res.send(data);
  });
});

app.get('/send/lunch', function(request, res) {
  var today = new Date();
  bot.sendLunch(today);
  res.send("gönderildi");
});

app.get('/send/dinner', function(request, res) {
  var today = new Date();
  bot.sendDinner(today);
  res.send("gönderildi");

});

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});
<|endoftext|>


<commit_before>const crypto = require('crypto');
const lua = require('./lua.json');

function uuid(placeholder) {
  if (placeholder) {
    return (placeholder ^ (crypto.randomBytes(1)[0] % 16) >> placeholder / 4).toString(16);
  } else {
    return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, uuid);
  }
}

function BQueue(redisClient, queueName = 'bqueue', queueCount = 1) {
  if (typeof queueName !== 'string') {
    throw new Error('Queue name must be a string!');
  } else if (!Number.isInteger(queueCount)) {
    throw new Error('Queue count must be an integer!');
  } else if (queueCount < 1 || queueCount > 1000) {
    throw new Error('Queue count must be between 1 and 1000!');
  }

  this.redisClient = redisClient;
  this.queueName = queueName;
  this.queueCount = queueCount;

  this.redisClient.defineCommand('getBatch', {
    numberOfKeys: 1,
    lua: lua.getBatch
  });
  this.redisClient.defineCommand('removeMessages', {
    numberOfKeys: 1,
    lua: lua.removeMessages
  });
  this.redisClient.defineCommand('reinsertUnprocessed', {
    numberOfKeys: 1,
    lua: lua.reinsertUnprocessed
  });
}

BQueue.prototype.pushMessage = function(message = '') {
  return new Promise((resolve, reject) => {
    const queueNumber = Math.floor(Math.random() * this.queueCount);
    const queue = this.queueName + ':' + queueNumber;
    const id = uuid();
    const record = JSON.stringify({
      id: id,
      message: message
    });
    const queueKey = '{' + queue + '}:messages';
    const messageKey = queueKey + ':' + id;
    this.redisClient.pipeline().set(messageKey, record).lpush(queueKey, id).exec(err => {
      if (err) {
        return reject(err);
      } else {
        return resolve({
          name: this.queueName,
          number: queueNumber,
          id: id
        });
      }
    });
  });
};

BQueue.prototype.getBatch = function(maxBatchSize = 1, processingTimeout = 5000) {
  return new Promise((resolve, reject) => {
    if (!Number.isInteger(maxBatchSize)) {
      return reject(Error('Max batch size must be an integer!'));
    } else if (maxBatchSize < 1 || maxBatchSize > 10000) {
      return reject(Error('Max batch sizee must be between 1 and 10000!'));
    } else if (!Number.isInteger(processingTimeout)) {
      return reject(Error('Processing timeout must be an integer!'));
    } else if (processingTimeout < 1000 || processingTimeout > 604800000) {
      return reject(Error('Processing timeout must be between 1000 and 604800000!'));
    }
    const queueNumber = Math.floor(Math.random() * this.queueCount);
    const queue = this.queueName + ':' + queueNumber;
    this.redisClient.getBatch(queue, maxBatchSize, processingTimeout, (err, results) => {
      if (err) {
        return reject(err);
      } else {
        const messages = results.map(value => JSON.parse(value));
        return resolve({
          name: this.queueName,
          number: queueNumber,
          messages: messages,
          remove: () => {
            return new Promise((resolve, reject) => {
              const ids = messages.filter(message => message).map(message => message.id);
              this.redisClient.removeMessages(queue, ...ids, (err, results) => {
                if (err) {
                  return reject(err);
                } else {
                  return resolve(results);
                }
              });
            });
          }
        });
      }
    });
  });
};

BQueue.prototype.reinsertUnprocessed = function(maxMessages = 1000) {
  return new Promise((resolve, reject) => {
    if (!Number.isInteger(maxMessages)) {
      return reject(Error('Max messages must be an integer!'));
    } else if (maxMessages < 1 || maxMessages > 10000) {
      return reject(Error('Max messages must be between 1 and 10000!'));
    }
    const queueNumber = Math.floor(Math.random() * this.queueCount);
    const queue = this.queueName + ':' + queueNumber;
    this.redisClient.reinsertUnprocessed(queue, maxMessages, (err, result) => {
      if (err) {
        return reject(err);
      } else {
        return resolve({
          name: this.queueName,
          number: queueNumber,
          ids: result
        });
      }
    });
  });
};

module.exports = BQueue;
<commit_msg>Add ability to specify queue number<commit_after>const crypto = require('crypto');
const lua = require('./lua.json');

function uuid(placeholder) {
  if (placeholder) {
    return (placeholder ^ (crypto.randomBytes(1)[0] % 16) >> placeholder / 4).toString(16);
  } else {
    return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, uuid);
  }
}

function BQueue(redisClient, queueName = 'bqueue', queueCount = 1) {
  if (typeof queueName !== 'string') {
    throw new Error('Queue name must be a string!');
  } else if (!Number.isInteger(queueCount)) {
    throw new Error('Queue count must be an integer!');
  } else if (queueCount < 1 || queueCount > 1000) {
    throw new Error('Queue count must be between 1 and 1000!');
  }

  this.redisClient = redisClient;
  this.queueName = queueName;
  this.queueCount = queueCount;

  this.redisClient.defineCommand('getBatch', {
    numberOfKeys: 1,
    lua: lua.getBatch
  });
  this.redisClient.defineCommand('removeMessages', {
    numberOfKeys: 1,
    lua: lua.removeMessages
  });
  this.redisClient.defineCommand('reinsertUnprocessed', {
    numberOfKeys: 1,
    lua: lua.reinsertUnprocessed
  });
}

BQueue.prototype.pushMessage = function(message = '', queueNumber = Math.floor(Math.random() * this.queueCount)) {
  return new Promise((resolve, reject) => {
    if (!Number.isInteger(queueNumber)) {
      return reject(Error('Queue number must be an integer!'));
    } else if (queueNumber < 0 || queueNumber >= this.queueCount) {
      return reject(Error('Queue number must be between 0 and ' + this.queueCount - 1 + '!'));
    }
    const queue = this.queueName + ':' + queueNumber;
    const id = uuid();
    const record = JSON.stringify({
      id: id,
      message: message
    });
    const queueKey = '{' + queue + '}:messages';
    const messageKey = queueKey + ':' + id;
    this.redisClient.pipeline().set(messageKey, record).lpush(queueKey, id).exec(err => {
      if (err) {
        return reject(err);
      } else {
        return resolve({
          name: this.queueName,
          number: queueNumber,
          id: id
        });
      }
    });
  });
};

BQueue.prototype.getBatch = function(maxBatchSize = 1, processingTimeout = 5000, queueNumber = Math.floor(Math.random() * this.queueCount)) {
  return new Promise((resolve, reject) => {
    if (!Number.isInteger(maxBatchSize)) {
      return reject(Error('Max batch size must be an integer!'));
    } else if (maxBatchSize < 1 || maxBatchSize > 10000) {
      return reject(Error('Max batch sizee must be between 1 and 10000!'));
    } else if (!Number.isInteger(processingTimeout)) {
      return reject(Error('Processing timeout must be an integer!'));
    } else if (processingTimeout < 1000 || processingTimeout > 604800000) {
      return reject(Error('Processing timeout must be between 1000 and 604800000!'));
    } else if (!Number.isInteger(queueNumber)) {
      return reject(Error('Queue number must be an integer!'));
    } else if (queueNumber < 0 || queueNumber >= this.queueCount) {
      return reject(Error('Queue number must be between 0 and ' + this.queueCount - 1 + '!'));
    }
    const queue = this.queueName + ':' + queueNumber;
    this.redisClient.getBatch(queue, maxBatchSize, processingTimeout, (err, results) => {
      if (err) {
        return reject(err);
      } else {
        const messages = results.map(value => JSON.parse(value));
        return resolve({
          name: this.queueName,
          number: queueNumber,
          messages: messages,
          remove: () => {
            return new Promise((resolve, reject) => {
              const ids = messages.filter(message => message).map(message => message.id);
              this.redisClient.removeMessages(queue, ...ids, (err, results) => {
                if (err) {
                  return reject(err);
                } else {
                  return resolve(results);
                }
              });
            });
          }
        });
      }
    });
  });
};

BQueue.prototype.reinsertUnprocessed = function(maxMessages = 1000, queueNumber = Math.floor(Math.random() * this.queueCount)) {
  return new Promise((resolve, reject) => {
    if (!Number.isInteger(maxMessages)) {
      return reject(Error('Max messages must be an integer!'));
    } else if (maxMessages < 1 || maxMessages > 10000) {
      return reject(Error('Max messages must be between 1 and 10000!'));
    } else if (!Number.isInteger(queueNumber)) {
      return reject(Error('Queue number must be an integer!'));
    } else if (queueNumber < 0 || queueNumber >= this.queueCount) {
      return reject(Error('Queue number must be between 0 and ' + this.queueCount - 1 + '!'));
    }
    const queue = this.queueName + ':' + queueNumber;
    this.redisClient.reinsertUnprocessed(queue, maxMessages, (err, result) => {
      if (err) {
        return reject(err);
      } else {
        return resolve({
          name: this.queueName,
          number: queueNumber,
          ids: result
        });
      }
    });
  });
};

module.exports = BQueue;
<|endoftext|>


<commit_before>"use strict";

const uuid = require('node-uuid');
const EventTarget = require('event-target-shim');
const MacNotification = require('bindings')('Notification').MacNotification
const notifications = [];

module.exports = class Notification extends EventTarget {
  constructor(title, options) {
    super();

    if (!title) throw new Error('Title is required');

    Object.assign(this, {title}, options);

    options = options || {};
    options.id = options.id || uuid.v4();
    options.body = options.body || '';
    options.canReply = !!options.canReply;

    let activated = (isReply, response, id) => {
      const notification = this.getNotificationById(id);
      if (!notification) return;

      if (isReply) {
        notification.dispatchEvent({type: 'reply', response});
      } else {
        notification.dispatchEvent({type: 'click'});
      }
    };

    let args = Object.assign({title, activated}, options);
    this.notification = new MacNotification(args);
    notifications.push(this);
  }

  close() {
    let i = getNotificationIndexById(this.notification.id);
    if (i) notifications.splice(i, 1);

    this.notification.close();
    this.notification = null;

    this.dispatchEvent({type: 'close'});
  }

  getNotificationById(id) {
    return notifications.find((item) => (item.notification.id === id));
  }

  getNotificationIndexById(id) {
    return notifications.findIndex((item) => (item.notification.id === id));
  }
};<commit_msg>:wrench: Make removal more robust<commit_after>"use strict";

const uuid = require('node-uuid');
const EventTarget = require('event-target-shim');
const MacNotification = require('bindings')('Notification').MacNotification
const notifications = [];

module.exports = class Notification extends EventTarget {
  constructor(title, options) {
    super();

    if (!title) throw new Error('Title is required');

    Object.assign(this, {title}, options);

    options = options || {};
    options.id = options.id || uuid.v4();
    options.body = options.body || '';
    options.canReply = !!options.canReply;

    let activated = (isReply, response, id) => {
      const notification = this.getNotificationById(id);
      if (!notification) return;

      if (isReply) {
        notification.dispatchEvent({type: 'reply', response});
      } else {
        notification.dispatchEvent({type: 'click'});
      }
    };

    let args = Object.assign({title, activated}, options);
    this.notification = new MacNotification(args);
    notifications.push(this);
  }

  close() {
    if (notifications && notifications.length > 0) {
      let i = this.getNotificationIndexById(this.notification.id);
      if (i) notifications.splice(i, 1);
    }

    this.notification.close();
    this.notification = null;

    this.dispatchEvent({type: 'close'});
  }

  getNotificationById(id) {
    return notifications.find((item) => (item.notification.id === id));
  }

  getNotificationIndexById(id) {
    return notifications.findIndex((item) => (item.notification.id === id));
  }
};<|endoftext|>


<commit_before>'use strict';

const Hapi = require('hapi');
const nodemailer = require('nodemailer');

// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: '',
        pass: ''
    }
});

// Create a server with a host and port
const server = new Hapi.Server();
server.connection({
    host: '0.0.0.0',
    port: process.env.PORT || 8000
});

// Add the route
server.route({
    method: 'GET',
    path:'/send-email',
    handler: (request, reply)=> {
        console.log(sendEmail(request.query) )
        reply(200)
    }
});

server.route({
    method: 'GET',
    path:'/users',
    handler: (request, reply)=> {
        reply({
            name : 'manuel',
            lastname: 'otero'
        })
    }
});

// Start the server
server.start((err) => {

    if (err) {
        throw err;
    }
    console.log('Server running at:', server.info.uri);
});

const sendEmail = (params)=>{
    console.log("Prepearing Email")
    console.log(params)
    transporter.sendMail({
        from: params.from || 'customservice@hapi.com',
        to: params.to || '',
        subject: params.subject, // Subject line
        text: params.text,
        html: 'Hello world ?' // html body
    }, (error, info) => {
        if (error) {
            return error;
        }
        return info
    });
}
<commit_msg>deploy<commit_after>'use strict';

const Hapi = require('hapi');
const nodemailer = require('nodemailer');

// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: '',
        pass: ''
    }
});

// Create a server with a host and port
const server = new Hapi.Server();
server.connection({
    host: '0.0.0.0',
    port: process.env.PORT || 8000,
    routes : {
        cors : true
    }
});

// Add the route
server.route({
    method: 'GET',
    path:'/send-email',
    handler: (request, reply)=> {
        console.log(sendEmail(request.query) )
        reply(200)
    }
});

server.route({
    method: 'GET',
    path:'/users',
    handler: (request, reply)=> {
        reply({
            name : 'manuel',
            lastname: 'otero'
        })
    }
});

// Start the server
server.start((err) => {

    if (err) {
        throw err;
    }
    console.log('Server running at:', server.info.uri);
});

const sendEmail = (params)=>{
    console.log("Prepearing Email")
    console.log(params)
    transporter.sendMail({
        from: params.from || 'customservice@hapi.com',
        to: params.to || '',
        subject: params.subject, // Subject line
        text: params.text,
        html: 'Hello world ?' // html body
    }, (error, info) => {
        if (error) {
            return error;
        }
        return info
    });
}
<|endoftext|>


<commit_before>define([
  'angular',
  'bpmn-js',
  'text!./cam-tasklist-task-diagram.html'
], function(
  angular,
  Viewer,
  template
) {
  'use strict';
  var $ = angular.element;
  var $win = $(window);

  return [
    'camAPI',
  function(
    camAPI
  ) {
    var ProcessDefinition = camAPI.resource('process-definition');

    return {
      scope: {
        task: '='
      },

      template: template,

      link: function(scope, element) {
        var process;
        var viewer = new Viewer({
          container: element.find('.diagram-holder')
        });

        scope.loading = false;
        scope.rendering = false;

        function resizeContainer() {
          var height = $win.height();
          var top = element.offset().top + 50;

          if ((height + 400) > top) {
            element.height(height - top);
          }
          else {
            element.height(400);
          }
        }

        function renderDiagram() {
          if (!process._xml) { return; }
          viewer.importXML(process._xml.bpmn20Xml, function(err) {
            if (err) { throw err; }

            if (!element.width() || !viewer.diagram) { return; }
            resizeContainer();

            var canvas = viewer.get('canvas');
            canvas.addMarker(scope.task.taskDefinitionKey, 'highlight');
            canvas.zoom('fit-viewport');

            scope.rendering = false;
          });
        }

        scope.drawDiagram = function() {
          if (!process || !element.width()) { return; }
          if (!scope.$root.authentication) {
            throw new Error('Not authenticated');
          }

          scope.rendering = true;

          if (process._xml) {
            return renderDiagram();
          }

          scope.loading = true;
          ProcessDefinition.xml(process, function(err, xml) {
            scope.loading = false;
            if (err) { throw err; }

            process._xml = xml;

            renderDiagram();
          });
        };

        scope.$on('tasklist.task.tab', function(evt, tabName) {
          if (tabName === 'diagram') {
            scope.drawDiagram();
          }
        });

        $win.on('resize', renderDiagram);
        element.on('$destroy', function() {
          $win.off('resize', renderDiagram);
        });

        scope.$watch('task', function(newV, oldV) {
          process = scope.task._embedded.processDefinition[0];
          scope.drawDiagram();
        });
      }
    };
  }];
});
<commit_msg>impr(task diagram): laverage tasklist.task.tab event useage<commit_after>define([
  'angular',
  'bpmn-js',
  'text!./cam-tasklist-task-diagram.html'
], function(
  angular,
  Viewer,
  template
) {
  'use strict';
  var $ = angular.element;
  var $win = $(window);

  return [
    'camAPI',
  function(
    camAPI
  ) {
    var ProcessDefinition = camAPI.resource('process-definition');

    return {
      scope: {
        task: '='
      },

      template: template,

      link: function(scope, element) {
        var process;
        var viewer = new Viewer({
          container: element.find('.diagram-holder')
        });

        scope.loading = false;
        scope.rendering = false;

        function resizeContainer() {
          var height = $win.height();
          var top = element.offset().top + 50;

          if ((height + 400) > top) {
            element.height(height - top);
          }
          else {
            element.height(400);
          }
        }

        function renderDiagram() {
          if (!process._xml) { return; }
          viewer.importXML(process._xml.bpmn20Xml, function(err) {
            if (err) { throw err; }

            resizeContainer();

            var canvas = viewer.get('canvas');
            canvas.addMarker(scope.task.taskDefinitionKey, 'highlight');
            canvas.zoom('fit-viewport');

            scope.rendering = false;
          });
        }

        scope.drawDiagram = function() {
          if (!process) { return; }
          if (!scope.$root.authentication) {
            throw new Error('Not authenticated');
          }

          scope.rendering = true;

          if (process._xml) {
            return renderDiagram();
          }

          scope.loading = true;
          ProcessDefinition.xml(process, function(err, xml) {
            scope.loading = false;
            if (err) { throw err; }

            process._xml = xml;

            renderDiagram();
          });
        };

        scope.$on('tasklist.task.tab', function(evt, tabName) {
          if (tabName === 'diagram') {
            scope.drawDiagram();
          }
        });

        $win.on('resize', renderDiagram);
        element.on('$destroy', function() {
          $win.off('resize', renderDiagram);
        });

        scope.$watch('task', function(newV, oldV) {
          process = scope.task._embedded.processDefinition[0];
        });
      }
    };
  }];
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

const fs = require('fs');
const path = require('path');
const package_json = path.resolve('./package.json');
const tsconfig_json = path.resolve('./tsconfig.json');
const webpack_config_js = path.resolve('./webpack.config.js');
const karma_config_js = path.resolve('./karma.conf.js');
const git_ignore_file = path.resolve('./.gitignore');
const execSync = require('child_process').execSync;

// webpack 2.x
const webpack_config = `module.exports = {
  entry: './index.ts',
  output: {
    filename: './[name].js'
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js']
  },
  module: {
    rules: [
      { test: /\.tsx?$/, loader: 'ts-loader' }
    ]
  }
}`;

// karma config
const karma_config = `var webpackConfig = require('./webpack.config');
module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ["jasmine"],
    files: [
      { pattern: "tests/*.spec.*" }
    ],
    exclude: [
    ],
    preprocessors: {
      'tests/*.spec.*': ['webpack'],
    },
    webpack: webpackConfig,
    reporters: ["progress"],
    colors: true,
    logLevel: config.LOG_INFO,
    browsers: ['Chrome'],
    mime: {
      'text/x-typescript': ['ts','tsx']
    }
  })
}`;

const git_ignore = `
.DS_Store
node_modules
*.log
`;

if (!fs.existsSync(package_json)) {
  console.log('Initializing package.json');
  execSync('npm init -y');
}

console.log('Installing packages. This might take a couple minutes.');
execSync('npm install webpack webpack-dev-server ts-loader typescript --save-dev');
execSync('npm install @types/jasmine jasmine-core karma karma-jasmine karma-webpack karma-chrome-launcher --save-dev');

if (!fs.existsSync(tsconfig_json)) {
  console.log('Creating tsconfig.json');
  execSync('tsc --init');
}

const tsconfig = require(tsconfig_json);
if (!tsconfig.compilerOptions || ! tsconfig.compilerOptions.lib) {
  tsconfig["compilerOptions"]["lib"] = ["dom", "es2015.promise", "es5"];
}

console.log('Updating tsconfig.json');
fs.writeFileSync(
  tsconfig_json,
  JSON.stringify(tsconfig, null, 2)
);

RegExp.prototype.toJSON = RegExp.prototype.toString;
if (!fs.existsSync(webpack_config_js)) {
  console.log('Creating webpack.config.js');
  fs.writeFileSync(
    webpack_config_js,
    webpack_config
  );
}

if (!fs.existsSync(karma_config_js)) {
  console.log('Creating karma.conf.js');
  fs.writeFileSync(
    karma_config_js,
    karma_config
  );
}

console.log('Initializing git');
execSync('git init');

if (!fs.existsSync(git_ignore_file)) {
  console.log('Creating .gitignore');
  fs.writeFileSync(
    git_ignore_file,
    git_ignore
  );
}

console.log('Adding npm scripts');
const package_info = require(package_json);
if (!package_info.scripts || ! package_info.scripts['dev']) {
  package_info["scripts"]["dev"] = 'webpack-dev-server --inline --hot';
}
if (!package_info.scripts || ! package_info.scripts['build:prod']) {
  package_info["scripts"]["build"] = 'webpack -p';
}
if (package_info.scripts) {
  package_info["scripts"]["test"] = 'karma start';
}
fs.writeFileSync(
  package_json,
  JSON.stringify(package_info, null, 2)
);<commit_msg>Fix #1: Remove comments from tsc config<commit_after>#!/usr/bin/env node

'use strict';

const fs = require('fs');
const path = require('path');
const package_json = path.resolve('./package.json');
const tsconfig_json = path.resolve('./tsconfig.json');
const webpack_config_js = path.resolve('./webpack.config.js');
const karma_config_js = path.resolve('./karma.conf.js');
const git_ignore_file = path.resolve('./.gitignore');
const execSync = require('child_process').execSync;

// webpack 2.x
const webpack_config = `module.exports = {
  entry: './index.ts',
  output: {
    filename: './[name].js'
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js']
  },
  module: {
    rules: [
      { test: /\.tsx?$/, loader: 'ts-loader' }
    ]
  }
}`;

// karma config
const karma_config = `var webpackConfig = require('./webpack.config');
module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ["jasmine"],
    files: [
      { pattern: "tests/*.spec.*" }
    ],
    exclude: [
    ],
    preprocessors: {
      'tests/*.spec.*': ['webpack'],
    },
    webpack: webpackConfig,
    reporters: ["progress"],
    colors: true,
    logLevel: config.LOG_INFO,
    browsers: ['Chrome'],
    mime: {
      'text/x-typescript': ['ts','tsx']
    }
  })
}`;

const git_ignore = `
.DS_Store
node_modules
*.log
`;

if (!fs.existsSync(package_json)) {
  console.log('Initializing package.json');
  execSync('npm init -y');
}

console.log('Installing packages. This might take a couple minutes.');
execSync('npm install webpack webpack-dev-server ts-loader typescript --save-dev');
execSync('npm install @types/jasmine jasmine-core karma karma-jasmine karma-webpack karma-chrome-launcher --save-dev');

if (!fs.existsSync(tsconfig_json)) {
  console.log('Creating tsconfig.json');
  execSync('tsc --init');
}

let tsconfig_raw = fs.readFileSync(tsconfig_json, 'utf8');
tsconfig_raw = tsconfig_raw.replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/igm, '');
const tsconfig = JSON.parse(tsconfig_raw);

if (!tsconfig.compilerOptions || ! tsconfig.compilerOptions.lib) {
  tsconfig["compilerOptions"]["lib"] = ["dom", "es2015.promise", "es5"];
}

console.log('Updating tsconfig.json');
fs.writeFileSync(
  tsconfig_json,
  JSON.stringify(tsconfig, null, 2)
);

RegExp.prototype.toJSON = RegExp.prototype.toString;
if (!fs.existsSync(webpack_config_js)) {
  console.log('Creating webpack.config.js');
  fs.writeFileSync(
    webpack_config_js,
    webpack_config
  );
}

if (!fs.existsSync(karma_config_js)) {
  console.log('Creating karma.conf.js');
  fs.writeFileSync(
    karma_config_js,
    karma_config
  );
}

console.log('Initializing git');
execSync('git init');

if (!fs.existsSync(git_ignore_file)) {
  console.log('Creating .gitignore');
  fs.writeFileSync(
    git_ignore_file,
    git_ignore
  );
}

console.log('Adding npm scripts');
const package_info = require(package_json);
if (!package_info.scripts || ! package_info.scripts['dev']) {
  package_info["scripts"]["dev"] = 'webpack-dev-server --inline --hot';
}
if (!package_info.scripts || ! package_info.scripts['build:prod']) {
  package_info["scripts"]["build"] = 'webpack -p';
}
if (package_info.scripts) {
  package_info["scripts"]["test"] = 'karma start';
}
fs.writeFileSync(
  package_json,
  JSON.stringify(package_info, null, 2)
);<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { Image, TouchableOpacity, ImageBackground } from 'react-native';
import resolveAssetSource from 'react-native/Libraries/Image/resolveAssetSource';

export default class ScalableImage extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            size: {
                width: null,
                height: null,
            }
        };

        this.mounted = false;
    }

    componentDidMount() {
        this.mounted = true;
        this.onProps(this.props);
    }

    componentWillUnmount() {
        this.mounted = false;
    }

    componentWillReceiveProps(nextProps) {
        this.onProps(nextProps);
    }

    onProps(props) {
        if (props.source.uri) {
            const source = props.source.uri ? props.source.uri : props.source;
            Image.getSize(source, (width, height) => this.adjustSize(width, height, props), console.log);
        }
        else {
            const source = resolveAssetSource(props.source);
            this.adjustSize(source.width, source.height, props);
        }
    }

    adjustSize(sourceWidth, sourceHeight, props) {
        const { width, height, maxWidth, maxHeight } = props;

        let ratio = 1;

        if (width && height) {
            ratio = Math.min(width / sourceWidth, height / sourceHeight);
        }
        else if (width) {
            ratio = width / sourceWidth;
        }
        else if (height) {
            ratio = height / sourceHeight;
        }

        // Deprecated stuff. Added the PR by mistake. You should use only width and height props
        if (maxWidth && sourceWidth * ratio > maxWidth) {
            ratio = maxWidth / sourceWidth;
        }

        if (maxHeight && sourceHeight * ratio > maxHeight) {
            ratio = maxHeight / sourceHeight;
        }

        if (this.mounted) {
            this.setState({
                size: {
                    width: sourceWidth * ratio,
                    height: sourceHeight * ratio
                }
            }, () => this.props.onSize(this.state.size));
        }
    }

    render() {
        const ImageComponent = this.props.background
            ? ImageBackground
            : Image;

        const image = <ImageComponent { ...this.props } style={[this.props.style, this.state.size]}/>;

        if (!this.props.onPress) {
            return image;
        }

        return (
            <TouchableOpacity onPress={this.props.onPress}>
                {image}
            </TouchableOpacity>
        );
    }
}

ScalableImage.propTypes = {
    width: PropTypes.number,
    height: PropTypes.number,
    onPress: PropTypes.func,
    onSize: PropTypes.func,
    background: PropTypes.bool,
};

ScalableImage.defaultProps = {
    background: false,
    onSize: size => {}
};
<commit_msg>Updated import of resolveAssetSource (#14)<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { Image, TouchableOpacity, ImageBackground } from 'react-native';
const resolveAssetSource = Image.resolveAssetSource;

export default class ScalableImage extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            size: {
                width: null,
                height: null,
            }
        };

        this.mounted = false;
    }

    componentDidMount() {
        this.mounted = true;
        this.onProps(this.props);
    }

    componentWillUnmount() {
        this.mounted = false;
    }

    componentWillReceiveProps(nextProps) {
        this.onProps(nextProps);
    }

    onProps(props) {
        if (props.source.uri) {
            const source = props.source.uri ? props.source.uri : props.source;
            Image.getSize(source, (width, height) => this.adjustSize(width, height, props), console.log);
        }
        else {
            const source = resolveAssetSource(props.source);
            this.adjustSize(source.width, source.height, props);
        }
    }

    adjustSize(sourceWidth, sourceHeight, props) {
        const { width, height, maxWidth, maxHeight } = props;

        let ratio = 1;

        if (width && height) {
            ratio = Math.min(width / sourceWidth, height / sourceHeight);
        }
        else if (width) {
            ratio = width / sourceWidth;
        }
        else if (height) {
            ratio = height / sourceHeight;
        }

        // Deprecated stuff. Added the PR by mistake. You should use only width and height props
        if (maxWidth && sourceWidth * ratio > maxWidth) {
            ratio = maxWidth / sourceWidth;
        }

        if (maxHeight && sourceHeight * ratio > maxHeight) {
            ratio = maxHeight / sourceHeight;
        }

        if (this.mounted) {
            this.setState({
                size: {
                    width: sourceWidth * ratio,
                    height: sourceHeight * ratio
                }
            }, () => this.props.onSize(this.state.size));
        }
    }

    render() {
        const ImageComponent = this.props.background
            ? ImageBackground
            : Image;

        const image = <ImageComponent { ...this.props } style={[this.props.style, this.state.size]}/>;

        if (!this.props.onPress) {
            return image;
        }

        return (
            <TouchableOpacity onPress={this.props.onPress}>
                {image}
            </TouchableOpacity>
        );
    }
}

ScalableImage.propTypes = {
    width: PropTypes.number,
    height: PropTypes.number,
    onPress: PropTypes.func,
    onSize: PropTypes.func,
    background: PropTypes.bool,
};

ScalableImage.defaultProps = {
    background: false,
    onSize: size => {}
};
<|endoftext|>


<commit_before>var suggestions = [
  [/behaviour/i,    'behavior'],
  [/centre/i,       'center'],
  [/chequed/i,      'checked'],
  [/cheque(?!d)/i,  'check'],
  [/colour/i,       'color'],
  [/dialogue/i,     'dialog'],
  [/eh/i,           'em'],
  [/grey/i,         'gray'],
  [/loonie/i,       '100px'],
  [/poutine/i,      'padding'],
  [/queue/i,        'line'],
  [/rotateZed/i,    'rotateZ'],
  [/scaleZed/i,     'scaleZ'],
  [/toonie/i,       '200px'],
  [/toque/i,        'border-top'],
  [/translateZed/i, 'translateZ'],
  [/zed-index/i,    'z-index'],
  [/ +for sure$/i,   ' !important'],
  [/ +please$/i,     ' !important'],
  [/ +sorry$/i,     ' !important']
];

var transform = function(string) {
  suggestions.forEach(function(pair) {
    string = string.replace(pair[0], pair[1]);
  });
  return string;
};

module.exports = function(ast, reworkInstance) {
  ast.rules.forEach(function (rule) {
    if (rule.type != 'rule') return;

    rule.selectors = rule.selectors.map(transform);

    rule.declarations.forEach(function (declaration, index) {
      declaration.property = transform(declaration.property);
      declaration.value = transform(declaration.value);
    });
  });
};
<commit_msg>fix whitespace<commit_after>var suggestions = [
  [/behaviour/i,    'behavior'],
  [/centre/i,       'center'],
  [/chequed/i,      'checked'],
  [/cheque(?!d)/i,  'check'],
  [/colour/i,       'color'],
  [/dialogue/i,     'dialog'],
  [/eh/i,           'em'],
  [/grey/i,         'gray'],
  [/loonie/i,       '100px'],
  [/poutine/i,      'padding'],
  [/queue/i,        'line'],
  [/rotateZed/i,    'rotateZ'],
  [/scaleZed/i,     'scaleZ'],
  [/toonie/i,       '200px'],
  [/toque/i,        'border-top'],
  [/translateZed/i, 'translateZ'],
  [/zed-index/i,    'z-index'],
  [/ +for sure$/i,  ' !important'],
  [/ +please$/i,    ' !important'],
  [/ +sorry$/i,     ' !important']
];

var transform = function(string) {
  suggestions.forEach(function(pair) {
    string = string.replace(pair[0], pair[1]);
  });
  return string;
};

module.exports = function(ast, reworkInstance) {
  ast.rules.forEach(function (rule) {
    if (rule.type != 'rule') return;

    rule.selectors = rule.selectors.map(transform);

    rule.declarations.forEach(function (declaration, index) {
      declaration.property = transform(declaration.property);
      declaration.value = transform(declaration.value);
    });
  });
};
<|endoftext|>