<commit_before>/* global Mustache  */
(function($) {
  'use strict';

  var idCount = 0;

  var join = function(base, url) {
    if (url.indexOf('http') === 0 || url.indexOf('//') === 0) {
      return url;
    }
    return base + url;
  };

  var renderMustache = function(template, context) {
    context = context || {};

    //Add the lambdas we need
    context.lang = function() {
      return function(txt, render) {
        return render('{{=[[ ]]=}}' + txt.replace(/lang/g, 'sv'));
      };
    };
    context.currency =  function() {
      return function(txt, render) {
        return render('{{=[[ ]]=}}' + txt.replace(/currency/g, 'SEK'));
      };
    };
    context.gettext =  function() {
      return function(txt, render) {
        return render('{{=[[ ]]=}}' + txt);
      };
    };

    return Mustache.render(template, context);
  };

  var loadConfig = function(urls, configs, options, done) {
    var path = urls.shift();

    $.getJSON(path, function(config) {
      configs[config.name] = config;

      angular.forEach(config.dependencies, function(version, name) {
        if (!configs[name]) {
          urls.push(options.root + name + '/diversity.json');
        }
      });

      //Recurse and load the next
      if (urls.length > 0) {
        loadConfig(urls, configs, options, done);
      } else {
        //we're done!
        done();
      }
    });
  };

  //Load lots of json files recursively
  var loadAll = function(firstUrl, next, done) {
    if (angular.isString(firstUrl)) {
      firstUrl = [firstUrl];
    }

    var results = [];
    var loadAllInner = function(urls, next, done) {
      var path = urls.shift();
      console.log('ajax', path);
      $.ajax(path, {
        type: 'GET',
        dataType: 'text',
        success: function(data) {
          results.push(data);

          var n = next(path, data);
          if (angular.isString(n)) {
            urls.push(n);
          } else if (angular.isArray(n)) {
            urls = urls.concat(n);
          }
        },
        error: function() { console.log('fail', arguments); },
        complete: function() {
          if (urls.length > 0) {
            loadAllInner(urls, next, done);
          } else {
            done(results);
          }
        }
      });
    };

    loadAllInner(firstUrl, next, done);
  };

/*

        //We append scripts in the correct order
        //FIXME: probably not the best way to do it.
        frag = document.createDocumentFragment();
        angular.forEach(scripts,function(url){
          var script = document.createElement('script');
          script.setAttribute('type','text/javascript');
          script.innerHTML = cache[url];
          frag.appendChild(script);
          console.log(url);
        });

*/
  //We need to load scripts in the correct order, therefore we do it synced
  //probably doesn't work in ie.
  var loadScripts = function(scripts, allDone) {
    if (!scripts || scripts.length === 0) {
      allDone();
      return;
    }

    var url = scripts.shift();
    var script = document.createElement('script');
    script.setAttribute('type', 'text/javascript');
    script.onload = function() {
      //script onload!
      console.log('onload', url);
      loadScripts(scripts, allDone);
    };
    script.onerror = function() {
      console.log('onerror', url);
      loadScripts(scripts, allDone);
    };
    script.src = url;
    document.head.appendChild(script);
  };

  $.fn.diversity = function(name, options) {
    options = $.extend({
      root: '',  //root of main component
      deps: 'deps/', //root of component dependencies
      locale: 'sv',
      backend: 'https://davidstage.textalk.se/backend/jsonrpc/v1/',
      context:  {
        webshop: 11011,
        languageCode: 'sv',
        currencyCode: 'SEK'
      }
    }, options);
    var target = this[0];

    //we need an id on target
    if (!target.id) {
      target.id = 'diversity-component-' + name + '-' + idCount++;
    }

    //Prepare global object for preloaded data, mostly translations
    window.tws = window.tws || {};
    window.tws.data = window.tws.data || {};

    //Start by loading all resources except scripts and CSS and cache them
    //This means all dependant components, all tranlations and all mustache
    //templates
    var cache = {};
    var configs = {};
    loadAll(
      options.root + '/diversity.json',
      function(path, data) {
        cache[path] = data;
        if (/diversity.json$/.test(path)) {
          if (angular.isString(data)) {
            data = JSON.parse(data);
          }
          var config = data;
          var basePath = path.substring(0, path.length - 14);
          config.basePath = basePath;
          configs[config.name] = config;

          var urls = [];
          angular.forEach(config.dependencies, function(version, name) {
            urls.push(options.deps + name + '/diversity.json');
          });

          if (angular.isString(config.template)) {
            urls.push(basePath + config.template);
          } else {
            angular.forEach(config.template, function(template) {
              urls.push(basePath + template);
            });
          }

          if (config.i18n && config.i18n[options.locale] &&
              config.i18n[options.locale].view) {
            urls.push(basePath + config.i18n[options.locale].view);
          }

          //filter out already loaded urls
          urls = urls.filter(function(url) { return !cache[url]; });

          return urls;
        }
      },
      function() {
        // Everything is loaded now. OK. lets traverse the dependency tree and
        // load scripts and css, and why not parse some mustach?
        var config  = configs[name];
        var scripts = [];
        var styles  = [];
        var done    = {};
        var bottomsup = function(component) {
          //bail out if this component is already loaded
          //i.e. several components depend on the same base component (tws-api)
          if (done[component.name]) {
            return;
          }

          //Do any dependencies first.
          angular.forEach(component.dependencies, function(version, name) {
            bottomsup(configs[name]);
          });

          //base url differs between
          options.context.baseUrl = component.basePath;
          //Add styles, we need this to get the order right
          if (angular.isString(component.script)) {
            scripts.push(join(component.basePath, component.script));
          } else {
            angular.forEach(component.script, function(url) {
              scripts.push(join(component.basePath, url));
            });
          }

          if (angular.isString(component.style)) {
            styles.push(join(component.basePath, component.style));
          } else {
            angular.forEach(component.style, function(url) {
              styles.push(join(component.basePath, url));
            });
          }

          //FIXME: support more than swedish
          if (component.i18n && component.i18n.sv && component.i18n.sv.view) {
            var po = cache[join(component.basePath, component.i18n.sv.view)];
            if (po) {
              //Might be initialized in template, might not.
              if (!window.tws.data[component.name]) {
                window.tws.data[component.name] = {};
              }
              window.tws.data[component.name].messages = JSON.parse(po);
              console.log(window.tws.data[component.name].messages);
            }
          }

          //mark as done!
          done[component.name] = true;
        };
        bottomsup(config);

        //now let's create some tags
        var frag = document.createDocumentFragment();

        angular.forEach(styles, function(style) {
          var link = document.createElement('link');
          link.setAttribute('rel', 'stylesheet');
          link.setAttribute('href', style);
          frag.appendChild(link);
        });

        //Then add them to head
        $('head')[0].appendChild(frag);

        console.log('Loading scripts');
        loadScripts(scripts, function() {
          // All scripts have loaded, let's render and boostrap

          // We only render template for top component
          // TODO: make API requests
          // TODO: get params
          // TODO: pageTypes
          // TODO: template choice
          if (config.template) {
            var template = config.template;
            if (angular.isArray(config.template)) {
              template = config.template[0];
            }
            var html = renderMustache(
              cache[config.basePath + template],
              options.context
            );
            target.innerHTML = html;
          }

          // We append bootstrap code as a script tag below the others, so it's executed whenever the
          // other scripts has loaded.
          // TODO support more than one component on a page
          if (config.angular) {
            var frag = document.createDocumentFragment();
            var bootstrap = document.createElement('script');
            bootstrap.setAttribute('type', 'text/javascript');

            var setup = [
            "console.log('bootstrap')",
            "angular.module('diversity',['"+config.angular+"'])",
                  ".constant('shopId','"+options.context.webshop+"')",
                  ".config(['twsJsonRpcClientProvider','twsSessionProvider','twsJedProvider','shopId',",
                  "function(twsJsonRpcClientProvider,  twsSessionProvider,  twsJedProvider,  shopId){",
                  " twsJsonRpcClientProvider.set(",
                  "     'ajaxUrl',               ",
                  "     '"+options.backend+"?webshop='+shopId",
                  "   );",
                  " if (window.localStorage) {",
                  "     twsSessionProvider.setSessionId(localStorage.getItem('tws.sessionId'));",
                  " }",
                  " twsSessionProvider.setResetJsonRpcOnSession(true);",
                  "}]);",
                  'angular.bootstrap(document.body,["diversity"]);'
            ];
            bootstrap.innerHTML = setup.join('\n');
            frag.appendChild(bootstrap);
            target.appendChild(frag);
          }
        });

      });
  };

})(jQuery);
<commit_msg>Updated to new twsApi naming<commit_after>/* global Mustache  */
(function($) {
  'use strict';

  var idCount = 0;

  var join = function(base, url) {
    if (url.indexOf('http') === 0 || url.indexOf('//') === 0) {
      return url;
    }
    return base + url;
  };

  var renderMustache = function(template, context) {
    context = context || {};

    //Add the lambdas we need
    context.lang = function() {
      return function(txt, render) {
        return render('{{=[[ ]]=}}' + txt.replace(/lang/g, 'sv'));
      };
    };
    context.currency =  function() {
      return function(txt, render) {
        return render('{{=[[ ]]=}}' + txt.replace(/currency/g, 'SEK'));
      };
    };
    context.gettext =  function() {
      return function(txt, render) {
        return render('{{=[[ ]]=}}' + txt);
      };
    };

    return Mustache.render(template, context);
  };

  var loadConfig = function(urls, configs, options, done) {
    var path = urls.shift();

    $.getJSON(path, function(config) {
      configs[config.name] = config;

      angular.forEach(config.dependencies, function(version, name) {
        if (!configs[name]) {
          urls.push(options.root + name + '/diversity.json');
        }
      });

      //Recurse and load the next
      if (urls.length > 0) {
        loadConfig(urls, configs, options, done);
      } else {
        //we're done!
        done();
      }
    });
  };

  //Load lots of json files recursively
  var loadAll = function(firstUrl, next, done) {
    if (angular.isString(firstUrl)) {
      firstUrl = [firstUrl];
    }

    var results = [];
    var loadAllInner = function(urls, next, done) {
      var path = urls.shift();
      console.log('ajax', path);
      $.ajax(path, {
        type: 'GET',
        dataType: 'text',
        success: function(data) {
          results.push(data);

          var n = next(path, data);
          if (angular.isString(n)) {
            urls.push(n);
          } else if (angular.isArray(n)) {
            urls = urls.concat(n);
          }
        },
        error: function() { console.log('fail', arguments); },
        complete: function() {
          if (urls.length > 0) {
            loadAllInner(urls, next, done);
          } else {
            done(results);
          }
        }
      });
    };

    loadAllInner(firstUrl, next, done);
  };

/*

        //We append scripts in the correct order
        //FIXME: probably not the best way to do it.
        frag = document.createDocumentFragment();
        angular.forEach(scripts,function(url){
          var script = document.createElement('script');
          script.setAttribute('type','text/javascript');
          script.innerHTML = cache[url];
          frag.appendChild(script);
          console.log(url);
        });

*/
  //We need to load scripts in the correct order, therefore we do it synced
  //probably doesn't work in ie.
  var loadScripts = function(scripts, allDone) {
    if (!scripts || scripts.length === 0) {
      allDone();
      return;
    }

    var url = scripts.shift();
    var script = document.createElement('script');
    script.setAttribute('type', 'text/javascript');
    script.onload = function() {
      //script onload!
      console.log('onload', url);
      loadScripts(scripts, allDone);
    };
    script.onerror = function() {
      console.log('onerror', url);
      loadScripts(scripts, allDone);
    };
    script.src = url;
    document.head.appendChild(script);
  };

  $.fn.diversity = function(name, options) {
    options = $.extend({
      root: '',  //root of main component
      deps: 'deps/', //root of component dependencies
      locale: 'sv',
      backend: 'https://davidstage.textalk.se/backend/jsonrpc/v1/',
      context:  {
        webshop: 11011,
        languageCode: 'sv',
        currencyCode: 'SEK'
      }
    }, options);
    var target = this[0];

    //we need an id on target
    if (!target.id) {
      target.id = 'diversity-component-' + name + '-' + idCount++;
    }

    //Prepare global object for preloaded data, mostly translations
    window.tws = window.tws || {};
    window.tws.data = window.tws.data || {};

    //Start by loading all resources except scripts and CSS and cache them
    //This means all dependant components, all tranlations and all mustache
    //templates
    var cache = {};
    var configs = {};
    loadAll(
      options.root + '/diversity.json',
      function(path, data) {
        cache[path] = data;
        if (/diversity.json$/.test(path)) {
          if (angular.isString(data)) {
            data = JSON.parse(data);
          }
          var config = data;
          var basePath = path.substring(0, path.length - 14);
          config.basePath = basePath;
          configs[config.name] = config;

          var urls = [];
          angular.forEach(config.dependencies, function(version, name) {
            urls.push(options.deps + name + '/diversity.json');
          });

          if (angular.isString(config.template)) {
            urls.push(basePath + config.template);
          } else {
            angular.forEach(config.template, function(template) {
              urls.push(basePath + template);
            });
          }

          if (config.i18n && config.i18n[options.locale] &&
              config.i18n[options.locale].view) {
            urls.push(basePath + config.i18n[options.locale].view);
          }

          //filter out already loaded urls
          urls = urls.filter(function(url) { return !cache[url]; });

          return urls;
        }
      },
      function() {
        // Everything is loaded now. OK. lets traverse the dependency tree and
        // load scripts and css, and why not parse some mustach?
        var config  = configs[name];
        var scripts = [];
        var styles  = [];
        var done    = {};
        var bottomsup = function(component) {
          //bail out if this component is already loaded
          //i.e. several components depend on the same base component (tws-api)
          if (done[component.name]) {
            return;
          }

          //Do any dependencies first.
          angular.forEach(component.dependencies, function(version, name) {
            bottomsup(configs[name]);
          });

          //base url differs between
          options.context.baseUrl = component.basePath;
          //Add styles, we need this to get the order right
          if (angular.isString(component.script)) {
            scripts.push(join(component.basePath, component.script));
          } else {
            angular.forEach(component.script, function(url) {
              scripts.push(join(component.basePath, url));
            });
          }

          if (angular.isString(component.style)) {
            styles.push(join(component.basePath, component.style));
          } else {
            angular.forEach(component.style, function(url) {
              styles.push(join(component.basePath, url));
            });
          }

          //FIXME: support more than swedish
          if (component.i18n && component.i18n.sv && component.i18n.sv.view) {
            var po = cache[join(component.basePath, component.i18n.sv.view)];
            if (po) {
              //Might be initialized in template, might not.
              if (!window.tws.data[component.name]) {
                window.tws.data[component.name] = {};
              }
              window.tws.data[component.name].messages = JSON.parse(po);
              console.log(window.tws.data[component.name].messages);
            }
          }

          //mark as done!
          done[component.name] = true;
        };
        bottomsup(config);

        //now let's create some tags
        var frag = document.createDocumentFragment();

        angular.forEach(styles, function(style) {
          var link = document.createElement('link');
          link.setAttribute('rel', 'stylesheet');
          link.setAttribute('href', style);
          frag.appendChild(link);
        });

        //Then add them to head
        $('head')[0].appendChild(frag);

        console.log('Loading scripts');
        loadScripts(scripts, function() {
          // All scripts have loaded, let's render and boostrap

          // We only render template for top component
          // TODO: make API requests
          // TODO: get params
          // TODO: pageTypes
          // TODO: template choice
          if (config.template) {
            var template = config.template;
            if (angular.isArray(config.template)) {
              template = config.template[0];
            }
            var html = renderMustache(
              cache[config.basePath + template],
              options.context
            );
            target.innerHTML = html;
          }

          // We append bootstrap code as a script tag below the others, so it's executed whenever the
          // other scripts has loaded.
          // TODO support more than one component on a page
          if (config.angular) {
            var frag = document.createDocumentFragment();
            var bootstrap = document.createElement('script');
            bootstrap.setAttribute('type', 'text/javascript');

            var setup = [
            "console.log('bootstrap')",
            "angular.module('diversity',['"+config.angular+"'])",
                  ".constant('shopId','"+options.context.webshop+"')",
                  ".config(['twsApi.JsonRpcClientProvider','twsApi.SessionProvider','twsApi.JedProvider','shopId',",
                  "function(twsJsonRpcClientProvider,  twsSessionProvider,  twsJedProvider,  shopId){",
                  " twsJsonRpcClientProvider.set(",
                  "     'ajaxUrl',               ",
                  "     '"+options.backend+"?webshop='+shopId",
                  "   );",
                  " if (window.localStorage) {",
                  "     twsSessionProvider.setSessionId(localStorage.getItem('tws.sessionId'));",
                  " }",
                  " twsSessionProvider.setResetJsonRpcOnSession(true);",
                  "}]);",
                  'angular.bootstrap(document.body,["diversity"]);'
            ];
            bootstrap.innerHTML = setup.join('\n');
            frag.appendChild(bootstrap);
            target.appendChild(frag);
          }
        });

      });
  };

})(jQuery);
<|endoftext|>


<commit_before>vegalab = {};

function compile(){
    // Capture the Vega and Javascript code.
    var spec = d3.select("#vega").node().value;
    var js = d3.select("#js").node().value;
    var data = d3.select("#data").node().value;

    // Create a JavaScript object out of the spec.
    //
    // TODO(choudhury): error checking for the eval call.
    try{
        spec = eval("(" + spec + ")");
    }
    catch(e){
        console.log("error parsing Vega spec: " + e);
        return;
    }

    // Compile the Vega code into the template, and display it on the page.
    var source = vg.compile(spec, vegalab.template);
    d3.select("#code")
        .text(source);

    // Eval the generated source, and capture the resulting function with a
    // name.
    eval("vegalab.make_chart = " + source + ";");

    // Create a visualization by calling the function.
    vegalab.chart = vegalab.make_chart();
    vegalab.chart.el("#chart");

    // Eval the user Javascript, which should be just a function.  Default to
    // the function that does nothing.
    if(js.length > 0){
        try{
            eval("vegalab.js = " + js);
        }
        catch(e){
            console.log("error parsing user JavaScript: " + e);
            return;
        }
    }
    else{
        vegalab.js = function() {};
    }

    // The data window should contain either a function that returns the data to
    // be used, or a JSON object describing the data directly.
    if(data.length > 0){
        try{
            // Try to parse a JSON object from the data window.
            var d = $.parseJSON(data);

            // If we succeed, send the data object to the vega object.
            vegalab.chart.data(d);
        }
        catch(e){
            // Reaching here means the data window could not be parsed as JSON.
            // Try to parse it as JavaScript now.  The window should contain a
            // single function that returns a data value.
            try{
                eval("d = " + data);

                // Call d as a function, and send its output to the vega object.
                vegalab.chart.data(d());
            }
            catch(e){
                console.log("error parsing user data: " + e);
                return;
            }
        }
    }

    // Now that the data is ready, empty the container element and create the
    // chart.
    d3.select("#chart")
        .selectAll("*")
        .remove();
    vegalab.chart.init().update();

    // Call the user JavaScript code on the vega object.
    vegalab.js(vegalab.chart);
}

// A callback function for reading a selected file and pasting its contents into
// a textarea element.
function textplop(textarea_id){
    return function(e){
        // Grab the filename from the element.
        var file = d3.event.target.files[0];

        // Instantiate a file reader object, whose callback will simply plop
        // the text into the element.
        var reader = new FileReader();
        reader.onload = function(e){
            // Grab the text.
            var text = e.target.result;

            // Place it into the textarea element.
            d3.select("#" + textarea_id)
                .text(text);
        };
        reader.readAsText(file);
    }
}

function loadspec(){
    // Check to see if it's the "dummy" option (which just states the name of
    // the pull down menu).
    var sel = d3.select("#load").node();
    if(sel.selectedIndex === 0){
        return;
    }

    // Grab the name of the option's associated directory.
    var opt = sel.options[sel.selectedIndex].id;

    // Issue ajax calls to fill the textarea elements with the contents of the
    // appropriate files.
    //
    // NOTE: the directory name is the same as the filename base.
    var filename_prefix = "/apps/VegaLab/examples/" + opt + "/" + opt;

    // Fill in the Vega spec text box.
    d3.text(filename_prefix + ".json", function(text, err){
        if(err !== undefined){
            console.log("fatal error: could not read Vega spec '" + (filename_prefix + ".json") + "'");
            return;
        }

        d3.select("#vega")
            .text(text);
    });

    // Fill in the JavaScript box.
    d3.text(filename_prefix + ".js", function(text, err){
        console.log(err);
        if(err !== undefined){
            console.log("info/warning: could not read JavaScript file '" + (filename_prefix + ".js") + "'");
            return;
        }

        d3.select("#js")
            .text(text);
    });

    // Fill in the data box.
    d3.text(filename_prefix + "-data.js", function(text, err){
        // If this fails, we have to try "-data.json" too (since the file could
        // be either of those).
        if(err !== undefined){
            d3.text(filename_prefix + "-data.json", function(text, err){
                if(err !== undefined){
                    console.log("info/warning: could not read either JavaScript file '" + (filename_prefix + "-data.js") + "' or JSON file '" + (filename_prefix + "-data.json") + "'");
                    return;
                }

                d3.select("#data")
                    .text(text);
            });

            return;
        }

        d3.select("#data")
            .text(text);
    });
}

window.onload = function(){
    // Load the Vega template text.
    d3.text("/lib/vgd3-template.js.txt", function(text){
        // Save the text.
        vegalab.template = text;

        // Now that the necessary data is loaded, install the actions on the
        // buttons.
        //
        // Install file upload handlers on the textarea buttons.
        d3.select("#vega_file")
            .on("change", textplop("vega"));

        d3.select("#js_file")
            .on("change", textplop("js"));

        d3.select("#data_file")
            .on("change", textplop("data"));

        // Install click handler for compile button, and enable the button.
        d3.select("#compile")
            .on("click", compile)
            .attr("disabled", null);
    });

    var examples = [{dir: 'histogram', optname: 'Data Distribution Histograms'}];
    d3.select("#load")
        .on("change", loadspec)
        .data(examples)
        .append("option")
        .attr("id", function(d){
            return d.dir;
        })
        .html(function(d){
            return d.optname;
        });
};
<commit_msg>Shortened description of histogram example.<commit_after>vegalab = {};

function compile(){
    // Capture the Vega and Javascript code.
    var spec = d3.select("#vega").node().value;
    var js = d3.select("#js").node().value;
    var data = d3.select("#data").node().value;

    // Create a JavaScript object out of the spec.
    //
    // TODO(choudhury): error checking for the eval call.
    try{
        spec = eval("(" + spec + ")");
    }
    catch(e){
        console.log("error parsing Vega spec: " + e);
        return;
    }

    // Compile the Vega code into the template, and display it on the page.
    var source = vg.compile(spec, vegalab.template);
    d3.select("#code")
        .text(source);

    // Eval the generated source, and capture the resulting function with a
    // name.
    eval("vegalab.make_chart = " + source + ";");

    // Create a visualization by calling the function.
    vegalab.chart = vegalab.make_chart();
    vegalab.chart.el("#chart");

    // Eval the user Javascript, which should be just a function.  Default to
    // the function that does nothing.
    if(js.length > 0){
        try{
            eval("vegalab.js = " + js);
        }
        catch(e){
            console.log("error parsing user JavaScript: " + e);
            return;
        }
    }
    else{
        vegalab.js = function() {};
    }

    // The data window should contain either a function that returns the data to
    // be used, or a JSON object describing the data directly.
    if(data.length > 0){
        try{
            // Try to parse a JSON object from the data window.
            var d = $.parseJSON(data);

            // If we succeed, send the data object to the vega object.
            vegalab.chart.data(d);
        }
        catch(e){
            // Reaching here means the data window could not be parsed as JSON.
            // Try to parse it as JavaScript now.  The window should contain a
            // single function that returns a data value.
            try{
                eval("d = " + data);

                // Call d as a function, and send its output to the vega object.
                vegalab.chart.data(d());
            }
            catch(e){
                console.log("error parsing user data: " + e);
                return;
            }
        }
    }

    // Now that the data is ready, empty the container element and create the
    // chart.
    d3.select("#chart")
        .selectAll("*")
        .remove();
    vegalab.chart.init().update();

    // Call the user JavaScript code on the vega object.
    vegalab.js(vegalab.chart);
}

// A callback function for reading a selected file and pasting its contents into
// a textarea element.
function textplop(textarea_id){
    return function(e){
        // Grab the filename from the element.
        var file = d3.event.target.files[0];

        // Instantiate a file reader object, whose callback will simply plop
        // the text into the element.
        var reader = new FileReader();
        reader.onload = function(e){
            // Grab the text.
            var text = e.target.result;

            // Place it into the textarea element.
            d3.select("#" + textarea_id)
                .text(text);
        };
        reader.readAsText(file);
    }
}

function loadspec(){
    // Check to see if it's the "dummy" option (which just states the name of
    // the pull down menu).
    var sel = d3.select("#load").node();
    if(sel.selectedIndex === 0){
        return;
    }

    // Grab the name of the option's associated directory.
    var opt = sel.options[sel.selectedIndex].id;

    // Issue ajax calls to fill the textarea elements with the contents of the
    // appropriate files.
    //
    // NOTE: the directory name is the same as the filename base.
    var filename_prefix = "/apps/VegaLab/examples/" + opt + "/" + opt;

    // Fill in the Vega spec text box.
    d3.text(filename_prefix + ".json", function(text, err){
        if(err !== undefined){
            console.log("fatal error: could not read Vega spec '" + (filename_prefix + ".json") + "'");
            return;
        }

        d3.select("#vega")
            .text(text);
    });

    // Fill in the JavaScript box.
    d3.text(filename_prefix + ".js", function(text, err){
        console.log(err);
        if(err !== undefined){
            console.log("info/warning: could not read JavaScript file '" + (filename_prefix + ".js") + "'");
            return;
        }

        d3.select("#js")
            .text(text);
    });

    // Fill in the data box.
    d3.text(filename_prefix + "-data.js", function(text, err){
        // If this fails, we have to try "-data.json" too (since the file could
        // be either of those).
        if(err !== undefined){
            d3.text(filename_prefix + "-data.json", function(text, err){
                if(err !== undefined){
                    console.log("info/warning: could not read either JavaScript file '" + (filename_prefix + "-data.js") + "' or JSON file '" + (filename_prefix + "-data.json") + "'");
                    return;
                }

                d3.select("#data")
                    .text(text);
            });

            return;
        }

        d3.select("#data")
            .text(text);
    });
}

window.onload = function(){
    // Load the Vega template text.
    d3.text("/lib/vgd3-template.js.txt", function(text){
        // Save the text.
        vegalab.template = text;

        // Now that the necessary data is loaded, install the actions on the
        // buttons.
        //
        // Install file upload handlers on the textarea buttons.
        d3.select("#vega_file")
            .on("change", textplop("vega"));

        d3.select("#js_file")
            .on("change", textplop("js"));

        d3.select("#data_file")
            .on("change", textplop("data"));

        // Install click handler for compile button, and enable the button.
        d3.select("#compile")
            .on("click", compile)
            .attr("disabled", null);
    });

    var examples = [{dir: 'histogram', optname: 'Data Histograms'}];
    d3.select("#load")
        .on("change", loadspec)
        .data(examples)
        .append("option")
        .attr("id", function(d){
            return d.dir;
        })
        .html(function(d){
            return d.optname;
        });
};
<|endoftext|>


<commit_before>/**
 * Assets versioning task for Grunt
 *
 * @author Artem Sapegin (http://sapegin.me)
 */

/*jshint node:true */
module.exports = function(grunt) {
	'use strict';

	var fs = require('fs'),
		async = grunt.util.async;

	grunt.registerMultiTask('fingerprint', 'Assets versioning task for Grunt', function() {
		var target = this.target;
		var configPrefix = [ this.name, target ].join('.');
		this.requiresConfig([ configPrefix, 'src' ].join('.'));

		var maxFingerprint = 0;
		var done = this.async();

		async.forEach(this.filesSrc, function(file, next) {
			file = grunt.template.process(file);
			var fingerprint = getFileFingerprint(file);
			if (fingerprint > maxFingerprint) {
				maxFingerprint = fingerprint;
			}
			next();
		}, function() {
			save({
				fingerprint: maxFingerprint,
				target: target,
				filename: grunt.config.getRaw([ configPrefix, 'filename' ].join('.')),
				template: grunt.config.getRaw([ configPrefix, 'template' ].join('.'))
			}, done);
		});
	});

	function getFileFingerprint(filepath) {
		return fs.statSync(filepath).mtime.getTime();
	}

	function save(options, done) {
		var context = {
			target: options.target,
			fingerprint: options.fingerprint
		};

		var contents;
		if (options.template) {
			contents = grunt.template.process(options.template, {data: context});
		}
		else {
			contents = options.fingerprint;
		}

		var filename;
		if (options.filename) {
			filename = grunt.template.process(options.filename, {data: context});
		}
		else {
			filename = options.target;
		}

		grunt.file.write(filename, contents);
		grunt.log.writeln('File "' + filename + '" created.');
		done();
	}

};
<commit_msg>Generate fingerprint as md5 hex based on files contents.<commit_after>/**
 * Assets versioning task for Grunt
 *
 * @author Artem Sapegin (http://sapegin.me)
 */

/*jshint node:true */
module.exports = function(grunt) {
	'use strict';

	var fs = require('fs');
	var crypto = require('crypto');
	var async = grunt.util.async;

	grunt.registerMultiTask('fingerprint', 'Assets versioning task for Grunt', function() {
		var target = this.target;
		var configPrefix = [ this.name, target ].join('.');
		this.requiresConfig([ configPrefix, 'src' ].join('.'));

		var md5 = crypto.createHash('md5');
		var done = this.async();

		async.forEach(this.filesSrc, function(file, next) {
			file = grunt.template.process(file);
			md5.update(grunt.file.read(file));
			next();
		}, function() {
			save({
				fingerprint: md5.digest('hex'),
				target: target,
				filename: grunt.config.getRaw([ configPrefix, 'filename' ].join('.')),
				template: grunt.config.getRaw([ configPrefix, 'template' ].join('.'))
			}, done);
		});
	});

	function save(options, done) {
		var context = {
			target: options.target,
			fingerprint: options.fingerprint
		};

		var contents;
		if (options.template) {
			contents = grunt.template.process(options.template, {data: context});
		}
		else {
			contents = options.fingerprint;
		}

		var filename;
		if (options.filename) {
			filename = grunt.template.process(options.filename, {data: context});
		}
		else {
			filename = options.target;
		}

		grunt.file.write(filename, contents);
		grunt.log.writeln('File "' + filename + '" created.');
		done();
	}

};
<|endoftext|>


<commit_before>gui.Screen.Init();
var win = gui.Window.get();
win.zoomLevel = -1;

win.on('focus', function() { focused = true; win.setProgressBar(-0.1); });
win.on('blur', function() {
	focused = false;
	if ($('#main').css("display") != "table" && typeof powGlobals.engine !== 'undefined' && powGlobals.hasVideo == 0 && parseInt($('#all-download .progress-bar').attr('data-transitiongoal')) < 100) win.setProgressBar(parseInt($('#all-download .progress-bar').attr('data-transitiongoal'))/100);
	if (wjs().plugin) wjs().emitJsMessage("[hide-context-menu]");
});
win.on('close', function() {

	if ($('#main').css("display") != "table") {
		if (powGlobals.engine && powGlobals.hasVideo == 0) var r = confirm("Are you sure? This action will delete all downloaded files.");
		else r = true;
		if (r) {
			setTimeout(function() { win.close(true); },180000); // fallback, if any error appears and the process didn't finish, the app should still close (3 mins)
			win.hide();
			if ($('#main').css("display") != "table") wjs().stopPlayer();
			if (powGlobals.engine) {
				isReady = 0;
				clearTimeout(downSpeed);
				powGlobals.engine.swarm.removeListener('wire', onmagnet);
				powGlobals.engine.server.close(function() {
					powGlobals.engine.remove(function() {
						powGlobals.engine.destroy(function() {
							win.close(true);
						});
					});
				});
			} else {
				win.close(true);
			}
		}
	} else win.close(true);
});

$.fn.scrollEnd = function(callback, timeout) {
  $(this).scroll(function(){
    var $this = $(this);
    if ($this.data('scrollTimeout')) {
      clearTimeout($this.data('scrollTimeout'));
    }
    $this.data('scrollTimeout', setTimeout(callback,timeout));
  });
};

$(window).scrollEnd(function(){
    if ($(document).scrollTop() == 0) if (powGlobals.engine) if (powGlobals.hasVideo > 0) {
		if ($("body").css("overflow-y") == "visible" || $("body").css("overflow-y") == "auto") $("body").css("overflow-y","hidden");
		win.setMinimumSize(300, 210);
		if (!wjs().isPlaying()) wjs().togglePause();
	}
}, 1000);

$(window).resize(function() {
	if ($('#main').css("display") == "table") {
		if ($(window).height() < $("#main").height() && win.zoomLevel == 0) {
			if (win.zoomLevel > -1) win.zoomLevel = -1;
		} else if ($(window).width() < $("#main").width() && win.zoomLevel == 0) {
			if (win.zoomLevel > -1) win.zoomLevel = -1;
		} else if ($(window).width() > 730 && $(window).height() > 650 && win.zoomLevel == -1) {
			if (win.zoomLevel < 0) win.zoomLevel = 0;
		}
		$('#open-url').css('top', Math.round(($(window).height() - 187) / 2)+'px');
	} else {
		if (win.zoomLevel != 0) win.zoomLevel = 0;
		$("#filesList").css("min-height",$("#player_wrapper").height());
	}
});

function resizeInBounds(newWidth,newHeight) {
	// find the screen where the window is
	gui.Screen.screens.some(function(screen,i) {
		// check if the window is horizontally inside the bounds of this screen
		var inTheScreen = 0;
		if (parseInt(win.x) > parseInt(screen.bounds.x) && parseInt(win.x) < (parseInt(screen.bounds.x) + parseInt(screen.work_area.width))) {
			inTheScreen = 1;
		} else if (i == 0 && parseInt(win.x) <= parseInt(screen.bounds.x)) inTheScreen = 1;
		if (inTheScreen) {
			// resize the window, but keep it in bounds
			if (parseInt(newWidth) >= parseInt(screen.work_area.width)) {
				if (parseInt(newHeight) >= parseInt(screen.work_area.height)) {
					win.resizeTo(screen.work_area.width, screen.work_area.height);
					win.moveTo(0,0);
				} else {
					win.resizeTo(screen.work_area.width, newHeight);
					win.moveTo(0,Math.floor((screen.work_area.height - newHeight)/2));
				}
			} else {
				if (parseInt(newHeight) >= parseInt(screen.work_area.height)) {
					win.resizeTo(newWidth, screen.work_area.height);
					win.moveTo(Math.floor((screen.work_area.width - newWidth)/2),0);
				} else {
					win.resizeTo(newWidth, newHeight);
					if ((parseInt(win.x) + parseInt(newWidth)) > parseInt(screen.work_area.width)) {
						if ((parseInt(win.y) + parseInt(newHeight)) > parseInt(screen.work_area.height)) {
							win.moveTo((screen.work_area.width - newWidth),(screen.work_area.height - newHeight));
						} else if (parseInt(win.y) < 0) {
							win.moveTo((screen.work_area.width - newWidth),0);
						} else {
							win.moveTo((screen.work_area.width - newWidth),win.y);
						}
					} else {
						if ((parseInt(win.y) + parseInt(newHeight)) > parseInt(screen.work_area.height)) {
							if (parseInt(win.x) < 0) {
								win.moveTo(0,(screen.work_area.height - newHeight));
							} else {
								win.moveTo(win.x,(screen.work_area.height - newHeight));
							}
						} else if (parseInt(win.y) < 0) {
							if (parseInt(win.x) < 0) {
								win.moveTo(0,0);
							} else {
								win.moveTo(win.x,0);
							}
						} else {
							if (parseInt(win.x) < 0) {
								win.moveTo(0,win.y);
							}
						}
					}
				}
			}
			return false;
		}
	});
	// end find the screen where the window is
	if (playerLoaded) wjs().emitJsMessage("[refresh-aspect]");
}
<commit_msg>Fix for Close App Issue<commit_after>gui.Screen.Init();
var win = gui.Window.get();
win.zoomLevel = -1;

win.on('focus', function() { focused = true; win.setProgressBar(-0.1); });
win.on('blur', function() {
	focused = false;
	if ($('#main').css("display") != "table" && typeof powGlobals.engine !== 'undefined' && powGlobals.hasVideo == 0 && parseInt($('#all-download .progress-bar').attr('data-transitiongoal')) < 100) win.setProgressBar(parseInt($('#all-download .progress-bar').attr('data-transitiongoal'))/100);
	if (wjs().plugin) wjs().emitJsMessage("[hide-context-menu]");
});
win.on('close', function() {

	if ($('#main').css("display") != "table") {
		if (powGlobals.engine && powGlobals.hasVideo == 0) var r = confirm("Are you sure? This action will delete all downloaded files.");
		else r = true;
		if (r) {
			setTimeout(function() { win.close(true); },180000); // fallback, if any error appears and the process didn't finish, the app should still close (3 mins)
			win.hide();
			if ($('#main').css("display") != "table") wjs().stopPlayer();
			if (powGlobals.engine) {
				isReady = 0;
				clearTimeout(downSpeed);
				powGlobals.engine.swarm.removeListener('wire', onmagnet);
				powGlobals.engine.server.close(function() {
					powGlobals.engine.remove(function() {
						if (powGlobals.engine) powGlobals.engine.destroy(function() { win.close(true); });
						else win.close(true);
					});
				});
			} else {
				win.close(true);
			}
		}
	} else win.close(true);
});

$.fn.scrollEnd = function(callback, timeout) {
  $(this).scroll(function(){
    var $this = $(this);
    if ($this.data('scrollTimeout')) {
      clearTimeout($this.data('scrollTimeout'));
    }
    $this.data('scrollTimeout', setTimeout(callback,timeout));
  });
};

$(window).scrollEnd(function(){
    if ($(document).scrollTop() == 0) if (powGlobals.engine) if (powGlobals.hasVideo > 0) {
		if ($("body").css("overflow-y") == "visible" || $("body").css("overflow-y") == "auto") $("body").css("overflow-y","hidden");
		win.setMinimumSize(300, 210);
		if (!wjs().isPlaying()) wjs().togglePause();
	}
}, 1000);

$(window).resize(function() {
	if ($('#main').css("display") == "table") {
		if ($(window).height() < $("#main").height() && win.zoomLevel == 0) {
			if (win.zoomLevel > -1) win.zoomLevel = -1;
		} else if ($(window).width() < $("#main").width() && win.zoomLevel == 0) {
			if (win.zoomLevel > -1) win.zoomLevel = -1;
		} else if ($(window).width() > 730 && $(window).height() > 650 && win.zoomLevel == -1) {
			if (win.zoomLevel < 0) win.zoomLevel = 0;
		}
		$('#open-url').css('top', Math.round(($(window).height() - 187) / 2)+'px');
	} else {
		if (win.zoomLevel != 0) win.zoomLevel = 0;
		$("#filesList").css("min-height",$("#player_wrapper").height());
	}
});

function resizeInBounds(newWidth,newHeight) {
	// find the screen where the window is
	gui.Screen.screens.some(function(screen,i) {
		// check if the window is horizontally inside the bounds of this screen
		var inTheScreen = 0;
		if (parseInt(win.x) > parseInt(screen.bounds.x) && parseInt(win.x) < (parseInt(screen.bounds.x) + parseInt(screen.work_area.width))) {
			inTheScreen = 1;
		} else if (i == 0 && parseInt(win.x) <= parseInt(screen.bounds.x)) inTheScreen = 1;
		if (inTheScreen) {
			// resize the window, but keep it in bounds
			if (parseInt(newWidth) >= parseInt(screen.work_area.width)) {
				if (parseInt(newHeight) >= parseInt(screen.work_area.height)) {
					win.resizeTo(screen.work_area.width, screen.work_area.height);
					win.moveTo(0,0);
				} else {
					win.resizeTo(screen.work_area.width, newHeight);
					win.moveTo(0,Math.floor((screen.work_area.height - newHeight)/2));
				}
			} else {
				if (parseInt(newHeight) >= parseInt(screen.work_area.height)) {
					win.resizeTo(newWidth, screen.work_area.height);
					win.moveTo(Math.floor((screen.work_area.width - newWidth)/2),0);
				} else {
					win.resizeTo(newWidth, newHeight);
					if ((parseInt(win.x) + parseInt(newWidth)) > parseInt(screen.work_area.width)) {
						if ((parseInt(win.y) + parseInt(newHeight)) > parseInt(screen.work_area.height)) {
							win.moveTo((screen.work_area.width - newWidth),(screen.work_area.height - newHeight));
						} else if (parseInt(win.y) < 0) {
							win.moveTo((screen.work_area.width - newWidth),0);
						} else {
							win.moveTo((screen.work_area.width - newWidth),win.y);
						}
					} else {
						if ((parseInt(win.y) + parseInt(newHeight)) > parseInt(screen.work_area.height)) {
							if (parseInt(win.x) < 0) {
								win.moveTo(0,(screen.work_area.height - newHeight));
							} else {
								win.moveTo(win.x,(screen.work_area.height - newHeight));
							}
						} else if (parseInt(win.y) < 0) {
							if (parseInt(win.x) < 0) {
								win.moveTo(0,0);
							} else {
								win.moveTo(win.x,0);
							}
						} else {
							if (parseInt(win.x) < 0) {
								win.moveTo(0,win.y);
							}
						}
					}
				}
			}
			return false;
		}
	});
	// end find the screen where the window is
	if (playerLoaded) wjs().emitJsMessage("[refresh-aspect]");
}
<|endoftext|>


<commit_before>var runner = require('testacular').runner;
var server = require('testacular').server;

module.exports = function(grunt) {
  grunt.registerMultiTask('testacular', 'run testacular.', function() {
    var done = this.async();
    if (this.data.configFile) {
      this.data.configFile = grunt.template.process(this.data.configFile);
    }
    //support `testacular run`, useful for grunt watch
    if (this.flags.run){
      runner.run(this.data, finished.bind(done));
      return;
    }
    server.start(this.data, finished.bind(done));
  });
};

function finished(code){ return this(code === 0); }<commit_msg>add license/copyright<commit_after>/*
 * gruntacular
 * https://github.com/OpenWebStack/gruntacular
 *
 * Copyright (c) 2013 Dave Geddes
 * Licensed under the MIT license.
 */

var runner = require('testacular').runner;
var server = require('testacular').server;

module.exports = function(grunt) {
  grunt.registerMultiTask('testacular', 'run testacular.', function() {
    var done = this.async();
    if (this.data.configFile) {
      this.data.configFile = grunt.template.process(this.data.configFile);
    }
    //support `testacular run`, useful for grunt watch
    if (this.flags.run){
      runner.run(this.data, finished.bind(done));
      return;
    }
    server.start(this.data, finished.bind(done));
  });
};

function finished(code){ return this(code === 0); }<|endoftext|>


<commit_before>(function() {
    'use strict';

    var EventEmitter= require('events').EventEmitter,

        versionio   = require('version-io'),
        changelog   = require('changelog-io'),
        rendy       = require('rendy'),
        spawnify    = require('spawnify'),
        async       = require('async'),
        minor       = require('minor'),
        prepend     = require('prepend'),
        grizzly     = require('grizzly'),
        readjson    = require('readjson'),
        jessy       = require('jessy'),

        Cmd         = [
            'git add --all',
            'git commit -m "chore(package) v{{ version }}"',
            'git pull --rebase',
            'git push origin {{ branch }}',
        ].join('&&'),

        CmdTag      = [
            'git tag v{{ version }}',
            'git push origin v{{ version }}'
        ].join('&&'),

        MSG         = [ 'publish <version>',
                        'package: {{ name }} v{{ version }}'
                    ].join('\n');

    module.exports  = function(version) {
        var emitter = new EventEmitter(),
            name    = process.cwd() + '/package.json';

        readjson(name, function(error, info) {
            var msg;

            if (error) {
                msg             = error.message;
                error.message   = 'Error reading package.json: ' + msg;
                emitter.emit('error', error);
            } else if (!version) {
                emitter.emit('data', rendy(MSG, {
                    name    : info.name,
                    version : info.version
                }));
            } else {
                publish(version, info, emitter);
            }
        });

        return emitter;
    };

    function publish(version, info, emitter) {
        var cmd,
            cmdTag,
            type        = '--',
            chlog       = '';

        if (!version.indexOf('v')) {
            version  = version.slice(1);
            type    += 'v' + version;
        } else if (/major|minor|patch/.test(version)) {
            type    += version;
            version  = minor(version, info.version);
        }

        cmd = rendy(Cmd, {
            version: version,
            branch: info.branch || 'master'
        });

        cmdTag = rendy(CmdTag, {
            version: version
        });

        async.series([
            function beforePublish(callback) {
                var cmd     = jessy('scripts.wisdom', info);

                if (!cmd)
                    callback();
                else
                    runWisdom(type, emitter, callback);
            },

            function(callback) {
                var isUndefined = typeof info.changelog === 'undefined';

                if (!isUndefined && !info.changelog) {
                    emitter.emit('data', 'changelog: false\n');
                    callback();
                } else {
                    changelog(version, function(error, data) {
                        if (error) {
                            callback(error);
                        } else {
                            prepend('ChangeLog', data, callback);

                            chlog = rmLines(data, 2);
                            chlog = markdown(chlog);
                        }
                    });
                }
            },

            function(callback) {
                versionio(version, callback);
            },

            function(callback) {
                versionio(version, {name: 'bower'}, function(error) {
                    if (error && error.code !== 'ENOENT')
                        emitter.emit('error', error);

                    callback();
                });
            },

            function(callback) {
               execute(cmd, emitter, callback);
            },

            function release(callback) {
                var isUndefined = typeof info.release === 'undefined';

                if (!isUndefined && !info.release) {
                    emitter.emit('data', 'release: false\n');
                    npmPublish(info, emitter, callback);
                } else {
                    execute(cmdTag, emitter, callback);
                }
            },

            function publish(callback) {
                var v       = 'v' + version,
                    repo    = getRepoName(info),
                    owner   = getOwner(info),
                    data    = {
                        owner       : owner,
                        repo        : repo,
                        tag_name    : v,
                        name        : info.name + ' ' + v,
                        body        : chlog
                    };

                grizzly(null, data, function(error) {
                    if (!error) {
                        emitter.emit('data', 'release: ok\n');
                        callback();
                    } else {
                        emitter.emit('data', 'Error releasing on github. Trying again.\n');
                        publish(callback);
                    }
                });
            },

            npmPublish.bind(null, info, emitter),

        ], function(error) {
            if (error)
                emitter.emit('error', error);

            emitter.emit('exit');
        });

        return emitter;
    }

    function npmPublish(info, emitter, callback) {
        if (!info.private)
            execute('npm publish', emitter, callback);
    }

    function execute(cmd, emitter, callback) {
        var rejected,
            spawn = spawnify(cmd);

        spawn.on('error', function(error) {
            rejected = ~error.message.indexOf('rejected');

            emitter.emit('error', error);

            if (rejected)
                callback(error);
        });

        spawn.on('data', function(data) {
            emitter.emit('data', data);
        });

        spawn.on('exit', function() {
            spawn = null;

            if (!rejected)
                callback();
        });
    }

    function runWisdom(type, emitter, callback) {
        var isError,
            spawn = spawnify('npm run wisdom -- ' + type);

        spawn.on('error', function(error) {
            isError = true;
            emitter.emit('error', error);
        });

        spawn.on('data', function(data) {
            emitter.emit('data', data);
        });

        spawn.on('close', function() {
            callback();
        });
    }

    function rmLines(str, count) {
        return str
            .split('\n')
            .slice(count)
            .join('\n');
    }

    function markdown(str) {
        return str
            .replace(/fix:/g, '## fix')
            .replace(/feature:/g, '## feature');
    }

    function getRepoName(json) {
        return json.repository.url
            .split('/')
            .pop()
            .replace('.git', '');
    }

    function getOwner(json) {
        var FROM_OWNER   = 3,
            WITHOUT_REPO = -1;

        return json.repository.url
            .split('/')
            .slice(FROM_OWNER, WITHOUT_REPO)
            .pop();
    }
})();
<commit_msg>feature(wisdom) changelog: add "\n" on error<commit_after>(function() {
    'use strict';

    var EventEmitter= require('events').EventEmitter,

        versionio   = require('version-io'),
        changelog   = require('changelog-io'),
        rendy       = require('rendy'),
        spawnify    = require('spawnify'),
        async       = require('async'),
        minor       = require('minor'),
        prepend     = require('prepend'),
        grizzly     = require('grizzly'),
        readjson    = require('readjson'),
        jessy       = require('jessy'),

        Cmd         = [
            'git add --all',
            'git commit -m "chore(package) v{{ version }}"',
            'git pull --rebase',
            'git push origin {{ branch }}',
        ].join('&&'),

        CmdTag      = [
            'git tag v{{ version }}',
            'git push origin v{{ version }}'
        ].join('&&'),

        MSG         = [ 'publish <version>',
                        'package: {{ name }} v{{ version }}'
                    ].join('\n');

    module.exports  = function(version) {
        var emitter = new EventEmitter(),
            name    = process.cwd() + '/package.json';

        readjson(name, function(error, info) {
            var msg;

            if (error) {
                msg             = error.message;
                error.message   = 'Error reading package.json: ' + msg;
                emitter.emit('error', error);
            } else if (!version) {
                emitter.emit('data', rendy(MSG, {
                    name    : info.name,
                    version : info.version
                }));
            } else {
                publish(version, info, emitter);
            }
        });

        return emitter;
    };

    function publish(version, info, emitter) {
        var cmd,
            cmdTag,
            type        = '--',
            chlog       = '';

        if (!version.indexOf('v')) {
            version  = version.slice(1);
            type    += 'v' + version;
        } else if (/major|minor|patch/.test(version)) {
            type    += version;
            version  = minor(version, info.version);
        }

        cmd = rendy(Cmd, {
            version: version,
            branch: info.branch || 'master'
        });

        cmdTag = rendy(CmdTag, {
            version: version
        });

        async.series([
            function beforePublish(callback) {
                var cmd     = jessy('scripts.wisdom', info);

                if (!cmd)
                    callback();
                else
                    runWisdom(type, emitter, callback);
            },

            function(callback) {
                var isUndefined = typeof info.changelog === 'undefined';

                if (!isUndefined && !info.changelog) {
                    emitter.emit('data', 'changelog: false\n');
                    callback();
                } else {
                    changelog(version, function(error, data) {
                        if (error) {
                            error.message += '\n';
                            callback(error);
                        } else {
                            prepend('ChangeLog', data, callback);

                            chlog = rmLines(data, 2);
                            chlog = markdown(chlog);
                        }
                    });
                }
            },

            function(callback) {
                versionio(version, callback);
            },

            function(callback) {
                versionio(version, {name: 'bower'}, function(error) {
                    if (error && error.code !== 'ENOENT')
                        emitter.emit('error', error);

                    callback();
                });
            },

            function(callback) {
               execute(cmd, emitter, callback);
            },

            function release(callback) {
                var isUndefined = typeof info.release === 'undefined';

                if (!isUndefined && !info.release) {
                    emitter.emit('data', 'release: false\n');
                    npmPublish(info, emitter, callback);
                } else {
                    execute(cmdTag, emitter, callback);
                }
            },

            function publish(callback) {
                var v       = 'v' + version,
                    repo    = getRepoName(info),
                    owner   = getOwner(info),
                    data    = {
                        owner       : owner,
                        repo        : repo,
                        tag_name    : v,
                        name        : info.name + ' ' + v,
                        body        : chlog
                    };

                grizzly(null, data, function(error) {
                    if (!error) {
                        emitter.emit('data', 'release: ok\n');
                        callback();
                    } else {
                        emitter.emit('data', 'Error releasing on github. Trying again.\n');
                        publish(callback);
                    }
                });
            },

            npmPublish.bind(null, info, emitter),

        ], function(error) {
            if (error)
                emitter.emit('error', error);

            emitter.emit('exit');
        });

        return emitter;
    }

    function npmPublish(info, emitter, callback) {
        if (!info.private)
            execute('npm publish', emitter, callback);
    }

    function execute(cmd, emitter, callback) {
        var rejected,
            spawn = spawnify(cmd);

        spawn.on('error', function(error) {
            rejected = ~error.message.indexOf('rejected');

            emitter.emit('error', error);

            if (rejected)
                callback(error);
        });

        spawn.on('data', function(data) {
            emitter.emit('data', data);
        });

        spawn.on('exit', function() {
            spawn = null;

            if (!rejected)
                callback();
        });
    }

    function runWisdom(type, emitter, callback) {
        var isError,
            spawn = spawnify('npm run wisdom -- ' + type);

        spawn.on('error', function(error) {
            isError = true;
            emitter.emit('error', error);
        });

        spawn.on('data', function(data) {
            emitter.emit('data', data);
        });

        spawn.on('close', function() {
            callback();
        });
    }

    function rmLines(str, count) {
        return str
            .split('\n')
            .slice(count)
            .join('\n');
    }

    function markdown(str) {
        return str
            .replace(/fix:/g, '## fix')
            .replace(/feature:/g, '## feature');
    }

    function getRepoName(json) {
        return json.repository.url
            .split('/')
            .pop()
            .replace('.git', '');
    }

    function getOwner(json) {
        var FROM_OWNER   = 3,
            WITHOUT_REPO = -1;

        return json.repository.url
            .split('/')
            .slice(FROM_OWNER, WITHOUT_REPO)
            .pop();
    }
})();
<|endoftext|>


<commit_before>
var elasticsearch = require('elasticsearch');
var util = require('./util');

module.exports.run = function(hosts, task, driver_data) {
  var driver = util.load_driver(task.driver);
  var operations = create_operations(driver, task.operations);
  var opindex;

  if(task.cycle_operations) {
    opindex = 0;
  } else {
    opindex = false;
  }

  try {
    var esClient = new elasticsearch.Client({
      hosts: hosts,
      min_sockets: 1,
      requestTimeout: 30000
    });

    esClient.ping({
      requestTimeout: 30000,
    }, function (error) {
      if (error) {
        util.log('Error connecting to Elasticsearch. Terminating.');
        process.exit();
      }
    });
  }
  catch(e){
    var error_message = 'Worker failed to start Elasticsearch Client: ' + e.message + ' Terminating.';
    util.log(error_message);
    process.exit();
  }

  var state;
  if(typeof driver.init === 'function') {
    state = driver.init(esClient, task.parameters, driver_data);
  } else {
    state = {};
  }

  var interval = task.op_dur_ms;

  var initial_delay = 0;
  if (interval > 0) {
    initial_delay = task.initial_delay_ms;
  }

  setTimeout(function benchmark(driver, esClient, state, driver_data, task, operations, opindex, interval) {
    var start_ts = util.get_timestamp();
    var op;
    if(util.is_integer(opindex)) {
      var idx = opindex % operations.length;
      op = operations[idx];
      opindex++;
    } else {
      op = select_random_operation(operations);
    }

    driver[op.name](esClient, state, driver_data, op.parameters, function result_callback(result) {
      if(util.is_string(result)) {
        result = { 'result_code': result };
      } else if (util.is_object(result)) {
        if(!result['result_code']) {
          result['result_code'] = 'RESULT_CODE_MISSING';
        }
      } else {
        console.log('Error: Illegal return type from job %s and operation %s.', job.job_id, op.name);
        process.exit();
      }

      var latency = util.get_timestamp() - start_ts;

      var sla_breach = false;
      if(op.sla > 0 && op.sla < latency) {
        sla_breach = true;
      }

      var label;
      if(op.label) {
        label = op.label;
      } else {
        label = op.name;
      }

      var parameters = util.clone(task.parameters);

      for(var key in op.parameters) {
        if(util.is_string(key)) {
          parameters[key] = op.parameters[key];
        }
      }

      process.send( { statistic: { timestamp: util.get_timestamp_string(), job_id: task.job_id, driver: task.driver, record_type: "detail", operation: op.name, label: label, parameters: parameters, result: result, latency: latency, sla_breach: sla_breach} } );

      var delay = Math.max(0, (interval - (util.get_timestamp() - start_ts)));

      setTimeout(benchmark, delay, driver, esClient, state, driver_data, task, operations, opindex, interval);
    });
  }, initial_delay, driver, esClient, state, driver_data, task, operations, opindex, interval);
}

function create_operations(driver, operations) {
  var total_weight = 0;

  if (operations === undefined || operations === []) {
    return get_driver_operations(driver);
  }

  operations.forEach(function (op) {
    if (op.weight) {
      total_weight += op.weight;
    } else {
      op.weight = 1.0;
      total.weight += 1.0;
    }
  });

  operations.forEach(function (op) {
    op.weight = op.weight / total_weight;
  });

  return operations;
}

function get_driver_operations(driver) {
  var operations = [];
  var opnames = [];

  for (opname in driver) {
    if(typeof driver[opname] === 'function' && opname !== 'init') {
        opnames.push(opname);
    }
  }

  var weight = 1.0 / opnames.length;

  opnames.forEach(function(entry){
    operations.push({ name: entry, weight: weight, sla: 0});
  });

  return operations;
}

function select_random_operation(operations) {
  var rnd = Math.random();
  var agg = 0.0;
  var index = 0;
  var selected_operation;

  while (agg < rnd) {
    selected_operation = operations[index];
    agg +=  operations[index]['weight'];
    index++;
  }

  return selected_operation;
}
<commit_msg>Fixed handling of case where there are no job level parameters.<commit_after>
var elasticsearch = require('elasticsearch');
var util = require('./util');

module.exports.run = function(hosts, task, driver_data) {
  var driver = util.load_driver(task.driver);
  var operations = create_operations(driver, task.operations);
  var opindex;

  if(task.cycle_operations) {
    opindex = 0;
  } else {
    opindex = false;
  }

  try {
    var esClient = new elasticsearch.Client({
      hosts: hosts,
      min_sockets: 1,
      requestTimeout: 30000
    });

    esClient.ping({
      requestTimeout: 30000,
    }, function (error) {
      if (error) {
        util.log('Error connecting to Elasticsearch. Terminating.');
        process.exit();
      }
    });
  }
  catch(e){
    var error_message = 'Worker failed to start Elasticsearch Client: ' + e.message + ' Terminating.';
    util.log(error_message);
    process.exit();
  }

  var state;
  if(typeof driver.init === 'function') {
    state = driver.init(esClient, task.parameters, driver_data);
  } else {
    state = {};
  }

  var interval = task.op_dur_ms;

  var initial_delay = 0;
  if (interval > 0) {
    initial_delay = task.initial_delay_ms;
  }

  setTimeout(function benchmark(driver, esClient, state, driver_data, task, operations, opindex, interval) {
    var start_ts = util.get_timestamp();
    var op;
    if(util.is_integer(opindex)) {
      var idx = opindex % operations.length;
      op = operations[idx];
      opindex++;
    } else {
      op = select_random_operation(operations);
    }

    driver[op.name](esClient, state, driver_data, op.parameters, function result_callback(result) {
      if(util.is_string(result)) {
        result = { 'result_code': result };
      } else if (util.is_object(result)) {
        if(!result['result_code']) {
          result['result_code'] = 'RESULT_CODE_MISSING';
        }
      } else {
        console.log('Error: Illegal return type from job %s and operation %s.', job.job_id, op.name);
        process.exit();
      }

      var latency = util.get_timestamp() - start_ts;

      var sla_breach = false;
      if(op.sla > 0 && op.sla < latency) {
        sla_breach = true;
      }

      var label;
      if(op.label) {
        label = op.label;
      } else {
        label = op.name;
      }

      var parameters;
      if(task.parameters) {
        parameters = util.clone(task.parameters);
      } else {
        parameters = {};
      }

      for(var key in op.parameters) {
        if(util.is_string(key)) {
          parameters[key] = op.parameters[key];
        }
      }

      process.send( { statistic: { timestamp: util.get_timestamp_string(), job_id: task.job_id, driver: task.driver, record_type: "detail", operation: op.name, label: label, parameters: parameters, result: result, latency: latency, sla_breach: sla_breach} } );

      var delay = Math.max(0, (interval - (util.get_timestamp() - start_ts)));

      setTimeout(benchmark, delay, driver, esClient, state, driver_data, task, operations, opindex, interval);
    });
  }, initial_delay, driver, esClient, state, driver_data, task, operations, opindex, interval);
}

function create_operations(driver, operations) {
  var total_weight = 0;

  if (operations === undefined || operations === []) {
    return get_driver_operations(driver);
  }

  operations.forEach(function (op) {
    if (op.weight) {
      total_weight += op.weight;
    } else {
      op.weight = 1.0;
      total.weight += 1.0;
    }
  });

  operations.forEach(function (op) {
    op.weight = op.weight / total_weight;
  });

  return operations;
}

function get_driver_operations(driver) {
  var operations = [];
  var opnames = [];

  for (opname in driver) {
    if(typeof driver[opname] === 'function' && opname !== 'init') {
        opnames.push(opname);
    }
  }

  var weight = 1.0 / opnames.length;

  opnames.forEach(function(entry){
    operations.push({ name: entry, weight: weight, sla: 0});
  });

  return operations;
}

function select_random_operation(operations) {
  var rnd = Math.random();
  var agg = 0.0;
  var index = 0;
  var selected_operation;

  while (agg < rnd) {
    selected_operation = operations[index];
    agg +=  operations[index]['weight'];
    index++;
  }

  return selected_operation;
}
<|endoftext|>


<commit_before>
/*!
 * Cluster - Worker
 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var EventEmitter = require('events').EventEmitter
  , spawn = require('child_process').spawn
  , binding = process.binding('net')
  , utils = require('./utils')
  , net = require('net');

// COMPAT:

net.Socket = net.Stream;

/**
 * Node binary.
 */

var node = process.execPath;

/**
 * Initialize a new `Worker` with the given `master`.
 *
 * Signals:
 *
 *   - `SIGINT`   immediately exit
 *   - `SIGTERM`  immediately exit
 *   - `SIGQUIT`  graceful exit
 *
 * @param {Master} master
 * @api private
 */

var Worker = module.exports = function Worker(master) {
  this.master = master;
  this.server = master.server;
};

/**
 * Inherit from `EventEmitter.prototype`.
 */

Worker.prototype.__proto__ = EventEmitter.prototype;

/**
 * Worker is a receiver.
 */

require('./mixins/receiver')(Worker.prototype);

/**
 * Start worker.
 *
 * @api private
 */

Worker.prototype.start = function(){
  var self = this
    , call = this.master.call;

  // proxy to provide worker id
  this.master.call = function(){
    var args = utils.toArray(arguments);
    args.unshift(self.id);
    return call.apply(this, args);
  };

  // demote usr/group
  this.server.on('listening', function(){
    var group = self.options.group;
    if (group) process.setgid(group);
    var user = self.options.user;
    if (user) process.setuid(user);
  });

  // stdin
  this.stdin = new net.Socket(0, 'unix');
  this.stdin.setEncoding('ascii');
  this.stdin.on('fd', this.server.listenFD.bind(this.server));
  this.stdin.on('data', this.frame.bind(this));
  this.stdin.resume();

  // signal handlers
  process.on('SIGINT', this.destroy.bind(this));
  process.on('SIGTERM', this.destroy.bind(this));
  process.on('SIGQUIT', this.close.bind(this));
  process.on('uncaughtException', function(err){
    // stderr for logs
    console.error(err.stack || err.message);

    // report exception
    self.master.call('workerException', err);

    // exit
    process.nextTick(function(){
      self.destroy();
    });
  });
};

/**
 * Received connect event, set the worker `id`
 * and `options`.
 *
 * @param {String} id
 * @param {Object} options
 * @api private
 */

Worker.prototype.connect = function(id, options){
  this.options = options;

  // worker id
  this.id = id;

  // timeout
  this.timeout = options.timeout;

  // notify master of connection
  this.master.call('connect');
};

/**
 * Immediate shutdown.
 *
 * @api private
 */

Worker.prototype.destroy = function(){
  process.exit();
};

/**
 * Perform graceful shutdown.
 *
 * @api private
 */

Worker.prototype.close = function(){
  var self = this
    , server = this.server;

  if (server.connections) {
    // stop accepting
    server.watcher.stop();

    // check pending connections
    setInterval(function(){
      self.master.call('workerWaiting', server.connections);
      server.connections || self.destroy();
    }, 2000);

    // timeout
    if (this.timeout) {
      setTimeout(function(){
        self.master.call('workerTimeout', self.timeout);
        self.destroy();
      }, this.timeout);
    }
  } else {
    this.destroy();
  }
};

/**
 * Spawn the worker with the given `id`.
 *
 * @param {Number} id
 * @return {Worker} for chaining
 * @api private
 */

Worker.prototype.spawn = function(id){
  var fds = binding.socketpair()
    , customFds = [fds[0]].concat(this.master.customFds)
    , env = {};

  // merge env
  for (var key in process.env) {
    env[key] = process.env[key];
  }

  this.id = env.CLUSTER_WORKER = id;

  // spawn worker process
  this.proc = spawn(
      node
    , this.master.cmd
    , { customFds: customFds, env: env });

  // unix domain socket for ICP + fd passing
  this.sock = new net.Socket(fds[1], 'unix');
  return this;
};

/**
 * Invoke worker's `method` (called from Master).
 *
 * @param {String} method
 * @param {...} args
 * @api private
 */

Worker.prototype.call = function(method){
  this.sock.write(utils.frame({
      args: utils.toArray(arguments, 1)
    , method: method
  }), 'ascii');
};
<commit_msg>Changed; only caught uncaughtExceptions when no other listeners are present<commit_after>
/*!
 * Cluster - Worker
 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var EventEmitter = require('events').EventEmitter
  , spawn = require('child_process').spawn
  , binding = process.binding('net')
  , utils = require('./utils')
  , net = require('net');

// COMPAT:

net.Socket = net.Stream;

/**
 * Node binary.
 */

var node = process.execPath;

/**
 * Initialize a new `Worker` with the given `master`.
 *
 * Signals:
 *
 *   - `SIGINT`   immediately exit
 *   - `SIGTERM`  immediately exit
 *   - `SIGQUIT`  graceful exit
 *
 * @param {Master} master
 * @api private
 */

var Worker = module.exports = function Worker(master) {
  this.master = master;
  this.server = master.server;
};

/**
 * Inherit from `EventEmitter.prototype`.
 */

Worker.prototype.__proto__ = EventEmitter.prototype;

/**
 * Worker is a receiver.
 */

require('./mixins/receiver')(Worker.prototype);

/**
 * Start worker.
 *
 * @api private
 */

Worker.prototype.start = function(){
  var self = this
    , call = this.master.call;

  // proxy to provide worker id
  this.master.call = function(){
    var args = utils.toArray(arguments);
    args.unshift(self.id);
    return call.apply(this, args);
  };

  // demote usr/group
  this.server.on('listening', function(){
    var group = self.options.group;
    if (group) process.setgid(group);
    var user = self.options.user;
    if (user) process.setuid(user);
  });

  // stdin
  this.stdin = new net.Socket(0, 'unix');
  this.stdin.setEncoding('ascii');
  this.stdin.on('fd', this.server.listenFD.bind(this.server));
  this.stdin.on('data', this.frame.bind(this));
  this.stdin.resume();

  // signal handlers
  process.on('SIGINT', this.destroy.bind(this));
  process.on('SIGTERM', this.destroy.bind(this));
  process.on('SIGQUIT', this.close.bind(this));

  // conditionally handle uncaughtException
  if (!process.listeners('uncaughtException').length) {
    process.on('uncaughtException', function(err){
      // stderr for logs
      console.error(err.stack || err.message);

      // report exception
      self.master.call('workerException', err);

      // exit
      process.nextTick(function(){
        self.destroy();
      });
    });
  }
};

/**
 * Received connect event, set the worker `id`
 * and `options`.
 *
 * @param {String} id
 * @param {Object} options
 * @api private
 */

Worker.prototype.connect = function(id, options){
  this.options = options;

  // worker id
  this.id = id;

  // timeout
  this.timeout = options.timeout;

  // notify master of connection
  this.master.call('connect');
};

/**
 * Immediate shutdown.
 *
 * @api private
 */

Worker.prototype.destroy = function(){
  process.exit();
};

/**
 * Perform graceful shutdown.
 *
 * @api private
 */

Worker.prototype.close = function(){
  var self = this
    , server = this.server;

  if (server.connections) {
    // stop accepting
    server.watcher.stop();

    // check pending connections
    setInterval(function(){
      self.master.call('workerWaiting', server.connections);
      server.connections || self.destroy();
    }, 2000);

    // timeout
    if (this.timeout) {
      setTimeout(function(){
        self.master.call('workerTimeout', self.timeout);
        self.destroy();
      }, this.timeout);
    }
  } else {
    this.destroy();
  }
};

/**
 * Spawn the worker with the given `id`.
 *
 * @param {Number} id
 * @return {Worker} for chaining
 * @api private
 */

Worker.prototype.spawn = function(id){
  var fds = binding.socketpair()
    , customFds = [fds[0]].concat(this.master.customFds)
    , env = {};

  // merge env
  for (var key in process.env) {
    env[key] = process.env[key];
  }

  this.id = env.CLUSTER_WORKER = id;

  // spawn worker process
  this.proc = spawn(
      node
    , this.master.cmd
    , { customFds: customFds, env: env });

  // unix domain socket for ICP + fd passing
  this.sock = new net.Socket(fds[1], 'unix');
  return this;
};

/**
 * Invoke worker's `method` (called from Master).
 *
 * @param {String} method
 * @param {...} args
 * @api private
 */

Worker.prototype.call = function(method){
  this.sock.write(utils.frame({
      args: utils.toArray(arguments, 1)
    , method: method
  }), 'ascii');
};
<|endoftext|>


<commit_before>var paths = require('../paths');

var Scheduler = require(paths.lib + 'scheduler');
var Task = require(paths.lib + 'task');
var jobs = require(paths.jobs);
var Logger = require('./logger');
var moment = require('moment');
/**
	@class Worker
	@extends Scheduler
	@extends Db
*/
var Worker = function(name){
	Scheduler.apply(this,arguments);

	/** @private **/
	var _self = this;
	var logger = '';

	/** @public **/
	this.name = name;

	/** @public **/
	this.createTask = function(hash){

		if(!hash) return false;

		var _worker = this;

		// Instance of tasks to be configured
		var task  = new Task(hash);

		// Add method to execute job
		task.execute = jobs[task.job.name];

		// Listening Task events

		task.once("start", logger.start);
		task.once("schedule", logger.schedule);
		task.once("unschedule", logger.unschedule);
		task.once("error", logger.error);

		task.once("end", function(id, date){
			var id = id || task.id;
			var date = date || task.date;
			logger.end(id, function(){
				if( task.repeat ){
					logger.repeat(id, date, task.repeat);
				}
			});
		});
		return task;
	};

	/** @public **/
	this.switcher = function(doc){

		if( doc.deleted ) _self.unschedule(task);
		else {
			// convert document to real task
			var task = _self.createTask(doc);

			// Decide what to do with a task
			if( task.isWaiting() ){
				if ( task.isDelayed() ){
					_self.executeTask(task);
				} else _self.schedule(task);

			} else if( task.isReschedule() ){
				_self.reschedule(task);

			} else if( task.isCancel() ){
				_self.unschedule(task);

			}
		}
	};

	/** @private **/
	var __construct = function(_self){
		logger = new Logger();
		logger.init(_self.name, _self.switcher);

		// Start timer extented from scheduler
		_self.startClock();

		function exit(){
			logger.resetAll(_self.name, function(err, res){
				if (err) console.log(err);
				else console.log('All tasks reseted');
				process.exit();
			});
		}

		// When was to exit, change all scheduled docs to waiting again
		process.on('SIGINT', function () {
			console.log('SIGINT');
			exit();
		});
		process.on('SIGTERM', function () {
			console.log('SIGTERM');
			exit();
		});
	}(this);
};

/**
** @static
*/
Worker.getWorker = function(name){
	return new Worker(name);
};
module.exports = Worker;<commit_msg>testes with multiple jobs<commit_after>var paths = require('../paths');

var Scheduler = require(paths.lib + 'scheduler');
var Task = require(paths.lib + 'task');
var jobs = require(paths.jobs);
var Logger = require('./logger');
var moment = require('moment');
/**
	@class Worker
	@extends Scheduler
	@extends Db
*/
var Worker = function(name){
	Scheduler.apply(this,arguments);

	/** @private **/
	var _self = this;
	var logger = '';

	/** @public **/
	this.name = name;

	/** @public **/
	this.createTask = function(hash){

		if(!hash) return false;

		var _worker = this;

		// Instance of tasks to be configured
		var task  = new Task(hash);

		// Add method to execute job
		task.execute = jobs[task.job.name];

		// Listening Task events

		task.once("start", logger.start);
		task.once("schedule", logger.schedule);
		task.once("unschedule", logger.unschedule);
		task.once("error", logger.error);

		task.once("end", function(id, date){
			var id = id || task.id;
			var date = date || task.date;
			logger.end(id, function(){
				if( task.repeat ){
					logger.repeat(id, date, task.repeat);
				}
			});
		});
		return task;
	};

	/** @public **/
	this.switcher = function(doc){

		if( doc.deleted ) _self.unschedule(task);
		else {
			// convert document to real task
			var task = _self.createTask(doc);

			// Decide what to do with a task
			if( task.isWaiting() ){
				if ( task.isDelayed() ){
					_self.executeTask(task);
				} else _self.schedule(task);

			} else if( task.isReschedule() ){
				_self.reschedule(task);

			} else if( task.isCancel() ){
				_self.unschedule(task);

			}
		}
	};

	/** @private **/
	var __construct = function(_self){
		logger = new Logger();
		logger.init(_self.name, _self.switcher);

		// Start timer extented from scheduler
		_self.startClock();

		function exit(){
			logger.resetAll(_self.name, function(err, res){
				if (err) console.log(err);
				else console.log('All tasks reseted');
				process.exit();
			});
		}

		// When was to exit, change all scheduled docs to waiting again
		process.on('SIGINT', function () {
			console.log('SIGINT');
			exit();
		});
		process.on('SIGTERM', function () {
			console.log('SIGTERM');
			exit();
		});
	}(this);
};

/**
** @static
*/
Worker.getWorker = function(name){
	return new Worker(name);
};
module.exports = Worker;<|endoftext|>