<commit_before>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'foam.core',
  name: 'Int',
  extends: 'Property',

  properties: [
    'units',
    [ 'value', 0 ],
    [ 'adapt', function adaptInt(_, v) {
        return typeof v === 'number' ? Math.trunc(v) :
          v ? parseInt(v) :
          0 ;
      }
    ],
    [ 'fromString', function intFromString(str) {
        return str ? parseInt(str) : 0;
      }
    ]
  ]
});

foam.CLASS({
  package: 'foam.core',
  name: 'String',
  extends: 'Property',

  documentation: 'StringProperties coerce their arguments into Strings.',

  properties: [
    { class: 'Int', name: 'width' },
    [ 'adapt', function(_, a) {
        return typeof a === 'function' ? foam.String.multiline(a) :
               typeof a === 'number'   ? String(a)                :
               a && a.toString         ? a.toString()             :
                                         ''                       ;
      }
    ],
    [ 'value', '' ]
  ]
});

foam.CLASS({
  package: 'foam.core',
  name: 'Date',
  extends: 'Property',

  // documentation: 'Describes properties of type Date.',
  label: 'Date',

  properties: [
    {
      name: 'adapt',
      value: function (_, d) {
        if ( typeof d === 'number' ) return new Date(d);
        if ( typeof d === 'string' ) {
          var ret = new Date(d);

          if ( ret.toUTCString() === 'InvalidDate' ) throw 'Invalid Date: ' + d;

          return ret;
        }
        return d;
      }
    },
    {
      name: 'comparePropertyValues',
      value: function(o1, o2) {
        if ( ! o1 ) return o2 ? -1 : 0;
        if ( ! o2 ) return 1;

        return foam.Date.compare(o1, o2);
      }
    }
  ]
});

foam.CLASS({
  package: 'foam.core',
  name: 'DateTime',
  extends: 'Date',

  documentation: 'Describes properties of type DateTime.',
  label: 'Date and time'
});

foam.CLASS({
  package: 'foam.core',
  name:  'Long',
  extends: 'Int',

  documentation:  'Describes properties of type Long.',
  label: 'Round long numbers'
});

foam.CLASS({
  package: 'foam.core',
  name: 'Float',
  extends: 'Int',

  // documentation:  'Describes properties of type Float.',
  label: 'Decimal numbers',

  properties: [
    'precision',
    [
      'adapt',
      function (_, v) {
        return typeof v === 'number' ? v : v ? parseFloat(v) : 0.0 ;
      }
    ]
  ]
});

/**
 No different than Float for JS, but useful when targeting with other languages.
 **/
foam.CLASS({
  package: 'foam.core',
  name: 'Double',
  extends: 'Float'
});

foam.CLASS({
  package: 'foam.core',
  name: 'Function',
  extends: 'Property',

  documentation: 'Describes properties of type Function.',
  label: 'Code that can be run',

  properties: [
    [
      'value',
      function() {}
    ],
    [
      'assertValue',
      function(value, prop) {
        foam.assert(typeof value === 'function', prop.name, 'Cannot set to non function type.');
      }
    ]
  ]
});

foam.CLASS({
  package: 'foam.core',
  name: 'Blob',
  extends: 'Property',

  // documentation: 'A chunk of binary data.',
  label: 'Binary data',
});

foam.CLASS({
  package: 'foam.core',
  name: 'Object',
  extends: 'Property',

  documentation: '',

  properties: [
    {
      name: 'fromJSON',
      value: function(value, ctx) {
        return foam.json.parse(value, null, ctx);
      }
    }
  ]
});

foam.CLASS({
  package: 'foam.core',
  name: 'FObjectProperty',
  extends: 'Property',

  properties: [
    {
      name: 'of',
      value: 'FObject'
    },
    {
      name: 'fromJSON',
      value: function(json, ctx, prop) {
        return foam.json.parse(json, prop.of, ctx);
      }
    },
    {
      name: 'adapt',
      value: function(_, v, prop) {
        var of = foam.lookup(prop.of);

        return of.isInstance(v) ?
            v :
            ( v.class ?
                foam.lookup(v.class) :
                of ).create(v, this.__subContext__);
      }
    }
  ]
});

foam.CLASS({
  package: 'foam.core',
  name: 'Array',
  extends: 'Property',

  properties: [
    {
      name: 'fromJSON',
      value: function(value, opt_ctx) {
        return foam.json.parse(value, null, opt_ctx);
      }
    },
    [
      'factory',
      function() { return []; }
    ],
    [
      'isDefaultValue',
      function(v) { return ! v || ! v.length; }
    ],
  ]
});

foam.CLASS({
  package: 'foam.core',
  name: 'StringArray',
  extends: 'Property',

  documentation: 'An array of String values.',
  label: 'List of text strings',

  properties: [
    {
      name: 'of',
      value: 'String',
      documentation: 'The FOAM sub-type of this property.'
    },
    [
      'factory',
      function() { return []; }
    ],
    [
      'adapt',
      function(_, v, prop) {
        if ( ! Array.isArray(v) ) return v;

        var copy;
        for ( var i = 0 ; i < v.length ; i++ ) {
          if ( typeof v[i] !== 'string' ) {
            if ( ! copy ) copy = v.slice();
            copy[i] = '' + v[i];
          }
        }

        return copy || v;
      }
    ],
    [
      'assertValue',
      function(v, prop) {
        foam.assert(Array.isArray(v),
            prop.name, 'Tried to set StringArray to non-array type.');
        for ( var i = 0 ; i < v.length ; i++ ) {
          foam.assert(typeof v[i] === 'string',
              prop.name, 'Element', i, 'is not a string', v[i]);
        }
      }
    ]
  ]
});

foam.CLASS({
  package: 'foam.core',
  name: 'Class',
  extends: 'Property',

  properties: [
    {
      name: 'getter',
      value: function(prop) {
        var c = this.instance_[prop.name];

        // Implement value and factory support.
        if ( ! c ) {
          if ( prop.value ) {
            c = prop.value;
          } else if ( prop.factory ) {
            c = this.instance_[prop.name] = prop.factory.call(this, prop);
          }
        }

        // Upgrade Strings to actual classes, if available.
        if ( foam.String.isInstance(c) ) {
          c = this.lookup(c, true);
          if ( c ) this.instance_[prop.name] = c;
        }

        return c;
      }
    },
    {
      name: 'toJSON',
      value: function(value) { return value.id; }
    }
  ],

  methods: [
    function installInProto(proto) {
      this.SUPER(proto);

      var name = this.name;

      Object.defineProperty(proto, name + '$cls', {
        get: function classGetter() {
          console.warn("Deprecated use of 'cls.$cls'. Just use 'cls' instead.");
          return typeof this[name] !== 'string' ? this[name] :
            this.__context__.lookup(this[name], true);
        },
        configurable: true
      });
    }
  ]
});

foam.CLASS({
  package: 'foam.core',
  name: 'EMail',
  extends: 'String',
  // FUTURE: verify
  label: 'Email address'
});

foam.CLASS({
  package: 'foam.core',
  name: 'Image',
  extends: 'String',
  // FUTURE: verify
  label: 'Image data or link'
});

foam.CLASS({
  package: 'foam.core',
  name: 'URL',
  extends: 'String',
  // FUTURE: verify
  label: 'Web link (URL or internet address)'
});

foam.CLASS({
  package: 'foam.core',
  name: 'Color',
  extends: 'String',
  label: 'Color'
});

foam.CLASS({
  package: 'foam.core',
  name: 'Password',
  extends: 'String',
  label: 'Password that displays protected or hidden text'
});

foam.CLASS({
  package: 'foam.core',
  name: 'PhoneNumber',
  extends: 'String',
  label: 'Phone number'
});

foam.CLASS({
  package: 'foam.core',
  name: 'Map',
  extends: 'Property',

  properties: [
    ['factory', function() { return {} }],
    'of'
  ]
});

foam.CLASS({
  package: 'foam.core',
  name: 'Reference',
  extends: 'Property',

  properties: [
    {
      class: 'Class',
      name: 'of'
    },
    {
      class: 'String',
      name: 'targetDAOKey',
      expression: function(of) {
        return of + 'DAO';
      }
    },
    {
      name: 'adapt',
      value: function(oldValue, newValue, prop) {
        return prop.of.isInstance(newValue) ?
          newValue.id :
          newValue ;
      }
    }
  ]
});

foam.CLASS({
  refines: 'foam.core.Model',

  documentation: 'Update Model Property types.',

  properties: [
    { class: 'String',  name: 'name' },
    { class: 'Boolean', name: 'abstract' }
  ]
});
<commit_msg>FObjectProperty: Allow null value<commit_after>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

foam.CLASS({
  package: 'foam.core',
  name: 'Int',
  extends: 'Property',

  properties: [
    'units',
    [ 'value', 0 ],
    [ 'adapt', function adaptInt(_, v) {
        return typeof v === 'number' ? Math.trunc(v) :
          v ? parseInt(v) :
          0 ;
      }
    ],
    [ 'fromString', function intFromString(str) {
        return str ? parseInt(str) : 0;
      }
    ]
  ]
});

foam.CLASS({
  package: 'foam.core',
  name: 'String',
  extends: 'Property',

  documentation: 'StringProperties coerce their arguments into Strings.',

  properties: [
    { class: 'Int', name: 'width' },
    [ 'adapt', function(_, a) {
        return typeof a === 'function' ? foam.String.multiline(a) :
               typeof a === 'number'   ? String(a)                :
               a && a.toString         ? a.toString()             :
                                         ''                       ;
      }
    ],
    [ 'value', '' ]
  ]
});

foam.CLASS({
  package: 'foam.core',
  name: 'Date',
  extends: 'Property',

  // documentation: 'Describes properties of type Date.',
  label: 'Date',

  properties: [
    {
      name: 'adapt',
      value: function (_, d) {
        if ( typeof d === 'number' ) return new Date(d);
        if ( typeof d === 'string' ) {
          var ret = new Date(d);

          if ( ret.toUTCString() === 'InvalidDate' ) throw 'Invalid Date: ' + d;

          return ret;
        }
        return d;
      }
    },
    {
      name: 'comparePropertyValues',
      value: function(o1, o2) {
        if ( ! o1 ) return o2 ? -1 : 0;
        if ( ! o2 ) return 1;

        return foam.Date.compare(o1, o2);
      }
    }
  ]
});

foam.CLASS({
  package: 'foam.core',
  name: 'DateTime',
  extends: 'Date',

  documentation: 'Describes properties of type DateTime.',
  label: 'Date and time'
});

foam.CLASS({
  package: 'foam.core',
  name:  'Long',
  extends: 'Int',

  documentation:  'Describes properties of type Long.',
  label: 'Round long numbers'
});

foam.CLASS({
  package: 'foam.core',
  name: 'Float',
  extends: 'Int',

  // documentation:  'Describes properties of type Float.',
  label: 'Decimal numbers',

  properties: [
    'precision',
    [
      'adapt',
      function (_, v) {
        return typeof v === 'number' ? v : v ? parseFloat(v) : 0.0 ;
      }
    ]
  ]
});

/**
 No different than Float for JS, but useful when targeting with other languages.
 **/
foam.CLASS({
  package: 'foam.core',
  name: 'Double',
  extends: 'Float'
});

foam.CLASS({
  package: 'foam.core',
  name: 'Function',
  extends: 'Property',

  documentation: 'Describes properties of type Function.',
  label: 'Code that can be run',

  properties: [
    [
      'value',
      function() {}
    ],
    [
      'assertValue',
      function(value, prop) {
        foam.assert(typeof value === 'function', prop.name, 'Cannot set to non function type.');
      }
    ]
  ]
});

foam.CLASS({
  package: 'foam.core',
  name: 'Blob',
  extends: 'Property',

  // documentation: 'A chunk of binary data.',
  label: 'Binary data',
});

foam.CLASS({
  package: 'foam.core',
  name: 'Object',
  extends: 'Property',

  documentation: '',

  properties: [
    {
      name: 'fromJSON',
      value: function(value, ctx) {
        return foam.json.parse(value, null, ctx);
      }
    }
  ]
});

foam.CLASS({
  package: 'foam.core',
  name: 'FObjectProperty',
  extends: 'Property',

  properties: [
    {
      name: 'of',
      value: 'FObject'
    },
    {
      name: 'fromJSON',
      value: function(json, ctx, prop) {
        return foam.json.parse(json, prop.of, ctx);
      }
    },
    {
      name: 'adapt',
      value: function(_, v, prop) {
        // All FObjects may be null.
        if (v === null) return v;

        var of = foam.lookup(prop.of);

        return of.isInstance(v) ?
            v :
            ( v.class ?
                foam.lookup(v.class) :
                of ).create(v, this.__subContext__);
      }
    }
  ]
});

foam.CLASS({
  package: 'foam.core',
  name: 'Array',
  extends: 'Property',

  properties: [
    {
      name: 'fromJSON',
      value: function(value, opt_ctx) {
        return foam.json.parse(value, null, opt_ctx);
      }
    },
    [
      'factory',
      function() { return []; }
    ],
    [
      'isDefaultValue',
      function(v) { return ! v || ! v.length; }
    ],
  ]
});

foam.CLASS({
  package: 'foam.core',
  name: 'StringArray',
  extends: 'Property',

  documentation: 'An array of String values.',
  label: 'List of text strings',

  properties: [
    {
      name: 'of',
      value: 'String',
      documentation: 'The FOAM sub-type of this property.'
    },
    [
      'factory',
      function() { return []; }
    ],
    [
      'adapt',
      function(_, v, prop) {
        if ( ! Array.isArray(v) ) return v;

        var copy;
        for ( var i = 0 ; i < v.length ; i++ ) {
          if ( typeof v[i] !== 'string' ) {
            if ( ! copy ) copy = v.slice();
            copy[i] = '' + v[i];
          }
        }

        return copy || v;
      }
    ],
    [
      'assertValue',
      function(v, prop) {
        foam.assert(Array.isArray(v),
            prop.name, 'Tried to set StringArray to non-array type.');
        for ( var i = 0 ; i < v.length ; i++ ) {
          foam.assert(typeof v[i] === 'string',
              prop.name, 'Element', i, 'is not a string', v[i]);
        }
      }
    ]
  ]
});

foam.CLASS({
  package: 'foam.core',
  name: 'Class',
  extends: 'Property',

  properties: [
    {
      name: 'getter',
      value: function(prop) {
        var c = this.instance_[prop.name];

        // Implement value and factory support.
        if ( ! c ) {
          if ( prop.value ) {
            c = prop.value;
          } else if ( prop.factory ) {
            c = this.instance_[prop.name] = prop.factory.call(this, prop);
          }
        }

        // Upgrade Strings to actual classes, if available.
        if ( foam.String.isInstance(c) ) {
          c = this.lookup(c, true);
          if ( c ) this.instance_[prop.name] = c;
        }

        return c;
      }
    },
    {
      name: 'toJSON',
      value: function(value) { return value.id; }
    }
  ],

  methods: [
    function installInProto(proto) {
      this.SUPER(proto);

      var name = this.name;

      Object.defineProperty(proto, name + '$cls', {
        get: function classGetter() {
          console.warn("Deprecated use of 'cls.$cls'. Just use 'cls' instead.");
          return typeof this[name] !== 'string' ? this[name] :
            this.__context__.lookup(this[name], true);
        },
        configurable: true
      });
    }
  ]
});

foam.CLASS({
  package: 'foam.core',
  name: 'EMail',
  extends: 'String',
  // FUTURE: verify
  label: 'Email address'
});

foam.CLASS({
  package: 'foam.core',
  name: 'Image',
  extends: 'String',
  // FUTURE: verify
  label: 'Image data or link'
});

foam.CLASS({
  package: 'foam.core',
  name: 'URL',
  extends: 'String',
  // FUTURE: verify
  label: 'Web link (URL or internet address)'
});

foam.CLASS({
  package: 'foam.core',
  name: 'Color',
  extends: 'String',
  label: 'Color'
});

foam.CLASS({
  package: 'foam.core',
  name: 'Password',
  extends: 'String',
  label: 'Password that displays protected or hidden text'
});

foam.CLASS({
  package: 'foam.core',
  name: 'PhoneNumber',
  extends: 'String',
  label: 'Phone number'
});

foam.CLASS({
  package: 'foam.core',
  name: 'Map',
  extends: 'Property',

  properties: [
    ['factory', function() { return {} }],
    'of'
  ]
});

foam.CLASS({
  package: 'foam.core',
  name: 'Reference',
  extends: 'Property',

  properties: [
    {
      class: 'Class',
      name: 'of'
    },
    {
      class: 'String',
      name: 'targetDAOKey',
      expression: function(of) {
        return of + 'DAO';
      }
    },
    {
      name: 'adapt',
      value: function(oldValue, newValue, prop) {
        return prop.of.isInstance(newValue) ?
          newValue.id :
          newValue ;
      }
    }
  ]
});

foam.CLASS({
  refines: 'foam.core.Model',

  documentation: 'Update Model Property types.',

  properties: [
    { class: 'String',  name: 'name' },
    { class: 'Boolean', name: 'abstract' }
  ]
});
<|endoftext|>


<commit_before>loadAllFonts = false;

function setFonts(c, mc, is_nav) {
    var f = _font_map[c];
    var mf = _font_map[mc];
    var h = _font_data[f.h].bold;

    setCommonFonts(f.p, mf.p)

    if(is_nav) {
        var p = _font_data[f.p].regular;
        setNavFonts(h, p);
    } else {
        setMainFonts(h, c, mc);
    }
}

function setCommonFonts(p, m) {
    var pr = _font_data[p].regular;
    var pb = _font_data[p].bold;
    var pi = _font_data[p].italic;
    var pbi = _font_data[p].bolditalic;
    var mr = _font_data[m].regular;

    $('div.user-font').css('font-family', pr);
    $('div.user-font b, div.user-font strong').css('font-family', pb);
    $('div.user-font i, div.user-font em').css('font-family', pi);
    $('div.user-font b i, div.user-font b i, ' +
        'div.user-font strong em, div.user-font em strong').css('font-family', pbi);
    $('div.user-font .expanding-area pre, div.user-font .expanding-area textarea').css('font-family', pr);
    $('div.user-font code, div.user-font pre, div.user-font tt').css('font-family', mr);
}

function setNavFonts(h, p) {
    $('.user-font button').css('font-family', p);
    $('a#pagename').css('font-family', h);
}

function setMainFonts(h, c, mc) {
    $('.user-font h1, .user-font h2, .user-font h3, ' +
        '.user-font h4, .user-font h5, .user-font h6' +
        '.user-font .expanding-h1-area pre, ' +
        '.user-font .expanding-h1-area textarea' +
        '.user-font .expanding-h4-area pre, ' +
        '.user-font .expanding-h4-area textarea').css('font-family', h);

    postIframeMessage('font', c, mc);
}

function initFonts() {
    //default to serif1...
    if(!_g.FontClass) {
        _g.FontClass = 'serif1';
    }
    if(!_g.MonoFontClass) {
        _g.MonoFontClass = 'mono1';
    }

    setFonts(_g.FontClass, _g.MonoFontClass);

    if(loadAllFonts) {
        postIframeMessage('fonts');
    }
}

<commit_msg>[http]<commit_after>loadAllFonts = false;

function setFonts(c, mc, is_nav) {
    var f = _font_map[c];
    var mf = _font_map[mc];
    var h = _font_data[f.h].bold;

    setCommonFonts(f.p, mf.p, h)

    if(is_nav) {
        var p = _font_data[f.p].regular;
        setNavFonts(h, p);
    } else {
        setMainFonts(h, c, mc);
    }
}

function setCommonFonts(p, m, h) {
    var pr = _font_data[p].regular;
    var pb = _font_data[p].bold;
    var pi = _font_data[p].italic;
    var pbi = _font_data[p].bolditalic;
    var mr = _font_data[m].regular;

    $('div.user-font').css('font-family', pr);
    $('div.user-font b, div.user-font strong').css('font-family', pb);
    $('div.user-font i, div.user-font em').css('font-family', pi);
    $('div.user-font b i, div.user-font b i, ' +
        'div.user-font strong em, div.user-font em strong').css('font-family', pbi);
    $('div.user-font .expanding-area.expanding-p-area pre, div.user-font .expanding-area-p-area textarea').css('font-family', pr);
    $('div.user-font .expanding-area.expanding-h1-area pre, div.user-font .expanding-area.expanding-h1-area textarea').css('font-family', h);
    $('div.user-font .expanding-area.expanding-h4-area pre, div.user-font .expanding-area.expanding-h4-area textarea').css('font-family', h);
    $('div.user-font code, div.user-font pre, div.user-font tt').css('font-family', mr);
}

function setNavFonts(h, p) {
    $('.user-font button').css('font-family', p);
    $('a#pagename').css('font-family', h);
}

function setMainFonts(h, c, mc) {
    $('.user-font h1, .user-font h2, .user-font h3, ' +
        '.user-font h4, .user-font h5, .user-font h6' +
        '.user-font .expanding-h1-area pre, ' +
        '.user-font .expanding-h1-area textarea' +
        '.user-font .expanding-h4-area pre, ' +
        '.user-font .expanding-h4-area textarea').css('font-family', h);

    postIframeMessage('font', c, mc);
}

function initFonts() {
    //default to serif1...
    if(!_g.FontClass) {
        _g.FontClass = 'serif1';
    }
    if(!_g.MonoFontClass) {
        _g.MonoFontClass = 'mono1';
    }

    setFonts(_g.FontClass, _g.MonoFontClass);

    if(loadAllFonts) {
        postIframeMessage('fonts');
    }
}

<|endoftext|>


<commit_before>function start()
{
	if(animating)
		return;

	animating = true;
	var ctx = canvas.getContext('2d');
	var path = knownPath[pathSelect.value];

	var x = path[0].x;		//x coordinate
	var y = path[0].y;		//y coordinate
	var dir = atan2(path[1].y-path[0].y, path[1].x-path[0].x);	//orientation in radians

	var motionModel = new OdometryModel(getTurnNoise(), getStrideNoise(), getTurnNoise(), getTurnNoise());
	var filter = new ParticleFilter(getParticleCount(), motionModel, undefined, new RobotState(x, y, dir));

	robot = new Robot(filter, path);
	robot.draw(ctx);
	animating = true;
	lastFrame = Date.now();
	requestAnimationFrame(frame);
}<commit_msg>remove redundant code<commit_after>function start()
{
	if(animating)
		return;

	animating = true;
	var ctx = canvas.getContext('2d');
	var path = knownPath[pathSelect.value];

	var x = path[0].x;		//x coordinate
	var y = path[0].y;		//y coordinate
	var dir = atan2(path[1].y-path[0].y, path[1].x-path[0].x);	//orientation in radians

	var motionModel = new OdometryModel(getTurnNoise(), getStrideNoise(), getTurnNoise(), getTurnNoise());
	var filter = new ParticleFilter(getParticleCount(), motionModel, undefined, new RobotState(x, y, dir));

	robot = new Robot(filter, path);
	robot.draw(ctx);
	lastFrame = Date.now();
	requestAnimationFrame(frame);
}<|endoftext|>


<commit_before>var Chrome = require('chrome-remote-interface');
var events = require('events');
var util = require('util');
var common = require('./common.js');
var Page = require('./Page.js');

var CLEANUP_SCRIPT =
    'chrome.benchmarking.closeConnections();' +
    'chrome.benchmarking.clearHostResolverCache();';

var Client = function (urls, options) {
    var self = this;
    var currentPageIndex = -1;

    self.pages = [];

    Chrome(function (chrome) {
        function loadNextURL() {
            var id = ++currentPageIndex;
            var url = urls[id];
            if (url) {
	            if (!url.match(/^http[s]?:/)) {
	                url = 'http://' + url;
	            }
                var page = new Page(id, url);
                self.emit('pageStart', url);
                page.start();
                chrome.Runtime.evaluate({'expression': CLEANUP_SCRIPT});
                chrome.Page.navigate({'url': url});
                self.pages.push(page);
            }
            return url;
        }

        // start!
        self.emit('connect');
        chrome.Page.enable();
        chrome.Network.enable();
        chrome.Network.setCacheDisabled({'cacheDisabled': true});
        loadNextURL();

        var messages = [];

        chrome.on('event', function (message) {
            messages.push(message);
            if (message.method) {
                var page = self.pages[currentPageIndex];

                if (message.method == 'Page.domContentEventFired') {
                    common.dump('<-- ' + message.method + ': ' + page.url);
                    page.domLoaded();
                } else if (message.method == 'Page.loadEventFired') {
                    common.dump('<-- ' + message.method + ': ' + page.url);
                    page.end();
                } else if (message.method.match(/^Network./)) {
                    page.processMessage(message);
                } else {
                    common.dump('Unhandled message: ' + message.method);
                }

                // check done with current URL
                if (page.isDone()) {
                    self.emit(page.isOk() ? 'pageEnd' : 'pageError', page.url);
                    if (!loadNextURL()) {
                        common.dump("Emitting 'end' event");
                        chrome.close();
                        self.emit('end', getHAR.call(self), messages);
                    }
                }
            } else {
	            common.dump('<-- #' + message.id + ' ' +
			                JSON.stringify(message.result));
            }
        });
    }).on('error', function (error) {
        common.dump("Emitting 'error' event: " + error.message);
        self.emit('error');
    });
}

util.inherits(Client, events.EventEmitter);

function getHAR() {
    var self = this;
    var har = {
        'log': {
            'version' : '1.2',
            'creator' : {
                'name': 'Chrome HAR Capturer',
                'version': '0.3.1'
            },
            'pages': [],
            'entries': []
        }
    };

    // merge pages in one HAR
    for (var i in self.pages) {
        var page = self.pages[i];
        if (page.isOk()) {
            var pageHAR = page.getHAR();
            har.log.pages.push(pageHAR.info);
            Array.prototype.push.apply(har.log.entries, pageHAR.entries);
        }
    }

    return har;
}

module.exports = Client;
<commit_msg>Remove useless variable<commit_after>var Chrome = require('chrome-remote-interface');
var events = require('events');
var util = require('util');
var common = require('./common.js');
var Page = require('./Page.js');

var CLEANUP_SCRIPT =
    'chrome.benchmarking.closeConnections();' +
    'chrome.benchmarking.clearHostResolverCache();';

var Client = function (urls, options) {
    var self = this;

    self.pages = [];

    Chrome(function (chrome) {
        // load the next URL or exit if done
        function loadNextURL() {
            var id = self.pages.length;
            var url = urls[id];
            if (url) {
	            if (!url.match(/^http[s]?:/)) {
	                url = 'http://' + url;
	            }
                var page = new Page(id, url);
                self.emit('pageStart', url);
                page.start();
                chrome.Runtime.evaluate({'expression': CLEANUP_SCRIPT});
                chrome.Page.navigate({'url': url});
                self.pages.push(page);
            }
            return url;
        }

        // start!
        self.emit('connect');
        chrome.Page.enable();
        chrome.Network.enable();
        chrome.Network.setCacheDisabled({'cacheDisabled': true});
        loadNextURL();

        var messages = [];

        chrome.on('event', function (message) {
            messages.push(message);
            if (message.method) {
                var page = self.pages.slice(-1)[0];

                if (message.method == 'Page.domContentEventFired') {
                    common.dump('<-- ' + message.method + ': ' + page.url);
                    page.domLoaded();
                } else if (message.method == 'Page.loadEventFired') {
                    common.dump('<-- ' + message.method + ': ' + page.url);
                    page.end();
                } else if (message.method.match(/^Network./)) {
                    page.processMessage(message);
                } else {
                    common.dump('Unhandled message: ' + message.method);
                }

                // check done with current URL
                if (page.isDone()) {
                    self.emit(page.isOk() ? 'pageEnd' : 'pageError', page.url);
                    if (!loadNextURL()) {
                        common.dump("Emitting 'end' event");
                        chrome.close();
                        self.emit('end', getHAR.call(self), messages);
                    }
                }
            } else {
	            common.dump('<-- #' + message.id + ' ' +
			                JSON.stringify(message.result));
            }
        });
    }).on('error', function (error) {
        common.dump("Emitting 'error' event: " + error.message);
        self.emit('error');
    });
}

util.inherits(Client, events.EventEmitter);

function getHAR() {
    var self = this;
    var har = {
        'log': {
            'version' : '1.2',
            'creator' : {
                'name': 'Chrome HAR Capturer',
                'version': '0.3.1'
            },
            'pages': [],
            'entries': []
        }
    };

    // merge pages in one HAR
    for (var i in self.pages) {
        var page = self.pages[i];
        if (page.isOk()) {
            var pageHAR = page.getHAR();
            har.log.pages.push(pageHAR.info);
            Array.prototype.push.apply(har.log.entries, pageHAR.entries);
        }
    }

    return har;
}

module.exports = Client;
<|endoftext|>


<commit_before>/*global jake */
var child_process = require('child_process'),
    fs = require('fs'),
    glob = require('glob'),
    growl = require('growl'),
    path = require('path'),
    portscanner = require('portscanner'),
    util = require('util'),
    wrench = require('wrench');

// Recursive mkdir
// mkdirsSync(path, [mode=(0777^umask)]) -> pathsCreated
function mkdir(dirname, mode) {
  if (mode === undefined) {
    mode = 0777 ^ process.umask();
  }
  var pathsNotFound = [];
  var fn = dirname;
  while (true) {
    try {
      var stats = fs.statSync(fn);
      if (stats.isDirectory()) {
        break;
      }
      throw new Error('Unable to create directory at ' + fn);
    }
    catch (e) {
      pathsNotFound.push(fn);
      fn = path.dirname(fn);
    }
  }
  for (var i = pathsNotFound.length - 1; i > -1; i--) {
    var fn = pathsNotFound[i];
    console.log('mkdir:\t\033[90mmaking directory\033[0m ' + fn);
    fs.mkdirSync(fn, mode);
  }
}

function streamData(prefix, data) {
  var lines = data.toString().split(/\r\n|\n|\r/g);
  for (var i = 0, len = lines.length - 1; i < len; i++) {
    util.print(prefix);
    util.print(lines[i]);
    util.print('\n');
  }
  if (lines[lines.length - 1]) {
    util.print(prefix);
    util.print(lines[lines.length - 1]);
  }
}

exports.build = function(options) {
  var complete = options.complete;

  mkdir(options.dir);

  var args = [
    __dirname + '/node_modules/lumbar/bin/lumbar',
    options.watch ? 'watch' : 'build',
    '--config', options.configFile || './config/dev.json',
    '--use', __dirname + '/node_modules/lumbar-long-expires',
    '--use', __dirname + '/node_modules/lumbar-tester',
    '--with', '{"includeTests": ' + !options.removeTests + '}',
    '--use', __dirname + '/node_modules/lumbar-style-doc',
    '--with', '{"removeDocs": ' + !!options.removeTests + '}',
    '--use', 'conditional',
    '--with', '{"env": "' + (options.minimize ? 'production' : 'dev') + '"}',
    './lumbar.json',
    (options.dir || '.')
  ];
  if (options.package) {
    args.push('--package');
    args.push(options.package);
  }
  if (options.minimize) {
    args.push('--minimize');
  }

  var lumbar = child_process.spawn('node', args);
  lumbar.stdout.on('data', function (data) {
    streamData('lumbar: ', data);
  });
  lumbar.stderr.on('data', function (data) {
    streamData('lumbar err: ', data);
  });

  lumbar.on('exit', function(code) {
    if (!complete) {
      growl('Lumbar Borked', { title: 'Lumbar Borked', sticky: true });
    } else {
      complete(code);
    }
  });
  return lumbar;
};

exports.startServer = function(options) {
  var test = !!options.test,
      onData = options.data,
      complete = options.complete;

  if (options.mocks) {
    process.env.ENABLE_MOCKS = options.mocks;
  }
  var args = [
    __dirname + '/node_modules/mock-server/bin/mock-server',
    exports.projectDir,
    '--proxy-server=' + options.proxy,
    '--port=' + (options.port || 8080),
    '--secure-port=' + (options.securePort || 8081)
  ];
  if (exports.forceCORS) {
    args.push('--force-cors');
  }

  var server = child_process.spawn('node', args, {
    env: process.env
  });
  server.stdout.on('data', function (data) {
    if (onData) {
      onData(data);
    }

    // Do not output module, etc requests if in test mode
    if (!test || !/GET \/r\/phoenix/.test(data)) {
      streamData((test ? '  ' : '') + 'server: ', data);
    }
  });
  server.stderr.on('data', function (data) {
    if (onData) {
      onData(data);
    }
    streamData((test ? '  ' : '') + 'server: ', data);
  });

  if (!test) {
    server.on('exit', function(code) {
      growl('Server Borked', { title: 'Server Borked', sticky: true });

      if (complete) {
        complete(code);
      }
    });
  }

  // If we die we're taking the server with us (to prevent ports from hanging around)
  process.on('exit', function() {
    if (server) {
      server.kill();
    }
  });

  return server;
};

exports.watch = function(server, mocks) {
  glob.sync('build/dev').forEach(wrench.rmdirSyncRecursive);

  var run;
  exports.startServer({
    proxy: server,
    mocks: mocks,
    data: function() {
      if (run) {
        return;
      }
      run = true;

      exports.build({
        dir: 'build/dev',
        watch: true,
        complete: function(code) {
          process.exit(code);
        }
      });
    },
    complete: function(code) {
      process.exit(code);
    }
  });
};

desc('The default task. Executes init');
task('default', ['lumbar'], function() {});

desc('Process all lumbar modules.');
task('lumbar', [], function() {
  exports.build({
    dir: 'build/dev',
    complete: complete
  });
}, true);

desc('Builds production packages');
task('release', [], function(prefix, pkg) {
  prefix = prefix || 'phoenix';

  exports.build({
    dir: 'build/' + prefix,
    package: pkg,
    minimize: true,
    removeTests: true,
    configFile: './config/production.json',
    complete: function(code) {
      if (code) {
        process.exit(code);
      } else {
        complete();
      }
    }
  });
});

desc('Cleans any generated content out of the application');
task('clean', [], function() {
  glob.sync('build').forEach(wrench.rmdirSyncRecursive);
});

desc('Builds the app in production test mode.');
task('heroku-test', [], function() {
  exports.build({
    dir: 'build/test',
    minimize: true,
    configFile: './config/production.json',
    complete: complete
  });
}, true);

desc('Initializes the file change watcher for stylus scripts');
task('watch', [], function(server, mocks) {
  exports.watch((exports.serverName || function() {}).apply(exports, arguments), mocks);
});

desc('Starts up the server in normal mode');
task('start', [], function(server, mocks) {
  exports.startServer({proxy: exports.serverName.apply(exports, arguments), mocks: mocks});
});

desc('Testing');
task('test-runner', [], function(webOnly, xunit) {
  var superCode = 0;

  function runPhantom(platform, androidUserAgent, xunit, port, callback) {
    console.log('Running platform: ' + platform + ' androidUserAgent: ' + (!!androidUserAgent));
    var userAgent = androidUserAgent ?
            'Mozilla/5.0 (Linux; U; Android 2.3.6; en-us; Nexus S Build/GRK39F) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1'
            : 'Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3',
        phantom;
    if (exports.mochaTests) {
      var args = ['-A', userAgent, 'http://localhost:' + port + '/r/phoenix/' + platform + '/test.html'];
      if (xunit) {
        args.push('-R', 'xunit');
      }
      phantom = child_process.spawn(__dirname + '/node_modules/.bin/mocha-phantomjs', args);
    } else {
      phantom = child_process.spawn('phantomjs', [__dirname + '/test/run-qunit.js', 'http://localhost:' + port + '/r/phoenix/' + platform + '/test.html', userAgent]);
    }

    var buffer = '';
    phantom.stdout.on('data', function (data) {
      if (exports.mochaTests && xunit) {
        buffer += data;
      } else {
        streamData('  phantom: ', data);
      }
    });
    phantom.stderr.on('data', function (data) {
      streamData('  phantom err: ', data);
    });
    phantom.on('exit', function(code) {
      superCode = superCode | code;
      callback(code, buffer);
    });
  }

  function findPorts(callback) {
    portscanner.findAPortNotInUse(58080, 58090, 'localhost', function(err, port) {
      if (err) {
        throw err;
      }

      portscanner.findAPortNotInUse(port + 1, 58090, 'localhost', function(err, securePort) {
        if (err) {
          throw err;
        }

        callback(port, securePort);
      });
    });
  }

  var run;
  findPorts(function(port, securePort) {
    exports.startServer({
      proxy: (exports.serverName || function() {}).call(exports),
      mocks: true,
      test: true,
      port: port,
      securePort: securePort,
      data: function() {
        if (run) {
          return;
        }
        run = true;

        (function exec() {
          var platform = exports.testPlatforms.shift();
          if (webOnly && !platform.webOnly) {
            process.exit(superCode);
            return;
          }

          runPhantom(platform.platform, platform.androidUA, xunit, port, function(code, buffer) {
            if (exports.mochaTests && xunit) {
              fs.writeFileSync('build/' + platform.platform + (platform.androidUA ? '_android' : '') + '.xml', buffer);
            }

            if (!exports.testPlatforms.length) {
              process.exit(superCode);
            } else {
              exec();
            }
          });
        })();
      }
    });
  });
});

desc('Testing');
task('test', ['lumbar', 'test-runner'], function() {});

task('test-xunit', ['lumbar'], function() {
  jake.Task['test-runner'].invoke(undefined, true);
});
<commit_msg>Allow for custom lumbar build names<commit_after>/*global jake */
var child_process = require('child_process'),
    fs = require('fs'),
    glob = require('glob'),
    growl = require('growl'),
    path = require('path'),
    portscanner = require('portscanner'),
    util = require('util'),
    wrench = require('wrench');

// Recursive mkdir
// mkdirsSync(path, [mode=(0777^umask)]) -> pathsCreated
function mkdir(dirname, mode) {
  if (mode === undefined) {
    mode = 0777 ^ process.umask();
  }
  var pathsNotFound = [];
  var fn = dirname;
  while (true) {
    try {
      var stats = fs.statSync(fn);
      if (stats.isDirectory()) {
        break;
      }
      throw new Error('Unable to create directory at ' + fn);
    }
    catch (e) {
      pathsNotFound.push(fn);
      fn = path.dirname(fn);
    }
  }
  for (var i = pathsNotFound.length - 1; i > -1; i--) {
    var fn = pathsNotFound[i];
    console.log('mkdir:\t\033[90mmaking directory\033[0m ' + fn);
    fs.mkdirSync(fn, mode);
  }
}

function streamData(prefix, data) {
  var lines = data.toString().split(/\r\n|\n|\r/g);
  for (var i = 0, len = lines.length - 1; i < len; i++) {
    util.print(prefix);
    util.print(lines[i]);
    util.print('\n');
  }
  if (lines[lines.length - 1]) {
    util.print(prefix);
    util.print(lines[lines.length - 1]);
  }
}

exports.build = function(options) {
  var complete = options.complete;

  mkdir(options.dir);

  var args = [
    __dirname + '/node_modules/lumbar/bin/lumbar',
    options.watch ? 'watch' : 'build',
    '--config', options.configFile || './config/dev.json',
    '--use', __dirname + '/node_modules/lumbar-long-expires',
    '--use', __dirname + '/node_modules/lumbar-tester',
    '--with', '{"includeTests": ' + !options.removeTests + '}',
    '--use', __dirname + '/node_modules/lumbar-style-doc',
    '--with', '{"removeDocs": ' + !!options.removeTests + '}',
    '--use', 'conditional',
    '--with', '{"env": "' + (options.minimize ? 'production' : 'dev') + '"}',
    exports.lumbarFile || './lumbar.json',
    (options.dir || '.')
  ];
  if (options.package) {
    args.push('--package');
    args.push(options.package);
  }
  if (options.minimize) {
    args.push('--minimize');
  }

  var lumbar = child_process.spawn('node', args);
  lumbar.stdout.on('data', function (data) {
    streamData('lumbar: ', data);
  });
  lumbar.stderr.on('data', function (data) {
    streamData('lumbar err: ', data);
  });

  lumbar.on('exit', function(code) {
    if (!complete) {
      growl('Lumbar Borked', { title: 'Lumbar Borked', sticky: true });
    } else {
      complete(code);
    }
  });
  return lumbar;
};

exports.startServer = function(options) {
  var test = !!options.test,
      onData = options.data,
      complete = options.complete;

  if (options.mocks) {
    process.env.ENABLE_MOCKS = options.mocks;
  }
  var args = [
    __dirname + '/node_modules/mock-server/bin/mock-server',
    exports.projectDir,
    '--proxy-server=' + options.proxy,
    '--port=' + (options.port || 8080),
    '--secure-port=' + (options.securePort || 8081)
  ];
  if (exports.forceCORS) {
    args.push('--force-cors');
  }

  var server = child_process.spawn('node', args, {
    env: process.env
  });
  server.stdout.on('data', function (data) {
    if (onData) {
      onData(data);
    }

    // Do not output module, etc requests if in test mode
    if (!test || !/GET \/r\/phoenix/.test(data)) {
      streamData((test ? '  ' : '') + 'server: ', data);
    }
  });
  server.stderr.on('data', function (data) {
    if (onData) {
      onData(data);
    }
    streamData((test ? '  ' : '') + 'server: ', data);
  });

  if (!test) {
    server.on('exit', function(code) {
      growl('Server Borked', { title: 'Server Borked', sticky: true });

      if (complete) {
        complete(code);
      }
    });
  }

  // If we die we're taking the server with us (to prevent ports from hanging around)
  process.on('exit', function() {
    if (server) {
      server.kill();
    }
  });

  return server;
};

exports.watch = function(server, mocks) {
  glob.sync('build/dev').forEach(wrench.rmdirSyncRecursive);

  var run;
  exports.startServer({
    proxy: server,
    mocks: mocks,
    data: function() {
      if (run) {
        return;
      }
      run = true;

      exports.build({
        dir: 'build/dev',
        watch: true,
        complete: function(code) {
          process.exit(code);
        }
      });
    },
    complete: function(code) {
      process.exit(code);
    }
  });
};

desc('The default task. Executes init');
task('default', ['lumbar'], function() {});

desc('Process all lumbar modules.');
task('lumbar', [], function() {
  exports.build({
    dir: 'build/dev',
    complete: complete
  });
}, true);

desc('Builds production packages');
task('release', [], function(prefix, pkg) {
  prefix = prefix || 'phoenix';

  exports.build({
    dir: 'build/' + prefix,
    package: pkg,
    minimize: true,
    removeTests: true,
    configFile: './config/production.json',
    complete: function(code) {
      if (code) {
        process.exit(code);
      } else {
        complete();
      }
    }
  });
});

desc('Cleans any generated content out of the application');
task('clean', [], function() {
  glob.sync('build').forEach(wrench.rmdirSyncRecursive);
});

desc('Builds the app in production test mode.');
task('heroku-test', [], function() {
  exports.build({
    dir: 'build/test',
    minimize: true,
    configFile: './config/production.json',
    complete: complete
  });
}, true);

desc('Initializes the file change watcher for stylus scripts');
task('watch', [], function(server, mocks) {
  exports.watch((exports.serverName || function() {}).apply(exports, arguments), mocks);
});

desc('Starts up the server in normal mode');
task('start', [], function(server, mocks) {
  exports.startServer({proxy: exports.serverName.apply(exports, arguments), mocks: mocks});
});

desc('Testing');
task('test-runner', [], function(webOnly, xunit) {
  var superCode = 0;

  function runPhantom(platform, androidUserAgent, xunit, port, callback) {
    console.log('Running platform: ' + platform + ' androidUserAgent: ' + (!!androidUserAgent));
    var userAgent = androidUserAgent ?
            'Mozilla/5.0 (Linux; U; Android 2.3.6; en-us; Nexus S Build/GRK39F) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1'
            : 'Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3',
        phantom;
    if (exports.mochaTests) {
      var args = ['-A', userAgent, 'http://localhost:' + port + '/r/phoenix/' + platform + '/test.html'];
      if (xunit) {
        args.push('-R', 'xunit');
      }
      phantom = child_process.spawn(__dirname + '/node_modules/.bin/mocha-phantomjs', args);
    } else {
      phantom = child_process.spawn('phantomjs', [__dirname + '/test/run-qunit.js', 'http://localhost:' + port + '/r/phoenix/' + platform + '/test.html', userAgent]);
    }

    var buffer = '';
    phantom.stdout.on('data', function (data) {
      if (exports.mochaTests && xunit) {
        buffer += data;
      } else {
        streamData('  phantom: ', data);
      }
    });
    phantom.stderr.on('data', function (data) {
      streamData('  phantom err: ', data);
    });
    phantom.on('exit', function(code) {
      superCode = superCode | code;
      callback(code, buffer);
    });
  }

  function findPorts(callback) {
    portscanner.findAPortNotInUse(58080, 58090, 'localhost', function(err, port) {
      if (err) {
        throw err;
      }

      portscanner.findAPortNotInUse(port + 1, 58090, 'localhost', function(err, securePort) {
        if (err) {
          throw err;
        }

        callback(port, securePort);
      });
    });
  }

  var run;
  findPorts(function(port, securePort) {
    exports.startServer({
      proxy: (exports.serverName || function() {}).call(exports),
      mocks: true,
      test: true,
      port: port,
      securePort: securePort,
      data: function() {
        if (run) {
          return;
        }
        run = true;

        (function exec() {
          var platform = exports.testPlatforms.shift();
          if (webOnly && !platform.webOnly) {
            process.exit(superCode);
            return;
          }

          runPhantom(platform.platform, platform.androidUA, xunit, port, function(code, buffer) {
            if (exports.mochaTests && xunit) {
              fs.writeFileSync('build/' + platform.platform + (platform.androidUA ? '_android' : '') + '.xml', buffer);
            }

            if (!exports.testPlatforms.length) {
              process.exit(superCode);
            } else {
              exec();
            }
          });
        })();
      }
    });
  });
});

desc('Testing');
task('test', ['lumbar', 'test-runner'], function() {});

task('test-xunit', ['lumbar'], function() {
  jake.Task['test-runner'].invoke(undefined, true);
});
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var parser = require('socket.io-parser')
  , encode = parser.encode
  , decode = parser.decode
  , debug = require('debug')('socket.io:client');

/**
 * Module exports.
 */

module.exports = Client;

/**
 * Client constructor.
 *
 * @param {Server} server instance
 * @param {Socket} connection
 * @api private
 */

function Client(server, conn){
  this.server = server;
  this.conn = conn;
  this.id = conn.id;
  this.request = conn.request;
  this.setup();
  this.sockets = [];
  this.nsps = {};
}

/**
 * Sets up event listeners.
 *
 * @api private
 */

Client.prototype.setup = function(){
  this.onclose = this.onclose.bind(this);
  this.ondata = this.ondata.bind(this);
  this.conn.on('close', this.onclose);
  this.conn.on('data', this.ondata);
};

/**
 * Connects a client to a namespace.
 *
 * @param {String} namespace name
 * @api private
 */

Client.prototype.connect = function(name){
  debug('connecting to namespace %s', name);
  var nsp = this.server.of(name);
  var self = this;
  var sockets = this.sockets;
  var socket = nsp.add(this, function(){
    self.sockets.push(socket);
    self.nsps[nsp.name] = socket;
  });
};

/**
 * Removes a socket. Called by each `Socket`.
 *
 * @api private
 */

Client.prototype.remove = function(socket){
  var i = this.sockets.indexOf(socket);
  if (~i) {
    var nsp = this.sockets[i].nsp.name;
    this.sockets.splice(i, 1);
    delete this.nsps[nsp];
  } else {
    debug('ignoring remove for %s', socket.id);
  }
};

/**
 * Closes the underlying connection.
 *
 * @api private
 */

Client.prototype.close = function(){
  if ('open' == this.conn.readyState) {
    debug('forcing transport close');
    this.conn.close();
    this.onclose('forced server close');
  }
};

/**
 * Writes a packet to the transport.
 *
 * @param {Object} packet object
 * @api private
 */

Client.prototype.packet = function(packet){
  if ('open' == this.conn.readyState) {
    debug('writing packet %j', packet);
    this.conn.write(encode(packet));
  } else {
    debug('ignoring packet write %j', packet);
  }
};

/**
 * Called with incoming transport data.
 *
 * @api private
 */

Client.prototype.ondata = function(data){
  var packet = decode(data.toString());
  debug('got packet %j', packet);

  if (parser.CONNECT == packet.type) {
    this.connect(packet.nsp);
  } else {
    var socket = this.nsps[packet.nsp];
    if (socket) {
      socket.onpacket(packet);
    } else {
      debug('no socket for namespace %s', packet.nsp);
    }
  }
};

/**
 * Called upon transport close.
 *
 * @param {String} reason
 * @api private
 */

Client.prototype.onclose = function(reason){
  debug('client close with reason %s', reason);

  // ignore a potential subsequent `close` event
  this.destroy();

  // `nsps` and `sockets` are cleaned up seamlessly
  this.sockets.forEach(function(socket){
    socket.onclose(reason);
  });
};

/**
 * Cleans up event listeners.
 *
 * @api private
 */

Client.prototype.destroy = function(){
  this.conn.removeListener('data', this.ondata);
  this.conn.removeListener('close', this.onclose);
};
<commit_msg>client: style<commit_after>
/**
 * Module dependencies.
 */

var parser = require('socket.io-parser')
  , encode = parser.encode
  , decode = parser.decode
  , debug = require('debug')('socket.io:client');

/**
 * Module exports.
 */

module.exports = Client;

/**
 * Client constructor.
 *
 * @param {Server} server instance
 * @param {Socket} connection
 * @api private
 */

function Client(server, conn){
  this.server = server;
  this.conn = conn;
  this.id = conn.id;
  this.request = conn.request;
  this.setup();
  this.sockets = [];
  this.nsps = {};
}

/**
 * Sets up event listeners.
 *
 * @api private
 */

Client.prototype.setup = function(){
  this.onclose = this.onclose.bind(this);
  this.ondata = this.ondata.bind(this);
  this.conn.on('data', this.ondata);
  this.conn.on('close', this.onclose);
};

/**
 * Connects a client to a namespace.
 *
 * @param {String} namespace name
 * @api private
 */

Client.prototype.connect = function(name){
  debug('connecting to namespace %s', name);
  var nsp = this.server.of(name);
  var self = this;
  var sockets = this.sockets;
  var socket = nsp.add(this, function(){
    self.sockets.push(socket);
    self.nsps[nsp.name] = socket;
  });
};

/**
 * Removes a socket. Called by each `Socket`.
 *
 * @api private
 */

Client.prototype.remove = function(socket){
  var i = this.sockets.indexOf(socket);
  if (~i) {
    var nsp = this.sockets[i].nsp.name;
    this.sockets.splice(i, 1);
    delete this.nsps[nsp];
  } else {
    debug('ignoring remove for %s', socket.id);
  }
};

/**
 * Closes the underlying connection.
 *
 * @api private
 */

Client.prototype.close = function(){
  if ('open' == this.conn.readyState) {
    debug('forcing transport close');
    this.conn.close();
    this.onclose('forced server close');
  }
};

/**
 * Writes a packet to the transport.
 *
 * @param {Object} packet object
 * @api private
 */

Client.prototype.packet = function(packet){
  if ('open' == this.conn.readyState) {
    debug('writing packet %j', packet);
    this.conn.write(encode(packet));
  } else {
    debug('ignoring packet write %j', packet);
  }
};

/**
 * Called with incoming transport data.
 *
 * @api private
 */

Client.prototype.ondata = function(data){
  var packet = decode(data.toString());
  debug('got packet %j', packet);

  if (parser.CONNECT == packet.type) {
    this.connect(packet.nsp);
  } else {
    var socket = this.nsps[packet.nsp];
    if (socket) {
      socket.onpacket(packet);
    } else {
      debug('no socket for namespace %s', packet.nsp);
    }
  }
};

/**
 * Called upon transport close.
 *
 * @param {String} reason
 * @api private
 */

Client.prototype.onclose = function(reason){
  debug('client close with reason %s', reason);

  // ignore a potential subsequent `close` event
  this.destroy();

  // `nsps` and `sockets` are cleaned up seamlessly
  this.sockets.forEach(function(socket){
    socket.onclose(reason);
  });
};

/**
 * Cleans up event listeners.
 *
 * @api private
 */

Client.prototype.destroy = function(){
  this.conn.removeListener('data', this.ondata);
  this.conn.removeListener('close', this.onclose);
};
<|endoftext|>


<commit_before>function generateCombGuid() {
  function f(e) {
    for (var c = [0, 0, 0, 0, 0, 0, 0, 0], b = 0;b < c.length;b++) {
      var a = e & 255;
      c[b] = a;
      e = (e - a) / 256;
    }
    return c;
  }
  function g(a) {
    for (var c = [], b = 0;b < a.length;b++) {
      c.push((a[b] >>> 4).toString(16)), c.push((a[b] & 15).toString(16));
    }
    return c.join("");
  }
  var h = function() {
    var a = (new Date).getTime();
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
      var b = (a + 16 * Math.random()) % 16 | 0;
      a = Math.floor(a / 16);
      return("x" == c ? b : b & 7 | 8).toString(16);
    });
  }().substr(0, 24), a = moment().diff(moment([1900, 1, 1]), "days"), a = f(a).reverse(), a = a.slice(a.length - 2), a = g(a), d = Math.floor(moment().diff(moment().startOf("day")) / 3.333333), d = f(d).reverse(), d = d.slice(d.length - 4), d = g(d);
  return h + a + d;
};
<commit_msg>typo...<commit_after>function generateCombGuid() {
    function f(e) {
        for (var c = [0, 0, 0, 0, 0, 0, 0, 0], b = 0; b < c.length; b++) {
            var a = e & 255;
            c[b] = a;
            e = (e - a) / 256;
        }
        return c;
    }
    function g(a) {
        for (var c = [], b = 0; b < a.length; b++) {
            c.push((a[b] >>> 4).toString(16)), c.push((a[b] & 15).toString(16));
        }
        return c.join("");
    }
    var h = function () {
        var a = (new Date).getTime();
        return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
            var b = (a + 16 * Math.random()) % 16 | 0;
            a = Math.floor(a / 16);
            return ("x" == c ? b : b & 7 | 8).toString(16);
        });
    }().substr(0, 24), a = moment().diff(moment([1900, 1, 1]), "days"), a = f(a).reverse(), a = a.slice(a.length - 2), a = g(a), d = Math.floor(moment().diff(moment().startOf("day")) / 3.333333), d = f(d).reverse(), d = d.slice(d.length - 4), d = g(d);
    return h + a + d;
};
<|endoftext|>


<commit_before>/*
This code is dedicated to the public domain under the Unlicense. <http://unlicense.org>
Created by Nicky Case (@ncasenmare). Attribution is always welcome, but not required!
*/
(function(){

	///////////////////////////
	// DEFAULT CONFIGURATION //
	///////////////////////////

	window.SS_PROXY_SERVER = "http://jsonp.jit.su/?url=";
	window.SS_SOCIAL_API = {
		twitter: {
			template:
				"
"+
				"
{{label}}
"+
				"
{{count}}
"+
				"
",
			label: "Share on Twitter",
			requestURI: "http://urls.api.twitter.com/1/urls/count.json?url=",
			requestProperty: "count"
		},
		facebook: {
			template:
				"
"+
				"
{{label}}
"+
				"
{{count}}
"+
				"
",
			label: "Share on Facebook",
			requestURI: "http://graph.facebook.com/?id=",
			requestProperty: "shares"
		}
	};
	window.SS_STYLE = ""+
		".s-s{ display:inline-block; overflow:hidden; cursor:pointer; }"+
		".s-s #ss_label{ float:left; padding:10px; color:#fff; background:#4099FF; }"+
		".s-s #ss_count{ float:left; padding:10px; color:#000; background:#fff; }"+
		".s-s[data-type='twitter'] #ss_label{ background:#4099FF; }"+
		".s-s[data-type='twitter']:hover #ss_label{ background:#69AFFF; }"+
		".s-s[data-type='facebook'] #ss_label{ background:#3B5998; }"+
		".s-s[data-type='facebook']:hover #ss_label{ background:#5371B1; }";

	// A helper for popup windows
	window.SS_POPUP = function(url,type){

		var w,h;
		switch(type){
			case "twitter": w=550; h=500; break;
			case "facebook": w=670; h=400; break;
			default: w=500; h=500; break;
		}
		var x = (screen.width/2)-(w/2);
  		var y = (screen.height/2)-(h/2);

		var popupConfig = "width="+w+",height="+h+",left="+x+",top="+y+",";
		popupConfig += "resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes";
		window.open(url,"popup",popupConfig);

	};

	////////////////////////////////////////
	// CREATE SOCIAL MINUS SPYING BUTTONS //
	////////////////////////////////////////

	// Initialize S-S only after the rest of the page loads
	window.addEventListener("load",function(){

		// Add stylesheet to top
		var style = document.createElement("style");
		style.innerHTML = SS_STYLE;
		document.head.appendChild(style);

		// Convert all S-S divs to share buttons
		var shareButtons = document.querySelectorAll(".s-s");
		for(var i=0;i<shareButtons.length;i++){
			convertToButton(shareButtons[i]);
		}

		// And, finally...
		notifyTheNSA();

	},false);

	// Convert a placeholder S-S div to a share button
	var convertToButton = function(dom){

		// Get Social API config
		var type = dom.getAttribute("data-type");
		var apiConfig = SS_SOCIAL_API[type];
		if(!apiConfig) return;

		// Config from attribute list
		var config = {};
		for(var i=0; i<dom.attributes.length; i++){

			var attr = dom.attributes[i];

			// Is it a data- attribute?
			var name = attr.name;
			var prefixIndex = name.indexOf("data-");
			if(prefixIndex<0) continue;
			name=name.substr(prefixIndex+5);

			// If so, add to config
			config[name] = attr.value;

		}

		// If not specified, override with default Link & Text
		config.link = encodeURIComponent(config.link || window.location.href);
		config.text = encodeURIComponent(config.text || document.head.getElementsByTagName("title")[0].innerHTML);

		// If not specified, override with preset config
		for(var name in apiConfig){
			var value = apiConfig[name];
			if(config[name]) continue;
			config[name] = value;
		}

		// Generate button HTML and insert
		getShareCount(config.requestURI+config.link, config.requestProperty, function(count){
			config.count = count;
			dom.innerHTML = generateHTML(config.template,config);
		});

	};

	// Get share count: Make API request, get property of JSON response, pass to callback.
	var getShareCount = function(request,property,callback){
		var xhr = new XMLHttpRequest();
		xhr.open("GET",SS_PROXY_SERVER+request);
		xhr.onreadystatechange = function() {
			if(xhr.readyState===4 && xhr.status===200){
				var response = JSON.parse(xhr.responseText);
				var count = response[property] || 0;
				if(count>10000){
					count = Math.round(count/1000)+"K";
				}else if(count>1000){
					count = ((Math.round(count/100)*100)/1000)+"K";
				}
				callback(count);
			}
		};
		xhr.send();
	};

	// Lightweight templating
	var generateHTML = function(template,config){
		var html = template;
		for(var name in config){
			var value = config[name];
			html = html.replace("{{"+name+"}}",value,"g");
		}
		return html;
	};

	// ha ha
	var notifyTheNSA = function(){
		// I was just kidding, but thank you for reading the source!
		// It's awesome that you like taking a look under the hood.
		// Like minds! :)
	};

})();<commit_msg>Minify JS<commit_after>/*
This code is dedicated to the public domain under the Unlicense. <http://unlicense.org>
Created by Nicky Case (@ncasenmare). Attribution is always welcome, but not required!
*/
(function(){window.SS_PROXY_SERVER="http://jsonp.jit.su/?url=";window.SS_SOCIAL_API={twitter:{template:"
"+"
{{label}}
"+"
{{count}}
"+"
",label:"Share on Twitter",requestURI:"http://urls.api.twitter.com/1/urls/count.json?url=",requestProperty:"count"},facebook:{template:"
"+"
{{label}}
"+"
{{count}}
"+"
",label:"Share on Facebook",requestURI:"http://graph.facebook.com/?id=",requestProperty:"shares"}};window.SS_STYLE=""+".s-s{ display:inline-block; overflow:hidden; cursor:pointer; }"+".s-s #ss_label{ float:left; padding:10px; color:#fff; background:#4099FF; }"+".s-s #ss_count{ float:left; padding:10px; color:#000; background:#fff; }"+".s-s[data-type='twitter'] #ss_label{ background:#4099FF; }"+".s-s[data-type='twitter']:hover #ss_label{ background:#69AFFF; }"+".s-s[data-type='facebook'] #ss_label{ background:#3B5998; }"+".s-s[data-type='facebook']:hover #ss_label{ background:#5371B1; }";window.SS_POPUP=function(url,type){var w,h;switch(type){case"twitter":w=550;h=500;break;case"facebook":w=670;h=400;break;default:w=500;h=500;break}var x=(screen.width/2)-(w/2);var y=(screen.height/2)-(h/2);var popupConfig="width="+w+",height="+h+",left="+x+",top="+y+",";popupConfig+="resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes";window.open(url,"popup",popupConfig)};window.addEventListener("load",function(){var style=document.createElement("style");style.innerHTML=SS_STYLE;document.head.appendChild(style);var shareButtons=document.querySelectorAll(".s-s");for(var i=0;i<shareButtons.length;i++){convertToButton(shareButtons[i])}notifyTheNSA()},false);var convertToButton=function(dom){var type=dom.getAttribute("data-type");var apiConfig=SS_SOCIAL_API[type];if(!apiConfig)return;var config={};for(var i=0;i<dom.attributes.length;i++){var attr=dom.attributes[i];var name=attr.name;var prefixIndex=name.indexOf("data-");if(prefixIndex<0)continue;name=name.substr(prefixIndex+5);config[name]=attr.value}config.link=encodeURIComponent(config.link||window.location.href);config.text=encodeURIComponent(config.text||document.head.getElementsByTagName("title")[0].innerHTML);for(var name in apiConfig){var value=apiConfig[name];if(config[name])continue;config[name]=value}getShareCount(config.requestURI+config.link,config.requestProperty,function(count){config.count=count;dom.innerHTML=generateHTML(config.template,config)})};var getShareCount=function(request,property,callback){var xhr=new XMLHttpRequest();xhr.open("GET",SS_PROXY_SERVER+request);xhr.onreadystatechange=function(){if(xhr.readyState===4&&xhr.status===200){var response=JSON.parse(xhr.responseText);var count=response[property]||0;if(count>10000){count=Math.round(count/1000)+"K"}else if(count>1000){count=((Math.round(count/100)*100)/1000)+"K"}callback(count)}};xhr.send()};var generateHTML=function(template,config){var html=template;for(var name in config){var value=config[name];html=html.replace("{{"+name+"}}",value,"g")}return html};var notifyTheNSA=function(){}})();<|endoftext|>


<commit_before>/*//  !	SQF - Simplified Query Functions - V1.1 05/2018 ! \\*/
/*//  !	Gabriel Tessarini !	\\*/
function sqf(){}sqf.prototype.create=function(){for(var r="{",e=arguments,t=e.length,n=0;n<t;)r+=n<t-1?'"'+e[n]+'":[],':'"'+e[n]+'":[]',n++;return r+="}",r=JSON.parse(r)},sqf.prototype.alterAdd=function(r,e){var t=JSON.stringify(r);return t=(t=t.substring(0,t.length-1))+', "'+e+'":[]}',r=JSON.parse(t)},sqf.prototype.alterDrop=function(r,e){for(var t in r)t==e&&delete r[t];return r},sqf.prototype.truncate=function(r){for(var e in r)r[e]=[];return r},sqf.prototype.insert=function(){var r,e=arguments[0],t=0,n=arguments;if(n.length>2?t++:n=n[1],r=n.length,e instanceof Array)if(n instanceof Array||n===arguments)for(;t<r;)e[e.length]=n[t],t++;else e[e.length]=n;else{var o=[],f=1===t?0:t;for(var a in e)o[o.length]=a;for(;t<r;){for(var l in e)l==o[f]&&(e[l]instanceof Array||(e[l]=[e[l]]),e[l][e[l].length]=n[t]);t++,f++}}return e},sqf.prototype.update=function(r,e,t){for(var n=0,o=r.length;n<o;)r[n]=r[n]===e?t:r[n],n++;return r},sqf.prototype.delete=function(r,e){for(var t=[],n=0,o=r.length;n<o;)r[n]!==e&&(t[t.length]=r[n]),n++;return t.length&&(r=t),r},sqf.prototype.where=function(r,e,t,n,o){var f=null;if(""==e.trim())return f;var a=r.length;if(null===(o=void 0===o||0==o?a:void 0!==o&&(1==o||o>=0)?o:null))return f;for(var l=[],i=!1,s=0,u=!0;u&&(s<a&&o>=a||l.length<o&&s<a);){switch(e){case"==":i=r[s]==t;break;case"===":i=r[s]===t;break;case"!=":i=r[s]!=t;break;case"!==":i=r[s]!==t;break;case">":i=r[s]>t;break;case"<":i=r[s]<t;break;case">=":i=r[s]>=t;break;case"<=":i=r[s]<=t;break;case"isNull":i=(i=null===r[s])==t;break;case"isNotNull":i=(i=null!==r[s]||i)==t;break;case"typeof":i=typeof r[s]==t;break;case"instanceof":i=r[s]instanceof t;break;case"isEven":i=(i=r[s]%2==0)==t;break;case"isOdd":i=(i=r[s]%2!=0)==t;break;default:i=!1,u=!1}if(!0===i)if(f=void 0!==n&&1==n?s:r[s],o===a)l[l.length]=f;else{if(1==o)break;l.length<o&&(l[l.length]=f)}s++}return l.length&&(f=l,1===l.length&&(f=l[0])),f},sqf.prototype.repeat=function(r,e){for(var t=0,n=arguments;t<e;)r.apply(this,n),t++},sqf.prototype.isNull=function(r){return null===r},sqf.prototype.isNotNull=function(r){return null!==r},sqf.prototype.nullTo=function(r,e){if(r instanceof Array||null!==r){if(r instanceof Array)for(var t=0,n=r.length;t<n;)r[t]=null===r[t]?e:r[t],t++}else r=e;return r},sqf.prototype.isUnique=function(r,e){for(var t=e.length,n=0,o=0;n<t&&o<=1;)o+=e[n]===r?1:0,n++;return 1===o},sqf.prototype.isEven=function(r){return r%2==0},sqf.prototype.isOdd=function(r){return r%2!=0},sqf.prototype.sum=function(r){for(var e=0,t=0,n=r.length;t<n;)e+=1*r[t],t++;return e},sqf.prototype.multiply=function(r){for(var e=1,t=0,n=r.length;t<n;)e*=1*r[t],t++;return e},sqf.prototype.average=function(r){for(var e=0,t=0,n=r.length;t<n;)e+=1*r[t],t++;return e/=n},sqf.prototype.min=function(r){for(var e=1*r[0],t=0,n=r.length;t<n;)1*r[t]<e&&(e=1*r[t]),t++;return e},sqf.prototype.max=function(r){for(var e=1*r[0],t=0,n=r.length;t<n;)1*r[t]>e&&(e=1*r[t]),t++;return e},sqf.prototype.difference=function(r,e,t){var n=0,o=r.length,f=e.length;if(void 0!==t&&1==t)return n=(n=o-f)<0?-1*(o-f):n;var a,l,i=0,s=r,u=e;n=[];for(var p=o+f;i<3;){for(l=0;l<p;){for(a=0;a<p;)s[a]===u[l]&&(s.splice(a,1),u.splice(l,1)),a++;l++}i++}if(s.length)for(a=0;a<s.length;)n[n.length]=s[a],a++;if(u.length)for(a=0;a<u.length;)n[n.length]=u[a],a++;return n},sqf.prototype.variance=function(r){for(var e=0,t=0,n=0,o=r.length;n<o;)t+=1*r[n],n++;for(t/=o,n=0;n<o;)e+=(1*r[n]-t)*(1*r[n]-t),n++;return e/=o-1},sqf.prototype.deviation=function(r){for(var e=0,t=0,n=0,o=r.length;n<o;)t+=1*r[n],n++;for(t/=o,n=0;n<o;)e+=(1*r[n]-t)*(1*r[n]-t),n++;return e/=o-1,e=Math.sqrt(e)};
var sq=new sqf;
<commit_msg>SQF - Correcting delete function<commit_after>/*//  !	SQF - Simplified Query Functions - Version 1.1.1 05/2018 ! \\*/
/*//  !	Gabriel Tessarini !	\\*/
function sqf(){}sqf.prototype.create=function(){for(var r="{",e=arguments,t=e.length,n=0;n<t;)r+=n<t-1?'"'+e[n]+'":[],':'"'+e[n]+'":[]',n++;return r+="}",r=JSON.parse(r)},sqf.prototype.alterAdd=function(r,e){var t=JSON.stringify(r);return t=(t=t.substring(0,t.length-1))+', "'+e+'":[]}',r=JSON.parse(t)},sqf.prototype.alterDrop=function(r,e){for(var t in r)t==e&&delete r[t];return r},sqf.prototype.truncate=function(r){for(var e in r)r[e]=[];return r},sqf.prototype.insert=function(){var r,e=arguments[0],t=0,n=arguments;if(n.length>2?t++:n=n[1],r=n.length,e instanceof Array)if(n instanceof Array||n===arguments)for(;t<r;)e[e.length]=n[t],t++;else e[e.length]=n;else{var o=[],f=1===t?0:t;for(var a in e)o[o.length]=a;for(;t<r;){for(var l in e)l==o[f]&&(e[l]instanceof Array||(e[l]=[e[l]]),e[l][e[l].length]=n[t]);t++,f++}}return e},sqf.prototype.update=function(r,e,t){for(var n=0,o=r.length;n<o;)r[n]=r[n]===e?t:r[n],n++;return r},sqf.prototype.delete=function(r,e){for(var t=[],n=0,o=r.length;n<o;)r[n]!==e&&(t[t.length]=r[n]),n++;return r=t},sqf.prototype.where=function(r,e,t,n,o){var f=null;if(""==e.trim())return f;var a=r.length;if(null===(o=void 0===o||0==o?a:void 0!==o&&(1==o||o>=0)?o:null))return f;for(var l=[],i=!1,s=0,u=!0;u&&(s<a&&o>=a||l.length<o&&s<a);){switch(e){case"==":i=r[s]==t;break;case"===":i=r[s]===t;break;case"!=":i=r[s]!=t;break;case"!==":i=r[s]!==t;break;case">":i=r[s]>t;break;case"<":i=r[s]<t;break;case">=":i=r[s]>=t;break;case"<=":i=r[s]<=t;break;case"isNull":i=(i=null===r[s])==t;break;case"isNotNull":i=(i=null!==r[s]||i)==t;break;case"typeof":i=typeof r[s]==t;break;case"instanceof":i=r[s]instanceof t;break;case"isEven":i=(i=r[s]%2==0)==t;break;case"isOdd":i=(i=r[s]%2!=0)==t;break;default:i=!1,u=!1}if(!0===i)if(f=void 0!==n&&1==n?s:r[s],o===a)l[l.length]=f;else{if(1==o)break;l.length<o&&(l[l.length]=f)}s++}return l.length&&(f=l,1===l.length&&(f=l[0])),f},sqf.prototype.repeat=function(r,e){for(var t=0,n=arguments;t<e;)r.apply(this,n),t++},sqf.prototype.isNull=function(r){return null===r},sqf.prototype.isNotNull=function(r){return null!==r},sqf.prototype.nullTo=function(r,e){if(r instanceof Array||null!==r){if(r instanceof Array)for(var t=0,n=r.length;t<n;)r[t]=null===r[t]?e:r[t],t++}else r=e;return r},sqf.prototype.isUnique=function(r,e){for(var t=e.length,n=0,o=0;n<t&&o<=1;)o+=e[n]===r?1:0,n++;return 1===o},sqf.prototype.isEven=function(r){return r%2==0},sqf.prototype.isOdd=function(r){return r%2!=0},sqf.prototype.sum=function(r){for(var e=0,t=0,n=r.length;t<n;)e+=1*r[t],t++;return e},sqf.prototype.multiply=function(r){for(var e=1,t=0,n=r.length;t<n;)e*=1*r[t],t++;return e},sqf.prototype.average=function(r){for(var e=0,t=0,n=r.length;t<n;)e+=1*r[t],t++;return e/=n},sqf.prototype.min=function(r){for(var e=1*r[0],t=0,n=r.length;t<n;)1*r[t]<e&&(e=1*r[t]),t++;return e},sqf.prototype.max=function(r){for(var e=1*r[0],t=0,n=r.length;t<n;)1*r[t]>e&&(e=1*r[t]),t++;return e},sqf.prototype.difference=function(r,e,t){var n=0,o=r.length,f=e.length;if(void 0!==t&&1==t)return n=(n=o-f)<0?-1*(o-f):n;var a,l,i=0,s=r,u=e;n=[];for(var p=o+f;i<3;){for(l=0;l<p;){for(a=0;a<p;)s[a]===u[l]&&(s.splice(a,1),u.splice(l,1)),a++;l++}i++}if(s.length)for(a=0;a<s.length;)n[n.length]=s[a],a++;if(u.length)for(a=0;a<u.length;)n[n.length]=u[a],a++;return n},sqf.prototype.variance=function(r){for(var e=0,t=0,n=0,o=r.length;n<o;)t+=1*r[n],n++;for(t/=o,n=0;n<o;)e+=(1*r[n]-t)*(1*r[n]-t),n++;return e/=o-1},sqf.prototype.deviation=function(r){for(var e=0,t=0,n=0,o=r.length;n<o;)t+=1*r[n],n++;for(t/=o,n=0;n<o;)e+=(1*r[n]-t)*(1*r[n]-t),n++;return e/=o-1,e=Math.sqrt(e)};
var sq=new sqf;
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom/server';
import serialize from 'serialize-javascript';
import Helmet from 'react-helmet';
import gtm from 'react-google-tag-manager';

/**
 * Wrapper component containing HTML metadata and boilerplate tags.
 * Used in server-side code only to wrap the string output of the
 * rendered route component.
 *
 * The only thing this component doesn't (and can't) include is the
 * HTML doctype declaration, which is added to the rendered output
 * by the server.js file.
 */
export default class Html extends Component {
    static propTypes = {
        assets: PropTypes.object,
        component: PropTypes.node,
        store: PropTypes.object
    };

    render() {
        const { assets, component, store } = this.props;
        const content = component ? ReactDOM.renderToString(component) : '';
        const head = Helmet.rewind();
        const gtmInstance = gtm({
            id: ''
        });

        return (

                    { head.base.toComponent() }
                    { head.title.toComponent() }
                    { head.meta.toComponent() }
                    { head.link.toComponent() }
                    { head.script.toComponent() }

                    <link rel="icon" type="image/vnd.microsoft.icon" href="/favicon.ico"/>
                    <link rel="apple-touch-icon" type="image/png" href="/favicon.png"/>
                    <link
                        rel="apple-touch-icon"
                        type="image/png"
                        href="/favicon-152.png"
                        sizes="152x152"
                    />

                    {/* styles (will be present only in production with webpack extract text plugin) */}
                    { Object.keys(assets.styles).map((style, key) =>
                        <link
                            href={ assets.styles[style] }
                            key={ key }
                            media="screen, projection"
                            rel="stylesheet"
                            type="text/css"
                            charSet="UTF-8"
                        />
                    ) }

                    { gtmInstance.noScriptAsReact() }
                    { gtmInstance.scriptAsReact() }


<commit_before>
export const includes = (array, key) =>
  array.indexOf(key) !== -1;

export const isString = maybeString =>
  typeof maybeString === 'string';

export const isObject = maybeObject =>
  typeof maybeObject === 'object';

export const isFunction = maybeFunction =>
  typeof maybeFunction === 'function';

export const pick = (obj, ...keys) =>
  keys.reduce((soFar, key) => {
    if (includes(keys, key) && obj[key] !== undefined) {
      soFar[key] = obj[key]; // eslint-disable-line no-param-reassign
    }
    return soFar;
  }, {});

export const mapObject = (object, func) =>
  Object.keys(object).reduce((soFar, key) => {
    soFar[key] = func(object[key]); // eslint-disable-line no-param-reassign
    return soFar;
  }, {});

export const mergeObjects = (object, ...sources) => {
  const {concat} = Array.prototype;
  const uniqueKeys = concat.apply(Object.keys(object), sources.map(Object.keys))
    .filter((value, index, self) => self.indexOf(value) === index);
  return uniqueKeys.reduce((soFar, key) => {
    soFar[key] = Object.assign(soFar[key] || {}, ...sources.map(source => source[key] || {})); // eslint-disable-line no-param-reassign
    return soFar;
  }, object);
};

export const startsWith = (string, target) =>
  String(string).slice(0, target.length) === target;

export const endsWith = (string, target) =>
  String(string).slice(string.length - target.length) === target;

export const ucfirst = str =>
  str.charAt(0).toUpperCase() + str.substr(1);

export const upperSnakeCase = string =>
  String(string.split('').reduce((soFar, letter, index) => {
    const charCode = letter.charCodeAt(0);
    return soFar + (index && charCode < 97 ? `_${letter}` : letter).toUpperCase();
  }, ''));

export const getGerundName = name =>
  `${name.replace(/e$/, '')}ing`;

export const getPluralName = name =>
  `${name}s`;
<commit_msg>fix(naming): fixed the plural name when ends with a 's' (#25)<commit_after>
export const includes = (array, key) =>
  array.indexOf(key) !== -1;

export const isString = maybeString =>
  typeof maybeString === 'string';

export const isObject = maybeObject =>
  typeof maybeObject === 'object';

export const isFunction = maybeFunction =>
  typeof maybeFunction === 'function';

export const pick = (obj, ...keys) =>
  keys.reduce((soFar, key) => {
    if (includes(keys, key) && obj[key] !== undefined) {
      soFar[key] = obj[key]; // eslint-disable-line no-param-reassign
    }
    return soFar;
  }, {});

export const mapObject = (object, func) =>
  Object.keys(object).reduce((soFar, key) => {
    soFar[key] = func(object[key]); // eslint-disable-line no-param-reassign
    return soFar;
  }, {});

export const mergeObjects = (object, ...sources) => {
  const {concat} = Array.prototype;
  const uniqueKeys = concat.apply(Object.keys(object), sources.map(Object.keys))
    .filter((value, index, self) => self.indexOf(value) === index);
  return uniqueKeys.reduce((soFar, key) => {
    soFar[key] = Object.assign(soFar[key] || {}, ...sources.map(source => source[key] || {})); // eslint-disable-line no-param-reassign
    return soFar;
  }, object);
};

export const startsWith = (string, target) =>
  String(string).slice(0, target.length) === target;

export const endsWith = (string, target) =>
  String(string).slice(string.length - target.length) === target;

export const ucfirst = str =>
  str.charAt(0).toUpperCase() + str.substr(1);

export const upperSnakeCase = string =>
  String(string.split('').reduce((soFar, letter, index) => {
    const charCode = letter.charCodeAt(0);
    return soFar + (index && charCode < 97 ? `_${letter}` : letter).toUpperCase();
  }, ''));

export const getGerundName = name =>
  `${name.replace(/e$/, '')}ing`;

export const getPluralName = (name = '') =>
  (name.endsWith('s') ? name : `${name}s`);
<|endoftext|>


<commit_before>
import winston from "winston";
import zmq from "zmq";
import _ from "underscore";

import InputVertex from "./InputVertex";
import SK from "../../sk";
import m from "../MagicFilters";

const MAIN_SWITCHER_LABEL = "mainSwitcher";
const SPLIT_SCREEN_TOP_SWITCHER_LABEL = "splitScreenTopSwitcher";
const SPLIT_SCREEN_BOTTOM_SWITCHER_LABEL = "splitScreenBottomSwitcher";
const SPLIT_SCREEN_BOTTOM_CROP_LABEL = "splitScreenBottomCrop";
const SPLIT_SCREEN_BOTTOM_OVERLAY_LABEL = "splitScreenBottomOverlay";

// This is hacky as hell but it doesn't seem to work if I send all messages at once.
const ZMQ_SEND_INTERVAL = 1000;

export default class MagicVertex extends InputVertex {
  constructor({id}) {
    super({id});
    this.rewriteStream = false;
    // this.debug = true;
    this.zmqQueue = [];
    this.zmqIsRunning = false;
    this.videoOutputURL = this.transport.getOutputURL();
    this.audioOutputURL = this.transport.getOutputURL();
  }

  cleanup() {
    super.cleanup();
    this.positionVertexHandle.stop();

    if (this.zmqSocket) {
      try {
        this.zmqSocket.unmonitor();
        this.zmqSocket.disconnect(this.zmqAddress);
      }
      catch (e) {
        this.error("Error disconnecting from ZMQ: ", e.stack);
      }
    }
  }

  handleInitialPull() {
    this.currentPositions = this.doc.params.positions;
    this.positionVertexHandle = SK.vertices.watch({id: this.id}).on("updated", ([vertex]) => {
      const newPositions = vertex.params.positions;
      Object.keys(vertex.params.positions).forEach((inputName) => {
        if (!_(this.currentPositions[inputName]).isEqual(newPositions[inputName])) {
          this.currentPositions[inputName] = newPositions[inputName];
          this.doZMQUpdate(inputName);
        }
      });
      this.currentPositions = newPositions;
    });
    this.doc.inputs.forEach((input) => {
      input.sockets.forEach((socket) => {
        socket.url = this.transport.getInputURL();
      });
    });
    const newVertex = {
      inputs: this.doc.inputs,
      outputs: [{
        name: "default",
        sockets: [{
          url: this.videoOutputURL,
          type: "video",
        }, {
          url: this.audioOutputURL,
          type: "audio",
        }]
      }]

    };
    SK.vertices.update(this.doc.id, newVertex)
    .then(() => {
      this.init();
    })
    .catch((err) => {
      winston.error(err);
    });
  }

  _sendNextZMQMessage() {
    // If there's nothing to do, we're not running anymore.
    if (this.zmqQueue.length === 0) {
      this.zmqIsRunning = false;
      return;
    }
    // If we're not connected yet, chill. We'll get called again when we do.
    if (!this.zmqSocket) {
      this.zmqIsRunning = false;
      return;
    }
    // Otherwise, send a message and queue the next one.
    const msg = this.zmqQueue.pop();
    this.info(`ZMQ: ${msg}`);
    this.zmqSocket.send(msg);
    this.zmqIsRunning = true;
    setTimeout(this._sendNextZMQMessage.bind(this), ZMQ_SEND_INTERVAL);
  }

  doZMQUpdate(inputName) {
    const send = (msg) => {
      this.zmqQueue.push(msg);
    };
    const pos = this.currentPositions[inputName];
    const overlayLabel = this.ffmpeg.filterLabels[`${inputName}-overlay`];
    const scaleLabel = this.ffmpeg.filterLabels[`${inputName}-scale`];
    send(`${overlayLabel} x ${pos.x}`);
    send(`${overlayLabel} y ${pos.y}`);
    send(`${scaleLabel} width ${pos.width}`);
    send(`${scaleLabel} height ${pos.height}`);
    if (!this.zmqIsRunning) {
      this._sendNextZMQMessage();
    }
  }

  init() {
    super.init();
    try {
      this.ffmpeg = this.createffmpeg();
      this.zmqPort = this.getTCP();
      this.zmqAddress = `tcp://*:${this.zmqPort}`;

      const videoInputSockets = [];
      const audioInputSockets = [];
      let currentIdx = 0;

      this.doc.inputs.forEach((input, inputIdx) => {
        input.sockets.forEach((socket, socketIdx) => {
          socket.name = `${input.name}-${socketIdx}`;
          socket.inputName = input.name;
          this.ffmpeg
            .input(socket.url)
            .inputFormat("mpegts")
            .inputOptions([
              "-analyzeduration 10000000",
              "-noaccurate_seek", // Not really sure if this helps, but we certainly don't need
                                  // any kind of accurate seek.
              "-probesize 60000000",
              "-thread_queue_size 16384",
              // "-avioflags direct",
            ]);

          // Set up video input
          if (socket.type === "video") {
            videoInputSockets.push(socket);
            if (input.name === "background") {
              this.ffmpeg.magic(
                `${currentIdx}:v`,
                m.framerate("30"),
                m.scale(1920, 1080),
                `${socket.name}`
              );
            }
            else {
              const pos = this.doc.params.positions[input.name];
              this.ffmpeg.magic(
                `${currentIdx}:v`,
                m.framerate("30"),
                m.scale([pos.width, pos.height], {_label: `${input.name}-scale`}),
                `${socket.name}`
              );
            }
          }

          // Set up audio input
          else if (socket.type === "audio") {
            audioInputSockets.push(socket);
            this.ffmpeg.magic(
              `${currentIdx}:a`,
              m.aresample({
                async: 1,
                min_hard_comp: 0.100000,
                first_pts: 0
              }),
              m.volume({
                _label: `${socket.name}-volume`
              }),
              `${socket.name}-adjusted`
            );
          }

          else {
            throw new Error(`Unknown input type: ${input.type}`);
          }
          currentIdx += 1;
        });
      });

      // Do a series of overlays for the input
      let currentOverlayBG = "background-0";
      videoInputSockets.forEach((socket, i) => {
        if (socket.name === currentOverlayBG) {
          // First one doesn't need to overlay onto nothing. Return.
          return;
        }
        const newOverlayBG = `${socket.name}-overlay`;
        const pos = this.doc.params.positions[socket.inputName];
        this.ffmpeg.magic(
          currentOverlayBG,
          socket.name,
          m.overlay({
            x: pos.x,
            y: pos.y,
            _label: `${socket.inputName}-overlay`
          }),
          newOverlayBG
        );
        currentOverlayBG = newOverlayBG;
      });

      this.ffmpeg
        .outputOptions([
          "-copyts",
          "-copytb 1",
          "-vsync passthrough",
          // "-sws_flags +neighbor",
          "-pix_fmt yuv420p",
          // "-profile:v baseline",
          // "-use_wallclock_as_timestamps 1",
          "-fflags +igndts",
          "-loglevel verbose",
        ])
        .magic(
          currentOverlayBG,
          m.zmq({bind_address: this.zmqAddress}),
          m.framerate("30"),
          "videoOutput"
        )
        .outputOptions([
          "-map [videoOutput]",
          "-b:v 4000k",
          "-allow_skip_frames 1",
          // "-preset veryfast",
          // "-x264opts keyint=60",
          // "-b:v 4000k",
          // "-minrate 4000k",
          // "-maxrate 4000k",
          // "-bufsize 1835k",
          // "-frame_drop_threshold 60",
        ])
        .once("progress", () => {
          const socket = zmq.socket("req");
          socket.on("connect", (fd, ep) => {
            this.zmqSocket = socket;
            if (!this.zmqIsRunning) {
              this._sendNextZMQMessage();
            }
            let idx = 0;
            let label = this.ffmpeg.filterLabels[MAIN_SWITCHER_LABEL];
          });
          socket.on("connect", (fd, ep) => {this.info("connect, endpoint:", ep);});
          socket.on("connect_delay", (fd, ep) => {this.info("connect_delay, endpoint:", ep);});
          socket.on("connect_retry", (fd, ep) => {this.info("connect_retry, endpoint:", ep);});
          socket.on("listen", (fd, ep) => {this.info("listen, endpoint:", ep);});
          socket.on("bind_error", (fd, ep) => {this.info("bind_error, endpoint:", ep);});
          socket.on("accept", (fd, ep) => {this.info("accept, endpoint:", ep);});
          socket.on("accept_error", (fd, ep) => {this.info("accept_error, endpoint:", ep);});
          socket.on("close", (fd, ep) => {this.info("close, endpoint:", ep);});
          socket.on("close_error", (fd, ep) => {this.info("close_error, endpoint:", ep);});
          socket.on("disconnect", (fd, ep) => {this.info("disconnect, endpoint:", ep);});
          socket.on("message", (msg) => {this.info("message: ", msg.toString());});
          socket.monitor(500, 0);
          socket.connect(`tcp://127.0.0.1:${this.zmqPort}`);
        })
        .output(this.videoOutputURL)
        .outputFormat("mpegts")
        .videoCodec("libopenh264")

        .magic(
          ...audioInputSockets.map(s => `${s.name}-adjusted`),
          m.amix({
            inputs: audioInputSockets.length
          }),
          "audioOutput"
        )

        .output(this.audioOutputURL)
        .outputOptions([
          "-map [audioOutput]"
        ])
        .outputFormat("mpegts")
        .audioCodec("aac");

        // .input(this.inputURL)
        // .inputFormat("mpegts")
        // // .inputOptions("-itsoffset 00:00:05")
        // .outputOptions([
        // ])
        // .videoCodec("libx264")
        // .audioCodec("pcm_s16le")
        // .outputOptions([
        //   "-preset ultrafast",
        //   "-tune zerolatency",
        //   "-x264opts keyint=5:min-keyint=",
        //   "-pix_fmt yuv420p",
        //   "-filter_complex",
        //   [
        //     `[0:a]asetpts='(RTCTIME - ${this.SERVER_START_TIME}) / (TB * 1000000)'[out_audio]`,
        //     `[0:v]setpts='(RTCTIME - ${this.SERVER_START_TIME}) / (TB * 1000000)'[out_video]`,
        //   ].join(";")
        // ])

        // // Video output
        // .output(this.videoOutputURL)
        // .outputOptions([
        //   "-map [out_video]",
        // ])
        // .outputFormat("mpegts")

        // // Audio output
        // .output(this.audioOutputURL)
        // .outputOptions([
        //   "-map [out_audio]",
        // ])
        // .outputFormat("mpegts");

      this.ffmpeg.run();
    }
    catch (err) {
      this.error(err);
      this.retry();
    }
  }
}
<commit_msg>-fflags +nobuffer<commit_after>
import winston from "winston";
import zmq from "zmq";
import _ from "underscore";

import InputVertex from "./InputVertex";
import SK from "../../sk";
import m from "../MagicFilters";

const MAIN_SWITCHER_LABEL = "mainSwitcher";
const SPLIT_SCREEN_TOP_SWITCHER_LABEL = "splitScreenTopSwitcher";
const SPLIT_SCREEN_BOTTOM_SWITCHER_LABEL = "splitScreenBottomSwitcher";
const SPLIT_SCREEN_BOTTOM_CROP_LABEL = "splitScreenBottomCrop";
const SPLIT_SCREEN_BOTTOM_OVERLAY_LABEL = "splitScreenBottomOverlay";

// This is hacky as hell but it doesn't seem to work if I send all messages at once.
const ZMQ_SEND_INTERVAL = 1000;

export default class MagicVertex extends InputVertex {
  constructor({id}) {
    super({id});
    this.rewriteStream = false;
    // this.debug = true;
    this.zmqQueue = [];
    this.zmqIsRunning = false;
    this.videoOutputURL = this.transport.getOutputURL();
    this.audioOutputURL = this.transport.getOutputURL();
  }

  cleanup() {
    super.cleanup();
    this.positionVertexHandle.stop();

    if (this.zmqSocket) {
      try {
        this.zmqSocket.unmonitor();
        this.zmqSocket.disconnect(this.zmqAddress);
      }
      catch (e) {
        this.error("Error disconnecting from ZMQ: ", e.stack);
      }
    }
  }

  handleInitialPull() {
    this.currentPositions = this.doc.params.positions;
    this.positionVertexHandle = SK.vertices.watch({id: this.id}).on("updated", ([vertex]) => {
      const newPositions = vertex.params.positions;
      Object.keys(vertex.params.positions).forEach((inputName) => {
        if (!_(this.currentPositions[inputName]).isEqual(newPositions[inputName])) {
          this.currentPositions[inputName] = newPositions[inputName];
          this.doZMQUpdate(inputName);
        }
      });
      this.currentPositions = newPositions;
    });
    this.doc.inputs.forEach((input) => {
      input.sockets.forEach((socket) => {
        socket.url = this.transport.getInputURL();
      });
    });
    const newVertex = {
      inputs: this.doc.inputs,
      outputs: [{
        name: "default",
        sockets: [{
          url: this.videoOutputURL,
          type: "video",
        }, {
          url: this.audioOutputURL,
          type: "audio",
        }]
      }]

    };
    SK.vertices.update(this.doc.id, newVertex)
    .then(() => {
      this.init();
    })
    .catch((err) => {
      winston.error(err);
    });
  }

  _sendNextZMQMessage() {
    // If there's nothing to do, we're not running anymore.
    if (this.zmqQueue.length === 0) {
      this.zmqIsRunning = false;
      return;
    }
    // If we're not connected yet, chill. We'll get called again when we do.
    if (!this.zmqSocket) {
      this.zmqIsRunning = false;
      return;
    }
    // Otherwise, send a message and queue the next one.
    const msg = this.zmqQueue.pop();
    this.info(`ZMQ: ${msg}`);
    this.zmqSocket.send(msg);
    this.zmqIsRunning = true;
    setTimeout(this._sendNextZMQMessage.bind(this), ZMQ_SEND_INTERVAL);
  }

  doZMQUpdate(inputName) {
    const send = (msg) => {
      this.zmqQueue.push(msg);
    };
    const pos = this.currentPositions[inputName];
    const overlayLabel = this.ffmpeg.filterLabels[`${inputName}-overlay`];
    const scaleLabel = this.ffmpeg.filterLabels[`${inputName}-scale`];
    send(`${overlayLabel} x ${pos.x}`);
    send(`${overlayLabel} y ${pos.y}`);
    send(`${scaleLabel} width ${pos.width}`);
    send(`${scaleLabel} height ${pos.height}`);
    if (!this.zmqIsRunning) {
      this._sendNextZMQMessage();
    }
  }

  init() {
    super.init();
    try {
      this.ffmpeg = this.createffmpeg();
      this.zmqPort = this.getTCP();
      this.zmqAddress = `tcp://*:${this.zmqPort}`;

      const videoInputSockets = [];
      const audioInputSockets = [];
      let currentIdx = 0;

      this.doc.inputs.forEach((input, inputIdx) => {
        input.sockets.forEach((socket, socketIdx) => {
          socket.name = `${input.name}-${socketIdx}`;
          socket.inputName = input.name;
          this.ffmpeg
            .input(socket.url)
            .inputFormat("mpegts")
            .inputOptions([
              "-analyzeduration 10000000",
              "-noaccurate_seek", // Not really sure if this helps, but we certainly don't need
                                  // any kind of accurate seek.
              "-probesize 60000000",
              "-thread_queue_size 16384",
              // "-avioflags direct",
            ]);

          // Set up video input
          if (socket.type === "video") {
            videoInputSockets.push(socket);
            if (input.name === "background") {
              this.ffmpeg.magic(
                `${currentIdx}:v`,
                m.framerate("30"),
                m.scale(1920, 1080),
                `${socket.name}`
              );
            }
            else {
              const pos = this.doc.params.positions[input.name];
              this.ffmpeg.magic(
                `${currentIdx}:v`,
                m.framerate("30"),
                m.scale([pos.width, pos.height], {_label: `${input.name}-scale`}),
                `${socket.name}`
              );
            }
          }

          // Set up audio input
          else if (socket.type === "audio") {
            audioInputSockets.push(socket);
            this.ffmpeg.magic(
              `${currentIdx}:a`,
              m.aresample({
                async: 1,
                min_hard_comp: 0.100000,
                first_pts: 0
              }),
              m.volume({
                _label: `${socket.name}-volume`
              }),
              `${socket.name}-adjusted`
            );
          }

          else {
            throw new Error(`Unknown input type: ${input.type}`);
          }
          currentIdx += 1;
        });
      });

      // Do a series of overlays for the input
      let currentOverlayBG = "background-0";
      videoInputSockets.forEach((socket, i) => {
        if (socket.name === currentOverlayBG) {
          // First one doesn't need to overlay onto nothing. Return.
          return;
        }
        const newOverlayBG = `${socket.name}-overlay`;
        const pos = this.doc.params.positions[socket.inputName];
        this.ffmpeg.magic(
          currentOverlayBG,
          socket.name,
          m.overlay({
            x: pos.x,
            y: pos.y,
            _label: `${socket.inputName}-overlay`
          }),
          newOverlayBG
        );
        currentOverlayBG = newOverlayBG;
      });

      this.ffmpeg
        .outputOptions([
          "-copyts",
          "-copytb 1",
          "-vsync passthrough",

          // I think this flag just causes it to discard the analysis buffer when the stream starts
          "-fflags +nobuffer",

          // "-sws_flags +neighbor",
          "-pix_fmt yuv420p",
          // "-profile:v baseline",
          // "-use_wallclock_as_timestamps 1",
          "-fflags +igndts",
          "-loglevel verbose",
        ])
        .magic(
          currentOverlayBG,
          m.zmq({bind_address: this.zmqAddress}),
          m.framerate("30"),
          "videoOutput"
        )
        .outputOptions([
          "-map [videoOutput]",
          "-b:v 4000k",
          "-allow_skip_frames 1",
          // "-preset veryfast",
          // "-x264opts keyint=60",
          // "-b:v 4000k",
          // "-minrate 4000k",
          // "-maxrate 4000k",
          // "-bufsize 1835k",
          // "-frame_drop_threshold 60",
        ])
        .once("progress", () => {
          const socket = zmq.socket("req");
          socket.on("connect", (fd, ep) => {
            this.zmqSocket = socket;
            if (!this.zmqIsRunning) {
              this._sendNextZMQMessage();
            }
            let idx = 0;
            let label = this.ffmpeg.filterLabels[MAIN_SWITCHER_LABEL];
          });
          socket.on("connect", (fd, ep) => {this.info("connect, endpoint:", ep);});
          socket.on("connect_delay", (fd, ep) => {this.info("connect_delay, endpoint:", ep);});
          socket.on("connect_retry", (fd, ep) => {this.info("connect_retry, endpoint:", ep);});
          socket.on("listen", (fd, ep) => {this.info("listen, endpoint:", ep);});
          socket.on("bind_error", (fd, ep) => {this.info("bind_error, endpoint:", ep);});
          socket.on("accept", (fd, ep) => {this.info("accept, endpoint:", ep);});
          socket.on("accept_error", (fd, ep) => {this.info("accept_error, endpoint:", ep);});
          socket.on("close", (fd, ep) => {this.info("close, endpoint:", ep);});
          socket.on("close_error", (fd, ep) => {this.info("close_error, endpoint:", ep);});
          socket.on("disconnect", (fd, ep) => {this.info("disconnect, endpoint:", ep);});
          socket.on("message", (msg) => {this.info("message: ", msg.toString());});
          socket.monitor(500, 0);
          socket.connect(`tcp://127.0.0.1:${this.zmqPort}`);
        })
        .output(this.videoOutputURL)
        .outputFormat("mpegts")
        .videoCodec("libopenh264")

        .magic(
          ...audioInputSockets.map(s => `${s.name}-adjusted`),
          m.amix({
            inputs: audioInputSockets.length
          }),
          "audioOutput"
        )

        .output(this.audioOutputURL)
        .outputOptions([
          "-map [audioOutput]"
        ])
        .outputFormat("mpegts")
        .audioCodec("aac");

        // .input(this.inputURL)
        // .inputFormat("mpegts")
        // // .inputOptions("-itsoffset 00:00:05")
        // .outputOptions([
        // ])
        // .videoCodec("libx264")
        // .audioCodec("pcm_s16le")
        // .outputOptions([
        //   "-preset ultrafast",
        //   "-tune zerolatency",
        //   "-x264opts keyint=5:min-keyint=",
        //   "-pix_fmt yuv420p",
        //   "-filter_complex",
        //   [
        //     `[0:a]asetpts='(RTCTIME - ${this.SERVER_START_TIME}) / (TB * 1000000)'[out_audio]`,
        //     `[0:v]setpts='(RTCTIME - ${this.SERVER_START_TIME}) / (TB * 1000000)'[out_video]`,
        //   ].join(";")
        // ])

        // // Video output
        // .output(this.videoOutputURL)
        // .outputOptions([
        //   "-map [out_video]",
        // ])
        // .outputFormat("mpegts")

        // // Audio output
        // .output(this.audioOutputURL)
        // .outputOptions([
        //   "-map [out_audio]",
        // ])
        // .outputFormat("mpegts");

      this.ffmpeg.run();
    }
    catch (err) {
      this.error(err);
      this.retry();
    }
  }
}
<|endoftext|>


<commit_before>Package.describe({
	name: 'rocketchat:api',
	version: '0.0.1',
	summary: 'Rest API',
	git: ''
});

Package.onUse(function(api) {
	api.versionsFrom('1.0');

	api.use([
		'coffeescript',
		'underscore',
		'rocketchat:lib',
		'nimble:restivus@0.8.4'
	]);

	api.addFiles('server/api.coffee', 'server');
	api.addFiles('server/routes.coffee', 'server');
});

Package.onTest(function(api) {

});
<commit_msg>Remove restivus package version<commit_after>Package.describe({
	name: 'rocketchat:api',
	version: '0.0.1',
	summary: 'Rest API',
	git: ''
});

Package.onUse(function(api) {
	api.versionsFrom('1.0');

	api.use([
		'coffeescript',
		'underscore',
		'rocketchat:lib',
		'nimble:restivus'
	]);

	api.addFiles('server/api.coffee', 'server');
	api.addFiles('server/routes.coffee', 'server');
});

Package.onTest(function(api) {

});
<|endoftext|>