<commit_before>/**
 * Library for working with an entry.
 *
 * This source code is licensed under the MIT-style license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * Author: Chris Zieba (zieba.chris@gmail.com)
*/

var dodgercms = dodgercms || {};

dodgercms.entry = (function() {
  'use strict';

  var DATA_KEY = '.dodgercms/data.json';

  /**
   * When an entry gets deleted.
   *
   * @param {String} key Access key
   * @param {String} dataBucket Bucket where the markdown files are
   * @param {String} siteBucket Bucket for the front end website
   * @param {Function} callback Callback function
  */
  function remove(key, dataBucket, siteBucket, callback) {
    dodgercms.s3.deleteObjects(key, dataBucket, function(err, data) {
      if (err) {
        callback(err);
      } else {
        dodgercms.s3.deleteObjects(key, siteBucket, function(err, data) {
          if (err) {
            callback(err);
          } else {
            callback(null, data);
          }
        });
      }
    });
  }

  /**
   * When an entry gets renamed.
   *
   * @param {String} source The original location of the key
   * @param {String} target The new location of the key
   * @param {String} dataBucket Bucket where the markdown files are
   * @param {String} siteBucket Bucket for the front end website
   * @param {Function} callback Callback function
  */
  function rename(source, target, dataBucket, siteBucket, callback) {
    dodgercms.s3.renameObjects(source, target, dataBucket, function(err, data) {
      if (err) {
        callback(err);
      } else {
        dodgercms.s3.renameObjects(source, target, siteBucket, function(err, data) {
          if (err) {
            callback(err);
          } else {
            // removes from both buckets
            remove(source, dataBucket, siteBucket, callback);
          }
        });
      }
    });
  }

  /**
   * Creates a new entry if it does not exist, or updates an existing entry.
   *
   * @param {String} key The key name
   * @param {String} title The title of the entry
   * @param {String} content The markdown content
   * @param {String} bucket The front end bucket
   * @param {String} endpoint The endpoint for the bucket
   * @param {Function} callback Callback function
  */
  function upsert(key, title, content, bucket, endpoint, callback) {
    async.waterfall([
      function(waterfallCb) {
        var options = {
          renderer: new marked.Renderer(),
          gfm: true,
          tables: true,
          breaks: false,
          pedantic: false,
          sanitize: true,
          smartLists: true,
          smartypants: true,
          highlight: function(code) {
            return hljs.highlightAuto(code).value;
          }
        };

        // Convert the content to HTML
        marked(content, options, function(err, data) {
          if (err) {
            waterfallCb(err);
          } else {
            waterfallCb(null, data);
          }
        });
      },
      // Process the templates
      function(body, waterfallCb) {
        var modified = new Date();

        var context = {
          key: key,
          title: title,
          modified: modified.toLocaleString(),
          body: body,
          bucket: bucket,
          endpoint: endpoint,
          dataKey: DATA_KEY
        };

        var entry = dodgercms.templates['entry.html'];
        var html = entry(context);

        waterfallCb(null, html);
      },
      // Upload the key to S3
      function(html, waterfallCb) {
        var params = {
          Bucket: bucket,
          Key: key,
          Body: html,
          ContentType: 'text/html; charset=UTF-8',
          Expires: 0,
          CacheControl: 'public, max-age=0, no-cache',
          Metadata: {
            'title': title
          }
        };

        dodgercms.s3.upload(params, function(err, data) {
          if (err) {
            waterfallCb(err);
          } else {
            waterfallCb(null);
          }
        });
      }
    ],
    // Callback
    function(err, result) {
      if (err) {
        callback(err);
      } else {
        callback(null, result);
      }
    });
  }

  /**
   * Generates the menu data.
   *
   * @param {String} bucket The front end bucket
   * @param {String} endpoint The endpoint for the bucket
   * @param {Function} callback Callback function
  */
  function menu(bucket, endpoint, callback) {
    async.waterfall([
      // The navigation needs to be updated
      function(waterfallCb) {
        dodgercms.s3.listObjects(null, bucket, function(err, data) {
          if (err) {
            waterfallCb(err);
          } else {
            waterfallCb(null, data);
          }
        });
      },
      // Filter unwanted files
      function(data, waterfallCb) {
        var contents = data.Contents;
        for (var i = contents.length -1; i >= 0 ; i-=1) {
          // keys beginning with a period are treated as hidden or system files
          if (contents[i].Key.substr(0, 1) === '.') {
            contents.splice(i, 1);
          }
        }

        waterfallCb(null, contents);
      },
      // Takes the files from the s3 bucket
      function(data, waterfallCb) {
        var keys = [];

        // Get each object in parallel
        async.each(data, function(object, cb) {
          dodgercms.s3.headObject(object.Key, bucket, function(err, objectData) {
            if (err) {
              cb(err);
            } else {
              // Add the Key attribute
              objectData.Key = object.Key;
              keys.push(objectData);
              cb(null);
            }
          });

        },
        function(err) {
          if (err) {
            waterfallCb(err);
          } else {
            waterfallCb(null, keys);
          }
        });
      },
      // Takes an array of keys and builds a tree
      function(keys, waterfallCb) {
        var tree = [];

        // A reference to the parentScope is needed so we can add the index if needed
        function buildFromSegments(scope, parentScope, keyParts, pathSegments, isFolder, keyLabel) {
          // Remove the first segment from the path
          var current = pathSegments.shift();

          // Keep track of the key, which is the link to the entry
          keyParts.push(current);

          // The label defaults to the current part if no other title or folder label is added
          var label = current;

          // See if that segment already exists in the current scope
          var found = findInScope(scope, current);

          // If we did not find a match, create the new object for this path segment
          if (!found) {
            var key = keyParts.join('/');

            // Check if the last part in the path segment
            if (!pathSegments.length) {
              // If the key is a folder we need to add a trailing slash
              if (isFolder) {
                key += '/';
              }

              if (keyLabel) {
                label = keyLabel;
              }
            } else {
              // If there are more parts then the key must be a folder
              key += '/';
            }

            found = {
              key: key,
              part: current,
              index: (!pathSegments.length && current === 'index') ? true : false,
              link: (isFolder) ? null : key,
              label: label,
              children: false
            };

            if (parentScope && isFolder && current === 'index') {
              parentScope.link = parentScope.key;
            }

            scope.push(found);
          } else {
            // The label needs to be applied if not already
            if (!pathSegments.length && isFolder && keyLabel) {
              found.label = keyLabel;
            }
          }

          // If there are still path segments left, we need to create
          // a children array (if we haven't already) and recurse further
          if (pathSegments.length) {
            found.children = found.children || [];
            buildFromSegments(found.children, found, keyParts, pathSegments, isFolder, keyLabel);
          }
        }

        // Attempts to find a path segment in the current scope
        function findInScope(scope, find) {
          for (var i = 0; i < scope.length; i++) {
            if (scope[i].part === find) {
              return scope[i];
            }
          }
        }

        keys.forEach(function(object) {
          var key = object.Key;
          // If it ends with a slash its a directory
          var isFolder = (key.substr(-1) === '/') ? true : false;
          var label = (isFolder) ? object.Metadata.label : object.Metadata.title;

          // Remove the last slash if is exists so there is no empty string in the split array
          var parts = object.Key.replace(/\/\s*$/, '').split('/');

          buildFromSegments(tree, null, [], parts, isFolder, label);
        });

        waterfallCb(null, tree);
      },
      // Upload the nav to the bucket
      function(data, waterfallCb) {
        var params = {
          Bucket: bucket,
          Key: DATA_KEY,
          Body: JSON.stringify(data),
          ContentType: 'application/json; charset=UTF-8',
          Expires: 0,
          CacheControl: 'public, max-age=0, no-cache'
        };
        dodgercms.s3.upload(params, function(err, data) {
          if (err) {
            waterfallCb(err);
          } else {
            waterfallCb(null, data);
          }
        });
      }
    ],
    function(err, result) {
      if (err) {
        callback(err);
      } else {
        callback(null, result);
      }
    });
  }

  return {
    upsert: upsert,
    remove: remove,
    rename: rename,
    menu: menu
  };
}());<commit_msg>Fix folder index link<commit_after>/**
 * Library for working with an entry.
 *
 * This source code is licensed under the MIT-style license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * Author: Chris Zieba (zieba.chris@gmail.com)
*/

var dodgercms = dodgercms || {};

dodgercms.entry = (function() {
  'use strict';

  var DATA_KEY = '.dodgercms/data.json';

  /**
   * When an entry gets deleted.
   *
   * @param {String} key Access key
   * @param {String} dataBucket Bucket where the markdown files are
   * @param {String} siteBucket Bucket for the front end website
   * @param {Function} callback Callback function
  */
  function remove(key, dataBucket, siteBucket, callback) {
    dodgercms.s3.deleteObjects(key, dataBucket, function(err, data) {
      if (err) {
        callback(err);
      } else {
        dodgercms.s3.deleteObjects(key, siteBucket, function(err, data) {
          if (err) {
            callback(err);
          } else {
            callback(null, data);
          }
        });
      }
    });
  }

  /**
   * When an entry gets renamed.
   *
   * @param {String} source The original location of the key
   * @param {String} target The new location of the key
   * @param {String} dataBucket Bucket where the markdown files are
   * @param {String} siteBucket Bucket for the front end website
   * @param {Function} callback Callback function
  */
  function rename(source, target, dataBucket, siteBucket, callback) {
    dodgercms.s3.renameObjects(source, target, dataBucket, function(err, data) {
      if (err) {
        callback(err);
      } else {
        dodgercms.s3.renameObjects(source, target, siteBucket, function(err, data) {
          if (err) {
            callback(err);
          } else {
            // removes from both buckets
            remove(source, dataBucket, siteBucket, callback);
          }
        });
      }
    });
  }

  /**
   * Creates a new entry if it does not exist, or updates an existing entry.
   *
   * @param {String} key The key name
   * @param {String} title The title of the entry
   * @param {String} content The markdown content
   * @param {String} bucket The front end bucket
   * @param {String} endpoint The endpoint for the bucket
   * @param {Function} callback Callback function
  */
  function upsert(key, title, content, bucket, endpoint, callback) {
    async.waterfall([
      function(waterfallCb) {
        var options = {
          renderer: new marked.Renderer(),
          gfm: true,
          tables: true,
          breaks: false,
          pedantic: false,
          sanitize: true,
          smartLists: true,
          smartypants: true,
          highlight: function(code) {
            return hljs.highlightAuto(code).value;
          }
        };

        // Convert the content to HTML
        marked(content, options, function(err, data) {
          if (err) {
            waterfallCb(err);
          } else {
            waterfallCb(null, data);
          }
        });
      },
      // Process the templates
      function(body, waterfallCb) {
        var modified = new Date();

        var context = {
          key: key,
          title: title,
          modified: modified.toLocaleString(),
          body: body,
          bucket: bucket,
          endpoint: endpoint,
          dataKey: DATA_KEY
        };

        var entry = dodgercms.templates['entry.html'];
        var html = entry(context);

        waterfallCb(null, html);
      },
      // Upload the key to S3
      function(html, waterfallCb) {
        var params = {
          Bucket: bucket,
          Key: key,
          Body: html,
          ContentType: 'text/html; charset=UTF-8',
          Expires: 0,
          CacheControl: 'public, max-age=0, no-cache',
          Metadata: {
            'title': title
          }
        };

        dodgercms.s3.upload(params, function(err, data) {
          if (err) {
            waterfallCb(err);
          } else {
            waterfallCb(null);
          }
        });
      }
    ],
    // Callback
    function(err, result) {
      if (err) {
        callback(err);
      } else {
        callback(null, result);
      }
    });
  }

  /**
   * Generates the menu data.
   *
   * @param {String} bucket The front end bucket
   * @param {String} endpoint The endpoint for the bucket
   * @param {Function} callback Callback function
  */
  function menu(bucket, endpoint, callback) {
    async.waterfall([
      // The navigation needs to be updated
      function(waterfallCb) {
        dodgercms.s3.listObjects(null, bucket, function(err, data) {
          if (err) {
            waterfallCb(err);
          } else {
            waterfallCb(null, data);
          }
        });
      },
      // Filter unwanted files
      function(data, waterfallCb) {
        var contents = data.Contents;
        for (var i = contents.length -1; i >= 0 ; i-=1) {
          // keys beginning with a period are treated as hidden or system files
          if (contents[i].Key.substr(0, 1) === '.') {
            contents.splice(i, 1);
          }
        }

        waterfallCb(null, contents);
      },
      // Takes the files from the s3 bucket
      function(data, waterfallCb) {
        var keys = [];

        // Get each object in parallel
        async.each(data, function(object, cb) {
          dodgercms.s3.headObject(object.Key, bucket, function(err, objectData) {
            if (err) {
              cb(err);
            } else {
              // Add the Key attribute
              objectData.Key = object.Key;
              keys.push(objectData);
              cb(null);
            }
          });

        },
        function(err) {
          if (err) {
            waterfallCb(err);
          } else {
            waterfallCb(null, keys);
          }
        });
      },
      // Takes an array of keys and builds a tree
      function(keys, waterfallCb) {
        var tree = [];

        // A reference to the parentScope is needed so we can add the index if needed
        function buildFromSegments(scope, parentScope, keyParts, pathSegments, isFolder, keyLabel) {
          // Remove the first segment from the path
          var current = pathSegments.shift();

          // Keep track of the key, which is the link to the entry
          keyParts.push(current);

          // The label defaults to the current part if no other title or folder label is added
          var label = current;

          // See if that segment already exists in the current scope
          var found = findInScope(scope, current);

          // If we did not find a match, create the new object for this path segment
          if (!found) {
            var key = keyParts.join('/');

            // Check if the last part in the path segment
            if (!pathSegments.length) {
              // If the key is a folder we need to add a trailing slash
              if (isFolder) {
                key += '/';
              }

              if (keyLabel) {
                label = keyLabel;
              }
            } else {
              // If there are more parts then the key must be a folder
              key += '/';
            }

            found = {
              key: key,
              part: current,
              index: (!pathSegments.length && current === 'index') ? true : false,
              // The link is filled in later if the folder contains an index
              link: (isFolder) ? null : key,
              label: label,
              children: false
            };

            // Add the link in for folders which have an index file
            if (parentScope && current === 'index') {
              parentScope.link = parentScope.key;
            }

            scope.push(found);
          } else {
            // The label needs to be applied if not already
            if (!pathSegments.length && isFolder && keyLabel) {
              found.label = keyLabel;
            }
          }

          // If there are still path segments left, we need to create
          // a children array (if we haven't already) and recurse further
          if (pathSegments.length) {
            found.children = found.children || [];
            buildFromSegments(found.children, found, keyParts, pathSegments, isFolder, keyLabel);
          }
        }

        // Attempts to find a path segment in the current scope
        function findInScope(scope, find) {
          for (var i = 0; i < scope.length; i++) {
            if (scope[i].part === find) {
              return scope[i];
            }
          }
        }

        keys.forEach(function(object) {
          var key = object.Key;
          // If it ends with a slash its a directory
          var isFolder = (key.substr(-1) === '/') ? true : false;
          var label = (isFolder) ? object.Metadata.label : object.Metadata.title;

          // Remove the last slash if is exists so there is no empty string in the split array
          var parts = object.Key.replace(/\/\s*$/, '').split('/');

          buildFromSegments(tree, null, [], parts, isFolder, label);
        });

        waterfallCb(null, tree);
      },
      // Upload the nav to the bucket
      function(data, waterfallCb) {
        var params = {
          Bucket: bucket,
          Key: DATA_KEY,
          Body: JSON.stringify(data),
          ContentType: 'application/json; charset=UTF-8',
          Expires: 0,
          CacheControl: 'public, max-age=0, no-cache'
        };
        dodgercms.s3.upload(params, function(err, data) {
          if (err) {
            waterfallCb(err);
          } else {
            waterfallCb(null, data);
          }
        });
      }
    ],
    function(err, result) {
      if (err) {
        callback(err);
      } else {
        callback(null, result);
      }
    });
  }

  return {
    upsert: upsert,
    remove: remove,
    rename: rename,
    menu: menu
  };
}());<|endoftext|>


<commit_before>var scriptsToRun = []

/* a collection of various hacks to unbreak sites, mainly due to missing window.open() support */

/* all sites - re-implements window.close, since the built-in function doesn't work correctly */

window.addEventListener('message', function (e) {
  if (e.data === 'close-window') {
    ipc.send('close-window')
  }
})

scriptsToRun.push(`
  window.close = function () {
    postMessage('close-window', '*')
  }
`)

if (window.location.hostname === 'google.com' || window.location.hostname.endsWith('.google.com')) {
  /* define window.chrome
     this is necessary because some websites (such as the Google Drive file viewer, see issue #378) check for a
     Chrome user agent, and then do things like if(chrome.<module>) {}
     so we need to define an empty chrome object to prevent errors
     */

  scriptsToRun.push(`
    window.chrome = {}
  `)
}

/* drive.google.com - fixes clicking on files to open them */

if (window.location.hostname === 'drive.google.com') {
  scriptsToRun.push(`
    var realWindowOpen = window.open

    window.open = function (url) {
      if (url) {
        return realWindowOpen(url)
      }
      return {
        document: new Proxy({}, {
          get: function () {
            return function () {
              return document.createElement('div')
            }
          },
          set: function () {
            console.warn('unpatched set', arguments)}
        }
        ),
        location: {
          replace: function (location) {
            realWindowOpen(location)
          }
        }
      }
    }
  `)
}

/* news.google.com - fixes clicking on news articles */

if (window.location.hostname === 'news.google.com') {
  scriptsToRun.push(`
    window.open = null
  `)
}

if (scriptsToRun.length > 0) {
  setTimeout(function () {
    electron.webFrame.executeJavaScript(scriptsToRun.join(';'))
  }, 0)
}
<commit_msg>workaround for google drive failing to load<commit_after>var scriptsToRun = []

/* a collection of various hacks to unbreak sites, mainly due to missing window.open() support */

/* all sites - re-implements window.close, since the built-in function doesn't work correctly */

window.addEventListener('message', function (e) {
  if (e.data === 'close-window') {
    ipc.send('close-window')
  }
})

scriptsToRun.push(`
  window.close = function () {
    postMessage('close-window', '*')
  }
`)

if (window.location.hostname === 'google.com' || window.location.hostname.endsWith('.google.com')) {
  /* define window.chrome
     this is necessary because some websites (such as the Google Drive file viewer, see issue #378) check for a
     Chrome user agent, and then do things like if(chrome.<module>) {}
     so we need to create a chrome object to prevent errors
     (https://github.com/electron/electron/issues/16587)
     */

  scriptsToRun.push(`
    window.chrome = {
      runtime: {
        connect: () => {
          return {
            onMessage: {
              addListener: () => {console.warn('chrome.runtime is not implemented')},
              removeListener: () => {console.warn('chrome.runtime is not implemented')},
            },
            postMessage: () => {console.warn('chrome.runtime is not implemented')},
            disconnect: () => {console.warn('chrome.runtime is not implemented')},
          }
        }
      }
    }
  `)
}

/* drive.google.com - fixes clicking on files to open them */

if (window.location.hostname === 'drive.google.com') {
  scriptsToRun.push(`
    var realWindowOpen = window.open

    window.open = function (url) {
      if (url) {
        return realWindowOpen(url)
      }
      return {
        document: new Proxy({}, {
          get: function () {
            return function () {
              return document.createElement('div')
            }
          },
          set: function () {
            console.warn('unpatched set', arguments)}
        }
        ),
        location: {
          replace: function (location) {
            realWindowOpen(location)
          }
        }
      }
    }
  `)
}

/* news.google.com - fixes clicking on news articles */

if (window.location.hostname === 'news.google.com') {
  scriptsToRun.push(`
    window.open = null
  `)
}

if (scriptsToRun.length > 0) {
  setTimeout(function () {
    electron.webFrame.executeJavaScript(scriptsToRun.join(';'))
  }, 0)
}
<|endoftext|>


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

  /* global ripple: false, angular: false, _: false, jQuery: false, store: false, Options: false */

  function AddressPopover($timeout, id, $filter, $parse, scope, element, attr) {
    this.$timeout = $timeout;
    this.$parse = $parse;
    this.scope = scope;
    this.element = element;

    this.cancelHidePopoverTimeout = null;
    this.cancelShowPopoverTimeout = null;
    this.tip = null;
    this.shown = false;
    this.identity = '';
    this.summ = '';
    this.rippleName = '';
    this.rpamountFilter = $filter('rpamount');
    this.popoverCreated = false;
    this.rpAddressPopoverSum = attr.rpAddressPopoverSum;
    this.rpAddressPopoverSumMinus = attr.rpAddressPopoverSumMinus;

    if (attr.rpAddressPopover && attr.rpAddressPopover != 'rp-address-popover') {
      this.identity = $parse(attr.rpAddressPopover)(scope);
    }

    this.onPopoverEnterBound = null;
    this.onPopoverLeaveBound = null;
    this.onElemLeaveBound = null;
    this.onElemEnterBound = this.onElemEnter.bind(this);
    element.bind('mouseenter', this.onElemEnterBound);

    var _this = this;
    if (attr.rpAddressPopoverLinkToCharts) {
      id.resolveName(this.identity, { tilde: true }).then(function(name) {
        _this.rippleName = name;
        if (_this.popoverCreated) {
          var data = element.data('popover');
          if (data) {
            data.options.content = _this.makeContent();
            data.setContent();
          }
        }
      });
    }

    // Make sure popover is destroyed and removed.
    scope.$on('$destroy', function onDestroyPopover() {
      $timeout.cancel(_this.cancelHidePopoverTimeout);
      _this.cancelHidePopoverTimeout = null;
      $timeout.cancel(_this.cancelShowPopoverTimeout);
      _this.cancelShowPopoverTimeout = null;
      _this.unbindHanlders();
      if (_this.tip) {
        _this.tip.remove();
        _this.tip = null;
      }
      this.scope = null;
      this.element = null;
      this.onPopoverEnterBound = null;
      this.onPopoverLeaveBound = null;
      this.onElemLeaveBound = null;
      this.onElemEnterBound = null;
    });
  }

  AddressPopover.popupDelay = 800;
  AddressPopover.hideDelay =  700;
  AddressPopover.summFilterOpts = { force_precision: 100, min_precision: 2 };

  AddressPopover.prototype.create = function() {
    if (this.rpAddressPopoverSum) {
      var nowSumm = this.$parse(this.rpAddressPopoverSum)(this.scope);
      nowSumm = this.rpamountFilter(nowSumm, AddressPopover.summFilterOpts);
      if (nowSumm != this.summ) {
        if (this.rpAddressPopoverSumMinus && nowSumm != 'n/a') {
          nowSumm = '-' + nowSumm;
        }
        this.summ = nowSumm;
      }
    }

    var options = {
      content: this.makeContent(),
      html: true,
      trigger: 'manual', placement: 'top',
      container: 'body',
      template: '

'
    };

    var popover = this.element.popover(options);
    this.tip = this.element.data('popover').tip();
    this.onPopoverEnterBound = this.onPopoverEnter.bind(this);
    this.tip.bind('mouseenter', this.onPopoverEnterBound);
    this.onPopoverLeaveBound = this.onPopoverLeave.bind(this);
    this.tip.bind('mouseleave', this.onPopoverLeaveBound);
    this.popoverCreated = true;
  }

  AddressPopover.prototype.makeContent = function() {
    var htmlContent = ['
'];
    if (this.summ) {
      htmlContent.push('
', String(this.summ), '
');
    }

    if (this.rippleName) {
      if (this.rippleName !== this.identity) {
        htmlContent.push('
', this.rippleName, '
');
      }
      htmlContent.push('', this.identity, '', '
');
      htmlContent.push('', AddressPopover.textShowInGraph, '');
    } else if (this.identity) {
      htmlContent.push(AddressPopover.textRippleAddress, ' ', this.identity);
    }
    htmlContent.push('
');
    return htmlContent.join('');
  }

  AddressPopover.prototype.showPopover = function() {
    if (!this.popoverCreated) {
      this.create();
    }

    var _this = this;
    // allow $compile to bind values to template
    this.$timeout(function() {
      _this.element.popover('show');
      _this.shown = true;
    }, 10, false);
  }

  AddressPopover.prototype.hidePopover = function() {
    if (!this.cancelHidePopoverTimeout) {
      var _this = this;
      this.cancelHidePopoverTimeout = this.$timeout(function() {
        _this.element.popover('hide');
        _this.shown = false;
      }, AddressPopover.hideDelay, false);
      this.cancelHidePopoverTimeout['finally'](function() {
        _this.cancelHidePopoverTimeout = null;
      });
    }
  }

  AddressPopover.prototype.onPopoverEnter = function() {
    if (this.cancelShowPopoverTimeout) {
      this.$timeout.cancel(this.cancelShowPopoverTimeout);
      this.cancelShowPopoverTimeout = null;
    }
    if (this.cancelHidePopoverTimeout) {
      this.$timeout.cancel(this.cancelHidePopoverTimeout);
      this.cancelHidePopoverTimeout = null;
    }
  }

  AddressPopover.prototype.onPopoverLeave = function() {
    this.hidePopover();
  }

  AddressPopover.prototype.onElemEnter = function() {
    if (!this.onElemLeaveBound) {
      this.onElemLeaveBound = this.onElemLeave.bind(this)
      this.element.bind('mouseleave', this.onElemLeaveBound);
    }

    if (this.cancelHidePopoverTimeout) {
      this.$timeout.cancel(this.cancelHidePopoverTimeout);
      this.cancelHidePopoverTimeout = null;
    } else if (!this.cancelShowPopoverTimeout) {
      this.cancelShowPopoverTimeout = this.$timeout(this.showPopover.bind(this), AddressPopover.popupDelay, false);
      this.cancelShowPopoverTimeout['finally'](this.onCancelShowPopoverTimeoutFinally.bind(this));
    }
  }

  AddressPopover.prototype.onCancelShowPopoverTimeoutFinally = function() {
    this.cancelShowPopoverTimeout = null;
  }

  AddressPopover.prototype.onElemLeave = function() {
    if (this.cancelShowPopoverTimeout) {
      this.$timeout.cancel(this.cancelShowPopoverTimeout);
      this.cancelShowPopoverTimeout = null;
    } else if (this.shown) {
      this.hidePopover();
    }
  }

  AddressPopover.prototype.unbindHanlders = function() {
    this.element.unbind('mouseenter', this.onElemEnterBound);
    this.element.unbind('mouseleave', this.onElemLeaveBound);

    if (this.tip) {
      this.tip.unbind('mouseenter', this.onPopoverEnterBound);
      this.tip.unbind('mouseleave', this.onPopoverLeaveBound);
    }
  }

  var myTemplate = require('../../templates/directives/addresspopover.jade')();
  var texts = myTemplate.split('
');

  AddressPopover.textRippleAddress = texts[0];
  AddressPopover.textShowInGraph = texts.length > 1 ? texts[1] : 'Show in graph';

  /**
   * Special popover to show ripple address with ability to double click on address to select.
   * Also can link to www.ripplecharts.com.
   * rp-address-popover-link-to-charts - show ling to ripple charts
   * rp-address-popover-sum - show full sum of according model in popover
   * rp-address-popover-sum-minus - put minus sign before sum
   */
  angular.module('directives').directive('rpAddressPopover', rpAddressPopover);

  rpAddressPopover.$inject = ['$timeout', 'rpId', '$filter', '$parse'];

  function rpAddressPopover($timeout, id, $filter, $parse) {
    return {
      restrict: 'A',
      replace: false,
      compile: function (element, attr, linker) {
        return function (scope, element, attr) {
          var p = new AddressPopover($timeout, id, $filter, $parse, scope, element, attr);
        };
      }
    };
  }
})();
<commit_msg>[FIX] addressPopover: use $templateRequest (RT-3357)<commit_after>
(function() {
  // 'use strict';

  /* global ripple: false, angular: false, _: false, jQuery: false, store: false, Options: false */

  function AddressPopover($timeout, id, $filter, $parse, scope, element, attr) {
    this.$timeout = $timeout;
    this.$parse = $parse;
    this.scope = scope;
    this.element = element;

    this.cancelHidePopoverTimeout = null;
    this.cancelShowPopoverTimeout = null;
    this.tip = null;
    this.shown = false;
    this.identity = '';
    this.summ = '';
    this.rippleName = '';
    this.rpamountFilter = $filter('rpamount');
    this.popoverCreated = false;
    this.rpAddressPopoverSum = attr.rpAddressPopoverSum;
    this.rpAddressPopoverSumMinus = attr.rpAddressPopoverSumMinus;

    if (attr.rpAddressPopover && attr.rpAddressPopover != 'rp-address-popover') {
      this.identity = $parse(attr.rpAddressPopover)(scope);
    }

    this.onPopoverEnterBound = null;
    this.onPopoverLeaveBound = null;
    this.onElemLeaveBound = null;
    this.onElemEnterBound = this.onElemEnter.bind(this);
    element.bind('mouseenter', this.onElemEnterBound);

    var _this = this;
    if (attr.rpAddressPopoverLinkToCharts) {
      id.resolveName(this.identity, { tilde: true }).then(function(name) {
        _this.rippleName = name;
        if (_this.popoverCreated) {
          var data = element.data('popover');
          if (data) {
            data.options.content = _this.makeContent();
            data.setContent();
          }
        }
      });
    }

    // Make sure popover is destroyed and removed.
    scope.$on('$destroy', function onDestroyPopover() {
      $timeout.cancel(_this.cancelHidePopoverTimeout);
      _this.cancelHidePopoverTimeout = null;
      $timeout.cancel(_this.cancelShowPopoverTimeout);
      _this.cancelShowPopoverTimeout = null;
      _this.unbindHanlders();
      if (_this.tip) {
        _this.tip.remove();
        _this.tip = null;
      }
      this.scope = null;
      this.element = null;
      this.onPopoverEnterBound = null;
      this.onPopoverLeaveBound = null;
      this.onElemLeaveBound = null;
      this.onElemEnterBound = null;
    });
  }

  AddressPopover.popupDelay = 800;
  AddressPopover.hideDelay =  700;
  AddressPopover.summFilterOpts = { force_precision: 100, min_precision: 2 };

  AddressPopover.prototype.create = function() {
    if (this.rpAddressPopoverSum) {
      var nowSumm = this.$parse(this.rpAddressPopoverSum)(this.scope);
      nowSumm = this.rpamountFilter(nowSumm, AddressPopover.summFilterOpts);
      if (nowSumm != this.summ) {
        if (this.rpAddressPopoverSumMinus && nowSumm != 'n/a') {
          nowSumm = '-' + nowSumm;
        }
        this.summ = nowSumm;
      }
    }

    var options = {
      content: this.makeContent(),
      html: true,
      trigger: 'manual', placement: 'top',
      container: 'body',
      template: '

'
    };

    var popover = this.element.popover(options);
    this.tip = this.element.data('popover').tip();
    this.onPopoverEnterBound = this.onPopoverEnter.bind(this);
    this.tip.bind('mouseenter', this.onPopoverEnterBound);
    this.onPopoverLeaveBound = this.onPopoverLeave.bind(this);
    this.tip.bind('mouseleave', this.onPopoverLeaveBound);
    this.popoverCreated = true;
  }

  AddressPopover.prototype.makeContent = function() {
    var htmlContent = ['
'];
    if (this.summ) {
      htmlContent.push('
', String(this.summ), '
');
    }

    if (this.rippleName) {
      if (this.rippleName !== this.identity) {
        htmlContent.push('
', this.rippleName, '
');
      }
      htmlContent.push('', this.identity, '', '
');
      htmlContent.push('', AddressPopover.textShowInGraph, '');
    } else if (this.identity) {
      htmlContent.push(AddressPopover.textRippleAddress, ' ', this.identity);
    }
    htmlContent.push('
');
    return htmlContent.join('');
  }

  AddressPopover.prototype.showPopover = function() {
    if (!this.popoverCreated) {
      this.create();
    }

    var _this = this;
    // allow $compile to bind values to template
    this.$timeout(function() {
      _this.element.popover('show');
      _this.shown = true;
    }, 10, false);
  }

  AddressPopover.prototype.hidePopover = function() {
    if (!this.cancelHidePopoverTimeout) {
      var _this = this;
      this.cancelHidePopoverTimeout = this.$timeout(function() {
        _this.element.popover('hide');
        _this.shown = false;
      }, AddressPopover.hideDelay, false);
      this.cancelHidePopoverTimeout['finally'](function() {
        _this.cancelHidePopoverTimeout = null;
      });
    }
  }

  AddressPopover.prototype.onPopoverEnter = function() {
    if (this.cancelShowPopoverTimeout) {
      this.$timeout.cancel(this.cancelShowPopoverTimeout);
      this.cancelShowPopoverTimeout = null;
    }
    if (this.cancelHidePopoverTimeout) {
      this.$timeout.cancel(this.cancelHidePopoverTimeout);
      this.cancelHidePopoverTimeout = null;
    }
  }

  AddressPopover.prototype.onPopoverLeave = function() {
    this.hidePopover();
  }

  AddressPopover.prototype.onElemEnter = function() {
    if (!this.onElemLeaveBound) {
      this.onElemLeaveBound = this.onElemLeave.bind(this)
      this.element.bind('mouseleave', this.onElemLeaveBound);
    }

    if (this.cancelHidePopoverTimeout) {
      this.$timeout.cancel(this.cancelHidePopoverTimeout);
      this.cancelHidePopoverTimeout = null;
    } else if (!this.cancelShowPopoverTimeout) {
      this.cancelShowPopoverTimeout = this.$timeout(this.showPopover.bind(this), AddressPopover.popupDelay, false);
      this.cancelShowPopoverTimeout['finally'](this.onCancelShowPopoverTimeoutFinally.bind(this));
    }
  }

  AddressPopover.prototype.onCancelShowPopoverTimeoutFinally = function() {
    this.cancelShowPopoverTimeout = null;
  }

  AddressPopover.prototype.onElemLeave = function() {
    if (this.cancelShowPopoverTimeout) {
      this.$timeout.cancel(this.cancelShowPopoverTimeout);
      this.cancelShowPopoverTimeout = null;
    } else if (this.shown) {
      this.hidePopover();
    }
  }

  AddressPopover.prototype.unbindHanlders = function() {
    this.element.unbind('mouseenter', this.onElemEnterBound);
    this.element.unbind('mouseleave', this.onElemLeaveBound);

    if (this.tip) {
      this.tip.unbind('mouseenter', this.onPopoverEnterBound);
      this.tip.unbind('mouseleave', this.onPopoverLeaveBound);
    }
  }

  AddressPopover.textRippleAddress = 'span(l10n) Ripple address';
  AddressPopover.textShowInGraph = 'span(l10n) Show in graph';

  /**
   * Special popover to show ripple address with ability to double click on address to select.
   * Also can link to www.ripplecharts.com.
   * rp-address-popover-link-to-charts - show ling to ripple charts
   * rp-address-popover-sum - show full sum of according model in popover
   * rp-address-popover-sum-minus - put minus sign before sum
   */
  angular.module('directives').directive('rpAddressPopover', rpAddressPopover);

  rpAddressPopover.$inject = ['$timeout', 'rpId', '$filter', '$parse', '$templateRequest'];

  function rpAddressPopover($timeout, id, $filter, $parse, $templateRequest) {
    $templateRequest('templates/' + window.lang + '/directives/addresspopover.html', false).then(function(template) {
      var texts = template.split('
');
      AddressPopover.textRippleAddress = texts[0];
      AddressPopover.textShowInGraph = texts.length > 1 ? texts[1] : AddressPopover.textShowInGraph;
    });

    return {
      restrict: 'A',
      replace: false,
      compile: function (element, attr, linker) {
        return function (scope, element, attr) {
          var p = new AddressPopover($timeout, id, $filter, $parse, scope, element, attr);
        };
      }
    };
  }
})();
<|endoftext|>


<commit_before>var elixir = require('laravel-elixir');

elixir(function(mix) {
    mix.scripts([
              'app.js',
                'config.js',
                'controllers/*.js',
                'modules/*.js',
                'directives/*.js',
                'services/*.js',
                'menu.js'
              ], 'public/js/app.js');

    mix.scripts([
            '../../../node_modules/angular-bootstrap-switch/dist/angular-bootstrap-switch.js',
            '../../../node_modules/moment/moment.js',
            '../../../node_modules/string-mask/src/string-mask.js',
            '../../../node_modules/sweetalert/dist/sweetalert-dev.js',
            '../../../node_modules/ng-file-upload/dist/ng-file-upload-shim.js',
            '../../../node_modules/ng-file-upload/dist/ng-file-upload.js',
              'dist/*.js',
      ],'public/js/dist.js');

    mix.copy([
      'resources/assets/js/scripts/'
      ],'public/js/scripts/');
});
<commit_msg>fix gulpfile.js<commit_after>var elixir = require('laravel-elixir');

elixir(function (mix) {

  mix.browserify('main.js');

  mix.scripts([
    '../../../node_modules/jquery/dist/jquery.js',
    '../../../node_modules/moment/moment.js',
    '../../../node_modules/materialize-css/dist/js/materialize.js'
  ], 'public/js/dist.js');

  mix.styles([
    "../../../node_modules/materialize-css/dist/css/materialize.css",
    "main.css"
  ],'public/css/dist.css');

  mix.copy('node_modules/materialize-css/dist/fonts', 'public/fonts');

});
<|endoftext|>


<commit_before>/**
 @file
 Original Speed Reader by Charlotte Dann
 Fork gutted and supported by Bryan Ollendyke
*/
(function ($) {
  $(document).ready(function(){
    function words_load() {
      words_set();
      word_show(0);
      word_update();
      spritz_pause(true);
    }

  /* TEXT PARSING */
  function words_set() {
    // make a tmp container to rip out HTML chars
    var tmp = document.createElement("div");
    tmp.innerHTML = $words.html();
    if (document.all) {
      words = tmp.innerText;
    }
    else {
      words = tmp.textContent;
    }
    words = words.trim().split(' ');
    for (var j = 1; j < words.length; j++) {
      words[j] = words[j].replace(/{linebreak}/g, '   ');
    }
  }
  /* ON EACH WORD */
  function word_show(i) {
    $('#spritz_progress').width(100*i/words.length+'%');
    var word = words[i];
    var stop = Math.round((word.length+1)*0.4)-1;
    $space.html('
'+word.slice(0,stop)+'

'+word[stop]+'

'+word.slice(stop+1)+'
');
  }
  function word_next() {
    i++;
    word_show(i);
  }
  function word_prev() {
    i--;
    word_show(i);
  }

  /* ITERATION FUNCTION */
  function word_update() {
    spritz = setInterval(function() {
      word_next();
      if (i+1 == words.length) {
        setTimeout(function() {
          $space.html('');
          spritz_pause(true);
          i = 0;
          word_show(0);
        }, interval);
        clearInterval(spritz);
      }
    }, interval);
  }

  /* PAUSING FUNCTIONS */
  function spritz_pause(ns) {
      if (!paused) {
      clearInterval(spritz);
      paused = true;
      $('html').addClass('paused');
    }
  }
  function spritz_play() {
    word_update();
    paused = false;
    $('html').removeClass('paused');
  }
  function spritz_flip() {
    if (paused) {
      spritz_play();
    } else {
      spritz_pause();
    }
  }

  /* SPEED FUNCTIONS */
  function spritz_speed() {
    interval = 60000/$('#spritz_wpm').val();
    if (!paused) {
      clearInterval(spritz);
      word_update();
    }
  }
  function spritz_faster() {
    $('#spritz_wpm').val(parseInt($('#spritz_wpm').val(), 10) + 50);
    spritz_speed();
  }
  function spritz_slower() {
    if ($('#spritz_wpm').val() >= 100) {
      $('#spritz_wpm').val(parseInt($('#spritz_wpm').val(), 10) - 50);
    }
    spritz_speed();
  }

  /* KEY EVENTS */
  function button_flash(btn, time) {
    var $btn = $('.controls a.'+btn);
    $btn.addClass('active');
    if (typeof(time) === 'undefined') time = 100;
    setTimeout(function() {
      $btn.removeClass('active');
    }, time);
  }
    var $wpm = $('#spritz_wpm');
    var interval = 60000/$wpm.val();
    var paused = false;
    var $space = $('#spritz_word');
    var i = 0;
    var night = false;
    var $words = $(Drupal.settings.speedreader.selector);
    /* CONTROLS */
    $('#spritz_wpm').change(function() {
      spritz_speed();
    });
    $('.controls a, .controls label').click(function() {
      switch (this.id) {
        case 'spritz_slower':
          spritz_slower(); break;
        case 'spritz_faster':
          spritz_faster(); break;
        case 'spritz_pause':
          spritz_flip(); break;
      }
      return false;
    });

    $(document).keyup(function(e) {
      if (e.target.tagName.toLowerCase() != 'body') {
        return;
      }
      switch (e.keyCode) {
        case 32:
          spritz_flip(); button_flash('pause'); break;
        case 38:
          spritz_faster(); button_flash('faster'); break;
        case 40:
          spritz_slower(); button_flash('slower'); break;
      }
    });

    /* INITIATE */
    words_load();

    $('a.toggle').click(function() {
      $(this).siblings('.togglable').slideToggle();
      return false;
    });
  });
})(jQuery);
<commit_msg>better replacement pattern to remove line endings and true white space<commit_after>/**
 @file
 Original Speed Reader by Charlotte Dann
 Fork gutted and supported by Bryan Ollendyke
*/
(function ($) {
  $(document).ready(function(){
    function words_load() {
      words_set();
      word_show(0);
      word_update();
      spritz_pause(true);
    }

  /* TEXT PARSING */
  function words_set() {
    // make a tmp container to rip out HTML chars
    var tmp = document.createElement("div");
    tmp.innerHTML = $words.html();
    if (document.all) {
      words = tmp.innerText;
    }
    else {
      words = tmp.textContent;
    }
    words = words.replace(/\s{2,}/g, ' ');
    words = words.trim().split(' ');
    for (var j = 1; j < words.length; j++) {
      words[j] = words[j].replace(/{linebreak}/g, '   ');
    }
  }
  /* ON EACH WORD */
  function word_show(i) {
    $('#spritz_progress').width(100*i/words.length+'%');
    var word = words[i];
    var stop = Math.round((word.length+1)*0.4)-1;
    $space.html('
'+word.slice(0,stop)+'

'+word[stop]+'

'+word.slice(stop+1)+'
');
  }
  function word_next() {
    i++;
    word_show(i);
  }
  function word_prev() {
    i--;
    word_show(i);
  }

  /* ITERATION FUNCTION */
  function word_update() {
    spritz = setInterval(function() {
      word_next();
      if (i+1 == words.length) {
        setTimeout(function() {
          $space.html('');
          spritz_pause(true);
          i = 0;
          word_show(0);
        }, interval);
        clearInterval(spritz);
      }
    }, interval);
  }

  /* PAUSING FUNCTIONS */
  function spritz_pause(ns) {
      if (!paused) {
      clearInterval(spritz);
      paused = true;
      $('html').addClass('paused');
    }
  }
  function spritz_play() {
    word_update();
    paused = false;
    $('html').removeClass('paused');
  }
  function spritz_flip() {
    if (paused) {
      spritz_play();
    } else {
      spritz_pause();
    }
  }

  /* SPEED FUNCTIONS */
  function spritz_speed() {
    interval = 60000/$('#spritz_wpm').val();
    if (!paused) {
      clearInterval(spritz);
      word_update();
    }
  }
  function spritz_faster() {
    $('#spritz_wpm').val(parseInt($('#spritz_wpm').val(), 10) + 50);
    spritz_speed();
  }
  function spritz_slower() {
    if ($('#spritz_wpm').val() >= 100) {
      $('#spritz_wpm').val(parseInt($('#spritz_wpm').val(), 10) - 50);
    }
    spritz_speed();
  }

  /* KEY EVENTS */
  function button_flash(btn, time) {
    var $btn = $('.controls a.'+btn);
    $btn.addClass('active');
    if (typeof(time) === 'undefined') time = 100;
    setTimeout(function() {
      $btn.removeClass('active');
    }, time);
  }
    var $wpm = $('#spritz_wpm');
    var interval = 60000/$wpm.val();
    var paused = false;
    var $space = $('#spritz_word');
    var i = 0;
    var night = false;
    var $words = $(Drupal.settings.speedreader.selector);
    /* CONTROLS */
    $('#spritz_wpm').change(function() {
      spritz_speed();
    });
    $('.controls a, .controls label').click(function() {
      switch (this.id) {
        case 'spritz_slower':
          spritz_slower(); break;
        case 'spritz_faster':
          spritz_faster(); break;
        case 'spritz_pause':
          spritz_flip(); break;
      }
      return false;
    });

    $(document).keyup(function(e) {
      if (e.target.tagName.toLowerCase() != 'body') {
        return;
      }
      switch (e.keyCode) {
        case 32:
          spritz_flip(); button_flash('pause'); break;
        case 38:
          spritz_faster(); button_flash('faster'); break;
        case 40:
          spritz_slower(); button_flash('slower'); break;
      }
    });

    /* INITIATE */
    words_load();

    $('a.toggle').click(function() {
      $(this).siblings('.togglable').slideToggle();
      return false;
    });
  });
})(jQuery);
<|endoftext|>


<commit_before>'use babel';
'use strict';
import fs from 'fs';
import path from 'path';
import os from 'os';
import glob from 'glob';
import {exec} from 'child_process';

/**
 */
export default class CMake {
  /**
   *@param {path} executable
   */
  constructor(executable) {
    this.executable = '"' + executable.trim() + '"';
    this.generators = null;
  }

  /**
   * @return {Promise}
   */
  validateExecutable() {
    const that = this;
    return new Promise((resolve, reject) => {
      if (that.generators != null) {
        resolve(that);
      } else {
        exec(that.executable + ' --help', (err, stdout, stderr) => {
          if (err || stderr.length > 0) {
            reject('failed to execute!');
          } else {
            const generators =
                stdout.toString('utf8').match(/.*\s*=\s*Generates.*/g);
            if (generators) {
              that.generators =
                  generators.map((line) => line.split('=')[0].trim());
              resolve();
            } else
              reject('failed to produce generators!');
          }
        });
      }
    });
  }

  /**
   * @param {path} cachePath
   * @return {Promise}
   */
  extractGeneratorFromCache(cachePath) {
    return new Promise(function(resolve, reject) {
      fs.readFile(cachePath, 'utf8', function(err, cache) {
        if (err) {
          reject(err);
        } else {
          const matches = cache.match(/CMAKE_GENERATOR:INTERNAL=(.*)/);
          if (matches.length != 2)
            reject('could not find generator in cmake cache!');
          else
            resolve(matches[1]);
        }
      });
    });
  }

  /**
   * @param {string} targetName
   * @param {path} buildDirectory
   * @param {boolean} parallelBuild
   * @param {Array} extraBuildArguments
   * @return {target}
   */
  createMakeFileTarget(
      targetName, buildDirectory, parallelBuild, extraBuildArguments) {
    argumentList = ['--build', buildDirectory, '--target', targetName, '--'];
    if (parallelBuild) argumentList.push('-j' + os.cpus().length);
    return {
      name: targetName,
      exec: this.executable,
      cwd: buildDirectory,
      args: argumentList.concat(extraBuildArguments),
    };
  }

  /**
   * @param {path} buildDirectory
   * @param {boolean} parallelBuild
   * @param {Array} extraBuildArguments
   * @return {Promise}
   */
  makeFileTargets(buildDirectory, parallelBuild, extraBuildArguments) {
    const that = this;
    return new Promise((resolve, reject) => {
      exec(
          that.executable + ' --build "' + buildDirectory + '" --target help',
          {cwd: buildDirectory}, (err, stdout, stderr) => {
            if (err || stderr.length > 0) {
              reject('failed to execute!');
            } else {
              let targets = [];
              const targetRegexp = /\.{3}\s(.[^\s]+)/g;
              let match = targetRegexp.exec(stdout);
              while (match != null) {
                targets.push(that.createMakeFileTarget(
                    match[1].trim(), buildDirectory, parallelBuild,
                    extraBuildArguments));
                match = targetRegexp.exec(stdout);
              }

              resolve(targets);
            }
          });
    });
  }

  /**
   * @param {string} targetName
   * @param {path} buildDirectory
   * @param {boolean} parallelBuild
   * @param {Array} extraBuildArguments
   * @return {target}
   */
  ninjaTarget(targetName, buildDirectory, parallelBuild, extraBuildArguments) {
    argumentList = ['--build', buildDirectory, '--target', targetName, '--'];
    if (parallelBuild) argumentList.push('-j' + os.cpus().length);
    return {
      name: targetName,
      exec: this.executable,
      cwd: buildDirectory,
      args: argumentList.concat(extraBuildArguments),
    };
  }

  /**
   * @param {path} buildDirectory
   * @param {boolean} parallelBuild
   * @param {Array} extraBuildArguments
   * @return {Promise}
   */
  ninjaTargets(buildDirectory, parallelBuild, extraBuildArguments) {
    const that = this;
    return new Promise((resolve, reject) => {
      exec(
          that.executable + ' --build "' + buildDirectory + '" -- -t targets',
          {cwd: buildDirectory}, (err, stdout, stderr) => {
            if (err || stderr.length > 0) {
              reject('failed to execute!');
            } else {
              let targets = [];
              const targetRegexp = /(.+):/g;
              let match = targetRegexp.exec(stdout);
              while (match != null) {
                targets.push(that.ninjaTarget(
                    match[1].trim(), buildDirectory, parallelBuild,
                    extraBuildArguments));
                match = targetRegexp.exec(stdout);
              }

              resolve(targets);
            }
          });
    });
  }

  //   createVisualStudioTarget(targetName) {
  //     argumentList =
  //         ['--build', this.buildDirectory, '--target', targetName, '--'];
  //     if (this.parallelBuild) argumentList.push('/maxcpucount');
  //     return {
  //       atomCommandName: 'cmake:' + targetName,
  //       name: targetName,
  //       exec: this.executable,
  //       cwd: this.buildDirectory,
  //       args: argumentList.concat(this.buildArguments),
  //       errorMatch: compileErrorMatch.concat(generateErrorMatch),
  //       warningMatch: compileWarningMatch.concat(generateWarningMatch),
  //     };
  //   }

  /**
   * @param {string} targetName
   * @param {path} buildDirectory
   * @param {boolean} parallelBuild
   * @param {Array} extraBuildArguments
   * @return {target}
   */
  createVisualStudioTarget(
      targetName, buildDirectory, parallelBuild, extraBuildArguments) {
    argumentList = ['--build', buildDirectory, '--target', targetName, '--'];
    if (parallelBuild) argumentList.push('/maxcpucount');
    return {
      name: targetName,
      exec: this.executable,
      cwd: buildDirectory,
      args: argumentList.concat(extraBuildArguments),
    };
  }

  /**
   * @param {path} buildDirectory
   * @param {boolean} parallelBuild
   * @param {Array} extraBuildArguments
   * @return {Promise}
   */
  visualStudioTargets(buildDirectory, parallelBuild, extraBuildArguments) {
    const that = this;
    return new Promise(function(resolve, reject) {
      glob(
          '**/*.vcxproj', {
            cwd: buildDirectory,
            nodir: true,
            ignore: 'CMakeFiles/**',
          },
          (error, files) => {
            if (error)
              reject(error);
            else
              resolve(files.map((file) => path.basename(file, '.vcxproj'))
                          .concat(['clean'])
                          .map(
                              (targetName) =>
                                  that.createVisualStudioTarget(targetName)));
          });
    });
  }

  /**
   * @param {path} sourceDirectory
   * @param {path} buildDirectory
   * @param {boolean} parallelBuild
   * @param {Array} extraBuildArguments
   * @return {Promise}
   */
  extractTargets(
      sourceDirectory, buildDirectory, parallelBuild, extraBuildArguments) {
    const that = this;
    return that
        .extractGeneratorFromCache(path.join(buildDirectory, 'CMakeCache.txt'))
        .then((generator) => {
          if (generator.match('Visual Studio'))
            return that
                .visualStudioTargets(
                    buildDirectory, parallelBuild, extraBuildArguments)
                .then((targets) => {
                  return {generator: generator, targets: targets};
                });
          else if (generator.match('Ninja'))
            return that
                .ninjaTargets(
                    buildDirectory, parallelBuild, extraBuildArguments)
                .then((targets) => {
                  return {generator: generator, targets: targets};
                });
          else if (generator.match('Unix Makefiles'))
            return that
                .makeFileTargets(
                    buildDirectory, parallelBuild, extraBuildArguments)
                .then((targets) => {
                  return {generator: generator, targets: targets};
                });
        });
  }
};
<commit_msg>Better error messages.<commit_after>'use babel';
'use strict';
import fs from 'fs';
import path from 'path';
import os from 'os';
import glob from 'glob';
import {exec} from 'child_process';

/**
 */
export default class CMake {
  /**
   *@param {path} executable
   */
  constructor(executable) {
    this.executable = '"' + executable.trim() + '"';
    this.generators = null;
  }

  /**
   * @return {Promise}
   */
  validateExecutable() {
    const that = this;
    return new Promise((resolve, reject) => {
      if (that.generators != null) {
        resolve(that);
      } else {
        exec(that.executable + ' --help', (err, stdout, stderr) => {
          if (err || stderr.length > 0) {
            reject(stderr.replace('/bin/sh: ', '').trim() + '!');
          } else {
            const generators =
                stdout.toString('utf8').match(/.*\s*=\s*Generates.*/g);
            if (generators) {
              that.generators =
                  generators.map((line) => line.split('=')[0].trim());
              resolve();
            } else
              reject(
                  'The executable "' + that.executable +
                  '" failed to produce generators!');
          }
        });
      }
    });
  }

  /**
   * @param {path} cachePath
   * @return {Promise}
   */
  extractGeneratorFromCache(cachePath) {
    return new Promise(function(resolve, reject) {
      fs.readFile(cachePath, 'utf8', function(err, cache) {
        if (err) {
          reject(err);
        } else {
          const matches = cache.match(/CMAKE_GENERATOR:INTERNAL=(.*)/);
          if (matches.length != 2)
            reject('Could not find generator in cmake cache!');
          else
            resolve(matches[1]);
        }
      });
    });
  }

  /**
   * @param {string} targetName
   * @param {path} buildDirectory
   * @param {boolean} parallelBuild
   * @param {Array} extraBuildArguments
   * @return {target}
   */
  createMakeFileTarget(
      targetName, buildDirectory, parallelBuild, extraBuildArguments) {
    argumentList = ['--build', buildDirectory, '--target', targetName, '--'];
    if (parallelBuild) argumentList.push('-j' + os.cpus().length);
    return {
      name: targetName,
      exec: this.executable,
      cwd: buildDirectory,
      args: argumentList.concat(extraBuildArguments),
    };
  }

  /**
   * @param {path} buildDirectory
   * @param {boolean} parallelBuild
   * @param {Array} extraBuildArguments
   * @return {Promise}
   */
  makeFileTargets(buildDirectory, parallelBuild, extraBuildArguments) {
    const that = this;
    return new Promise((resolve, reject) => {
      exec(
          that.executable + ' --build "' + buildDirectory + '" --target help',
          {cwd: buildDirectory}, (err, stdout, stderr) => {
            if (err || stderr.length > 0) {
              reject(stderr.replace('/bin/sh: ', '').trim() + '!');
            } else {
              let targets = [];
              const targetRegexp = /\.{3}\s(.[^\s]+)/g;
              let match = targetRegexp.exec(stdout);
              while (match != null) {
                targets.push(that.createMakeFileTarget(
                    match[1].trim(), buildDirectory, parallelBuild,
                    extraBuildArguments));
                match = targetRegexp.exec(stdout);
              }

              resolve(targets);
            }
          });
    });
  }

  /**
   * @param {string} targetName
   * @param {path} buildDirectory
   * @param {boolean} parallelBuild
   * @param {Array} extraBuildArguments
   * @return {target}
   */
  ninjaTarget(targetName, buildDirectory, parallelBuild, extraBuildArguments) {
    argumentList = ['--build', buildDirectory, '--target', targetName, '--'];
    if (parallelBuild) argumentList.push('-j' + os.cpus().length);
    return {
      name: targetName,
      exec: this.executable,
      cwd: buildDirectory,
      args: argumentList.concat(extraBuildArguments),
    };
  }

  /**
   * @param {path} buildDirectory
   * @param {boolean} parallelBuild
   * @param {Array} extraBuildArguments
   * @return {Promise}
   */
  ninjaTargets(buildDirectory, parallelBuild, extraBuildArguments) {
    const that = this;
    return new Promise((resolve, reject) => {
      exec(
          that.executable + ' --build "' + buildDirectory + '" -- -t targets',
          {cwd: buildDirectory}, (err, stdout, stderr) => {
            if (err || stderr.length > 0) {
              reject(stderr.replace('/bin/sh: ', '').trim() + '!');
            } else {
              let targets = [];
              const targetRegexp = /(.+):/g;
              let match = targetRegexp.exec(stdout);
              while (match != null) {
                targets.push(that.ninjaTarget(
                    match[1].trim(), buildDirectory, parallelBuild,
                    extraBuildArguments));
                match = targetRegexp.exec(stdout);
              }

              resolve(targets);
            }
          });
    });
  }

  /**
   * @param {string} targetName
   * @param {path} buildDirectory
   * @param {boolean} parallelBuild
   * @param {Array} extraBuildArguments
   * @return {target}
   */
  createVisualStudioTarget(
      targetName, buildDirectory, parallelBuild, extraBuildArguments) {
    argumentList = ['--build', buildDirectory, '--target', targetName, '--'];
    if (parallelBuild) argumentList.push('/maxcpucount');
    return {
      name: targetName,
      exec: this.executable,
      cwd: buildDirectory,
      args: argumentList.concat(extraBuildArguments),
    };
  }

  /**
   * @param {path} buildDirectory
   * @param {boolean} parallelBuild
   * @param {Array} extraBuildArguments
   * @return {Promise}
   */
  visualStudioTargets(buildDirectory, parallelBuild, extraBuildArguments) {
    const that = this;
    return new Promise(function(resolve, reject) {
      glob(
          '**/*.vcxproj', {
            cwd: buildDirectory,
            nodir: true,
            ignore: 'CMakeFiles/**',
          },
          (error, files) => {
            if (error)
              reject(error);
            else
              resolve(files.map((file) => path.basename(file, '.vcxproj'))
                          .concat(['clean'])
                          .map(
                              (targetName) =>
                                  that.createVisualStudioTarget(targetName)));
          });
    });
  }

  /**
   * @param {path} sourceDirectory
   * @param {path} buildDirectory
   * @param {boolean} parallelBuild
   * @param {Array} extraBuildArguments
   * @return {Promise}
   */
  extractTargets(
      sourceDirectory, buildDirectory, parallelBuild, extraBuildArguments) {
    const that = this;
    return that
        .extractGeneratorFromCache(path.join(buildDirectory, 'CMakeCache.txt'))
        .then((generator) => {
          if (generator.match('Visual Studio'))
            return that
                .visualStudioTargets(
                    buildDirectory, parallelBuild, extraBuildArguments)
                .then((targets) => {
                  return {generator: generator, targets: targets};
                });
          else if (generator.match('Ninja'))
            return that
                .ninjaTargets(
                    buildDirectory, parallelBuild, extraBuildArguments)
                .then((targets) => {
                  return {generator: generator, targets: targets};
                });
          else if (generator.match('Unix Makefiles'))
            return that
                .makeFileTargets(
                    buildDirectory, parallelBuild, extraBuildArguments)
                .then((targets) => {
                  return {generator: generator, targets: targets};
                });
        });
  }
};
<|endoftext|>


<commit_before>test(
  'ResultValueTest',

  [
    'ephox.katamari.api.Fun',
    'ephox.katamari.api.Result',
    'ephox.katamari.test.arb.ArbDataTypes',
    'ephox.wrap.Jsc'
  ],

  function (Fun, Result, ArbDataTypes, Jsc) {
    var testSanity = function () {
      var s = Result.value(5);
      assert.eq(true, s.is(5));
      assert.eq(true, s.isValue());
      assert.eq(false, s.isError());
      assert.eq(5, s.getOr(6));
      assert.eq(5, s.getOrThunk(function () { return 6; }));
      assert.eq(5, s.getOrDie());
      assert.eq(5, s.or(Result.value(6)).getOrDie());
      assert.eq(5, s.orThunk(function () {
        return Result.error('Should not get here.');
      }).getOrDie());

      assert.eq(11, s.fold(function (e) {
        throw 'Should not get here!';
      }, function (v) {
        return v + 6;
      }));

      assert.eq(10, s.map(function (v) {
        return v * 2;
      }).getOrDie());

      assert.eq('test5', s.bind(function (v) {
        return Result.value('test' + v);
      }).getOrDie());

      assert.eq(true, s.exists(Fun.always));
      assert.eq(false, s.forall(Fun.never));

      assert.eq(true, Result.value(5).toOption().isSome());
    };

    var arbResultError = ArbDataTypes.resultError;
    var arbResultValue = ArbDataTypes.resultValue;

    var testSpecs = function () {
      Jsc.property('Checking value.is(value.getOrDie()) is always true', arbResultValue, function (res) {
        return Jsc.eq(true, res.is(res.getOrDie()));
      });

      Jsc.property('Checking value.isValue is always true', arbResultValue, function (res) {
        return Jsc.eq(true, res.isValue());
      });

      Jsc.property('Checking value.isError is always false', arbResultValue, function (res) {
        return Jsc.eq(false, res.isError());
      });

      Jsc.property('Checking value.getOr(v) === value.value ', arbResultValue, 'json', function (res, json) {
        var inside = res.fold(Fun.die('no'), Fun.identity);
        return Jsc.eq(inside, json) ? true : Jsc.eq(inside, res.getOr(json)) === true;
      });

      Jsc.property('Checking value.getOrDie() does not throw', arbResultValue, function (res) {
        try {
          res.getOrDie();
          return true;
        } catch (err) {
          return false;
        }
      });

      Jsc.property('Checking value.or(oValue) = value', arbResultValue, 'json', function (res, json) {
        var inside = res.fold(Fun.die('no'), Fun.identity);
        return Jsc.eq(inside, json) ? true : Jsc.eq(inside, res.or(Result.value(json)).getOr(json)) === true;
      });

      Jsc.property('Checking value.orThunk(die) does not throw', arbResultValue, function (res) {
        try {
          res.orThunk(Fun.die('dies'));
          return true;
        } catch (err) {
          return false;
        }
      });

      Jsc.property('Checking value.fold(die, id) = value.getOrDie()', arbResultValue, 'json', function (res, json) {
        var actual = res.getOrDie();
        return Jsc.eq(actual, res.fold(Fun.die('should not get here'), Fun.identity));
      });

      Jsc.property('Checking value.map(f) = f(value.getOrDie())', arbResultValue, 'json -> json', function (res, f) {
        return Jsc.eq(res.map(f).getOrDie(), f(res.getOrDie()));
      });

      Jsc.property('Checking value.each(f) = undefined', arbResultValue, 'string -> json', function (res, f) {
        var actual = res.each(f);
        return Jsc.eq(undefined, actual);
      });

      Jsc.property('Given f :: s -> RV, checking value.bind(f).getOrDie() = f(value.getOrDie()).getOrDie()', arbResultValue, Jsc.fn(arbResultValue), function (res, f) {
        return Jsc.eq(res.bind(f).getOrDie(), f(res.getOrDie()).getOrDie());
      });

      Jsc.property('Given f :: s -> RE, checking value.bind(f).fold(id, die) = f(value.getOrDie()).fold(id, die)', arbResultValue, Jsc.fn(arbResultError), function (res, f) {
        var toErrString = function (r) {
          return r.fold(Fun.identity, Fun.die('Not a Result.error'));
        };

        return Jsc.eq(toErrString(res.bind(f)), toErrString(f(res.getOrDie())));
      });

      Jsc.property('Checking value.forall is true iff. f(value.getOrDie() === true)', arbResultValue, 'string -> bool', function (res, f) {
        return Jsc.eq(f(res.getOrDie()), res.forall(f));
      });

      Jsc.property('Checking value.exists is true iff. f(value.getOrDie() === true)', arbResultValue, 'string -> bool', function (res, f) {
        return  Jsc.eq(f(res.getOrDie()), res.exists(f));
      });

      Jsc.property('Checking value.toOption is always Option.some(value.getOrDie())', arbResultValue, function (res) {
        return Jsc.eq(res.getOrDie(), res.toOption().getOrDie());
      });
    };

    testSanity();
    testSpecs();

  }
);<commit_msg>VAN-25: cleanup of labels<commit_after>test(
  'ResultValueTest',

  [
    'ephox.katamari.api.Fun',
    'ephox.katamari.api.Result',
    'ephox.katamari.test.arb.ArbDataTypes',
    'ephox.wrap.Jsc'
  ],

  function (Fun, Result, ArbDataTypes, Jsc) {
    var testSanity = function () {
      var s = Result.value(5);
      assert.eq(true, s.is(5));
      assert.eq(true, s.isValue());
      assert.eq(false, s.isError());
      assert.eq(5, s.getOr(6));
      assert.eq(5, s.getOrThunk(function () { return 6; }));
      assert.eq(5, s.getOrDie());
      assert.eq(5, s.or(Result.value(6)).getOrDie());
      assert.eq(5, s.orThunk(function () {
        return Result.error('Should not get here.');
      }).getOrDie());

      assert.eq(11, s.fold(function (e) {
        throw 'Should not get here!';
      }, function (v) {
        return v + 6;
      }));

      assert.eq(10, s.map(function (v) {
        return v * 2;
      }).getOrDie());

      assert.eq('test5', s.bind(function (v) {
        return Result.value('test' + v);
      }).getOrDie());

      assert.eq(true, s.exists(Fun.always));
      assert.eq(false, s.forall(Fun.never));

      assert.eq(true, Result.value(5).toOption().isSome());
    };

    var arbResultError = ArbDataTypes.resultError;
    var arbResultValue = ArbDataTypes.resultValue;

    var testSpecs = function () {
      Jsc.property('Checking value.is(value.getOrDie()) === true', arbResultValue, function (res) {
        return Jsc.eq(true, res.is(res.getOrDie()));
      });

      Jsc.property('Checking value.isValue === true', arbResultValue, function (res) {
        return Jsc.eq(true, res.isValue());
      });

      Jsc.property('Checking value.isError === false', arbResultValue, function (res) {
        return Jsc.eq(false, res.isError());
      });

      Jsc.property('Checking value.getOr(v) === value.value', arbResultValue, 'json', function (res, json) {
        var inside = res.fold(Fun.die('no'), Fun.identity);
        return Jsc.eq(inside, res.getOr(json)) === true;
      });

      Jsc.property('Checking value.getOrDie() does not throw', arbResultValue, function (res) {
        try {
          res.getOrDie();
          return true;
        } catch (err) {
          return false;
        }
      });

      Jsc.property('Checking value.or(oValue) === value', arbResultValue, 'json', function (res, json) {
        var inside = res.fold(Fun.die('no'), Fun.identity);
        return Jsc.eq(inside, res.or(Result.value(json)).getOr(json)) === true;
      });

      Jsc.property('Checking value.orThunk(die) does not throw', arbResultValue, function (res) {
        try {
          res.orThunk(Fun.die('dies'));
          return true;
        } catch (err) {
          return false;
        }
      });

      Jsc.property('Checking value.fold(die, id) === value.getOrDie()', arbResultValue, 'json', function (res, json) {
        var actual = res.getOrDie();
        return Jsc.eq(actual, res.fold(Fun.die('should not get here'), Fun.identity));
      });

      Jsc.property('Checking value.map(f) === f(value.getOrDie())', arbResultValue, 'json -> json', function (res, f) {
        return Jsc.eq(res.map(f).getOrDie(), f(res.getOrDie()));
      });

      Jsc.property('Checking value.each(f) === undefined', arbResultValue, 'string -> json', function (res, f) {
        var actual = res.each(f);
        return Jsc.eq(undefined, actual);
      });

      Jsc.property('Given f :: s -> RV, checking value.bind(f).getOrDie() === f(value.getOrDie()).getOrDie()', arbResultValue, Jsc.fn(arbResultValue), function (res, f) {
        return Jsc.eq(res.bind(f).getOrDie(), f(res.getOrDie()).getOrDie());
      });

      Jsc.property('Given f :: s -> RE, checking value.bind(f).fold(id, die) === f(value.getOrDie()).fold(id, die)', arbResultValue, Jsc.fn(arbResultError), function (res, f) {
        var toErrString = function (r) {
          return r.fold(Fun.identity, Fun.die('Not a Result.error'));
        };

        return Jsc.eq(toErrString(res.bind(f)), toErrString(f(res.getOrDie())));
      });

      Jsc.property('Checking value.forall is true iff. f(value.getOrDie() === true)', arbResultValue, 'string -> bool', function (res, f) {
        return Jsc.eq(f(res.getOrDie()), res.forall(f));
      });

      Jsc.property('Checking value.exists is true iff. f(value.getOrDie() === true)', arbResultValue, 'string -> bool', function (res, f) {
        return  Jsc.eq(f(res.getOrDie()), res.exists(f));
      });

      Jsc.property('Checking value.toOption is always Option.some(value.getOrDie())', arbResultValue, function (res) {
        return Jsc.eq(res.getOrDie(), res.toOption().getOrDie());
      });
    };

    testSanity();
    testSpecs();

  }
);<|endoftext|>


<commit_before>/**
 * Created by james on 17-1-12.
 */
(function () {
    window.solarReport = {}
    solarReport.render = function (solar) {
        var tooltip = d3.select("body").append("div")
            .attr("class", "tooltip") //用于css设置类样式
            .attr("opacity", 0.0);
        solarReport.renderAppList(solar);
        solarReport.renderStaticPie(solar);
        solarReport.renderDepLines(solar);
    }
    solarReport.renderAppList = function renderAppList(solar) {
        var report = d3.select('#appList')
        report.style('height', (solar.planets.length * 0.8 + 2) + 'em')
        var svg = report.append('svg');
        svg.style('height', (solar.planets.length * 0.8 + 2) + 'em')
        //            var rect = svg.append("rect").attr({fill: '#fff', stroke: 'steelblue', height: 95, width: 290})
        svg.append('text').text('Domain Name: ' + solar.name).attr({
            fill: 'black',
            'font-size': '0.8em',
            y: '1em'
        })
        svg.append('text').text('App No.: ' + solar.planets.length).attr({
            fill: 'black',
            'font-size': '0.8em',
            y: '2em'
        })
        for (var i = 0; i < solar.planets.length; i++) {
            var planet = solar.planets[i];
            svg.append('text').html( planet.name ).attr({
                fill: 'black',
                'font-size': '0.8em',
                y: (3 + i) + 'em',
                x: '1em'
            })
        }
    }
    solarReport.doStatic = function (solar) {
        var planetStatic = solar.domainJsonObj.planetStatic;
        var validSuffix = jsonConvert.valid_suffix;

        if (planetStatic)
            return planetStatic

        planetStatic = []
        for (var i = 0; i < validSuffix.length; i++)
            planetStatic[i] = 0
        for (var i = 0; i < solar.planets.length; i++) {
            var planet = solar.planets[i]
            for (var j = 0; j < validSuffix.length; j++) {
                if (jsonConvert.endWith(planet.name, validSuffix[j])) {
                    planetStatic[j]++;
                }
            }
        }
        solar.domainJsonObj.planets = planetStatic
        return planetStatic;
    }
    solarReport.renderStaticPie = function (solar) {
        var planetTypes = solarReport.doStatic(solar)
        var dataset = []
        for (var i = 0; i < jsonConvert.valid_suffix.length; i++) {
            dataset.push([jsonConvert.valid_suffix[i], planetTypes[i]])
        }
        var pie = d3.layout.pie().value(function (d) {
            return d[1];
        })
        var piedata = pie(dataset)

        var width = 200
        var height = 200
        var outerRadius = width / 3
        var innerRadius = 0;
        var arc = d3.svg.arc().innerRadius(innerRadius).outerRadius(outerRadius)
        var color = d3.scale.category20()
        var svg = d3.select("#solarPie").append("svg").attr({width: width, height: height})
        var arcs = svg.selectAll("g").data(piedata).enter()
            .append("g")
            .attr("transform", "translate(" + (width / 2) + "," + (height / 2) + ")")
        arcs.append("path")
            .attr("fill", function (d, i) {
                return color(i)
            })
            .attr("d", function (d) {
                return arc(d)
            })
        arcs.append("text")
            .attr("transform", function (d) {
                var x = arc.centroid(d)[0] * 1.4;
                var y = arc.centroid(d)[1] * 1.4;
                return "translate(" + x + "," + y + ")";
            })
            .attr("text-anchor", "middle")
            .text(function (d) {
                var percent = Number(d.value) / d3.sum(dataset, function (d) {
                        return d[1]
                    }) * 100
                if (percent != 0)
                    return percent.toFixed(1) + "%"
            })
        arcs.append("line")
            .attr("stroke", "black")
            .attr("x1", function (d) {
                return arc.centroid(d)[0] * 2
            })
            .attr("y1", function (d) {
                return arc.centroid(d)[1] * 2
            })
            .attr("x2", function (d) {
                var longX = 2.2
                if (d.data[1] == 0)
                    longX = 2
                return arc.centroid(d)[0] * longX
            })
            .attr("y2", function (d) {
                var longY = 2.2
                if (d.data[1] == 0)
                    longY = 2
                return arc.centroid(d)[1] * longY
            })
        arcs.append("text")
            .attr("transform", function (d) {
                var x = arc.centroid(d)[0] * 2.5
                var y = arc.centroid(d)[1] * 2.5
                return "translate(" + x + "," + y + ")"
            })
            .attr("text-anchor", "middle")
            .text(function (d) {
                if (d.data[1] != 0)
                    return d.data[0]
                return ""
            })
        console.log(solar.domainJsonObj)
    }
    solarReport.renderDepLines = function (solar) {

        var static = null;
        for (var i = 0; i < atlas.depStatic.length; i++) {
            if (solar.name == atlas.depStatic[i].domain) {
                static = atlas.depStatic[i];
                break;
            }
        }
        if (!static)
            return
        var dataset = [static.dependsByApps.length, static.dependsByDomains.length, static.dependsOnApps.length, static.dependsOnDomains.length, static.biDependApps.length, static.biDependDomains.length]
        var depSet = [static.dependsByApps, static.dependsByDomains, static.dependsOnApps, static.dependsOnDomains, static.biDependApps, static.biDependDomains]
        var hintSet = ['ToPlanets', 'ToSolar', 'fromPlanets', 'fromSolar', 'biDirectPlanets', 'biDirectSolars']
        var width = 200
        var height = 300;
        var step = 30;
        var lineHeight = 20
        var lineWidthUnit = 20;
        var svg = d3.select("#depBar").append("svg").attr("width", width).attr("height", height);
        var enter = svg.selectAll('rect').data(dataset).enter();
        var rect = enter.append("rect").attr("fill", "steelblue")
            .attr('y', function (d, i) {
                return i * (lineHeight + step) + step - 5
            }).attr('x', 0)
            .attr('height', lineHeight)
            .attr('width', function (d, i) {
                var wid = d >= 10 ? 10 : d
                return wid * lineWidthUnit;
            })
            .style('cursor','help')
            .on('click', function (d, i) {
                var text = $('#depContent').text()
                if (text == "")
                    $('#depContent').html(function () {
                        var hint = hintSet[i] + ":"+depSet[i]
                        // for (var j = 0; j < depSet.length; j++)
                        //     for (var k = 0; k < depSet[i].length; k++)
                        //         hint += '\' + depSet[j][k] + '\'
                        return hint;
                    })
                else
                    $('#depContent').text("")
            })
        // var rectTran = rect.transition()
        //     .duration(2000).ease("back-in")
        //     .attrTween("width", function (d, i, a) {
        //         return function (t) {
        //             return Number(a) + t * 300
        //         }
        //     })
        var textEnter = svg.selectAll('#depBar text').data(dataset).enter()
        textEnter.append("text")
            .attr("fill", "white")
            .attr('y', function (d, i) {
                return i * (lineHeight + step) + step - 5
            })
            .attr('x', 5)
            .attr({dy: "1.2em"})
            .text(function (d, i) {
                return d
            })
        for (var i = 0; i < hintSet.length; i++) {
            svg.append("text").attr('x', 0).attr({'fill': 'steelblue', 'dy': '1.2em'}).attr('y', function () {
                return i * (step + lineHeight)
            }).text(hintSet[i])

        }
    }

}).call(this)<commit_msg>textureLoader optimized<commit_after>/**
 * Created by james on 17-1-12.
 */
(function () {
    window.solarReport = {}
    solarReport.render = function (solar) {
        var tooltip = d3.select("body").append("div")
            .attr("class", "tooltip") //用于css设置类样式
            .attr("opacity", 0.0);
        solarReport.renderAppList(solar);
        solarReport.renderStaticPie(solar);
        solarReport.renderDepLines(solar);
    }
    solarReport.renderAppList = function renderAppList(solar) {
        var report = d3.select('#appList')
        report.style('height', (solar.planets.length * 0.8 + 2) + 'em')
        var svg = report.append('svg');
        svg.style('height', (solar.planets.length * 0.8 + 2) + 'em')
        //            var rect = svg.append("rect").attr({fill: '#fff', stroke: 'steelblue', height: 95, width: 290})
        svg.append('text').text('Domain Name: ' + solar.name).attr({
            fill: 'black',
            'font-size': '0.8em',
            y: '1em'
        })
        svg.append('text').text('App No.: ' + solar.planets.length).attr({
            fill: 'black',
            'font-size': '0.8em',
            y: '2em'
        })
        for (var i = 0; i < solar.planets.length; i++) {
            var planet = solar.planets[i];
            svg.append('text').html( planet.name ).attr({
                fill: 'black',
                'font-size': '0.8em',
                y: (3 + i) + 'em',
                x: '1em'
            })
        }
    }
    solarReport.doStatic = function (solar) {
        var planetStatic = solar.domainJsonObj.planetStatic;
        var validSuffix = jsonConvert.valid_suffix;

        if (planetStatic)
            return planetStatic

        planetStatic = []
        for (var i = 0; i < validSuffix.length; i++)
            planetStatic[i] = 0
        for (var i = 0; i < solar.planets.length; i++) {
            var planet = solar.planets[i]
            for (var j = 0; j < validSuffix.length; j++) {
                if (jsonConvert.endWith(planet.name, validSuffix[j])) {
                    planetStatic[j]++;
                }
            }
        }
        solar.domainJsonObj.planets = planetStatic
        return planetStatic;
    }
    solarReport.renderStaticPie = function (solar) {
        var planetTypes = solarReport.doStatic(solar)
        var dataset = []
        for (var i = 0; i < jsonConvert.valid_suffix.length; i++) {
            dataset.push([jsonConvert.valid_suffix[i], planetTypes[i]])
        }
        var pie = d3.layout.pie().value(function (d) {
            return d[1];
        })
        var piedata = pie(dataset)

        var width = 200
        var height = 200
        var outerRadius = width / 3
        var innerRadius = 0;
        var arc = d3.svg.arc().innerRadius(innerRadius).outerRadius(outerRadius)
        var color = d3.scale.category20()
        var svg = d3.select("#solarPie").append("svg").attr({width: width, height: height})
        var arcs = svg.selectAll("g").data(piedata).enter()
            .append("g")
            .attr("transform", "translate(" + (width / 2) + "," + (height / 2) + ")")
        arcs.append("path")
            .attr("fill", function (d, i) {
                return color(i)
            })
            .attr("d", function (d) {
                return arc(d)
            })
        arcs.append("text")
            .attr("transform", function (d) {
                var x = arc.centroid(d)[0] * 1.4;
                var y = arc.centroid(d)[1] * 1.4;
                return "translate(" + x + "," + y + ")";
            })
            .attr("text-anchor", "middle")
            .text(function (d) {
                var percent = Number(d.value) / d3.sum(dataset, function (d) {
                        return d[1]
                    }) * 100
                if (percent != 0)
                    return percent.toFixed(1) + "%"
            })
        arcs.append("line")
            .attr("stroke", "black")
            .attr("x1", function (d) {
                return arc.centroid(d)[0] * 2
            })
            .attr("y1", function (d) {
                return arc.centroid(d)[1] * 2
            })
            .attr("x2", function (d) {
                var longX = 2.2
                if (d.data[1] == 0)
                    longX = 2
                return arc.centroid(d)[0] * longX
            })
            .attr("y2", function (d) {
                var longY = 2.2
                if (d.data[1] == 0)
                    longY = 2
                return arc.centroid(d)[1] * longY
            })
        arcs.append("text")
            .attr("transform", function (d) {
                var x = arc.centroid(d)[0] * 2.5
                var y = arc.centroid(d)[1] * 2.5
                return "translate(" + x + "," + y + ")"
            })
            .attr("text-anchor", "middle")
            .text(function (d) {
                if (d.data[1] != 0)
                    return d.data[0]
                return ""
            })
    }
    solarReport.renderDepLines = function (solar) {

        var static = null;
        for (var i = 0; i < atlas.depStatic.length; i++) {
            if (solar.name == atlas.depStatic[i].domain) {
                static = atlas.depStatic[i];
                break;
            }
        }
        if (!static)
            return
        var dataset = [static.dependsByApps.length, static.dependsByDomains.length, static.dependsOnApps.length, static.dependsOnDomains.length, static.biDependApps.length, static.biDependDomains.length]
        var depSet = [static.dependsByApps, static.dependsByDomains, static.dependsOnApps, static.dependsOnDomains, static.biDependApps, static.biDependDomains]
        var hintSet = ['ToPlanets', 'ToSolar', 'fromPlanets', 'fromSolar', 'biDirectPlanets', 'biDirectSolars']
        var width = 200
        var height = 300;
        var step = 30;
        var lineHeight = 20
        var lineWidthUnit = 20;
        var svg = d3.select("#depBar").append("svg").attr("width", width).attr("height", height);
        var enter = svg.selectAll('rect').data(dataset).enter();
        var rect = enter.append("rect").attr("fill", "steelblue")
            .attr('y', function (d, i) {
                return i * (lineHeight + step) + step - 5
            }).attr('x', 0)
            .attr('height', lineHeight)
            .attr('width', function (d, i) {
                var wid = d >= 10 ? 10 : d
                return wid * lineWidthUnit;
            })
            .style('cursor','help')
            .on('click', function (d, i) {
                var text = $('#depContent').text()
                if (text == "")
                    $('#depContent').html(function () {
                        var hint = hintSet[i] + ":"+depSet[i]
                        // for (var j = 0; j < depSet.length; j++)
                        //     for (var k = 0; k < depSet[i].length; k++)
                        //         hint += '\' + depSet[j][k] + '\'
                        return hint;
                    })
                else
                    $('#depContent').text("")
            })
        // var rectTran = rect.transition()
        //     .duration(2000).ease("back-in")
        //     .attrTween("width", function (d, i, a) {
        //         return function (t) {
        //             return Number(a) + t * 300
        //         }
        //     })
        var textEnter = svg.selectAll('#depBar text').data(dataset).enter()
        textEnter.append("text")
            .attr("fill", "white")
            .attr('y', function (d, i) {
                return i * (lineHeight + step) + step - 5
            })
            .attr('x', 5)
            .attr({dy: "1.2em"})
            .text(function (d, i) {
                return d
            })
        for (var i = 0; i < hintSet.length; i++) {
            svg.append("text").attr('x', 0).attr({'fill': 'steelblue', 'dy': '1.2em'}).attr('y', function () {
                return i * (step + lineHeight)
            }).text(hintSet[i])

        }
    }

}).call(this)<|endoftext|>


<commit_before>var gulp = require('gulp');
var source = require('vinyl-source-stream');
var watchify = require('watchify');
var browserify = require('browserify');
var plugins = require('gulp-load-plugins')();

var bundler = watchify(browserify('./public/js/index.js', watchify.args)
  .transform('babelify', {presets: ['es2015', 'react']}));
bundler.on('update', bundle);
bundler.on('log', plugins.util.log);

function bundle() {
  return bundler.bundle()
    // log errors
    .on('error', plugins.util.log.bind(plugins.util, 'Browserify Error'))
    .pipe(source('index.js'))
    // build sourcemaps
    .pipe(require('vinyl-buffer')())
    .pipe(plugins.sourcemaps.init({loadMaps: true})) // loads map from browserify file
    .pipe(plugins.sourcemaps.write('./')) // writes .map file
    .pipe(gulp.dest('./public/dest'))
    .pipe(plugins.livereload());
}

gulp.task('scss:lint', function() {
  gulp.src('./public/scss/**/*.scss')
    .pipe(plugins.sassLint())
    .pipe(plugins.sassLint.format())
    .pipe(plugins.sassLint.failOnError());
});

gulp.task('scss:compileDev', function() {
  gulp.src('./public/scss/**/*.scss')
    //build sourcemaps
    .pipe(plugins.sourcemaps.init())
    .pipe(plugins.sass({errLogToConsole: true}))
    .pipe(plugins.sourcemaps.write())
    .pipe(gulp.dest('./public/dest/css'))
    .pipe(plugins.livereload());
});

gulp.task('scss:compile', ['fonts:copy'], function() {
  gulp.src('./public/scss/**/*.scss')
    .pipe(plugins.sass({errLogToConsole: true}))
    .pipe(gulp.dest('./public/dest/css'));
});

gulp.task('css:minify', ['scss:compile'], function() {
  gulp.src('./public/dest/css/*.css')
    .pipe(plugins.cleanCss())
    .pipe(gulp.dest('./public/dest/css'));
});

gulp.task('js:develop', function() {
  bundle();
});

gulp.task('js:compress', function() {
  var bundleStream = browserify('./public/js/index.js')
    .transform('babelify', {presets: ['es2015', 'react']})
    .bundle();

  bundleStream
    .pipe(source('index.js'))
    .pipe(plugins.streamify(plugins.uglify()))
    .pipe(require('vinyl-buffer')())
    .pipe(plugins.sourcemaps.init({loadMaps: true}))
    .pipe(plugins.sourcemaps.write('./'))
    .pipe(gulp.dest('./public/dest'));
});

gulp.task('scss:develop', ['scss:lint', 'scss:compileDev']);

gulp.task('fonts:copy', function() {
  gulp.src(['./node_modules/font-awesome/fonts/*', './node_modules/bootstrap-sass/assets/fonts/bootstrap/*'])
    .pipe(gulp.dest('./public/dest/fonts'));
});

gulp.task('css:copy', function() {
  gulp.src('./node_modules/mapbox.js/theme/**/*')
    .pipe(gulp.dest('./public/dest/css/mapbox'));
});

gulp.task('views', function() {
  return gulp.src(['views/index.pug', 'views/terms.pug'])
    .pipe(plugins.pug({
      // Your options in here.
    }))
    .pipe(gulp.dest('./public'));
});

gulp.task('develop', function() {
  plugins.livereload.listen();

  require('nodemon')({
    script: 'bin/www',
    stdout: true
  }).on('readable', function() {
    this.stdout.on('data', function(chunk) {
      if (/^listening/.test(chunk)) {
        plugins.livereload.reload();
      }
      process.stdout.write(chunk);
    });
  });

  gulp.watch('public/**/*.scss', ['scss:develop']);

  gulp.watch('public/**/!(dest)/**/*.+(jsx|js)', ['js:develop']);
});

gulp.task('build', [
  'fonts:copy',
  'css:copy',
  'css:minify',
  'js:compress'
]);

gulp.task('static', [
  'fonts:copy',
  'css:copy',
  'css:minify',
  'js:compress',
  'views'
]);
<commit_msg>minify for static<commit_after>var gulp = require('gulp');
var source = require('vinyl-source-stream');
var watchify = require('watchify');
var browserify = require('browserify');
var plugins = require('gulp-load-plugins')();

var bundler = watchify(browserify('./public/js/index.js', watchify.args)
  .transform('babelify', {presets: ['es2015', 'react']}));
bundler.on('update', bundle);
bundler.on('log', plugins.util.log);

function bundle() {
  return bundler.bundle()
    // log errors
    .on('error', plugins.util.log.bind(plugins.util, 'Browserify Error'))
    .pipe(source('index.js'))
    // build sourcemaps
    .pipe(require('vinyl-buffer')())
    .pipe(plugins.sourcemaps.init({loadMaps: true})) // loads map from browserify file
    .pipe(plugins.sourcemaps.write('./')) // writes .map file
    .pipe(gulp.dest('./public/dest'))
    .pipe(plugins.livereload());
}

gulp.task('set-prod-node-env', function() {
  process.env.NODE_ENV = 'production';
});

gulp.task('scss:lint', function() {
  gulp.src('./public/scss/**/*.scss')
    .pipe(plugins.sassLint())
    .pipe(plugins.sassLint.format())
    .pipe(plugins.sassLint.failOnError());
});

gulp.task('scss:compileDev', function() {
  gulp.src('./public/scss/**/*.scss')
    //build sourcemaps
    .pipe(plugins.sourcemaps.init())
    .pipe(plugins.sass({errLogToConsole: true}))
    .pipe(plugins.sourcemaps.write())
    .pipe(gulp.dest('./public/dest/css'))
    .pipe(plugins.livereload());
});

gulp.task('scss:compile', ['fonts:copy'], function() {
  gulp.src('./public/scss/**/*.scss')
    .pipe(plugins.sass({errLogToConsole: true}))
    .pipe(gulp.dest('./public/dest/css'));
});

gulp.task('css:minify', ['scss:compile'], function() {
  gulp.src('./public/dest/css/*.css')
    .pipe(plugins.cleanCss())
    .pipe(gulp.dest('./public/dest/css'));
});

gulp.task('js:develop', function() {
  bundle();
});

gulp.task('js:compress', function() {
  var bundleStream = browserify('./public/js/index.js')
    .transform('babelify', {presets: ['es2015', 'react']})
    .bundle();

  bundleStream
    .pipe(source('index.js'))
    .pipe(plugins.streamify(plugins.uglify()))
    .pipe(require('vinyl-buffer')())
    .pipe(plugins.sourcemaps.init({loadMaps: true}))
    .pipe(plugins.sourcemaps.write('./'))
    .pipe(gulp.dest('./public/dest'));
});

gulp.task('scss:develop', ['scss:lint', 'scss:compileDev']);

gulp.task('fonts:copy', function() {
  gulp.src(['./node_modules/font-awesome/fonts/*', './node_modules/bootstrap-sass/assets/fonts/bootstrap/*'])
    .pipe(gulp.dest('./public/dest/fonts'));
});

gulp.task('css:copy', function() {
  gulp.src('./node_modules/mapbox.js/theme/**/*')
    .pipe(gulp.dest('./public/dest/css/mapbox'));
});

gulp.task('views', function() {
  return gulp.src(['views/index.pug', 'views/terms.pug'])
    .pipe(plugins.pug({
      // Your options in here.
    }))
    .pipe(gulp.dest('./public'));
});

gulp.task('develop', function() {
  plugins.livereload.listen();

  require('nodemon')({
    script: 'bin/www',
    stdout: true
  }).on('readable', function() {
    this.stdout.on('data', function(chunk) {
      if (/^listening/.test(chunk)) {
        plugins.livereload.reload();
      }
      process.stdout.write(chunk);
    });
  });

  gulp.watch('public/**/*.scss', ['scss:develop']);

  gulp.watch('public/**/!(dest)/**/*.+(jsx|js)', ['js:develop']);
});

gulp.task('build', [
  'fonts:copy',
  'css:copy',
  'css:minify',
  'js:compress'
]);

gulp.task('static', [
  'set-prod-node-env',
  'fonts:copy',
  'css:copy',
  'css:minify',
  'js:compress',
  'views'
]);
<|endoftext|>