<commit_before>/**
 * Created by nuintun on 2015/4/27.
 */

'use strict';

var is = require('is');
var fs = require('fs');
var path = require('path');
var relative = path.relative;
var Vinyl = require('vinyl');
var through = require('through');
var util = require('./util');
var common = require('./common');
var colors = util.colors;
var debug = util.debug;
var async = require('./async');
var transport = require('./transport');

// empty buffer
var NULL = new Buffer('');

/**
 * include
 * @param options
 * @returns {*}
 */
function include(options){
  var initialized = false;
  var defaults = common.initOptions(options);

  // stream
  return through({ objectMode: true }, function (vinyl, encoding, next){
    // hack old vinyl
    vinyl._isVinyl = true;
    // normalize vinyl base
    vinyl.base = relative(vinyl.cwd, vinyl.base);

    // return empty vinyl
    if (vinyl.isNull()) {
      return next(null, vinyl);
    }

    // throw error if stream vinyl
    if (vinyl.isStream()) {
      return next(util.throwError('streaming not supported.'));
    }

    if (!initialized) {
      // debug
      debug('cwd: %s', colors.magenta(util.normalize(util.cwd)));

      initialized = true;
    }

    // catch error
    try {
      // stream
      var stream = this;

      // clone options
      options = util.extend({}, defaults);

      // lock wwwroot
      util.readonlyProperty(options, 'wwwroot');
      // lock plugins
      util.readonlyProperty(options, 'plugins');

      // transport
      transport(vinyl, options, function (vinyl, options){
        var pool = {};
        var pkg = vinyl.package;
        var start = vinyl.clone();
        var end = vinyl.clone();
        var pathFromCwd = util.pathFromCwd(vinyl.path);

        // set start and end file status
        start.startConcat = true;
        start.contents = NULL;
        end.endConcat = true;
        end.contents = NULL;

        // clean vinyl
        delete start.package;
        delete end.package;

        // compute include
        options.include = is.fn(options.include)
          ? options.include(pkg.id || null, vinyl.path)
          : options.include;

        // debug
        debug('concat: %s start', colors.magenta(pathFromCwd));
        stream.push(start);
        includeDeps.call(stream, vinyl, pool, options, function (){
          stream.push(end);
          // debug
          debug('concat: %s ...ok', colors.magenta(pathFromCwd));
          next();
        });
      });
    } catch (error) {
      // show error message
      util.print(colors.red.bold(error.stack) + '\x07');
      next();
    }
  });
}

/**
 * create a new vinyl
 * @param path
 * @param cwd
 * @param base
 * @returns {Vinyl|null}
 */
function vinylFile(path, cwd, base){
  if (!is.string(path) || !is.string(cwd) || !is.string(base)) return null;

  // file exists
  if (fs.existsSync(path)) {
    return new Vinyl({
      path: path,
      cwd: cwd,
      base: base,
      stat: fs.statSync(path),
      contents: fs.readFileSync(path)
    });
  }

  // file not exists
  util.print('file: %s not exists', colors.yellow(util.pathFromCwd(path)));

  return null;
}

/**
 * walk file
 * @param vinyl
 * @param pool
 * @param options
 * @param done
 */
function walk(vinyl, pool, options, done){
  var stream = this;
  var pkg = vinyl.package;
  var target = pool[vinyl.path];

  /**
   * read
   * @param path
   * @param next
   */
  function doRead(path, next){
    if (pool.hasOwnProperty(path)) {
      next();
    } else {
      // create a vinyl file
      var child = vinylFile(path, vinyl.cwd, vinyl.base);

      // read file success
      if (child !== null) {
        // debug
        debug('include: %s', colors.magenta(util.pathFromCwd(child.path)));
        // transport file
        transport(child, options, function (child, options){
          // cache next
          target.next = next;
          // add cache status
          pool[child.path] = {
            next: null,
            parent: target,
            included: false
          };

          // walk
          walk.call(stream, child, pool, options, done);
        });
      } else {
        next();
      }
    }
  }

  /**
   * lookup
   */
  function doLookup(){
    // push file to stream
    stream.push(vinyl);

    // all file include
    if (target.parent === null) {
      done();
    } else if (target.parent.next !== null) {
      // run parent next dependencies
      target.parent.next();
    }

    // change cache status
    target.next = null;
    target.included = true;

    // clean parent
    if (target.parent !== null) {
      delete target.parent;
    }
  }

  // bootstrap
  if (target.included || !pkg) {
    doLookup();
  } else {
    async.series(pkg.include, doRead, doLookup);
  }
}

/**
 * include dependencies file
 * @param vinyl
 * @param pool
 * @param options
 * @param done
 */
function includeDeps(vinyl, pool, options, done){
  // return if include not equal 'all' and 'relative'
  if (!options.include) {
    this.push(vinyl);
    return done();
  }

  // set pool cache
  pool[vinyl.path] = {
    next: null,
    parent: null,
    included: false
  };

  // bootstrap
  walk.call(this, vinyl, pool, options, function (){
    // free memory
    pool = null;

    // callback
    done();
  });
}

/**
 * exports module
 */
module.exports = include;
<commit_msg>use async plugin<commit_after>/**
 * Created by nuintun on 2015/4/27.
 */

'use strict';

var is = require('is');
var fs = require('fs');
var path = require('path');
var relative = path.relative;
var Vinyl = require('vinyl');
var through = require('through');
var util = require('./util');
var common = require('./common');
var colors = util.colors;
var debug = util.debug;
var async = require('./async');
var transport = require('./transport');

// empty buffer
var NULL = new Buffer('');

/**
 * include
 * @param options
 * @returns {*}
 */
function include(options){
  var initialized = false;
  var defaults = common.initOptions(options);

  // stream
  return through({ objectMode: true }, function (vinyl, encoding, next){
    // hack old vinyl
    vinyl._isVinyl = true;
    // normalize vinyl base
    vinyl.base = relative(vinyl.cwd, vinyl.base);

    // return empty vinyl
    if (vinyl.isNull()) {
      return next(null, vinyl);
    }

    // throw error if stream vinyl
    if (vinyl.isStream()) {
      return next(util.throwError('streaming not supported.'));
    }

    if (!initialized) {
      // debug
      debug('cwd: %s', colors.magenta(util.normalize(util.cwd)));

      initialized = true;
    }

    // catch error
    try {
      // stream
      var stream = this;

      // clone options
      options = util.extend({}, defaults);

      // lock wwwroot
      util.readonlyProperty(options, 'wwwroot');
      // lock plugins
      util.readonlyProperty(options, 'plugins');

      // transport
      transport(vinyl, options, function (vinyl, options){
        var pool = {};
        var pkg = vinyl.package;
        var start = vinyl.clone();
        var end = vinyl.clone();
        var pathFromCwd = util.pathFromCwd(vinyl.path);

        // set start and end file status
        start.startConcat = true;
        start.contents = NULL;
        end.endConcat = true;
        end.contents = NULL;

        // clean vinyl
        delete start.package;
        delete end.package;

        // compute include
        options.include = is.fn(options.include)
          ? options.include(pkg.id || null, vinyl.path)
          : options.include;

        // debug
        debug('concat: %s start', colors.magenta(pathFromCwd));
        stream.push(start);
        includeDeps.call(stream, vinyl, pool, options, function (){
          stream.push(end);
          // debug
          debug('concat: %s ...ok', colors.magenta(pathFromCwd));
          next();
        });
      });
    } catch (error) {
      // show error message
      util.print(colors.red.bold(error.stack) + '\x07');
      next();
    }
  });
}

/**
 * create a new vinyl
 * @param path
 * @param cwd
 * @param base
 * @returns {Vinyl|null}
 */
function vinylFile(path, cwd, base){
  if (!is.string(path) || !is.string(cwd) || !is.string(base)) return null;

  // file exists
  if (fs.existsSync(path)) {
    return new Vinyl({
      path: path,
      cwd: cwd,
      base: base,
      stat: fs.statSync(path),
      contents: fs.readFileSync(path)
    });
  }

  // file not exists
  util.print('file: %s not exists', colors.yellow(util.pathFromCwd(path)));

  return null;
}

/**
 * walk file
 * @param vinyl
 * @param pool
 * @param options
 * @param done
 */
function walk(vinyl, pool, options, done){
  var stream = this;
  var pkg = vinyl.package;
  var target = pool[vinyl.path];

  /**
   * read
   * @param path
   * @param next
   */
  function doRead(path, next){
    if (pool.hasOwnProperty(path)) {
      next();
    } else {
      // create a vinyl file
      var child = vinylFile(path, vinyl.cwd, vinyl.base);

      // read file success
      if (child !== null) {
        // debug
        debug('include: %s', colors.magenta(util.pathFromCwd(child.path)));
        // transport file
        transport(child, options, function (child, options){
          // cache next
          target.next = next;
          // add cache status
          pool[child.path] = {
            next: null,
            parent: target,
            included: false
          };

          // walk
          walk.call(stream, child, pool, options, done);
        });
      } else {
        next();
      }
    }
  }

  /**
   * lookup
   */
  function doLookup(){
    // push file to stream
    stream.push(vinyl);

    // all file include
    if (target.parent === null) {
      done();
    } else if (target.parent.next !== null) {
      // run parent next dependencies
      target.parent.next();
    }

    // change cache status
    target.next = null;
    target.included = true;

    // clean parent
    if (target.parent !== null) {
      delete target.parent;
    }
  }

  // bootstrap
  if (target.included || !pkg) {
    doLookup();
  } else {
    async.series(pkg.include, doRead, doLookup);
  }
}

/**
 * include dependencies file
 * @param vinyl
 * @param pool
 * @param options
 * @param done
 */
function includeDeps(vinyl, pool, options, done){
  // return if include not equal 'all' and 'relative'
  if (!options.include) {
    this.push(vinyl);

    return done();
  }

  // set pool cache
  pool[vinyl.path] = {
    next: null,
    parent: null,
    included: false
  };

  // bootstrap
  walk.call(this, vinyl, pool, options, function (){
    // free memory
    pool = null;

    // callback
    done();
  });
}

/**
 * exports module
 */
module.exports = include;
<|endoftext|>


<commit_before>PEG.compiler = {
  /*
   * Generates a parser from a specified grammar AST. Throws |PEG.GrammarError|
   * if the AST contains a semantic error. Note that not all errors are detected
   * during the generation and some may protrude to the generated parser and
   * cause its malfunction.
   */
  compile: function(ast) {
    var PASS_NAMES = [
      "reportMissingRules",
      "reportLeftRecursion",
      "removeProxyRules",
      "computeStackDepths"
    ];

    for (var i = 0; i < PASS_NAMES.length; i++) {
      this.passes[PASS_NAMES[i]](ast);
    }

    var source = this.emitter(ast);
    var result = eval(source);
    result._source = source;

    return result;
  }
};

// @include "passes.js"
// @include "emitter.js"
<commit_msg>Make pass list customizable via |PEG.compiler.appliedPassNames| property<commit_after>PEG.compiler = {
  /*
   * Names of passes that will get run during the compilation (in the specified
   * order).
   */
  appliedPassNames: [
    "reportMissingRules",
    "reportLeftRecursion",
    "removeProxyRules",
    "computeStackDepths"
  ],

  /*
   * Generates a parser from a specified grammar AST. Throws |PEG.GrammarError|
   * if the AST contains a semantic error. Note that not all errors are detected
   * during the generation and some may protrude to the generated parser and
   * cause its malfunction.
   */
  compile: function(ast) {
    for (var i = 0; i < this.appliedPassNames.length; i++) {
      this.passes[this.appliedPassNames[i]](ast);
    }

    var source = this.emitter(ast);
    var result = eval(source);
    result._source = source;

    return result;
  }
};

// @include "passes.js"
// @include "emitter.js"
<|endoftext|>


<commit_before>var exec              = require('child_process').exec
var assert            = require('assert')
var git               = require('./git')
var concurrentProcess = require('./src/parallel')
var eachParallel      = require('./src/parallel-each')
var logger            = require('./src/logger')
var isEmpty           = require('./src/isEmpty')

function install (opts) {
  logger.msg('\nDependencies:\n\n')
  // process.stdout.write(blu('\nDependencies:\n\n'))

  function installDependencies (cmd, packages, msg, cb) {
    if (!isEmpty(packages)) {
      eachParallel(packages, function (val, key, done) {
        exec(cmd + val, function (err) {
          // process.stdout.write(dim(blk('  module: ')) + red(item) + '\n')
          logger.events('  module: ', val)
          done(err)
        })
      }, function (err) {
        assert.ifError(err)
        cb(err, msg)
      })
    } else {
      cb(null, msg)
    }
  }

  var commands = {
    cmd1: function (cb) {
      var cmd = 'npm install --save-dev '
      installDependencies(cmd, opts.devpackages, 'devDependencies', function (err, msg) {
        cb(null, msg)
      })
    },

    cmd2: function (cb) {
      var cmd = 'npm install --save '
      installDependencies(cmd, opts.packages, 'dependencies', function (err, msg) {
        cb(null, msg)
      })
    }
  }

  concurrentProcess(commands, function (err, results) {
    assert.ifError(err)
    if (opts.git) git(opts)
    else process.stdout.write(mag('\nAll done.\n'))
  })
}

module.exports = install
<commit_msg>clean up install<commit_after>var exec              = require('child_process').exec
var assert            = require('assert')
var git               = require('./git')
var concurrentProcess = require('./src/parallel')
var eachParallel      = require('./src/parallel-each')
var logger            = require('./src/logger')
var isEmpty           = require('./src/isEmpty')
var tim               = require('./src/timeout')

function install (opts) {
  logger.info('\nDependencies:\n\n')

  function installDependencies (cmd, packages, msg, cb) {
    if (!isEmpty(packages)) {
      eachParallel(packages, function (val, key, done) {
        exec(cmd + val, function (err) {
          logger.events('  module: ', val)
          done(null, msg)
        })
      }, function (err) {
        assert.ifError(err)
        cb(null, msg)
      })
    } else {
      cb(null, msg)
    }
  }

  var commands = {
    cmd1: function (cb) {
      var cmd = 'npm install --save-dev '
      installDependencies(cmd, opts.devpackages, 'devDependencies', function (err, msg) {
        cb(null, msg)
      })
    },

    cmd2: function (cb) {
      var cmd = 'npm install --save '
      installDependencies(cmd, opts.packages, 'dependencies', function (err, msg) {
        cb(null, msg)
      })
    }
  }

  concurrentProcess(commands, function (err, results) {
    assert.ifError(err)
    if (opts.git) git(opts)
    else {
      tim(100)(function () {
        logger.msgdone()
      })
  })
}

module.exports = install
<|endoftext|>


<commit_before>/*
 * Copyright 2013 Jive Software
 *
 *    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.
 */

/**
 * Created with IntelliJ IDEA.
 * User: matt
 * Date: 3/1/13
 * Time: 11:20 AM
 * To change this template use File | Settings | File Templates.
 */

var tasks = {};

/**
 * Schedule a task.
 * @param key String with which you'll identify this task later
 * @param interval The interval to invoke the callback
 * @param cb The callback
 */
exports.schedule = function schedule(key, interval, cb, context){
    if  (!cb) {
        return;
    }
    this.unschedule(key);
    tasks[key] = setInterval( function() { cb(context) }, interval);
    console.log("scheduled task: " + key);
};

exports.unschedule = function unschedule(key){
    if(tasks[key]){
        clearInterval(tasks[key]);
    }
};

exports.getTasks = function getTasks(){
    return Object.keys(tasks);
};

exports.shutdown = function(){
    var scheduler = this;
    this.getTasks().forEach(function(taskKey){
        scheduler.unschedule(taskKey);
    });
};<commit_msg>Cleanup<commit_after>/*
 * Copyright 2013 Jive Software
 *
 *    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.
 */

var tasks = {};

/**
 * Schedule a task.
 * @param key String with which you'll identify this task later
 * @param interval The interval to invoke the callback
 * @param cb The callback
 */
exports.schedule = function schedule(key, interval, cb, context){
    if  (!cb) {
        return;
    }
    this.unschedule(key);
    tasks[key] = setInterval( function() { cb(context) }, interval);
    console.log("scheduled task: " + key);
};

exports.unschedule = function unschedule(key){
    if(tasks[key]){
        clearInterval(tasks[key]);
    }
};

exports.getTasks = function getTasks(){
    return Object.keys(tasks);
};

exports.shutdown = function(){
    var scheduler = this;
    this.getTasks().forEach(function(taskKey){
        scheduler.unschedule(taskKey);
    });
};<|endoftext|>


<commit_before>var lingcod = (function(){

    var options = {};
    var that = {};

    that.init = function(opts){
        options = opts;
        that.options = opts;

        $('#sidebar').tabs();
        resize();
        google.earth.createInstance(
            "map",
            function(i){
                geInit(i);
            },
            function(code){
                geFailure(code);
            });
        setupListeners();
        lingcod.menu_items.init($('.menu_items'));
        // makes button clicking a lot more reliable!!
        $(document).find('a.button').live('dragstart', function(){
            return false;
        });
    };

    var geInit = function(pluginInstance){
        ge = pluginInstance;
        ge.getWindow().setVisibility(true); // required
        gex = new GEarthExtensions(ge);

        that.googleLayers = new lingcod.map.googleLayers(ge,
            $('#ge_options'), $('#ge_layers'));
        that.geocoder = new lingcod.map.geocoder(gex, $('#flyToLocation'));
        that.measureTool = new lingcod.measureTool();

        $('#measure_distance').click(function(){
            that.measureTool.clear();
            that.measureTool.measureDistance(gex, "measureAmount");
            $('#measure_clear').removeClass('disabled');
            $('#measureAmountHolder').show();
        });
        $('#measure_area').click(function(){
            that.measureTool.clear();
            that.measureTool.measureArea(gex, "measureAmount");
            $('#measure_clear').removeClass('disabled');
            $('#measureAmountHolder').show();
        });
        $('#measure_clear').click(function(){
            that.measureTool.clear();
            $(this).addClass('disabled');
            $('#measureAmountHolder').hide();
        });
        $('#measure_units').change(function(){
            that.measureTool.setUnits($(this).val());
        });

        $('#datalayerstree').append('

');

        var studyRegion = lingcod.kmlTree({
            url: window.studyregion,
            ge: ge,
            gex: gex,
            animate: false,
            map_div: $('#map'),
            element: $('#study_region'),
            trans: options.media_url + 'common/images/transparent.gif',
            title: true
        });
        $(studyRegion).bind('kmlLoaded', function(){
            $('#study_region').find('li').dblclick();
        });
        studyRegion.load();

        var publicData = lingcod.kmlTree({
            url: window.public_data_layers,
            ge: ge,
            gex: gex,
            animate: false,
            map_div: $('#map'),
            element: $('#public_data'),
            trans: options.media_url + 'common/images/transparent.gif',
            title: true
        });
        publicData.load(true);

        // var forest = lingcod.kmlForest({
        //     element: $('#datalayerstree'),
        //     ge: ge,
        //     gex: gex,
        //     div: $('#map')
        // });
        //
        // forest.add(window.studyregion, {
        //     cachebust: true,
        //     callback: function(kmlObject, topNode){
        //         topNode.find('> ul > li > a').trigger('dblclick');
        //     }
        // });
        //
        // forest.add(window.public_data_layers, {
        //     cachebust: true
        // });

        var panel = lingcod.panel({appendTo: $('#panel-holder'),
            showCloseButton: false});

        that.client = lingcod.rest.client(gex, panel);

        if(typeof options.form_shown === 'function'){
            $(that.client).bind('form_shown', options.form_shown);
        }

        if(options.ecotrust){
            var ecotrustData = lingcod.kmlTree({
                url: options.ecotrust,
                ge: ge,
                gex: gex,
                animate: false,
                map_div: $('#map'),
                element: $('#ecotrust_data'),
                trans: options.media_url + 'common/images/transparent.gif',
                title: true
            });
            ecotrustData.load(true);
        }

        var editors = [];

        if(options.myshapes){
            for(var i=0;i<options.myshapes.length; i++){
                editors.push(lingcod.rest.kmlEditor({
                    ge: ge,
                    gex: gex,
                    appendTo: '#myshapestree',
                    div: '#map',
                    url: options.myshapes[i],
                    client: that.client
                }));
            }
        }

        $('#sidebar, #meta-navigation').click(function(e){
            if(e.target === this || e.target === $('#MyShapes')[0]){
                for(var i=0;i<editors.length;i++){
                    editors[0].clearSelection();
                }
            }
        });

        var url = that.options.media_url + 'common/kml/shadow.kmz';
        google.earth.fetchKml(ge, url, function(k){
            ge.getFeatures().appendChild(k);
        });
    };

    var studyRegionLoaded = function(kmlObject, node){
        // Reorder so studyRegion is on top of the list
        $('#datalayerstree').prepend(node);
        if (kmlObject.getAbstractView()){
            ge.getView().setAbstractView(kmlObject.getAbstractView());
        }
    };

    var geFailure = function(errorCode){
        alert("Failure loading the Google Earth Plugin: " + errorCode);
    }

    var setupListeners = function(){
        $(window).smartresize(function(){
            resize();
        });
        $('#meta-navigation').click(function(){
            lingcod.menu_items.closeAll();
        });
        $('#sidebar').bind('mouseup', function(e){
            lingcod.menu_items.closeAll();
            return false;
        });
        $('#sidebar-mask').click(function(){
            lingcod.menu_items.closeAll();
        });
    };

    var resize = function(){
        var mh = $('#meta-navigation').outerHeight();
        var h = $(document.body).height() - mh;
        $('#sidebar').css({top: mh, height: h});
        $('#panel-holder').css({top: mh, height: h});

        var w = $(document.body).width() - $('#sidebar').width();
        $('#map_container').height(h).width(w);
    };

    that.maskSidebar = function(){
        $('#panel-holder').show();
        $('#sidebar').addClass('masked');
    };

    that.unmaskSidebar = function(){
        $('#panel-holder').hide();
        $('#sidebar').removeClass('masked');
    };

    var panels = [];

    that.addPanel = function(panel){
        panels.push(panel);
        $(panel).bind('panelshow', onPanelShown);
        $(panel).bind('panelhide', onPanelHide);
        $(panel).bind('panelclose', onPanelHide);
    },

    that.removePanel = function(panel){
        panels.remove(panel);
        $(panel).unbind('panelshow', onPanelShown);
        $(panel).unbind('panelhide', onPanelHide);
        $(panel).unbind('panelclose', onPanelHide);
    };

    var onPanelShown = function(e, panel){
        that.maskSidebar();
    };

    var onPanelHide = function(e, panel){
        var count = 0;
        for(var i=0; i<panels.length; i++){
            var p = panels[i];
            if(p.shown){
                count++;
            }
        }
        if(count > 0){
            // console.log('another panel still shown');
        }else{
            that.unmaskSidebar();
        }
    };

    return that;
})();<commit_msg>turned on status bar and navigation controls by default<commit_after>var lingcod = (function(){

    var options = {};
    var that = {};

    that.init = function(opts){
        options = opts;
        that.options = opts;

        $('#sidebar').tabs();
        resize();
        google.earth.createInstance(
            "map",
            function(i){
                geInit(i);
            },
            function(code){
                geFailure(code);
            });
        setupListeners();
        lingcod.menu_items.init($('.menu_items'));
        // makes button clicking a lot more reliable!!
        $(document).find('a.button').live('dragstart', function(){
            return false;
        });
    };

    var geInit = function(pluginInstance){
        ge = pluginInstance;
        ge.getWindow().setVisibility(true); // required
        ge.getOptions().setStatusBarVisibility(true);
        ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);
        gex = new GEarthExtensions(ge);

        // that.googleLayers = new lingcod.map.googleLayers(ge,
        //     $('#ge_options'), $('#ge_layers'));
        that.geocoder = new lingcod.map.geocoder(gex, $('#flyToLocation'));
        that.measureTool = new lingcod.measureTool();

        $('#measure_distance').click(function(){
            that.measureTool.clear();
            that.measureTool.measureDistance(gex, "measureAmount");
            $('#measure_clear').removeClass('disabled');
            $('#measureAmountHolder').show();
        });
        $('#measure_area').click(function(){
            that.measureTool.clear();
            that.measureTool.measureArea(gex, "measureAmount");
            $('#measure_clear').removeClass('disabled');
            $('#measureAmountHolder').show();
        });
        $('#measure_clear').click(function(){
            that.measureTool.clear();
            $(this).addClass('disabled');
            $('#measureAmountHolder').hide();
        });
        $('#measure_units').change(function(){
            that.measureTool.setUnits($(this).val());
        });

        $('#datalayerstree').append('

');

        var studyRegion = lingcod.kmlTree({
            url: window.studyregion,
            ge: ge,
            gex: gex,
            animate: false,
            map_div: $('#map'),
            element: $('#study_region'),
            trans: options.media_url + 'common/images/transparent.gif',
            title: true
        });
        $(studyRegion).bind('kmlLoaded', function(){
            $('#study_region').find('li').dblclick();
        });
        studyRegion.load();

        var publicData = lingcod.kmlTree({
            url: window.public_data_layers,
            ge: ge,
            gex: gex,
            animate: false,
            map_div: $('#map'),
            element: $('#public_data'),
            trans: options.media_url + 'common/images/transparent.gif',
            title: true
        });
        publicData.load(true);

        // var forest = lingcod.kmlForest({
        //     element: $('#datalayerstree'),
        //     ge: ge,
        //     gex: gex,
        //     div: $('#map')
        // });
        //
        // forest.add(window.studyregion, {
        //     cachebust: true,
        //     callback: function(kmlObject, topNode){
        //         topNode.find('> ul > li > a').trigger('dblclick');
        //     }
        // });
        //
        // forest.add(window.public_data_layers, {
        //     cachebust: true
        // });

        var panel = lingcod.panel({appendTo: $('#panel-holder'),
            showCloseButton: false});

        that.client = lingcod.rest.client(gex, panel);

        if(typeof options.form_shown === 'function'){
            $(that.client).bind('form_shown', options.form_shown);
        }

        if(options.ecotrust){
            var ecotrustData = lingcod.kmlTree({
                url: options.ecotrust,
                ge: ge,
                gex: gex,
                animate: false,
                map_div: $('#map'),
                element: $('#ecotrust_data'),
                trans: options.media_url + 'common/images/transparent.gif',
                title: true
            });
            ecotrustData.load(true);
        }

        var editors = [];

        if(options.myshapes){
            for(var i=0;i<options.myshapes.length; i++){
                editors.push(lingcod.rest.kmlEditor({
                    ge: ge,
                    gex: gex,
                    appendTo: '#myshapestree',
                    div: '#map',
                    url: options.myshapes[i],
                    client: that.client
                }));
            }
        }

        $('#sidebar, #meta-navigation').click(function(e){
            if(e.target === this || e.target === $('#MyShapes')[0]){
                for(var i=0;i<editors.length;i++){
                    editors[0].clearSelection();
                }
            }
        });

        var url = that.options.media_url + 'common/kml/shadow.kmz';
        google.earth.fetchKml(ge, url, function(k){
            ge.getFeatures().appendChild(k);
        });
    };

    var studyRegionLoaded = function(kmlObject, node){
        // Reorder so studyRegion is on top of the list
        $('#datalayerstree').prepend(node);
        if (kmlObject.getAbstractView()){
            ge.getView().setAbstractView(kmlObject.getAbstractView());
        }
    };

    var geFailure = function(errorCode){
        alert("Failure loading the Google Earth Plugin: " + errorCode);
    }

    var setupListeners = function(){
        $(window).smartresize(function(){
            resize();
        });
        $('#meta-navigation').click(function(){
            lingcod.menu_items.closeAll();
        });
        $('#sidebar').bind('mouseup', function(e){
            lingcod.menu_items.closeAll();
            return false;
        });
        $('#sidebar-mask').click(function(){
            lingcod.menu_items.closeAll();
        });
    };

    var resize = function(){
        var mh = $('#meta-navigation').outerHeight();
        var h = $(document.body).height() - mh;
        $('#sidebar').css({top: mh, height: h});
        $('#panel-holder').css({top: mh, height: h});

        var w = $(document.body).width() - $('#sidebar').width();
        $('#map_container').height(h).width(w);
    };

    that.maskSidebar = function(){
        $('#panel-holder').show();
        $('#sidebar').addClass('masked');
    };

    that.unmaskSidebar = function(){
        $('#panel-holder').hide();
        $('#sidebar').removeClass('masked');
    };

    var panels = [];

    that.addPanel = function(panel){
        panels.push(panel);
        $(panel).bind('panelshow', onPanelShown);
        $(panel).bind('panelhide', onPanelHide);
        $(panel).bind('panelclose', onPanelHide);
    },

    that.removePanel = function(panel){
        panels.remove(panel);
        $(panel).unbind('panelshow', onPanelShown);
        $(panel).unbind('panelhide', onPanelHide);
        $(panel).unbind('panelclose', onPanelHide);
    };

    var onPanelShown = function(e, panel){
        that.maskSidebar();
    };

    var onPanelHide = function(e, panel){
        var count = 0;
        for(var i=0; i<panels.length; i++){
            var p = panels[i];
            if(p.shown){
                count++;
            }
        }
        if(count > 0){
            // console.log('another panel still shown');
        }else{
            that.unmaskSidebar();
        }
    };

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


<commit_before>'use strict';

var crypto = require('crypto')
  , File = require('./file')
  , path = require('path')
  , fs = require('fs');

/**
 * Asset compiler and management.
 *
 * @constructor
 * @param {String} directory The directory where we save our static files.
 * @param {Pipe} pipe The configured Pipe instance.
 * @param {Object} options Configuration.
 * @api private
 */
function Compiler(directory, pipe, options) {
  options = options || {};

  this.pathname = options.pathname || '/';
  this.dir = directory;
  this.pipe = pipe;
  this.list = [];

  this.buffer = Object.create(null);
  this.alias = Object.create(null);
}

Compiler.prototype.__proto__ = require('events').EventEmitter.prototype;

//
// Lazy read the pipe.js JavaScript client. It's already pre-compiled by
// browserify.
//
Object.defineProperty(Compiler.prototype, 'client', {
  get: function read() {
    read.pipe = read.pipe || fs.readFileSync(path.resolve(__dirname, '../dist/pipe.js'), 'utf-8');
    return read.pipe;
  }
});

/**
 * Create the BigPipe base front-end framework that's required for the handling
 * of the real-time connections and the initialisation of the arriving pagelets.
 *
 * @param {String} core Core libraries that need to be loaded on every page.
 * @api private
 */
Compiler.prototype.bigPipe = function bigPipe(core) {
  var library = this.pipe.primus.library() + this.client + (core || '')
    , name = this.hash(library);

  return this.register('/pipe.js', this.pathname + name +'.js', library);
};

/**
 * Create a hash of the code which can be used a filename. This allows us to
 * agressively cache the data.
 *
 * @param {String} code The code that is send to the client.
 * @returns {String} The compiled hash.
 * @api private
 */
Compiler.prototype.hash = function hash(code) {
  return crypto.createHash('sha1').update(code).digest('hex').toString('hex');
};

/**
 * Register a new library with the compiler.
 *
 * @param {String} alias How we know this dependency.
 * @param {String} pathname The exact matching pathname to serve the given code.
 * @param {Mixed} code The library that needs to be transferd.
 * @api private
 */
Compiler.prototype.register = function register(alias, pathname, code) {
  var filename = path.basename(pathname)
    , extname = path.extname(pathname)
    , file;

  //
  // Make sure that the given code is a buffer.
  //
  if (!Buffer.isBuffer(code)) code = new Buffer(code);

  file = this.buffer[pathname] = new File(code, extname);

  this.alias[alias] = pathname;
  this.emit('register', file, alias, pathname);

  return this.save(filename, file);
};

/**
 * Catalog the pages. As we're not caching the file look ups, this method can be
 * called when a file changes so we will generate new.
 *
 * @param {Array} pages The array of pages.
 * @api private
 */
Compiler.prototype.catalog = function catalog(pages) {
  var temper = this.pipe.temper
    , compiler = this
    , core = [];

  /**
   * Process the dependencies.
   *
   * @param {String} filepath The location of a file.
   * @api private
   */
  function prefab(filepath) {
    if (/^(http:|https:)?\/\//.test(filepath)) return;

    var code = fs.readFileSync(filepath, 'utf-8')
      , extname = path.extname(filepath)
      , filename = compiler.hash(code);

    //
    // Update the CSS with a selector that contains the filename which is
    // required for async loading of CSS.
    //
    if ('.css' === extname) {
      code = code + '#pagelet_'+ filename + '{ height: 45px }';
    }

    compiler.register(filepath, compiler.pathname + filename + extname, code);
  }

  pages.forEach(function each(Page) {
    var dependencies = ['/pipe.js']
      , page = Page.prototype;

    page.pagelets.forEach(function each(Pagelet) {
      var pagelet = Pagelet.prototype
        , view;

      if (pagelet.js) prefab(pagelet.js);
      if (pagelet.css) prefab(pagelet.css);

      pagelet.dependencies.forEach(function each(dependency) {
        prefab(dependency);

        if (!~dependencies.indexOf(dependency)) {
          dependencies.push(dependency);
        }
      });

      if (!pagelet.view) return;

      //
      // The views can be rendered on the client, but some of them require
      // a library, this library should be cached in the core library.
      //
      view = temper.fetch(pagelet.view);
      if (view.library && !~core.indexOf(view.library)) core.push(view.library);
    });

    page.dependencies = dependencies.reduce(function reduce(memo, dependency) {
      var extname = path.extname(dependency);

      memo[extname] = memo[extname] || [];
      memo[extname].push(dependency);

      return memo;
    }, Object.create(null));
  });

  //
  // Last, but not least, update the pipe.js library.
  //
  this.bigPipe(core.join('\n'));
};

/**
 * Find all required dependencies for given page constructor.
 *
 * @param {Page} page The initialised page.
 * @returns {Object}
 * @api private
 */
Compiler.prototype.page = function find(page) {
  var compiler = this;

  /**
   * Resolve all dependencies to their hashed versions.
   *
   * @param {String} original The original file path.
   * @returns {String} The hashed version.
   * @api private
   */
  function alias(original) {
    return compiler.alias[original] || original;
  }

  return {
    css: (page.dependencies['.css'] || []).map(alias),
    js: (page.dependencies['.js'] || []).map(alias)
  };
};

/**
 * Store the compiled files to disk. This a vital part of the compiler as we're
 * changing the file names every single time there is a change. But these files
 * can still be cached on the client and it would result in 404's and or broken
 * functionaility.
 *
 * @param {String} name The file name that we're serving.
 * @param {File} file The file instance.
 * @api private
 */
Compiler.prototype.save = function save(name, file) {
  var directory = path.resolve(this.dir)
    , pathname = this.pathname;

  fs.writeFileSync(path.resolve(directory, name), file.code);

  this.list = fs.readdirSync(directory).reduce(function (memo, file) {
    var extname = path.extname(file);

    if (extname) memo[pathname + file] = path.resolve(directory, file);

    return memo;
  }, {});

  return this;
};

/**
 * Serve the file.
 *
 * @param {Request} req Incoming HTTP request.
 * @param {Response} res Outgoing HTTP response.
 * @returns {Boolean} The request is handled by the compiler.
 * @api private
 */
Compiler.prototype.serve = function serve(req, res) {
  if (!(req.uri.pathname in this.buffer)) return false;

  var file = this.buffer[req.uri.pathname];

  res.setHeader('Content-Type', file.type);
  res.setHeader('Content-Length', file.length);
  res.end(file.buffer);

  return true;
};

//
// Expose the module.
//
module.exports = Compiler;
<commit_msg>[minor] Implement an API to retrieve the resources for the pagelet. [minor] Small comment changes.<commit_after>'use strict';

var crypto = require('crypto')
  , File = require('./file')
  , path = require('path')
  , fs = require('fs');

/**
 * Asset compiler and management.
 *
 * @constructor
 * @param {String} directory The directory where we save our static files.
 * @param {Pipe} pipe The configured Pipe instance.
 * @param {Object} options Configuration.
 * @api private
 */
function Compiler(directory, pipe, options) {
  options = options || {};

  this.pathname = options.pathname || '/';
  this.dir = directory;
  this.pipe = pipe;
  this.list = [];

  this.buffer = Object.create(null);
  this.alias = Object.create(null);
}

Compiler.prototype.__proto__ = require('events').EventEmitter.prototype;

//
// Lazy read the pipe.js JavaScript client. It's already pre-compiled by
// browserify.
//
Object.defineProperty(Compiler.prototype, 'client', {
  get: function read() {
    read.pipe = read.pipe || fs.readFileSync(path.resolve(__dirname, '../dist/pipe.js'), 'utf-8');
    return read.pipe;
  }
});

/**
 * Create the BigPipe base front-end framework that's required for the handling
 * of the real-time connections and the initialisation of the arriving pagelets.
 *
 * @param {String} core Core libraries that need to be loaded on every page.
 * @api private
 */
Compiler.prototype.bigPipe = function bigPipe(core) {
  var library = this.pipe.primus.library() + this.client + (core || '')
    , name = this.hash(library);

  return this.register('/pipe.js', this.pathname + name +'.js', library);
};

/**
 * Create a hash of the code which can be used a filename. This allows us to
 * aggressively cache the data.
 *
 * @param {String} code The code that is send to the client.
 * @returns {String} The compiled hash.
 * @api private
 */
Compiler.prototype.hash = function hash(code) {
  return crypto.createHash('sha1').update(code).digest('hex').toString('hex');
};

/**
 * Register a new library with the compiler.
 *
 * @param {String} alias How we know this dependency.
 * @param {String} pathname The exact matching pathname to serve the given code.
 * @param {Mixed} code The library that needs to be transfered.
 * @api private
 */
Compiler.prototype.register = function register(alias, pathname, code) {
  var filename = path.basename(pathname)
    , extname = path.extname(pathname)
    , file;

  //
  // Make sure that the given code is a buffer.
  //
  if (!Buffer.isBuffer(code)) code = new Buffer(code);

  file = this.buffer[pathname] = new File(code, extname);

  this.alias[alias] = pathname;
  this.emit('register', file, alias, pathname);

  return this.save(filename, file);
};

/**
 * Catalog the pages. As we're not caching the file look ups, this method can be
 * called when a file changes so we will generate new.
 *
 * @param {Array} pages The array of pages.
 * @api private
 */
Compiler.prototype.catalog = function catalog(pages) {
  var temper = this.pipe.temper
    , compiler = this
    , core = [];

  /**
   * Process the dependencies.
   *
   * @param {String} filepath The location of a file.
   * @api private
   */
  function prefab(filepath) {
    if (/^(http:|https:)?\/\//.test(filepath)) return;

    var code = fs.readFileSync(filepath, 'utf-8')
      , extname = path.extname(filepath)
      , filename = compiler.hash(code);

    //
    // Update the CSS with a selector that contains the filename which is
    // required for async loading of CSS.
    //
    if ('.css' === extname) {
      code = code + '#pagelet_'+ filename + ' { height: 45px }';
    }

    compiler.register(filepath, compiler.pathname + filename + extname, code);
  }

  pages.forEach(function each(Page) {
    var dependencies = ['/pipe.js']
      , page = Page.prototype;

    page.pagelets.forEach(function each(Pagelet) {
      var pagelet = Pagelet.prototype
        , view;

      if (pagelet.js) prefab(pagelet.js);
      if (pagelet.css) prefab(pagelet.css);

      pagelet.dependencies.forEach(function each(dependency) {
        prefab(dependency);

        if (!~dependencies.indexOf(dependency)) {
          dependencies.push(dependency);
        }
      });

      if (!pagelet.view) return;

      //
      // The views can be rendered on the client, but some of them require
      // a library, this library should be cached in the core library.
      //
      view = temper.fetch(pagelet.view);
      if (view.library && !~core.indexOf(view.library)) core.push(view.library);

      compiler.register(
        pagelet.view,
        compiler.pathname + compiler.hash(view.client) +'.js',
        view.client
      );
    });

    page.dependencies = dependencies.reduce(function reduce(memo, dependency) {
      var extname = path.extname(dependency);

      memo[extname] = memo[extname] || [];
      memo[extname].push(dependency);

      return memo;
    }, Object.create(null));
  });

  //
  // Last, but not least, update the pipe.js library.
  //
  this.bigPipe(core.join('\n'));
};

/**
 * Find all required dependencies for given page constructor.
 *
 * @param {Page} page The initialised page.
 * @returns {Object}
 * @api private
 */
Compiler.prototype.page = function find(page) {
  var compiler = this;

  /**
   * Resolve all dependencies to their hashed versions.
   *
   * @param {String} original The original file path.
   * @returns {String} The hashed version.
   * @api private
   */
  function alias(original) {
    return compiler.alias[original] || original;
  }

  return {
    css: (page.dependencies['.css'] || []).map(alias),
    js: (page.dependencies['.js'] || []).map(alias)
  };
};

/**
 * A list of resources that need to be loaded for the given pagelet.
 *
 * @param {Pagelet} pagelet The initialised pagelet.
 * @param {Boolean} streaming The pagelet is streaming, so include the view.
 * @returns {Object}
 * @api private
 */
Compiler.prototype.pagelet = function find(pagelet, streaming) {
  var compiler = this
    , css = []
    , js = [];

  /**
   * Resolve all dependencies to their hashed versions.
   *
   * @param {String} original The original file path.
   * @returns {String} The hashed version.
   * @api private
   */
  function alias(original) {
    return compiler.alias[original] || original;
  }

  if (pagelet.js) js.push(alias(pagelet.js));
  if (pagelet.css) css.push(alias(pagelet.css));
  if (streaming && pagelet.view) js.push(alias(pagelet.view));

  return { css: css, js: js };
};

/**
 * Store the compiled files to disk. This a vital part of the compiler as we're
 * changing the file names every single time there is a change. But these files
 * can still be cached on the client and it would result in 404's and or broken
 * functionality.
 *
 * @param {String} name The file name that we're serving.
 * @param {File} file The file instance.
 * @api private
 */
Compiler.prototype.save = function save(name, file) {
  var directory = path.resolve(this.dir)
    , pathname = this.pathname;

  fs.writeFileSync(path.resolve(directory, name), file.code);

  this.list = fs.readdirSync(directory).reduce(function (memo, file) {
    var extname = path.extname(file);

    if (extname) memo[pathname + file] = path.resolve(directory, file);

    return memo;
  }, {});

  return this;
};

/**
 * Serve the file.
 *
 * @param {Request} req Incoming HTTP request.
 * @param {Response} res Outgoing HTTP response.
 * @returns {Boolean} The request is handled by the compiler.
 * @api private
 */
Compiler.prototype.serve = function serve(req, res) {
  if (!(req.uri.pathname in this.buffer)) return false;

  var file = this.buffer[req.uri.pathname];

  res.setHeader('Content-Type', file.type);
  res.setHeader('Content-Length', file.length);
  res.end(file.buffer);

  return true;
};

//
// Expose the module.
//
module.exports = Compiler;
<|endoftext|>


<commit_before>'use strict';
const BinBuild = require('bin-build');
const log = require('logalot');
const bin = require('.');

bin.run(['--help'], err => {
	if (err) {
		log.warn(err.message);
		log.warn('zopflipng pre-build test failed');
		log.info('compiling from source');

		let makeBin = 'make';

		if (process.platform === 'freebsd') {
			makeBin = 'gmake';
		}

		const builder = new BinBuild()
			.src('https://github.com/google/zopfli/archive/6818a0859063b946094fb6f94732836404a0d89a.zip')
			.cmd(`mkdir -p ${bin.dest()}`)
			.cmd(`${makeBin} zopflipng && mv ./zopflipng ${bin.path()}`);

		return builder.run(err => {
			if (err) {
				log.error(err.stack);
				return;
			}

			log.success('zopflipng built successfully');
		});
	}

	log.success('zopflipng pre-build test passed successfully');
});
<commit_msg>Fix FreeBSD compiler selection (#11)<commit_after>'use strict';
const BinBuild = require('bin-build');
const log = require('logalot');
const bin = require('.');

bin.run(['--help'], err => {
	if (err) {
		log.warn(err.message);
		log.warn('zopflipng pre-build test failed');
		log.info('compiling from source');

		let makeBin = 'make';
		let makeArgs = '';

		if (process.platform === 'freebsd') {
			makeBin = 'gmake';
			makeArgs = 'CC=cc CXX=c++';
		}

		const builder = new BinBuild()
			.src('https://github.com/google/zopfli/archive/6818a0859063b946094fb6f94732836404a0d89a.zip')
			.cmd(`mkdir -p ${bin.dest()}`)
			.cmd(`${makeBin} zopflipng ${makeArgs} && mv ./zopflipng ${bin.path()}`);

		return builder.run(err => {
			if (err) {
				log.error(err.stack);
				return;
			}

			log.success('zopflipng built successfully');
		});
	}

	log.success('zopflipng pre-build test passed successfully');
});
<|endoftext|>


<commit_before>import {
  connected as $connected,
  created as $created,
  props as $props,
  renderer as $renderer,
  rendererDebounced as $rendererDebounced,
} from '../util/symbols';
import { customElementsV0 } from '../util/support';
import data from '../util/data';
import debounce from '../util/debounce';
import getOwnPropertyDescriptors from '../util/get-own-property-descriptors';

const setElementAsDefined = elem => elem.setAttribute('defined', '');

function callConstructor(elem) {
  const elemData = data(elem);
  const readyCallbacks = elemData.readyCallbacks;
  const Ctor = elem.constructor;
  const { created, observedAttributes, props } = Ctor;

  // Ensures that this can never be called twice.
  if (elem[$created]) return;
  elem[$created] = true;

  // Set up a renderer that is debounced for property sets to call directly.
  elem[$rendererDebounced] = debounce(Ctor[$renderer]);

  if (props) {
    Ctor[$props](elem);
  }

  if (created) {
    created(elem);
  }

  if (readyCallbacks) {
    readyCallbacks.forEach(cb => cb(elem));
    delete elemData.readyCallbacks;
  }

  // In v0 we must ensure the attributeChangedCallback is called for attrs
  // that aren't linked to props so that the callback behaves the same no
  // matter if v0 or v1 is being used.
  if (customElementsV0) {
    observedAttributes.forEach((name) => {
      const propertyName = data(elem, 'attributeLinks')[name];
      if (!propertyName) {
        elem.attributeChangedCallback(name, null, elem.getAttribute(name));
      }
    });
  }
}

function callConnected(elem) {
  const ctor = elem.constructor;
  const { attached } = ctor;
  const render = ctor[$renderer];
  elem[$connected] = true;
  if (typeof render === 'function') {
    render(elem);
  }
  if (typeof attached === 'function') {
    attached(elem);
  }
}

function callDisconnected(elem) {
  const { detached } = elem.constructor;
  elem[$connected] = false;
  if (typeof detached === 'function') {
    detached(elem);
  }
}

// v1
function Component(...args) {
  const elm = Reflect.construct(HTMLElement, args, this.constructor);
  callConstructor(elm);
  return elm;
}

// v1
Component.observedAttributes = [];

// Skate
Component.props = {};

// Skate
Component.extend = function extend(definition = {}, Base = this) {
  // Create class for the user.
  class Ctor extends Base {}

  // Pass on statics from the Base if not supported (IE 9 and 10).
  if (!Ctor.observedAttributes) {
    const staticOpts = getOwnPropertyDescriptors(Base);
    delete staticOpts.length;
    delete staticOpts.prototype;
    Object.defineProperties(Ctor, staticOpts);
  }

  // For inheriting from the object literal.
  const opts = getOwnPropertyDescriptors(definition);
  const prot = getOwnPropertyDescriptors(definition.prototype);

  // Prototype is non configurable (but is writable).
  delete opts.prototype;

  // Pass on static and instance members from the definition.
  Object.defineProperties(Ctor, opts);
  Object.defineProperties(Ctor.prototype, prot);

  return Ctor;
};

// Skate
//
// This is a default implementation that does strict equality copmarison on
// prevoius props and next props. It synchronously renders on the first prop
// that is different and returns immediately.
Component.updated = function updated(elem, prev) {
  if (!prev) {
    return true;
  }

  // eslint-disable-next-line no-restricted-syntax
  for (const name in prev) {
    if (prev[name] !== elem[name]) {
      return true;
    }
  }
};

Component.prototype = Object.create(HTMLElement.prototype, {
  // v1
  connectedCallback: {
    configurable: true,
    value() {
      setElementAsDefined(this);
      callConnected(this);
    },
  },

  // v1
  disconnectedCallback: {
    configurable: true,
    value() {
      callDisconnected(this);
    },
  },

  // v0 and v1
  attributeChangedCallback: {
    configurable: true,
    value(name, oldValue, newValue) {
      const { attributeChanged, observedAttributes } = this.constructor;
      const propertyName = data(this, 'attributeLinks')[name];

      // In V0 we have to ensure the attribute is being observed.
      if (customElementsV0 && observedAttributes.indexOf(name) === -1) {
        return;
      }

      if (propertyName) {
        const propData = data(this, `api/property/${propertyName}`);

        // This ensures a property set doesn't cause the attribute changed
        // handler to run again once we set this flag. This only ever has a
        // chance to run when you set an attribute, it then sets a property and
        // then that causes the attribute to be set again.
        if (propData.syncingAttribute) {
          propData.syncingAttribute = false;
        } else {
          // Sync up the property.
          const propOpts = this.constructor.props[propertyName];
          propData.settingAttribute = true;
          this[propertyName] = newValue !== null && propOpts.deserialize ? propOpts.deserialize(newValue) : newValue;
        }
      }

      if (attributeChanged) {
        attributeChanged(this, { name, newValue, oldValue });
      }
    },
  },

  // v0
  createdCallback: {
    configurable: true,
    value() {
      setElementAsDefined(this);
      callConstructor(this);
    },
  },

  // v0
  attachedCallback: {
    configurable: true,
    value() {
      callConnected(this);
    },
  },

  // v0
  detachedCallback: {
    configurable: true,
    value() {
      callDisconnected(this);
    },
  },
});

export default Component;
<commit_msg>chore: revert some cherry pick errors from previous commit<commit_after>import {
  connected as $connected,
  created as $created,
  props as $props,
  renderer as $renderer,
  rendererDebounced as $rendererDebounced,
} from '../util/symbols';
import { customElementsV0 } from '../util/support';
import data from '../util/data';
import debounce from '../util/debounce';
import getAllKeys from '../util/get-all-keys';
import getOwnPropertyDescriptors from '../util/get-own-property-descriptors';

const setElementAsDefined = elem => elem.setAttribute('defined', '');

function callConstructor(elem) {
  const elemData = data(elem);
  const readyCallbacks = elemData.readyCallbacks;
  const Ctor = elem.constructor;
  const { created, observedAttributes, props } = Ctor;

  // Ensures that this can never be called twice.
  if (elem[$created]) return;
  elem[$created] = true;

  // Set up a renderer that is debounced for property sets to call directly.
  elem[$rendererDebounced] = debounce(Ctor[$renderer]);

  if (props) {
    Ctor[$props](elem);
  }

  if (created) {
    created(elem);
  }

  if (readyCallbacks) {
    readyCallbacks.forEach(cb => cb(elem));
    delete elemData.readyCallbacks;
  }

  // In v0 we must ensure the attributeChangedCallback is called for attrs
  // that aren't linked to props so that the callback behaves the same no
  // matter if v0 or v1 is being used.
  if (customElementsV0) {
    observedAttributes.forEach((name) => {
      const propertyName = data(elem, 'attributeLinks')[name];
      if (!propertyName) {
        elem.attributeChangedCallback(name, null, elem.getAttribute(name));
      }
    });
  }
}

function callConnected(elem) {
  const ctor = elem.constructor;
  const { attached } = ctor;
  const render = ctor[$renderer];
  elem[$connected] = true;
  if (typeof render === 'function') {
    render(elem);
  }
  if (typeof attached === 'function') {
    attached(elem);
  }
}

function callDisconnected(elem) {
  const { detached } = elem.constructor;
  elem[$connected] = false;
  if (typeof detached === 'function') {
    detached(elem);
  }
}

// v1
function Component(...args) {
  const elm = Reflect.construct(HTMLElement, args, this.constructor);
  callConstructor(elm);
  return elm;
}

// v1
Component.observedAttributes = [];

// Skate
Component.props = {};

// Skate
Component.extend = function extend(definition = {}, Base = this) {
  // Create class for the user.
  class Ctor extends Base {}

  // Pass on statics from the Base if not supported (IE 9 and 10).
  if (!Ctor.observedAttributes) {
    const staticOpts = getOwnPropertyDescriptors(Base);
    delete staticOpts.length;
    delete staticOpts.prototype;
    Object.defineProperties(Ctor, staticOpts);
  }

  // For inheriting from the object literal.
  const opts = getOwnPropertyDescriptors(definition);
  const prot = getOwnPropertyDescriptors(definition.prototype);

  // Prototype is non configurable (but is writable).
  delete opts.prototype;

  // Pass on static and instance members from the definition.
  Object.defineProperties(Ctor, opts);
  Object.defineProperties(Ctor.prototype, prot);

  return Ctor;
};

// Skate
//
// This is a default implementation that does strict equality copmarison on
// previous props and next props. It synchronously renders on the first prop
// that is different and returns immediately.
Component.updated = function updated(elem, prev) {
  if (!prev) {
    return true;
  }
  // use get all keys so that we check Symbols as well as regular props
  // using a for loop so we can break early
  const allKeys = getAllKeys(prev);
  for (let i = 0; i < allKeys.length; i += 1) {
    if (prev[allKeys[i]] !== elem[allKeys[i]]) {
      return true;
    }
  }
};

Component.prototype = Object.create(HTMLElement.prototype, {
  // v1
  connectedCallback: {
    configurable: true,
    value() {
      setElementAsDefined(this);
      callConnected(this);
    },
  },

  // v1
  disconnectedCallback: {
    configurable: true,
    value() {
      callDisconnected(this);
    },
  },

  // v0 and v1
  attributeChangedCallback: {
    configurable: true,
    value(name, oldValue, newValue) {
      const { attributeChanged, observedAttributes } = this.constructor;
      const propertyName = data(this, 'attributeLinks')[name];

      // In V0 we have to ensure the attribute is being observed.
      if (customElementsV0 && observedAttributes.indexOf(name) === -1) {
        return;
      }

      if (propertyName) {
        const propData = data(this, `api/property/${propertyName}`);

        // This ensures a property set doesn't cause the attribute changed
        // handler to run again once we set this flag. This only ever has a
        // chance to run when you set an attribute, it then sets a property and
        // then that causes the attribute to be set again.
        if (propData.syncingAttribute) {
          propData.syncingAttribute = false;
        } else {
          // Sync up the property.
          const propOpts = this.constructor.props[propertyName];
          propData.settingAttribute = true;
          this[propertyName] = newValue !== null && propOpts.deserialize ? propOpts.deserialize(newValue) : newValue;
        }
      }

      if (attributeChanged) {
        attributeChanged(this, { name, newValue, oldValue });
      }
    },
  },

  // v0
  createdCallback: {
    configurable: true,
    value() {
      setElementAsDefined(this);
      callConstructor(this);
    },
  },

  // v0
  attachedCallback: {
    configurable: true,
    value() {
      callConnected(this);
    },
  },

  // v0
  detachedCallback: {
    configurable: true,
    value() {
      callDisconnected(this);
    },
  },
});

export default Component;
<|endoftext|>


<commit_before>import AWS from 'aws-sdk'
import awsLambda from 'node-aws-lambda'
import crypto from 'crypto'
import { Client } from 'amazon-api-gateway-client'

/**
 * @class
 */
export default class Composer {
  /**
   * @param {String} accessKeyId
   * @param {Application} application
   * @param {Client=} client
   * @param {String} region
   * @param {String} secretAccessKey
   */
  constructor({ accessKeyId, application, client, region, secretAccessKey }) {
    this.accessKeyId = accessKeyId;
    this.application = application;
    this.client = client;
    this.region = region;
    this.secretAccessKey = secretAccessKey;
  }

  /**
   * @param {String} functionName
   * @param {String} httpMethod
   * @param {String} path
   * @param {Stirng} resourceId
   * @param {Stirng} restapiId
   * @param {String} uri
   * @return {Promise}
   */
  createMethodSet({ functionName, httpMethod, path, resourceId, restapiId, uri }) {
    return this.getClient().putMethod({
      httpMethod: httpMethod,
      resourceId: resourceId,
      restapiId: restapiId
    }).then((resource) => {
      return this.getClient().putIntegration({
        httpMethod: httpMethod,
        integrationHttpMethod: 'POST',
        resourceId: resourceId,
        restapiId: restapiId,
        type: 'AWS',
        uri: uri
      });
    }).then((integration) => {
      return this.getClient().putMethodResponse({
        httpMethod: httpMethod,
        resourceId: resourceId,
        restapiId: restapiId,
        statusCode: 200
      });
    }).then(() => {
      return this.getClient().putIntegrationResponse({
        httpMethod: httpMethod,
        resourceId: resourceId,
        restapiId: restapiId,
        statusCode: 200
      });
    }).then(() => {
      return new Promise((resolve, reject) => {
        new AWS.Lambda({
          region: 'us-east-1'
        }).addPermission(
          {
            Action: 'lambda:InvokeFunction',
            FunctionName: functionName,
            Principal: 'apigateway.amazonaws.com',
            StatementId: crypto.randomBytes(20).toString('hex')
          },
          (error, data) => {
            resolve();
          }
        );
      })
    });
  }

  /**
   * @param {String} restapiId
   * @return {Promise}
   */
  createResourceSets({ restapiId }) {
    return this.getClient().createResources({
      paths: this.getPaths(),
      restapiId: restapiId
    }).then(() => {
      return Promise.all(
        this.application.getActions().map((action) => {
          return this.getClient().findResourceByPath({
            path: action.getPath(),
            restapiId: restapiId
          }).then((resource) => {
            return this.createMethodSet({
              functionName: action.getName(),
              httpMethod: action.getHttpMethod(),
              path: action.getPath(),
              resourceId: resource.source.id,
              restapiId: restapiId,
              uri: action.getUri()
            });
          });
        })
      );
    });
  }

  /**
   * @return {Promise}
   */
  createRestapi() {
    return this.getClient().createRestapi({
      name: this.application.getName()
    }).then((restapi) => {
      this.application.writeRestapiId(restapi.source.id);
      return restapi;
    });
  }

  /**
   * @return {Promise}
   */
  createZipFiles() {
    return Promise.all(
      this.application.getActions().map((action) => {
        return action.createZipFile();
      })
    );
  }

  /**
   * @param {String} restapiId
   * @return {Promise}
   */
  deleteDefaultModels({ restapiId }) {
    return Promise.all(
      [
        'Empty',
        'Error'
      ].map((modelName) => {
        return this.getClient().deleteModel({
          modelName: modelName,
          restapiId: restapiId
        });
      })
    );
  }

  /**
   * Set up Amazon Lambda functions and API Gateway endpoints.
   * @return {Promise}
   */
  deploy() {
    return this.createZipFiles().then(() => {
      return this.uploadActions();
    }).then(() => {
      return this.updateActionsMetadata();
    }).then(() => {
      return this.findOrCreateRestapi();
    }).then((restapi) => {
      return this.deleteDefaultModels({
        restapiId: restapi.source.id
      }).then(() => {
        return restapi;
      });
    }).then((restapi) => {
      return this.createResourceSets({
        restapiId: restapi.source.id
      });
    });
  }

  /**
   * @return {Promise}
   */
  findOrCreateRestapi() {
    const restapiId = this.application.getRestapiId();
    if (restapiId) {
      return this.getClient().getRestapi({ restapiId: restapiId });
    } else {
      return this.createRestapi();
    }
  }

  /**
   * @return {Client}
   */
  getClient() {
    if (!this.client) {
      this.client = new Client({
        accessKeyId: this.accessKeyId,
        region: this.region,
        secretAccessKey: this.secretAccessKey
      });
    }
    return this.client;
  }

  /**
   * @return {Array.<String>}
   */
  getPaths() {
    return this.application.getActions().map((action) => {
      return action.getPath();
    });
  }

  /**
   * @return {Promise}
   */
  updateActionsMetadata() {
    return Promise.all(
      this.application.getActions().map((action) => {
        return new Promise((resolve, reject) => {
          const lambda = new AWS.Lambda({
            region: 'us-east-1'
          });
          lambda.getFunction({ FunctionName: action.getName() }, (error, data) => {
            action.writeArn(data.Configuration.FunctionArn);
            resolve();
          });
        });
      })
    );
  }

  /**
   * @return {Promise}
   */
  uploadActions() {
    return Promise.all(
      this.application.getActions().map((action) => {
        return new Promise((resolve, reject) => {
          awsLambda.deploy(
            `${action.getDirectoryPath()}/dist.zip`,
            {
              functionName: action.getName(),
              handler: action.getHandlerId(),
              region: action.getRegion(),
              role: action.getRole(),
              timeout: action.getTimeout()
            },
            () => {
              console.log(`Uploaded ${action.getName()} function`);
              resolve();
            }
          );
        });
      })
    );
  }

  /**
   * @param {Function} middleware
   * @param {Object=} options
   * @return {Composer}
   */
  use(middleware, options) {
    return new this.constructor({
      accessKeyId: this.accessKeyId,
      application: this.application,
      client: this.getClient().use(middleware, options),
      region: this.region,
      secretAccessKey: this.secretAccessKey
    });
  }
}
<commit_msg>Create deployment at the end of `fluct deploy`<commit_after>import AWS from 'aws-sdk'
import awsLambda from 'node-aws-lambda'
import crypto from 'crypto'
import { Client } from 'amazon-api-gateway-client'

const DEFAULT_STAGE_NAME = 'production';

/**
 * @class
 */
export default class Composer {
  /**
   * @param {String} accessKeyId
   * @param {Application} application
   * @param {Client=} client
   * @param {String} region
   * @param {String} secretAccessKey
   */
  constructor({ accessKeyId, application, client, region, secretAccessKey }) {
    this.accessKeyId = accessKeyId;
    this.application = application;
    this.client = client;
    this.region = region;
    this.secretAccessKey = secretAccessKey;
  }

  /**
   * @param {Stirng} restapiId
   * @return {Promise}
   */
  createDeployment({ restapiId }) {
    return this.getClient().createDeployment({
      restapiId: restapiId,
      stageName: DEFAULT_STAGE_NAME
    });
  }

  /**
   * @param {String} functionName
   * @param {String} httpMethod
   * @param {String} path
   * @param {Stirng} resourceId
   * @param {Stirng} restapiId
   * @param {String} uri
   * @return {Promise}
   */
  createMethodSet({ functionName, httpMethod, path, resourceId, restapiId, uri }) {
    return this.getClient().putMethod({
      httpMethod: httpMethod,
      resourceId: resourceId,
      restapiId: restapiId
    }).then((resource) => {
      return this.getClient().putIntegration({
        httpMethod: httpMethod,
        integrationHttpMethod: 'POST',
        resourceId: resourceId,
        restapiId: restapiId,
        type: 'AWS',
        uri: uri
      });
    }).then((integration) => {
      return this.getClient().putMethodResponse({
        httpMethod: httpMethod,
        resourceId: resourceId,
        restapiId: restapiId,
        statusCode: 200
      });
    }).then(() => {
      return this.getClient().putIntegrationResponse({
        httpMethod: httpMethod,
        resourceId: resourceId,
        restapiId: restapiId,
        statusCode: 200
      });
    }).then(() => {
      return new Promise((resolve, reject) => {
        new AWS.Lambda({
          region: 'us-east-1'
        }).addPermission(
          {
            Action: 'lambda:InvokeFunction',
            FunctionName: functionName,
            Principal: 'apigateway.amazonaws.com',
            StatementId: crypto.randomBytes(20).toString('hex')
          },
          (error, data) => {
            resolve();
          }
        );
      })
    });
  }

  /**
   * @param {String} restapiId
   * @return {Promise}
   */
  createResourceSets({ restapiId }) {
    return this.getClient().createResources({
      paths: this.getPaths(),
      restapiId: restapiId
    }).then(() => {
      return Promise.all(
        this.application.getActions().map((action) => {
          return this.getClient().findResourceByPath({
            path: action.getPath(),
            restapiId: restapiId
          }).then((resource) => {
            return this.createMethodSet({
              functionName: action.getName(),
              httpMethod: action.getHttpMethod(),
              path: action.getPath(),
              resourceId: resource.source.id,
              restapiId: restapiId,
              uri: action.getUri()
            });
          });
        })
      );
    });
  }

  /**
   * @return {Promise}
   */
  createRestapi() {
    return this.getClient().createRestapi({
      name: this.application.getName()
    }).then((restapi) => {
      this.application.writeRestapiId(restapi.source.id);
      return restapi;
    });
  }

  /**
   * @return {Promise}
   */
  createZipFiles() {
    return Promise.all(
      this.application.getActions().map((action) => {
        return action.createZipFile();
      })
    );
  }

  /**
   * @param {String} restapiId
   * @return {Promise}
   */
  deleteDefaultModels({ restapiId }) {
    return Promise.all(
      [
        'Empty',
        'Error'
      ].map((modelName) => {
        return this.getClient().deleteModel({
          modelName: modelName,
          restapiId: restapiId
        });
      })
    );
  }

  /**
   * Set up Amazon Lambda functions and API Gateway endpoints.
   * @return {Promise}
   */
  deploy() {
    return this.createZipFiles().then(() => {
      return this.uploadActions();
    }).then(() => {
      return this.updateActionsMetadata();
    }).then(() => {
      return this.findOrCreateRestapi();
    }).then((restapi) => {
      return this.deleteDefaultModels({
        restapiId: restapi.source.id
      }).then(() => {
        return restapi;
      });
    }).then((restapi) => {
      return this.createResourceSets({
        restapiId: restapi.source.id
      }).then(() => {
        return restapi;
      });
    }).then((restapi) => {
      this.createDeployment({
        restapiId: restapi.source.id
      });
    });
  }

  /**
   * @return {Promise}
   */
  findOrCreateRestapi() {
    const restapiId = this.application.getRestapiId();
    if (restapiId) {
      return this.getClient().getRestapi({ restapiId: restapiId });
    } else {
      return this.createRestapi();
    }
  }

  /**
   * @return {Client}
   */
  getClient() {
    if (!this.client) {
      this.client = new Client({
        accessKeyId: this.accessKeyId,
        region: this.region,
        secretAccessKey: this.secretAccessKey
      });
    }
    return this.client;
  }

  /**
   * @return {Array.<String>}
   */
  getPaths() {
    return this.application.getActions().map((action) => {
      return action.getPath();
    });
  }

  /**
   * @return {Promise}
   */
  updateActionsMetadata() {
    return Promise.all(
      this.application.getActions().map((action) => {
        return new Promise((resolve, reject) => {
          const lambda = new AWS.Lambda({
            region: 'us-east-1'
          });
          lambda.getFunction({ FunctionName: action.getName() }, (error, data) => {
            action.writeArn(data.Configuration.FunctionArn);
            resolve();
          });
        });
      })
    );
  }

  /**
   * @return {Promise}
   */
  uploadActions() {
    return Promise.all(
      this.application.getActions().map((action) => {
        return new Promise((resolve, reject) => {
          awsLambda.deploy(
            `${action.getDirectoryPath()}/dist.zip`,
            {
              functionName: action.getName(),
              handler: action.getHandlerId(),
              region: action.getRegion(),
              role: action.getRole(),
              timeout: action.getTimeout()
            },
            () => {
              console.log(`Uploaded ${action.getName()} function`);
              resolve();
            }
          );
        });
      })
    );
  }

  /**
   * @param {Function} middleware
   * @param {Object=} options
   * @return {Composer}
   */
  use(middleware, options) {
    return new this.constructor({
      accessKeyId: this.accessKeyId,
      application: this.application,
      client: this.getClient().use(middleware, options),
      region: this.region,
      secretAccessKey: this.secretAccessKey
    });
  }
}
<|endoftext|>


<commit_before>var LZString = require("lz-string");
var HashMap = require("hashmap");

function compress(jsonData) {
    return LZString.compress(jsonData);
}

function decompress(compressed) {
    return LZString.decompress(compressed);
}

/**
 * Function that counts number of symbols occurrences in string and returns
 * @param input string that is expected to be JSON (but not a mandatory)
 * @returns {*} a map < symbol, count >
 */
function countOccurrences(input) {
    var occurrencesMap = new HashMap();
    for (var i = 0; i < input.length; i++) {
        var currentChar = input.charAt(i);
        if (occurrencesMap.has(currentChar)) {
            var charCount = occurrencesMap.get(currentChar);
            charCount++;
            occurrencesMap.set(currentChar, charCount);
        } else {
            occurrencesMap.set(currentChar, 1);
        }
    }
    return occurrencesMap;
}

/**
 * "Class" Node that will build a Huffman tree later on.
 * @param symbol - char from an input string
 * @param probability - number of occurrences of this symbol in a string
 * @constructor creates a new object of type Node
 */
function Node(symbol, probability) {
    this.symbol = symbol;
    this.probability = probability;
    this.leftNode = null;
    this.rightNode = null;
}

/**
 * Quick qSort algorithm for probability of Nodes.
 * Why not to use Array.prototype.qSort()?
 * Because I also need to swap elements in keysArray in the same order as valuesArray.
 * So, swap function is always called twice
 * @param keysArray array of symbols
 * @param valuesArray array of probabilities
 */
function quickSort(keysArray, valuesArray) {

    /**
     * @param pivot - index of the pivot
     * @param left - index of leftmost element
     * @param right - index of rightmost element
     */
    function partition(pivot, left, right) {
        var storeIndex = left,
            pivotValue = valuesArray[pivot];

        swap(keysArray, pivot, right);
        swap(valuesArray, pivot, right);

        for (var i = left; i < right; i++) {
            if (valuesArray[i] < pivotValue) {
                swap(keysArray, i, storeIndex);
                swap(valuesArray, i, storeIndex);
                storeIndex++;
            }
        }

        swap(keysArray, right, storeIndex);
        swap(valuesArray, right, storeIndex);
        return storeIndex;
    }

    function qSort(left, right) {
        var pivot = null;

        if (typeof left !== "number") {
            left = 0;
        }

        if (typeof right !== "number") {
            right = valuesArray.length - 1;
        }

        if (left < right) {
            pivot = left + Math.ceil((right - left) * 0.5);
            var newPivot = partition(pivot, left, right);

            qSort(left, newPivot - 1);
            qSort(newPivot + 1, right);
        }
    }

    return {
        qSort,
        partition
    };
}

/**
 * Function that returns sorted array of Nodes that is sorted by priority, which is probability
 * @param occurrencesMap - map < symbol, count >
 * @returns {*[]} sorted array of Nodes
 */
function createPriorityQueue(occurrencesMap) {
    // After that create an array of Nodes and qSort it by Probability value and return this array
    var queue = [occurrencesMap.count()];
    var keysArray = occurrencesMap.keys();
    var valuesArray = occurrencesMap.values();
    quickSort(keysArray, valuesArray).qSort(0, valuesArray.length - 1);
    for (var i = 0; i < occurrencesMap.count(); i++) {
        queue[i] = new Node(keysArray[i], valuesArray[i]);
    }
    return queue;
}

function swap(queue, firstIndex, secondIndex) {
    var temp = queue[firstIndex];
    queue[firstIndex] = queue[secondIndex];
    queue[secondIndex] = temp;
}

function selectionSort(queue) {
    var length = queue.length, min;

    for (var i = 0; i < length; i++) {
        min = i;

        for (var j = i + 1; j < length; j++) {
            if (queue[j].probability < queue[min].probability) {
                min = j;
            }
        }

        if (i !== min) {
            swap(queue, i, min);
        }
    }
    return queue;
}

function buildTree(queue) {

    var newNode;
    while (queue.length > 1) {
        newNode = new Node(null, queue[0].probability + queue[1].probability);
        newNode.leftNode = queue[0];
        newNode.rightNode = queue[1];
        queue[0] = null;
        queue[1] = null;
        queue[1] = newNode;
        queue = queue.slice(1, queue.length);
        queue = selectionSort(queue);
    }
    return newNode;
}

exports.compress = compress;
exports.decompress = decompress;
exports.countOccurences = countOccurrences;
exports.createPriorityQueue = createPriorityQueue;
exports.quickSort = quickSort;
exports.swap = swap;
exports.selectionSort = selectionSort;
exports.buildTree = buildTree;<commit_msg>New fixes<commit_after>var LZString = require("lz-string");
var HashMap = require("hashmap");

function compress(jsonData) {
    return LZString.compress(jsonData);
}

function decompress(compressed) {
    return LZString.decompress(compressed);
}

/**
 * Function that counts number of symbols occurrences in string and returns
 * @param input string that is expected to be JSON (but not a mandatory)
 * @returns {*} a map < symbol, count >
 */
function countOccurrences(input) {
    var occurrencesMap = new HashMap();
    for (var i = 0; i < input.length; i++) {
        var currentChar = input.charAt(i);
        if (occurrencesMap.has(currentChar)) {
            var charCount = occurrencesMap.get(currentChar);
            charCount++;
            occurrencesMap.set(currentChar, charCount);
        } else {
            occurrencesMap.set(currentChar, 1);
        }
    }
    return occurrencesMap;
}

/**
 * "Class" Node that will build a Huffman tree later on.
 * @param symbol - char from an input string
 * @param probability - number of occurrences of this symbol in a string
 * @constructor creates a new object of type Node
 */
function Node(symbol, probability) {
    this.symbol = symbol;
    this.probability = probability;
    this.leftNode = null;
    this.rightNode = null;
}

/**
 * Quick qSort algorithm for probability of Nodes.
 * Why not to use Array.prototype.qSort()?
 * Because I also need to swap elements in keysArray in the same order as valuesArray.
 * So, swap function is always called twice
 * @param keysArray array of symbols
 * @param valuesArray array of probabilities
 */
function quickSort(keysArray, valuesArray) {

    /**
     * @param pivot - index of the pivot
     * @param left - index of leftmost element
     * @param right - index of rightmost element
     */
    function partition(pivot, left, right) {
        var storeIndex = left,
            pivotValue = valuesArray[pivot];

        swap(keysArray, pivot, right);
        swap(valuesArray, pivot, right);

        for (var i = left; i < right; i++) {
            if (valuesArray[i] < pivotValue) {
                swap(keysArray, i, storeIndex);
                swap(valuesArray, i, storeIndex);
                storeIndex++;
            }
        }

        swap(keysArray, right, storeIndex);
        swap(valuesArray, right, storeIndex);
        return storeIndex;
    }

    function qSort(left, right) {
        var pivot = null;

        if (typeof left !== "number") {
            left = 0;
        }

        if (typeof right !== "number") {
            right = valuesArray.length - 1;
        }

        if (left < right) {
            pivot = left + Math.ceil((right - left) * 0.5);
            var newPivot = partition(pivot, left, right);

            qSort(left, newPivot - 1);
            qSort(newPivot + 1, right);
        }
    }

    return {
        qSort,
        partition
    };
}

/**
 * Function that returns sorted array of Nodes that is sorted by priority, which is probability
 * @param occurrencesMap - map < symbol, count >
 * @returns {*[]} sorted array of Nodes
 */
function createPriorityQueue(occurrencesMap) {
    // After that create an array of Nodes and qSort it by Probability value and return this array
    var queue = [occurrencesMap.count()];
    var keysArray = occurrencesMap.keys();
    var valuesArray = occurrencesMap.values();
    quickSort(keysArray, valuesArray).qSort(0, valuesArray.length - 1);
    for (var i = 0; i < occurrencesMap.count(); i++) {
        queue[i] = new Node(keysArray[i], valuesArray[i]);
    }
    return queue;
}

function swap(queue, firstIndex, secondIndex) {
    var temp = queue[firstIndex];
    queue[firstIndex] = queue[secondIndex];
    queue[secondIndex] = temp;
}

function selectionSort(queue) {
    var length = queue.length, min;

    for (var i = 0; i < length; i++) {
        min = i;

        for (var j = i + 1; j < length; j++) {
            if (queue[j].probability < queue[min].probability) {
                min = j;
            }
        }

        if (i !== min) {
            swap(queue, i, min);
        }
    }
    return queue;
}

function buildTree(queue) {

    var newNode;
    while (queue.length > 1) {
        newNode = new Node(null, queue[0].probability + queue[1].probability);
        newNode.leftNode = queue[0];
        newNode.rightNode = queue[1];
        queue[0] = null;
        queue[1] = newNode;
        queue = queue.slice(1, queue.length);
        queue = selectionSort(queue);
    }
    return newNode;
}

exports.compress = compress;
exports.decompress = decompress;
exports.countOccurences = countOccurrences;
exports.createPriorityQueue = createPriorityQueue;
exports.quickSort = quickSort;
exports.swap = swap;
exports.selectionSort = selectionSort;
exports.buildTree = buildTree;<|endoftext|>


<commit_before>/* global $ location django */
$(document).ready(function () {
  var $main = $('main')
  var currentPath
  var popup
  var patternsForPopup = /\/accounts\b/

  var headers = {
    'X-Embed': ''
  }

  var loadHtml = function (html, textStatus, xhr) {
    var $root = $(html).filter('main')
    var nextPath = xhr.getResponseHeader('x-ajax-path')

    if (patternsForPopup.test(nextPath)) {
      $('#embed-confirm').modal('show')
      return false
    }
    // only update the currentPath if there was no modal opened
    currentPath = nextPath

    $main.empty()
    $main.append($root.children())
    onReady()
  }

  var onReady = function () {
    // adhocracy4.onReady($main)
  }

  var getEmbedTarget = function ($element, url) {
    var embedTarget = $element.data('embedTarget')

    if (embedTarget) {
      return embedTarget
    } else if (!url || url[0] === '#' || $element.attr('target')) {
      return 'ignore'
    } else if ($element.is('.rich-text a')) {
      return 'external'
    } else if (patternsForPopup.test(url)) {
      return 'popup'
    } else {
      return 'internal'
    }
  }

  $(document).on('click', 'a[href]', function (event) {
    // NOTE: event.target.href is resolved against /embed/
    var url = event.target.getAttribute('href')
    var $link = $(event.target)
    var embedTarget = getEmbedTarget($link, url)

    if (embedTarget === 'internal') {
      event.preventDefault()

      if (url[0] === '?') {
        url = currentPath + url
      }

      $.ajax({
        url: url,
        headers: headers,
        success: loadHtml
      })
    } else if (embedTarget === 'popup') {
      event.preventDefault()
      popup = window.open(
        url,
        'embed_popup',
        'height=650,width=500,location=yes,menubar=no,toolbar=no,status=no'
      )
    }
  })

  $(document).on('submit', 'form[action]', function (event) {
    var form = event.target
    var $form = $(form)
    var embedTarget = getEmbedTarget($form, form.method)

    if (embedTarget === 'internal') {
      event.preventDefault()

      $.ajax({
        url: form.action,
        method: form.method,
        headers: headers,
        data: $form.serialize(),
        success: loadHtml
      })
    }
  })

  $('.js-embed-logout').on('click', function (e) {
    e.preventDefault()
    $.post(
      '/accounts/logout/',
      function () {
        location.reload()
      }
    )
  })

  // The popup will send a message when the user is logged in. Only after
  // this message the Popup will close.
  window.addEventListener('message', function (e) {
    if (e.origin === location.origin) {
      var data = JSON.parse(e.data)

      if (data.name === 'popup-close' && popup) {
        popup.close()
        location.reload()
      }
    }
  }, false)

  $(document).ajaxError(function (event, jqxhr) {
    var text
    var $error = $('

')
    var $close = $('<button class="alert__close"></button>')

    var removeMessage = function () {
      $error.remove()
    }

    switch (jqxhr.status) {
      case 404:
        text = django.gettext('We couldn\'t find what you were looking for.')
        break
      case 401:
      case 403:
        text = django.gettext('You don\'t have the permission to view this page.')
        break
      default:
        text = django.gettext('Something went wrong!')
        break
    }

    $error.text(text)
    $error.append($close)
    $error.prependTo($('#embed-status'))
    $close.attr('title', django.gettext('Close'))

    $error.on('click', removeMessage)
    setTimeout(removeMessage, 6000)
  })

  $.ajax({
    url: $('body').data('url'),
    headers: headers,
    success: loadHtml
  })
})
<commit_msg>embed: jump to top after navigation<commit_after>/* global $ location django */
$(document).ready(function () {
  var $main = $('main')
  var currentPath
  var popup
  var patternsForPopup = /\/accounts\b/
  var $top = $('
')

  var headers = {
    'X-Embed': ''
  }

  var loadHtml = function (html, textStatus, xhr) {
    var $root = $(html).filter('main')
    var nextPath = xhr.getResponseHeader('x-ajax-path')

    if (patternsForPopup.test(nextPath)) {
      $('#embed-confirm').modal('show')
      return false
    }
    // only update the currentPath if there was no modal opened
    currentPath = nextPath

    $main.empty()
    $main.append($top)
    $main.append($root.children())
    onReady()

    // jump to top after navigation
    $top.focus()
  }

  var onReady = function () {
    // adhocracy4.onReady($main)
  }

  var getEmbedTarget = function ($element, url) {
    var embedTarget = $element.data('embedTarget')

    if (embedTarget) {
      return embedTarget
    } else if (!url || url[0] === '#' || $element.attr('target')) {
      return 'ignore'
    } else if ($element.is('.rich-text a')) {
      return 'external'
    } else if (patternsForPopup.test(url)) {
      return 'popup'
    } else {
      return 'internal'
    }
  }

  $(document).on('click', 'a[href]', function (event) {
    // NOTE: event.target.href is resolved against /embed/
    var url = event.target.getAttribute('href')
    var $link = $(event.target)
    var embedTarget = getEmbedTarget($link, url)

    if (embedTarget === 'internal') {
      event.preventDefault()

      if (url[0] === '?') {
        url = currentPath + url
      }

      $.ajax({
        url: url,
        headers: headers,
        success: loadHtml
      })
    } else if (embedTarget === 'popup') {
      event.preventDefault()
      popup = window.open(
        url,
        'embed_popup',
        'height=650,width=500,location=yes,menubar=no,toolbar=no,status=no'
      )
    }
  })

  $(document).on('submit', 'form[action]', function (event) {
    var form = event.target
    var $form = $(form)
    var embedTarget = getEmbedTarget($form, form.method)

    if (embedTarget === 'internal') {
      event.preventDefault()

      $.ajax({
        url: form.action,
        method: form.method,
        headers: headers,
        data: $form.serialize(),
        success: loadHtml
      })
    }
  })

  $('.js-embed-logout').on('click', function (e) {
    e.preventDefault()
    $.post(
      '/accounts/logout/',
      function () {
        location.reload()
      }
    )
  })

  // The popup will send a message when the user is logged in. Only after
  // this message the Popup will close.
  window.addEventListener('message', function (e) {
    if (e.origin === location.origin) {
      var data = JSON.parse(e.data)

      if (data.name === 'popup-close' && popup) {
        popup.close()
        location.reload()
      }
    }
  }, false)

  $(document).ajaxError(function (event, jqxhr) {
    var text
    var $error = $('

')
    var $close = $('<button class="alert__close"></button>')

    var removeMessage = function () {
      $error.remove()
    }

    switch (jqxhr.status) {
      case 404:
        text = django.gettext('We couldn\'t find what you were looking for.')
        break
      case 401:
      case 403:
        text = django.gettext('You don\'t have the permission to view this page.')
        break
      default:
        text = django.gettext('Something went wrong!')
        break
    }

    $error.text(text)
    $error.append($close)
    $error.prependTo($('#embed-status'))
    $close.attr('title', django.gettext('Close'))

    $error.on('click', removeMessage)
    setTimeout(removeMessage, 6000)
  })

  $.ajax({
    url: $('body').data('url'),
    headers: headers,
    success: loadHtml
  })
})
<|endoftext|>