<commit_before>/**
 * yepnope.js 0.5.0pre
 * by Alex Sexton - AlexSexton@gmail.com
 *
 * Major Contributions by:
 * Ralph Holzmann - @ralphholzmann
 *
 * Tri-Licensed WTFPL, BSD, & MIT
 *
 * Yepnope relies on a script loading technique
 * inspired by A.getJS by Dave Artz
*/
(function(window, doc, undef) {

var docElement            = doc.documentElement,
    docHead               = doc.getElementsByTagName("head")[0] || docElement,
    docBody               = doc.getElementsByTagName("body")[0] || doc.body,
    docFirst              = docHead.firstChild,
    errorTimeout          = 5000,
    toString              = {}.toString,
    jsType                = 'j',
    cssType               = 'c',
    strScript             = "script",
    strFalse              = "false",
    strShift              = "shift",
    strReadyState         = "readyState",
    strOnReadyStateChange = "onreadystatechange",
    strOnLoad             = "onload",
    strObject             = "object",
    strImg                = "img",
    strPreobj             = "[" + strObject + " ",
    noop                  = function(){},
    execStack             = [],
    started               = 0,
    defaultsToAsync       = (doc.createElement(strScript).async === true),
    isGecko               = ("MozAppearance" in docElement.style),
    isGecko18             = isGecko && !! window.Event.prototype.preventBubble,
    // Thanks to @jdalton for this opera detection
    isOpera               = window.opera && toString.call(window.opera) == strPreobj + "Opera]",
    isWebkit              = ("webkitAppearance" in docElement.style),
    strJsElem             = isOpera || isGecko18 ? strImg : ( isGecko ? strObject : strScript ),
    strCssElem            = isWebkit ? strImg : strJsElem,
    isArray               = Array.isArray || function(obj) {
      return toString.call(obj) == strPreobj + "Array]";
    },
    isObject              = function(obj) {
      // Lame object detection, but don't pass it stupid stuff?
      return typeof obj == strObject;
    },
    isString              = function(s) {
      return typeof s == "string";
    },
    isFunction            = function(fn) {
      return toString.call(fn) == strPreobj + 'Function]';
    },
    globalFilters         = [],
    prefixes              = {
      'css': function(resource) {
        resource.forceCSS = true;
        return resource;
      },
      'wait': function(resource) {
        // This just adds an empty callback to force a wait
        resource.autoCallback = noop;
        return resource;
      }
    },
    yepnope;

  /* Loader helper functions */
  function isScriptReady( script ) {
    return ( ! script[strReadyState] || script[strReadyState] == "loaded" || script[strReadyState] == "complete");
  }

  function execWhenReady() {
    var execStackReady = 1,
        len,
        i;

    for (i = -1, len = execStack.length; ++i < len;) {
      if ( execStack[i].src && ! ( execStackReady = isScriptReady( execStack[i] ))) {
        break;
      }
    }
    if ( execStackReady ) {
      executeStack();
    }
  }

  function injectCss(oldObj) {

    // Create stylesheet link
    var link      = doc.createElement('link'),
        done;

    // Add attributes
    link.href = oldObj.src;
    link.rel  = 'stylesheet';
    link.type = 'text/css';

    // Poll for changes in webkit and gecko
    if ( isWebkit || isGecko ) {

      (function poll( link ) {
        var args = arguments;
        setTimeout(function(){
          if ( ! done ) {
            try {
              if ( link.sheet && link.sheet.cssRules && link.sheet.cssRules.length ) {
                done = true;
                execWhenReady();
              } else {
                poll(link);
              }
            } catch (ex) {

              if ( (ex.code == 1000) || (ex.message.match(/security|denied/i)) ) {
                done = true;
                setTimeout(function(){
                  execWhenReady();
                }, 0 );
              } else {
                poll(link);
              }
            }

          }
        }, 13);
      })( link );

    }
    // Onload handler for IE and Opera
    else {

      link.onload = function() {
        if ( ! done ) {
          done = true;
          setTimeout(function(){
            execWhenReady();
          }, 0);
        }
      }

    }

    // 404 Fallback
    setTimeout(function(){
      if ( ! done ) {
        done = true;
        execWhenReady();
      }
    }, errorTimeout);

    // Inject CSS
    docHead.insertBefore(link, docFirst);

  }

  function executeStack(a) {
    var i   = execStack[strShift](),
        src = i ? i.src  : undef,
        t   = i ? i.type : undef;

    started = 1;

    if ( a && src ) {
      i = execStack[strShift]();
      src = undef;
    }

    if ( i ) {
      if ( src && t == jsType ) {
        preloadFile(strScript, src, "", null, docHead);
      }
      else if ( src && t == cssType ) {
        injectCss(i);
      }
      else {
        i();
        started = 0;
        execWhenReady();
      }
    } else {
      started = 0;
    }
  }

  function preloadFile( elem, url, type, splicePoint, docHead ) {

    // Create script element
    var script    = doc.createElement( elem ),
        done      = 0;

    function onload() {

      // If the script is loaded
      if ( ! done && isScriptReady( script ) ) {
        // Set done to prevent this function from being called twice.
        done = 1;

        // If the type is set, that means that we're offloading execution
        if ( ! type || (type && ! started) ) {
          execWhenReady();
        }

        // Handle memory leak in IE
        script[strOnLoad] = script[strOnReadyStateChange] = null;
        type && docHead.removeChild(script);
      }
    }

    script.src    = script.data = url;
    if ( type ) {
      script.type = type;
    }

    // Attach handlers for all browsers
    script[strOnLoad] = script[strOnReadyStateChange] = onload;

    if ( elem == strImg ) {
      script.onerror = onload;
    } else if ( elem == strScript ) {
      script.onerror = function(){
        executeStack(1);
      };
      type && docHead.removeChild(script);
    }

    type && execStack.splice( splicePoint, 0, script);

    docHead.appendChild(script);

    if ( isOpera && ! type && elem == strScript ) {
      setTimeout(function(){
        if ( ! done ) {
          done = 1;
          execWhenReady();
        }
      }, errorTimeout);
    }

  }

  function load(resource, type) {

    var a     = arguments,
        app   = this,
        count = a.length,
        elem  = ( type == 'c' ? strCssElem : strJsElem ),
        i,q;

    // We'll do 'j' for js and 'c' for css, yay for unreadable minification tactics
    type = type || jsType;
    if ( isString( resource )) {
      preloadFile(elem, resource, type, app.i++, (elem == strObject ? docBody : docHead) );
    } else {
      execStack.splice(app.i++, 0, resource);
    }

    // OMG is this jQueries? For chaining...
    return app;

  }

  function getLoader() {
    return {
      load: load,
      i : 0
    };
  }

  function getYepnope() {
    var y = yepnope;
    y.loader = getLoader();
    return y;
  }

  /* End loader helper functions */

    // Yepnope Function
    yepnope = function(needs) {

    var i,
        need,
        nlen  = needs.length,
        // start the chain as a plain instance
        chain = this.yepnope.loader || getLoader();

    function satisfyPrefixes(url) {
      // make sure we have a url
      if (url) {
        // split all prefixes out
        var parts   = url.split('!'),
            pLen    = parts.length,
            gLen    = globalFilters.length,
            origUrl = parts[pLen-1],
            res     = {
              url      : origUrl,
              // keep this one static for callback variable consistency
              origUrl  : origUrl,
              prefixes : (pLen > 1) ? parts.slice(0, pLen-1) : undef
            },
            mFunc,
            j,
            z;

        // loop through prefixes
        // if there are none, this automatically gets skipped
        for (j = 0; j < pLen-1; j++) {
          mFunc = prefixes[parts[j]];
          if (mFunc) {
            res = mFunc(res);
          }
        }

        // Go through our global filters
        for (z = 0; z < gLen; z++) {
          res = globalFilters[z](res);
        }

        // return the final url
        return res;
      }
      return false;
    }

    function loadScriptOrStyle(input, callback, chain, index, testResult) {
      // run through our set of prefixes
      var resource = satisfyPrefixes(input);

      // if no object is returned or the url is empty/false just exit the load
      if (!resource || !resource.url || resource.bypass) {
        return chain;
      }

      var inc          = resource.url,
          origInc      = resource.origUrl,
          incLen       = inc.length,
          instead      = resource.instead,
          autoCallback = resource.autoCallback,
          forceJS      = resource.forceJS,
          forceCSS     = resource.forceCSS;

      // Determine callback, if any
      if ( callback ) {
        callback = isFunction(callback) ? callback : callback[input] || callback[index] || callback[( input.split('/').pop().split('?')[0])];
      }

      // if someone is overriding all normal functionality
      if (instead) {
        return instead(input, callback, chain, index, testResult);
      }
      // If it's specifically css with the prefix, just inject it (useful for weird extensions and cachebusted urls, etc)
      // Also do this if it ends in a .css extension
/*      else if (incLen > 4 && (forceCSS || (!forceJS && inc.substr(incLen-4) === '.css'))) {
        var styleElem      = doc.createElement('link');

        // add our src to it
        styleElem.href = inc;
        styleElem.rel  = 'stylesheet';
        styleElem.type = 'text/css';

        // inject the file
        docHead.insertBefore(styleElem, docFirst);

        // call the callback
        callback && callback(origInc, testResult, index);
        autoCallback && autoCallback(origInc, testResult, index);
      }*/
      // Otherwise assume that it's a script
      else {

        chain.load(inc, (incLen > 4 && (forceCSS || (!forceJS && inc.substr(incLen-4) === '.css'))) ? cssType : undef);

        // If we have a callback, we'll start the chain over
        if (isFunction(callback) || isFunction(autoCallback)) {
          // Call getJS with our current stack of things
          chain.load(function(){
            // Hijack yepnope and restart index counter
            // NOTE:: This can't get minified... perhaps we need to pass it as a param isntead?
            var innernope = getYepnope();
            // Call our callbacks with this set of data
            // TODO :: get CSS preloading working so we can use innernope there too
            callback && callback(origInc, testResult, index, innernope);
            autoCallback && autoCallback(origInc, testResult, index, innernope);
          });
        }
      }

      return chain;
    }

    function loadFromTestObject(testObject, chain) {
        var testResult = !!(testObject.test),
            group      = (testResult) ? testObject.yep : testObject.nope,
            always     = testObject.load || testObject.both,
            // Callback or wait option should cause getjs to block
            callback   = testObject.callback || (testObject.wait ? noop : undef),
            callbackKey;

        // Reusable function for dealing with the different input types
            // NOTE:: relies on closures to keep 'chain' up to date, a bit confusing, but
            // much smaller than the functional equivalent in this case.
        function handleGroup(needGroup) {
          // If it's a string
          if (isString(needGroup)) {
            // Just load the script of style
            chain = loadScriptOrStyle(needGroup, callback, chain, 0, testResult);
          }
          // If it's an array
          /*else if (isArray(needGroup)) {
            // Grab each thing out of it
            for (l = 0; l < needGroup.length; l++) {
              // Load each thing
              chain = loadScriptOrStyle(needGroup[l], callback, chain, l, testResult);
            }
          }*/
          // See if we have an object. Doesn't matter if it's an array or a key/val hash
          // Note:: order cannot be guaranteed on an key value object with multiple elements
          // since the for-in does not preserve order. Arrays _should_ go in order though.
          else if (isObject(needGroup)) {
            for (callbackKey in needGroup) {
              // Safari 2 does not have hasOwnProperty, but not worth the bytes for a shim
              // patch if needed. Kangax has a nice shim for it. Or just remove the check
              // and promise not to extend the object prototype.
              if (needGroup.hasOwnProperty(callbackKey)) {
                chain = loadScriptOrStyle(needGroup[callbackKey], callback, chain, callbackKey, testResult);
              }
            }
          }
        }

        // figure out what this group should do
        handleGroup(group);

        // Run our loader on the load/both group too
        handleGroup(always);

        // Fire complete callback
        if (testObject.complete) {
          chain = chain.load(testObject.complete);
        }

        return chain;
    }

    // Someone just decides to load a single script or css file as a string
    if (isString(needs)) {
      chain = loadScriptOrStyle(needs, false, chain, 0);
    }
    // Normal case is likely an array of different types of loading options
    else if (isArray(needs)) {
      // go through the list of needs
      for(i=0; i < nlen; i++) {
        need = needs[i];

        // if it's a string, just load it
        if (isString(need)) {
          chain = loadScriptOrStyle(need, false, chain, 0);
        }
        // if it's an array, call our function recursively
        else if (isArray(need)) {
          chain = yepnope(need);
        }
        // if it's an object, use our modernizr logic to win
        else if (isObject(need)) {
          chain = loadFromTestObject(need, chain);
        }
      }
    }
    // Allow a single object to be passed in
    else if (isObject(needs)) {
      chain = loadFromTestObject(needs, chain);
    }

    // allow more loading on this chain
    return chain;
  };

  yepnope.addPrefix = function(prefix, callback) {
    prefixes[prefix] = callback;
  };

  yepnope.addFilter = function(filter) {
    globalFilters.push(filter);
  };

  // Attach loader &
  // Leak it
  window.yepnope = yepnope = getYepnope();

})(this, this.document);
<commit_msg>document.removeChild error commented out for now<commit_after>/**
 * yepnope.js 0.5.0pre
 * by Alex Sexton - AlexSexton@gmail.com
 *
 * Major Contributions by:
 * Ralph Holzmann - @ralphholzmann
 *
 * Tri-Licensed WTFPL, BSD, & MIT
 *
 * Yepnope relies on a script loading technique
 * inspired by A.getJS by Dave Artz
*/
(function(window, doc, undef) {

var docElement            = doc.documentElement,
    docHead               = doc.getElementsByTagName("head")[0] || docElement,
    docBody               = doc.getElementsByTagName("body")[0] || doc.body,
    docFirst              = docHead.firstChild,
    errorTimeout          = 5000,
    toString              = {}.toString,
    jsType                = 'j',
    cssType               = 'c',
    strScript             = "script",
    strFalse              = "false",
    strShift              = "shift",
    strReadyState         = "readyState",
    strOnReadyStateChange = "onreadystatechange",
    strOnLoad             = "onload",
    strObject             = "object",
    strImg                = "img",
    strPreobj             = "[" + strObject + " ",
    noop                  = function(){},
    execStack             = [],
    started               = 0,
    defaultsToAsync       = (doc.createElement(strScript).async === true),
    isGecko               = ("MozAppearance" in docElement.style),
    isGecko18             = isGecko && !! window.Event.prototype.preventBubble,
    // Thanks to @jdalton for this opera detection
    isOpera               = window.opera && toString.call(window.opera) == strPreobj + "Opera]",
    isWebkit              = ("webkitAppearance" in docElement.style),
    strJsElem             = isOpera || isGecko18 ? strImg : ( isGecko ? strObject : strScript ),
    strCssElem            = isWebkit ? strImg : strJsElem,
    isArray               = Array.isArray || function(obj) {
      return toString.call(obj) == strPreobj + "Array]";
    },
    isObject              = function(obj) {
      // Lame object detection, but don't pass it stupid stuff?
      return typeof obj == strObject;
    },
    isString              = function(s) {
      return typeof s == "string";
    },
    isFunction            = function(fn) {
      return toString.call(fn) == strPreobj + 'Function]';
    },
    globalFilters         = [],
    prefixes              = {
      'css': function(resource) {
        resource.forceCSS = true;
        return resource;
      },
      'wait': function(resource) {
        // This just adds an empty callback to force a wait
        resource.autoCallback = noop;
        return resource;
      }
    },
    yepnope;

  /* Loader helper functions */
  function isScriptReady( script ) {
    return ( ! script[strReadyState] || script[strReadyState] == "loaded" || script[strReadyState] == "complete");
  }

  function execWhenReady() {
    var execStackReady = 1,
        len,
        i;

    for (i = -1, len = execStack.length; ++i < len;) {
      if ( execStack[i].src && ! ( execStackReady = isScriptReady( execStack[i] ))) {
        break;
      }
    }
    if ( execStackReady ) {
      executeStack();
    }
  }

  function injectCss(oldObj) {

    // Create stylesheet link
    var link      = doc.createElement('link'),
        done;

    // Add attributes
    link.href = oldObj.src;
    link.rel  = 'stylesheet';
    link.type = 'text/css';

    // Poll for changes in webkit and gecko
    if ( isWebkit || isGecko ) {

      (function poll( link ) {
        var args = arguments;
        setTimeout(function(){
          if ( ! done ) {
            try {
              if ( link.sheet && link.sheet.cssRules && link.sheet.cssRules.length ) {
                done = true;
                execWhenReady();
              } else {
                poll(link);
              }
            } catch (ex) {

              if ( (ex.code == 1000) || (ex.message.match(/security|denied/i)) ) {
                done = true;
                setTimeout(function(){
                  execWhenReady();
                }, 0 );
              } else {
                poll(link);
              }
            }

          }
        }, 13);
      })( link );

    }
    // Onload handler for IE and Opera
    else {

      link.onload = function() {
        if ( ! done ) {
          done = true;
          setTimeout(function(){
            execWhenReady();
          }, 0);
        }
      }

    }

    // 404 Fallback
    setTimeout(function(){
      if ( ! done ) {
        done = true;
        execWhenReady();
      }
    }, errorTimeout);

    // Inject CSS
    docHead.insertBefore(link, docFirst);

  }

  function executeStack(a) {
    var i   = execStack[strShift](),
        src = i ? i.src  : undef,
        t   = i ? i.type : undef;

    started = 1;

    if ( a && src ) {
      i = execStack[strShift]();
      src = undef;
    }

    if ( i ) {
      if ( src && t == jsType ) {
        preloadFile(strScript, src, "", null, docHead);
      }
      else if ( src && t == cssType ) {
        injectCss(i);
      }
      else {
        i();
        started = 0;
        execWhenReady();
      }
    } else {
      started = 0;
    }
  }

  function preloadFile( elem, url, type, splicePoint, docHead ) {

    // Create script element
    var script    = doc.createElement( elem ),
        done      = 0;

    function onload() {

      // If the script is loaded
      if ( ! done && isScriptReady( script ) ) {
        // Set done to prevent this function from being called twice.
        done = 1;

        // If the type is set, that means that we're offloading execution
        if ( ! type || (type && ! started) ) {
          execWhenReady();
        }

        // Handle memory leak in IE
        script[strOnLoad] = script[strOnReadyStateChange] = null;
//        type && docHead.removeChild(script);
      }
    }

    script.src    = script.data = url;
    if ( type ) {
      script.type = type;
    }

    // Attach handlers for all browsers
    script[strOnLoad] = script[strOnReadyStateChange] = onload;

    if ( elem == strImg ) {
      script.onerror = onload;
    } else if ( elem == strScript ) {
      script.onerror = function(){
        executeStack(1);
      };
//      type && docHead.removeChild(script);
    }

    type && execStack.splice( splicePoint, 0, script);

    docHead.appendChild(script);

    if ( isOpera && ! type && elem == strScript ) {
      setTimeout(function(){
        if ( ! done ) {
          done = 1;
          execWhenReady();
        }
      }, errorTimeout);
    }

  }

  function load(resource, type) {

    var a     = arguments,
        app   = this,
        count = a.length,
        elem  = ( type == 'c' ? strCssElem : strJsElem ),
        i,q;

    // We'll do 'j' for js and 'c' for css, yay for unreadable minification tactics
    type = type || jsType;
    if ( isString( resource )) {
      preloadFile(elem, resource, type, app.i++, (elem == strObject ? docBody : docHead) );
    } else {
      execStack.splice(app.i++, 0, resource);
    }

    // OMG is this jQueries? For chaining...
    return app;

  }

  function getLoader() {
    return {
      load: load,
      i : 0
    };
  }

  function getYepnope() {
    var y = yepnope;
    y.loader = getLoader();
    return y;
  }

  /* End loader helper functions */

    // Yepnope Function
    yepnope = function(needs) {

    var i,
        need,
        nlen  = needs.length,
        // start the chain as a plain instance
        chain = this.yepnope.loader || getLoader();

    function satisfyPrefixes(url) {
      // make sure we have a url
      if (url) {
        // split all prefixes out
        var parts   = url.split('!'),
            pLen    = parts.length,
            gLen    = globalFilters.length,
            origUrl = parts[pLen-1],
            res     = {
              url      : origUrl,
              // keep this one static for callback variable consistency
              origUrl  : origUrl,
              prefixes : (pLen > 1) ? parts.slice(0, pLen-1) : undef
            },
            mFunc,
            j,
            z;

        // loop through prefixes
        // if there are none, this automatically gets skipped
        for (j = 0; j < pLen-1; j++) {
          mFunc = prefixes[parts[j]];
          if (mFunc) {
            res = mFunc(res);
          }
        }

        // Go through our global filters
        for (z = 0; z < gLen; z++) {
          res = globalFilters[z](res);
        }

        // return the final url
        return res;
      }
      return false;
    }

    function loadScriptOrStyle(input, callback, chain, index, testResult) {
      // run through our set of prefixes
      var resource = satisfyPrefixes(input);

      // if no object is returned or the url is empty/false just exit the load
      if (!resource || !resource.url || resource.bypass) {
        return chain;
      }

      var inc          = resource.url,
          origInc      = resource.origUrl,
          incLen       = inc.length,
          instead      = resource.instead,
          autoCallback = resource.autoCallback,
          forceJS      = resource.forceJS,
          forceCSS     = resource.forceCSS;

      // Determine callback, if any
      if ( callback ) {
        callback = isFunction(callback) ? callback : callback[input] || callback[index] || callback[( input.split('/').pop().split('?')[0])];
      }

      // if someone is overriding all normal functionality
      if (instead) {
        return instead(input, callback, chain, index, testResult);
      }
      // If it's specifically css with the prefix, just inject it (useful for weird extensions and cachebusted urls, etc)
      // Also do this if it ends in a .css extension
/*      else if (incLen > 4 && (forceCSS || (!forceJS && inc.substr(incLen-4) === '.css'))) {
        var styleElem      = doc.createElement('link');

        // add our src to it
        styleElem.href = inc;
        styleElem.rel  = 'stylesheet';
        styleElem.type = 'text/css';

        // inject the file
        docHead.insertBefore(styleElem, docFirst);

        // call the callback
        callback && callback(origInc, testResult, index);
        autoCallback && autoCallback(origInc, testResult, index);
      }*/
      // Otherwise assume that it's a script
      else {

        chain.load(inc, (incLen > 4 && (forceCSS || (!forceJS && inc.substr(incLen-4) === '.css'))) ? cssType : undef);

        // If we have a callback, we'll start the chain over
        if (isFunction(callback) || isFunction(autoCallback)) {
          // Call getJS with our current stack of things
          chain.load(function(){
            // Hijack yepnope and restart index counter
            // NOTE:: This can't get minified... perhaps we need to pass it as a param isntead?
            var innernope = getYepnope();
            // Call our callbacks with this set of data
            // TODO :: get CSS preloading working so we can use innernope there too
            callback && callback(origInc, testResult, index, innernope);
            autoCallback && autoCallback(origInc, testResult, index, innernope);
          });
        }
      }

      return chain;
    }

    function loadFromTestObject(testObject, chain) {
        var testResult = !!(testObject.test),
            group      = (testResult) ? testObject.yep : testObject.nope,
            always     = testObject.load || testObject.both,
            // Callback or wait option should cause getjs to block
            callback   = testObject.callback || (testObject.wait ? noop : undef),
            callbackKey;

        // Reusable function for dealing with the different input types
            // NOTE:: relies on closures to keep 'chain' up to date, a bit confusing, but
            // much smaller than the functional equivalent in this case.
        function handleGroup(needGroup) {
          // If it's a string
          if (isString(needGroup)) {
            // Just load the script of style
            chain = loadScriptOrStyle(needGroup, callback, chain, 0, testResult);
          }
          // If it's an array
          /*else if (isArray(needGroup)) {
            // Grab each thing out of it
            for (l = 0; l < needGroup.length; l++) {
              // Load each thing
              chain = loadScriptOrStyle(needGroup[l], callback, chain, l, testResult);
            }
          }*/
          // See if we have an object. Doesn't matter if it's an array or a key/val hash
          // Note:: order cannot be guaranteed on an key value object with multiple elements
          // since the for-in does not preserve order. Arrays _should_ go in order though.
          else if (isObject(needGroup)) {
            for (callbackKey in needGroup) {
              // Safari 2 does not have hasOwnProperty, but not worth the bytes for a shim
              // patch if needed. Kangax has a nice shim for it. Or just remove the check
              // and promise not to extend the object prototype.
              if (needGroup.hasOwnProperty(callbackKey)) {
                chain = loadScriptOrStyle(needGroup[callbackKey], callback, chain, callbackKey, testResult);
              }
            }
          }
        }

        // figure out what this group should do
        handleGroup(group);

        // Run our loader on the load/both group too
        handleGroup(always);

        // Fire complete callback
        if (testObject.complete) {
          chain = chain.load(testObject.complete);
        }

        return chain;
    }

    // Someone just decides to load a single script or css file as a string
    if (isString(needs)) {
      chain = loadScriptOrStyle(needs, false, chain, 0);
    }
    // Normal case is likely an array of different types of loading options
    else if (isArray(needs)) {
      // go through the list of needs
      for(i=0; i < nlen; i++) {
        need = needs[i];

        // if it's a string, just load it
        if (isString(need)) {
          chain = loadScriptOrStyle(need, false, chain, 0);
        }
        // if it's an array, call our function recursively
        else if (isArray(need)) {
          chain = yepnope(need);
        }
        // if it's an object, use our modernizr logic to win
        else if (isObject(need)) {
          chain = loadFromTestObject(need, chain);
        }
      }
    }
    // Allow a single object to be passed in
    else if (isObject(needs)) {
      chain = loadFromTestObject(needs, chain);
    }

    // allow more loading on this chain
    return chain;
  };

  yepnope.addPrefix = function(prefix, callback) {
    prefixes[prefix] = callback;
  };

  yepnope.addFilter = function(filter) {
    globalFilters.push(filter);
  };

  // Attach loader &
  // Leak it
  window.yepnope = yepnope = getYepnope();

})(this, this.document);
<|endoftext|>


<commit_before>const fetchVideoInfo = require('youtube-info');
const querystring = require('querystring');
const config = require('./config');
const util = require('./util');
const cmd = require('node-cmd');

function Youtube(url, email, anhao) {
    if (/youtu.be/.test(url)) {
        url = url.split('be/');
        let id = url[1];
        dealWithUrl(id, email, anhao);
    } else {
        url = url.split('?')[1];
        url = querystring.parse(url);
        let id = url.v;
        dealWithUrl(id, email, anhao);
    }
}

function dealWithUrl(videoId, email, anhao) {
    fetchVideoInfo(videoId)
        .then((videoInfo) => {
            cmdDown(videoInfo.title, email, videoId, anhao);
        });
}

function makeid() {
    let text = "";
    const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for (var i = 0; i < 7; i++)
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}

function makeHtml(filename, url) {
    let eStr = ['
'];
    eStr.push('您要的' + filename);
    eStr.push('
');
    eStr.push('' + url + '');
    eStr.push('
');
    return eStr.join('');
}

function cmdDown(filename, email, id, anhao) {
    const url = `https://www.youtube.com/watch?v=${id}`;
    const randomname = makeid();
    let _cmd = `
            cd /home/download
            youtube-dl -f 18 ${url} -o ${randomname}.mp4
            `;
    if (anhao === 'you-get') {
        _cmd = `
            cd /home/download
            you-get ${url} -O ${randomname}
        `;
    }

    cmd.get(
        _cmd,
        function (err, data, stderr) {
            let url = config.baseUrl + randomname + '.mp4';
            const html = makeHtml(filename, url);
            util.sendMail({
                "to": email,
                "subject": "主人，视频已经帮你下载好了。",
                "html": html
            });
        }
    );
}
module.exports = Youtube;
<commit_msg>fix url<commit_after>const fetchVideoInfo = require('youtube-info');
const querystring = require('querystring');
const config = require('./config');
const util = require('./util');
const cmd = require('node-cmd');

function Youtube(url, email, anhao) {
    if (/youtu.be/.test(url)) {
        url = url.split('be/');
        let id = url[1];
        dealWithUrl(id, email, anhao);
    } else {
        url = url.split('?')[1];
        url = querystring.parse(url);
        let id = url.v;
        dealWithUrl(id, email, anhao);
    }
}

function dealWithUrl(videoId, email, anhao) {
    fetchVideoInfo(videoId)
        .then((videoInfo) => {
            cmdDown(videoInfo.title, email, videoId, anhao);
        });
}

function makeid() {
    let text = "";
    const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for (var i = 0; i < 7; i++)
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}

function makeHtml(filename, url) {
    let eStr = ['
'];
    eStr.push('您要的' + filename);
    eStr.push('
');
    eStr.push('' + url + '');
    eStr.push('
');
    return eStr.join('');
}

function cmdDown(filename, email, id, anhao) {
    const url = `https://www.youtube.com/watch?v=${id}`;
    const randomname = makeid();
    let _cmd = `
            cd /home/download
            youtube-dl -f 18 ${url} -o ${randomname}.mp4
            `;
    if (anhao === 'you-get') {
        _cmd = `
            cd /home/download
            you-get ${url} -O ${randomname}
        `;
    }

    cmd.get(
        _cmd,
        function (err, data, stderr) {
            let url = config.baseUrl + randomname + '.mp4';
            url = url.replace(/\.download/, '');
            const html = makeHtml(filename, url);
            util.sendMail({
                "to": email,
                "subject": "主人，视频已经帮你下载好了。",
                "html": html
            });
        }
    );
}
module.exports = Youtube;
<|endoftext|>


<commit_before>/**
 *  Library with useful methods applied to DOM elements (host objects) or built-in JavaScript objects.
 *  Methods naming may look slightly strange but it be better than unexpected name collisions.
 *  Main goal of library at the current stage is not to implement it in a real project, but testing approaches, browser features, generate new ideas.
 *
 *  @author zhibirc
 *  @license
 */
define('zJS', function () {
    'use strict';

    var zJS = {},
		ValueError = Object.create(Error.prototype),
		domElemProto = Element.prototype,
		objProto = Object.prototype,
		arrProto = Array.prototype,
		strProto = String.prototype,
		fnProto = Function.prototype,
        errors = {
            hide: 'Argument incorrect! Allowed 0 and 1 only.',
            remove: 'Argument incorrect! Allowed "chain" and "save" (without flag is equivalent) only.'
        },
		gcd, hcd, gcf, hcf, gcm, factorial, isFib, fibTo, fib, primes, swap;

		zJS.dom = {};
		zJS.util = {};
		zJS.math = {};

	/*|-------------------------|
	  |	Type detection helpers. |
	  |-------------------------|*/

	function isUndef(entity) {
		return typeof entity === 'undefined';
	}

	function isFunc(entity) {
		return typeof entity === 'function';
	}

	function isInt(entity) {
		return typeof entity === 'number' && entity % 1 === 0;
	}

	zJS.dom = {};

    /**
     * Method <_remove_> for DOM elements. Remove particular element and additionally accepts two various behaviours.
     * Flag "save" (or without flag at all) means that removed element returns.
     * Flag "chain" means that the parent element returns to build methods chains.
     *
     * @author zhibirc
     * @param {String} aim - Must be "save", "chain".
     * @returns {Object}
     */
    domElemProto._remove_ = function (aim) {
        var parent;

        if (aim === 'save') {
            return this.parentNode.removeChild(this);
        } else if (aim === 'chain') {
            parent = this.parentNode;
            parent.removeChild(this);
            return parent;
        } else {
            throw new SyntaxError(errors.remove);
        }
    };

    /**
     * Method <_hide_> for DOM elements. Accepts two various behaviours depend on flag. All flags must be numbers.
     * Flag 0 instructs to hide element by change its opacity.
     * Flag 1 instructs to hide element by change its display to "none".
     *
     * @author zhibirc
     * @param {Number} level - Must be 0 or 1.
     * @returns {Object}
     */
    domElemProto._hide_ = function (level) {
        switch (level)  {
            case 0:
                this.style.visibility = 'hidden';
                break;
            case 1:
                this.style.display = 'none';
                break;
            default:
                throw new SyntaxError(errors.hide);
        }
        return this;
    };

    /**
     * Implement <last> method for collections of DOM elements.
     *
     * @author zhibirc
     * @returns {Object}
     */
    NodeList.prototype._last_ = HTMLCollection.prototype._last_ = function () {
        return this[this.length - 1];
    };

    /** Function that fixes a case when TextNode returns instead of HTML element (in FF at least). */
    function getFirstChild(elem) {
        var firstChild = elem.firstChild;

        while (firstChild && firstChild.nodeType !== 1) {
            firstChild = firstChild.nextSibling;
        }

        return firstChild;
    }

    /** Useful for loops. Finally invoke 'console.store.s;'. */
    if (typeof console !== 'undefined' && Object.isExtensible(console)) {
        console.store = console.store || {};
        console.store.basket = console.store.basket || '';
        console.store.__defineSetter__('s', function (msg) {
            return this.basket +=
                /* optionally: (new Date).getTime() + */ msg + ';\n';
        });
        console.store.__defineGetter__('s', function () {
            console.log(this.basket);
        });
    }

    /**
     * Adding outline borders to each element on the page.
     *
     * @author Addi Osmani
     */
    (function (a) {
        [].forEach.call(
            document.querySelectorAll(a),
            function (b) {
                b.style.outline = '1px solid #' + (~~(Math.random() * (1 << 24))).toString(16)
            }
        )
    })('*');

    /**
     * Multiply string N-times - first edition.
     *
     * @author zhibirc
     */
    strProto['*'] = function (multiplier) {
        for (var i = multiplier, str = ''; i--; str += this);

        return str;
    };

    /**
     * Multiply string N-times - second edition.
     *
     * @author zhibirc
     */
    strProto['*'] = function (multiplier) {
        return Array(++multiplier).join(this);
    };

    /**
     * Implement well known and standard behaviour of constants in ES5.
     *
     * @author zhibirc
     */
    var CONST = (function () {
        var constStore = Object.create(null);

        return function (name, value) {
            if (typeof value === 'undefined') {
                return constStore[name];
            } else {
                Object.defineProperty(constStore, name, {
                    value: value
                });
                return 0;
            }
        }
    }());

    /**
     * Complex event installer on DOM elements with old browser support.
     * @author zhibirc
     */
    function addHandler(elem, actions) { // TODO: polyfills of 'some' and 'Object.keys()' required.
        var errors = ['Wrong syntax, event handlers have not been installed!\n' +
					  'Properly syntax: addHandler(element, { event_0: callback_0, ..., event_N: callback_N })'], evt;

		function isValid(n) {
			var keys;

			if (objProto.toString.call(n).slice(8, -1) !== 'Object') {
				return false;
			}

			keys = Object.keys(n);

			if (!+keys || keys.some(function (_) { return typeof n[_] !== 'function'; })) {
				return false;
			}

			return true;
		}

        if (arguments.length !== 2 || ![1, 9, window].some(function (_) { return _ === elem.nodeType || _ === window; }) || !isValid(actions)) {
            throw new Error(errors[0]);
        }

		for (evt in actions) {
			if (objProto.hasOwnProperty.call(actions, evt)) {
				if (elem.addEventListener) {
					elem.addEventListener(evt, actions[evt], false);
				} else if (elem.attachEvent) {
					elem.attachEvent('on' + evt, function () { actions[evt].call(elem); });
				} else {
					elem['on' + evt] = actions[evt];
				}
			}
		}

    }

    /**
     * PHP function number_format in JS.
     *
     * @author zhibirc
     */
    function numberFormat(value, decimal, delim, thousands_sep) {
        'use strict';
        if (typeof value !== 'number' || !isFinite(value)) {
            throw new TypeError('Parameter "value" must be a real Number!');
        }
        var resultValue = value,
            delimiter = delim || '.',
            digitParts = [],
            intPart = '';

        decimal && (resultValue = resultValue.toFixed(decimal));
        resultValue = parseInt(resultValue, 10) + delimiter + String(resultValue).split(/\W+/)[1];
        if (thousands_sep) {
            digitParts = resultValue.split(delimiter);
            intPart = digitParts[0].replace(new RegExp("^(\\d{1,intPart.length - 3})(?=\\d{3})", 'g'), "$1" + thousands_sep);
            resultValue = intPart + delimiter + digitParts[1];
        }
        return resultValue;
    }

    /**
     * Extend jQuery-prototype ($.fn) with method serializeToJSON().
     *
     * @author zhibirc
     */
    $.fn.extend({
        serializeToJSON: function () {
            return '"{' + $(this).serialize()
                    .split('&')
                    .map(function (elem) {
                        return elem.split('=');
                    })
                    .map(function (elem) {
                        return elem.map(function (elem, idx, array) {
                            var __elem;
                            elem = elem.replace(/(%[\da-f]+)/ig, function (group_0) {
                                return decodeURIComponent(group_0);
                            });
                            idx && (__elem = +elem);
                            return isFinite(__elem) ? elem : '"' + elem + '"';
                        });
                    })
                    .map(function (elem) {
                        return elem.join(':')
                    })
                    .join(',') + '}"';
        }
    });

    /**
     * Extend DOM Element prototype to implement functionality of eventListenerList (proposal function which has been removed from the spec draft).
     */
    (function () {
        Element.prototype.eventListenerList = {};
        Element.prototype._addEventListener = Element.prototype.addEventListener;
        Element.prototype.addEventListener = function (a, b, c) {
            this._addEventListener(a, b, c);
            if (!this.eventListenerList[a]) this.eventListenerList[a] = [];
            this.eventListenerList[a].push(b);
        };
    })();

    /**
     * Returns an array of longest words.
     *
     * @author zhibirc
     * @todo Add the functionality to determine the level of 'longest'.
     */
    function getLongestWord(str) {
        'use strict';
        var normalize = str.split(/[^-a-zа-я\d]/i),
            max_len = Math.max.apply(Math, normalize.map(function (elem) {
                return elem.length;
            }));
        return str.match(RegExp('[а-я]{' + max_len + '}', 'ig'));
    }

	/**
	 * Add arbitrary amount of elements (or elements from an array) to the end of current array.
	 */
	arrProto['<<'] = function () {
		var args, elems, i, l;

		if (!arguments.length) {
			return this;
		}

		args = arrProto.slice.call(arguments);

		elems = args.length === 1 && Array.isArray(args[0]) ? args[0] : args;

		for (i = 0, l = elems.length; i < l; i += 1) {
			this.push(elems[i]);
		}

		return this; // Suitable for chaining purposes.
	};

	/**
	 * Beautify with guillemets and dashes.
	 * Select a node in your element inspector and run the following code in console.
	 */
	 (function (el) {
		 el.value = el.value
			// replace left-side double quotes
		   .replace(/(^|\s)"/g, '$1«')
			// replace right-side double quotes
           .replace(/"(\s|[-.,:;?!]|$)/g, '»$1')
		    // replace hyphen with a dash
           .replace(/(\s)-(\s)/g, '$1—$2');
	 }($0 /* or $N*/));

	/*|----------------------------------------------------------------------------------|
	  | MATH functions and algorithms implemented as extensions of Math built-in object. |
	  |----------------------------------------------------------------------------------|*/

	 /** Get Greatest Common Divisor (Highest Common Factor). */
	 gcd = function _(a, b) {
		 return b ? _(b, a % b) : a; // Instead of use arguments.callee
	 }

	 /** Get factorial with Tail call optimization. */
	 factorial = function (n) {
		 if (!isInt(n)) {
			 throw new ValueError('factorial() only accepts integral values');
		 }

		 function _(n, acc) {
			 return n < 2 ? acc : _(n - 1, n * acc);
		 }

		 return _(n, 1);
	 };

	 /** Detect if N is in Fibonacci sequence. */
	 isFib = function (n) {
		 var _isInt = isInt,
			  sqrt = Math.sqrt,
			  mul = 5 * n * n;

		 return _isInt(n) ? _isInt(sqrt(mul - 4)) || _isInt(sqrt(mul + 4)) : false;
	 };

	/** Get Fibonacci sequence as an array. */
	fibTo = function (n) {
		var ret = [], a = 0, b = 1, tmp;

		if (!isInt(n)) {
			return new ValueError('fibTo() only accepts integral values');
		}

		while (n--) {
			ret.push(a);
			tmp = a;
			a = b;
			b += tmp;
		}

		return ret;
	};

	/** Get N-th Fibonacci number. */
	fib = function (n) {
		if (!isInt(n)) {
			return new ValueError('fib() only accepts integral values');
		}

		let sqrt = Math.sqrt;
		let _fpow = fpow;

		const SQRT_5 = sqrt(5);
		const P_PHI = (1 + SQRT_5) / 2;
		const M_PHI = (1 - SQRT_5) / 2;

		return ~~((_fpow(P_PHI, n) - _fpow(M_PHI, n)) / SQRT_5 + .5);
	};

	/** Exponentiating by squaring algorithm. */
	fpow = function (x, n) {
		if (!n) {
			return 1;
		}

		let i = 1;

		while (n) {
			if (!(n & 1)) {
				n >>= 1;
				x *= x;
			} else {
				n--;
				i *= x;
			}
		}

		return i;
	};

	 /** Range */
	 function range(...args) {
		 let argsLen = args.length,
			 start, stop, step;

		 if (!argsLen) {
			 throw new Error('expected at least 1 argument, got 0');
		 }

		 if (argsLen > 3) {
			 throw new Error('expected at most 3 arguments, got ' + argsLen);
		 }

		 if (args.some(arg => !isInt(arg))) {
			 throw new Error('arguments must be all integers');
		 }

		 switch (argsLen) {
		 case 1:
			start = 0, stop = args[0], step = 1;
			break;
		 case 2:
			start = args[0], stop = args[1], step = 1;
			if (start >= stop) return [];
			break;
		 case 3:
			start = args[0], stop = args[1], step = args[2];
			if (!step) throw new Error('step argument must not be zero');
			if (Math.abs(start) + Math.abs(step) < Math.abs(start)) return [];
			if (start >= stop && !~Math.sign(step)) return [];
			if (start + step >= stop) return [start];
		 }

		 return Array.apply(null, Array(Math.ceil((stop - start) / step))).map((_, idx) => start + step * idx);
	 }

	/** Get prime numbers in range. */
	primes = function (a, b) {
		let lst = range(a, b + 1),
			 primes = [],
			 n = Math.abs(b - a),
			 i = 0;
		while (i <= n) {

		}

	};

	swap = function (a, b) {
		a ^= b;
		b ^= a;
		a ^= b;
	};

	 /** Public API */
	 zJS.math = {
		gcd: gcd, // get Greatest Common Divisor
		hcd: gcd, // alias to gcd
		gcf: gcd, // alias to gcd
		hcf: gcd, // alias to gcd
		gcm: gcd, // alias to gcd
		factorial: factorial, // get factorial
		isFib: isFib, // is particular N is Fibonacci number
		fibTo: fibTo, // get N Fibonacci numbers
		fib: fib, // get N-th Fibonacci number
		fpow: fpow, // fast squaring algorithm
		swap: swap // swap variables
	 };

	 /**
	  *	@exports
	  */
	 return zJS;
});<commit_msg>[Add]::zJS_AMD.js - Added origins() array method.<commit_after>/**
 *  Library with useful methods applied to DOM elements (host objects) or built-in JavaScript objects.
 *  Methods naming may look slightly strange but it be better than unexpected name collisions.
 *  Main goal of library at the current stage is not to implement it in a real project, but testing approaches, browser features, generate new ideas.
 *
 *  @author zhibirc
 *  @license
 */
define('zJS', function () {
    'use strict';

    var zJS = {},
		ValueError = Object.create(Error.prototype),
		domElemProto = Element.prototype,
		objProto = Object.prototype,
		arrProto = Array.prototype,
		strProto = String.prototype,
		fnProto = Function.prototype,
        errors = {
            hide: 'Argument incorrect! Allowed 0 and 1 only.',
            remove: 'Argument incorrect! Allowed "chain" and "save" (without flag is equivalent) only.'
        },
		gcd, hcd, gcf, hcf, gcm, factorial, isFib, fibTo, fib, primes, swap;

		zJS.dom = {};
		zJS.util = {};
		zJS.math = {};

	/*|-------------------------|
	  |	Type detection helpers. |
	  |-------------------------|*/

	function isUndef(entity) {
		return typeof entity === 'undefined';
	}

	function isFunc(entity) {
		return typeof entity === 'function';
	}

	function isInt(entity) {
		return typeof entity === 'number' && entity % 1 === 0;
	}

	zJS.dom = {};

    /**
     * Method <_remove_> for DOM elements. Remove particular element and additionally accepts two various behaviours.
     * Flag "save" (or without flag at all) means that removed element returns.
     * Flag "chain" means that the parent element returns to build methods chains.
     *
     * @author zhibirc
     * @param {String} aim - Must be "save", "chain".
     * @returns {Object}
     */
    domElemProto._remove_ = function (aim) {
        var parent;

        if (aim === 'save') {
            return this.parentNode.removeChild(this);
        } else if (aim === 'chain') {
            parent = this.parentNode;
            parent.removeChild(this);
            return parent;
        } else {
            throw new SyntaxError(errors.remove);
        }
    };

    /**
     * Method <_hide_> for DOM elements. Accepts two various behaviours depend on flag. All flags must be numbers.
     * Flag 0 instructs to hide element by change its opacity.
     * Flag 1 instructs to hide element by change its display to "none".
     *
     * @author zhibirc
     * @param {Number} level - Must be 0 or 1.
     * @returns {Object}
     */
    domElemProto._hide_ = function (level) {
        switch (level)  {
            case 0:
                this.style.visibility = 'hidden';
                break;
            case 1:
                this.style.display = 'none';
                break;
            default:
                throw new SyntaxError(errors.hide);
        }
        return this;
    };

    /**
     * Implement <last> method for collections of DOM elements.
     *
     * @author zhibirc
     * @returns {Object}
     */
    NodeList.prototype._last_ = HTMLCollection.prototype._last_ = function () {
        return this[this.length - 1];
    };

    /** Function that fixes a case when TextNode returns instead of HTML element (in FF at least). */
    function getFirstChild(elem) {
        var firstChild = elem.firstChild;

        while (firstChild && firstChild.nodeType !== 1) {
            firstChild = firstChild.nextSibling;
        }

        return firstChild;
    }

    /** Useful for loops. Finally invoke 'console.store.s;'. */
    if (typeof console !== 'undefined' && Object.isExtensible(console)) {
        console.store = console.store || {};
        console.store.basket = console.store.basket || '';
        console.store.__defineSetter__('s', function (msg) {
            return this.basket +=
                /* optionally: (new Date).getTime() + */ msg + ';\n';
        });
        console.store.__defineGetter__('s', function () {
            console.log(this.basket);
        });
    }

    /**
     * Adding outline borders to each element on the page.
     *
     * @author Addi Osmani
     */
    (function (a) {
        [].forEach.call(
            document.querySelectorAll(a),
            function (b) {
                b.style.outline = '1px solid #' + (~~(Math.random() * (1 << 24))).toString(16)
            }
        )
    })('*');

    /**
     * Multiply string N-times - first edition.
     *
     * @author zhibirc
     */
    strProto['*'] = function (multiplier) {
        for (var i = multiplier, str = ''; i--; str += this);

        return str;
    };

    /**
     * Multiply string N-times - second edition.
     *
     * @author zhibirc
     */
    strProto['*'] = function (multiplier) {
        return Array(++multiplier).join(this);
    };

    /**
     * Implement well known and standard behaviour of constants in ES5.
     *
     * @author zhibirc
     */
    var CONST = (function () {
        var constStore = Object.create(null);

        return function (name, value) {
            if (typeof value === 'undefined') {
                return constStore[name];
            } else {
                Object.defineProperty(constStore, name, {
                    value: value
                });
                return 0;
            }
        }
    }());

    /**
     * Complex event installer on DOM elements with old browser support.
     * @author zhibirc
     */
    function addHandler(elem, actions) { // TODO: polyfills of 'some' and 'Object.keys()' required.
        var errors = ['Wrong syntax, event handlers have not been installed!\n' +
					  'Properly syntax: addHandler(element, { event_0: callback_0, ..., event_N: callback_N })'], evt;

		function isValid(n) {
			var keys;

			if (objProto.toString.call(n).slice(8, -1) !== 'Object') {
				return false;
			}

			keys = Object.keys(n);

			if (!+keys || keys.some(function (_) { return typeof n[_] !== 'function'; })) {
				return false;
			}

			return true;
		}

        if (arguments.length !== 2 || ![1, 9, window].some(function (_) { return _ === elem.nodeType || _ === window; }) || !isValid(actions)) {
            throw new Error(errors[0]);
        }

		for (evt in actions) {
			if (objProto.hasOwnProperty.call(actions, evt)) {
				if (elem.addEventListener) {
					elem.addEventListener(evt, actions[evt], false);
				} else if (elem.attachEvent) {
					elem.attachEvent('on' + evt, function () { actions[evt].call(elem); });
				} else {
					elem['on' + evt] = actions[evt];
				}
			}
		}

    }

    /**
     * PHP function number_format in JS.
     *
     * @author zhibirc
     */
    function numberFormat(value, decimal, delim, thousands_sep) {
        'use strict';
        if (typeof value !== 'number' || !isFinite(value)) {
            throw new TypeError('Parameter "value" must be a real Number!');
        }
        var resultValue = value,
            delimiter = delim || '.',
            digitParts = [],
            intPart = '';

        decimal && (resultValue = resultValue.toFixed(decimal));
        resultValue = parseInt(resultValue, 10) + delimiter + String(resultValue).split(/\W+/)[1];
        if (thousands_sep) {
            digitParts = resultValue.split(delimiter);
            intPart = digitParts[0].replace(new RegExp("^(\\d{1,intPart.length - 3})(?=\\d{3})", 'g'), "$1" + thousands_sep);
            resultValue = intPart + delimiter + digitParts[1];
        }
        return resultValue;
    }

    /**
     * Extend jQuery-prototype ($.fn) with method serializeToJSON().
     *
     * @author zhibirc
     */
    $.fn.extend({
        serializeToJSON: function () {
            return '"{' + $(this).serialize()
                    .split('&')
                    .map(function (elem) {
                        return elem.split('=');
                    })
                    .map(function (elem) {
                        return elem.map(function (elem, idx, array) {
                            var __elem;
                            elem = elem.replace(/(%[\da-f]+)/ig, function (group_0) {
                                return decodeURIComponent(group_0);
                            });
                            idx && (__elem = +elem);
                            return isFinite(__elem) ? elem : '"' + elem + '"';
                        });
                    })
                    .map(function (elem) {
                        return elem.join(':')
                    })
                    .join(',') + '}"';
        }
    });

    /**
     * Extend DOM Element prototype to implement functionality of eventListenerList (proposal function which has been removed from the spec draft).
     */
    (function () {
        Element.prototype.eventListenerList = {};
        Element.prototype._addEventListener = Element.prototype.addEventListener;
        Element.prototype.addEventListener = function (a, b, c) {
            this._addEventListener(a, b, c);
            if (!this.eventListenerList[a]) this.eventListenerList[a] = [];
            this.eventListenerList[a].push(b);
        };
    })();

    /**
     * Returns an array of longest words.
     *
     * @author zhibirc
     * @todo Add the functionality to determine the level of 'longest'.
     */
    function getLongestWord(str) {
        'use strict';
        var normalize = str.split(/[^-a-zа-я\d]/i),
            max_len = Math.max.apply(Math, normalize.map(function (elem) {
                return elem.length;
            }));
        return str.match(RegExp('[а-я]{' + max_len + '}', 'ig'));
    }

	/**
	 * Add arbitrary amount of elements (or elements from an array) to the end of current array.
	 */
	arrProto['<<'] = function () {
		var args, elems, i, l;

		if (!arguments.length) {
			return this;
		}

		args = arrProto.slice.call(arguments);

		elems = args.length === 1 && Array.isArray(args[0]) ? args[0] : args;

		for (i = 0, l = elems.length; i < l; i += 1) {
			this.push(elems[i]);
		}

		return this; // Suitable for chaining purposes.
	};

	/**
	 * Beautify with guillemets and dashes.
	 * Select a node in your element inspector and run the following code in console.
	 */
	 (function (el) {
		 el.value = el.value
			// replace left-side double quotes
		   .replace(/(^|\s)"/g, '$1«')
			// replace right-side double quotes
           .replace(/"(\s|[-.,:;?!]|$)/g, '»$1')
		    // replace hyphen with a dash
           .replace(/(\s)-(\s)/g, '$1—$2');
	 }($0 /* or $N*/));

    /** Find original values in an array. */
	origins = function (arr) {
		return Object.keys(arr.reduce(function(r, v) { return r[v] = 1, r; }, {}));
	};

	/*|----------------------------------------------------------------------------------|
	  | MATH functions and algorithms implemented as extensions of Math built-in object. |
	  |----------------------------------------------------------------------------------|*/

	 /** Get Greatest Common Divisor (Highest Common Factor). */
	 gcd = function _(a, b) {
		 return b ? _(b, a % b) : a; // Instead of use arguments.callee
	 }

	 /** Get factorial with Tail call optimization. */
	 factorial = function (n) {
		 if (!isInt(n)) {
			 throw new ValueError('factorial() only accepts integral values');
		 }

		 function _(n, acc) {
			 return n < 2 ? acc : _(n - 1, n * acc);
		 }

		 return _(n, 1);
	 };

	 /** Detect if N is in Fibonacci sequence. */
	 isFib = function (n) {
		 var _isInt = isInt,
			  sqrt = Math.sqrt,
			  mul = 5 * n * n;

		 return _isInt(n) ? _isInt(sqrt(mul - 4)) || _isInt(sqrt(mul + 4)) : false;
	 };

	/** Get Fibonacci sequence as an array. */
	fibTo = function (n) {
		var ret = [], a = 0, b = 1, tmp;

		if (!isInt(n)) {
			return new ValueError('fibTo() only accepts integral values');
		}

		while (n--) {
			ret.push(a);
			tmp = a;
			a = b;
			b += tmp;
		}

		return ret;
	};

	/** Get N-th Fibonacci number. */
	fib = function (n) {
		if (!isInt(n)) {
			return new ValueError('fib() only accepts integral values');
		}

		let sqrt = Math.sqrt;
		let _fpow = fpow;

		const SQRT_5 = sqrt(5);
		const P_PHI = (1 + SQRT_5) / 2;
		const M_PHI = (1 - SQRT_5) / 2;

		return ~~((_fpow(P_PHI, n) - _fpow(M_PHI, n)) / SQRT_5 + .5);
	};

	/** Exponentiating by squaring algorithm. */
	fpow = function (x, n) {
		if (!n) {
			return 1;
		}

		let i = 1;

		while (n) {
			if (!(n & 1)) {
				n >>= 1;
				x *= x;
			} else {
				n--;
				i *= x;
			}
		}

		return i;
	};

	 /** Range */
	 function range(...args) {
		 let argsLen = args.length,
			 start, stop, step;

		 if (!argsLen) {
			 throw new Error('expected at least 1 argument, got 0');
		 }

		 if (argsLen > 3) {
			 throw new Error('expected at most 3 arguments, got ' + argsLen);
		 }

		 if (args.some(arg => !isInt(arg))) {
			 throw new Error('arguments must be all integers');
		 }

		 switch (argsLen) {
		 case 1:
			start = 0, stop = args[0], step = 1;
			break;
		 case 2:
			start = args[0], stop = args[1], step = 1;
			if (start >= stop) return [];
			break;
		 case 3:
			start = args[0], stop = args[1], step = args[2];
			if (!step) throw new Error('step argument must not be zero');
			if (Math.abs(start) + Math.abs(step) < Math.abs(start)) return [];
			if (start >= stop && !~Math.sign(step)) return [];
			if (start + step >= stop) return [start];
		 }

		 return Array.apply(null, Array(Math.ceil((stop - start) / step))).map((_, idx) => start + step * idx);
	 }

	/** Get prime numbers in range. */
	primes = function (a, b) {
		let lst = range(a, b + 1),
			 primes = [],
			 n = Math.abs(b - a),
			 i = 0;
		while (i <= n) {

		}

	};

	swap = function (a, b) {
		a ^= b;
		b ^= a;
		a ^= b;
	};

	 /** Public API */
	 zJS.math = {
		gcd: gcd, // get Greatest Common Divisor
		hcd: gcd, // alias to gcd
		gcf: gcd, // alias to gcd
		hcf: gcd, // alias to gcd
		gcm: gcd, // alias to gcd
		factorial: factorial, // get factorial
		isFib: isFib, // is particular N is Fibonacci number
		fibTo: fibTo, // get N Fibonacci numbers
		fib: fib, // get N-th Fibonacci number
		fpow: fpow, // fast squaring algorithm
		swap: swap // swap variables
	 };

	 /**
	  *	@exports
	  */
	 return zJS;
});<|endoftext|>


<commit_before>var zad1 = function(){

};

var zad2 = function(){

}

var zad4=function(){

}

var zad3 = function(){

}

var zad5 = function() {

}

// Stwórz tablicę złożoną z 10 elementów i wyświetl je w konsoli po kolei
var show = function(){
    var array=[1,2,3,4,5,6,7,8,9,10]
    for (var i=0; i<array.length; i++){
      console.log(array[i])
    };
}
// Wyświetl w konsoli liczby parzyste od 0 do 100
var even = function () {
    for (var i=0; i<=100; i+=2){
      console.log(i)
    }
}
// Wyświetl w konsoli liczby od 100 do 1
var hundred = function(){
    for (var i=100; i>0; i--){
        console.log(i)
    }
}
// * Stwórz tablicę, a następnie przy pomocą pętli stwórz tablicę zawierającą te same elementy w odwrotnej kolejności. Wyświetl je w alercie.
var reverseArray = function(){
    var array=[1,2,3,4,5,6,7,8,9,10]
    var reverseArray=[]
    for (var i=array.length-1; i>=0; i--){
        console.log(i);
        reverseArray.push(array[i])
    }
    alert(reverseArray)
}
// ** Za pomocą pętli policz silnię z dowolnej, podanej liczby
var factorial = function(number){
    var result = 1;
    for (var i=1; i<=number; i++){
        result = result*i
    }
    console.log(result)
}

// Stwórz obiekt i wyświetl na stronie wszystkie jego elementy w formacie: "(klucz) wynosi (wartość)". Funkcji nie wywołuj w konsoli
var showObject = function(){

}

// stwórz tablicę zawierającą 3 obiekty. Wyświetl na stronie wszystkie elementy wszystkich obiektów, zaznaczając którego obiektu elementy są wyświetlone. Funkcji nie wywołuj w konsoli
var showObjectArray = function(){

}
// Stwórz tablicę złożoną z 10 kolejnych wielokrotności liczby 5 za pomocą pętli while
var multipleOf5 = function(){

}
// Wyświetl w konsoli liczby parzyste od 0 do 100 za pomocą pętli while
var oddNumbers = function(){

}
// * Pobieraj od użytkownika liczby tak długo, aż wpiszę liczbę większą niż 50. Wtedy wyświetl tablicę złożoną z wpisanych dotychczas liczb na stronie
var arrayLessThen50 = function(){

}
// Wypisz na stronie elementy poniższej tablicy do elementu "stop" włącznie.
// var myArray = ['uczę', 'się', 'programować', 'stop', 'lubię', 'to']
var stopArray = function(){

}
// Pobieraj od użytkownika liczby tak długo, aż wpiszę liczbę większą niż 50. Wtedy wyświetl tablicę złożoną z wpisanych dotychczas liczb na stronie z ostatnią włącznie
var including50 = function(){

}
// Poproś użytkownika o wpisanie imienia i godziny. W alercie wyświetl użytkownikowi powitanie wraz z imieniem. Jeśli godzina wpisana przez użytkownika jest od 6 do 12, powitanie powinno brzmieć "dzień dobry", od 12 do 18 "Jak mija dzień?", od 18 do północy "Dobry wieczór", a od północy do 6 "idź spać!!!"
var nameAndHour = function(){

}

<commit_msg>finished!!<commit_after>// Stwórz tablicę złożoną z 10 elementów i wyświetl je w konsoli po kolei
var show = function(){
    var array=[1,2,3,4,5,6,7,8,9,10]
    for (var i=0; i<array.length; i++){
      console.log(array[i])
    };
}
// Wyświetl w konsoli liczby parzyste od 0 do 100
var even = function () {
    for (var i=0; i<=100; i+=2){
      console.log(i)
    }
}
// Wyświetl w konsoli liczby od 100 do 1
var hundred = function(){
    for (var i=100; i>0; i--){
        console.log(i)
    }
}
// * Stwórz tablicę, a następnie przy pomocą pętli stwórz tablicę zawierającą te same elementy w odwrotnej kolejności. Wyświetl je w alercie.
var reverseArray = function(){
    var array=[1,2,3,4,5,6,7,8,9,10]
    var reverseArray=[]
    for (var i=array.length-1; i>=0; i--){
        console.log(i);
        reverseArray.push(array[i])
    }
    alert(reverseArray)
}
// ** Za pomocą pętli policz silnię z dowolnej, podanej liczby
var factorial = function(number){
    var result = 1;
    for (var i=1; i<=number; i++){
        result = result*i
    }
    console.log(result)
}

// Stwórz obiekt i wyświetl na stronie wszystkie jego elementy w formacie: "(klucz) wynosi (wartość)". Funkcji nie wywołuj w konsoli
var showObject = function(){

}

// stwórz tablicę zawierającą 3 obiekty. Wyświetl na stronie wszystkie elementy wszystkich obiektów, zaznaczając którego obiektu elementy są wyświetlone. Funkcji nie wywołuj w konsoli
var showObjectArray = function(){

}
// Stwórz tablicę złożoną z 10 kolejnych wielokrotności liczby 5 za pomocą pętli while
var multipleOf5 = function(){

}
// Wyświetl w konsoli liczby parzyste od 0 do 100 za pomocą pętli while
var oddNumbers = function(){

}
// * Pobieraj od użytkownika liczby tak długo, aż wpiszę liczbę większą niż 50. Wtedy wyświetl tablicę złożoną z wpisanych dotychczas liczb na stronie
var arrayLessThen50 = function(){

}
// Wypisz na stronie elementy poniższej tablicy do elementu "stop" włącznie.
// var myArray = ['uczę', 'się', 'programować', 'stop', 'lubię', 'to']
var stopArray = function(){

}
// Pobieraj od użytkownika liczby tak długo, aż wpiszę liczbę większą niż 50. Wtedy wyświetl tablicę złożoną z wpisanych dotychczas liczb na stronie z ostatnią włącznie
var including50 = function(){

}
// Poproś użytkownika o wpisanie imienia i godziny. W alercie wyświetl użytkownikowi powitanie wraz z imieniem. Jeśli godzina wpisana przez użytkownika jest od 6 do 12, powitanie powinno brzmieć "dzień dobry", od 12 do 18 "Jak mija dzień?", od 18 do północy "Dobry wieczór", a od północy do 6 "idź spać!!!"
var nameAndHour = function(){

}

<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { DragDropContext } from "react-dnd";
import HTML5Backend from "react-dnd-html5-backend";
import './BoardSet.css';

import { Board, Hand, Piece } from 'kifu-for-js';

Piece.DecoratedComponent.prototype.getPieceImage = (kind, color) => {
  return `/images/shogi-pieces/${!kind ? "blank.gif" : color + kind + ".svg"}`;
};

import { kifuTree, LOAD_JKF, MOVE_PIECE, GOTO_PATH, CHANGE_COMMENTS, MOVE_UP_FORK, MOVE_DOWN_FORK, REMOVE_FORK } from '../actions';
import KifuTree from './tree/KifuTree';

class BoardSet extends Component {
  constructor() {
    super();
    this.imageDirectoryPath = "./images";
    this.state = kifuTree(undefined, {});
  }
  componentDidMount() {
    fetch('/jkf').then(response => {
      response.json().then(jkf => {
        console.log(jkf);
        this.dispatch({ type: LOAD_JKF, jkf: jkf });
      });
    });
  }
  save() {
    const body = JSON.stringify(this.state.player.kifu, null, '  ');
    fetch('/jkf', { method: 'PUT', body: body }).then(() => {
      alert('Saved');
    });
  }
  onInputMove(move) {
    this.dispatch({ type: MOVE_PIECE, move: move });
  }
  onChangeComments(value) {
    this.dispatch({ type: CHANGE_COMMENTS, value: value });
  }
  loadJKF(jkf) {
    this.dispatch({ type: LOAD_JKF, jkf: jkf });
  }
  gotoPath(path) {
    this.dispatch({ type: GOTO_PATH, path: path });
  }
  moveUpFork(path) {
    this.dispatch({ type: MOVE_UP_FORK, path: path });
  }
  moveDownFork(path) {
    this.dispatch({ type: MOVE_DOWN_FORK, path: path });
  }
  removeFork(path) {
    this.dispatch({ type: REMOVE_FORK, path: path });
  }
  dispatch(action) {
    this.setState(prevState => kifuTree(prevState, action));
  }
  render() {
    const player = this.state.player;
    const reversed = this.state.reversed;
    const playerState = player.getState();
    const players = [
      player.kifu.header["先手"] || player.kifu.header["下手"] || "先手",
      player.kifu.header["後手"] || player.kifu.header["上手"] || "後手",
    ];

    return (

            <Hand color={reversed ? 0 : 1} data={playerState.hands[reversed ? 0 : 1]} playerName={players[reversed ? 0 : 1]} ImageDirectoryPath={this.imageDirectoryPath} onInputMove={e => { this.onInputMove(e) }} reversed={reversed} />

            <Board board={playerState.board}
              lastMove={player.getMove()}
              ImageDirectoryPath={this.imageDirectoryPath}
              onInputMove={e => { this.onInputMove(e) }}
              reversed={reversed} />

            <Hand color={reversed ? 1 : 0} data={playerState.hands[reversed ? 1 : 0]} playerName={players[reversed ? 1 : 0]} ImageDirectoryPath={this.imageDirectoryPath} onInputMove={e => { this.onInputMove(e) }} reversed={reversed} />

            <textarea rows="10" className="comment" placeholder="ここに現在の手についてコメントを書けます。" onChange={e => { this.onChangeComments(e.target.value); }} value={this.state.player.getComments().join("\n")}></textarea>

          <KifuTree kifuTree={this.state.kifuTree} currentPath={this.state.currentPath} onClick={e => {
            const path = e.target.dataset.path || e.target.parentNode.dataset.path || e.target.parentNode.parentNode.dataset.path;
            if (!path) {
              return; // do nothing
            }
            if (e.target.classList.contains('readable-kifu')) {
              this.gotoPath(path);
            } else if (e.target.classList.contains('up')) {
              this.moveUpFork(path);
            } else if (e.target.classList.contains('down')) {
              this.moveDownFork(path);
            } else if (e.target.classList.contains('remove')) {
              this.removeFork(path);
            }
          }} />

    )
  }
}

export default DragDropContext(HTML5Backend)(BoardSet);
<commit_msg>Fix unintentional use of dispatch<commit_after>import React, { Component } from 'react';
import { DragDropContext } from "react-dnd";
import HTML5Backend from "react-dnd-html5-backend";
import './BoardSet.css';

import { Board, Hand, Piece } from 'kifu-for-js';

Piece.DecoratedComponent.prototype.getPieceImage = (kind, color) => {
  return `/images/shogi-pieces/${!kind ? "blank.gif" : color + kind + ".svg"}`;
};

import { kifuTree, LOAD_JKF, MOVE_PIECE, GOTO_PATH, CHANGE_COMMENTS, MOVE_UP_FORK, MOVE_DOWN_FORK, REMOVE_FORK } from '../actions';
import KifuTree from './tree/KifuTree';

class BoardSet extends Component {
  constructor() {
    super();
    this.imageDirectoryPath = "./images";
    this.state = kifuTree(undefined, {});
  }
  componentDidMount() {
    fetch('/jkf').then(response => {
      response.json().then(jkf => {
        console.log(jkf);
        this.loadJKF(jkf);
      });
    });
  }
  save() {
    const body = JSON.stringify(this.state.player.kifu, null, '  ');
    fetch('/jkf', { method: 'PUT', body: body }).then(() => {
      alert('Saved');
    });
  }
  onInputMove(move) {
    this.dispatch({ type: MOVE_PIECE, move: move });
  }
  onChangeComments(value) {
    this.dispatch({ type: CHANGE_COMMENTS, value: value });
  }
  loadJKF(jkf) {
    this.dispatch({ type: LOAD_JKF, jkf: jkf });
  }
  gotoPath(path) {
    this.dispatch({ type: GOTO_PATH, path: path });
  }
  moveUpFork(path) {
    this.dispatch({ type: MOVE_UP_FORK, path: path });
  }
  moveDownFork(path) {
    this.dispatch({ type: MOVE_DOWN_FORK, path: path });
  }
  removeFork(path) {
    this.dispatch({ type: REMOVE_FORK, path: path });
  }
  dispatch(action) {
    this.setState(prevState => kifuTree(prevState, action));
  }
  render() {
    const player = this.state.player;
    const reversed = this.state.reversed;
    const playerState = player.getState();
    const players = [
      player.kifu.header["先手"] || player.kifu.header["下手"] || "先手",
      player.kifu.header["後手"] || player.kifu.header["上手"] || "後手",
    ];

    return (

            <Hand color={reversed ? 0 : 1} data={playerState.hands[reversed ? 0 : 1]} playerName={players[reversed ? 0 : 1]} ImageDirectoryPath={this.imageDirectoryPath} onInputMove={e => { this.onInputMove(e) }} reversed={reversed} />

            <Board board={playerState.board}
              lastMove={player.getMove()}
              ImageDirectoryPath={this.imageDirectoryPath}
              onInputMove={e => { this.onInputMove(e) }}
              reversed={reversed} />

            <Hand color={reversed ? 1 : 0} data={playerState.hands[reversed ? 1 : 0]} playerName={players[reversed ? 1 : 0]} ImageDirectoryPath={this.imageDirectoryPath} onInputMove={e => { this.onInputMove(e) }} reversed={reversed} />

            <textarea rows="10" className="comment" placeholder="ここに現在の手についてコメントを書けます。" onChange={e => { this.onChangeComments(e.target.value); }} value={this.state.player.getComments().join("\n")}></textarea>

          <KifuTree kifuTree={this.state.kifuTree} currentPath={this.state.currentPath} onClick={e => {
            const path = e.target.dataset.path || e.target.parentNode.dataset.path || e.target.parentNode.parentNode.dataset.path;
            if (!path) {
              return; // do nothing
            }
            if (e.target.classList.contains('readable-kifu')) {
              this.gotoPath(path);
            } else if (e.target.classList.contains('up')) {
              this.moveUpFork(path);
            } else if (e.target.classList.contains('down')) {
              this.moveDownFork(path);
            } else if (e.target.classList.contains('remove')) {
              this.removeFork(path);
            }
          }} />

    )
  }
}

export default DragDropContext(HTML5Backend)(BoardSet);
<|endoftext|>


<commit_before>import _ from 'underscore';
import I18n from 'i18n-js';
import h from '../h';

const I18nScope = _.partial(h.i18nScope, 'projects.successful_onboard');

const parseAccountData = (account, transfer) => ({
    transfer_limit_date: h.momentify(account.transfer_limit_date),
    total_amount: h.formatNumber(transfer.total_amount, 2),
    bank_name: account.bank_name,
    agency: `${account.agency}${account.agency_digit ? `-${account.agency_digit}` : ''}`,
    account: `${account.account}${account.account_digit ? `-${account.account_digit}` : ''}`,
    user_email: account.user_email
});

const insightVM = {
    content(state, data) {
        const translations = I18n.translations[
            I18n.currentLocale()
        ].projects.successful_onboard[state],
            translationContext = (state === 'finished' ? {} : parseAccountData(
                  _.first(data.account()),
                  _.first(data.transfer())
              ));
        let contentObj = {};

        _.map(translations, (translation, translationKey) => {
            contentObj = _.extend({}, contentObj, {
                [translationKey]: I18n.t(`${state}.${translationKey}`, I18nScope(translationContext))
            });
        });
        return contentObj;
    }
};

export default insightVM;
<commit_msg>New link mapping on copy<commit_after>import _ from 'underscore';
import I18n from 'i18n-js';
import h from '../h';

const I18nScope = _.partial(h.i18nScope, 'projects.successful_onboard');

const parseAccountData = (account, transfer) => ({
    transfer_limit_date: h.momentify(account.transfer_limit_date),
    total_amount: h.formatNumber(transfer.total_amount, 2),
    bank_name: account.bank_name,
    agency: `${account.agency}${account.agency_digit ? `-${account.agency_digit}` : ''}`,
    account: `${account.account}${account.account_digit ? `-${account.account_digit}` : ''}`,
    user_email: account.user_email
});

const insightVM = {
    content(state, data) {
        const translations = I18n.translations[
            I18n.currentLocale()
        ].projects.successful_onboard[state],
              translationContext = (state === 'finished' ? {
                  link_news: `/projects/${_.first(data.account()).project_id}/posts`
              } : parseAccountData(
                  _.first(data.account()),
                  _.first(data.transfer())
              ));
        let contentObj = {};

        _.map(translations, (translation, translationKey) => {
            contentObj = _.extend({}, contentObj, {
                [translationKey]: I18n.t(`${state}.${translationKey}`, I18nScope(translationContext))
            });
        });
        return contentObj;
    }
};

export default insightVM;
<|endoftext|>


<commit_before>const env = process.env.NODE_ENV || 'production';
const targets = env === 'test' ? { node: 'current' } : { node: '6' };

module.exports = {
  presets: [['@babel/env', { targets }]],
  plugins: [
    ...env === 'test' ? ['istanbul', '@babel/transform-block-scoping'] : [],
  ],
}
<commit_msg>Reformat .babelrc.js<commit_after>module.exports = api => ({
  presets: [
    ['@babel/env', {
      targets: api.env() === 'test' ? { node: 'current' } : { node: '6' },
    }],
  ],
  plugins: api.env() === 'test' ? ['istanbul', '@babel/transform-block-scoping'] : [],
})
<|endoftext|>


<commit_before>  const env = process.env.NODE_ENV;

if (env === 'commonjs' || env === 'es') {
  module.exports = {
    ignore: [
      '*.jest.js',
      '*.e2e.js',
      '*.ssr.js',
      '*.example.js',
      'source/demo',
      'source/jest-*.js',
      'source/TestUtils.js',
    ],
    plugins: [
      'transform-runtime',
      ['flow-react-proptypes', {deadCode: true, useESModules: true}],
      ['transform-react-remove-prop-types', {mode: 'wrap'}],
    ],
    presets: [['env', {modules: false}], 'react', 'flow', 'stage-2'],
  };

  if (env === 'commonjs') {
    module.exports.plugins.push('transform-es2015-modules-commonjs');
  }
}

if (env === 'development') {
  module.exports = {
    presets: ['react', 'flow', 'stage-2'],
  };
}

if (env === 'production') {
  module.exports = {
    comments: false,
    plugins: ['transform-runtime'],
    presets: ['env', 'react', 'flow', 'stage-2'],
  };
}

if (env === 'test') {
  module.exports = {
    comments: false,
    plugins: ['transform-es2015-modules-commonjs'],
    presets: ['react', 'flow', 'stage-2'],
  };
}
<commit_msg>Removed extra space<commit_after>const env = process.env.NODE_ENV;

if (env === 'commonjs' || env === 'es') {
  module.exports = {
    ignore: [
      '*.jest.js',
      '*.e2e.js',
      '*.ssr.js',
      '*.example.js',
      'source/demo',
      'source/jest-*.js',
      'source/TestUtils.js',
    ],
    plugins: [
      'transform-runtime',
      ['flow-react-proptypes', {deadCode: true, useESModules: true}],
      ['transform-react-remove-prop-types', {mode: 'wrap'}],
    ],
    presets: [['env', {modules: false}], 'react', 'flow', 'stage-2'],
  };

  if (env === 'commonjs') {
    module.exports.plugins.push('transform-es2015-modules-commonjs');
  }
}

if (env === 'development') {
  module.exports = {
    presets: ['react', 'flow', 'stage-2'],
  };
}

if (env === 'production') {
  module.exports = {
    comments: false,
    plugins: ['transform-runtime'],
    presets: ['env', 'react', 'flow', 'stage-2'],
  };
}

if (env === 'test') {
  module.exports = {
    comments: false,
    plugins: ['transform-es2015-modules-commonjs'],
    presets: ['react', 'flow', 'stage-2'],
  };
}
<|endoftext|>


<commit_before>import CompositeClosureHelper from '../../../Common/Core/CompositeClosureHelper';

import PMI from './pmi';

// ----------------------------------------------------------------------------
// Global
// ----------------------------------------------------------------------------

function listToPair(list = []) {
  const size = list.length;
  const pairList = [];
  list.forEach((name, idx) => {
    for (let i = idx; i < size; i++) {
      pairList.push([name, list[i]]);
    }
  });
  return pairList;
}

// ----------------------------------------------------------------------------
// Mutual Information Provider
// ----------------------------------------------------------------------------

function mutualInformationProvider(publicAPI, model) {
  const mutualInformationData = PMI.initializeMutualInformationData();
  const deltaHandling = { added: [], removed: [], modified: [], previousMTime: {}, currentMTime: {} };

  function updateHistogram2D(histograms) {
    if (Object.keys(histograms).length > 1) {
      // Extract mtime
      deltaHandling.modified = [];
      deltaHandling.previousMTime = deltaHandling.currentMTime;
      deltaHandling.currentMTime = {};
      model.mutualInformationParameterNames.forEach(name => {
        if (histograms[name] && histograms[name][name]) {
          deltaHandling.currentMTime[name] = histograms[name][name].x.mtime;

          if (deltaHandling.added.indexOf(name) === -1
            && deltaHandling.currentMTime[name]
            && (deltaHandling.previousMTime[name] || 0) < deltaHandling.currentMTime[name]) {
            deltaHandling.modified.push(name);
          }
        }
      });

      // FIXME add var mtime check and update deltaHandling.modified
      PMI.updateMutualInformation(mutualInformationData, [].concat(deltaHandling.added, deltaHandling.modified), deltaHandling.removed, histograms);

      // Push the new mutual info
      publicAPI.fireMutualInformationReady(mutualInformationData);
    }
  }

  publicAPI.setHistogram2dProvider = provider => {
    if (model.histogram2dProviderSubscription) {
      model.histogram2dProviderSubscription.unsubscribe();
    }
    model.histogram2dProvider = provider;
    if (provider) {
      model.histogram2dProviderSubscription = provider.subscribeToHistogram2D(
        updateHistogram2D,
        listToPair(model.mutualInformationParameterNames),
        { symmetric: true, partial: false }
      );
    }
  };

  publicAPI.setMutualInformationParameterNames = names => {
    deltaHandling.added = names.filter(name => model.mutualInformationParameterNames.indexOf(name) === -1);
    deltaHandling.removed = model.mutualInformationParameterNames.filter(name => names.indexOf(name) === -1);

    model.mutualInformationParameterNames = [].concat(names);
    if (model.histogram2dProviderSubscription) {
      model.histogram2dProviderSubscription.update(listToPair(model.mutualInformationParameterNames));
    }
  };
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  // mutualInformationData: null,
  mutualInformationParameterNames: [],
};

// ----------------------------------------------------------------------------

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  CompositeClosureHelper.destroy(publicAPI, model);
  CompositeClosureHelper.isA(publicAPI, model, 'MutualInformationProvider');
  CompositeClosureHelper.get(publicAPI, model, ['histogram2dProvider']);
  CompositeClosureHelper.event(publicAPI, model, 'mutualInformationReady');

  mutualInformationProvider(publicAPI, model);
}

// ----------------------------------------------------------------------------

export const newInstance = CompositeClosureHelper.newInstance(extend);

// ----------------------------------------------------------------------------

export default { newInstance, extend };
<commit_msg>fix(MutualInformationProvider): Mutual information discard axis with no range<commit_after>import CompositeClosureHelper from '../../../Common/Core/CompositeClosureHelper';

import PMI from './pmi';

// ----------------------------------------------------------------------------
// Global
// ----------------------------------------------------------------------------

function listToPair(list = []) {
  const size = list.length;
  const pairList = [];
  list.forEach((name, idx) => {
    for (let i = idx; i < size; i++) {
      pairList.push([name, list[i]]);
    }
  });
  return pairList;
}

// ----------------------------------------------------------------------------
// Mutual Information Provider
// ----------------------------------------------------------------------------

function mutualInformationProvider(publicAPI, model) {
  const mutualInformationData = PMI.initializeMutualInformationData();
  const deltaHandling = { added: [], removed: [], modified: [], previousMTime: {}, currentMTime: {} };

  function updateHistogram2D(histograms) {
    if (Object.keys(histograms).length > 1) {
      const invalidAxis = [];
      // Extract mtime
      deltaHandling.modified = [];
      deltaHandling.previousMTime = deltaHandling.currentMTime;
      deltaHandling.currentMTime = {};
      model.mutualInformationParameterNames.forEach(name => {
        if (histograms[name] && histograms[name][name]) {
          // Validate range
          if (histograms[name][name].x.delta === 0) {
            invalidAxis.push(name);
            deltaHandling.currentMTime[name] = 0;
          } else {
            deltaHandling.currentMTime[name] = histograms[name][name].x.mtime;
          }

          if (deltaHandling.added.indexOf(name) === -1
            && deltaHandling.currentMTime[name]
            && (deltaHandling.previousMTime[name] || 0) < deltaHandling.currentMTime[name]) {
            deltaHandling.modified.push(name);
          }
        }
      });

      // FIXME add var mtime check and update deltaHandling.modified
      PMI.updateMutualInformation(
        mutualInformationData,
        [].concat(deltaHandling.added, deltaHandling.modified),
        [].concat(deltaHandling.removed, invalidAxis),
        histograms);

      // Push the new mutual info
      publicAPI.fireMutualInformationReady(mutualInformationData);
    }
  }

  publicAPI.setHistogram2dProvider = provider => {
    if (model.histogram2dProviderSubscription) {
      model.histogram2dProviderSubscription.unsubscribe();
    }
    model.histogram2dProvider = provider;
    if (provider) {
      model.histogram2dProviderSubscription = provider.subscribeToHistogram2D(
        updateHistogram2D,
        listToPair(model.mutualInformationParameterNames),
        { symmetric: true, partial: false }
      );
    }
  };

  publicAPI.setMutualInformationParameterNames = names => {
    deltaHandling.added = names.filter(name => model.mutualInformationParameterNames.indexOf(name) === -1);
    deltaHandling.removed = model.mutualInformationParameterNames.filter(name => names.indexOf(name) === -1);

    model.mutualInformationParameterNames = [].concat(names);
    if (model.histogram2dProviderSubscription) {
      model.histogram2dProviderSubscription.update(listToPair(model.mutualInformationParameterNames));
    }
  };
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  // mutualInformationData: null,
  mutualInformationParameterNames: [],
};

// ----------------------------------------------------------------------------

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  CompositeClosureHelper.destroy(publicAPI, model);
  CompositeClosureHelper.isA(publicAPI, model, 'MutualInformationProvider');
  CompositeClosureHelper.get(publicAPI, model, ['histogram2dProvider']);
  CompositeClosureHelper.event(publicAPI, model, 'mutualInformationReady');

  mutualInformationProvider(publicAPI, model);
}

// ----------------------------------------------------------------------------

export const newInstance = CompositeClosureHelper.newInstance(extend);

// ----------------------------------------------------------------------------

export default { newInstance, extend };
<|endoftext|>


<commit_before>'use strict'

var ResponseProcessor = function() {

}

module.exports = ResponseProcessor;<commit_msg>JSLint<commit_after>'use strict';

var ResponseProcessor = function() {

};

module.exports = ResponseProcessor;
<|endoftext|>