<commit_before>const pick = require('lodash.pick');
const diffPatcher = require('jsondiffpatch').create();

const History = require('./diffHistoryModel').model;

const saveDiffObject = (currentObject, original, updated, user, reason) => {
  const diff = diffPatcher.diff(
    JSON.parse(JSON.stringify(original)),
    JSON.parse(JSON.stringify(updated))
  );

  if (!diff) return;

  const collectionId = currentObject._id;
  const collectionName = currentObject.constructor.modelName;

  return History.findOne({ collectionId, collectionName })
    .sort('-version')
    .then(lastHistory => {
      const history = new History({
        collectionId,
        collectionName,
        diff,
        user,
        reason,
        version: lastHistory ? lastHistory.version + 1 : 0 // TODO: bad logic
      });
      return history.save();
    });
};

const saveDiffHistory = (queryObject, currentObject) => {
  return currentObject.constructor.findOne({ _id: currentObject._id }).then(selfObject => {
    if (!selfObject) return;

    const updateParams = queryObject._update['$set'] || queryObject._update;
    const dbObject = pick(selfObject, Object.keys(updateParams));

    return saveDiffObject(
      currentObject,
      dbObject,
      updateParams,
      queryObject.options.__user,
      queryObject.options.__reason
    );
  });
};

const saveDiffs = queryObject =>
  queryObject
    .find(queryObject._conditions)
    .cursor()
    .eachAsync(result => saveDiffHistory(queryObject, result)); // TODO: Not sure if cursor available here, swap to mapSeries if not.

const getVersion = (model, id, version) => {
  return model.findOne({ _id: id }).then(latest => {
    return History.find(
      {
        collectionName: model.modelName,
        collectionId: id,
        version: { $gte: parseInt(version, 10) }
      },
      { diff: 1, version: 1 },
      { sort: '-version' }
    )
      .cursor()
      .eachAsync(history => {
        // TODO: Not sure if cursor available here, swap to mapSeries if not.
        const object = latest ? latest : {};
        return diffPatcher.unpatch(object, history.diff);
      });
  });
};

const getHistories = (modelName, id, expandableFields) => {
  return History.find({ collectionName: modelName, collectionId: id })
    .cursor()
    .eachAsync(history => {
      const changedValues = [];
      const changedFields = [];
      for (const key in history.diff) {
        if (history.diff.hasOwnProperty(key)) {
          if (expandableFields.indexOf(key) > -1) {
            const oldValue = history.diff[key][0];
            const newValue = history.diff[key][1];
            changedValues.push(key + ' from ' + oldValue + ' to ' + newValue);
          } else {
            changedFields.push(key);
          }
        }
      }
      const comment = 'modified ' + changedFields.concat(changedValues).join(', ');
      return {
        changedBy: history.user,
        changedAt: history.createdAt,
        updatedAt: history.updatedAt,
        reason: history.reason,
        comment: comment
      };
    });
};

const plugin = function lastModifiedPlugin(schema) {
  schema.pre('save', function(next) {
    if (this.isNew) return next();
    this.constructor
      .findOne({ _id: this._id })
      .then(original => saveDiffObject(this, original, this, this.__user, this.__reason))
      .then(() => next())
      .catch(next);
  });

  schema.pre('findOneAndUpdate', function(next) {
    saveDiffs(this)
      .then(() => next())
      .catch(next);
  });

  schema.pre('update', function(next) {
    saveDiffs(this)
      .then(() => next())
      .catch(next);
  });

  schema.pre('remove', function(next) {
    saveDiffObject(this, this, {}, this.__user, this.__reason)
      .then(() => next())
      .catch(next);
  });
};

module.exports = {
  plugin,
  getVersion,
  getHistories
};
<commit_msg>Fix diffHistory eachAsync returns.<commit_after>const pick = require('lodash.pick');
const diffPatcher = require('jsondiffpatch').create();

const History = require('./diffHistoryModel').model;

const saveDiffObject = (currentObject, original, updated, user, reason) => {
  const diff = diffPatcher.diff(
    JSON.parse(JSON.stringify(original)),
    JSON.parse(JSON.stringify(updated))
  );

  if (!diff) return;

  const collectionId = currentObject._id;
  const collectionName = currentObject.constructor.modelName;

  return History.findOne({ collectionId, collectionName })
    .sort('-version')
    .then(lastHistory => {
      const history = new History({
        collectionId,
        collectionName,
        diff,
        user,
        reason,
        version: lastHistory ? lastHistory.version + 1 : 0
      });
      return history.save();
    });
};

const saveDiffHistory = (queryObject, currentObject) => {
  return currentObject.constructor.findOne({ _id: currentObject._id }).then(selfObject => {
    if (!selfObject) return;

    const updateParams = queryObject._update['$set'] || queryObject._update;
    const dbObject = pick(selfObject, Object.keys(updateParams));

    return saveDiffObject(
      currentObject,
      dbObject,
      updateParams,
      queryObject.options.__user,
      queryObject.options.__reason
    );
  });
};

const saveDiffs = queryObject =>
  queryObject
    .find(queryObject._conditions)
    .cursor()
    .eachAsync(result => saveDiffHistory(queryObject, result));

const getVersion = (model, id, version) => {
  return model.findById(id).then(latest => {
    latest = latest || {};
    return History.find(
      {
        collectionName: model.modelName,
        collectionId: id,
        version: { $gte: parseInt(version, 10) }
      },
      { diff: 1, version: 1 },
      { sort: '-version' }
    )
      .lean()
      .cursor()
      .eachAsync(history => {
        diffPatcher.unpatch(latest, history.diff);
      })
      .then(() => latest);
  });
};

const getHistories = (modelName, id, expandableFields) => {
  const histories = [];
  return History.find({ collectionName: modelName, collectionId: id })
    .cursor()
    .eachAsync(history => {
      const changedValues = [];
      const changedFields = [];
      for (const key in history.diff) {
        if (history.diff.hasOwnProperty(key)) {
          if (expandableFields.indexOf(key) > -1) {
            const oldValue = history.diff[key][0];
            const newValue = history.diff[key][1];
            changedValues.push(key + ' from ' + oldValue + ' to ' + newValue);
          } else {
            changedFields.push(key);
          }
        }
      }
      const comment = 'modified ' + changedFields.concat(changedValues).join(', ');
      histories.push({
        changedBy: history.user,
        changedAt: history.createdAt,
        updatedAt: history.updatedAt,
        reason: history.reason,
        comment: comment
      });
    })
    .then(() => histories);
};

const plugin = function lastModifiedPlugin(schema) {
  schema.pre('save', function(next) {
    if (this.isNew) return next();
    this.constructor
      .findOne({ _id: this._id })
      .then(original => saveDiffObject(this, original, this, this.__user, this.__reason))
      .then(() => next())
      .catch(next);
  });

  schema.pre('findOneAndUpdate', function(next) {
    saveDiffs(this)
      .then(() => next())
      .catch(next);
  });

  schema.pre('update', function(next) {
    saveDiffs(this)
      .then(() => next())
      .catch(next);
  });

  schema.pre('remove', function(next) {
    saveDiffObject(this, this, {}, this.__user, this.__reason)
      .then(() => next())
      .catch(next);
  });
};

module.exports = {
  plugin,
  getVersion,
  getHistories
};
<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

"use strict";

const { Cu } = require("chrome");
const { Trace, TraceError } = require("../core/trace.js").get(module.id);
const { target } = require("../target.js");
const { Theme } = require("../chrome/theme.js");

const { Services } = Cu.import("resource://gre/modules/Services.jsm", {});
const Telemetry = Services.telemetry;

const ADDON_NAME = "Firebug";

// Register a histogram for Firebug theme (on/off)
const THEME_ACTIVE_FLAG = "THEME_ACTIVE_FLAG";
Telemetry.registerAddonHistogram(
  ADDON_NAME,
  THEME_ACTIVE_FLAG,
  0, 0, 0,
  Telemetry.HISTOGRAM_FLAG
);

/**
 * This object is intended to collect various telemetry data and store
 * them into proper histograms. The object also defined useful API that
 * can be used from other modules.
 *
 * See http://arewesnappyyet.com for aggregated data.
 *
 * xxxHonza: unregister histograms on uninstall?
 */
var FirebugTelemetry =
{
  initialize: function(Firebug) {
    // Set a flag if Firebug theme is active.
    if (Theme.isFirebugActive()) {
      this.log(THEME_ACTIVE_FLAG, 1);
    }

    // TODO: collect other data
  },

  shutdown: function(Firebug) {
  },

  // Helpers

  getHistogram: function(histogramId) {
    return Telemetry.getAddonHistogram(ADDON_NAME, histogramId);
  },

  log: function(histogramId, value) {
    if (histogramId) {
      try {
        let histogram = this.getHistogram(histogramId);
        histogram.add(value);
      } catch(err) {
        TraceError.sysout("telemetry.log; EXCEPTION " + err, err);
      }
    }
  }
};

// Initialization

target.on("initialize", Firebug => {
  FirebugTelemetry.initialize(Firebug);
});

target.on("shutdown", Firebug => {
  FirebugTelemetry.shutdown(Firebug);
});

// Exports from this module
exports.Telemetry = FirebugTelemetry;
<commit_msg>Registering telemetry histogram can throw an exception<commit_after>/* See license.txt for terms of usage */

"use strict";

const { Cu } = require("chrome");
const { Trace, TraceError } = require("../core/trace.js").get(module.id);
const { target } = require("../target.js");
const { Theme } = require("../chrome/theme.js");

const { Services } = Cu.import("resource://gre/modules/Services.jsm", {});
const Telemetry = Services.telemetry;

const ADDON_NAME = "Firebug";

// Register a histogram for Firebug theme (on/off)
const THEME_ACTIVE_FLAG = "THEME_ACTIVE_FLAG";

/**
 * This object is intended to collect various telemetry data and store
 * them into proper histograms. The object also defined useful API that
 * can be used from other modules.
 *
 * See http://arewesnappyyet.com for aggregated data.
 *
 * xxxHonza: unregister histograms on uninstall?
 */
var FirebugTelemetry =
{
  initialize: function(Firebug) {
    this.registerAddonHistogram(THEME_ACTIVE_FLAG);

    // Set a flag if Firebug theme is active.
    if (Theme.isFirebugActive()) {
      this.log(THEME_ACTIVE_FLAG, 1);
    }

    // TODO: collect other data
  },

  shutdown: function(Firebug) {
  },

  // Helpers

  getHistogram: function(histogramId) {
    return Telemetry.getAddonHistogram(ADDON_NAME, histogramId);
  },

  log: function(histogramId, value) {
    if (histogramId) {
      try {
        let histogram = this.getHistogram(histogramId);
        histogram.add(value);
      } catch(err) {
        TraceError.sysout("telemetry.log; EXCEPTION " + err, err);
      }
    }
  },

  registerAddonHistogram: function(histogramId) {
    try {
      let histogram = this.getHistogram(histogramId);
      if (histogram)
        return;

      Telemetry.registerAddonHistogram(
        ADDON_NAME,
        histogramId,
        0, 0, 0,
        Telemetry.HISTOGRAM_FLAG
      );
    } catch (err) {
      TraceError.sysout("telemetry.registerAddonHistogram; EXCEPTION " + err, err);
    }
  }
};

// Initialization

target.on("initialize", Firebug => {
  FirebugTelemetry.initialize(Firebug);
});

target.on("shutdown", Firebug => {
  FirebugTelemetry.shutdown(Firebug);
});

// Exports from this module
exports.Telemetry = FirebugTelemetry;
<|endoftext|>


<commit_before>/*jshint node:true, indent:2, curly:false, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true,
regexp:true, undef:true, strict:true, trailing:true, white:true */
/*global X:true XM:true */

(function () {
  "use strict";

  var _ = X._,
    exec = require('child_process').exec;

  /**
    Used to serve up files to the client. Uses Content-Type to prompt browser to
    save the file

    @extends X.Route
    @class
   */
  X.maintenanceRoute = X.Route.create({

    handle: function (xtr) {
      var that = this,
        url = require("url"),
        querystring = require("querystring"),
        originalUrl = xtr.get("url"),
        args = url.parse(originalUrl).query,
        parsedArgs = querystring.parse(args),
        recordType = parsedArgs.recordType,
        recordId = parsedArgs.id,
        cookie = xtr.request.cookies.xtsessioncookie,
        session,
        sessionParams,
        response = xtr.get("response"),
        queryPayload,
        query;

      var organizationColl = new XM.OrganizationCollection(),
        fetchSuccess = function (model, response) {
          _.each(response, function (org) {
            _.each(org.extensions, function (ext) {
              var extLoc = ext.extension.location,
                extName = ext.extension.name,
                scriptLocation = extLoc + "/source/" + extName + "/database/source/init_script.sql",
                host = org.databaseServer,
                orgName = org.name,
                command = "psql -d " + host + "/" + orgName + " -f " + scriptLocation + "\n";

              xtr.write(command);
              //console.log(command);
              // TODO: get dbserver details into org orm
            });
          });
          xtr.close();
        },
        fetchError = function (model, error) {
          console.log("fetch error");
          xtr.write("error").close();
        },
        options = {
          success: fetchSuccess,
          error: fetchError,
          username: X.options.globalDatabase.nodeUsername
        };

      organizationColl.fetch(options);

      /*
      var psqlRoot = "/usr/local/pgsql/bin/psql";
      var sudoUser = process.env.SUDO_USER;
      var psqlCommand = psqlRoot + " -U " + sudoUser + " -d mongojr -h 127.0.0.1 -p 5432 -f init_script.sql";
      console.log(psqlCommand);
      var child = exec("(cd ../database/server/source && exec " + psqlCommand + ")", function (error, stdout, stderr) {
        console.log(stdout);
        console.log(stderr);
        if (error !== null) {
          console.log('exec error: ' + error);
        }
      });
      */
    },

    handles: ["maintenance", "/maintenance"]
  });
}());
<commit_msg>issue #19051: used new fields in organization orm<commit_after>/*jshint node:true, indent:2, curly:false, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true,
regexp:true, undef:true, strict:true, trailing:true, white:true */
/*global X:true XM:true */

(function () {
  "use strict";

  var _ = X._,
    exec = require('child_process').exec;

  /**
    Used to serve up files to the client. Uses Content-Type to prompt browser to
    save the file

    @extends X.Route
    @class
   */
  X.maintenanceRoute = X.Route.create({

    handle: function (xtr) {
      var that = this,
        url = require("url"),
        querystring = require("querystring"),
        originalUrl = xtr.get("url"),
        args = url.parse(originalUrl).query,
        parsedArgs = querystring.parse(args),
        recordType = parsedArgs.recordType,
        recordId = parsedArgs.id,
        cookie = xtr.request.cookies.xtsessioncookie,
        session,
        sessionParams,
        response = xtr.get("response"),
        queryPayload,
        query;

      var organizationColl = new XM.OrganizationCollection(),
        fetchSuccess = function (model, response) {
          _.each(response, function (org) {
            if (!org.isActive) {
              // no need to update disactivated organizations
              return;
            }
            _.each(org.extensions, function (ext) {
              var extLoc = ext.extension.location,
                extName = ext.extension.name,
                scriptLocation = extLoc + "/source/" + extName + "/database/source/init_script.sql",
                host = org.databaseServer.hostname + ":" + org.databaseServer.port,
                orgName = org.name,
                command = "psql -d " + host + "/" + orgName + " -f " + scriptLocation + "\n";

              xtr.write(command);
              //console.log(command);
              // TODO: get dbserver details into org orm
            });
          });
          xtr.close();
        },
        fetchError = function (model, error) {
          console.log("fetch error");
          xtr.write("error").close();
        },
        options = {
          success: fetchSuccess,
          error: fetchError,
          username: X.options.globalDatabase.nodeUsername
        };

      organizationColl.fetch(options);

      /*
      var psqlRoot = "/usr/local/pgsql/bin/psql";
      var sudoUser = process.env.SUDO_USER;
      var psqlCommand = psqlRoot + " -U " + sudoUser + " -d mongojr -h 127.0.0.1 -p 5432 -f init_script.sql";
      console.log(psqlCommand);
      var child = exec("(cd ../database/server/source && exec " + psqlCommand + ")", function (error, stdout, stderr) {
        console.log(stdout);
        console.log(stderr);
        if (error !== null) {
          console.log('exec error: ' + error);
        }
      });
      */
    },

    handles: ["maintenance", "/maintenance"]
  });
}());
<|endoftext|>


<commit_before>var ROUNDING = 30 * 60 * 1000; /*ms*/
start = moment();
start = moment(Math.ceil((+start) / ROUNDING) * ROUNDING);
jQuery(document).ready(function() {
    $('#time_input').datetimepicker({
        format: 'YYYY-MM-DD HH:mm',
        stepping: 1
    });
});<commit_msg>some code quality tweeks<commit_after>var ROUNDING = 30 * 60 * 1000; /*ms*/
var start = moment();
start = moment(Math.ceil((+start) / ROUNDING) * ROUNDING);
jQuery(document).ready(function() {
    $('#time_input').datetimepicker({
        format: 'YYYY-MM-DD HH:mm',
        stepping: 1
    });
});<|endoftext|>


<commit_before>(function($) {

  /*
    Create the settings and languages menu
  */
  (function() {
    var $menus = $('#settings-menu, #languages-menu');
    $menus.mozMenu();
    $menus.parent().find('.submenu').mozKeyboardNav();
  })();

  /*
    Set up the "from search" buttons if user came from search
  */
  (function() {
    var $fromSearchNav = $('.from-search-navigate');
    if($fromSearchNav.length) {
      var $fromSearchList = $('.from-search-toc');
      $fromSearchNav.mozMenu({
        submenu: $fromSearchList,
        brickOnClick: true
      });
      $fromSearchList.find('ol').mozKeyboardNav();
    }
  })();

  /*
    Toggle for quick links show/hide
  */
  (function() {
    // Set up the quick links for the toggler
    var $quickLinks = $('#quick-links');
    setupTogglers($quickLinks.find('> ul > li, > ol > li'));
    $quickLinks.find('.toggleable').mozTogglers();

    var $columnContainer = $('#wiki-column-container');
    var $quickLinksControl = $('#wiki-controls .quick-links');

    var child = $('#wiki-left').get(0);
    if(child) {
      var parent = child.parentNode;
    }

    // Quick Link toggles
    $('#quick-links-toggle, #show-quick-links').on('click', function(e) {
      e.preventDefault();
      $(child).toggleClass('column-closed');
      $columnContainer.toggleClass('wiki-left-closed');
      $quickLinksControl.toggleClass('hidden');

      if($(child).hasClass('column-closed')) {
        $(window).trigger('resize');
        parent.removeChild(child);
      }
      else {
        parent.appendChild(child);
      }
    });
  })();

  /*
    Set up the zone subnav accordion
  */
  $('.zone-subnav-container').each(function() {
    var $subnavList = $(this).find('.subnav > ol');
    if(!$subnavList.length) return; // Exit if the subnav isn't set up properly

    // Set the list items as togglers where needed
    setupTogglers($subnavList.find('li'));

    // Make them toggleable!
    $subnavList.find('.toggleable').mozTogglers();

    // Try to find the current page in the list, if found, open it
    var $selected = $subnavList.find('a[href$="' + document.location.pathname + '"]');
    $selected.each(function() {
      $(this).parents('.toggleable').find('.toggler').trigger('click');
    }).parent().addClass('current');

    // Mark this is an accordion so the togglers open/close properly
    $subnavList.addClass('accordion');
  });

  /*
    Subscribe / unsubscribe to an article
  */
  $('.page-watch a').on('click', function(e) {
    e.preventDefault();
    $(this).closest('form').submit();
  });

  // Utility method for the togglers
  function setupTogglers($elements) {
    $elements.each(function() {
      var $li = $(this);
      var $sublist = $li.find('> ul, > ol');

      if($sublist.length) {
        $li.addClass('toggleable closed');
        $li.find('> a').addClass('toggler').prepend('');
        $sublist.addClass('toggle-container');
      }
    });
  }

  /*
    Set up the scrolling TOC effect
  */
  (function() {
    var $toc = $('#toc');
    if($toc.length) {
      var tocOffset = $toc.offset().top;
      var $toggler = $toc.find('> .toggler');
      var fixedClass = 'fixed';
      var $wikiRight = $('#wiki-right');

      var resizeFn = debounce(function(e) {
        // Set forth the pinned or static positioning of the table of contents
        var scroll = window.scrollY;
        var maxHeight = window.innerHeight - parseInt($toc.css('padding-top'), 10) - parseInt($toc.css('padding-bottom'), 10);

        if(scroll > tocOffset && $toggler.css('pointer-events') == 'none') {
          $toc.css({
            width: $toc.css('width'),
            maxHeight: maxHeight
          });

          if(!$toc.hasClass(fixedClass)){
            $toc.addClass(fixedClass);
          }
        }
        else {
          $toc.css({
            width: 'auto',
            maxHeight: 'none'
          });
          $toc.removeClass(fixedClass);
        }

        // Should the TOC be one-column (auto-closed) or sidebar'd
        if(!e || e.type == 'resize') {
          if($toggler.css('pointer-events') == 'auto'  || $toggler.find('i').css('display') != 'none') { /* icon check is for old IEs that don't support pointer-events */
            if(!$toc.attr('data-closed')) {
              $toggler.trigger('click');
            }
          }
          else if($toc.attr('data-closed')) { // Changes width, should be opened (i.e. mobile to desktop width)
            $toggler.trigger('click');
          }
        }
      }, 10);

      // Set it forth!
      resizeFn();
      $(window).on('scroll resize', resizeFn);
    }
  })();

  /*
    Stack overflow search form, used for dev program

    ex: http://stackoverflow.com/search?q=[firefox]+or+[firefox-os]+or+[html5-apps]+foobar
  */

  $('.stack-form').html('<form action="http://stackoverflow.com/search">' + gettext('Search StackOverflow') + '<input id="stack-search" placeholder="' + gettext('Search StackOverflow') + '" /><button type="submit" class="offscreen">Submit Search</button></form>').find('form').on('submit', function(e) {
    e.preventDefault();

    var value = $(this).find('#stack-search').val();

    if(value != '') {
      window.location = 'http://stackoverflow.com/search?q=[firefox]+or+[firefox-os]+or+[html5-apps]+' + value;
    }
  });

  function debounce(func, wait, immediate) {
    var timeout;
    return function() {
      var context = this, args = arguments;
      var later = function() {
        timeout = null;
        if (!immediate) func.apply(context, args);
      };
      var callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
      if (callNow) func.apply(context, args);
    };
  };

})(jQuery);<commit_msg>Corrected text<commit_after>(function($) {

  /*
    Create the settings and languages menu
  */
  (function() {
    var $menus = $('#settings-menu, #languages-menu');
    $menus.mozMenu();
    $menus.parent().find('.submenu').mozKeyboardNav();
  })();

  /*
    Set up the "from search" buttons if user came from search
  */
  (function() {
    var $fromSearchNav = $('.from-search-navigate');
    if($fromSearchNav.length) {
      var $fromSearchList = $('.from-search-toc');
      $fromSearchNav.mozMenu({
        submenu: $fromSearchList,
        brickOnClick: true
      });
      $fromSearchList.find('ol').mozKeyboardNav();
    }
  })();

  /*
    Toggle for quick links show/hide
  */
  (function() {
    // Set up the quick links for the toggler
    var $quickLinks = $('#quick-links');
    setupTogglers($quickLinks.find('> ul > li, > ol > li'));
    $quickLinks.find('.toggleable').mozTogglers();

    var $columnContainer = $('#wiki-column-container');
    var $quickLinksControl = $('#wiki-controls .quick-links');

    var child = $('#wiki-left').get(0);
    if(child) {
      var parent = child.parentNode;
    }

    // Quick Link toggles
    $('#quick-links-toggle, #show-quick-links').on('click', function(e) {
      e.preventDefault();
      $(child).toggleClass('column-closed');
      $columnContainer.toggleClass('wiki-left-closed');
      $quickLinksControl.toggleClass('hidden');

      if($(child).hasClass('column-closed')) {
        $(window).trigger('resize');
        parent.removeChild(child);
      }
      else {
        parent.appendChild(child);
      }
    });
  })();

  /*
    Set up the zone subnav accordion
  */
  $('.zone-subnav-container').each(function() {
    var $subnavList = $(this).find('.subnav > ol');
    if(!$subnavList.length) return; // Exit if the subnav isn't set up properly

    // Set the list items as togglers where needed
    setupTogglers($subnavList.find('li'));

    // Make them toggleable!
    $subnavList.find('.toggleable').mozTogglers();

    // Try to find the current page in the list, if found, open it
    var $selected = $subnavList.find('a[href$="' + document.location.pathname + '"]');
    $selected.each(function() {
      $(this).parents('.toggleable').find('.toggler').trigger('click');
    }).parent().addClass('current');

    // Mark this is an accordion so the togglers open/close properly
    $subnavList.addClass('accordion');
  });

  /*
    Subscribe / unsubscribe to an article
  */
  $('.page-watch a').on('click', function(e) {
    e.preventDefault();
    $(this).closest('form').submit();
  });

  // Utility method for the togglers
  function setupTogglers($elements) {
    $elements.each(function() {
      var $li = $(this);
      var $sublist = $li.find('> ul, > ol');

      if($sublist.length) {
        $li.addClass('toggleable closed');
        $li.find('> a').addClass('toggler').prepend('');
        $sublist.addClass('toggle-container');
      }
    });
  }

  /*
    Set up the scrolling TOC effect
  */
  (function() {
    var $toc = $('#toc');
    if($toc.length) {
      var tocOffset = $toc.offset().top;
      var $toggler = $toc.find('> .toggler');
      var fixedClass = 'fixed';
      var $wikiRight = $('#wiki-right');

      var resizeFn = debounce(function(e) {
        // Set forth the pinned or static positioning of the table of contents
        var scroll = window.scrollY;
        var maxHeight = window.innerHeight - parseInt($toc.css('padding-top'), 10) - parseInt($toc.css('padding-bottom'), 10);

        if(scroll > tocOffset && $toggler.css('pointer-events') == 'none') {
          $toc.css({
            width: $toc.css('width'),
            maxHeight: maxHeight
          });

          if(!$toc.hasClass(fixedClass)){
            $toc.addClass(fixedClass);
          }
        }
        else {
          $toc.css({
            width: 'auto',
            maxHeight: 'none'
          });
          $toc.removeClass(fixedClass);
        }

        // Should the TOC be one-column (auto-closed) or sidebar'd
        if(!e || e.type == 'resize') {
          if($toggler.css('pointer-events') == 'auto'  || $toggler.find('i').css('display') != 'none') { /* icon check is for old IEs that don't support pointer-events */
            if(!$toc.attr('data-closed')) {
              $toggler.trigger('click');
            }
          }
          else if($toc.attr('data-closed')) { // Changes width, should be opened (i.e. mobile to desktop width)
            $toggler.trigger('click');
          }
        }
      }, 10);

      // Set it forth!
      resizeFn();
      $(window).on('scroll resize', resizeFn);
    }
  })();

  /*
    Stack overflow search form, used for dev program

    ex: http://stackoverflow.com/search?q=[firefox]+or+[firefox-os]+or+[html5-apps]+foobar
  */

  $('.stack-form').html('<form action="http://stackoverflow.com/search">' + gettext('Search Stack Overflow') + '<input id="stack-search" placeholder="' + gettext('Search Stack Overflow') + '" /><button type="submit" class="offscreen">Submit Search</button></form>').find('form').on('submit', function(e) {
    e.preventDefault();

    var value = $(this).find('#stack-search').val();

    if(value != '') {
      window.location = 'http://stackoverflow.com/search?q=[firefox]+or+[firefox-os]+or+[html5-apps]+' + value;
    }
  });

  function debounce(func, wait, immediate) {
    var timeout;
    return function() {
      var context = this, args = arguments;
      var later = function() {
        timeout = null;
        if (!immediate) func.apply(context, args);
      };
      var callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
      if (callNow) func.apply(context, args);
    };
  };

})(jQuery);<|endoftext|>


<commit_before>import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';

module('Integration | Component | researcher-show', function(hooks) {
  setupRenderingTest(hooks);

  test('it renders', async function(assert) {
    // Set any properties with this.set('myProperty', 'value');
    // Handle any actions with this.set('myAction', function(val) { ... });

    // Template block usage:
    await render(hbs`
      <ResearcherShow>
        template block text
      </ResearcherShow>
    `);

    assert.equal(this.element.textContent.trim(), 'ORCID');
  });
});
<commit_msg>fix test<commit_after>import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';

module('Integration | Component | researcher-show', function(hooks) {
  setupRenderingTest(hooks);

  test('it renders', async function(assert) {
    // Set any properties with this.set('myProperty', 'value');
    // Handle any actions with this.set('myAction', function(val) { ... });

    // Template block usage:
    await render(hbs`
      <ResearcherShow>
        template block text
      </ResearcherShow>
    `);

    assert.equal(this.element.textContent.trim(), 'ORCID ID');
  });
});
<|endoftext|>


<commit_before>var PROTOCOL = 0x4343
var VERSION = 0x02
var MAXBYTESIZE = 40
var OP_CODES = {
  'issuance': {
    'start': 0x00,
    'end': 0x0f,
    'encoder': require('cc-issuance-encoder')
  },
  'transfer': {
    'start': 0x10,
    'end': 0x1f,
    'encoder': require('cc-transfer-encoder')
  }
}

var encodingLookup = {}

for (var transactionType in OP_CODES) {
  for (var j = OP_CODES[transactionType].start; j <= OP_CODES[transactionType].end; j++) {
    encodingLookup[j] = {}
    encodingLookup[j].encode = OP_CODES[transactionType].encoder.encode
    encodingLookup[j].decode = OP_CODES[transactionType].encoder.decode
    encodingLookup[j].type = transactionType
  }
}

var paymentsInputToSkip = function (payments) {
  var result = JSON.parse(JSON.stringify(payments))
  result.sort(function (a, b) {
    return a.input - b.input
  })
  for (var i = 0; i < result.length; i++) {
    var skip = false
    if (result[i + 1] && result[i + 1].input > result[i].input) {
      skip = true
    }
    delete result[i].input
    result[i].skip = skip
  }
  return result
}

var paymentsSkipToInput = function (payments) {
  var paymentsDecoded = []
  var input = 0
  for (var i = 0; i < payments.length; i++) {
    paymentsDecoded.push({
      input: input,
      amount: payments[i].amount,
      output: payments[i].output,
      range: payments[i].range,
      percent: payments[i].percent
    })
    if (payments[i].skip) input = input + 1
  }
  return paymentsDecoded
}

function Transaction (data) {
  data = data || {}
  this.type = data.type || 'transfer'
  this.noRules = data.noRules || true
  this.payments = data.payments || []
  this.protocol = data.protocol || PROTOCOL
  this.version = data.version || VERSION
  this.lockStatus = data.lockStatus
  this.divisibility = data.divisibility
  this.multiSig = data.multiSig || []
  this.amount = data.amount
  this.sha2 = data.sha2
  this.torrentHash = data.torrentHash
}

Transaction.fromHex = function (op_return) {
  if (!Buffer.isBuffer(op_return)) {
    op_return = new Buffer(op_return, 'hex')
  }
  var decoder = encodingLookup[op_return[3]]
  var rawData = decoder.decode(op_return)
  rawData.type = decoder.type
  rawData.payments = paymentsSkipToInput(rawData.payments)
  return new Transaction(rawData)
}

Transaction.newTransaction = function (protocol, version) {
  return new Transaction({protocol: protocol, version: version})
}

Transaction.prototype.addPayment = function (input, amount, output, range, percent) {
  range = range || false
  percent = percent || false
  this.payments.push({input: input, amount: amount, output: output, range: range, percent: percent})
}

/**
 * @param {Number=} amount - the amount of units of the asset to issue. Integer.
 * @param {Number=} divisibility - the divisibility of the asset to issue - how many decimal points can an asset unit have. Integer.
 */
Transaction.prototype.setAmount = function (amount, divisibility) {
  if (typeof amount === 'undefined') throw new Error('Amount has to be defined')
  this.type = 'issuance'
  this.divisibility = divisibility || 0
  this.amount = amount
}

Transaction.prototype.setLockStatus = function (lockStatus) {
  this.lockStatus = lockStatus
  this.type = 'issuance'
}

Transaction.prototype.allowRules = function () {
  this.noRules = false
}

Transaction.prototype.shiftOutputs = function (shiftAmount) {
  shiftAmount = shiftAmount || 1
  this.payments.forEach(function (payment) {
    payment.output += shiftAmount
  })
}

Transaction.prototype.setHash = function (torrentHash, sha2) {
  if (!torrentHash) throw new Error('Can\'t set hashes without the torrent hash')
  if (!Buffer.isBuffer(torrentHash)) torrentHash = new Buffer(torrentHash, 'hex')
  this.torrentHash = torrentHash
  if (sha2) {
    if (!Buffer.isBuffer(sha2)) sha2 = new Buffer(sha2, 'hex')
    this.sha2 = sha2
  }
}

Transaction.prototype.encode = function () {
  var encoder = OP_CODES[this.type].encoder
  this.payments = paymentsInputToSkip(this.payments)
  var result = encoder.encode(this, MAXBYTESIZE)
  this.payments = paymentsSkipToInput(this.payments)
  return result
}

Transaction.prototype.toJson = function () {
  var data = {}
  data.payments = this.payments
  data.protocol = this.protocol
  data.version = this.version
  data.type = this.type
  if (this.type === 'issuance') {
    data.lockStatus = this.lockStatus
    data.divisibility = this.divisibility
    data.amount = this.amount
  }
  data.multiSig = this.multiSig
  if (this.torrentHash) {
    data.torrentHash = this.torrentHash.toString('hex')
    if (this.sha2) data.sha2 = this.sha2.toString('hex')
  }
  return data
}

module.exports = Transaction
<commit_msg>80 byte<commit_after>var PROTOCOL = 0x4343
var VERSION = 0x02
var MAXBYTESIZE = 80
var OP_CODES = {
  'issuance': {
    'start': 0x00,
    'end': 0x0f,
    'encoder': require('cc-issuance-encoder')
  },
  'transfer': {
    'start': 0x10,
    'end': 0x1f,
    'encoder': require('cc-transfer-encoder')
  }
}

var encodingLookup = {}

for (var transactionType in OP_CODES) {
  for (var j = OP_CODES[transactionType].start; j <= OP_CODES[transactionType].end; j++) {
    encodingLookup[j] = {}
    encodingLookup[j].encode = OP_CODES[transactionType].encoder.encode
    encodingLookup[j].decode = OP_CODES[transactionType].encoder.decode
    encodingLookup[j].type = transactionType
  }
}

var paymentsInputToSkip = function (payments) {
  var result = JSON.parse(JSON.stringify(payments))
  result.sort(function (a, b) {
    return a.input - b.input
  })
  for (var i = 0; i < result.length; i++) {
    var skip = false
    if (result[i + 1] && result[i + 1].input > result[i].input) {
      skip = true
    }
    delete result[i].input
    result[i].skip = skip
  }
  return result
}

var paymentsSkipToInput = function (payments) {
  var paymentsDecoded = []
  var input = 0
  for (var i = 0; i < payments.length; i++) {
    paymentsDecoded.push({
      input: input,
      amount: payments[i].amount,
      output: payments[i].output,
      range: payments[i].range,
      percent: payments[i].percent
    })
    if (payments[i].skip) input = input + 1
  }
  return paymentsDecoded
}

function Transaction (data) {
  data = data || {}
  this.type = data.type || 'transfer'
  this.noRules = data.noRules || true
  this.payments = data.payments || []
  this.protocol = data.protocol || PROTOCOL
  this.version = data.version || VERSION
  this.lockStatus = data.lockStatus
  this.divisibility = data.divisibility
  this.multiSig = data.multiSig || []
  this.amount = data.amount
  this.sha2 = data.sha2
  this.torrentHash = data.torrentHash
}

Transaction.fromHex = function (op_return) {
  if (!Buffer.isBuffer(op_return)) {
    op_return = new Buffer(op_return, 'hex')
  }
  var decoder = encodingLookup[op_return[3]]
  var rawData = decoder.decode(op_return)
  rawData.type = decoder.type
  rawData.payments = paymentsSkipToInput(rawData.payments)
  return new Transaction(rawData)
}

Transaction.newTransaction = function (protocol, version) {
  return new Transaction({protocol: protocol, version: version})
}

Transaction.prototype.addPayment = function (input, amount, output, range, percent) {
  range = range || false
  percent = percent || false
  this.payments.push({input: input, amount: amount, output: output, range: range, percent: percent})
}

/**
 * @param {Number=} amount - the amount of units of the asset to issue. Integer.
 * @param {Number=} divisibility - the divisibility of the asset to issue - how many decimal points can an asset unit have. Integer.
 */
Transaction.prototype.setAmount = function (amount, divisibility) {
  if (typeof amount === 'undefined') throw new Error('Amount has to be defined')
  this.type = 'issuance'
  this.divisibility = divisibility || 0
  this.amount = amount
}

Transaction.prototype.setLockStatus = function (lockStatus) {
  this.lockStatus = lockStatus
  this.type = 'issuance'
}

Transaction.prototype.allowRules = function () {
  this.noRules = false
}

Transaction.prototype.shiftOutputs = function (shiftAmount) {
  shiftAmount = shiftAmount || 1
  this.payments.forEach(function (payment) {
    payment.output += shiftAmount
  })
}

Transaction.prototype.setHash = function (torrentHash, sha2) {
  if (!torrentHash) throw new Error('Can\'t set hashes without the torrent hash')
  if (!Buffer.isBuffer(torrentHash)) torrentHash = new Buffer(torrentHash, 'hex')
  this.torrentHash = torrentHash
  if (sha2) {
    if (!Buffer.isBuffer(sha2)) sha2 = new Buffer(sha2, 'hex')
    this.sha2 = sha2
  }
}

Transaction.prototype.encode = function () {
  var encoder = OP_CODES[this.type].encoder
  this.payments = paymentsInputToSkip(this.payments)
  var result = encoder.encode(this, MAXBYTESIZE)
  this.payments = paymentsSkipToInput(this.payments)
  return result
}

Transaction.prototype.toJson = function () {
  var data = {}
  data.payments = this.payments
  data.protocol = this.protocol
  data.version = this.version
  data.type = this.type
  if (this.type === 'issuance') {
    data.lockStatus = this.lockStatus
    data.divisibility = this.divisibility
    data.amount = this.amount
  }
  data.multiSig = this.multiSig
  if (this.torrentHash) {
    data.torrentHash = this.torrentHash.toString('hex')
    if (this.sha2) data.sha2 = this.sha2.toString('hex')
  }
  return data
}

module.exports = Transaction
<|endoftext|>


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

/**
 * @fileoverview String constants of region codes for testing.
 * @author Nikolaos Trogkanis
 */

goog.provide('i18n.phonenumbers.RegionCode');

/**
 * Enum containing string constants of region codes for easier testing.
 *
 * @enum {string}
 */
i18n.phonenumbers.RegionCode = {
  // Region code for global networks (e.g. +800 numbers).
  UN001: '001',
  AD: 'AD',
  AO: 'AO',
  AQ: 'AQ',
  AR: 'AR',
  AU: 'AU',
  BR: 'BR',
  BS: 'BS',
  BY: 'BY',
  CA: 'CA',
  CN: 'CN',
  CS: 'CS',
  DE: 'DE',
  GB: 'GB',
  IT: 'IT',
  JP: 'JP',
  KR: 'KR',
  MX: 'MX',
  NZ: 'NZ',
  PL: 'PL',
  RE: 'RE',
  SG: 'SG',
  US: 'US',
  YT: 'YT',
  ZW: 'ZW',
  // Official code for the unknown region.
  ZZ: 'ZZ'
};
<commit_msg>JS: Remove errornous svn:executable property from source code file.<commit_after>/**
 * @license
 * Copyright (C) 2011 The Libphonenumber Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview String constants of region codes for testing.
 * @author Nikolaos Trogkanis
 */

goog.provide('i18n.phonenumbers.RegionCode');

/**
 * Enum containing string constants of region codes for easier testing.
 *
 * @enum {string}
 */
i18n.phonenumbers.RegionCode = {
  // Region code for global networks (e.g. +800 numbers).
  UN001: '001',
  AD: 'AD',
  AO: 'AO',
  AQ: 'AQ',
  AR: 'AR',
  AU: 'AU',
  BR: 'BR',
  BS: 'BS',
  BY: 'BY',
  CA: 'CA',
  CN: 'CN',
  CS: 'CS',
  DE: 'DE',
  GB: 'GB',
  IT: 'IT',
  JP: 'JP',
  KR: 'KR',
  MX: 'MX',
  NZ: 'NZ',
  PL: 'PL',
  RE: 'RE',
  SG: 'SG',
  US: 'US',
  YT: 'YT',
  ZW: 'ZW',
  // Official code for the unknown region.
  ZZ: 'ZZ'
};
<|endoftext|>


<commit_before>var async = require('async');
var db = require('./db');
var r = require('./redis');
var redis = r.client;
var moment = require('moment');
var kue = r.kue;
var jobs = r.jobs;
module.exports = function getStatus(cb) {
    async.series({
        matches: function(cb) {
            db.matches.count({}, cb);
        },
        players: function(cb) {
            db.players.count({}, cb);
        },
        user_players: function(cb) {
            db.players.count({
                last_visited: {
                    $gt: new Date(0)
                }
            }, cb);
        },
        full_history_players: function(cb) {
            db.players.count({
                full_history_time: {
                    $gt: new Date(0)
                }
            }, cb);
        },
        tracked_players: function(cb) {
            redis.get("trackedPlayers", function(err, res) {
                res = res ? Object.keys(JSON.parse(res)).length : 0;
                cb(err, res);
            });
        },
        rating_players: function(cb) {
            redis.get("ratingPlayers", function(err, res) {
                res = res ? Object.keys(JSON.parse(res)).length : 0;
                cb(err, res);
            });
        },
        donated_players: function(cb) {
            redis.get("donators", function(err, res) {
                res = res ? Object.keys(JSON.parse(res)).length : 0;
                cb(err, res);
            });
        },
        matches_last_day: function(cb) {
            redis.keys("added_match:*", function(err, result) {
                cb(err, result.length);
            });
        },
        parsed_last_day: function(cb) {
            redis.keys("parsed_match:*", function(err, result) {
                cb(err, result.length);
            });
        },
        requested_last_day: function(cb) {
            redis.keys("requested_match:*", function(err, result) {
                cb(err, result.length);
            });
        },
        last_added: function(cb) {
            db.matches.find({}, {
                sort: {
                    _id: -1
                },
                fields: {
                    match_id: 1,
                    match_seq_num: 1,
                    start_time: 1,
                    duration: 1
                },
                limit: 10
            }, cb);
        },
        last_parsed: function(cb) {
            db.matches.find({
                parse_status: 2
            }, {
                sort: {
                    _id: -1
                },
                fields: {
                    match_id: 1,
                    match_seq_num: 1,
                    start_time: 1,
                    duration: 1
                },
                limit: 10
            }, cb);
        },
        kue: function(cb) {
            var counts = {};
            jobs.types(function(err, data) {
                async.each(data, function(d, cb) {
                    jobs.cardByType(d, "inactive", function(err, result) {
                        counts[d] = result;
                        cb(err);
                    });
                }, function(err) {
                    cb(err, counts);
                });
            });
        }
    }, cb);
};<commit_msg>added cached players count to status<commit_after>var async = require('async');
var db = require('./db');
var r = require('./redis');
var redis = r.client;
var jobs = r.jobs;
module.exports = function getStatus(cb) {
    async.series({
        matches: function(cb) {
            db.matches.count({}, cb);
        },
        players: function(cb) {
            db.players.count({}, cb);
        },
        user_players: function(cb) {
            db.players.count({
                last_visited: {
                    $gt: new Date(0)
                }
            }, cb);
        },
        full_history_players: function(cb) {
            db.players.count({
                full_history_time: {
                    $gt: new Date(0)
                }
            }, cb);
        },
        tracked_players: function(cb) {
            redis.get("trackedPlayers", function(err, res) {
                res = res ? Object.keys(JSON.parse(res)).length : 0;
                cb(err, res);
            });
        },
        rating_players: function(cb) {
            redis.get("ratingPlayers", function(err, res) {
                res = res ? Object.keys(JSON.parse(res)).length : 0;
                cb(err, res);
            });
        },
        donated_players: function(cb) {
            redis.get("donators", function(err, res) {
                res = res ? Object.keys(JSON.parse(res)).length : 0;
                cb(err, res);
            });
        },
        cached_players: function(cb) {
            redis.keys("player:*", function(err, result) {
                cb(err, result.length);
            });
        },
        matches_last_day: function(cb) {
            redis.keys("added_match:*", function(err, result) {
                cb(err, result.length);
            });
        },
        parsed_last_day: function(cb) {
            redis.keys("parsed_match:*", function(err, result) {
                cb(err, result.length);
            });
        },
        requested_last_day: function(cb) {
            redis.keys("requested_match:*", function(err, result) {
                cb(err, result.length);
            });
        },
        last_added: function(cb) {
            db.matches.find({}, {
                sort: {
                    _id: -1
                },
                fields: {
                    match_id: 1,
                    match_seq_num: 1,
                    start_time: 1,
                    duration: 1
                },
                limit: 10
            }, cb);
        },
        last_parsed: function(cb) {
            db.matches.find({
                parse_status: 2
            }, {
                sort: {
                    _id: -1
                },
                fields: {
                    match_id: 1,
                    match_seq_num: 1,
                    start_time: 1,
                    duration: 1
                },
                limit: 10
            }, cb);
        },
        kue: function(cb) {
            var counts = {};
            jobs.types(function(err, data) {
                async.each(data, function(d, cb) {
                    jobs.cardByType(d, "inactive", function(err, result) {
                        counts[d] = result;
                        cb(err);
                    });
                }, function(err) {
                    cb(err, counts);
                });
            });
        }
    }, cb);
};<|endoftext|>


<commit_before>import async from 'async';
import Field from '../Field';
import React from 'react';
import Select from 'react-select';
import xhr from 'xhr';
import { Button, FormInput } from 'elemental';

function compareValues(current, next) {
	if (current.length !== next.length) return false;
	for (let i = 0; i < current.length; i++) {
		if (current[i] !== next[i]) return false;
	}
	return true;
}

module.exports = Field.create({

	displayName: 'RelationshipField',

	getInitialState () {
		return {
			value: null,
		};
	},

	componentDidMount () {
		this._itemsCache = {};
		this.loadValue(this.props.value);
	},

	componentWillReceiveProps (nextProps) {
		if (nextProps.value === this.props.value || nextProps.many && compareValues(this.props.value, nextProps.value)) return;
		this.loadValue(nextProps.value);
	},

	shouldCollapse () {
		if (this.props.many) {
			// many:true relationships have an Array for a value
			return this.props.collapse && !this.props.value.length;
		}
		return this.props.collapse && !this.props.value;
	},

	buildFilters () {
		var filters = {};

		_.each(this.props.filters, function(value, key) {
			if(_.isString(value) && value[0] == ':') {//eslint-disable-line eqeqeq
				var fieldName = value.slice(1);

				var val = this.props.values[fieldName];
				if (val) {
					filters[key] = val;
					return;
				}

				// check if filtering by id and item was already saved
				if (fieldName === ':_id' && Keystone.item) {
					filters[key] = Keystone.item.id;
					return;
				}
			} else {
				filters[key] = value;
			}
		}, this);

		var parts = [];

		_.each(filters, function (val, key) {
			parts.push('filters[' + key + ']=' + encodeURIComponent(val));
		});

		return parts.join('&');
	},

	cacheItem (item) {
		item.href = '/keystone/' + this.props.refList.path + '/' + item.id;
		this._itemsCache[item.id] = item;
	},

	loadValue (values) {
		if (!values) {
			return this.setState({
				loading: false,
				value: null,
			});
		};
		values = values.split(",");
		let cachedValues = values.map(i => this._itemsCache[i]).filter(i => i);
		if (cachedValues.length === values.length) {
			this.setState({
				loading: false,
				value: this.props.many ? cachedValues : cachedValues[0],
			});
			return;
		}
		this.setState({
			loading: true,
			value: null,
		});
		async.map(values, (value, done) => {
			xhr({
				url: '/keystone/api/' + this.props.refList.path + '/' + value + '?basic',
				responseType: 'json',
			}, (err, resp, data) => {
				if (err || !data) return done(err);
				this.cacheItem(data);
				done(err, data);
			});
		}, (err, expanded) => {
			if (!this.isMounted()) return;
			this.setState({
				loading: false,
				value: this.props.many ? expanded : expanded[0],
			});
		});
	},

	loadOptions (input, callback) {
		// TODO: Implement filters
		xhr({
			url: '/keystone/api/' + this.props.refList.path + '?basic&search=' + input,
			responseType: 'json',
		}, (err, resp, data) => {
			if (err) {
				console.error('Error loading items:', err);
				return callback(null, []);
			}
			data.results.forEach(this.cacheItem);
			callback(null, {
				options: data.results,
				complete: data.results.length === data.count,
			});
		});
	},

	valueChanged (value) {
		this.props.onChange({
			path: this.props.path,
			value: value,
		});
	},

	renderSelect (noedit) {
		return (
			<Select.Async
				multi={this.props.many}
				disabled={noedit}
				loadOptions={this.loadOptions}
				labelKey="name"
				name={this.props.path}
				onChange={this.valueChanged}
				simpleValue
				value={this.state.value}
				valueKey="id"
			/>
		);
	},

	renderValue () {
		return this.renderSelect(true);
	},

	renderField () {
		return this.renderSelect();
	}

});
<commit_msg>forgot to save<commit_after>import async from 'async';
import Field from '../Field';
import React from 'react';
import Select from 'react-select';
import xhr from 'xhr';
import { Button, FormInput } from 'elemental';

function compareValues(current, next) {
	if (current.length !== next.length) return false;
	for (let i = 0; i < current.length; i++) {
		if (current[i] !== next[i]) return false;
	}
	return true;
}

module.exports = Field.create({

	displayName: 'RelationshipField',

	getInitialState () {
		return {
			value: null,
		};
	},

	componentDidMount () {
		this._itemsCache = {};
		this.loadValue(this.props.value);
	},

	componentWillReceiveProps (nextProps) {
		if (nextProps.value === this.props.value || nextProps.many && compareValues(this.props.value, nextProps.value)) return;
		this.loadValue(nextProps.value);
	},

	shouldCollapse () {
		if (this.props.many) {
			// many:true relationships have an Array for a value
			return this.props.collapse && !this.props.value.length;
		}
		return this.props.collapse && !this.props.value;
	},

	buildFilters () {
		var filters = {};

		_.each(this.props.filters, function(value, key) {
			if(_.isString(value) && value[0] == ':') {//eslint-disable-line eqeqeq
				var fieldName = value.slice(1);

				var val = this.props.values[fieldName];
				if (val) {
					filters[key] = val;
					return;
				}

				// check if filtering by id and item was already saved
				if (fieldName === ':_id' && Keystone.item) {
					filters[key] = Keystone.item.id;
					return;
				}
			} else {
				filters[key] = value;
			}
		}, this);

		var parts = [];

		_.each(filters, function (val, key) {
			parts.push('filters[' + key + ']=' + encodeURIComponent(val));
		});

		return parts.join('&');
	},

	cacheItem (item) {
		item.href = '/keystone/' + this.props.refList.path + '/' + item.id;
		this._itemsCache[item.id] = item;
	},

	loadValue (values) {
		if (!values) {
			return this.setState({
				loading: false,
				value: null,
			});
		};
		values = Array.isArray(values) ? values : values.split(",");
		let cachedValues = values.map(i => this._itemsCache[i]).filter(i => i);
		if (cachedValues.length === values.length) {
			this.setState({
				loading: false,
				value: this.props.many ? cachedValues : cachedValues[0],
			});
			return;
		}
		this.setState({
			loading: true,
			value: null,
		});
		async.map(values, (value, done) => {
			xhr({
				url: '/keystone/api/' + this.props.refList.path + '/' + value + '?basic',
				responseType: 'json',
			}, (err, resp, data) => {
				if (err || !data) return done(err);
				this.cacheItem(data);
				done(err, data);
			});
		}, (err, expanded) => {
			if (!this.isMounted()) return;
			this.setState({
				loading: false,
				value: this.props.many ? expanded : expanded[0],
			});
		});
	},

	loadOptions (input, callback) {
		// TODO: Implement filters
		xhr({
			url: '/keystone/api/' + this.props.refList.path + '?basic&search=' + input,
			responseType: 'json',
		}, (err, resp, data) => {
			if (err) {
				console.error('Error loading items:', err);
				return callback(null, []);
			}
			data.results.forEach(this.cacheItem);
			callback(null, {
				options: data.results,
				complete: data.results.length === data.count,
			});
		});
	},

	valueChanged (value) {
		this.props.onChange({
			path: this.props.path,
			value: value,
		});
	},

	renderSelect (noedit) {
		return (
			<Select.Async
				multi={this.props.many}
				disabled={noedit}
				loadOptions={this.loadOptions}
				labelKey="name"
				name={this.props.path}
				onChange={this.valueChanged}
				simpleValue
				value={this.state.value}
				valueKey="id"
			/>
		);
	},

	renderValue () {
		return this.renderSelect(true);
	},

	renderField () {
		return this.renderSelect();
	}

});
<|endoftext|>


<commit_before>'use strict';
(function(module){
  function Project(project){
    for(var key in project){
      this[key] = project[key];
    }
    this.projectTotal = Project.projectLines(this.code);
  }

  Project.all = [];
  Project.reposArray = [];

  //Method that compiles the project template and returns it.
  Project.prototype.toHtml = function(){
    var $source = $('#project-template').html();
    var template = Handlebars.compile($source);
    return template(this);
  };

  //Method that populates the Project.all property
  Project.loadAll = function(data){
    data.map(function(ele) {
      Project.all.push(new Project(ele));
    });
  };

  //Method that is used to populate the projectTotal property
  Project.projectLines = function(code){
    return code.reduce(function(a, b){
      return a + b;
    });
  };

  //Method that is used to calculate the total lines of code across projects, it is called by the stats template.
  Project.totalLines = function(){
    return Project.all.map(function(project){
      return project.projectTotal;
    }).reduce(function(a, b){
      return a + b;
    }, 0);
  };

  //Method to grab each project's total lines into a format that is usable for a handlebars template
  Project.collateTotals = function(){
    return Project.all.map(function(project){
      return ('
' + project.projectName + ': '+ project.projectTotal + ' lines
');
    }).reduce(function(a, b){
      return a + b;
    });
  };

  //Method that pulls in the data from the json file in our Project object
  Project.getAll = function(next){
    $.getJSON('/data/projectData.json', function(responseData) {
      Project.loadAll(responseData);
      Project.requestRepos(Project.repoDataMerge);
      // localStorage.projectData = JSON.stringify(responseData);
      localStorage.projectData = JSON.stringify(Project.all);
      next();
    });
  };

  //Method that checks local storage for the data and determines if we use it or parse it from the json file.
  Project.fetchAll = function(next){
    if(localStorage.projectData){
      $.ajax({
        type: 'HEAD',
        url: '/data/projectData.json',
        success: function(data, textStatus, xhr){
          var eTag = xhr.getResponseHeader('ETag');
          if(!localStorage.eTag || eTag !== localStorage.eTag){
            localStorage.etTag = eTag;
            Project.getAll(next);
          }else{
            Project.loadAll(JSON.parse(localStorage.projectData));
            if (next) next();
          }
        }
      });
    }else{
      Project.getAll(next);
    }
  };

  //Method that call upon the github /repos endpoint to get all the repositories sorted by last updated from my github account filtered by non fork repos.
  Project.requestRepos = function(callback){
    $.ajax({
      url: 'https://api.github.com/users/' + gitRepo.gitUser + '/repos' + '?sort=updated',
      type: 'GET',
      headers: {'Authorization': 'token ' + gitRepo.gitToken},
      success: function(data, message, xhr){
        console.log(data);
        Project.reposArray = data.filter(function(repo){
          return repo.fork === false;
        });
        callback();
      }
    });
  };

  //Method to mutate the data in the Project.all property with updated information from the github /repos api
  Project.repoDataMerge = function(){
    Project.reposArray.forEach(function(repo){
      Project.all.forEach(function(project){
        if(repo.name === project.repoName){
          project.lastUpdated = repo.updated_at;
          project.repoUrl = repo.html_url;
        }
      });
    });
  };

  module.Project = Project;
})(window);
<commit_msg>Fixing async issue when merging in github data.<commit_after>'use strict';
(function(module){
  function Project(project){
    for(var key in project){
      this[key] = project[key];
    }
    this.projectTotal = Project.projectLines(this.code);
  }

  Project.all = [];
  Project.reposArray = [];

  //Method that compiles the project template and returns it.
  Project.prototype.toHtml = function(){
    var $source = $('#project-template').html();
    var template = Handlebars.compile($source);
    return template(this);
  };

  //Method that populates the Project.all property
  Project.loadAll = function(data){
    Project.all = data.map(function(ele) {
      return new Project(ele);
    });
  };

  //Method that is used to populate the projectTotal property
  Project.projectLines = function(code){
    return code.reduce(function(a, b){
      return a + b;
    });
  };

  //Method that is used to calculate the total lines of code across projects, it is called by the stats template.
  Project.totalLines = function(){
    return Project.all.map(function(project){
      return project.projectTotal;
    }).reduce(function(a, b){
      return a + b;
    }, 0);
  };

  //Method to grab each project's total lines into a format that is usable for a handlebars template
  Project.collateTotals = function(){
    return Project.all.map(function(project){
      return ('
' + project.projectName + ': '+ project.projectTotal + ' lines
');
    }).reduce(function(a, b){
      return a + b;
    });
  };

  //Method that pulls in the data from the json file in our Project object
  Project.getAll = function(next){
    $.getJSON('/data/projectData.json', function(responseData) {
      Project.loadAll(responseData);
      Project.requestRepos(Project.updateData(next));
    });
  };

  Project.updateData = function(next){
    return function(){
      Project.repoDataMerge();
      localStorage.projectData = JSON.stringify(Project.all);
      next();
    };
  };
  //Method that checks local storage for the data and determines if we use it or parse it from the json file.
  Project.fetchAll = function(next){
    if(localStorage.projectData){
      $.ajax({
        type: 'HEAD',
        url: '/data/projectData.json',
        success: function(data, textStatus, xhr){
          var eTag = xhr.getResponseHeader('ETag');
          if(!localStorage.eTag || eTag !== localStorage.eTag){
            localStorage.etTag = eTag;
            Project.getAll(next);
          }else{
            Project.loadAll(JSON.parse(localStorage.projectData));
            if (next) next();
          }
        }
      });
    }else{
      Project.getAll(next);
    }
  };

  //Method that call upon the github /repos endpoint to get all the repositories sorted by last updated from my github account filtered by non fork repos.
  Project.requestRepos = function(callback){
    $.ajax({
      url: 'https://api.github.com/users/' + gitRepo.gitUser + '/repos' + '?sort=updated',
      type: 'GET',
      headers: {'Authorization': 'token ' + gitRepo.gitToken},
      success: function(data, message, xhr){
        console.log(data);
        Project.reposArray = data.filter(function(repo){
          return repo.fork === false;
        });
        callback();
      }
    });
  };

  //Method to mutate the data in the Project.all property with updated information from the github /repos api
  Project.repoDataMerge = function(){
    Project.reposArray.forEach(function(repo){
      Project.all.forEach(function(project){
        if(repo.name === project.repoName){
          project.lastUpdated = new Date(repo.updated_at);
          project.repoUrl = repo.html_url;
        }
      });
    });
  };

  module.Project = Project;
})(window);
<|endoftext|>


<commit_before>$(document).ready(function () {

    $(document).on("contextmenu", function () {
        return false;
    });

    var $files = $(".files");

    var $templates = {
        "file":     $(".template.file").clone().removeClass("template"),
        "folder":   $(".template.folder").clone().removeClass("template"),
        "dirpath":  $(".path > .template.dir").clone().removeClass("template")
    };

    $(".template.file").remove();
    $(".template.folder").remove();
    $(".path > .template.dir").remove();

    $files.on("dblclick", "[data-path]", function () {
        var path = $(this).attr("data-path");
        if ($(this).hasClass("file")) {
            $API.runBash("xdg-open " + path);
            return;
        }
        readDir(path);
        return false;
    }).on("click", ".file,.folder", function (e) {
        if (!e.ctrlKey) {
            $(".file,.folder").removeClass("selected");
        }
        $(this).toggleClass("selected");
    });

    $(".path").on("click", "[data-path]", function () {
        var path = $(this).attr("data-path");
        readDir(path);
        return false;
    });

    function getPathTo(folder, fullPath) {
        var pathToFolder = "";
        return fullPath.substr(0, fullPath.indexOf(folder) + folder.length + 1);
    }

    function renderPath (path) {
        $API.setWindowTitle(path);
        var dirs = path.split("/");
        var $dirs = [];
        for (var i = 0; i < dirs.length - 1; ++i) {
            $dirs.push(
                $templates["dirpath"]
                    .clone()
                    .attr("data-path", getPathTo(dirs[i], path))
                    .text((tmp = dirs[i]) ? tmp : "root")
            );
        }

        var $path = $(".path");
        $path.find(".dir:not('.not-remove')").remove()
        $path.append($dirs);
    }

    window.readDir = function readDir (cDir) {
        $files.empty();
        renderPath(cDir);
        var commandRes = $API.runBash("ls " + cDir + " -F --group-directories-first");
        if (commandRes.stderr) {
            $files.html(commandRes.stderr);
        }
        var filesAndDirs = getFilesAndDirs(commandRes.stdout);
        for (var i = 0; i < filesAndDirs.length - 1; ++i) {
            var cFileOrDir = filesAndDirs[i];
            var isFolder = cFileOrDir.slice(-1) === "/" ? true : false;

            if (isFolder) {
                cFileOrDir = cFileOrDir.substr(0, cFileOrDir.length - 1);
            }

            var $template = $templates[isFolder ? "folder" : "file"];

            var $newFileOrDir = $template
                                    .clone()
                                    .attr("data-path", cDir + filesAndDirs[i])
            $newFileOrDir.find(".name").text(cFileOrDir)

            $files.append($newFileOrDir);
        }
    }

    readDir("/home/");

    function getFilesAndDirs (output) {
        return output.split("\n");
    }
});
<commit_msg>Alert error if it ocured.<commit_after>$(document).ready(function () {

    $(document).on("contextmenu", function () {
        return false;
    });

    var $files = $(".files");

    var $templates = {
        "file":     $(".template.file").clone().removeClass("template"),
        "folder":   $(".template.folder").clone().removeClass("template"),
        "dirpath":  $(".path > .template.dir").clone().removeClass("template")
    };

    $(".template.file").remove();
    $(".template.folder").remove();
    $(".path > .template.dir").remove();

    $files.on("dblclick", "[data-path]", function () {
        var path = $(this).attr("data-path");
        if ($(this).hasClass("file")) {

            var err = $API.runBash("xdg-open " + path).stderr;
            if (err) {
                alert("Error: " + err);
                return;
            }
            return;
        }
        readDir(path);
        return false;
    }).on("click", ".file,.folder", function (e) {
        if (!e.ctrlKey) {
            $(".file,.folder").removeClass("selected");
        }
        $(this).toggleClass("selected");
    });

    $(".path").on("click", "[data-path]", function () {
        var path = $(this).attr("data-path");
        readDir(path);
        return false;
    });

    function getPathTo(folder, fullPath) {
        var pathToFolder = "";
        return fullPath.substr(0, fullPath.indexOf(folder) + folder.length + 1);
    }

    function renderPath (path) {
        $API.setWindowTitle(path);
        var dirs = path.split("/");
        var $dirs = [];
        for (var i = 0; i < dirs.length - 1; ++i) {
            $dirs.push(
                $templates["dirpath"]
                    .clone()
                    .attr("data-path", getPathTo(dirs[i], path))
                    .text((tmp = dirs[i]) ? tmp : "root")
            );
        }

        var $path = $(".path");
        $path.find(".dir:not('.not-remove')").remove()
        $path.append($dirs);
    }

    window.readDir = function readDir (cDir) {
        $files.empty();
        renderPath(cDir);
        var commandRes = $API.runBash("ls " + cDir + " -F --group-directories-first");
        if (commandRes.stderr) {
            $files.html(commandRes.stderr);
        }
        var filesAndDirs = getFilesAndDirs(commandRes.stdout);
        for (var i = 0; i < filesAndDirs.length - 1; ++i) {
            var cFileOrDir = filesAndDirs[i];
            var isFolder = cFileOrDir.slice(-1) === "/" ? true : false;

            if (isFolder) {
                cFileOrDir = cFileOrDir.substr(0, cFileOrDir.length - 1);
            }

            var $template = $templates[isFolder ? "folder" : "file"];

            var $newFileOrDir = $template
                                    .clone()
                                    .attr("data-path", cDir + filesAndDirs[i])
            $newFileOrDir.find(".name").text(cFileOrDir)

            $files.append($newFileOrDir);
        }
    }

    readDir("/home/");

    function getFilesAndDirs (output) {
        return output.split("\n");
    }
});
<|endoftext|>


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

'use strict';

var is = require('is');
var path = require('path');
var join = path.join;
var extname = path.extname;
var rename = require('./rename');
var cmd = require('cmd-deps');
var css = require('css-deps');
var util = require('./util');
var debug = util.debug;
var colors = util.colors;
var initPlugins = require('./plugins/');

/**
 * get rename options
 * @param transform
 * @returns {object}
 */
function initRenameOptions(transform){
  if (is.fn(transform)) {
    return transform;
  }

  transform = transform || {};

  if (transform.min) {
    transform.suffix = '-min';
  }

  if (transform.debug) {
    transform.suffix = '-debug';
  }

  return transform;
}

/**
 * init options
 * @param options
 * @returns {object}
 */
function initOptions(options){
  var defaults = {
    css: {}, // { prefix: null, onpath: null }
    map: {}, // the map
    vars: {}, // the vars
    paths: {}, // the paths
    alias: {}, // the alias
    cache: true, // use memory file cahe
    ignore: [], // omit the given dependencies when include
    wwwroot: '', // web root
    rename: null, // { debug: boolean, min: boolean }
    plugins: null, // file trnasport plugins
    include: 'relative', // include model: self, relative, all
    idleading: '{{name}}/{{version}}/{{file}}' // the id prefix template
  };

  // mix
  util.extend(true, defaults, options);

  // wwwroot must be string
  if (!is.string(defaults.wwwroot)) {
    util.throwError('options.wwwroot\'s value should be string.');
  }

  // init wwwroot
  defaults.wwwroot = join(util.cwd, defaults.wwwroot);
  // init plugins
  defaults.plugins = initPlugins(defaults.plugins);
  // init css settings
  defaults.css = defaults.css || {};
  // init rename
  defaults.rename = initRenameOptions(defaults.rename);
  // init ignore
  defaults.ignore = Array.isArray(defaults.ignore) ? defaults.ignore : [];
  // init js settings
  defaults.js = defaults.js || {};
  // init js flags
  if (!defaults.js.hasOwnProperty('flags')) {
    defaults.js.flags = ['async'];
  }

  return defaults;
}

/**
 * resolve id leading
 * @param idleading
 * @param path
 * @param pkg
 * @returns {string}
 */
function resolveIdleading(idleading, path, pkg){
  return is.fn(idleading) ? idleading(path, pkg) : idleading;
}

/**
 * transport vinyl id
 * @param vinyl
 * @param options
 * @returns {string}
 */
function transportId(vinyl, options){
  var id;
  var pkg = util.parsePackage(vinyl, options.wwwroot);
  var idleading = resolveIdleading(options.idleading, vinyl.path, pkg);

  // get id
  id = util.template(idleading, pkg);
  // rename id
  id = util.addExt(id);
  id = rename(id, options.rename);
  id = util.hideExt(id);

  // seajs has hacked css before 3.0.0
  // https://github.com/seajs/seajs/blob/2.2.1/src/util-path.js#L49
  // demo https://github.com/popomore/seajs-test/tree/master/css-deps
  if (extname(id) === '.css') {
    id += '.js';
  }

  // normalize id
  id = util.normalize(id);
  id = path.normalize(id);
  id = id.replace(/^\/\//, '/');

  // debug
  debug('transport id: %s', colors.magenta(id));

  // rewrite vinyl path
  if (util.isAbsolute(id)) {
    vinyl.path = join(options.wwwroot, util.addExt(id));
  } else {
    vinyl.path = join(vinyl.cwd, vinyl.base, util.addExt(id));
  }

  // parse map
  id = util.parseMap(id, options.map);

  // set vinyl package info
  vinyl.package = util.extend(pkg, { id: id });

  return id;
}

/**
 * transport cmd dependencies.
 * @param vinyl
 * @param options
 * @returns {object}
 */
function transportDeps(vinyl, options){
  var deps = [];
  var include = [];
  var vars = options.vars;
  var alias = options.alias;
  var paths = options.paths;
  var pkg = vinyl.package || {};

  // replace require and collect dependencies
  vinyl.contents = new Buffer(cmd(vinyl.contents.toString(), function (id, flag){
    // parse id form alias, paths, vars
    id = util.parseAlias(id, alias);
    id = util.parsePaths(id, paths);
    id = util.parseAlias(id, alias);
    id = util.parseVars(id, vars);
    id = util.parseAlias(id, alias);

    // id is not a local file
    if (!util.isLocal(id)) {
      // cache dependencie id
      deps.push(id);
    } else {
      var path;

      // normalize id
      id = util.normalize(id);

      // if end with /, find index file
      if (id.substring(id.length - 1) === '/') {
        id += 'index';
      }

      // debug
      debug('transport%s deps: %s', flag ? ' ' + flag : '', colors.magenta(id));

      // add extname
      path = util.addExt(id);
      // rename id
      id = rename(path, options.rename);
      // hide extname
      id = util.hideExt(id);

      // seajs has hacked css before 3.0.0
      // https://github.com/seajs/seajs/blob/2.2.1/src/util-path.js#L49
      // demo https://github.com/popomore/seajs-test/tree/master/css-deps
      if (extname(id) === '.css') {
        id += '.js';
      }

      // normalize id
      id = util.normalize(id);
      // parse map
      id = util.parseMap(id, options.map);

      // cache dependencie id and path
      if (flag === null) {
        // cache dependencie id
        deps.push(id);

        // get absolute path
        path = util.resolve(path, vinyl, options.wwwroot);

        // cache dependencie absolute path
        include.push({
          id: id,
          path: path
        });
      }
    }

    return id;
  }, options.js.flags));

  // cache file dependencies
  vinyl.package = util.extend(pkg, {
    include: include,
    dependencies: deps
  });

  return deps;
}

/**
 * transport css dependencies.
 * @param vinyl
 * @param options
 * @returns {Array}
 */
function transportCssDeps(vinyl, options){
  var deps = [];
  var include = [];
  var pkg = vinyl.package || {};
  var onpath = options.css.onpath;
  var prefix = options.css.prefix;

  // init css settings
  onpath = is.fn(onpath) ? function (path, property){
    return options.css.onpath(path, property, vinyl.path, options.wwwroot);
  } : null;
  prefix = is.fn(prefix) ? prefix(vinyl.path, options.wwwroot) : prefix;

  // replace imports and collect dependencies
  vinyl.contents = new Buffer(css(vinyl.contents, function (id){
    var path;

    // id is not a local file
    if (!util.isLocal(id)) {
      // cache dependencie id
      deps.push(id);
    } else {
      // normalize id
      id = util.normalize(id);

      var isRelative = util.isRelative(id);
      var isAbsolute = util.isAbsolute(id);

      // css import parsing rules using html
      if (!isAbsolute && !isRelative) {
        id = './' + id;
      }

      // if end with /, find index file
      if (id.substring(id.length - 1) === '/') {
        id += 'index.css';
      }

      // debug
      debug('transport deps: %s', colors.magenta(id));

      // add extname
      path = util.addExt(id);
      // rename id
      id = rename(path, options.rename);
      // hide extname
      id = util.hideExt(id);

      // seajs has hacked css before 3.0.0
      // https://github.com/seajs/seajs/blob/2.2.1/src/util-path.js#L49
      // demo https://github.com/popomore/seajs-test/tree/master/css-deps
      if (extname(id) === '.css') {
        id += '.js';
      }

      // normalize id
      id = util.normalize(id);
      // parse map
      id = util.parseMap(id, options.map);

      // get absolute path
      path = util.resolve(path, vinyl, options.wwwroot);

      // cache dependencie id
      deps.push(id);
      // cache dependencie absolute path
      include.push({
        id: id,
        path: path
      });
    }

    // delete all import
    return false;
  }, { prefix: prefix, onpath: onpath }));

  // Cache file dependencies
  vinyl.package = util.extend(pkg, {
    include: include,
    dependencies: deps
  });

  return deps;
}

/**
 * exports module
 */
exports.initOptions = initOptions;
exports.transportId = transportId;
exports.transportDeps = transportDeps;
exports.transportCssDeps = transportCssDeps;
<commit_msg>bug fixed<commit_after>/**
 * Created by nuintun on 2015/4/27.
 */

'use strict';

var is = require('is');
var path = require('path');
var join = path.join;
var extname = path.extname;
var rename = require('./rename');
var cmd = require('cmd-deps');
var css = require('css-deps');
var util = require('./util');
var debug = util.debug;
var colors = util.colors;
var initPlugins = require('./plugins/');

/**
 * get rename options
 * @param transform
 * @returns {object}
 */
function initRenameOptions(transform){
  if (is.fn(transform)) {
    return transform;
  }

  transform = transform || {};

  if (transform.min) {
    transform.suffix = '-min';
  }

  if (transform.debug) {
    transform.suffix = '-debug';
  }

  return transform;
}

/**
 * init options
 * @param options
 * @returns {object}
 */
function initOptions(options){
  var defaults = {
    css: {}, // { prefix: null, onpath: null }
    map: {}, // the map
    vars: {}, // the vars
    paths: {}, // the paths
    alias: {}, // the alias
    cache: true, // use memory file cahe
    ignore: [], // omit the given dependencies when include
    wwwroot: '', // web root
    rename: null, // { debug: boolean, min: boolean }
    plugins: null, // file trnasport plugins
    include: 'relative', // include model: self, relative, all
    idleading: '{{name}}/{{version}}/{{file}}' // the id prefix template
  };

  // mix
  util.extend(true, defaults, options);

  // wwwroot must be string
  if (!is.string(defaults.wwwroot)) {
    util.throwError('options.wwwroot\'s value should be string.');
  }

  // init wwwroot
  defaults.wwwroot = join(util.cwd, defaults.wwwroot);
  // init plugins
  defaults.plugins = initPlugins(defaults.plugins);
  // init css settings
  defaults.css = defaults.css || {};
  // init rename
  defaults.rename = initRenameOptions(defaults.rename);
  // init ignore
  defaults.ignore = Array.isArray(defaults.ignore) ? defaults.ignore : [];
  // init js settings
  defaults.js = defaults.js || {};
  // init js flags
  if (!defaults.js.hasOwnProperty('flags')) {
    defaults.js.flags = ['async'];
  }

  return defaults;
}

/**
 * resolve id leading
 * @param idleading
 * @param path
 * @param pkg
 * @returns {string}
 */
function resolveIdleading(idleading, path, pkg){
  return is.fn(idleading) ? idleading(path, pkg) : idleading;
}

/**
 * transport vinyl id
 * @param vinyl
 * @param options
 * @returns {string}
 */
function transportId(vinyl, options){
  var id;
  var pkg = util.parsePackage(vinyl, options.wwwroot);
  var idleading = resolveIdleading(options.idleading, vinyl.path, pkg);

  // get id
  id = util.template(idleading, pkg);
  // rename id
  id = util.addExt(id);
  id = rename(id, options.rename);
  id = util.hideExt(id);

  // seajs has hacked css before 3.0.0
  // https://github.com/seajs/seajs/blob/2.2.1/src/util-path.js#L49
  // demo https://github.com/popomore/seajs-test/tree/master/css-deps
  if (extname(id) === '.css') {
    id += '.js';
  }

  // normalize id
  id = util.normalize(id);
  id = id.replace(/^\.\//, '');
  id = id.replace(/^\/\//, '/');

  // debug
  debug('transport id: %s', colors.magenta(id));

  // rewrite vinyl path
  if (util.isAbsolute(id)) {
    vinyl.path = join(options.wwwroot, util.addExt(id));
  } else {
    vinyl.path = join(vinyl.cwd, vinyl.base, util.addExt(id));
  }

  // parse map
  id = util.parseMap(id, options.map);

  // set vinyl package info
  vinyl.package = util.extend(pkg, { id: id });

  return id;
}

/**
 * transport cmd dependencies.
 * @param vinyl
 * @param options
 * @returns {object}
 */
function transportDeps(vinyl, options){
  var deps = [];
  var include = [];
  var vars = options.vars;
  var alias = options.alias;
  var paths = options.paths;
  var pkg = vinyl.package || {};

  // replace require and collect dependencies
  vinyl.contents = new Buffer(cmd(vinyl.contents.toString(), function (id, flag){
    // parse id form alias, paths, vars
    id = util.parseAlias(id, alias);
    id = util.parsePaths(id, paths);
    id = util.parseAlias(id, alias);
    id = util.parseVars(id, vars);
    id = util.parseAlias(id, alias);

    // id is not a local file
    if (!util.isLocal(id)) {
      // cache dependencie id
      deps.push(id);
    } else {
      var path;

      // normalize id
      id = util.normalize(id);

      // if end with /, find index file
      if (id.substring(id.length - 1) === '/') {
        id += 'index';
      }

      // debug
      debug('transport%s deps: %s', flag ? ' ' + flag : '', colors.magenta(id));

      // add extname
      path = util.addExt(id);
      // rename id
      id = rename(path, options.rename);
      // hide extname
      id = util.hideExt(id);

      // seajs has hacked css before 3.0.0
      // https://github.com/seajs/seajs/blob/2.2.1/src/util-path.js#L49
      // demo https://github.com/popomore/seajs-test/tree/master/css-deps
      if (extname(id) === '.css') {
        id += '.js';
      }

      // normalize id
      id = util.normalize(id);
      // parse map
      id = util.parseMap(id, options.map);

      // cache dependencie id and path
      if (flag === null) {
        // cache dependencie id
        deps.push(id);

        // get absolute path
        path = util.resolve(path, vinyl, options.wwwroot);

        // cache dependencie absolute path
        include.push({
          id: id,
          path: path
        });
      }
    }

    return id;
  }, options.js.flags));

  // cache file dependencies
  vinyl.package = util.extend(pkg, {
    include: include,
    dependencies: deps
  });

  return deps;
}

/**
 * transport css dependencies.
 * @param vinyl
 * @param options
 * @returns {Array}
 */
function transportCssDeps(vinyl, options){
  var deps = [];
  var include = [];
  var pkg = vinyl.package || {};
  var onpath = options.css.onpath;
  var prefix = options.css.prefix;

  // init css settings
  onpath = is.fn(onpath) ? function (path, property){
    return options.css.onpath(path, property, vinyl.path, options.wwwroot);
  } : null;
  prefix = is.fn(prefix) ? prefix(vinyl.path, options.wwwroot) : prefix;

  // replace imports and collect dependencies
  vinyl.contents = new Buffer(css(vinyl.contents, function (id){
    var path;

    // id is not a local file
    if (!util.isLocal(id)) {
      // cache dependencie id
      deps.push(id);
    } else {
      // normalize id
      id = util.normalize(id);

      var isRelative = util.isRelative(id);
      var isAbsolute = util.isAbsolute(id);

      // css import parsing rules using html
      if (!isAbsolute && !isRelative) {
        id = './' + id;
      }

      // if end with /, find index file
      if (id.substring(id.length - 1) === '/') {
        id += 'index.css';
      }

      // debug
      debug('transport deps: %s', colors.magenta(id));

      // add extname
      path = util.addExt(id);
      // rename id
      id = rename(path, options.rename);
      // hide extname
      id = util.hideExt(id);

      // seajs has hacked css before 3.0.0
      // https://github.com/seajs/seajs/blob/2.2.1/src/util-path.js#L49
      // demo https://github.com/popomore/seajs-test/tree/master/css-deps
      if (extname(id) === '.css') {
        id += '.js';
      }

      // normalize id
      id = util.normalize(id);
      // parse map
      id = util.parseMap(id, options.map);

      // get absolute path
      path = util.resolve(path, vinyl, options.wwwroot);

      // cache dependencie id
      deps.push(id);
      // cache dependencie absolute path
      include.push({
        id: id,
        path: path
      });
    }

    // delete all import
    return false;
  }, { prefix: prefix, onpath: onpath }));

  // Cache file dependencies
  vinyl.package = util.extend(pkg, {
    include: include,
    dependencies: deps
  });

  return deps;
}

/**
 * exports module
 */
exports.initOptions = initOptions;
exports.transportId = transportId;
exports.transportDeps = transportDeps;
exports.transportCssDeps = transportCssDeps;
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var gutil = require('gulp-util');
var constants = require('./constants');
var fs = require('fs');
var PluginError = gutil.PluginError;

module.exports.find = function (options) {
  if (!options.platform.match(/^win/)) {
    return 'xbuild';
  }

  var version;

  var env_var_dir = process.env['ProgramFiles(x86)'] || process.env['ProgramFiles'];
  var is64Bit = options.architecture === 'x64';

  if (options.toolsVersion === 'auto') {
    // ported from https://github.com/stevewillcock/grunt-msbuild/blob/master/tasks/msbuild.js#L167-L181
    var msbuildDir = path.join(env_var_dir, 'MSBuild');

    if (fs.existsSync(msbuildDir)) {
       var msbuildVersions = fs.readdirSync(msbuildDir)
           .filter(function(entryName) {
               return entryName.indexOf('1') === 0;
           });

       if (msbuildVersions.length > 0) {
           // set latest installed msbuild version
           options.toolsVersion = parseFloat(msbuildVersions.pop());
       }
    } else {
      options.toolsVersion = '4.0';
    }
  }
  version = constants.MSBUILD_VERSIONS[options.toolsVersion];

  if (!version) {
    throw new PluginError(constants.PLUGIN_NAME, 'No MSBuild Version was supplied!');
  }

  if (version === '12.0' || version === '14.0') {
    // On 64-bit systems msbuild is always under the x86 directory. If this
    // doesn't exist we are on a 32-bit system. See also:
    // https://blogs.msdn.microsoft.com/visualstudio/2013/07/24/msbuild-is-now-part-of-visual-studio/
    var pathRoot = env_var_dir || path.join('C:', is64Bit ? 'Program Files (x86)' : 'Program Files');
    var x64_dir = is64Bit ? 'amd64' : '';
    return path.join(pathRoot, 'MSBuild', version, 'Bin', x64_dir, 'MSBuild.exe');
  }

  var framework = is64Bit ? 'Framework64' : 'Framework';
  return path.join(options.windir, 'Microsoft.Net', framework, version, 'MSBuild.exe');
};
<commit_msg>Checking for Bin folder presence<commit_after>'use strict';

var path = require('path');
var gutil = require('gulp-util');
var constants = require('./constants');
var fs = require('fs');
var PluginError = gutil.PluginError;

module.exports.find = function (options) {
  if (!options.platform.match(/^win/)) {
    return 'xbuild';
  }

  var version;

  var env_var_dir = process.env['ProgramFiles(x86)'] || process.env['ProgramFiles'];
  var is64Bit = options.architecture === 'x64';

  if (options.toolsVersion === 'auto') {
    // ported from https://github.com/stevewillcock/grunt-msbuild/blob/master/tasks/msbuild.js#L167-L181
    var msbuildDir = path.join(env_var_dir, 'MSBuild');

    if (fs.existsSync(msbuildDir)) {
       var msbuildVersions = fs.readdirSync(msbuildDir)
           .filter(function(entryName) {
              var binDirExists = true;
              var binDirPath = path.join(msbuildDir, entryName, 'Bin');
              try {
                fs.statSync(binDirPath);
              } catch (e) {
                binDirExists = false;
              }
               return entryName.indexOf('1') === 0 && binDirExists;
           });

       if (msbuildVersions.length > 0) {
           // set latest installed msbuild version
           options.toolsVersion = parseFloat(msbuildVersions.pop());
       } else {
        options.toolsVersion = 4.0;
       }
    } else {
      options.toolsVersion = 4.0;
    }
  }
  version = constants.MSBUILD_VERSIONS[options.toolsVersion];

  if (!version) {
    throw new PluginError(constants.PLUGIN_NAME, 'No MSBuild Version was supplied!');
  }

  if (version === '12.0' || version === '14.0') {
    // On 64-bit systems msbuild is always under the x86 directory. If this
    // doesn't exist we are on a 32-bit system. See also:
    // https://blogs.msdn.microsoft.com/visualstudio/2013/07/24/msbuild-is-now-part-of-visual-studio/
    var pathRoot = env_var_dir || path.join('C:', is64Bit ? 'Program Files (x86)' : 'Program Files');
    var x64_dir = is64Bit ? 'amd64' : '';
    return path.join(pathRoot, 'MSBuild', version, 'Bin', x64_dir, 'MSBuild.exe');
  }

  var framework = is64Bit ? 'Framework64' : 'Framework';
  return path.join(options.windir, 'Microsoft.Net', framework, version, 'MSBuild.exe');
};
<|endoftext|>


<commit_before>/* eslint-disable no-magic-numbers */
import React from "react";
import PropTypes from "prop-types";
import { PropTypes as CustomPropTypes } from "victory-core";
import * as d3Hierarchy from "d3-hierarchy";
import * as d3Scale from "d3-scale";
import * as d3Shape from "d3-shape";
import flare from "../../flare.js";

class VictorySunburst extends React.Component {
  static displayName = "VictorySunburst";

  static propTypes = {
    colorScale: PropTypes.oneOfType([
      PropTypes.arrayOf(PropTypes.string),
      PropTypes.oneOf([
        "grayscale", "qualitative", "heatmap", "warm", "cool", "red", "green", "blue"
      ])
    ]),
    data: PropTypes.object,
    displayCore: PropTypes.bool,
    height: CustomPropTypes.nonNegative,
    minRadians: CustomPropTypes.nonNegative,
    onArcHover: PropTypes.func,
    radius: PropTypes.func,
    sort: PropTypes.bool,
    width: CustomPropTypes.nonNegative
  };

  static defaultProps = {
    colorScale: d3Scale.schemeCategory20,
    data: flare,
    displayCore: false,
    height: 700,
    minRadians: 0,
    radius: (width, height) => Math.min(width, height) / 2,
    sort: true,
    width: 700
  };

  drawSunburst() {
    const {
      colorScale,
      data,
      displayCore,
      height,
      minRadians,
      onArcHover,
      radius: getRadius,
      sort,
      width
    } = this.props;

    const radius = getRadius(width, height);
    const color = d3Scale.scaleOrdinal(colorScale);
    const partition = d3Hierarchy.partition();

    const xScale = d3Scale.scaleLinear()
      .range([0, Math.PI * 2]);

    const yScale = d3Scale.scaleSqrt()
      .range([0, radius]);

    const arc = d3Shape.arc()
      .startAngle((d) => xScale(d.x0))
      .endAngle((d) => xScale(d.x1))
      .innerRadius((d) => yScale(d.y0))
      .outerRadius((d) => yScale(d.y1));

    const root = d3Hierarchy.hierarchy(data, (d) => d.children)
      .sum((d) => {
        return d.children ? 0 : 1;
      })
      .sort(sort ? (a, b) => {
        return b.value - a.value;
      } : null);

    const nodes = partition(root).descendants()
      .filter((d) => {
        return (d.x1 - d.x0) > minRadians;
      });

    const sunburstArcs = nodes.map((node, i) => (
      <path
        key={`arc-${i}`}
        d={arc(node)}
        display={node.depth || displayCore ? null : "none"}
        fill={color((node.children ? node : node.parent).data.name)}
        onMouseOver={() => onArcHover(node)}
        style={{ cursor: "pointer" }}
        stroke="white"
      />
    ));

    return sunburstArcs;
  }

  render() {
    const { height, width } = this.props;

    return (
      <svg width={width} height={height}>
        <g transform={`translate(${width / 2},${height / 2})`}>
          {this.drawSunburst()}
        </g>
      </svg>
    );
  }
}

export default VictorySunburst;
<commit_msg>hide tooltip on mouseout<commit_after>/* eslint-disable no-magic-numbers */
import React from "react";
import PropTypes from "prop-types";
import { PropTypes as CustomPropTypes } from "victory-core";
import * as d3Hierarchy from "d3-hierarchy";
import * as d3Scale from "d3-scale";
import * as d3Shape from "d3-shape";
import flare from "../../flare.js";

class VictorySunburst extends React.Component {
  static displayName = "VictorySunburst";

  static propTypes = {
    colorScale: PropTypes.oneOfType([
      PropTypes.arrayOf(PropTypes.string),
      PropTypes.oneOf([
        "grayscale", "qualitative", "heatmap", "warm", "cool", "red", "green", "blue"
      ])
    ]),
    data: PropTypes.object,
    displayCore: PropTypes.bool,
    height: CustomPropTypes.nonNegative,
    minRadians: CustomPropTypes.nonNegative,
    onArcHover: PropTypes.func,
    radius: PropTypes.func,
    sort: PropTypes.bool,
    width: CustomPropTypes.nonNegative
  };

  static defaultProps = {
    colorScale: d3Scale.schemeCategory20,
    data: flare,
    displayCore: false,
    height: 700,
    minRadians: 0,
    radius: (width, height) => Math.min(width, height) / 2,
    sort: true,
    width: 700
  };

  drawSunburst() {
    const {
      colorScale,
      data,
      displayCore,
      height,
      minRadians,
      onArcHover,
      radius: getRadius,
      sort,
      width
    } = this.props;

    const radius = getRadius(width, height);
    const color = d3Scale.scaleOrdinal(colorScale);
    const partition = d3Hierarchy.partition();

    const xScale = d3Scale.scaleLinear()
      .range([0, Math.PI * 2]);

    const yScale = d3Scale.scaleSqrt()
      .range([0, radius]);

    const arc = d3Shape.arc()
      .startAngle((d) => xScale(d.x0))
      .endAngle((d) => xScale(d.x1))
      .innerRadius((d) => yScale(d.y0))
      .outerRadius((d) => yScale(d.y1));

    const root = d3Hierarchy.hierarchy(data, (d) => d.children)
      .sum((d) => {
        return d.children ? 0 : 1;
      })
      .sort(sort ? (a, b) => {
        return b.value - a.value;
      } : null);

    const nodes = partition(root).descendants()
      .filter((d) => {
        return (d.x1 - d.x0) > minRadians;
      });

    const sunburstArcs = nodes.map((node, i) => (
      <path
        key={`arc-${i}`}
        d={arc(node)}
        display={node.depth || displayCore ? null : "none"}
        fill={color((node.children ? node : node.parent).data.name)}
        onMouseOver={() => onArcHover(node)}
        onMouseOut={() => onArcHover()}
        style={{ cursor: "pointer" }}
        stroke="white"
      />
    ));

    return sunburstArcs;
  }

  render() {
    const { height, width } = this.props;

    return (
      <svg width={width} height={height}>
        <g transform={`translate(${width / 2},${height / 2})`}>
          {this.drawSunburst()}
        </g>
      </svg>
    );
  }
}

export default VictorySunburst;
<|endoftext|>