<commit_before>;(function() {
  sig.reset = reset
  sig.push = push
  sig.receive = receive
  sig.watch = watch
  sig.unwatch = unwatch
  sig.pause = pause
  sig.resume = resume
  sig.map = map
  sig.filter = filter
  sig.limit = limit
  sig.once = once
  sig.then = then
  sig.isSig = isSig
  sig.spread = spread
  sig.depend = depend
  sig.undepend = undepend

  function sig(receiver) {
    return {
      type: 'sig',
      paused: true,
      buffer: [],
      sources: [],
      targets: [],
      dependants: [],
      receiver: receiver || noop
    }
  }

  function reset(s) {
    s.sources.forEach(function(source) { untarget(s, source) })
    s.targets.forEach(function(target) { unsource(target, s) })
    s.dependants.forEach(reset)
    s.sources = []
    s.targets = []
    s.dependants = []
    return s
  }

  function watch(t, s) {
    unwatch(t, s)
    s.targets.push(t)
    t.sources.push(s)
    return t
  }

  function depend(t, s) {
    undepend(t, s)
    s.dependants.push(t)
    return t
  }

  function undepend(t, s) {
    rm(s.dependants, t)
    return t
  }

  function untarget(t, s) {
    rm(s.targets, t)
    return t
  }

  function unsource(t, s) {
    rm(t.sources, s)
    return t
  }

  function unwatch(t, s) {
    unsource(t, s)
    untarget(t, s)
    return t
  }

  function push(s, x) {
    if (s.paused) return buffer(s, x)

    return s.paused
      ? buffer(s, x)
      : send(s, x)
  }

  function receive(s, x) {
    s.receiver(x, s)
    return s
  }

  function pause(s) {
    s.paused = true
  }

  function resume(s) {
    s.paused = false
    flush(s)
  }

  function flush(s) {
    var buffer = s.buffer
    var i = -1
    var n = buffer.length
    while (++i < n) send(s, buffer[i])
    s.buffer = []
  }

  function send(s, x) {
    var targets = s.targets
    var i = -1
    var n = targets.length
    while (++i < n) receive(targets[i], x)
    return s
  }

  function buffer(s, x) {
    s.buffer.push(x)
    return s
  }

  function map(s, fn) {
    var t = sig(mapper(fn))
    watch(t, s)
    resume(s)
    return t
  }

  function filter(s, fn) {
    var t = sig(filterer(fn))
    watch(t, s)
    resume(s)
    return t
  }

  function limit(s, n) {
    var t = sig(limiter(n))
    watch(t, s)
    resume(s)
    return t
  }

  function once(s) {
    return limit(s, 1)
  }

  function then(s, fn) {
    return map(once(s), fn)
  }

  function isSig(s) {
    return (s || 0).type == 'sig'
  }

  function spread(fn) {
    return function(values) {
      var args = arguments.length > 1
        ? values.concat(Array.prototype.slice.call(arguments, 1))
        : values
      return fn.apply(fn, args)
    }
  }

  function mapper(fn) {
    return function(x, t) {
      push(t, fn(x, t))
    }
  }

  function filterer(fn) {
    return function(x, t) {
      if (fn(x, t)) push(t, x)
    }
  }

  function limiter(n) {
    i = 0

    return function(x, t) {
      if (++i > n) reset(t)
      else push(t, x)
    }
  }

  function rm(arr, x) {
    var i = arr.indexOf(x)
    if (i < 0) return
    arr.splice(i, 1)
  }

  function noop() {}

  if (typeof module != 'undefined')
    module.exports = sig
  else if (typeof define == 'function' && define.amd)
    define(function() { return sig })
  else
    this.sig = sig
}).call(this);
<commit_msg>fix global leak<commit_after>;(function() {
  sig.reset = reset
  sig.push = push
  sig.receive = receive
  sig.watch = watch
  sig.unwatch = unwatch
  sig.pause = pause
  sig.resume = resume
  sig.map = map
  sig.filter = filter
  sig.limit = limit
  sig.once = once
  sig.then = then
  sig.isSig = isSig
  sig.spread = spread
  sig.depend = depend
  sig.undepend = undepend

  function sig(receiver) {
    return {
      type: 'sig',
      paused: true,
      buffer: [],
      sources: [],
      targets: [],
      dependants: [],
      receiver: receiver || noop
    }
  }

  function reset(s) {
    s.sources.forEach(function(source) { untarget(s, source) })
    s.targets.forEach(function(target) { unsource(target, s) })
    s.dependants.forEach(reset)
    s.sources = []
    s.targets = []
    s.dependants = []
    return s
  }

  function watch(t, s) {
    unwatch(t, s)
    s.targets.push(t)
    t.sources.push(s)
    return t
  }

  function depend(t, s) {
    undepend(t, s)
    s.dependants.push(t)
    return t
  }

  function undepend(t, s) {
    rm(s.dependants, t)
    return t
  }

  function untarget(t, s) {
    rm(s.targets, t)
    return t
  }

  function unsource(t, s) {
    rm(t.sources, s)
    return t
  }

  function unwatch(t, s) {
    unsource(t, s)
    untarget(t, s)
    return t
  }

  function push(s, x) {
    if (s.paused) return buffer(s, x)

    return s.paused
      ? buffer(s, x)
      : send(s, x)
  }

  function receive(s, x) {
    s.receiver(x, s)
    return s
  }

  function pause(s) {
    s.paused = true
  }

  function resume(s) {
    s.paused = false
    flush(s)
  }

  function flush(s) {
    var buffer = s.buffer
    var i = -1
    var n = buffer.length
    while (++i < n) send(s, buffer[i])
    s.buffer = []
  }

  function send(s, x) {
    var targets = s.targets
    var i = -1
    var n = targets.length
    while (++i < n) receive(targets[i], x)
    return s
  }

  function buffer(s, x) {
    s.buffer.push(x)
    return s
  }

  function map(s, fn) {
    var t = sig(mapper(fn))
    watch(t, s)
    resume(s)
    return t
  }

  function filter(s, fn) {
    var t = sig(filterer(fn))
    watch(t, s)
    resume(s)
    return t
  }

  function limit(s, n) {
    var t = sig(limiter(n))
    watch(t, s)
    resume(s)
    return t
  }

  function once(s) {
    return limit(s, 1)
  }

  function then(s, fn) {
    return map(once(s), fn)
  }

  function isSig(s) {
    return (s || 0).type == 'sig'
  }

  function spread(fn) {
    return function(values) {
      var args = arguments.length > 1
        ? values.concat(Array.prototype.slice.call(arguments, 1))
        : values
      return fn.apply(fn, args)
    }
  }

  function mapper(fn) {
    return function(x, t) {
      push(t, fn(x, t))
    }
  }

  function filterer(fn) {
    return function(x, t) {
      if (fn(x, t)) push(t, x)
    }
  }

  function limiter(n) {
    var i = 0

    return function(x, t) {
      if (++i > n) reset(t)
      else push(t, x)
    }
  }

  function rm(arr, x) {
    var i = arr.indexOf(x)
    if (i < 0) return
    arr.splice(i, 1)
  }

  function noop() {}

  if (typeof module != 'undefined')
    module.exports = sig
  else if (typeof define == 'function' && define.amd)
    define(function() { return sig })
  else
    this.sig = sig
}).call(this);
<|endoftext|>


<commit_before>//
//  react-native-udp
//
//  Created by Mark Vayngrib on 05/10/15.
//  Copyright (c) 2015 Tradle, Inc. All rights reserved.
//

/**
 * @providesModule UdpSocket
 * @flow
 */

'use strict';

var React = require('react-native')
var mixInEventEmitter = require('mixInEventEmitter')
var DeviceEventEmitter = require('RCTDeviceEventEmitter')
var Sockets = require('NativeModules').UdpSockets
var base64 = require('base64-js')
var noop = function () {}
var instances = 0
var STATE = {
  UNBOUND: 0,
  BINDING: 1,
  BOUND: 2
}

function UdpSocket(type) {
  this._id = instances++
  this._state = STATE.UNBOUND
  this._subscription = DeviceEventEmitter.addListener(
    'udp-' + this._id + '-data', this._onReceive.bind(this)
  );

  // ensure compatibility with node's EventEmitter
  if (!this.on) this.on = this.addListener.bind(this)

  Sockets.createSocket(this._id, {
    type: type || 'udp4'
  }) // later
}

UdpSocket.prototype._debug = function() {
  // for now
  var args = [].slice.call(arguments)
  args.unshift('socket-' + this._id)
  console.log.apply(null, args)
}

UdpSocket.prototype.bind = function(port, address, callback) {
  var self = this

  if (this._state !== STATE.UNBOUND) throw new Error('Socket is already bound')

  if (typeof address === 'function') {
    callback = address
    address = undefined
  }

  if (!address) address = '0.0.0.0'

  if (!port) port = 0

  if (callback) this.once('listening', callback.bind(this))

  this._state = STATE.BINDING
  this._debug('binding, address:', address, 'port:', port)
  Sockets.bind(this._id, port, address, function(err, addr) {
    if (err) {
      // questionable: may want to self-destruct and
      // force user to create a new socket
      self._state = STATE.UNBOUND
      self._debug('failed to bind', err)
      return self.emit('error', err)
    }

    self._debug('bound to address:', addr.address, 'port:', addr.port)
    self._address = addr.address
    self._port = addr.port
    self._state = STATE.BOUND
    self.emit('listening')
  })
}

UdpSocket.prototype.close = function() {
  if (this._destroyed) return

  this._destroyed = true
  this._debug('closing')
  this._subscription.remove();

  Sockets.close(this._id, this._debug.bind(this, 'closed'))
  this.emit('close')
}

UdpSocket.prototype._onReceive = function(info) {
  this._debug('received', info)

  // from base64 string
  var buf = base64.toByteArray(info.data)
  var rinfo = {
    address: info.address,
    port: info.port,
    family: 'IPv4', // not necessarily
    size: buf.length
  }

  if (typeof Buffer !== 'undefined') buf = new Buffer(buf, 'binary')

  this.emit('message', buf, rinfo)
}

/**
 * socket.send(buf, offset, length, port, address, [callback])
 *
 * For UDP sockets, the destination port and IP address must be
 * specified. A string may be supplied for the address parameter, and it will
 * be resolved with DNS. An optional callback may be specified to detect any
 * DNS errors and when buf may be re-used. Note that DNS lookups will delay
 * the time that a send takes place, at least until the next tick. The only
 * way to know for sure that a send has taken place is to use the callback.
 *
 * If the socket has not been previously bound with a call to bind, it's
 * assigned a random port number and bound to the "all interfaces" address
 * (0.0.0.0 for udp4 sockets, ::0 for udp6 sockets).
 *
 * @param {Array|string} message to be sent
 * @param {number} offset Offset in the buffer where the message starts.
 * @param {number} length Number of bytes in the message.
 * @param {number} port destination port
 * @param {string} address destination IP
 * @param {function} callback Callback when message is done being delivered.
 *                            Optional.
 */
// UdpSocket.prototype.send = function (buf, host, port, cb) {
UdpSocket.prototype.send = function(buffer, offset, length, port, address, callback) {
  var self = this

  if (offset !== 0) throw new Error('Non-zero offset not supported yet')

  if (this._state === STATE.UNBOUND) {
    var args = [].slice.call(arguments)
    return this.bind(0, function(err) {
      if (err) return callback(err)

      self.send.apply(self, args)
    })
  }
  else if (this._state === STATE.BINDING) {
    // we're ok, GCDAsync(Udp)Socket handles queueing internally
  }

  callback = callback || noop
  var str
  if (typeof buffer === 'string') {
    console.warn('socket.send(): interpreting as base64')
    str = buffer
  }
  else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(buffer)) {
    str = buffer.toString('base64')
  }
  else if (buffer instanceof Uint8Array || Array.isArray(buffer)) {
    str = base64.fromByteArray(buffer)
  }
  else {
    throw new Error('invalid message format')
  }

  self._debug('sending', buffer, str)
  Sockets.send(this._id, str, +port, address, function(err) {
    if (err) {
      self._debug('send failed', err)
      return callback(err)
    }

    self._debug('sent')
    callback()
  })
}

UdpSocket.prototype.address = function() {
  if (this._state !== STATE.BOUND) {
    throw new Error('socket is not bound yet')
  }

  return {
    address: this._address,
    port: this._port,
    family: 'IPv4'
  }
}

UdpSocket.prototype.setBroadcast = function(flag) {
  // nothing yet
}

UdpSocket.prototype.setTTL = function(ttl) {
  // nothing yet
}

UdpSocket.prototype.setMulticastTTL = function(ttl, callback) {
  // nothing yet
}

UdpSocket.prototype.setMulticastLoopback = function(flag, callback) {
  // nothing yet
}

UdpSocket.prototype.addMembership = function(multicastAddress, multicastInterface, callback) {
  // nothing yet
}

UdpSocket.prototype.dropMembership = function(multicastAddress, multicastInterface, callback) {
  // nothing yet
}

UdpSocket.prototype.ref = function() {
  // anything?
}

UdpSocket.prototype.unref = function() {
  // anything?
}

mixInEventEmitter(UdpSocket, {
  'listening': true,
  'message': true,
  'close': true,
  'error': true
})

module.exports = UdpSocket<commit_msg>fix logging<commit_after>//
//  react-native-udp
//
//  Created by Mark Vayngrib on 05/10/15.
//  Copyright (c) 2015 Tradle, Inc. All rights reserved.
//

/**
 * @providesModule UdpSocket
 * @flow
 */

'use strict';

var React = require('react-native')
var mixInEventEmitter = require('mixInEventEmitter')
var DeviceEventEmitter = require('RCTDeviceEventEmitter')
var Sockets = require('NativeModules').UdpSockets
var base64 = require('base64-js')
var noop = function () {}
var instances = 0
var STATE = {
  UNBOUND: 0,
  BINDING: 1,
  BOUND: 2
}

function UdpSocket(type) {
  this._id = instances++
  this._state = STATE.UNBOUND
  this._subscription = DeviceEventEmitter.addListener(
    'udp-' + this._id + '-data', this._onReceive.bind(this)
  );

  // ensure compatibility with node's EventEmitter
  if (!this.on) this.on = this.addListener.bind(this)

  Sockets.createSocket(this._id, {
    type: type || 'udp4'
  }) // later
}

UdpSocket.prototype._debug = function() {
  // for now
  var args = [].slice.call(arguments)
  args.unshift('socket-' + this._id)
  console.log.apply(console, args)
}

UdpSocket.prototype.bind = function(port, address, callback) {
  var self = this

  if (this._state !== STATE.UNBOUND) throw new Error('Socket is already bound')

  if (typeof address === 'function') {
    callback = address
    address = undefined
  }

  if (!address) address = '0.0.0.0'

  if (!port) port = 0

  if (callback) this.once('listening', callback.bind(this))

  this._state = STATE.BINDING
  this._debug('binding, address:', address, 'port:', port)
  Sockets.bind(this._id, port, address, function(err, addr) {
    if (err) {
      // questionable: may want to self-destruct and
      // force user to create a new socket
      self._state = STATE.UNBOUND
      self._debug('failed to bind', err)
      return self.emit('error', err)
    }

    self._debug('bound to address:', addr.address, 'port:', addr.port)
    self._address = addr.address
    self._port = addr.port
    self._state = STATE.BOUND
    self.emit('listening')
  })
}

UdpSocket.prototype.close = function() {
  if (this._destroyed) return

  this._destroyed = true
  this._debug('closing')
  this._subscription.remove();

  Sockets.close(this._id, this._debug.bind(this, 'closed'))
  this.emit('close')
}

UdpSocket.prototype._onReceive = function(info) {
  this._debug('received', info)

  // from base64 string
  var buf = base64.toByteArray(info.data)
  var rinfo = {
    address: info.address,
    port: info.port,
    family: 'IPv4', // not necessarily
    size: buf.length
  }

  if (typeof Buffer !== 'undefined') buf = new Buffer(buf, 'binary')

  this.emit('message', buf, rinfo)
}

/**
 * socket.send(buf, offset, length, port, address, [callback])
 *
 * For UDP sockets, the destination port and IP address must be
 * specified. A string may be supplied for the address parameter, and it will
 * be resolved with DNS. An optional callback may be specified to detect any
 * DNS errors and when buf may be re-used. Note that DNS lookups will delay
 * the time that a send takes place, at least until the next tick. The only
 * way to know for sure that a send has taken place is to use the callback.
 *
 * If the socket has not been previously bound with a call to bind, it's
 * assigned a random port number and bound to the "all interfaces" address
 * (0.0.0.0 for udp4 sockets, ::0 for udp6 sockets).
 *
 * @param {Array|string} message to be sent
 * @param {number} offset Offset in the buffer where the message starts.
 * @param {number} length Number of bytes in the message.
 * @param {number} port destination port
 * @param {string} address destination IP
 * @param {function} callback Callback when message is done being delivered.
 *                            Optional.
 */
// UdpSocket.prototype.send = function (buf, host, port, cb) {
UdpSocket.prototype.send = function(buffer, offset, length, port, address, callback) {
  var self = this

  if (offset !== 0) throw new Error('Non-zero offset not supported yet')

  if (this._state === STATE.UNBOUND) {
    var args = [].slice.call(arguments)
    return this.bind(0, function(err) {
      if (err) return callback(err)

      self.send.apply(self, args)
    })
  }
  else if (this._state === STATE.BINDING) {
    // we're ok, GCDAsync(Udp)Socket handles queueing internally
  }

  callback = callback || noop
  var str
  if (typeof buffer === 'string') {
    console.warn('socket.send(): interpreting as base64')
    str = buffer
  }
  else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(buffer)) {
    str = buffer.toString('base64')
  }
  else if (buffer instanceof Uint8Array || Array.isArray(buffer)) {
    str = base64.fromByteArray(buffer)
  }
  else {
    throw new Error('invalid message format')
  }

  self._debug('sending', buffer, str)
  Sockets.send(this._id, str, +port, address, function(err) {
    if (err) {
      self._debug('send failed', err)
      return callback(err)
    }

    self._debug('sent')
    callback()
  })
}

UdpSocket.prototype.address = function() {
  if (this._state !== STATE.BOUND) {
    throw new Error('socket is not bound yet')
  }

  return {
    address: this._address,
    port: this._port,
    family: 'IPv4'
  }
}

UdpSocket.prototype.setBroadcast = function(flag) {
  // nothing yet
}

UdpSocket.prototype.setTTL = function(ttl) {
  // nothing yet
}

UdpSocket.prototype.setMulticastTTL = function(ttl, callback) {
  // nothing yet
}

UdpSocket.prototype.setMulticastLoopback = function(flag, callback) {
  // nothing yet
}

UdpSocket.prototype.addMembership = function(multicastAddress, multicastInterface, callback) {
  // nothing yet
}

UdpSocket.prototype.dropMembership = function(multicastAddress, multicastInterface, callback) {
  // nothing yet
}

UdpSocket.prototype.ref = function() {
  // anything?
}

UdpSocket.prototype.unref = function() {
  // anything?
}

mixInEventEmitter(UdpSocket, {
  'listening': true,
  'message': true,
  'close': true,
  'error': true
})

module.exports = UdpSocket<|endoftext|>


<commit_before>const should = require('should');
const expect = require('expect');

describe('Just a test', () => {
  it('to pass', () => {
    expect(true).toEqual(true);
  });
});
<commit_msg>bug(houndci): fix houndci violations Finishes #139196531<commit_after>/* eslint import/no-unresolved: 0 */
const should = require('should');
const expect = require('expect');

describe('Just a test', () => {
  it('to pass', () => {
    expect(true).toEqual(true);
  });
});
<|endoftext|>


<commit_before>var Price = (function () {
    'use strict';

    var createProposal = function (typeOfContract) {
        var proposal = {proposal: 1}, underlying = document.getElementById('underlying'),
            submarket = document.getElementById('submarket'),
            contractType = typeOfContract,
            amountType = document.getElementById('amount_type'),
            currency = document.getElementById('currency'),
            payout = document.getElementById('amount'),
            startTime = document.getElementById('date_start'),
            expiryType = document.getElementById('expiry_type'),
            duration = document.getElementById('duration_amount'),
            durationUnit = document.getElementById('duration_units'),
            endDate = document.getElementById('expiry_date'),
            endTime = document.getElementById('expiry_time'),
            highBarrier = document.getElementById('barrier'),
            lowBarrier = document.getElementById('barrier1');

        if (payout) {
            proposal['amount_val'] = payout.value;
        }
        if (amountType) {
            proposal['basis'] = amountType.value;
        }
        if (contractType) {
            proposal['contract_type'] = typeOfContract;
        }
        if (currency) {
            proposal['currency'] = currency.value;
        }
        if (underlying) {
            proposal['symbol'] = underlying.value;
        }

        if (startTime && startTime.value != 'now') {
            proposal['date_start'] = startTime.value;
        }

        if (expiryType && expiryType.value == 'duration') {
            proposal['duration'] = duration.value;
            proposal['duration_unit'] = durationUnit.value;
        } else if (expiryType && expiryType.value == 'endtime') {
            proposal['date_expiry'] = moment.utc(endDate.value + " " + endtime.value).unix();
        }

        if (highBarrier && highBarrier.value) {
            proposal['barrier'] = highBarrier.value;
        }
        if (lowBarrier && lowBarrier.value) {
            proposal['barrier2'] = lowBarrier.value;
        }

        return proposal;
    };

    var display = function (details, contractType, spotElement) {
        var type = details.request['data']['contract_type'],
            position = contractTypeDisplayMapping(type),
            display = contractType[type],
            container = document.getElementById('price_container_' + position),
            h4 = document.createElement('h4'),
            row = document.createElement('div'),
            description = row.cloneNode(),
            fragment = document.createDocumentFragment();

        while (container && container.firstChild) {
            container.removeChild(container.firstChild);
        }

        h4.setAttribute('class', 'contract_heading ' + display);
        h4.setAttribute('id', 'contract_heading_' + position);

        description.setAttribute('class', 'contract_description big-col');
        description.setAttribute('id', 'contract_description_' + position);
        row.setAttribute('class', 'row');

        var content = document.createTextNode(display);
        h4.appendChild(content);
        fragment.appendChild(h4);

        if (details['error']) {
            content = document.createTextNode(details['error']);
            description.appendChild(content);
            row.appendChild(description);
            fragment.appendChild(row);
        } else {
            var amount = document.createElement('div'),
                purchase = row.cloneNode(),
                button = document.createElement('button');

            amount.setAttribute('class', 'contract_amount col');
            amount.setAttribute('id', 'contract_amount_' + position);

            purchase.setAttribute('class', 'contract_purchase');
            purchase.setAttribute('id', 'contract_purchase_' + position);
            button.setAttribute('class', 'purchase_button');
            button.setAttribute('value', 'purchase');

            content = document.createTextNode(details['ask_price']);
            amount.appendChild(content);

            content = document.createTextNode(details['longcode']);
            description.appendChild(content);

            row.appendChild(amount);
            row.appendChild(description);

            content = document.createTextNode('Purchase');
            button.appendChild(content);
            purchase.appendChild(button);

            fragment.appendChild(row);
            fragment.appendChild(purchase);

            spotElement.textContent = details['spot'];

        }
        container.appendChild(fragment);
    };

    return {
        proposal: createProposal,
        display: display,
    };

})();
<commit_msg>don't add purchase button through javascript, store price id<commit_after>var Price = (function () {
    'use strict';

    var createProposal = function (typeOfContract) {
        var proposal = {proposal: 1}, underlying = document.getElementById('underlying'),
            submarket = document.getElementById('submarket'),
            contractType = typeOfContract,
            amountType = document.getElementById('amount_type'),
            currency = document.getElementById('currency'),
            payout = document.getElementById('amount'),
            startTime = document.getElementById('date_start'),
            expiryType = document.getElementById('expiry_type'),
            duration = document.getElementById('duration_amount'),
            durationUnit = document.getElementById('duration_units'),
            endDate = document.getElementById('expiry_date'),
            endTime = document.getElementById('expiry_time'),
            highBarrier = document.getElementById('barrier'),
            lowBarrier = document.getElementById('barrier1');

        if (payout) {
            proposal['amount_val'] = payout.value;
        }
        if (amountType) {
            proposal['basis'] = amountType.value;
        }
        if (contractType) {
            proposal['contract_type'] = typeOfContract;
        }
        if (currency) {
            proposal['currency'] = currency.value;
        }
        if (underlying) {
            proposal['symbol'] = underlying.value;
        }

        if (startTime && startTime.value != 'now') {
            proposal['date_start'] = startTime.value;
        }

        if (expiryType && expiryType.value == 'duration') {
            proposal['duration'] = duration.value;
            proposal['duration_unit'] = durationUnit.value;
        } else if (expiryType && expiryType.value == 'endtime') {
            proposal['date_expiry'] = moment.utc(endDate.value + " " + endtime.value).unix();
        }

        if (highBarrier && highBarrier.value) {
            proposal['barrier'] = highBarrier.value;
        }
        if (lowBarrier && lowBarrier.value) {
            proposal['barrier2'] = lowBarrier.value;
        }

        return proposal;
    };

    var display = function (details, contractType, spotElement) {
        var type = details.request['data']['contract_type'],
            position = contractTypeDisplayMapping(type),
            display = contractType[type],
            container = document.getElementById('price_container_' + position),
            description_container = document.getElementById('description_container_' + position),
            currency = document.getElementById('currency'),
            purchase = document.getElementById('contract_purchase_' + position),
            h4 = document.createElement('h4'),
            row = document.createElement('div'),
            description = row.cloneNode(),
            priceId = document.createElement('input'),
            fragment = document.createDocumentFragment();

        while (description_container && description_container.firstChild) {
            description_container.removeChild(description_container.firstChild);
        }

        h4.setAttribute('class', 'contract_heading ' + display);
        h4.setAttribute('id', 'contract_heading_' + position);

        description.setAttribute('class', 'contract_description big-col');
        description.setAttribute('id', 'contract_description_' + position);
        row.setAttribute('class', 'row');

        var content = document.createTextNode(display);
        h4.appendChild(content);
        fragment.appendChild(h4);

        if (details['error']) {
            purchase.style.display = 'none';
            content = document.createTextNode(details['error']);
            description.appendChild(content);
            row.appendChild(description);
            fragment.appendChild(row);
        } else {
            var amount = document.createElement('div');

            amount.setAttribute('class', 'contract_amount col');
            amount.setAttribute('id', 'contract_amount_' + position);

            content = document.createTextNode(currency.value + ' ' + details['ask_price']);
            amount.appendChild(content);

            content = document.createTextNode(details['longcode']);
            description.appendChild(content);

            // create unique id object that is send in response
            priceId.setAttribute('name', 'contract_price_id');
            priceId.setAttribute('class', 'contract_price_id');
            priceId.setAttribute('type', 'hidden');
            priceId.setAttribute('id', details['id']);

            row.appendChild(amount);
            row.appendChild(description);
            row.appendChild(priceId);

            fragment.appendChild(row);

            spotElement.textContent = details['spot'];
        }
        description_container.appendChild(fragment);
        container.insertBefore(description_container, purchase);
    };

    return {
        proposal: createProposal,
        display: display,
    };

})();
<|endoftext|>


<commit_before>
function Route(sourceAddress, destinationAddress, deployRate = 1) {
  this.sourceAddress = sourceAddress;
  this.destinationAddress = destinationAddress;
  this.deployRate = deployRate;

  this.sendCount = 0;
  this.receivedCount = 0;
  this.receivedStepCount = 0;
  this.efficiency = NaN;

  this.reset = function reset() {
    this.sendCount = 0;
    this.receivedCount = 0;
    this.receivedStepCount = 0;
    this.efficiency = NaN;
  }
}

function createSim(graph) {
  var self = {};

  self.simStep = 0;
  self.simDuration = 0;
  self.routes = {};

  function shuffleArray(a) {
    for (let i = a.length; i; i--) {
      let j = Math.floor(Math.random() * i);
      [a[i - 1], a[j]] = [a[j], a[i - 1]];
    }
  }

  self.reset = function reset() {
    var intNodes = graph.getIntNodes();
    for (var i = 0; i < intNodes.length; i++) {
      intNodes[i].o.reset();
    }

    for (var id in self.routes) {
      self.routes[id].reset();
    }

    self.simStep = 0;
    self.simDuration = 0;

    updateSimStatistics();

    graph.redraw();
  }

  function num(v, suffix = '') {
    return isNaN(v) ? '-' : (v.toFixed(2) + suffix);
  }

  function updateSimStatistics() {
    var intNodes = graph.getIntNodes();
    var intLinks = graph.getIntLinks();

    var packetsBroadcastCount = 0;
    var packetsUnicastCount = 0;
    var packetsSendCount = 0;
    var packetsReceivedCount = 0;
    var packetsTransitCount = 0;
    var routesCount = 0;

    var routingEfficiencySum = 0;
    var routingEfficiencyCount = 0;

    function countPackets(packet) {
      if (packet.destinationAddress === BROADCAST_MAC) {
        packetsBroadcastCount += 1;
      } else {
        packetsUnicastCount += 1;

        var id = packet.sourceAddress + '=>' + packet.destinationAddress;
        packetsTransitCount += (id in self.routes);
      }
    }

    for (var i in intNodes) {
      var node = intNodes[i].o;
      node.incoming.forEach(countPackets);
      node.outgoing.forEach(countPackets);
    }

    for (var id in self.routes) {
      var route = self.routes[id];
      routesCount += 1;
      packetsSendCount += route.sendCount;
      packetsReceivedCount += route.receivedCount;

      if (!isNaN(route.efficiency)) {
        routingEfficiencySum += route.efficiency;
        routingEfficiencyCount += 1;
      }
    }

    // Convert to medium percent
    var routingEfficiencyPercent = 100 * routingEfficiencySum / routingEfficiencyCount;

    $$('sim_steps_total').nodeValue = self.simStep;
    $$('sim_duration').nodeValue = self.simDuration + ' ms';

    $$('packets_unicast_count').nodeValue = packetsUnicastCount
    $$('packets_broadcast_count').nodeValue = packetsBroadcastCount;

    function percent(value) {
      var p = (100 * value / packetsSendCount);
      return isNaN(p) ? '' : (' (' + p.toFixed(2) + '%)');
    };

    $$('routes_count').nodeValue = routesCount;
    $$('routes_packets_send').nodeValue = packetsSendCount;
    $$('routes_packets_received').nodeValue = packetsReceivedCount + percent(packetsReceivedCount);
    $$('routes_packets_transit').nodeValue = packetsTransitCount + percent(packetsTransitCount);
    var packetsLostCount = (packetsSendCount - packetsReceivedCount - packetsTransitCount);
    $$('routes_packets_lost').nodeValue = packetsLostCount + percent(packetsLostCount);

    $$('routing_efficiency').nodeValue = num(routingEfficiencyPercent, '%');
  }

  function updateRoutesTable() {
    var tbody = $('sim_routes');

    // Remove all elements
    clearChildren(tbody);

    for (key in self.routes) {
      var route = self.routes[key];
      var tr = append(tbody, 'tr');
      var source_td = append(tr, 'td', route.sourceAddress.slice(-5));
      var target_td = append(tr, 'td', route.destinationAddress.slice(-5));
      append(tr, 'td', route.deployRate);
      append(tr, 'td', route.sendCount);
      append(tr, 'td', route.receivedCount);
      append(tr, 'td', num(route.efficiency * 100, '%'));

      source_td.title = route.sourceAddress
      target_td.title = route.destinationAddress;
    }

    var display = (tbody.children.length === 0);
    displayElement($('sim_no_routes'), display);
  }

  self.delRoutes = function delRoutes() {
    function delRoute(sourceNode, targetNode) {
      var id = sourceNode.mac + '=>' + targetNode.mac;
      delete routes[id];
      updateSimStatistics();
    }

    var intNodes = graph.getSelectedIntNodes();
    if (intNodes.length == 0) {
      alert('Select one source and at least one target node.');
      return;
    }

    var sourceNode = intNodes[0].o;
    for (var i = 1; i < intNodes.length; i += 1) {
      var targetNode = intNodes[i].o;
      delRoute(sourceNode, targetNode);
    }
    updateRoutesTable();
  }

  self.addRoutes = function addRoutes() {
    function addRoute(sourceAddress, destinationAddress) {
      var id = sourceAddress + '=>' + destinationAddress;
      if (!(id in self.routes)) {
        self.routes[id] = new Route(sourceAddress, destinationAddress, 1);
        updateSimStatistics();
      }
    }

    var intNodes = graph.getSelectedIntNodes();
    if (intNodes.length == 0) {
      alert('Select one source and at least one target node.');
      return;
    }

    var sourceAddress = intNodes[0].o.mac;
    for (var i = 1; i < intNodes.length; i += 1) {
      var destinationAddress = intNodes[i].o.mac;
      addRoute(sourceAddress, destinationAddress);
    }
    updateRoutesTable();
  }

  function deployPackets_() {
    var nodes = graph.getIntNodes();
    var nodeMap = {};

    nodes.forEach(function(e) {
      nodeMap[e.o.mac] = e.o;
    });

    for (var id in self.routes) {
      var route = self.routes[id];
      if (randomBoolean(route.deployRate)) {
        var src = route.sourceAddress;
        var dst = route.destinationAddress;
        nodeMap[src].incoming.push(
          new Packet(src, src, src, dst, self.simStep)
        );
        route.sendCount += 1
      }
    }
  }

  self.deployPackets = function deployPackets() {
    if (isEmpty(self.routes)) {
      alert('No routes set on which to deploy packets.');
      return;
    }

    deployPackets_();
    updateRoutesTable();
    updateSimStatistics();

    graph.redraw();
  }

  function updateRouteEfficiency() {
    var intNodes = graph.getIntNodes();
    var intLinks = graph.getIntLinks();
    var dijkstra = createDijkstra(intNodes, intLinks);

    for (var id in self.routes) {
      var route = self.routes[id];
      var sourceIntNode = intNodes.find(function(e) { return e.o.mac === route.sourceAddress; });
      var targetIntNode = intNodes.find(function(e) { return e.o.mac === route.destinationAddress; });
      var shortestDistance = dijkstra.getShortestDistance(sourceIntNode, targetIntNode);
      /*
      * Efficiency as rate of optimal step count weighted by rate of received packets.
      * This means packets in transit are counted as lost packets.
      */
      route.efficiency = (shortestDistance * route.receivedCount / route.receivedStepCount) * (route.receivedCount / route.sendCount);
    }
  }

  // Get other part of the link
  function getNeighbor(intLink, intNode) {
    return (intLink.source.index !== intNode.index) ? intLink.source : intLink.target;
  }

  // Decide if a transmission is successful based on link properties
  function isTransmissionSuccessful(intLink) {
    var n = 100 * (Math.min(intLink.packetCount, intLink.bandwidth) / intLink.bandwidth);
    return ((intLink.quality / 100) * Math.pow(0.999, n)) < Math.random();
  }

  function propagateBroadcastPacket(packet, intNode, intLinks) {
    function clonePacket(packet) {
      return JSON.parse(JSON.stringify(packet));
    }

    // Send cloned packet to all neighbors
    for (var k = 0; k < intLinks.length; k++) {
      var intLink = intLinks[k];
      var intNeigh = getNeighbor(intLink, intNode);

      intLink.packetCount += 1;
      if (isTransmissionSuccessful(intLink)) {
        packet = clonePacket(packet);
        intNeigh.o.incoming.push(packet);
      }
    }
  }

  function propagateUnicastPacket(packet, intNode, intLinks) {
    function updateRouteStats(packet) {
      var id = packet.sourceAddress + '=>' + packet.destinationAddress;
      if (id in self.routes) {
        var route = self.routes[id];
        route.receivedCount += 1;
        route.receivedStepCount += (self.simStep - packet.deployedAtStep);
      } else {
        console.log('Packet route not known: ' + id);
      }
    }

    // Send to one neighbor
    for (var k = 0; k < intLinks.length; k++) {
      var intLink = intLinks[k];
      var intNeigh = getNeighbor(intLink, intNode);

      if (packet.receiverAddress === intNeigh.o.mac) {
        intLink.packetCount += 1;
        if (isTransmissionSuccessful(intLink)) {
          intNeigh.o.incoming.push(packet);
          // Final destination reached
          if (packet.destinationAddress === intNeigh.o.mac) {
            updateRouteStats(packet);
          }
        }
        break;
      }
    }
  }

  self.step = function step(steps_id, deploy_id) {
    var steps = getInteger(steps_id);
    var deployPacketsEnabled = getBoolean(deploy_id);

    var intNodes = graph.getIntNodes();
    var intLinks = graph.getIntLinks();

    // Map internal node index to array of link objects
    var connections = {};

    intNodes.forEach(function(n) {
      connections[n.index] = [];
    });

    intLinks.forEach(function(l) {
      connections[l.source.index].push(l);
      connections[l.target.index].push(l);
      // Count packets over the link for packet loss calculation
      l.packetCount = 0;
    });

    var date = new Date();
    var simStartTime = date.getTime();

    // Simulation steps
    var len = intNodes.length;
    for (var step = 0; step < steps; step += 1) {
      self.simStep += 1;

      if (deployPacketsEnabled) {
        deployPackets_();
      }

      // Guarantee random handling
      shuffleArray(intNodes);

      // Step nodes
      for (var i = 0; i < len; i++) {
        var intNode = intNodes[i];
        intNode.o.step();
      }

      // Propagate packets
      for (var i = 0; i < len; i++) {
        var intNode = intNodes[i];
        var intLinks = connections[intNode.index];
        for (var p = 0; p < intNode.o.outgoing.length; p++) {
          var packet = intNode.o.outgoing[p];
          if (packet.receiverAddress === BROADCAST_MAC) {
            propagateBroadcastPacket(packet, intNode, intLinks);
          } else {
            propagateUnicastPacket(packet, intNode, intLinks);
          }
        }

        // All packets should have been handled
        intNode.o.outgoing = [];
      }
    }

    self.simDuration = date.getTime() - simStartTime;

    updateRouteEfficiency();
    updateRoutesTable();
    updateSimStatistics();

    graph.redraw();
  }

  return self;
}<commit_msg>lower precision of percentage values<commit_after>
function Route(sourceAddress, destinationAddress, deployRate = 1) {
  this.sourceAddress = sourceAddress;
  this.destinationAddress = destinationAddress;
  this.deployRate = deployRate;

  this.sendCount = 0;
  this.receivedCount = 0;
  this.receivedStepCount = 0;
  this.efficiency = NaN;

  this.reset = function reset() {
    this.sendCount = 0;
    this.receivedCount = 0;
    this.receivedStepCount = 0;
    this.efficiency = NaN;
  }
}

function createSim(graph) {
  var self = {};

  self.simStep = 0;
  self.simDuration = 0;
  self.routes = {};

  function shuffleArray(a) {
    for (let i = a.length; i; i--) {
      let j = Math.floor(Math.random() * i);
      [a[i - 1], a[j]] = [a[j], a[i - 1]];
    }
  }

  self.reset = function reset() {
    var intNodes = graph.getIntNodes();
    for (var i = 0; i < intNodes.length; i++) {
      intNodes[i].o.reset();
    }

    for (var id in self.routes) {
      self.routes[id].reset();
    }

    self.simStep = 0;
    self.simDuration = 0;

    updateSimStatistics();

    graph.redraw();
  }

  function num(v, suffix = '') {
    return isNaN(v) ? '-' : (v.toFixed(1) + suffix);
  }

  function updateSimStatistics() {
    var intNodes = graph.getIntNodes();
    var intLinks = graph.getIntLinks();

    var packetsBroadcastCount = 0;
    var packetsUnicastCount = 0;
    var packetsSendCount = 0;
    var packetsReceivedCount = 0;
    var packetsTransitCount = 0;
    var routesCount = 0;

    var routingEfficiencySum = 0;
    var routingEfficiencyCount = 0;

    function countPackets(packet) {
      if (packet.destinationAddress === BROADCAST_MAC) {
        packetsBroadcastCount += 1;
      } else {
        packetsUnicastCount += 1;

        var id = packet.sourceAddress + '=>' + packet.destinationAddress;
        packetsTransitCount += (id in self.routes);
      }
    }

    for (var i in intNodes) {
      var node = intNodes[i].o;
      node.incoming.forEach(countPackets);
      node.outgoing.forEach(countPackets);
    }

    for (var id in self.routes) {
      var route = self.routes[id];
      routesCount += 1;
      packetsSendCount += route.sendCount;
      packetsReceivedCount += route.receivedCount;

      if (!isNaN(route.efficiency)) {
        routingEfficiencySum += route.efficiency;
        routingEfficiencyCount += 1;
      }
    }

    // Convert to medium percent
    var routingEfficiencyPercent = 100 * routingEfficiencySum / routingEfficiencyCount;

    $$('sim_steps_total').nodeValue = self.simStep;
    $$('sim_duration').nodeValue = self.simDuration + ' ms';

    $$('packets_unicast_count').nodeValue = packetsUnicastCount
    $$('packets_broadcast_count').nodeValue = packetsBroadcastCount;

    function percent(value) {
      var p = (100 * value / packetsSendCount);
      return isNaN(p) ? '' : (' (' + p.toFixed(1) + '%)');
    };

    $$('routes_count').nodeValue = routesCount;
    $$('routes_packets_send').nodeValue = packetsSendCount;
    $$('routes_packets_received').nodeValue = packetsReceivedCount + percent(packetsReceivedCount);
    $$('routes_packets_transit').nodeValue = packetsTransitCount + percent(packetsTransitCount);
    var packetsLostCount = (packetsSendCount - packetsReceivedCount - packetsTransitCount);
    $$('routes_packets_lost').nodeValue = packetsLostCount + percent(packetsLostCount);

    $$('routing_efficiency').nodeValue = num(routingEfficiencyPercent, '%');
  }

  function updateRoutesTable() {
    var tbody = $('sim_routes');

    // Remove all elements
    clearChildren(tbody);

    for (key in self.routes) {
      var route = self.routes[key];
      var tr = append(tbody, 'tr');
      var source_td = append(tr, 'td', route.sourceAddress.slice(-5));
      var target_td = append(tr, 'td', route.destinationAddress.slice(-5));
      append(tr, 'td', route.deployRate);
      append(tr, 'td', route.sendCount);
      append(tr, 'td', route.receivedCount);
      append(tr, 'td', num(route.efficiency * 100, '%'));

      source_td.title = route.sourceAddress
      target_td.title = route.destinationAddress;
    }

    var display = (tbody.children.length === 0);
    displayElement($('sim_no_routes'), display);
  }

  self.delRoutes = function delRoutes() {
    function delRoute(sourceNode, targetNode) {
      var id = sourceNode.mac + '=>' + targetNode.mac;
      delete routes[id];
      updateSimStatistics();
    }

    var intNodes = graph.getSelectedIntNodes();
    if (intNodes.length == 0) {
      alert('Select one source and at least one target node.');
      return;
    }

    var sourceNode = intNodes[0].o;
    for (var i = 1; i < intNodes.length; i += 1) {
      var targetNode = intNodes[i].o;
      delRoute(sourceNode, targetNode);
    }
    updateRoutesTable();
  }

  self.addRoutes = function addRoutes() {
    function addRoute(sourceAddress, destinationAddress) {
      var id = sourceAddress + '=>' + destinationAddress;
      if (!(id in self.routes)) {
        self.routes[id] = new Route(sourceAddress, destinationAddress, 1);
        updateSimStatistics();
      }
    }

    var intNodes = graph.getSelectedIntNodes();
    if (intNodes.length == 0) {
      alert('Select one source and at least one target node.');
      return;
    }

    var sourceAddress = intNodes[0].o.mac;
    for (var i = 1; i < intNodes.length; i += 1) {
      var destinationAddress = intNodes[i].o.mac;
      addRoute(sourceAddress, destinationAddress);
    }
    updateRoutesTable();
  }

  function deployPackets_() {
    var nodes = graph.getIntNodes();
    var nodeMap = {};

    nodes.forEach(function(e) {
      nodeMap[e.o.mac] = e.o;
    });

    for (var id in self.routes) {
      var route = self.routes[id];
      if (randomBoolean(route.deployRate)) {
        var src = route.sourceAddress;
        var dst = route.destinationAddress;
        nodeMap[src].incoming.push(
          new Packet(src, src, src, dst, self.simStep)
        );
        route.sendCount += 1
      }
    }
  }

  self.deployPackets = function deployPackets() {
    if (isEmpty(self.routes)) {
      alert('No routes set on which to deploy packets.');
      return;
    }

    deployPackets_();
    updateRoutesTable();
    updateSimStatistics();

    graph.redraw();
  }

  function updateRouteEfficiency() {
    var intNodes = graph.getIntNodes();
    var intLinks = graph.getIntLinks();
    var dijkstra = createDijkstra(intNodes, intLinks);

    for (var id in self.routes) {
      var route = self.routes[id];
      var sourceIntNode = intNodes.find(function(e) { return e.o.mac === route.sourceAddress; });
      var targetIntNode = intNodes.find(function(e) { return e.o.mac === route.destinationAddress; });
      var shortestDistance = dijkstra.getShortestDistance(sourceIntNode, targetIntNode);
      /*
      * Efficiency as rate of optimal step count weighted by rate of received packets.
      * This means packets in transit are counted as lost packets.
      */
      route.efficiency = (shortestDistance * route.receivedCount / route.receivedStepCount) * (route.receivedCount / route.sendCount);
    }
  }

  // Get other part of the link
  function getNeighbor(intLink, intNode) {
    return (intLink.source.index !== intNode.index) ? intLink.source : intLink.target;
  }

  // Decide if a transmission is successful based on link properties
  function isTransmissionSuccessful(intLink) {
    var n = 100 * (Math.min(intLink.packetCount, intLink.bandwidth) / intLink.bandwidth);
    return ((intLink.quality / 100) * Math.pow(0.999, n)) < Math.random();
  }

  function propagateBroadcastPacket(packet, intNode, intLinks) {
    function clonePacket(packet) {
      return JSON.parse(JSON.stringify(packet));
    }

    // Send cloned packet to all neighbors
    for (var k = 0; k < intLinks.length; k++) {
      var intLink = intLinks[k];
      var intNeigh = getNeighbor(intLink, intNode);

      intLink.packetCount += 1;
      if (isTransmissionSuccessful(intLink)) {
        packet = clonePacket(packet);
        intNeigh.o.incoming.push(packet);
      }
    }
  }

  function propagateUnicastPacket(packet, intNode, intLinks) {
    function updateRouteStats(packet) {
      var id = packet.sourceAddress + '=>' + packet.destinationAddress;
      if (id in self.routes) {
        var route = self.routes[id];
        route.receivedCount += 1;
        route.receivedStepCount += (self.simStep - packet.deployedAtStep);
      } else {
        console.log('Packet route not known: ' + id);
      }
    }

    // Send to one neighbor
    for (var k = 0; k < intLinks.length; k++) {
      var intLink = intLinks[k];
      var intNeigh = getNeighbor(intLink, intNode);

      if (packet.receiverAddress === intNeigh.o.mac) {
        intLink.packetCount += 1;
        if (isTransmissionSuccessful(intLink)) {
          intNeigh.o.incoming.push(packet);
          // Final destination reached
          if (packet.destinationAddress === intNeigh.o.mac) {
            updateRouteStats(packet);
          }
        }
        break;
      }
    }
  }

  self.step = function step(steps_id, deploy_id) {
    var steps = getInteger(steps_id);
    var deployPacketsEnabled = getBoolean(deploy_id);

    var intNodes = graph.getIntNodes();
    var intLinks = graph.getIntLinks();

    // Map internal node index to array of link objects
    var connections = {};

    intNodes.forEach(function(n) {
      connections[n.index] = [];
    });

    intLinks.forEach(function(l) {
      connections[l.source.index].push(l);
      connections[l.target.index].push(l);
      // Count packets over the link for packet loss calculation
      l.packetCount = 0;
    });

    var date = new Date();
    var simStartTime = date.getTime();

    // Simulation steps
    var len = intNodes.length;
    for (var step = 0; step < steps; step += 1) {
      self.simStep += 1;

      if (deployPacketsEnabled) {
        deployPackets_();
      }

      // Guarantee random handling
      shuffleArray(intNodes);

      // Step nodes
      for (var i = 0; i < len; i++) {
        var intNode = intNodes[i];
        intNode.o.step();
      }

      // Propagate packets
      for (var i = 0; i < len; i++) {
        var intNode = intNodes[i];
        var intLinks = connections[intNode.index];
        for (var p = 0; p < intNode.o.outgoing.length; p++) {
          var packet = intNode.o.outgoing[p];
          if (packet.receiverAddress === BROADCAST_MAC) {
            propagateBroadcastPacket(packet, intNode, intLinks);
          } else {
            propagateUnicastPacket(packet, intNode, intLinks);
          }
        }

        // All packets should have been handled
        intNode.o.outgoing = [];
      }
    }

    self.simDuration = date.getTime() - simStartTime;

    updateRouteEfficiency();
    updateRoutesTable();
    updateSimStatistics();

    graph.redraw();
  }

  return self;
}<|endoftext|>


<commit_before>//
//  react-native-udp
//
//  Created by Mark Vayngrib on 05/10/15.
//  Copyright (c) 2015 Tradle, Inc. All rights reserved.
//

/**
 * @providesModule UdpSocket
 * @flow
 */

'use strict';

var inherits = require('inherits')
var EventEmitter = require('events').EventEmitter
var React = require('react-native')
var DeviceEventEmitter = require('RCTDeviceEventEmitter')
var Sockets = require('NativeModules').UdpSockets
var base64 = require('base64-js')
var noop = function () {}
var instances = 0
var STATE = {
  UNBOUND: 0,
  BINDING: 1,
  BOUND: 2
}

function UdpSocket(type) {
  EventEmitter.call(this)

  this._id = instances++
  this._state = STATE.UNBOUND
  this._subscription = DeviceEventEmitter.addListener(
    'udp-' + this._id + '-data', this._onReceive.bind(this)
  );

  // ensure compatibility with node's EventEmitter
  if (!this.on) this.on = this.addListener.bind(this)

  Sockets.createSocket(this._id, {
    type: type || 'udp4'
  }) // later
}

inherits(UdpSocket, EventEmitter)

UdpSocket.prototype._debug = function() {
  // for now
  if (typeof DEBUG !== 'undefined' && DEBUG) {
    var args = [].slice.call(arguments)
    args.unshift('socket-' + this._id)
    console.log.apply(console, args)
  }
}

UdpSocket.prototype.bind = function(port, address, callback) {
  var self = this

  if (this._state !== STATE.UNBOUND) throw new Error('Socket is already bound')

  if (typeof address === 'function') {
    callback = address
    address = undefined
  }

  if (!address) address = '0.0.0.0'

  if (!port) port = 0

  if (callback) this.once('listening', callback.bind(this))

  this._state = STATE.BINDING
  this._debug('binding, address:', address, 'port:', port)
  Sockets.bind(this._id, port, address, function(err, addr) {
    if (err) {
      // questionable: may want to self-destruct and
      // force user to create a new socket
      self._state = STATE.UNBOUND
      self._debug('failed to bind', err)
      return self.emit('error', err)
    }

    self._debug('bound to address:', addr.address, 'port:', addr.port)
    self._address = addr.address
    self._port = addr.port
    self._state = STATE.BOUND
    self.emit('listening')
  })
}

UdpSocket.prototype.close = function() {
  if (this._destroyed) return

  this._destroyed = true
  this._debug('closing')
  this._subscription.remove();

  Sockets.close(this._id, this._debug.bind(this, 'closed'))
  this.emit('close')
}

UdpSocket.prototype._onReceive = function(info) {
  this._debug('received', info)

  // from base64 string
  var buf = base64.toByteArray(info.data)
  var rinfo = {
    address: info.address,
    port: info.port,
    family: 'IPv4', // not necessarily
    size: buf.length
  }

  if (typeof Buffer !== 'undefined') buf = new Buffer(buf, 'binary')

  this.emit('message', buf, rinfo)
}

/**
 * socket.send(buf, offset, length, port, address, [callback])
 *
 * For UDP sockets, the destination port and IP address must be
 * specified. A string may be supplied for the address parameter, and it will
 * be resolved with DNS. An optional callback may be specified to detect any
 * DNS errors and when buf may be re-used. Note that DNS lookups will delay
 * the time that a send takes place, at least until the next tick. The only
 * way to know for sure that a send has taken place is to use the callback.
 *
 * If the socket has not been previously bound with a call to bind, it's
 * assigned a random port number and bound to the "all interfaces" address
 * (0.0.0.0 for udp4 sockets, ::0 for udp6 sockets).
 *
 * @param {Array|string} message to be sent
 * @param {number} offset Offset in the buffer where the message starts.
 * @param {number} length Number of bytes in the message.
 * @param {number} port destination port
 * @param {string} address destination IP
 * @param {function} callback Callback when message is done being delivered.
 *                            Optional.
 */
// UdpSocket.prototype.send = function (buf, host, port, cb) {
UdpSocket.prototype.send = function(buffer, offset, length, port, address, callback) {
  var self = this

  if (offset !== 0) throw new Error('Non-zero offset not supported yet')

  if (this._state === STATE.UNBOUND) {
    var args = [].slice.call(arguments)
    return this.bind(0, function(err) {
      if (err) return callback(err)

      self.send.apply(self, args)
    })
  }
  else if (this._state === STATE.BINDING) {
    // we're ok, GCDAsync(Udp)Socket handles queueing internally
  }

  callback = callback || noop
  var str
  if (typeof buffer === 'string') {
    console.warn('socket.send(): interpreting as base64')
    str = buffer
  }
  else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(buffer)) {
    str = buffer.toString('base64')
  }
  else if (buffer instanceof Uint8Array || Array.isArray(buffer)) {
    str = base64.fromByteArray(buffer)
  }
  else {
    throw new Error('invalid message format')
  }

  self._debug('sending', buffer, str)
  Sockets.send(this._id, str, +port, address, function(err) {
    if (err) {
      self._debug('send failed', err)
      return callback(err)
    }

    self._debug('sent')
    callback()
  })
}

UdpSocket.prototype.address = function() {
  if (this._state !== STATE.BOUND) {
    throw new Error('socket is not bound yet')
  }

  return {
    address: this._address,
    port: this._port,
    family: 'IPv4'
  }
}

UdpSocket.prototype.setBroadcast = function(flag) {
  // nothing yet
}

UdpSocket.prototype.setTTL = function(ttl) {
  // nothing yet
}

UdpSocket.prototype.setMulticastTTL = function(ttl, callback) {
  // nothing yet
}

UdpSocket.prototype.setMulticastLoopback = function(flag, callback) {
  // nothing yet
}

UdpSocket.prototype.addMembership = function(multicastAddress, multicastInterface, callback) {
  // nothing yet
}

UdpSocket.prototype.dropMembership = function(multicastAddress, multicastInterface, callback) {
  // nothing yet
}

UdpSocket.prototype.ref = function() {
  // anything?
}

UdpSocket.prototype.unref = function() {
  // anything?
}

module.exports = UdpSocket<commit_msg>add socket.type<commit_after>//
//  react-native-udp
//
//  Created by Mark Vayngrib on 05/10/15.
//  Copyright (c) 2015 Tradle, Inc. All rights reserved.
//

/**
 * @providesModule UdpSocket
 * @flow
 */

'use strict';

var inherits = require('inherits')
var EventEmitter = require('events').EventEmitter
var React = require('react-native')
var DeviceEventEmitter = require('RCTDeviceEventEmitter')
var Sockets = require('NativeModules').UdpSockets
var base64 = require('base64-js')
var noop = function () {}
var instances = 0
var STATE = {
  UNBOUND: 0,
  BINDING: 1,
  BOUND: 2
}

function UdpSocket(type) {
  EventEmitter.call(this)

  this.type = type
  this._id = instances++
  this._state = STATE.UNBOUND
  this._subscription = DeviceEventEmitter.addListener(
    'udp-' + this._id + '-data', this._onReceive.bind(this)
  );

  // ensure compatibility with node's EventEmitter
  if (!this.on) this.on = this.addListener.bind(this)

  Sockets.createSocket(this._id, {
    type: type || 'udp4'
  }) // later
}

inherits(UdpSocket, EventEmitter)

UdpSocket.prototype._debug = function() {
  // for now
  if (typeof DEBUG !== 'undefined' && DEBUG) {
    var args = [].slice.call(arguments)
    args.unshift('socket-' + this._id)
    console.log.apply(console, args)
  }
}

UdpSocket.prototype.bind = function(port, address, callback) {
  var self = this

  if (this._state !== STATE.UNBOUND) throw new Error('Socket is already bound')

  if (typeof address === 'function') {
    callback = address
    address = undefined
  }

  if (!address) address = '0.0.0.0'

  if (!port) port = 0

  if (callback) this.once('listening', callback.bind(this))

  this._state = STATE.BINDING
  this._debug('binding, address:', address, 'port:', port)
  Sockets.bind(this._id, port, address, function(err, addr) {
    if (err) {
      // questionable: may want to self-destruct and
      // force user to create a new socket
      self._state = STATE.UNBOUND
      self._debug('failed to bind', err)
      return self.emit('error', err)
    }

    self._debug('bound to address:', addr.address, 'port:', addr.port)
    self._address = addr.address
    self._port = addr.port
    self._state = STATE.BOUND
    self.emit('listening')
  })
}

UdpSocket.prototype.close = function() {
  if (this._destroyed) return

  this._destroyed = true
  this._debug('closing')
  this._subscription.remove();

  Sockets.close(this._id, this._debug.bind(this, 'closed'))
  this.emit('close')
}

UdpSocket.prototype._onReceive = function(info) {
  this._debug('received', info)

  // from base64 string
  var buf = base64.toByteArray(info.data)
  var rinfo = {
    address: info.address,
    port: info.port,
    family: 'IPv4', // not necessarily
    size: buf.length
  }

  if (typeof Buffer !== 'undefined') buf = new Buffer(buf, 'binary')

  this.emit('message', buf, rinfo)
}

/**
 * socket.send(buf, offset, length, port, address, [callback])
 *
 * For UDP sockets, the destination port and IP address must be
 * specified. A string may be supplied for the address parameter, and it will
 * be resolved with DNS. An optional callback may be specified to detect any
 * DNS errors and when buf may be re-used. Note that DNS lookups will delay
 * the time that a send takes place, at least until the next tick. The only
 * way to know for sure that a send has taken place is to use the callback.
 *
 * If the socket has not been previously bound with a call to bind, it's
 * assigned a random port number and bound to the "all interfaces" address
 * (0.0.0.0 for udp4 sockets, ::0 for udp6 sockets).
 *
 * @param {Array|string} message to be sent
 * @param {number} offset Offset in the buffer where the message starts.
 * @param {number} length Number of bytes in the message.
 * @param {number} port destination port
 * @param {string} address destination IP
 * @param {function} callback Callback when message is done being delivered.
 *                            Optional.
 */
// UdpSocket.prototype.send = function (buf, host, port, cb) {
UdpSocket.prototype.send = function(buffer, offset, length, port, address, callback) {
  var self = this

  if (offset !== 0) throw new Error('Non-zero offset not supported yet')

  if (this._state === STATE.UNBOUND) {
    var args = [].slice.call(arguments)
    return this.bind(0, function(err) {
      if (err) return callback(err)

      self.send.apply(self, args)
    })
  }
  else if (this._state === STATE.BINDING) {
    // we're ok, GCDAsync(Udp)Socket handles queueing internally
  }

  callback = callback || noop
  var str
  if (typeof buffer === 'string') {
    console.warn('socket.send(): interpreting as base64')
    str = buffer
  }
  else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(buffer)) {
    str = buffer.toString('base64')
  }
  else if (buffer instanceof Uint8Array || Array.isArray(buffer)) {
    str = base64.fromByteArray(buffer)
  }
  else {
    throw new Error('invalid message format')
  }

  self._debug('sending', buffer, str)
  Sockets.send(this._id, str, +port, address, function(err) {
    if (err) {
      self._debug('send failed', err)
      return callback(err)
    }

    self._debug('sent')
    callback()
  })
}

UdpSocket.prototype.address = function() {
  if (this._state !== STATE.BOUND) {
    throw new Error('socket is not bound yet')
  }

  return {
    address: this._address,
    port: this._port,
    family: 'IPv4'
  }
}

UdpSocket.prototype.setBroadcast = function(flag) {
  // nothing yet
}

UdpSocket.prototype.setTTL = function(ttl) {
  // nothing yet
}

UdpSocket.prototype.setMulticastTTL = function(ttl, callback) {
  // nothing yet
}

UdpSocket.prototype.setMulticastLoopback = function(flag, callback) {
  // nothing yet
}

UdpSocket.prototype.addMembership = function(multicastAddress, multicastInterface, callback) {
  // nothing yet
}

UdpSocket.prototype.dropMembership = function(multicastAddress, multicastInterface, callback) {
  // nothing yet
}

UdpSocket.prototype.ref = function() {
  // anything?
}

UdpSocket.prototype.unref = function() {
  // anything?
}

module.exports = UdpSocket
<|endoftext|>


<commit_before>/**
 * JPEG.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/html5/image/JPEG
@private
*/
define("moxie/runtime/html5/image/JPEG", [
	"moxie/core/utils/Basic",
	"moxie/core/Exceptions",
	"moxie/runtime/html5/image/JPEGHeaders",
	"moxie/runtime/html5/utils/BinaryReader",
	"moxie/runtime/html5/image/ExifParser"
], function(Basic, x, JPEGHeaders, BinaryReader, ExifParser) {

	function JPEG(binstr) {
		var _binstr, _br, _hm, _ep, _info, hasExif;

		_binstr = binstr;

		_br = new BinaryReader();
		_br.init(_binstr);

		// check if it is jpeg
		if (_br.SHORT(0) !== 0xFFD8) {
			throw new x.ImageError(x.ImageError.WRONG_FORMAT);
		}

		// backup headers
		_hm = new JPEGHeaders(binstr);

		// extract exif info
		_ep = new ExifParser();
		hasExif = !!_ep.init(_hm.get('app1')[0]);

		// get dimensions
		_info = _getDimensions.call(this);

		Basic.extend(this, {
			type: 'image/jpeg',

			size: _binstr.length,

			width: _info && _info.width || 0,

			height: _info && _info.height || 0,

			setExif: function(tag, value) {
				if (!hasExif) {
					return false; // or throw an exception
				}

				if (Basic.typeOf(tag) === 'object') {
					Basic.each(tag, function(value, tag) {
						_ep.setExif(tag, value);
					});
				} else {
					_ep.setExif(tag, value);
				}

				// update internal headers
				_hm.set('app1', _ep.getBinary());
			},

			writeHeaders: function() {
				if (!arguments.length) {
					// if no arguments passed, update headers internally
					return (_binstr = _hm.restore(_binstr));
				}
				return _hm.restore(arguments[0]);
			},

			stripHeaders: function(binstr) {
				return _hm.strip(binstr);
			},

			purge: function() {
				_purge.call(this);
			}
		});

		if (hasExif) {
			this.meta = {
				tiff: _ep.TIFF(),
				exif: _ep.EXIF(),
				gps: _ep.GPS(),
				thumb: _getThumb()
			};
		}

		function _getDimensions(br) {
			var idx = 0
			, marker
			, length
			;

			if (!br) {
				br = _br;
			}

			// examine all through the end, since some images might have very large APP segments
			while (idx <= br.length()) {
				marker = br.SHORT(idx += 2);

				if (marker >= 0xFFC0 && marker <= 0xFFC3) { // SOFn
					idx += 5; // marker (2 bytes) + length (2 bytes) + Sample precision (1 byte)
					return {
						height: br.SHORT(idx),
						width: br.SHORT(idx += 2)
					};
				}
				length = br.SHORT(idx += 2);
				idx += length - 2;
			}
			return null;
		}

		function _getThumb() {
			var binstr =  _ep.thumb()
			, br = new BinaryReader()
			, info
			;

			br.init(binstr);
			info = _getDimensions(br);
			br.init(null);

			if (!info) {
				return null;
			} else {
				info.data = binstr;
				return info;
			}
		}

		function _purge() {
			if (!_ep || !_hm || !_br) {
				return; // ignore any repeating purge requests
			}
			_ep.purge();
			_hm.purge();
			_br.init(null);
			_binstr = _info = _hm = _ep = _br = null;
		}
	}

	return JPEG;
});
<commit_msg>Image/Jpeg, HTML5: Survive the cases when there's no embedded thumb.<commit_after>/**
 * JPEG.js
 *
 * Copyright 2013, Moxiecode Systems AB
 * Released under GPL License.
 *
 * License: http://www.plupload.com/license
 * Contributing: http://www.plupload.com/contributing
 */

/**
@class moxie/runtime/html5/image/JPEG
@private
*/
define("moxie/runtime/html5/image/JPEG", [
	"moxie/core/utils/Basic",
	"moxie/core/Exceptions",
	"moxie/runtime/html5/image/JPEGHeaders",
	"moxie/runtime/html5/utils/BinaryReader",
	"moxie/runtime/html5/image/ExifParser"
], function(Basic, x, JPEGHeaders, BinaryReader, ExifParser) {

	function JPEG(binstr) {
		var _binstr, _br, _hm, _ep, _info, hasExif;

		_binstr = binstr;

		_br = new BinaryReader();
		_br.init(_binstr);

		// check if it is jpeg
		if (_br.SHORT(0) !== 0xFFD8) {
			throw new x.ImageError(x.ImageError.WRONG_FORMAT);
		}

		// backup headers
		_hm = new JPEGHeaders(binstr);

		// extract exif info
		_ep = new ExifParser();
		hasExif = !!_ep.init(_hm.get('app1')[0]);

		// get dimensions
		_info = _getDimensions.call(this);

		Basic.extend(this, {
			type: 'image/jpeg',

			size: _binstr.length,

			width: _info && _info.width || 0,

			height: _info && _info.height || 0,

			setExif: function(tag, value) {
				if (!hasExif) {
					return false; // or throw an exception
				}

				if (Basic.typeOf(tag) === 'object') {
					Basic.each(tag, function(value, tag) {
						_ep.setExif(tag, value);
					});
				} else {
					_ep.setExif(tag, value);
				}

				// update internal headers
				_hm.set('app1', _ep.getBinary());
			},

			writeHeaders: function() {
				if (!arguments.length) {
					// if no arguments passed, update headers internally
					return (_binstr = _hm.restore(_binstr));
				}
				return _hm.restore(arguments[0]);
			},

			stripHeaders: function(binstr) {
				return _hm.strip(binstr);
			},

			purge: function() {
				_purge.call(this);
			}
		});

		if (hasExif) {
			this.meta = {
				tiff: _ep.TIFF(),
				exif: _ep.EXIF(),
				gps: _ep.GPS(),
				thumb: _getThumb()
			};
		}

		function _getDimensions(br) {
			var idx = 0
			, marker
			, length
			;

			if (!br) {
				br = _br;
			}

			// examine all through the end, since some images might have very large APP segments
			while (idx <= br.length()) {
				marker = br.SHORT(idx += 2);

				if (marker >= 0xFFC0 && marker <= 0xFFC3) { // SOFn
					idx += 5; // marker (2 bytes) + length (2 bytes) + Sample precision (1 byte)
					return {
						height: br.SHORT(idx),
						width: br.SHORT(idx += 2)
					};
				}
				length = br.SHORT(idx += 2);
				idx += length - 2;
			}
			return null;
		}

		function _getThumb() {
			var binstr =  _ep.thumb()
			, br = new BinaryReader()
			, info
			;

			if (binstr) {
				br.init(binstr);
				info = _getDimensions(br);
				br.init(null);

				if (info) {
					info.data = binstr;
					return info;
				}
			}
			return null;
		}

		function _purge() {
			if (!_ep || !_hm || !_br) {
				return; // ignore any repeating purge requests
			}
			_ep.purge();
			_hm.purge();
			_br.init(null);
			_binstr = _info = _hm = _ep = _br = null;
		}
	}

	return JPEG;
});
<|endoftext|>


<commit_before>const fs = require('fs');
const http = require('http');
const shell = require('shelljs');
const decompress = require('decompress');
const decompressTargz = require('decompress-targz');
const env = require('./env.js');
const { exec } = require('./helper.js');

function writeFile(url, destination, resolve, reject) {
    const file = fs.createWriteStream(destination);

    const req = http.get(url, (res) => {
        res.pipe(file);
    });

    req.on('error', (e) => {
        file.unlink(destination);
        reject(e);
    });

    file.on('error', () => {
        file.unlink(destination);
        reject(new Error('File error'));
    });

    file.on('finish', resolve);
}

function download(url, destination) {
    if (fs.existsSync(destination)) {
        shell.echo(`${destination} already exists. Skipping download.`);

        return Promise.resolve();
    }

    const executor = writeFile.bind(null, url, destination);
    return new Promise(executor);
}

function validateFile(fileName) {
    let res;

    if (env.isWindows) {
        const output = exec(`certutil -hashfile ${fileName} SHA512`).split('\r\n');

        // `certutil` returns 2byte separated string
        // (e.g. "a9 89 b5 27 f3 f9 90 d4 71 e6 d4 7e e4 10 e5 7d 8b e7 62 0b")
        const sha512 = output[1].replace(/ /g, '');

        res = `${sha512}  ${fileName}`;
    } else {
        res = exec(`shasum -a 512 ${fileName}`).trim();
    }

    if (res !== env.sha512sum) {
        throw new Error(`Wrong sha512 for ${fileName}! Expected "${env.sha512sum}", got "${res}".`);
    }
}

function clearPath() {
    if (!shell.test('-d', env.sourceFolder)) {
        return;
    }

    shell.rm('-rf', env.sourceFolder);
}

function moveFolder() {
    const sourceCodeFolder = `${env.downloadedFolderName}/zookeeper-client/zookeeper-client-c`;
    if (env.isWindows) {
        shell.cp('-r', sourceCodeFolder, env.sourceFolder);
        shell.rm('-rf', env.downloadedFolderName);
        return;
    }

    shell.mv(sourceCodeFolder, env.sourceFolder);
}

function applyPatches() {
    if (env.isWindows) {
        const destination = `${env.sourceFolder}/src`;

        shell.sed('-i', '#include "zookeeper_log.h"', '#include "zookeeper_log.h"\n#include "winport.h"\n', `${destination}/zk_log.c`);
        shell.sed('-i', '#include "zookeeper.h"', '#include "winport.h"\n#include "zookeeper.h"\n', `${destination}/zk_adaptor.h`);
        shell.sed('-i', '#include "zk_adaptor.h"', '#include "zk_adaptor.h"\n#include "winport.h"\n', `${destination}/zookeeper.c`);

        if (!env.isVerbose) {
            const cmakeFile = 'CMakeLists.txt';
            shell.cp(`${env.rootFolder}/patches/${cmakeFile}`, `${env.sourceFolder}/src/${cmakeFile}`);
        }
    } else {
        exec(`patch -p0 < ${env.rootFolder}/patches/ZOOKEEPER-3078.patch`);
        shell.cp('-R', `${env.rootFolder}/patches/autoreconf/*`, `${env.sourceFolder}`);
    }
}

if (env.isAlreadyBuilt) {
    shell.echo('Zookeeper has already been built');
    shell.exit(0);
}

shell.config.fatal = true;

if (env.isVerbose) {
    shell.config.verbose = true;
}

shell.cd(env.workFolder);

download(env.downloadUrl, env.downloadedFileName)
    .then(() => {
        validateFile(env.downloadedFileName);

        clearPath();

        decompress(env.downloadedFileName, './', {
            plugins: [
                decompressTargz(),
            ],
        }).then(() => {
            moveFolder();
            applyPatches();
        }).catch((e) => {
            shell.echo(`Error: ${e.message}`);
            shell.exit(1);
        });
    })
    .catch((e) => {
        shell.echo(`Unable to download zookeeper library. Error: ${e.message}`);
        shell.exit(1);
    });
<commit_msg>fix: replace cmakelists in source dir<commit_after>const fs = require('fs');
const http = require('http');
const shell = require('shelljs');
const decompress = require('decompress');
const decompressTargz = require('decompress-targz');
const env = require('./env.js');
const { exec } = require('./helper.js');

function writeFile(url, destination, resolve, reject) {
    const file = fs.createWriteStream(destination);

    const req = http.get(url, (res) => {
        res.pipe(file);
    });

    req.on('error', (e) => {
        file.unlink(destination);
        reject(e);
    });

    file.on('error', () => {
        file.unlink(destination);
        reject(new Error('File error'));
    });

    file.on('finish', resolve);
}

function download(url, destination) {
    if (fs.existsSync(destination)) {
        shell.echo(`${destination} already exists. Skipping download.`);

        return Promise.resolve();
    }

    const executor = writeFile.bind(null, url, destination);
    return new Promise(executor);
}

function validateFile(fileName) {
    let res;

    if (env.isWindows) {
        const output = exec(`certutil -hashfile ${fileName} SHA512`).split('\r\n');

        // `certutil` returns 2byte separated string
        // (e.g. "a9 89 b5 27 f3 f9 90 d4 71 e6 d4 7e e4 10 e5 7d 8b e7 62 0b")
        const sha512 = output[1].replace(/ /g, '');

        res = `${sha512}  ${fileName}`;
    } else {
        res = exec(`shasum -a 512 ${fileName}`).trim();
    }

    if (res !== env.sha512sum) {
        throw new Error(`Wrong sha512 for ${fileName}! Expected "${env.sha512sum}", got "${res}".`);
    }
}

function clearPath() {
    if (!shell.test('-d', env.sourceFolder)) {
        return;
    }

    shell.rm('-rf', env.sourceFolder);
}

function moveFolder() {
    const sourceCodeFolder = `${env.downloadedFolderName}/zookeeper-client/zookeeper-client-c`;
    if (env.isWindows) {
        shell.cp('-r', sourceCodeFolder, env.sourceFolder);
        shell.rm('-rf', env.downloadedFolderName);
        return;
    }

    shell.mv(sourceCodeFolder, env.sourceFolder);
}

function applyPatches() {
    if (env.isWindows) {
        const destination = `${env.sourceFolder}/src`;

        shell.sed('-i', '#include "zookeeper_log.h"', '#include "zookeeper_log.h"\n#include "winport.h"\n', `${destination}/zk_log.c`);
        shell.sed('-i', '#include "zookeeper.h"', '#include "winport.h"\n#include "zookeeper.h"\n', `${destination}/zk_adaptor.h`);
        shell.sed('-i', '#include "zk_adaptor.h"', '#include "zk_adaptor.h"\n#include "winport.h"\n', `${destination}/zookeeper.c`);

        if (!env.isVerbose) {
            const cmakeFile = 'CMakeLists.txt';
            shell.cp(`${env.rootFolder}/patches/${cmakeFile}`, `${env.sourceFolder}/${cmakeFile}`);
        }
    } else {
        exec(`patch -p0 < ${env.rootFolder}/patches/ZOOKEEPER-3078.patch`);
        shell.cp('-R', `${env.rootFolder}/patches/autoreconf/*`, `${env.sourceFolder}`);
    }
}

if (env.isAlreadyBuilt) {
    shell.echo('Zookeeper has already been built');
    shell.exit(0);
}

shell.config.fatal = true;

if (env.isVerbose) {
    shell.config.verbose = true;
}

shell.cd(env.workFolder);

download(env.downloadUrl, env.downloadedFileName)
    .then(() => {
        validateFile(env.downloadedFileName);

        clearPath();

        decompress(env.downloadedFileName, './', {
            plugins: [
                decompressTargz(),
            ],
        }).then(() => {
            moveFolder();
            applyPatches();
        }).catch((e) => {
            shell.echo(`Error: ${e.message}`);
            shell.exit(1);
        });
    })
    .catch((e) => {
        shell.echo(`Unable to download zookeeper library. Error: ${e.message}`);
        shell.exit(1);
    });
<|endoftext|>


<commit_before>/**
 * Created by camilo on 06-09-16.
 */
//Importar

var express = require('express');

//Instanciar
var app = express();

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

app.get('/login', function (req, res) {
    res.sendfile(__dirname + '/Views/login.html');
});

app.get('/register', function (req, res) {
    res.sendfile(__dirname + '/Views/register.html');
});

app.get('/encuesta_paso1', function (req, res) {
    res.sendfile(__dirname + '/Views/encuesta_paso1.html');
});

app.get('/encuesta_paso2', function (req, res) {
    res.sendfile(__dirname + '/Views/encuesta_paso2.html');
});

app.use(express.static('public'));

//Escuchar
app.listen(9000);
console.log("Servidor corriendo en http://localhost:9000/");<commit_msg>Crear branch para comenzar a probar el login de usuarios<commit_after>/**
 * Created by camilo on 06-09-16.
 */
//Importar

var express = require('express');

//Instanciar
var app = express();

//Ruteo

//Hay que hacer que tengas que logearte para ver el main
app.get('/', function (req, res) {
    res.sendfile(__dirname + '/Views/index.html');
});

app.get('/login', function (req, res) {
    res.sendfile(__dirname + '/Views/login.html');
});

app.get('/register', function (req, res) {
    res.sendfile(__dirname + '/Views/register.html');
});

app.get('/encuesta_paso1', function (req, res) {
    res.sendfile(__dirname + '/Views/encuesta_paso1.html');
});

app.get('/encuesta_paso2', function (req, res) {
    res.sendfile(__dirname + '/Views/encuesta_paso2.html');
});

app.use(express.static('public'));

//Escuchar
app.listen(9000);
console.log("Servidor corriendo en http://localhost:9000/");<|endoftext|>


<commit_before>import pg from 'pg';
import log from '../../backend/log';
import models from '../../backend/data/models'
import async from 'async';
import Promise from 'bluebird';

export let job = async () => {
  try {
    // This first transaction marks these groups as having been picked up.
    let groups = []
    await models.sequelize.transaction(async (trans) => {
        groups = await models.GCBSDGroup.findAll({
          where: {
            $or : [
              {
                modified_dt: {
                  $lt: new Date(new Date() - 24 * 60 * 60 * 1000)
                }
              },
              {
                modified_dt: {
                  $eq: models.sequelize.col('create_dt')
                }
              }
            ],
          },
          transaction: trans
        })

        let promises = groups.map(async (group) => {
          await models.GCBSDGroup.update({
            modified_dt: new Date()
          }, {
            where: {
              id: group.id
            }
          }, { transaction: trans})
        })
        return await Promise.all(promises);
    });
    await models.sequelize.transaction(async (t) => {
      let promises = groups.map(async (group) => {
        if (group.query !== 'everyone') {
          await models.BSDPersonGCBSDGroup.destroy({
            where: {
              gc_bsd_group_id: group.id
            },
            transaction: t
          })
          let results = null;
          let limit = 100000;
          let offset = 0;
          let limitedQuery = null;

          do {
            limitedQuery = `${group.query} order by cons_id limit ${limit} offset ${offset}`
            log.info('Running query: ' + limitedQuery)
            results = await models.sequelize.query(limitedQuery, {transaction: t})
            if (results && results.length > 0) {
              let persons = results[0].map((result) => result.cons_id)
              await group.addPeople(persons, {transaction: t})
              log.info('Done inserting ' + persons.length + ' rows for group ' + group.id)
            }
            offset = offset + limit;
          } while(results && results.length > 0 && results[0].length > 0)
        }
      })
      await Promise.all(promises);
      log.info('Done refreshing groups')
    })
  }
  catch (ex) {
    log.error(ex.stack)
  }
}<commit_msg>Add a new log statement<commit_after>import pg from 'pg';
import log from '../../backend/log';
import models from '../../backend/data/models'
import async from 'async';
import Promise from 'bluebird';

export let job = async () => {
  try {
    log.info('Starting group refresh job...')
    // This first transaction marks these groups as having been picked up.
    let groups = []
    await models.sequelize.transaction(async (trans) => {
        groups = await models.GCBSDGroup.findAll({
          where: {
            $or : [
              {
                modified_dt: {
                  $lt: new Date(new Date() - 24 * 60 * 60 * 1000)
                }
              },
              {
                modified_dt: {
                  $eq: models.sequelize.col('create_dt')
                }
              }
            ],
          },
          transaction: trans
        })

        let promises = groups.map(async (group) => {
          await models.GCBSDGroup.update({
            modified_dt: new Date()
          }, {
            where: {
              id: group.id
            }
          }, { transaction: trans})
        })
        return await Promise.all(promises);
    });
    await models.sequelize.transaction(async (t) => {
      let promises = groups.map(async (group) => {
        if (group.query !== 'everyone') {
          await models.BSDPersonGCBSDGroup.destroy({
            where: {
              gc_bsd_group_id: group.id
            },
            transaction: t
          })
          let results = null;
          let limit = 100000;
          let offset = 0;
          let limitedQuery = null;

          do {
            limitedQuery = `${group.query} order by cons_id limit ${limit} offset ${offset}`
            log.info('Running query: ' + limitedQuery)
            results = await models.sequelize.query(limitedQuery, {transaction: t})
            if (results && results.length > 0) {
              let persons = results[0].map((result) => result.cons_id)
              await group.addPeople(persons, {transaction: t})
              log.info('Done inserting ' + persons.length + ' rows for group ' + group.id)
            }
            offset = offset + limit;
          } while(results && results.length > 0 && results[0].length > 0)
        }
      })
      await Promise.all(promises);
      log.info('Done refreshing groups')
    })
  }
  catch (ex) {
    log.error(ex.stack)
  }
}<|endoftext|>


<commit_before>/*
 * biojs-io-biom
 * https://github.com/iimog/biojs-io-biom
 *
 * Copyright (c) 2016 Markus J. Ankenbrand
 * Licensed under the MIT license.
 */

// chai is an assertion library
let chai = require('chai');

// @see http://chaijs.com/api/assert/
let assert = chai.assert;

// register alternative styles
// @see http://chaijs.com/api/bdd/
chai.expect();
chai.should();

// requires your main app (specified in index.js)
import {Biom, VERSION, DEFAULT_BIOM} from '../src/biojs-io-biom';

describe('biojs-io-biom module', () => {
  describe('Biom constructor should create a biom object with default values', () => {
    it('should create an object', () => {
      assert.equal(typeof new Biom(), "object");
    });
    it('id should be null after empty initialization', () => {
      assert.equal(new Biom().id, DEFAULT_BIOM.id);
    });
    it('new biom object should be initialized with default values', () => {
      let biom = new Biom();
      assert.equal(biom.columns, DEFAULT_BIOM.columns);
      assert.equal(biom.data, DEFAULT_BIOM.data);
      // The date is set to now by default and can not be checked in this manner
      // assert.equal(biom.date, DEFAULT_BIOM.date);
      assert.equal(biom.format, DEFAULT_BIOM.format);
      assert.equal(biom.format_url, DEFAULT_BIOM.format_url);
      assert.equal(biom.generated_by, DEFAULT_BIOM.generated_by);
      assert.equal(biom.matrix_element_type, DEFAULT_BIOM.matrix_element_type);
      assert.equal(biom.matrix_type, DEFAULT_BIOM.matrix_type);
      assert.equal(biom.rows, DEFAULT_BIOM.rows);
      assert.equal(biom.shape, DEFAULT_BIOM.shape);
      assert.equal(biom.type, DEFAULT_BIOM.type);
    });
  });

  describe('getter and setter for id should work', () => {
    it('should set and get the id to string', () => {
      let biom = new Biom();
      biom.id = "NewID";
      assert.equal(biom.id, "NewID");
    });
    it('should set and get the id to null', () => {
      let biom = new Biom();
      biom.id = null;
      assert.equal(biom.id, null);
    });
    it('should throw a type error when trying to set id to something other than string or null', () => {
      let biom = new Biom();
      assert.throws(() => {biom.id = []}, TypeError);
      assert.throws(() => {biom.id = 2}, TypeError);
      assert.throws(() => {biom.id = {}}, TypeError);
    });
  });

  describe('getter and setter for format should work', () => {
    it('should set and get the format to string', () => {
      let biom = new Biom();
      biom.format = "NewFormat";
      assert.equal(biom.format, "NewFormat");
    });
    it('should throw a type error when trying to set format to something other than string', () => {
      let biom = new Biom();
      assert.throws(() => {biom.format = []}, TypeError);
      assert.throws(() => {biom.format = 2}, TypeError);
      assert.throws(() => {biom.format = {}}, TypeError);
      assert.throws(() => {biom.format = null}, TypeError);
    });
  });
});
<commit_msg>Add test for format_url getter/setter<commit_after>/*
 * biojs-io-biom
 * https://github.com/iimog/biojs-io-biom
 *
 * Copyright (c) 2016 Markus J. Ankenbrand
 * Licensed under the MIT license.
 */

// chai is an assertion library
let chai = require('chai');

// @see http://chaijs.com/api/assert/
let assert = chai.assert;

// register alternative styles
// @see http://chaijs.com/api/bdd/
chai.expect();
chai.should();

// requires your main app (specified in index.js)
import {Biom, VERSION, DEFAULT_BIOM} from '../src/biojs-io-biom';

describe('biojs-io-biom module', () => {
  describe('Biom constructor should create a biom object with default values', () => {
    it('should create an object', () => {
      assert.equal(typeof new Biom(), "object");
    });
    it('id should be null after empty initialization', () => {
      assert.equal(new Biom().id, DEFAULT_BIOM.id);
    });
    it('new biom object should be initialized with default values', () => {
      let biom = new Biom();
      assert.equal(biom.columns, DEFAULT_BIOM.columns);
      assert.equal(biom.data, DEFAULT_BIOM.data);
      // The date is set to now by default and can not be checked in this manner
      // assert.equal(biom.date, DEFAULT_BIOM.date);
      assert.equal(biom.format, DEFAULT_BIOM.format);
      assert.equal(biom.format_url, DEFAULT_BIOM.format_url);
      assert.equal(biom.generated_by, DEFAULT_BIOM.generated_by);
      assert.equal(biom.matrix_element_type, DEFAULT_BIOM.matrix_element_type);
      assert.equal(biom.matrix_type, DEFAULT_BIOM.matrix_type);
      assert.equal(biom.rows, DEFAULT_BIOM.rows);
      assert.equal(biom.shape, DEFAULT_BIOM.shape);
      assert.equal(biom.type, DEFAULT_BIOM.type);
    });
  });

  describe('getter and setter for id should work', () => {
    it('should set and get the id to string', () => {
      let biom = new Biom();
      biom.id = "NewID";
      assert.equal(biom.id, "NewID");
    });
    it('should set and get the id to null', () => {
      let biom = new Biom();
      biom.id = null;
      assert.equal(biom.id, null);
    });
    it('should throw a type error when trying to set id to something other than string or null', () => {
      let biom = new Biom();
      assert.throws(() => {biom.id = []}, TypeError);
      assert.throws(() => {biom.id = 2}, TypeError);
      assert.throws(() => {biom.id = {}}, TypeError);
    });
  });

  describe('getter and setter for format should work', () => {
    it('should set and get the format to string', () => {
      let biom = new Biom();
      biom.format = "NewFormat";
      assert.equal(biom.format, "NewFormat");
    });
    it('should throw a type error when trying to set format to something other than string', () => {
      let biom = new Biom();
      assert.throws(() => {biom.format = []}, TypeError);
      assert.throws(() => {biom.format = 52}, TypeError);
      assert.throws(() => {biom.format = {}}, TypeError);
      assert.throws(() => {biom.format = null}, TypeError);
    });
  });

  describe('getter and setter for format_url should work', () => {
    it('should set and get the format_url to string', () => {
      let biom = new Biom();
      biom.format_url = "http://newformat.url";
      assert.equal(biom.format_url, "http://newformat.url");
    });
    it('should throw a type error when trying to set format_url to something other than string', () => {
      let biom = new Biom();
      assert.throws(() => {biom.format_url = []}, TypeError);
      assert.throws(() => {biom.format_url = 27}, TypeError);
      assert.throws(() => {biom.format_url = {}}, TypeError);
      assert.throws(() => {biom.format_url = null}, TypeError);
    });
  });
});
<|endoftext|>


<commit_before>import React from 'react';
import { Link } from 'react-router';
import moment from 'moment';
import 'moment/locale/nl';

class BlockUser extends React.Component {
  render() {
    return (
      <Link to={`conversation/${this.props.id}`} className="c-block-user" key={ this.props.id }>

          { this.renderBlockUserData() }

{ this.props.name }

{ this.renderBlockUserText() }

      </Link>
    );
  }

  renderBlockUserData() {
    let data = [];

    if (this.props.unreadMessagesCount) {
      data.push(
{this.props.unreadMessagesCount} new messages
);
    }

    if (this.props.lastMessage) {
      data.push(
{moment(this.props.lastMessageAt).fromNow()}
);
    }

    else if (this.props.lastSeenAt) {
      data.push(
{moment(this.props.lastSeenAt).fromNow()}
);
    }

    return data;
  }

  renderBlockUserText() {
    let text;

    if (this.props.lastMessage) {
      text = this.props.lastMessage;
    }

    else if (this.props.description) {
      text = this.props.description;
    }

    return text;
  }
}

BlockUser.propTypes = {
  id: React.PropTypes.number,
  name: React.PropTypes.string,
  description: React.PropTypes.string,
  lastMessage: React.PropTypes.string,
  imageSource: React.PropTypes.string,
  lastSeenDate: React.PropTypes.string,
  lastMessageDate: React.PropTypes.string,
  unreadMessagesLength: React.PropTypes.number,
};

export default BlockUser;
<commit_msg>add last seen to user-block in contact list<commit_after>import React from 'react';
import { Link } from 'react-router';
import moment from 'moment';
import 'moment/locale/nl';

class BlockUser extends React.Component {
  render() {
    return (
      <Link to={`conversation/${this.props.id}`} className="c-block-user" key={ this.props.id }>

          { this.renderBlockUserData() }

{ this.props.name }

{ this.renderBlockUserText() }

      </Link>
    );
  }

  renderBlockUserData() {
    let data = [];

    if (this.props.unreadMessagesCount) {
      data.push(
{this.props.unreadMessagesCount} new messages
);
    }

    if (this.props.lastMessage) {
      data.push(
{moment(this.props.lastMessageAt).fromNow()}
);
    }

    else if (this.props.lastSeenAt) {
      data.push(
last seen: {moment(this.props.lastSeenAt).fromNow()}
);
    }

    return data;
  }

  renderBlockUserText() {
    let text;

    if (this.props.lastMessage) {
      text = this.props.lastMessage;
    }

    else if (this.props.description) {
      text = this.props.description;
    }

    return text;
  }
}

BlockUser.propTypes = {
  id: React.PropTypes.number,
  name: React.PropTypes.string,
  description: React.PropTypes.string,
  lastMessage: React.PropTypes.string,
  imageSource: React.PropTypes.string,
  lastSeenDate: React.PropTypes.string,
  lastMessageDate: React.PropTypes.string,
  unreadMessagesLength: React.PropTypes.number,
};

export default BlockUser;
<|endoftext|>