<commit_before>/*jshint es5:false, asi:true, quotmark:false, eqeqeq:false, forin: false */
/*
 * (c) 2011 Tim Becker, see file LICENSE for details
 */

/*
 * Provides functionality for bencoding and decoding as use in
 * bittorrent and described in:
 *  http://www.bittorrent.org/beps/bep_0003.html
 *
 * Encoding is as follows:
 *
 *    var benc  = require("bncode"),
 *        exmp = {}
 *
 *    exmp.bla = "blup"
 *    exmp.foo = "bar"
 *    exmp.one = 1
 *    exmp.woah = {}
 *    exmp.woah.arr = []
 *    exmp.woah.arr.push(1)
 *    exmp.woah.arr.push(2)
 *    exmp.woah.arr.push(3)
 *    exmp.str = new Buffer("Buffers work too")
 *
 *    var bencBuffer = benc.encode(exmp) i
 *
 *    // d3:bla4:blup3:foo3:bar3:onei1e4:woahd3:arr \
 *    // li1ei2ei3eee3:str16:Buffers work tooe
 *
 *
 * Decoding will work in progressively, e.g. if you're receiving partial
 * bencoded strings on the network:
 *
 *    var benc = require("bncode"),
 *        buf  = null
 *
 *    decoder = new bncode.decoder()
 *    while (buf = receiveData()) {
 *      decoder.decode(buf)
 *    }
 *
 *    log(decoder.result())
 *
 *
 * Or "all in one"
 *
 *    var benc = require("bncode"),
 *        buf  = getBuffer(),
 *        dec  = benc.decode(buf)
 *
 *    log(dec.bla)
 *
 *
 * There are some subtleties concerning bencoded strings. These are
 * decoded as Buffer objects because they are just strings of raw bytes
 * and as such would wreak havoc with multi byte strings in javascript.
 *
 * The exception to this is strings that appear as keys in bencoded
 * dicts. These are decoded as Javascript Strings, as they should always
 * be strings of (ascii) characters and if they weren't decoded as JS
 * Strings, dict's would map to Javascript objects with properties.
 *
 */

var Transform   = require('stream').Transform;
var inherits = require('util').inherits

var I     = "i".charCodeAt(0)
var L     = "l".charCodeAt(0)
var E     = "e".charCodeAt(0)
var D     = "d".charCodeAt(0)
var COLON = ":".charCodeAt(0)
var DASH  = "-".charCodeAt(0)

var STATE_INITIAL          = 0
var STATE_STATE_STRING_LEN = STATE_INITIAL          + 1
var STATE_STRING           = STATE_STATE_STRING_LEN + 1
var STATE_COLON            = STATE_STRING           + 1
var STATE_STATE_INTEGER    = STATE_COLON            + 1
var STATE_INTEGER          = STATE_STATE_INTEGER    + 1

function log (m) {console.log(m); process.stdout.flush()}

/*
 * This is the internal state machine for taking apart bencoded strings,
 * it's not exposed in the eports.  It's constructed with four callbacks
 * that get fired when:
 *
 * cb: a value (string or number) is encountered
 * cb_list: a begin list element is encountered
 * cb_dict: a beginning of dictionary is encountered.
 * cd_end: an end element, wheter dict or list is encountered
 *
 * Once constructed, the machine may be fed with buffers containing
 * partial bencoded string. Call `consistent` to check whether the
 * current state is consistent, e.g. not smack-dap in the middle of
 * a string or a number and if the dict, list and end calls balance
 *
 *
 * The functionality being so rudimentary requires some more state and
 * logic in the code executing the machine, for this see Context, below.
 *
 */

var BdecodeSMachine = function (cb, cb_list, cb_dict, cb_end) {
  var depth   = 0
  var state   = STATE_INITIAL

  var cb      = cb
  var cb_list = cb_list
  var cb_dict = cb_dict
  var cb_end  = cb_end

  this.consistent = function() {
    return (state === STATE_INITIAL && depth === 0)
  }

  var strLen = 0
  var str    = ""
  var _int   = 0
  var neg    = false

  this.parse = function (buffer, encoding) {
    encoding = encoding ? encoding : "utf8"
    if ("string" === typeof(buffer)) {
      buffer = new Buffer(buffer, encoding)
    }
    for (var pos = 0; pos != buffer.length; ++pos) {

      switch(state) {
        case STATE_INITIAL:
          switch(buffer[pos]){
            case 0x30:
            case 0x31:
            case 0x32:
            case 0x33:
            case 0x34:
            case 0x35:
            case 0x36:
            case 0x37:
            case 0x38:
            case 0x39:
              state = STATE_STATE_STRING_LEN
              strLen = 0
              strLen += buffer[pos] - 0x30
              break
            case I:
              state = STATE_STATE_INTEGER
              _int  = 0
              neg   = false
              break
            case L:
              state = STATE_INITIAL
              depth += 1
              cb_list()
              break
            case D:
              state = STATE_INITIAL
              depth += 1
              cb_dict()
              break
            case E:
              state = STATE_INITIAL
              depth -= 1
              if (depth < 0) {
                throw new Error("end with no beginning: "+pos)
              } else {
                cb_end()
              }
              break
          }
          break;
        case STATE_STATE_STRING_LEN:
          if (integer(buffer[pos])) {
            strLen *= 10
            strLen += buffer[pos] - 0x30
          } else {
            str = new Buffer(strLen)
            pos -=1
            state = STATE_COLON
          }
          break
        case STATE_COLON:
          if (buffer[pos] != COLON) {
            throw new Error("not a colon at:"+pos.toString(16))
          }
          state = STATE_STRING
          // in case this is a zero length string, there's
          // no bytes to be collected.
          if (0 === strLen) {
            cb(new Buffer(0))
            state = STATE_INITIAL
          }
          break
        case STATE_STRING:
          if (0 === strLen) {
            cb(str)
            state = STATE_INITIAL
          } else {
            //str += String.fromCharCode(buffer[pos]) // not unicode safe..
            str[str.length-strLen] = buffer[pos]
            strLen -= 1
            if (0 === strLen) {
              cb(str)
              state = STATE_INITIAL
            }
          }
          break
        case STATE_STATE_INTEGER:
          state = STATE_INTEGER
          if (buffer[pos] == DASH) {
            neg = true  // handle neg and zero within value.
            break
          } // else fall through
        case STATE_INTEGER:
          if (integer(buffer[pos])) {
            _int *= 10
            _int += buffer[pos] - 0x30
          } else if (buffer[pos] == E) {
            var ret = neg ? 0 - _int : _int
            cb(ret)
            state = STATE_INITIAL
          } else {
            throw new Error("not part of int at:"+pos.toString(16))
          }
          break;
      } // switch state
    } // for buffer
  } // function parse

  var integer = function (value) {
    // check that value is a number and that
    // its value is ascii integer.
    if (! (typeof(value)==='number') ) {
      return false
    }
    return between(value, 0x30, 0x39)
  }
  var between = function(val, min, max) {
    return (min <= val  && val <= max)
  }

} // end BdecodeSMachine

/*
 * The exported decode functionality.
 */
var Bdecode = function () {
  // markers
  var DICTIONARY_START = {}
  var LIST_START       = {}

  var Context  = function() {
    var self  = this
    var stack = []

    this.cb   = function(o){
      stack.push(o)
    }
    this.cb_list = function(){
      self.cb(LIST_START)
    }
    this.cb_dict = function(){
      self.cb(DICTIONARY_START)
    }

    this.cb_end  = function(){

      // unwind the stack until either a DICTIONARY_START or LIST_START is
      // found, create arr or hash, stick unwound stack on, push arr or hash
      // back onto stack

      var obj       = null,
          tmp_stack = []

      while ( undefined !== (obj = stack.pop()) ) {
        if (LIST_START === obj) {
          var obj2 = null
          var list = []
          while( undefined !== (obj2 = tmp_stack.pop()) ) {
            list.push(obj2)
          }
          self.cb(list)
          break
        } else if (DICTIONARY_START === obj) {
          var key = null,
              val = null,
              dic = {}
          while ( (undefined !== (key = tmp_stack.pop())) && (undefined !== (val = tmp_stack.pop())) ) {
            dic[key.toString()] = val
          }

          if (undefined !== key && undefined === dic[key]) {
            throw new Error("uneven number of keys and values A")
          }
          self.cb(dic)
          break
        } else {
          tmp_stack.push(obj)
        }
      }
      if (tmp_stack.length > 0) {
        // could this case even occur?
        throw new Error("uneven number of keys and values B")
      }
    }
    this.result = function () {
      return stack
    }
  }

  var self      = this,
      ctx       = new Context(),
      smachine  = new BdecodeSMachine(ctx.cb, ctx.cb_list, ctx.cb_dict, ctx.cb_end)

  this.result    = function () {
    if (!smachine.consistent()) {
      throw new Error("not in consistent state. More bytes coming?")
    }
    return ctx.result()
  }

  this.decode = function(buf, encoding) {
    smachine.parse(buf, encoding)
  }
}

var Bencode = function(obj) {
  var self = this
  var to_encode = obj
  var buffer = null

  switch (typeof (obj) ) {
    case "string":
      return encodeString(obj)
    case "number":
      return encodeNumber(obj)
      break
    case "object":
      if (obj instanceof Array) {
        return encodeList(obj)
      } else if (Buffer.isBuffer(obj)) {
        return encodeBuffer(obj)
      }

      {
        // assume it's a hash
        return encodeDict(obj)
      }
  }

  function encodeString(obj) {
    var blen = Buffer.byteLength(obj),
        len  = blen.toString(10),
        buf  = new Buffer(len.length + 1 + blen)

    buf.write(len, 0, "ascii")
    buf.write(":", len.length, "ascii")
    buf.write(obj, len.length+1, "utf8")

    return buf
  }

  function encodeNumber(num) {
    var n   = num.toString(10),
        buf = new Buffer(n.length+2)

    buf.write("i", 0)
    buf.write(n, 1)
    buf.write("e", n.length+1)

    return buf
  }

  function encodeDict(obj) {
    var func = function (obj, pos) {
      var keys = Object.keys(obj).sort()
      for (var i in keys) {
        var key = Bencode(keys[i]),
            val = Bencode(obj[keys[i]])
        ensure(key.length + val.length, pos)
        key.copy(buffer, pos, 0)
        pos += key.length
        val.copy(buffer, pos, 0)
        pos += val.length
      }
      return pos
    }
    return assemble(obj, "d", func)
  }

  function encodeList(obj) {
    var func = function(obj, pos) {
      obj.forEach (function(o){
        var elem = Bencode(o)

        ensure(elem.length, pos)
        elem.copy(buffer, pos, 0)
        pos += elem.length
      })
      return pos
    }
    return assemble(obj, "l", func)
  }

  function encodeBuffer(obj) {
    var len = obj.length.toString(10),
        buf = new Buffer(len.length+1+obj.length);

    buf.write(len, 0, "ascii")
    buf.write(":", len.length, "ascii")
    obj.copy(buf, len.length+1, 0)

    return buf
  }

  function assemble (obj, prefix, func) {
    var pos = 0

    ensure(1024, 0)
    buffer.write(prefix, pos++)

    pos = func(obj, pos)
    ensure(1, pos)

    buffer.write("e", pos++)
    return buffer.slice(0, pos)
  }

  function ensure (num, pos) {
    if (!buffer) {
      buffer = new Buffer(num)
    } else {
      if (buffer.length > num+pos+1) {
        return
      } else {
        var buf2 = new Buffer(buffer.length + num)
        buffer.copy(buf2, 0, 0)
        buffer = buf2
      }
    }
  }
}

function decode (buffer, encoding) {
  var decoder = new Bdecode()

  decoder.decode(buffer, encoding)
  return decoder.result()[0]
}

function Stream (options) {
  options = options || {};
  options.objectMode = true;
  Transform.call(this, options);
  this._decoder = new Bdecode()
}

inherits(Stream, Transform);

Stream.prototype._transform = function (chunk, encoding, callback) {
  try {
    this._decoder.decode(chunk, encoding)
    callback(null);
  } catch(err) {
    callback(err);
  }
}

Stream.prototype._flush = function (callback) {
  this.push(this._decoder.result()[0]);
  callback(null);
}

exports.encode  = Bencode
exports.decoder = Bdecode
exports.decode  = decode
exports.Stream  = Stream

<commit_msg>improve the code style, fix incorrect usage<commit_after>/*jshint es5:false, asi:true, quotmark:false, eqeqeq:false, forin: false */

/*
 * (c) 2011 Tim Becker, see file LICENSE for details
 */

/*
 * Provides functionality for bencoding and decoding as use in
 * bittorrent and described in: http://www.bittorrent.org/beps/bep_0003.html
 *
 * Encoding is as follows:
 *
 *    var benc  = require('bncode'),
 *        exmp = {}
 *
 *    exmp.bla = "blup"
 *    exmp.foo = "bar"
 *    exmp.one = 1
 *    exmp.woah = {}
 *    exmp.woah.arr = []
 *    exmp.woah.arr.push(1)
 *    exmp.woah.arr.push(2)
 *    exmp.woah.arr.push(3)
 *    exmp.str = new Buffer("Buffers work too")
 *
 *    var bencBuffer = benc.encode(exmp) i
 *
 *    // d3:bla4:blup3:foo3:bar3:onei1e4:woahd3:arr \
 *    // li1ei2ei3eee3:str16:Buffers work tooe
 *
 *
 * Decoding will work in progressively, e.g. if you're receiving partial
 * bencoded strings on the network:
 *
 *    var benc = require("bncode"),
 *        buf  = null
 *
 *    decoder = new bncode.decoder()
 *    while (buf = receiveData()) {
 *      decoder.decode(buf)
 *    }
 *
 *    log(decoder.result())
 *
 *
 * Or "all in one"
 *
 *    var benc = require("bncode"),
 *        buf  = getBuffer(),
 *        dec  = benc.decode(buf)
 *
 *    log(dec.bla)
 *
 *
 * There are some subtleties concerning bencoded strings. These are
 * decoded as Buffer objects because they are just strings of raw bytes
 * and as such would wreak havoc with multi byte strings in javascript.
 *
 * The exception to this is strings that appear as keys in bencoded
 * dicts. These are decoded as Javascript Strings, as they should always
 * be strings of (ascii) characters and if they weren't decoded as JS
 * Strings, dict's would map to Javascript objects with properties.
 *
 */

exports.encode  = Bencode
exports.decoder = Bdecode
exports.decode  = decode
exports.Stream  = Stream

var inherits = require('util').inherits
var Transform = require('stream').Transform

var I     = 'i'.charCodeAt(0)
var L     = 'l'.charCodeAt(0)
var E     = 'e'.charCodeAt(0)
var D     = 'd'.charCodeAt(0)
var COLON = ':'.charCodeAt(0)
var DASH  = '-'.charCodeAt(0)

var STATE_INITIAL          = 0
var STATE_STATE_STRING_LEN = STATE_INITIAL          + 1
var STATE_STRING           = STATE_STATE_STRING_LEN + 1
var STATE_COLON            = STATE_STRING           + 1
var STATE_STATE_INTEGER    = STATE_COLON            + 1
var STATE_INTEGER          = STATE_STATE_INTEGER    + 1

/*
 * This is the internal state machine for taking apart bencoded strings,
 * it's not exposed in the eports.  It's constructed with four callbacks
 * that get fired when:
 *
 * cb: a value (string or number) is encountered
 * cb_list: a begin list element is encountered
 * cb_dict: a beginning of dictionary is encountered.
 * cd_end: an end element, wheter dict or list is encountered
 *
 * Once constructed, the machine may be fed with buffers containing
 * partial bencoded string. Call `consistent` to check whether the
 * current state is consistent, e.g. not smack-dap in the middle of
 * a string or a number and if the dict, list and end calls balance
 *
 *
 * The functionality being so rudimentary requires some more state and
 * logic in the code executing the machine, for this see Context, below.
 *
 */

function BdecodeSMachine (cb, cb_list, cb_dict, cb_end) {
  var depth = 0
  var state = STATE_INITIAL

  this.consistent = function () {
    return state === STATE_INITIAL && depth === 0
  }

  var strLen = 0
  var str    = ''
  var _int   = 0
  var neg    = false

  this.parse = function (buffer, encoding) {
    if (typeof buffer === 'string') {
      buffer = new Buffer(buffer, encoding || 'utf8')
    }

    for (var pos = 0; pos !== buffer.length; ++pos) {
      switch (state) {
        case STATE_INITIAL:
          switch (buffer[pos]) {
            case 0x30:
            case 0x31:
            case 0x32:
            case 0x33:
            case 0x34:
            case 0x35:
            case 0x36:
            case 0x37:
            case 0x38:
            case 0x39:
              state = STATE_STATE_STRING_LEN
              strLen = 0
              strLen += buffer[pos] - 0x30
              break
            case I:
              state = STATE_STATE_INTEGER
              _int  = 0
              neg   = false
              break
            case L:
              state = STATE_INITIAL
              depth += 1
              cb_list()
              break
            case D:
              state = STATE_INITIAL
              depth += 1
              cb_dict()
              break
            case E:
              state = STATE_INITIAL
              depth -= 1
              if (depth < 0) {
                throw new Error('end with no beginning: ' + pos)
              } else {
                cb_end()
              }
              break
          }
          break
        case STATE_STATE_STRING_LEN:
          if (integer(buffer[pos])) {
            strLen *= 10
            strLen += buffer[pos] - 0x30
          } else {
            str = new Buffer(strLen)
            pos -=1
            state = STATE_COLON
          }
          break
        case STATE_COLON:
          if (buffer[pos] !== COLON) {
            throw new Error('not a colon at: ' + pos.toString(16))
          }
          state = STATE_STRING
          // in case this is a zero length string, there's
          // no bytes to be collected.
          if (0 === strLen) {
            cb(new Buffer(0))
            state = STATE_INITIAL
          }
          break
        case STATE_STRING:
          if (0 === strLen) {
            cb(str)
            state = STATE_INITIAL
          } else {
            //str += String.fromCharCode(buffer[pos]) // not unicode safe..
            str[str.length-strLen] = buffer[pos]
            strLen -= 1
            if (0 === strLen) {
              cb(str)
              state = STATE_INITIAL
            }
          }
          break
        case STATE_STATE_INTEGER:
          state = STATE_INTEGER
          if (buffer[pos] === DASH) {
            neg = true  // handle neg and zero within value.
            break
          } // else fall through
        case STATE_INTEGER:
          if (integer(buffer[pos])) {
            _int *= 10
            _int += buffer[pos] - 0x30
          } else if (buffer[pos] === E) {
            var ret = neg ? 0 - _int : _int
            cb(ret)
            state = STATE_INITIAL
          } else {
            throw new Error('not part of int at:'+pos.toString(16))
          }
          break
      } // switch state
    } // for buffer
  } // function parse

  function integer (value) {
    // check that value is a number and that
    // its value is ascii integer.
    if (typeof value !== 'number') {
      return false
    }
    return between(value, 0x30, 0x39)
  }
  function between (val, min, max) {
    return (min <= val  && val <= max)
  }

} // end BdecodeSMachine

/*
 * The exported decode functionality.
 */
function Bdecode () {
  // markers
  var DICTIONARY_START = {}
  var LIST_START       = {}

  var Context  = function () {
    var self  = this
    var stack = []

    this.cb = function (o) {
      stack.push(o)
    }
    this.cb_list = function () {
      self.cb(LIST_START)
    }
    this.cb_dict = function () {
      self.cb(DICTIONARY_START)
    }

    this.cb_end = function () {

      // unwind the stack until either a DICTIONARY_START or LIST_START is
      // found, create arr or hash, stick unwound stack on, push arr or hash
      // back onto stack

      var obj       = null
      var tmp_stack = []

      while ((obj = stack.pop()) !== undefined) {
        if (LIST_START === obj) {
          var obj2 = null
          var list = []
          while((obj2 = tmp_stack.pop()) !== undefined) {
            list.push(obj2)
          }
          self.cb(list)
          break
        } else if (DICTIONARY_START === obj) {
          var key = null
          var val = null
          var dic = {}
          while ((key = tmp_stack.pop()) !== undefined && (val = tmp_stack.pop()) !== undefined) {
            dic[key.toString()] = val
          }

          if (key !== undefined && dic[key] === undefined) {
            throw new Error('uneven number of keys and values A')
          }
          self.cb(dic)
          break
        } else {
          tmp_stack.push(obj)
        }
      }
      if (tmp_stack.length > 0) {
        // could this case even occur?
        throw new Error('uneven number of keys and values B')
      }
    }
    this.result = function () {
      return stack
    }
  }

  var self     = this
  var ctx      = new Context()
  var smachine = new BdecodeSMachine(ctx.cb, ctx.cb_list, ctx.cb_dict, ctx.cb_end)

  this.result = function () {
    if (!smachine.consistent()) {
      throw new Error('not in consistent state. More bytes coming?')
    }
    return ctx.result()
  }

  this.decode = function (buf, encoding) {
    smachine.parse(buf, encoding)
  }
}

function Bencode (obj) {
  var self = this
  var to_encode = obj
  var buffer = null

  switch (typeof obj) {
    case 'string':
      return encodeString(obj)
    case 'number':
      return encodeNumber(obj)
    case 'object':
      if (obj instanceof Array) {
        return encodeList(obj)
      } else if (Buffer.isBuffer(obj)) {
        return encodeBuffer(obj)
      } else {
        // assume it's a hash
        return encodeDict(obj)
      }
  }

  function encodeString (obj) {
    var blen = Buffer.byteLength(obj)
    var len  = blen.toString(10)
    var buf  = new Buffer(len.length + 1 + blen)

    buf.write(len, 0, 'ascii')
    buf.write(':', len.length, 'ascii')
    buf.write(obj, len.length + 1, 'utf8')

    return buf
  }

  function encodeNumber (num) {
    var n   = num.toString(10)
    var buf = new Buffer(n.length + 2)

    buf.write('i', 0)
    buf.write(n, 1)
    buf.write('e', n.length + 1)

    return buf
  }

  function encodeDict (obj) {
    var func = function (obj, pos) {
      var keys = Object.keys(obj).sort()
      keys.forEach(function (key) {
        var val = new Bencode(obj[key])
        key = new Bencode(key)

        ensure(key.length + val.length, pos)
        key.copy(buffer, pos, 0)
        pos += key.length
        val.copy(buffer, pos, 0)
        pos += val.length
      })
      return pos
    }
    return assemble(obj, 'd', func)
  }

  function encodeList (obj) {
    var func = function(obj, pos) {
      obj.forEach(function (o) {
        var elem = new Bencode(o)

        ensure(elem.length, pos)
        elem.copy(buffer, pos, 0)
        pos += elem.length
      })
      return pos
    }
    return assemble(obj, 'l', func)
  }

  function encodeBuffer (obj) {
    var len = obj.length.toString(10)
    var buf = new Buffer(len.length + 1 + obj.length)

    buf.write(len, 0, 'ascii')
    buf.write(':', len.length, 'ascii')
    obj.copy(buf, len.length + 1, 0)

    return buf
  }

  function assemble (obj, prefix, func) {
    var pos = 0

    ensure(1024, 0)
    buffer.write(prefix, pos++)

    pos = func(obj, pos)
    ensure(1, pos)

    buffer.write('e', pos++)
    return buffer.slice(0, pos)
  }

  function ensure (num, pos) {
    if (!buffer) {
      buffer = new Buffer(num)
    } else {
      if (buffer.length > num + pos + 1) {
        return
      } else {
        var buf2 = new Buffer(buffer.length + num)
        buffer.copy(buf2, 0, 0)
        buffer = buf2
      }
    }
  }
}

function decode (buffer, encoding) {
  var decoder = new Bdecode()

  decoder.decode(buffer, encoding)
  return decoder.result()[0]
}

function Stream (options) {
  options = options || {}
  options.objectMode = true
  Transform.call(this, options)
  this._decoder = new Bdecode()
}

inherits(Stream, Transform)

Stream.prototype._transform = function (chunk, encoding, callback) {
  try {
    this._decoder.decode(chunk, encoding)
    callback(null)
  } catch(err) {
    callback(err)
  }
}

Stream.prototype._flush = function (callback) {
  this.push(this._decoder.result()[0])
  callback(null)
}
<|endoftext|>


<commit_before>window.onload = function animateJSON() {

    var animator = JSON.parse(localStorage.getItem('stringJSON'));
    var mainDiv = document.getElementById("outputJSON");

    const processDivClassName = "processes";
    const frameDivClassName = "frame"
    const frameTitleClassName = "frameTitle"
    const lifelines = "lifeLine";
    const activatorClassName = "activator"
    const arrowDivClassName = "arrows";
    const messageDivClassName = "messages";

    for(var i = 0; i < animator.processes.length; i++) {

        var div = document.createElement("div");
        div.className = processDivClassName;
        div.innerHTML =
            animator.processes[i].name.toString() + ": " +
            animator.processes[i].class.toString();
        mainDiv.appendChild(div);

        var lifeLineDiv = document.createElement("div");
        lifeLineDiv.className = lifelines;
        lifeLineDiv.id = animator.processes[i].name.toString();
        var activatorDiv = document.createElement("div");
        activatorDiv.className = activatorClassName;
        div.appendChild(lifeLineDiv);
        lifeLineDiv.appendChild(activatorDiv);
    }

    var superArray = Object.keys(animator.diagram);
     //if (superArray.hasOwnProperty('node'))
    for (var i = 0; i < superArray.length; i++) {
        if (superArray[i] === 'node') {
            var frameDiv = document.createElement("div");
            frameDiv.className = frameDivClassName;
            frameDiv.id = animator.diagram.node.toString();
            var frameTitle = document.createElement("div");
            frameTitle.className = frameTitleClassName;
            frameTitle.id = animator.diagram.node.toString() + "Title";
            frameTitle.innerHTML = animator.diagram.node.toString();
            mainDiv.appendChild(frameDiv);
            frameDiv.appendChild(frameTitle);
        }
    }

    var a = 50;
    var counter = 0;

    for(var j = 0; j < animator.diagram.content.length; j++) {

        for (var i = 0; i < animator.diagram.content[j].content.length; i++) {

            var startPosition = getPosition(document.querySelector("#" + animator.diagram.content[j].content[i].from.toString()));
            var endPosition = getPosition(document.querySelector("#" + animator.diagram.content[j].content[i].to.toString()));

            var arrow = document.createElement("div");
            arrow.className = arrowDivClassName;
            var svg = document.createElementNS('http://www.w3.org/2000/svg', "svg");
            var polygon = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
            var message = document.createElement("div");
            message.className = messageDivClassName;
            svg.setAttribute("preserveAspectRatio", "xMaxYMid slice");

            svg.setAttribute("viewBox", "0 0 1400 14");
            // decides what direction the arrow will go, and makes the length of the arrows

            if (startPosition.x > endPosition.x) {

                var arrowLengthLeft = startPosition.x - endPosition.x;
                svg.setAttribute("width", arrowLengthLeft + "px");
                arrow.style.transform = "rotate(180deg)";
                arrow.style.left = startPosition.x - 30 + 'px';
                message.style.left = arrowLengthLeft / 2 + 'px';
                message.style.top = 40 + 'px';
                message.style.transform = "rotate(180deg)";
            }
            else {

                var arrowLengthRight = endPosition.x - startPosition.x;
                svg.setAttribute("width", arrowLengthRight + "px");
                arrow.style.left = startPosition.x - 30 + 'px';
                message.style.left = arrowLengthRight / 2 + 'px';
            }

            svg.setAttribute("height", "14");
            polygon.setAttribute("points", "1400,7 1385,1 1390,6 0,6 0,8 1390,8 1385,13 1400,7");
            arrow.className = arrowDivClassName;

            message.innerHTML =
                animator.diagram.content[j].content[i].message.toString();

            // making so every arrow is on their own line with 50px heigth difference
            arrow.style.top = startPosition.y + counter * a - 20 + 'px';
            counter++;
            arrow.style.right = ((startPosition.x) - (startPosition.x - endPosition.x)) + 'px';

            // arrow.innerHTML =
            //     animator.diagram.content[0].content[i].message.toString();

            // arrow.style.position = "absolute";
            // arrow.style.left = document.getElementById(animator.diagram.content[0].content[i].from.toString()).getBoundingClientRect().left.toString() + 'px';
            // arrow.style.right = document.getElementById(animator.diagram.content[0].content[i].from.toString()).getBoundingClientRect().right.toString() + 'px';
            // arrow.style.top = document.getElementById(animator.diagram.content[0].content[i].from.toString()).getBoundingClientRect().top.toString() + 'px';
            // console.log(document.getElementById(animator.diagram.content[0].content[i].from.toString()).getBoundingClientRect().left.toString());

            arrow.appendChild(message);
            svg.appendChild(polygon);
            arrow.appendChild(svg);
            if (frameDiv === undefined) {
                mainDiv.appendChild(arrow);
            }
            else {
                frameDiv.appendChild(arrow);
                var element = document.getElementById('par');
                style = window.getComputedStyle(element);
                heightVal = parseInt(style.getPropertyValue('height').split("p")[0]);
                newVal = heightVal + 50;
                element.style.height = newVal + 'px';
             }
        }

    }
};

// var arrows = [];
//
// function Arrow(from, to, message) {
//     this.from = from;
//     this.to = to;
//     this.message = message;
// }
//
// function addArrow(from, to, message) {
//     var msg = new Arrow(from, to, message);
//     arrows.push(msg);
// }

// Helper function to get an element's exact position
function getPosition(el) {
    var xPos = 0;
    var yPos = 0;
    while (el) {
        if (el.tagName == "BODY") {
            // deal with browser quirks with body/window/document and page scroll
            var xScroll = el.scrollLeft || document.documentElement.scrollLeft;
            var yScroll = el.scrollTop || document.documentElement.scrollTop;

            xPos += (el.offsetLeft - xScroll + el.clientLeft);
            yPos += (el.offsetTop - yScroll + el.clientTop);
        } else {
            // for all other non-BODY elements
            xPos += (el.offsetLeft - el.scrollLeft + el.clientLeft);
            yPos += (el.offsetTop - el.scrollTop + el.clientTop);
        }

        el = el.offsetParent;
    }
    return {
        x: xPos,
        y: yPos
    };
}<commit_msg>re-added the log in animator.js<commit_after>window.onload = function animateJSON() {

    var animator = JSON.parse(localStorage.getItem('stringJSON'));
    var mainDiv = document.getElementById("outputJSON");

    const processDivClassName = "processes";
    const frameDivClassName = "frame"
    const frameTitleClassName = "frameTitle"
    const lifelines = "lifeLine";
    const activatorClassName = "activator"
    const arrowDivClassName = "arrows";
    const messageDivClassName = "messages";

    for(var i = 0; i < animator.processes.length; i++) {

        var div = document.createElement("div");
        div.className = processDivClassName;
        div.innerHTML =
            animator.processes[i].name.toString() + ": " +
            animator.processes[i].class.toString();
        mainDiv.appendChild(div);

        var lifeLineDiv = document.createElement("div");
        lifeLineDiv.className = lifelines;
        lifeLineDiv.id = animator.processes[i].name.toString();
        var activatorDiv = document.createElement("div");
        activatorDiv.className = activatorClassName;
        div.appendChild(lifeLineDiv);
        lifeLineDiv.appendChild(activatorDiv);
    }

    var superArray = Object.keys(animator.diagram);
     //if (superArray.hasOwnProperty('node'))
    for (var i = 0; i < superArray.length; i++) {
        if (superArray[i] === 'node') {
            var frameDiv = document.createElement("div");
            frameDiv.className = frameDivClassName;
            frameDiv.id = animator.diagram.node.toString();
            var frameTitle = document.createElement("div");
            frameTitle.className = frameTitleClassName;
            frameTitle.id = animator.diagram.node.toString() + "Title";
            frameTitle.innerHTML = animator.diagram.node.toString();
            mainDiv.appendChild(frameDiv);
            frameDiv.appendChild(frameTitle);
        }
    }

    var a = 50;
    var counter = 0;

    for(var j = 0; j < animator.diagram.content.length; j++) {

        for (var i = 0; i < animator.diagram.content[j].content.length; i++) {

            var startPosition = getPosition(document.querySelector("#" + animator.diagram.content[j].content[i].from.toString()));
            var endPosition = getPosition(document.querySelector("#" + animator.diagram.content[j].content[i].to.toString()));

            var arrow = document.createElement("div");
            arrow.className = arrowDivClassName;
            var svg = document.createElementNS('http://www.w3.org/2000/svg', "svg");
            var polygon = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
            var message = document.createElement("div");
            message.className = messageDivClassName;
            svg.setAttribute("preserveAspectRatio", "xMaxYMid slice");

            svg.setAttribute("viewBox", "0 0 1400 14");
            // decides what direction the arrow will go, and makes the length of the arrows

            if (startPosition.x > endPosition.x) {

                var arrowLengthLeft = startPosition.x - endPosition.x;
                svg.setAttribute("width", arrowLengthLeft + "px");
                arrow.style.transform = "rotate(180deg)";
                arrow.style.left = startPosition.x - 30 + 'px';
                message.style.left = arrowLengthLeft / 2 + 'px';
                message.style.top = 40 + 'px';
                message.style.transform = "rotate(180deg)";
            }
            else {

                var arrowLengthRight = endPosition.x - startPosition.x;
                svg.setAttribute("width", arrowLengthRight + "px");
                arrow.style.left = startPosition.x - 30 + 'px';
                message.style.left = arrowLengthRight / 2 + 'px';
            }

            svg.setAttribute("height", "14");
            polygon.setAttribute("points", "1400,7 1385,1 1390,6 0,6 0,8 1390,8 1385,13 1400,7");
            arrow.className = arrowDivClassName;

            message.innerHTML =
                animator.diagram.content[j].content[i].message.toString();

            // making so every arrow is on their own line with 50px heigth difference
            arrow.style.top = startPosition.y + counter * a - 20 + 'px';
            counter++;
            arrow.style.right = ((startPosition.x) - (startPosition.x - endPosition.x)) + 'px';

            // arrow.innerHTML =
            //     animator.diagram.content[0].content[i].message.toString();

            // arrow.style.position = "absolute";
            // arrow.style.left = document.getElementById(animator.diagram.content[0].content[i].from.toString()).getBoundingClientRect().left.toString() + 'px';
            // arrow.style.right = document.getElementById(animator.diagram.content[0].content[i].from.toString()).getBoundingClientRect().right.toString() + 'px';
            // arrow.style.top = document.getElementById(animator.diagram.content[0].content[i].from.toString()).getBoundingClientRect().top.toString() + 'px';
            // console.log(document.getElementById(animator.diagram.content[0].content[i].from.toString()).getBoundingClientRect().left.toString());

            arrow.appendChild(message);
            svg.appendChild(polygon);
            arrow.appendChild(svg);
            if (frameDiv === undefined) {
                mainDiv.appendChild(arrow);
            }
            else {
                frameDiv.appendChild(arrow);
                var element = document.getElementById('par');
                style = window.getComputedStyle(element);
                heightVal = parseInt(style.getPropertyValue('height').split("p")[0]);
                newVal = heightVal + 50;
                element.style.height = newVal + 'px';
             }
        }

    }

    var ul = document.getElementById("logList");
    var tot = 0;
    for(var e = 0; e < animator.diagram.content.length; e++){

        for(var i = 0; i < animator.diagram.content[e].content.length; i++){
            var li = document.createElement("li");
            li.setAttribute('id',((tot+1)+": Sending message From: " +
            animator.diagram.content[e].content[i].from.toString() +" To: "+
            animator.diagram.content[e].content[i].to.toString() +" || Message: "+
            animator.diagram.content[e].content[i].message.toString()));
            li.appendChild(document.createTextNode((tot+1)+": Sending message From: " +
            animator.diagram.content[e].content[i].from.toString() +" To: "+
            animator.diagram.content[e].content[i].to.toString() +" || Message: "+
            animator.diagram.content[e].content[i].message.toString()));
            ul.appendChild(li);
            tot++;
        }
    }

};

// var arrows = [];
//
// function Arrow(from, to, message) {
//     this.from = from;
//     this.to = to;
//     this.message = message;
// }
//
// function addArrow(from, to, message) {
//     var msg = new Arrow(from, to, message);
//     arrows.push(msg);
// }

// Helper function to get an element's exact position
function getPosition(el) {
    var xPos = 0;
    var yPos = 0;
    while (el) {
        if (el.tagName == "BODY") {
            // deal with browser quirks with body/window/document and page scroll
            var xScroll = el.scrollLeft || document.documentElement.scrollLeft;
            var yScroll = el.scrollTop || document.documentElement.scrollTop;

            xPos += (el.offsetLeft - xScroll + el.clientLeft);
            yPos += (el.offsetTop - yScroll + el.clientTop);
        } else {
            // for all other non-BODY elements
            xPos += (el.offsetLeft - el.scrollLeft + el.clientLeft);
            yPos += (el.offsetTop - el.scrollTop + el.clientTop);
        }

        el = el.offsetParent;
    }
    return {
        x: xPos,
        y: yPos
    };
}<|endoftext|>


<commit_before>window.onload = function animateJSON() {

    var animator = JSON.parse(localStorage.getItem('stringJSON'));
    var mainDiv = document.getElementById("outputJSON");

    const processDivClassName = "processes";
    const frameDivClassName = "frame";
    const frameTitleClassName = "frameTitle";
    const lifelines = "lifeLine";
    const activatorClassName = "activator";
    const arrowDivClassName = "arrowLtoR";
    const arrowDivClassName2 = "arrowRtoL";
    const messageDivClassName = "messages";

    for(var i = 0; i < animator.processes.length; i++) {

        var div = document.createElement("div");
        div.className = processDivClassName;
        div.innerHTML =
            animator.processes[i].name.toString() + ": " +
            animator.processes[i].class.toString();
        mainDiv.appendChild(div);

        var lifeLineDiv = document.createElement("div");
        lifeLineDiv.className = lifelines;
        lifeLineDiv.id = animator.processes[i].name.toString();
        var activatorDiv = document.createElement("div");
        activatorDiv.className = activatorClassName;
        div.appendChild(lifeLineDiv);
        lifeLineDiv.appendChild(activatorDiv);
    }

    var superArray = Object.keys(animator.diagram);
     //if (superArray.hasOwnProperty('node'))
    for (var i = 0; i < superArray.length; i++) {
        if (superArray[i] === 'node') {
            var frameDiv = document.createElement("div");
            frameDiv.className = frameDivClassName;
            frameDiv.id = animator.diagram.node.toString();
            var frameTitle = document.createElement("div");
            frameTitle.className = frameTitleClassName;
            frameTitle.id = animator.diagram.node.toString() + "Title";
            frameTitle.innerHTML = animator.diagram.node.toString();
            mainDiv.appendChild(frameDiv);
            frameDiv.appendChild(frameTitle);
        }
    }

    var a = 50;
    var counter = 0;

    for(var j = 0; j < animator.diagram.content.length; j++) {

        if(j !== 0) {
            var lineBreak = document.createElement('hr');
          if (frameDiv !== undefined) {
            //frameDiv.appendChild(lineBreak);
            }
        }

        for (var i = 0; i < animator.diagram.content[j].content.length; i++) {

        }
    }

createArrow(animator, 0, 0, 0, frameDiv, mainDiv);
createLog(animator, 0, 0, 0);

};

function createArrow(animator, j, i, counter, frameDiv,mainDiv){

     if(animator.diagram.content[j].content.length === i){
                i = 0;
                j++;

                var lineBreak = document.createElement('hr');
                if (frameDiv != undefined) {
                 frameDiv.appendChild(lineBreak);
                }
             }

const processDivClassName = "processes";
    const frameDivClassName = "frame";
    const frameTitleClassName = "frameTitle";
    const lifelines = "lifeLine";
    const activatorClassName = "activator";
    const arrowDivClassName = "arrowLtoR";
    const arrowDivClassName2 = "arrowRtoL";
    const messageDivClassName = "messages";

            var startPosition = getPosition(document.querySelector("#" + animator.diagram.content[j].content[i].from.toString()));
            var endPosition = getPosition(document.querySelector("#" + animator.diagram.content[j].content[i].to.toString()));

            var arrow = document.createElement("div");
            var svg = document.createElementNS('http://www.w3.org/2000/svg', "svg");
            var polygon = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
            var message = document.createElement("div");
            message.className = messageDivClassName;
            svg.setAttribute("preserveAspectRatio", "xMaxYMid slice");

            svg.setAttribute("viewBox", "0 0 1400 14");
            // decides what direction the arrow will go, and makes the length of the arrows

            if (startPosition.x > endPosition.x) {
                arrow.className = arrowDivClassName2;
                var arrowLengthLeft = startPosition.x - endPosition.x;
                svg.setAttribute("width", arrowLengthLeft + "px");
                arrow.style.transform = "rotate(180deg)";
                arrow.style.left = startPosition.x - 30 + 'px';
                message.style.left = arrowLengthLeft / 2 + 'px';
                message.style.top = 40 + 'px';
                message.style.transform = "rotate(180deg)";
            }
            else {
                arrow.className = arrowDivClassName;
                var arrowLengthRight = endPosition.x - startPosition.x;
                svg.setAttribute("width", arrowLengthRight + "px");
                arrow.style.left = startPosition.x - 30 + 'px';
                message.style.left = arrowLengthRight / 2 + 'px';
            }

            svg.setAttribute("height", "14");
            polygon.setAttribute("points", "1400,7 1385,1 1390,6 0,6 0,8 1390,8 1385,13 1400,7");

            message.innerHTML =
                animator.diagram.content[j].content[i].message.toString();

            // making so every arrow is on their own line with 50px heigth difference
           // arrow.style.top = startPosition.y + counter * a - 20 + 'px';
            counter++;
            arrow.style.right = ((startPosition.x) - (startPosition.x - endPosition.x)) + 'px';

            // arrow.innerHTML =
            //     animator.diagram.content[0].content[i].message.toString();

            // arrow.style.position = "absolute";
            // arrow.style.left = document.getElementById(animator.diagram.content[0].content[i].from.toString()).getBoundingClientRect().left.toString() + 'px';
            // arrow.style.right = document.getElementById(animator.diagram.content[0].content[i].from.toString()).getBoundingClientRect().right.toString() + 'px';
            // arrow.style.top = document.getElementById(animator.diagram.content[0].content[i].from.toString()).getBoundingClientRect().top.toString() + 'px';
            // console.log(document.getElementById(animator.diagram.content[0].content[i].from.toString()).getBoundingClientRect().left.toString());

            arrow.appendChild(message);
            svg.appendChild(polygon);
            arrow.appendChild(svg);
            if (frameDiv === undefined) {
                mainDiv.appendChild(arrow);
            }
            else {
                frameDiv.appendChild(arrow);
             }

            if(animator.diagram.content[j].content[i+1] === undefined && j+1 === animator.diagram.content.length){}

                else{

             setTimeout(function () {
            // Do Something Here
            // Then recall the parent function to
            // create a recursive loop.
            i++;

            createArrow(animator, j, i, counter, frameDiv, mainDiv);
            }, 1000);
         }
}

function createLog(animator, i, e, total){
var ul = document.getElementById("logList");
    if(animator.diagram.content[e].content.length === i){
    i = 0;
    e++;
}

            var li = document.createElement("li");
            li.setAttribute('id',((total+1)+": Sending message From: " +
            animator.diagram.content[e].content[i].from.toString() +" To: "+
            animator.diagram.content[e].content[i].to.toString() +" || Message: "+
            animator.diagram.content[e].content[i].message.toString()));
            li.appendChild(document.createTextNode((total+1)+": Sending message From: " +
            animator.diagram.content[e].content[i].from.toString() +" To: "+
            animator.diagram.content[e].content[i].to.toString() +" || Message: "+
            animator.diagram.content[e].content[i].message.toString()));
            ul.appendChild(li);

    if(animator.diagram.content.length > e){

    if(animator.diagram.content[e].content[i+1] === undefined && e+1 === animator.diagram.content.length){}

    else{

    setTimeout(function () {
        // Do Something Here
        // Then recall the parent function to
        // create a recursive loop.
        i++;
        total++;
        createLog(animator, i, e, total);
        }, 1000);
    }
     //setTimeout(createLog(animator), 1000);
   }

}

// var arrows = [];
//
// function Arrow(from, to, message) {
//     this.from = from;
//     this.to = to;
//     this.message = message;
// }
//
// function addArrow(from, to, message) {
//     var msg = new Arrow(from, to, message);
//     arrows.push(msg);
// }

// Helper function to get an element's exact position

function getPosition(el) {
    var xPos = 0;
    var yPos = 0;
    while (el) {
        if (el.tagName == "BODY") {
            // deal with browser quirks with body/window/document and page scroll
            var xScroll = el.scrollLeft || document.documentElement.scrollLeft;
            var yScroll = el.scrollTop || document.documentElement.scrollTop;

            xPos += (el.offsetLeft - xScroll + el.clientLeft);
            yPos += (el.offsetTop - yScroll + el.clientTop);
        } else {
            // for all other non-BODY elements
            xPos += (el.offsetLeft - el.scrollLeft + el.clientLeft);
            yPos += (el.offsetTop - el.scrollTop + el.clientTop);
        }

        el = el.offsetParent;
    }
    return {
        x: xPos,
        y: yPos
    };
}<commit_msg>Replaced superArray with animatorDiagramArray in animator.js<commit_after>window.onload = function animateJSON() {

    var animator = JSON.parse(localStorage.getItem('stringJSON'));
    var mainDiv = document.getElementById("outputJSON");

    const processDivClassName = "processes";
    const frameDivClassName = "frame";
    const frameTitleClassName = "frameTitle";
    const lifelines = "lifeLine";
    const activatorClassName = "activator";
    const arrowDivClassName = "arrowLtoR";
    const arrowDivClassName2 = "arrowRtoL";
    const messageDivClassName = "messages";

    for(var i = 0; i < animator.processes.length; i++) {

        var div = document.createElement("div");
        div.className = processDivClassName;
        div.innerHTML =
            animator.processes[i].name.toString() + ": " +
            animator.processes[i].class.toString();
        mainDiv.appendChild(div);

        var lifeLineDiv = document.createElement("div");
        lifeLineDiv.className = lifelines;
        lifeLineDiv.id = animator.processes[i].name.toString();
        var activatorDiv = document.createElement("div");
        activatorDiv.className = activatorClassName;
        div.appendChild(lifeLineDiv);
        lifeLineDiv.appendChild(activatorDiv);
    }

    var animatorDiagramArray = Object.keys(animator.diagram);
     //if (animatorDiagramArray.hasOwnProperty('node'))
    for (var i = 0; i < animatorDiagramArray.length; i++) {
        if (animatorDiagramArray[i] === 'node') {
            var frameDiv = document.createElement("div");
            frameDiv.className = frameDivClassName;
            frameDiv.id = animator.diagram.node.toString();
            var frameTitle = document.createElement("div");
            frameTitle.className = frameTitleClassName;
            frameTitle.id = animator.diagram.node.toString() + "Title";
            frameTitle.innerHTML = animator.diagram.node.toString();
            mainDiv.appendChild(frameDiv);
            frameDiv.appendChild(frameTitle);
        }
    }

    var a = 50;
    var counter = 0;

    for(var j = 0; j < animator.diagram.content.length; j++) {

        if(j !== 0) {
            var lineBreak = document.createElement('hr');
          if (frameDiv !== undefined) {
            //frameDiv.appendChild(lineBreak);
            }
        }

        for (var i = 0; i < animator.diagram.content[j].content.length; i++) {

        }
    }

createArrow(animator, 0, 0, 0, frameDiv, mainDiv);
createLog(animator, 0, 0, 0);

};

function createArrow(animator, j, i, counter, frameDiv,mainDiv){

     if(animator.diagram.content[j].content.length === i){
                i = 0;
                j++;

                var lineBreak = document.createElement('hr');
                if (frameDiv != undefined) {
                 frameDiv.appendChild(lineBreak);
                }
             }

const processDivClassName = "processes";
    const frameDivClassName = "frame";
    const frameTitleClassName = "frameTitle";
    const lifelines = "lifeLine";
    const activatorClassName = "activator";
    const arrowDivClassName = "arrowLtoR";
    const arrowDivClassName2 = "arrowRtoL";
    const messageDivClassName = "messages";

            var startPosition = getPosition(document.querySelector("#" + animator.diagram.content[j].content[i].from.toString()));
            var endPosition = getPosition(document.querySelector("#" + animator.diagram.content[j].content[i].to.toString()));

            var arrow = document.createElement("div");
            var svg = document.createElementNS('http://www.w3.org/2000/svg', "svg");
            var polygon = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
            var message = document.createElement("div");
            message.className = messageDivClassName;
            svg.setAttribute("preserveAspectRatio", "xMaxYMid slice");

            svg.setAttribute("viewBox", "0 0 1400 14");
            // decides what direction the arrow will go, and makes the length of the arrows

            if (startPosition.x > endPosition.x) {
                arrow.className = arrowDivClassName2;
                var arrowLengthLeft = startPosition.x - endPosition.x;
                svg.setAttribute("width", arrowLengthLeft + "px");
                arrow.style.transform = "rotate(180deg)";
                arrow.style.left = startPosition.x - 30 + 'px';
                message.style.left = arrowLengthLeft / 2 + 'px';
                message.style.top = 40 + 'px';
                message.style.transform = "rotate(180deg)";
            }
            else {
                arrow.className = arrowDivClassName;
                var arrowLengthRight = endPosition.x - startPosition.x;
                svg.setAttribute("width", arrowLengthRight + "px");
                arrow.style.left = startPosition.x - 30 + 'px';
                message.style.left = arrowLengthRight / 2 + 'px';
            }

            svg.setAttribute("height", "14");
            polygon.setAttribute("points", "1400,7 1385,1 1390,6 0,6 0,8 1390,8 1385,13 1400,7");

            message.innerHTML =
                animator.diagram.content[j].content[i].message.toString();

            // making so every arrow is on their own line with 50px heigth difference
           // arrow.style.top = startPosition.y + counter * a - 20 + 'px';
            counter++;
            arrow.style.right = ((startPosition.x) - (startPosition.x - endPosition.x)) + 'px';

            // arrow.innerHTML =
            //     animator.diagram.content[0].content[i].message.toString();

            // arrow.style.position = "absolute";
            // arrow.style.left = document.getElementById(animator.diagram.content[0].content[i].from.toString()).getBoundingClientRect().left.toString() + 'px';
            // arrow.style.right = document.getElementById(animator.diagram.content[0].content[i].from.toString()).getBoundingClientRect().right.toString() + 'px';
            // arrow.style.top = document.getElementById(animator.diagram.content[0].content[i].from.toString()).getBoundingClientRect().top.toString() + 'px';
            // console.log(document.getElementById(animator.diagram.content[0].content[i].from.toString()).getBoundingClientRect().left.toString());

            arrow.appendChild(message);
            svg.appendChild(polygon);
            arrow.appendChild(svg);
            if (frameDiv === undefined) {
                mainDiv.appendChild(arrow);
            }
            else {
                frameDiv.appendChild(arrow);
             }

            if(animator.diagram.content[j].content[i+1] === undefined && j+1 === animator.diagram.content.length){}

                else{

             setTimeout(function () {
            // Do Something Here
            // Then recall the parent function to
            // create a recursive loop.
            i++;

            createArrow(animator, j, i, counter, frameDiv, mainDiv);
            }, 1000);
         }
}

function createLog(animator, i, e, total){
var ul = document.getElementById("logList");
    if(animator.diagram.content[e].content.length === i){
    i = 0;
    e++;
}

            var li = document.createElement("li");
            li.setAttribute('id',((total+1)+": Sending message From: " +
            animator.diagram.content[e].content[i].from.toString() +" To: "+
            animator.diagram.content[e].content[i].to.toString() +" || Message: "+
            animator.diagram.content[e].content[i].message.toString()));
            li.appendChild(document.createTextNode((total+1)+": Sending message From: " +
            animator.diagram.content[e].content[i].from.toString() +" To: "+
            animator.diagram.content[e].content[i].to.toString() +" || Message: "+
            animator.diagram.content[e].content[i].message.toString()));
            ul.appendChild(li);

    if(animator.diagram.content.length > e){

    if(animator.diagram.content[e].content[i+1] === undefined && e+1 === animator.diagram.content.length){}

    else{

    setTimeout(function () {
        // Do Something Here
        // Then recall the parent function to
        // create a recursive loop.
        i++;
        total++;
        createLog(animator, i, e, total);
        }, 1000);
    }
     //setTimeout(createLog(animator), 1000);
   }

}

// var arrows = [];
//
// function Arrow(from, to, message) {
//     this.from = from;
//     this.to = to;
//     this.message = message;
// }
//
// function addArrow(from, to, message) {
//     var msg = new Arrow(from, to, message);
//     arrows.push(msg);
// }

// Helper function to get an element's exact position

function getPosition(el) {
    var xPos = 0;
    var yPos = 0;
    while (el) {
        if (el.tagName == "BODY") {
            // deal with browser quirks with body/window/document and page scroll
            var xScroll = el.scrollLeft || document.documentElement.scrollLeft;
            var yScroll = el.scrollTop || document.documentElement.scrollTop;

            xPos += (el.offsetLeft - xScroll + el.clientLeft);
            yPos += (el.offsetTop - yScroll + el.clientTop);
        } else {
            // for all other non-BODY elements
            xPos += (el.offsetLeft - el.scrollLeft + el.clientLeft);
            yPos += (el.offsetTop - el.scrollTop + el.clientTop);
        }

        el = el.offsetParent;
    }
    return {
        x: xPos,
        y: yPos
    };
}<|endoftext|>


<commit_before>'use strict';

require('classtool');

function spec(b) {
  var RpcClient       = require('bitcore/RpcClient').class(),
//      networks         = require('bitcore/network'),
      BitcoreTransaction = require('bitcore/Transaction').class(),
      BitcoreBlock = require('bitcore/Block').class(),
      util         = require('bitcore/util/util'),
      config       = require('../config/config');

   var  rpc  = b.rpc || new RpcClient(config.bitcoind);

  function TransactionRpc() {
  }

  TransactionRpc._parseRpcResult = function(info) {
    var b  = new Buffer(info.hex,'hex');
    var tx = new BitcoreTransaction();
    tx.parse(b);

    // Inputs
    if (tx.isCoinBase())  {
      info.isCoinBase = true;
    }

    var n =0;
    info.vin.forEach(function(i) {
      i.n = n++;
    });

    // Outputs
    var valueOut = 0;
    info.vout.forEach( function(o) {
      valueOut += o.value;
    });
    info.valueOut = valueOut;
    info.size     = b.length;

    return info;
  };

  TransactionRpc.getRpcInfo = function(txid,  cb) {
    var Self = this;

    rpc.getRawTransaction(txid, 1, function(err, txInfo) {

      // Not found?
      if (err && err.code === -5) return cb();
      if (err) return cb(err);

      var info = Self._parseRpcResult(txInfo.result);

      return cb(null,info);
    });
  };

  return TransactionRpc;
}
module.defineClass(spec);

<commit_msg>fix rounding errs at valueOut<commit_after>'use strict';

require('classtool');

function spec(b) {
  var RpcClient       = require('bitcore/RpcClient').class(),
//      networks         = require('bitcore/network'),
      BitcoreTransaction = require('bitcore/Transaction').class(),
      BitcoreBlock = require('bitcore/Block').class(),
      util         = require('bitcore/util/util'),
      config       = require('../config/config');

   var  rpc  = b.rpc || new RpcClient(config.bitcoind);

  function TransactionRpc() {
  }

  TransactionRpc._parseRpcResult = function(info) {
    var b  = new Buffer(info.hex,'hex');
    var tx = new BitcoreTransaction();
    tx.parse(b);

    // Inputs
    if (tx.isCoinBase())  {
      info.isCoinBase = true;
    }

    var n =0;
    info.vin.forEach(function(i) {
      i.n = n++;
    });

    // Outputs
    var valueOutSat = 0;
    info.vout.forEach( function(o) {
      valueOutSat += o.value * util.COIN;
    });
    info.valueOut = parseInt(valueOutSat) / util.COIN;
    info.size     = b.length;

    return info;
  };

  TransactionRpc.getRpcInfo = function(txid,  cb) {
    var Self = this;

    rpc.getRawTransaction(txid, 1, function(err, txInfo) {

      // Not found?
      if (err && err.code === -5) return cb();
      if (err) return cb(err);

      var info = Self._parseRpcResult(txInfo.result);

      return cb(null,info);
    });
  };

  return TransactionRpc;
}
module.defineClass(spec);

<|endoftext|>


<commit_before>// Add support for Retina displays when using element attribute "ng-src".
// This module overrides the built-in directive "ng-src" with one which
// distinguishes between standard or high-resolution (Retina) displays.

(function(angular, undefined) {
  'use strict';
  var infix = '@2x',
    dataUrlRegex = /^data:([a-z]+\/[a-z]+(;[a-z\-]+\=[a-z\-]+)?)?(;base64)?,(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,
    allowedImageTypesRegex = /(png|jp[e]?g)$/,
    fadeInWhenLoaded = false,
    loadErrorHandler = angular.noop;

  var ngRetina = angular.module('ngRetina', []).config(['$provide', function($provide) {
    $provide.decorator('ngSrcDirective', ['$delegate', function($delegate) {
      $delegate[0].compile = function(element, attrs) {
        // intentionally empty to override the built-in directive ng-src
      };
      return $delegate;
    }]);
  }]);

  // From https://gist.github.com/bgrins/6194623#gistcomment-1671744
  function isDataUri(uri) {
    return new RegExp(/^\s*data:([a-z]+\/[a-z0-9\-\+]+(;[a-z\-]+\=[a-z0-9\-]+)?)?(;base64)?,[a-z0-9\!\$\&\'\,\(\)\*\+\,\;\=\-\.\_\~\:\@\/\?\%\s]*\s*$/i).test(uri);
  }

  ngRetina.provider('ngRetina', function() {
    this.setInfix = function setInfix(value) {
      infix = value;
    };

    this.setFadeInWhenLoaded = function setFadeInWhenLoaded(value) {
      fadeInWhenLoaded = value;
    };

    this.setLoadErrorHandler = function setLoadErrorHandler(handler) {
      loadErrorHandler = handler;
    };

    this.$get = angular.noop;
  });

  ngRetina.directive('ngSrc', ['$window', '$http', '$log', function($window, $http, $log) {
    var msie = parseInt(((/msie (\d+)/.exec($window.navigator.userAgent.toLowerCase()) || [])[1]), 10);
    var isRetina = ((function() {
      var mediaQuery = '(-webkit-min-device-pixel-ratio: 1.5), (min--moz-device-pixel-ratio: 1.5), ' +
        '(-o-min-device-pixel-ratio: 3/2), (min-resolution: 1.5dppx)';
      if ($window.devicePixelRatio > 1) {
        return true;
      }
      return $window.matchMedia && $window.matchMedia(mediaQuery).matches;
    })());

    function getHighResolutionURL(url) {
      var parts = url.split('.');
      if (parts.length < 2) {
        return url;
      }
      parts[parts.length - 2] += infix;
      return parts.join('.');
    }

    return function(scope, element, attrs) {
      function setImgSrc(imageUrl) {
        element.on('error', loadErrorHandler);

        attrs.$set('src', imageUrl);
        if (msie) {
          element.prop('src', imageUrl);
        }
      }

      function getSessionStorageItem(imageUrl) {
        var item;
        try {
          item = $window.sessionStorage.getItem(imageUrl);
        } catch (e) {
          $log.warn('sessionStorage not supported');
          item = imageUrl;
        }
        return item;
      }

      function setSessionStorageItem(imageUrl, imageUrl2x) {
        try {
          $window.sessionStorage.setItem(imageUrl, imageUrl2x);
        } catch (e) {
          $log.warn('sessionStorage not supported');
        }
      }

      function set2xVariant(imageUrl) {
        var imageUrl2x;
        if (angular.isUndefined(attrs.at2x)) {
          imageUrl2x = getSessionStorageItem(imageUrl);
        } else {
          imageUrl2x = attrs.at2x;
        }

        if (!imageUrl2x) {
          imageUrl2x = getHighResolutionURL(imageUrl);
          $http.head(imageUrl2x).
            success(function(data, status) {
            setImgSrc(imageUrl2x);
            setSessionStorageItem(imageUrl, imageUrl2x);
          })
          .error(function(data, status, headers, config) {
            setImgSrc(imageUrl);
            setSessionStorageItem(imageUrl, imageUrl);
          });
        } else {
          setImgSrc(imageUrl2x);
        }
      }

      attrs.$observe('ngSrc', function(imageUrl, oldValue) {
        if (!imageUrl) {
          return;
        }

        if (isDataUri(imageUrl)) {
          return setImgSrc(imageUrl);
        }

        if (fadeInWhenLoaded && !getSessionStorageItem('fadedIn-' + imageUrl)) {
          element.css({
            opacity: 0,
            '-o-transition': 'opacity 0.5s ease-out',
            '-moz-transition': 'opacity 0.5s ease-out',
            '-webkit-transition': 'opacity 0.5s ease-out',
            'transition': 'opacity 0.5s ease-out'
          });
          element.on('load', function() {
            setSessionStorageItem('fadedIn-' + imageUrl, true);
            element.css('opacity', 1);
          });
        }

        if (isRetina &&
            angular.isUndefined(attrs.noretina) &&
            element[0].tagName === 'IMG' &&
            imageUrl.match(allowedImageTypesRegex) &&
            !imageUrl.match(dataUrlRegex)) {
            set2xVariant(imageUrl);
          } else {
            setImgSrc(imageUrl);
          }
      });
    };
  }]);
})(window.angular);
<commit_msg>Change success/error to then/catch. Fixes #47<commit_after>// Add support for Retina displays when using element attribute "ng-src".
// This module overrides the built-in directive "ng-src" with one which
// distinguishes between standard or high-resolution (Retina) displays.

(function(angular, undefined) {
  'use strict';
  var infix = '@2x',
    dataUrlRegex = /^data:([a-z]+\/[a-z]+(;[a-z\-]+\=[a-z\-]+)?)?(;base64)?,(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,
    allowedImageTypesRegex = /(png|jp[e]?g)$/,
    fadeInWhenLoaded = false,
    loadErrorHandler = angular.noop;

  var ngRetina = angular.module('ngRetina', []).config(['$provide', function($provide) {
    $provide.decorator('ngSrcDirective', ['$delegate', function($delegate) {
      $delegate[0].compile = function(element, attrs) {
        // intentionally empty to override the built-in directive ng-src
      };
      return $delegate;
    }]);
  }]);

  // From https://gist.github.com/bgrins/6194623#gistcomment-1671744
  function isDataUri(uri) {
    return new RegExp(/^\s*data:([a-z]+\/[a-z0-9\-\+]+(;[a-z\-]+\=[a-z0-9\-]+)?)?(;base64)?,[a-z0-9\!\$\&\'\,\(\)\*\+\,\;\=\-\.\_\~\:\@\/\?\%\s]*\s*$/i).test(uri);
  }

  ngRetina.provider('ngRetina', function() {
    this.setInfix = function setInfix(value) {
      infix = value;
    };

    this.setFadeInWhenLoaded = function setFadeInWhenLoaded(value) {
      fadeInWhenLoaded = value;
    };

    this.setLoadErrorHandler = function setLoadErrorHandler(handler) {
      loadErrorHandler = handler;
    };

    this.$get = angular.noop;
  });

  ngRetina.directive('ngSrc', ['$window', '$http', '$log', function($window, $http, $log) {
    var msie = parseInt(((/msie (\d+)/.exec($window.navigator.userAgent.toLowerCase()) || [])[1]), 10);
    var isRetina = ((function() {
      var mediaQuery = '(-webkit-min-device-pixel-ratio: 1.5), (min--moz-device-pixel-ratio: 1.5), ' +
        '(-o-min-device-pixel-ratio: 3/2), (min-resolution: 1.5dppx)';
      if ($window.devicePixelRatio > 1) {
        return true;
      }
      return $window.matchMedia && $window.matchMedia(mediaQuery).matches;
    })());

    function getHighResolutionURL(url) {
      var parts = url.split('.');
      if (parts.length < 2) {
        return url;
      }
      parts[parts.length - 2] += infix;
      return parts.join('.');
    }

    return function(scope, element, attrs) {
      function setImgSrc(imageUrl) {
        element.on('error', loadErrorHandler);

        attrs.$set('src', imageUrl);
        if (msie) {
          element.prop('src', imageUrl);
        }
      }

      function getSessionStorageItem(imageUrl) {
        var item;
        try {
          item = $window.sessionStorage.getItem(imageUrl);
        } catch (e) {
          $log.warn('sessionStorage not supported');
          item = imageUrl;
        }
        return item;
      }

      function setSessionStorageItem(imageUrl, imageUrl2x) {
        try {
          $window.sessionStorage.setItem(imageUrl, imageUrl2x);
        } catch (e) {
          $log.warn('sessionStorage not supported');
        }
      }

      function set2xVariant(imageUrl) {
        var imageUrl2x;
        if (angular.isUndefined(attrs.at2x)) {
          imageUrl2x = getSessionStorageItem(imageUrl);
        } else {
          imageUrl2x = attrs.at2x;
        }

        if (!imageUrl2x) {
          imageUrl2x = getHighResolutionURL(imageUrl);
          $http.head(imageUrl2x)
          .then(function(data, status) {
            setImgSrc(imageUrl2x);
            setSessionStorageItem(imageUrl, imageUrl2x);
          })
          .catch(function(data, status, headers, config) {
            setImgSrc(imageUrl);
            setSessionStorageItem(imageUrl, imageUrl);
          });
        } else {
          setImgSrc(imageUrl2x);
        }
      }

      attrs.$observe('ngSrc', function(imageUrl, oldValue) {
        if (!imageUrl) {
          return;
        }

        if (isDataUri(imageUrl)) {
          return setImgSrc(imageUrl);
        }

        if (fadeInWhenLoaded && !getSessionStorageItem('fadedIn-' + imageUrl)) {
          element.css({
            opacity: 0,
            '-o-transition': 'opacity 0.5s ease-out',
            '-moz-transition': 'opacity 0.5s ease-out',
            '-webkit-transition': 'opacity 0.5s ease-out',
            'transition': 'opacity 0.5s ease-out'
          });
          element.on('load', function() {
            setSessionStorageItem('fadedIn-' + imageUrl, true);
            element.css('opacity', 1);
          });
        }

        if (isRetina &&
            angular.isUndefined(attrs.noretina) &&
            element[0].tagName === 'IMG' &&
            imageUrl.match(allowedImageTypesRegex) &&
            !imageUrl.match(dataUrlRegex)) {
            set2xVariant(imageUrl);
          } else {
            setImgSrc(imageUrl);
          }
      });
    };
  }]);
})(window.angular);
<|endoftext|>


<commit_before>if(process.env["consumer_key"]) {
	var config = {};
	config.consumer_key =  process.env["consumer_key"];
	config.consumer_secret =  process.env["consumer_secret"];
	config.access_token_key =  process.env["access_token_key"];
	config.access_token_secret =  process.env["access_token_secret"];
} else{
	var config = require('./settings.json');
}

const PORT = process.env.PORT || 5000;

var http = require('http');
var schedule = require('node-schedule');
var twitter = require('twitter');
var request = require("request");
var cheerio = require("cheerio");

var url = "http://www.tagesspiegel.de/berlin/";

MyApp = {
    appinit: function() {
        MyApp.doKratz();
        MyApp.kratzSchedule();
    },

    doKratz: function() {
      request(url, function (error, response, body) {
        if (!error) {
          var $ = cheerio.load(body), headline = $(".hcf-headline").first().html();
          console.log("Letzte Nachricht: " + headline + "");

          var client = new twitter({
            consumer_key: config.consumer_key,
            consumer_secret: config.consumer_secret,
            access_token_key: config.access_token_key,
            access_token_secret: config.access_token_secret
          });
          var params = {screen_name: 'nodejs'};
          client.post('statuses/update', {status: 'News: ' + headline},  function(error, tweet, response){
            if(error) {
              console.log(JSON.stringify(error) );
            } else{
              console.log('OK');
            }
          });
        } else {
          console.log("We’ve encountered an error: " + error);
        }
      });
    },

    kratzSchedule: function (){
      var rule = new schedule.RecurrenceRule();
      rule.minute = 45;
      var j = schedule.scheduleJob(rule, function(){
        MyApp.doKratz();
      });
    }

};

function handleRequest(request, response){
    response.end('kratz ' + request.url);
}

var server = http.createServer(handleRequest);

server.listen(PORT, function(){ });

MyApp.appinit();
<commit_msg>clean up<commit_after>if(process.env["consumer_key"]) {
	var config = {};
	config.consumer_key =  process.env["consumer_key"];
	config.consumer_secret =  process.env["consumer_secret"];
	config.access_token_key =  process.env["access_token_key"];
	config.access_token_secret =  process.env["access_token_secret"];
} else{
	var config = require('./settings.json');
}

const PORT = process.env.PORT || 5000;

var http = require('http'),
    schedule = require('node-schedule'),
    twitter = require('twitter'),
    request = require("request"),
    cheerio = require("cheerio");

var url = "http://www.tagesspiegel.de/berlin/";

MyApp = {
    appinit: function() {
        MyApp.doKratz();
        MyApp.kratzSchedule();
    },

    doKratz: function() {
      request(url, function (error, response, body) {
        if (!error) {
          var $ = cheerio.load(body), headline = $(".hcf-headline").first().html();
          console.log("Letzte Nachricht: " + headline + "");

          var client = new twitter({
            consumer_key: config.consumer_key,
            consumer_secret: config.consumer_secret,
            access_token_key: config.access_token_key,
            access_token_secret: config.access_token_secret
          });
          var params = {screen_name: 'nodejs'};
          client.post('statuses/update', {status: 'News: ' + headline},  function(error, tweet, response){
            if(error) {
              console.log(JSON.stringify(error) );
            } else{
              console.log('OK');
            }
          });
        } else {
          console.log("We’ve encountered an error: " + error);
        }
      });
    },

    kratzSchedule: function (){
      var rule = new schedule.RecurrenceRule();
      rule.minute = 45;
      var j = schedule.scheduleJob(rule, function(){
        MyApp.doKratz();
      });
    }

};

function handleRequest(request, response){
    response.end('kratz ' + request.url);
}

var server = http.createServer(handleRequest);

server.listen(PORT, function(){});

MyApp.appinit();
<|endoftext|>