<commit_before>/**
 * @fileoverview Prevent usage of deprecated methods
 * @author Yannick Croissant
 * @author Scott Feeney
 * @author Sergei Startsev
 */
'use strict';

const has = require('has');

const Components = require('../util/Components');
const astUtil = require('../util/ast');
const docsUrl = require('../util/docsUrl');
const pragmaUtil = require('../util/pragma');
const versionUtil = require('../util/version');

// ------------------------------------------------------------------------------
// Constants
// ------------------------------------------------------------------------------

const MODULES = {
  react: ['React'],
  'react-addons-perf': ['ReactPerf', 'Perf']
};

const DEPRECATED_MESSAGE = '{{oldMethod}} is deprecated since React {{version}}{{newMethod}}{{refs}}';

// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------

module.exports = {
  meta: {
    docs: {
      description: 'Prevent usage of deprecated methods',
      category: 'Best Practices',
      recommended: true,
      url: docsUrl('no-deprecated')
    },
    schema: []
  },

  create: Components.detect((context, components, utils) => {
    const sourceCode = context.getSourceCode();
    const pragma = pragmaUtil.getFromContext(context);

    function getDeprecated() {
      const deprecated = {};
      // 0.12.0
      deprecated[`${pragma}.renderComponent`] = ['0.12.0', `${pragma}.render`];
      deprecated[`${pragma}.renderComponentToString`] = ['0.12.0', `${pragma}.renderToString`];
      deprecated[`${pragma}.renderComponentToStaticMarkup`] = ['0.12.0', `${pragma}.renderToStaticMarkup`];
      deprecated[`${pragma}.isValidComponent`] = ['0.12.0', `${pragma}.isValidElement`];
      deprecated[`${pragma}.PropTypes.component`] = ['0.12.0', `${pragma}.PropTypes.element`];
      deprecated[`${pragma}.PropTypes.renderable`] = ['0.12.0', `${pragma}.PropTypes.node`];
      deprecated[`${pragma}.isValidClass`] = ['0.12.0'];
      deprecated['this.transferPropsTo'] = ['0.12.0', 'spread operator ({...})'];
      // 0.13.0
      deprecated[`${pragma}.addons.classSet`] = ['0.13.0', 'the npm module classnames'];
      deprecated[`${pragma}.addons.cloneWithProps`] = ['0.13.0', `${pragma}.cloneElement`];
      // 0.14.0
      deprecated[`${pragma}.render`] = ['0.14.0', 'ReactDOM.render'];
      deprecated[`${pragma}.unmountComponentAtNode`] = ['0.14.0', 'ReactDOM.unmountComponentAtNode'];
      deprecated[`${pragma}.findDOMNode`] = ['0.14.0', 'ReactDOM.findDOMNode'];
      deprecated[`${pragma}.renderToString`] = ['0.14.0', 'ReactDOMServer.renderToString'];
      deprecated[`${pragma}.renderToStaticMarkup`] = ['0.14.0', 'ReactDOMServer.renderToStaticMarkup'];
      // 15.0.0
      deprecated[`${pragma}.addons.LinkedStateMixin`] = ['15.0.0'];
      deprecated['ReactPerf.printDOM'] = ['15.0.0', 'ReactPerf.printOperations'];
      deprecated['Perf.printDOM'] = ['15.0.0', 'Perf.printOperations'];
      deprecated['ReactPerf.getMeasurementsSummaryMap'] = ['15.0.0', 'ReactPerf.getWasted'];
      deprecated['Perf.getMeasurementsSummaryMap'] = ['15.0.0', 'Perf.getWasted'];
      // 15.5.0
      deprecated[`${pragma}.createClass`] = ['15.5.0', 'the npm module create-react-class'];
      deprecated[`${pragma}.addons.TestUtils`] = ['15.5.0', 'ReactDOM.TestUtils'];
      deprecated[`${pragma}.PropTypes`] = ['15.5.0', 'the npm module prop-types'];
      // 15.6.0
      deprecated[`${pragma}.DOM`] = ['15.6.0', 'the npm module react-dom-factories'];
      // 16.3.0
      deprecated.componentWillMount = [
        '16.3.0',
        'UNSAFE_componentWillMount',
        'https://reactjs.org/docs/react-component.html#unsafe_componentwillmount'
      ];
      deprecated.componentWillReceiveProps = [
        '16.3.0',
        'UNSAFE_componentWillReceiveProps',
        'https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops'
      ];
      deprecated.componentWillUpdate = [
        '16.3.0',
        'UNSAFE_componentWillUpdate',
        'https://reactjs.org/docs/react-component.html#unsafe_componentwillupdate'
      ];
      return deprecated;
    }

    function isDeprecated(method) {
      const deprecated = getDeprecated();

      return (
        deprecated &&
        deprecated[method] &&
        versionUtil.testReactVersion(context, deprecated[method][0])
      );
    }

    function checkDeprecation(node, method) {
      if (!isDeprecated(method)) {
        return;
      }
      const deprecated = getDeprecated();
      const version = deprecated[method][0];
      const newMethod = deprecated[method][1];
      const refs = deprecated[method][2];
      context.report({
        node: node,
        message: DEPRECATED_MESSAGE,
        data: {
          oldMethod: method,
          version,
          newMethod: newMethod ? `, use ${newMethod} instead` : '',
          refs: refs ? `, see ${refs}` : ''
        }
      });
    }

    function getReactModuleName(node) {
      let moduleName = false;
      if (!node.init) {
        return moduleName;
      }
      for (const module in MODULES) {
        if (!has(MODULES, module)) {
          continue;
        }
        moduleName = MODULES[module].find(name => name === node.init.name);
        if (moduleName) {
          break;
        }
      }
      return moduleName;
    }

    /**
     * Returns life cycle methods if available
     * @param {ASTNode} node The AST node being checked.
     * @returns {Array} The array of methods.
     */
    function getLifeCycleMethods(node) {
      const properties = astUtil.getComponentProperties(node);
      return properties.map(property => astUtil.getPropertyName(property));
    }

    /**
     * Checks life cycle methods
     * @param {ASTNode} node The AST node being checked.
     */
    function checkLifeCycleMethods(node) {
      if (utils.isES5Component(node) || utils.isES6Component(node)) {
        const methods = getLifeCycleMethods(node);
        methods.forEach(method => checkDeprecation(node, method));
      }
    }

    // --------------------------------------------------------------------------
    // Public
    // --------------------------------------------------------------------------

    return {

      MemberExpression: function(node) {
        checkDeprecation(node, sourceCode.getText(node));
      },

      ImportDeclaration: function(node) {
        const isReactImport = typeof MODULES[node.source.value] !== 'undefined';
        if (!isReactImport) {
          return;
        }
        node.specifiers.forEach(specifier => {
          if (!specifier.imported) {
            return;
          }
          checkDeprecation(node, `${MODULES[node.source.value][0]}.${specifier.imported.name}`);
        });
      },

      VariableDeclarator: function(node) {
        const reactModuleName = getReactModuleName(node);
        const isRequire = node.init && node.init.callee && node.init.callee.name === 'require';
        const isReactRequire = node.init
          && node.init.arguments
          && node.init.arguments.length
          && typeof MODULES[node.init.arguments[0].value] !== 'undefined';
        const isDestructuring = node.id && node.id.type === 'ObjectPattern';

        if (
          !(isDestructuring && reactModuleName) &&
          !(isDestructuring && isRequire && isReactRequire)
        ) {
          return;
        }
        node.id.properties.forEach(property => {
          checkDeprecation(node, `${reactModuleName || pragma}.${property.key.name}`);
        });
      },

      ClassDeclaration: checkLifeCycleMethods,
      ClassExpression: checkLifeCycleMethods,
      ObjectExpression: checkLifeCycleMethods
    };
  })
};
<commit_msg>Hotifx - Issue:1785 - fixed no-deprecated bug<commit_after>/**
 * @fileoverview Prevent usage of deprecated methods
 * @author Yannick Croissant
 * @author Scott Feeney
 * @author Sergei Startsev
 */
'use strict';

const has = require('has');

const Components = require('../util/Components');
const astUtil = require('../util/ast');
const docsUrl = require('../util/docsUrl');
const pragmaUtil = require('../util/pragma');
const versionUtil = require('../util/version');

// ------------------------------------------------------------------------------
// Constants
// ------------------------------------------------------------------------------

const MODULES = {
  react: ['React'],
  'react-addons-perf': ['ReactPerf', 'Perf']
};

const DEPRECATED_MESSAGE = '{{oldMethod}} is deprecated since React {{version}}{{newMethod}}{{refs}}';

// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------

module.exports = {
  meta: {
    docs: {
      description: 'Prevent usage of deprecated methods',
      category: 'Best Practices',
      recommended: true,
      url: docsUrl('no-deprecated')
    },
    schema: []
  },

  create: Components.detect((context, components, utils) => {
    const sourceCode = context.getSourceCode();
    const pragma = pragmaUtil.getFromContext(context);

    function getDeprecated() {
      const deprecated = {};
      // 0.12.0
      deprecated[`${pragma}.renderComponent`] = ['0.12.0', `${pragma}.render`];
      deprecated[`${pragma}.renderComponentToString`] = ['0.12.0', `${pragma}.renderToString`];
      deprecated[`${pragma}.renderComponentToStaticMarkup`] = ['0.12.0', `${pragma}.renderToStaticMarkup`];
      deprecated[`${pragma}.isValidComponent`] = ['0.12.0', `${pragma}.isValidElement`];
      deprecated[`${pragma}.PropTypes.component`] = ['0.12.0', `${pragma}.PropTypes.element`];
      deprecated[`${pragma}.PropTypes.renderable`] = ['0.12.0', `${pragma}.PropTypes.node`];
      deprecated[`${pragma}.isValidClass`] = ['0.12.0'];
      deprecated['this.transferPropsTo'] = ['0.12.0', 'spread operator ({...})'];
      // 0.13.0
      deprecated[`${pragma}.addons.classSet`] = ['0.13.0', 'the npm module classnames'];
      deprecated[`${pragma}.addons.cloneWithProps`] = ['0.13.0', `${pragma}.cloneElement`];
      // 0.14.0
      deprecated[`${pragma}.render`] = ['0.14.0', 'ReactDOM.render'];
      deprecated[`${pragma}.unmountComponentAtNode`] = ['0.14.0', 'ReactDOM.unmountComponentAtNode'];
      deprecated[`${pragma}.findDOMNode`] = ['0.14.0', 'ReactDOM.findDOMNode'];
      deprecated[`${pragma}.renderToString`] = ['0.14.0', 'ReactDOMServer.renderToString'];
      deprecated[`${pragma}.renderToStaticMarkup`] = ['0.14.0', 'ReactDOMServer.renderToStaticMarkup'];
      // 15.0.0
      deprecated[`${pragma}.addons.LinkedStateMixin`] = ['15.0.0'];
      deprecated['ReactPerf.printDOM'] = ['15.0.0', 'ReactPerf.printOperations'];
      deprecated['Perf.printDOM'] = ['15.0.0', 'Perf.printOperations'];
      deprecated['ReactPerf.getMeasurementsSummaryMap'] = ['15.0.0', 'ReactPerf.getWasted'];
      deprecated['Perf.getMeasurementsSummaryMap'] = ['15.0.0', 'Perf.getWasted'];
      // 15.5.0
      deprecated[`${pragma}.createClass`] = ['15.5.0', 'the npm module create-react-class'];
      deprecated[`${pragma}.addons.TestUtils`] = ['15.5.0', 'ReactDOM.TestUtils'];
      deprecated[`${pragma}.PropTypes`] = ['15.5.0', 'the npm module prop-types'];
      // 15.6.0
      deprecated[`${pragma}.DOM`] = ['15.6.0', 'the npm module react-dom-factories'];
      // 16.3.0
      deprecated.componentWillMount = [
        '16.3.0',
        'UNSAFE_componentWillMount',
        'https://reactjs.org/docs/react-component.html#unsafe_componentwillmount'
      ];
      deprecated.componentWillReceiveProps = [
        '16.3.0',
        'UNSAFE_componentWillReceiveProps',
        'https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops'
      ];
      deprecated.componentWillUpdate = [
        '16.3.0',
        'UNSAFE_componentWillUpdate',
        'https://reactjs.org/docs/react-component.html#unsafe_componentwillupdate'
      ];
      return deprecated;
    }

    function isDeprecated(method) {
      const deprecated = getDeprecated();

      return (
        deprecated &&
        deprecated[method] &&
        deprecated[method][0] &&
        versionUtil.testReactVersion(context, deprecated[method][0])
      );
    }

    function checkDeprecation(node, method) {
      if (!isDeprecated(method)) {
        return;
      }
      const deprecated = getDeprecated();
      const version = deprecated[method][0];
      const newMethod = deprecated[method][1];
      const refs = deprecated[method][2];
      context.report({
        node: node,
        message: DEPRECATED_MESSAGE,
        data: {
          oldMethod: method,
          version,
          newMethod: newMethod ? `, use ${newMethod} instead` : '',
          refs: refs ? `, see ${refs}` : ''
        }
      });
    }

    function getReactModuleName(node) {
      let moduleName = false;
      if (!node.init) {
        return moduleName;
      }
      for (const module in MODULES) {
        if (!has(MODULES, module)) {
          continue;
        }
        moduleName = MODULES[module].find(name => name === node.init.name);
        if (moduleName) {
          break;
        }
      }
      return moduleName;
    }

    /**
     * Returns life cycle methods if available
     * @param {ASTNode} node The AST node being checked.
     * @returns {Array} The array of methods.
     */
    function getLifeCycleMethods(node) {
      const properties = astUtil.getComponentProperties(node);
      return properties.map(property => astUtil.getPropertyName(property));
    }

    /**
     * Checks life cycle methods
     * @param {ASTNode} node The AST node being checked.
     */
    function checkLifeCycleMethods(node) {
      if (utils.isES5Component(node) || utils.isES6Component(node)) {
        const methods = getLifeCycleMethods(node);
        methods.forEach(method => checkDeprecation(node, method));
      }
    }

    // --------------------------------------------------------------------------
    // Public
    // --------------------------------------------------------------------------

    return {

      MemberExpression: function(node) {
        checkDeprecation(node, sourceCode.getText(node));
      },

      ImportDeclaration: function(node) {
        const isReactImport = typeof MODULES[node.source.value] !== 'undefined';
        if (!isReactImport) {
          return;
        }
        node.specifiers.forEach(specifier => {
          if (!specifier.imported) {
            return;
          }
          checkDeprecation(node, `${MODULES[node.source.value][0]}.${specifier.imported.name}`);
        });
      },

      VariableDeclarator: function(node) {
        const reactModuleName = getReactModuleName(node);
        const isRequire = node.init && node.init.callee && node.init.callee.name === 'require';
        const isReactRequire = node.init
          && node.init.arguments
          && node.init.arguments.length
          && typeof MODULES[node.init.arguments[0].value] !== 'undefined';
        const isDestructuring = node.id && node.id.type === 'ObjectPattern';

        if (
          !(isDestructuring && reactModuleName) &&
          !(isDestructuring && isRequire && isReactRequire)
        ) {
          return;
        }
        node.id.properties.forEach(property => {
          checkDeprecation(node, `${reactModuleName || pragma}.${property.key.name}`);
        });
      },

      ClassDeclaration: checkLifeCycleMethods,
      ClassExpression: checkLifeCycleMethods,
      ObjectExpression: checkLifeCycleMethods
    };
  })
};
<|endoftext|>


<commit_before>// Proceess escaped chars and hardbreaks

var ESCAPED = {};

'\\!"#$%&\'()*+,./:;<=>?@[]^_`{|}~-'
  .split('').forEach(function(ch) { ESCAPED[ch.charCodeAt(0)] = true; });

module.exports = function escape(state, silent) {
  var ch, pos = state.pos, max = state.posMax;

  if (state.src.charCodeAt(pos) !== 0x5C/* \ */) { return false; }

  pos++;

  if (pos < max) {
    ch = state.src.charCodeAt(pos);

    if (typeof ESCAPED[ch] !== 'undefined') {
      if (!silent) { state.pending += state.src[pos]; }
      state.pos += 2;
      return true;
    }

    if (ch === 0x0A) {
      if (!silent) {
        state.push({
          type: 'hardbreak',
          level: state.level
        });
      }

      pos++;
      // skip leading whitespaces from next line
      while (pos < max && state.src.charCodeAt(pos) === 0x20) { pos++; }

      state.pos = pos;
      return true;
    }
  }

  if (!silent) { state.pending += '\\'; }
  state.pos++;
  return true;
};
<commit_msg>Perf: md unescaping opt<commit_after>// Proceess escaped chars and hardbreaks

var ESCAPED = [];

for (var i = 0; i < 256; i++) { ESCAPED.push(false); }

'\\!"#$%&\'()*+,./:;<=>?@[]^_`{|}~-'
  .split('').forEach(function(ch) { ESCAPED[ch.charCodeAt(0)] = true; });

module.exports = function escape(state, silent) {
  var ch, pos = state.pos, max = state.posMax;

  if (state.src.charCodeAt(pos) !== 0x5C/* \ */) { return false; }

  pos++;

  if (pos < max) {
    ch = state.src.charCodeAt(pos);

    if (ch < 256 && ESCAPED[ch] !== 0) {
      if (!silent) { state.pending += state.src[pos]; }
      state.pos += 2;
      return true;
    }

    if (ch === 0x0A) {
      if (!silent) {
        state.push({
          type: 'hardbreak',
          level: state.level
        });
      }

      pos++;
      // skip leading whitespaces from next line
      while (pos < max && state.src.charCodeAt(pos) === 0x20) { pos++; }

      state.pos = pos;
      return true;
    }
  }

  if (!silent) { state.pending += '\\'; }
  state.pos++;
  return true;
};
<|endoftext|>


<commit_before>// ========================================================================
// SproutCore
// copyright 2006-2008 Sprout Systems, Inc.
// ========================================================================

require('views/view') ;
require('mixins/control') ;

SC.IMAGE_STATE_NONE = 'none';
SC.IMAGE_STATE_LOADING = 'loading';
SC.IMAGE_STATE_LOADED = 'loaded';
SC.IMAGE_STATE_FAILED = 'failed';
SC.IMAGE_STATE_SPRITE = 'sprite';

/**
  URL to a transparent GIF.  Used for spriting.
*/
SC.BLANK_IMAGE_URL = static_url('blank.gif');

/**
  @class

  Displays an image in the browser.

  The ImageView can be used to efficiently display images in the browser.
  It includes a built in support for a number of features that can improve
  your page load time if you use a lot of images including a image loading
  queue and automatic support for CSS spriting.

  Note that there are actually many controls that will natively include
  images using an icon property name.

  @extends SC.View
  @extends SC.Control
  @since SproutCore 1.0
*/
SC.ImageView = SC.View.extend(SC.Control,
/** @scope SC.ImageView.prototype */ {

  /** Image views contain an img tag. */
  emptyElement: '<%@1 src="'+SC.BLANK_IMAGE_URL+'" />',
  styleClass: 'sc-image-view',
  tagName: 'img',

  /**
    Current load status of the image.

    This status changes as an image is loaded from the server.  If spriting
    is used, this will always be loaded.  Must be one of the following
    constants: SC.IMAGE_STATE_NONE, SC.IMAGE_STATE_LOADING,
    SC.IMAGE_STATE_LOADED, SC.IMAGE_STATE_FAILED, SC.IMAGE_STATE_SPRITE

    @property {String}
  */
  status: SC.IMAGE_STATE_NONE,

  /**
    A url or CSS class name.

    This is the image you want the view to display.  It should be either a
    url or css class name.  You can also set the content and
    contentValueKey properties to have this value extracted
    automatically.

    If you want to use CSS spriting, set this value to a CSS class name.  If
    you need to use multiple class names to set your icon, separate them by
    spaces.

    Note that if you provide a URL, it must contain at least one '/' as this
    is how we autodetect URLs.

    @property {String}
  */
  value: null,

  /**
    If YES, image view will use the imageCache to control loading.  This
    setting is generally preferred.

    @property {String}
  */
  useImageCache: YES,

  /**
    If YES, this image can load in the background.  Otherwise, it is treated
    as a foreground image.  If the image is not visible on screen, it will
    always be treated as a background image.
  */
  canLoadInBackground: NO,

  displayProperties: 'status'.w(),

  updateDisplay: function() {
    // the image source is the value if the status is LOADED or blank
    var status = this.get('status'), value = this.get('value');

    if (status === SC.IMAGE_STATE_NONE && value) this._image_valueDidChange() ; // setup initial state

    var src = (status === SC.IMAGE_STATE_LOADED) ? value : SC.BLANK_IMAGE_URL;
    var className = ['sc-view',this.get('styleClass')];
    if (status === SC.IMAGE_STATE_SPRITE) className.push(value);
    this.$().attr('src', src).attr('class', className.join(' '));
  },

  /** @private -
    Whenever the value changes, update the image state and possibly schedule
    an image to load.
  */
  _image_valueDidChange: function() {
    var value = this.get('value'), isUrl = SC.ImageView.valueIsUrl(value);

    // if the old image is still loading, cancel it
    // if (this._loadingUrl) SC.imageCache.abortImage(this._loadingUrl);

    // now update local state as needed....
    if (isUrl && this.get('useImageCache')) {
      var isBackground = this.get('isVisibleInWindow') || this.get('canLoadInBackground');
      SC.imageCache.loadImage(value, this, this.imageDidLoad, isBackground);

      this.set('status', SC.IMAGE_STATE_LOADING);
      this._loadingUrl = value ;

    // otherwise, just set state immediately
    } else {
      this.set('status', (isUrl) ? SC.IMAGE_STATE_LOADED : SC.IMAGE_STATE_SPRITE);
      this.displayDidChange(); // call manually in case status did not change
      // (e.g value changes from one sprite to another)
    }

  }.observes('value'),

  /**
    Called when the imageCache indicates that the image has loaded.
    Changing the image state will update the display.
  */
  imageDidLoad: function(url, imageOrError) {
    if (url === this._loadingUrl) this._loadingUrl = null;

    // do nothing if we get this notification by the value of the image has
    // since changed.
    if (this.get('value') === url) {
      this.set('status', SC.$ok(imageOrError) ? SC.IMAGE_STATE_LOADED : SC.IMAGE_STATE_FAILED);
      this.displayDidChange();
    }
  }

}) ;

/**
  Returns YES if the passed value looks like an URL and not a CSS class
  name.
*/
SC.ImageView.valueIsUrl = function(value) {
  return value ? value.indexOf('/') >= 0 : NO ;
} ;

<commit_msg>fixed bug in SC.ImageView<commit_after>// ========================================================================
// SproutCore
// copyright 2006-2008 Sprout Systems, Inc.
// ========================================================================

require('views/view') ;
require('mixins/control') ;

SC.IMAGE_STATE_NONE = 'none';
SC.IMAGE_STATE_LOADING = 'loading';
SC.IMAGE_STATE_LOADED = 'loaded';
SC.IMAGE_STATE_FAILED = 'failed';
SC.IMAGE_STATE_SPRITE = 'sprite';

/**
  URL to a transparent GIF.  Used for spriting.
*/
SC.BLANK_IMAGE_URL = static_url('blank.gif');

/**
  @class

  Displays an image in the browser.

  The ImageView can be used to efficiently display images in the browser.
  It includes a built in support for a number of features that can improve
  your page load time if you use a lot of images including a image loading
  queue and automatic support for CSS spriting.

  Note that there are actually many controls that will natively include
  images using an icon property name.

  @extends SC.View
  @extends SC.Control
  @since SproutCore 1.0
*/
SC.ImageView = SC.View.extend(SC.Control,
/** @scope SC.ImageView.prototype */ {

  /** Image views contain an img tag. */
  emptyElement: '<%@1 src="'+SC.BLANK_IMAGE_URL+'" />',
  styleClass: 'sc-image-view',
  tagName: 'img',

  /**
    Current load status of the image.

    This status changes as an image is loaded from the server.  If spriting
    is used, this will always be loaded.  Must be one of the following
    constants: SC.IMAGE_STATE_NONE, SC.IMAGE_STATE_LOADING,
    SC.IMAGE_STATE_LOADED, SC.IMAGE_STATE_FAILED, SC.IMAGE_STATE_SPRITE

    @property {String}
  */
  status: SC.IMAGE_STATE_NONE,

  /**
    A url or CSS class name.

    This is the image you want the view to display.  It should be either a
    url or css class name.  You can also set the content and
    contentValueKey properties to have this value extracted
    automatically.

    If you want to use CSS spriting, set this value to a CSS class name.  If
    you need to use multiple class names to set your icon, separate them by
    spaces.

    Note that if you provide a URL, it must contain at least one '/' as this
    is how we autodetect URLs.

    @property {String}
  */
  value: null,

  /**
    If YES, image view will use the imageCache to control loading.  This
    setting is generally preferred.

    @property {String}
  */
  useImageCache: YES,

  /**
    If YES, this image can load in the background.  Otherwise, it is treated
    as a foreground image.  If the image is not visible on screen, it will
    always be treated as a background image.
  */
  canLoadInBackground: NO,

  displayProperties: 'status'.w(),

  updateDisplay: function() {
    // the image source is the value if the status is LOADED or blank
    var status = this.get('status'), value = this.get('value');

    if (status === SC.IMAGE_STATE_NONE && value) this._image_valueDidChange() ; // setup initial state

    var src = (status === SC.IMAGE_STATE_LOADED) ? value : SC.BLANK_IMAGE_URL;
    var className = ['sc-view',this.get('styleClass')];
    if (status === SC.IMAGE_STATE_SPRITE) className.push(value);
    this.$().attr('src', src).attr('class', className.join(' '));
  },

  /** @private -
    Whenever the value changes, update the image state and possibly schedule
    an image to load.
  */
  _image_valueDidChange: function() {
    var value = this.get('value'), isUrl = SC.ImageView.valueIsUrl(value);

    // if the old image is still loading, cancel it
    // if (this._loadingUrl) SC.imageCache.abortImage(this._loadingUrl);

    // now update local state as needed....
    if (isUrl && this.get('useImageCache')) {
      var isBackground = this.get('isVisibleInWindow') || this.get('canLoadInBackground');

      this._loadingUrl = value ; // note that we're loading...
      SC.imageCache.loadImage(value, this, this.imageDidLoad, isBackground);

      // only mark us as loading if we are still loading...
      if (this._loadingUrl) this.set('status', SC.IMAGE_STATE_LOADING);

    // otherwise, just set state immediately
    } else {
      this._loadingUrl = null ; // not loading...
      this.set('status', (isUrl) ? SC.IMAGE_STATE_LOADED : SC.IMAGE_STATE_SPRITE);
      this.displayDidChange(); // call manually in case status did not change
      // (e.g value changes from one sprite to another)
    }
  }.observes('value'),

  /**
    Called when the imageCache indicates that the image has loaded.
    Changing the image state will update the display.
  */
  imageDidLoad: function(url, imageOrError) {
    if (url === this._loadingUrl) this._loadingUrl = null;

    // do nothing if we get this notification by the value of the image has
    // since changed.
    if (this.get('value') === url) {
      this.set('status', SC.$ok(imageOrError) ? SC.IMAGE_STATE_LOADED : SC.IMAGE_STATE_FAILED);
      this.displayDidChange();
    }
  }

}) ;

/**
  Returns YES if the passed value looks like an URL and not a CSS class
  name.
*/
SC.ImageView.valueIsUrl = function(value) {
  return value ? value.indexOf('/') >= 0 : NO ;
} ;

<|endoftext|>


<commit_before>'use strict';

module.exports = function RouteFactory(options) {
  return ([
    require('./routes/credits'),
    require('./routes/debits'),
    require('./routes/users'),
    require('./routes/graphql'),
    require('./routes/referrals')
  ]).map(function(Router) {
    return Router({
      config: options.config,
      network: options.network,
      storage: options.storage,
      mailer: options.mailer,
      contracts: options.contracts
    }).getEndpointDefinitions();
  }).reduce(function(set1, set2) {
    return set1.concat(set2);
  }, []);
};
<commit_msg>Add marketing route to factory<commit_after>'use strict';

module.exports = function RouteFactory(options) {
  return ([
    require('./routes/credits'),
    require('./routes/debits'),
    require('./routes/users'),
    require('./routes/graphql'),
    require('./routes/referrals'),
    require('./routes/marketing')
  ]).map(function(Router) {
    return Router({
      config: options.config,
      network: options.network,
      storage: options.storage,
      mailer: options.mailer,
      contracts: options.contracts
    }).getEndpointDefinitions();
  }).reduce(function(set1, set2) {
    return set1.concat(set2);
  }, []);
};
<|endoftext|>


<commit_before>var AdmZip = require('adm-zip');
var parseString = require('xml2js').parseString;
var parseUrl = require('url').parse;
var util = require('./util');

function getMetaAttrs(meta) {
  meta = meta && meta.Session;
  if (!meta) {
    return {};
  }
  var result = meta.SessionTimers && meta.SessionTimers[0];
  result = result && result.$ || {};
  var SessionFlag = meta.SessionFlags && meta.SessionFlags[0] && meta.SessionFlags[0].SessionFlag;
  if (Array.isArray(SessionFlag)) {
    SessionFlag.forEach(function(flag) {
      flag = flag && flag.$;
      if (!flag || typeof flag.N !== 'string') {
        return;
      }
      result[flag.N] = flag.V || '';
    });
  }
  return result;
}

function parseMetaInfo(result) {
  var req = result.req;
  if (!req) {
    return false;
  }
  var port;
  if (/^[^:/]+:\/\//.test(req.url)) {
    var options = parseUrl(req.url);
    if (!req.headers.host) {
      req.headers.host = options.host;
    }
    port = options.port || (/^https:/i.test(req.url) ? 443 : 80);
    req.url = options.path;
  } else if (typeof req.headers.host !== 'string') {
    req.headers.host = '';
  }

  var meta = getMetaAttrs(result.meta);
  var startTime = result.startTime = new Date(meta.ClientConnected).getTime() || 0;
  if (meta.DNSTime >= 0) {
    startTime = result.dnsTime = +startTime + (+meta.DNSTime);
  }
  if (meta.ClientDoneRequest) {
    var requestTime = new Date(meta.ClientDoneRequest).getTime() || 0;
    startTime = result.requestTime = Math.max(startTime, requestTime);
  }
  if (meta.ClientBeginResponse) {
    var responseTime = new Date(meta.ClientBeginResponse).getTime() || 0;
    startTime = result.responseTime = Math.max(startTime, responseTime);
  }
  if (meta.ClientDoneResponse) {
    var endTime = new Date(meta.ClientDoneResponse).getTime() || 0;
    result.endTime = Math.max(endTime, startTime);
  }
  result.rules = {};
  var res = result.res = result.res || {};
  result.hostIp = res.ip = meta['x-hostip'];
  res.port = port;
  result.clientIp = req.ip = meta['x-clientip'];
  var clientPort = meta['x-clientport'];
  if (clientPort) {
    req.port = clientPort;
  }
  var size = meta['x-transfer-size'] || meta['x-responsebodytransferlength'];
  if (typeof size === 'string') {
    size = parseInt(size.replace(/\s*,\s*/g, ''), 10);
  }
  if (size > -1) {
    res.size = size;
  }
  if (req.method === 'CONNECT') {
    result.url = req.url;
    result.isHttps = true;
  } else {
    result.url = 'http://' + req.headers.host + req.url;
    if (/\bwebsocket\b/i.test(req.headers.upgrade)) {
      result.url = result.url.replace(/^http/, 'ws');
    }
  }
}

module.exports = function(buffer, cb) {
  var zip = new AdmZip(buffer);
  var zipEntries = zip.getEntries();
  var sessions = {};
  var count = 0;
  var execCallback = function() {
    if (count <= 0) {
      var result = [];
      Object.keys(sessions).forEach(function(key) {
        var session = sessions[key];
        if (session.req && session.meta) {
          if (parseMetaInfo(session) !== false) {
            result.push(session);
          }
        }
      });
      cb(result);
    }
  };
  zipEntries.forEach(function(entry) {
    if (entry.isDirectory) {
      return;
    }
    var entryName = entry.entryName;
    var filename = entryName.substring(4);
    var dashIndex = filename.lastIndexOf('_');
    if (dashIndex <= 0) {
      return;
    }
    var index = filename.substring(0, dashIndex);
    filename = filename.substring(dashIndex + 1).toLowerCase();
    if (['c.txt', 'm.xml', 's.txt'].indexOf(filename) === -1) {
      return;
    }
    var content = zip.readFile(entryName);
    if (!content) {
      return;
    }
    var result = sessions[index] = sessions[index] || {};
    ++count;
    if (filename === 'c.txt') {
      util.getReq(content, function(req) {
        setImmediate(function() {
          result.req = req;
          --count;
          execCallback();
        });
      });
    } else if (filename === 'm.xml') {
      parseString(content, function(err, meta) {
        setImmediate(function() {
          result.meta = meta;
          --count;
          execCallback();
        });
      });
    } else {
      util.getRes(content, function(res) {
        setImmediate(function() {
          result.res = res;
          --count;
          execCallback();
        });
      });
    }
  });
  execCallback();
};
<commit_msg>fix: import saz file<commit_after>var AdmZip = require('adm-zip');
var parseString = require('xml2js').parseString;
var parseUrl = require('url').parse;
var util = require('./util');

function getMetaAttrs(meta) {
  meta = meta && meta.Session;
  if (!meta) {
    return {};
  }
  var result = meta.SessionTimers && meta.SessionTimers[0];
  result = result && result.$ || {};
  var SessionFlag = meta.SessionFlags && meta.SessionFlags[0] && meta.SessionFlags[0].SessionFlag;
  if (Array.isArray(SessionFlag)) {
    SessionFlag.forEach(function(flag) {
      flag = flag && flag.$;
      if (!flag || typeof flag.N !== 'string') {
        return;
      }
      result[flag.N] = flag.V || '';
    });
  }
  return result;
}

function parseMetaInfo(result) {
  var req = result.req;
  if (!req) {
    return false;
  }
  var port;
  if (/^[^:/]+:\/\//.test(req.url)) {
    var options = parseUrl(req.url);
    if (!req.headers.host) {
      req.headers.host = options.host;
    }
    req.isHttps = /^https:/i.test(req.url);
    port = options.port || (req.isHttps ? 443 : 80);
    req.url = options.path;
  } else if (typeof req.headers.host !== 'string') {
    req.headers.host = '';
  }

  var meta = getMetaAttrs(result.meta);
  var startTime = result.startTime = new Date(meta.ClientConnected).getTime() || 0;
  if (meta.DNSTime >= 0) {
    startTime = result.dnsTime = +startTime + (+meta.DNSTime);
  }
  if (meta.ClientDoneRequest) {
    var requestTime = new Date(meta.ClientDoneRequest).getTime() || 0;
    startTime = result.requestTime = Math.max(startTime, requestTime);
  }
  if (meta.ClientBeginResponse) {
    var responseTime = new Date(meta.ClientBeginResponse).getTime() || 0;
    startTime = result.responseTime = Math.max(startTime, responseTime);
  }
  if (meta.ClientDoneResponse) {
    var endTime = new Date(meta.ClientDoneResponse).getTime() || 0;
    result.endTime = Math.max(endTime, startTime);
  }
  result.rules = {};
  var res = result.res = result.res || {};
  result.hostIp = res.ip = meta['x-hostip'];
  res.port = port;
  result.clientIp = req.ip = meta['x-clientip'];
  var clientPort = meta['x-clientport'];
  if (clientPort) {
    req.port = clientPort;
  }
  var size = meta['x-transfer-size'] || meta['x-responsebodytransferlength'];
  if (typeof size === 'string') {
    size = parseInt(size.replace(/\s*,\s*/g, ''), 10);
  }
  if (size > -1) {
    res.size = size;
  }
  if (req.method === 'CONNECT') {
    result.url = req.url;
    result.isHttps = true;
  } else {
    result.url = 'http' + (req.isHttps ? 's' : '') +'://' + req.headers.host + req.url;
    if (/\bwebsocket\b/i.test(req.headers.upgrade)) {
      result.url = result.url.replace(/^http/, 'ws');
    }
  }
}

module.exports = function(buffer, cb) {
  var zip = new AdmZip(buffer);
  var zipEntries = zip.getEntries();
  var sessions = {};
  var count = 0;
  var execCallback = function() {
    if (count <= 0) {
      var result = [];
      Object.keys(sessions).forEach(function(key) {
        var session = sessions[key];
        if (session.req && session.meta) {
          if (parseMetaInfo(session) !== false) {
            result.push(session);
          }
        }
      });
      cb(result);
    }
  };
  zipEntries.forEach(function(entry) {
    if (entry.isDirectory) {
      return;
    }
    var entryName = entry.entryName;
    var filename = entryName.substring(4);
    var dashIndex = filename.lastIndexOf('_');
    if (dashIndex <= 0) {
      return;
    }
    var index = filename.substring(0, dashIndex);
    filename = filename.substring(dashIndex + 1).toLowerCase();
    if (['c.txt', 'm.xml', 's.txt'].indexOf(filename) === -1) {
      return;
    }
    var content = zip.readFile(entryName);
    if (!content) {
      return;
    }
    var result = sessions[index] = sessions[index] || {};
    ++count;
    if (filename === 'c.txt') {
      util.getReq(content, function(req) {
        setImmediate(function() {
          result.req = req;
          --count;
          execCallback();
        });
      });
    } else if (filename === 'm.xml') {
      parseString(content, function(err, meta) {
        setImmediate(function() {
          result.meta = meta;
          --count;
          execCallback();
        });
      });
    } else {
      util.getRes(content, function(res) {
        setImmediate(function() {
          result.res = res;
          --count;
          execCallback();
        });
      });
    }
  });
  execCallback();
};
<|endoftext|>


<commit_before>import Log from 'debug';
import bus from 'bus';
import render from '../render/render';
import View from '../view/view';
import ForumRow from './forum-row-view';
import template from './template.jade';
import newForumButton from './new-forum-button.jade';
import forumStore from '../forum-store/forum-store';

const log = new Log('democracyos:settings-forum:view');

export default class ForumsView extends View {

  /**
   * Creates a profile edit view
   */

  constructor () {
    super(template);
    this.forumsList = this.find('.forums');
    this.load();
  }

  load () {
    forumStore.findUserForum()
      .then(forum => this.add(forum))
      .catch(err => {
        if (404 === err.status) {
          this.empty();
        } else {
          log('Found Error %s', err);
        }
      })
    ;
  }

  add (forum) {
    var row = new ForumRow(forum);
    this.forumsList.append(row.el);
    bus.on(`forum-store:destroy:${forum.name}`, row.bound('remove'));
  }

  empty () {
    this.forumsList.empty();
    this.forumsList.append(render(newForumButton));
  }
}
<commit_msg>add create button when all forums where deleted Closes #1089<commit_after>import Log from 'debug';
import bus from 'bus';
import render from '../render/render';
import View from '../view/view';
import ForumRow from './forum-row-view';
import template from './template.jade';
import newForumButton from './new-forum-button.jade';
import forumStore from '../forum-store/forum-store';

const log = new Log('democracyos:settings-forum:view');

export default class ForumsView extends View {

  /**
   * Creates a profile edit view
   */

  constructor () {
    super(template);
    this.forumsList = this.find('.forums');
    this.load();
  }

  load () {
    forumStore.findUserForum()
      .then(forum => this.add(forum))
      .catch(err => {
        if (404 === err.status) {
          this.empty();
        } else {
          log('Found Error %s', err);
        }
      })
    ;
  }

  add (forum) {
    var row = new ForumRow(forum);
    this.forumsList.append(row.el);
    bus.once(`forum-store:destroy:${forum.name}`, () => {
      row.remove();
      if ('' == this.forumsList.html()) this.empty();
    });
  }

  empty () {
    this.forumsList.empty();
    this.forumsList.append(render(newForumButton));
  }
}
<|endoftext|>


<commit_before>// Triggers for all occasions and zones.
[{
  zoneRegex: /.*/,
  triggers: [
    {
      id: 'General Provoke',
      regex: /:(\y{Name}):1D6D:Provoke:/,
      condition: function(data) { return data.role == 'tank' },
      infoText: function(data, matches) {
        return 'Provoke: ' + matches[1];
      },
    },
    {
      id: 'General Ultimatum',
      regex: /:(\y{Name}):1D73:Ultimatum:/,
      condition: function(data) { return data.role == 'tank' },
      infoText: function(data, matches) {
        return 'Ultimatum: ' + matches[1];
      },
    },
    {
      id: 'General Shirk',
      regex: /:(\y{Name}):1D71:Shirk:/,
      condition: function(data) { return data.role == 'tank' },
      infoText: function(data, matches) {
        return 'Shirk: ' + matches[1];
      },
    },
    {
      id: 'General Holmgang',
      regex: /:(\y{Name}):2B:Holmgang:/,
      condition: function(data) { return data.role == 'tank' },
      infoText: function(data, matches) {
        return 'Holmgang: ' + matches[1];
      },
    },
    {
      id: 'General Hallowed',
      regex: /:(\y{Name}):1E:Hallowed Ground:/,
      condition: function(data) { return data.role == 'tank' },
      infoText: function(data, matches) {
        return 'Hallowed: ' + matches[1];
      },
    },
    {
      id: 'General Living',
      regex: /:(\y{Name}):E36:Living Dead:/,
      condition: function(data) { return data.role == 'tank' },
      infoText: function(data, matches) {
        return 'Living: ' + matches[1];
      },
    },
    {
      id: 'General Walking',
      regex: /:(\y{Name}) gains the effect of Walking Dead/,
      condition: function(data) { return data.role == 'tank' },
      infoText: function(data, matches) {
        return 'Walking: ' + matches[1];
      },
    },
    {
      id: 'General Ready check',
      regex: /:(?:(\y{Name}) has initiated|You have commenced) a ready check\./,
      sound: '../../resources/sounds/Overwatch/D.Va_-_Game_on.ogg',
      soundVolume: 0.6,
    },
    {
      id: 'General Trick Attack',
      regex: /:\y{Name}:\y{AbilityCode}:Trick Attack:/,
      sound: '../../resources/sounds/WeakAuras/RoaringLion.ogg',
    },
    {
      id: 'General Battle Litany',
      regex: /:(\y{Name}) gains the effect of Battle Litany from .*? for [0-9.]+ Seconds/,
      sound: '../../resources/sounds/Overwatch/D.Va_-_Boosters_engaged.ogg',
      soundVolume: 0.6,
      condition: function(data, matches) { return matches[1] == data.me; },
    },
    {
      id: 'General Foe Requiem',
      regex: /:(\y{Name}) gains the effect of Foe Requiem from \1 for ([0-9.]+) Seconds/,
      sound: '../../resources/sounds/Overwatch/Hanzo_-_Sake.ogg',
      soundVolume: 0.6,
    },
  ],
}];
<commit_msg>Remove general sounds for trick, litany, requiem<commit_after>// Triggers for all occasions and zones.
[{
  zoneRegex: /.*/,
  triggers: [
    {
      id: 'General Provoke',
      regex: /:(\y{Name}):1D6D:Provoke:/,
      condition: function(data) { return data.role == 'tank' },
      infoText: function(data, matches) {
        return 'Provoke: ' + matches[1];
      },
    },
    {
      id: 'General Ultimatum',
      regex: /:(\y{Name}):1D73:Ultimatum:/,
      condition: function(data) { return data.role == 'tank' },
      infoText: function(data, matches) {
        return 'Ultimatum: ' + matches[1];
      },
    },
    {
      id: 'General Shirk',
      regex: /:(\y{Name}):1D71:Shirk:/,
      condition: function(data) { return data.role == 'tank' },
      infoText: function(data, matches) {
        return 'Shirk: ' + matches[1];
      },
    },
    {
      id: 'General Holmgang',
      regex: /:(\y{Name}):2B:Holmgang:/,
      condition: function(data) { return data.role == 'tank' },
      infoText: function(data, matches) {
        return 'Holmgang: ' + matches[1];
      },
    },
    {
      id: 'General Hallowed',
      regex: /:(\y{Name}):1E:Hallowed Ground:/,
      condition: function(data) { return data.role == 'tank' },
      infoText: function(data, matches) {
        return 'Hallowed: ' + matches[1];
      },
    },
    {
      id: 'General Living',
      regex: /:(\y{Name}):E36:Living Dead:/,
      condition: function(data) { return data.role == 'tank' },
      infoText: function(data, matches) {
        return 'Living: ' + matches[1];
      },
    },
    {
      id: 'General Walking',
      regex: /:(\y{Name}) gains the effect of Walking Dead/,
      condition: function(data) { return data.role == 'tank' },
      infoText: function(data, matches) {
        return 'Walking: ' + matches[1];
      },
    },
    {
      id: 'General Ready check',
      regex: /:(?:(\y{Name}) has initiated|You have commenced) a ready check\./,
      sound: '../../resources/sounds/Overwatch/D.Va_-_Game_on.ogg',
      soundVolume: 0.6,
    },
  ],
}];
<|endoftext|>


<commit_before>import React from 'react'

import * as MachineActions from '../actions/MachineActions'

export default class EditorAssembler extends React.Component {

    componentDidMount() {
        this.updateContent()
    }

    componentDidUpdate() {
        this.updateContent()
    }

    updateContent() {
        const selectedLine = this.getSelectedLine()
        React.findDOMNode(this).innerHTML = this.props.sourceCode.instructions.map(instruction =>
            `<li class="${instruction.type}">${instruction.assembler}</li>`).join('')
        this.setSelectedLine(selectedLine)
    }

    getSelectedLine() {
        if (!window.getSelection) {
            return -1
        }

        const selection = getSelection()

        if (selection.rangeCount <= 0) {
            return -1
        }

        const range = selection.getRangeAt(0)
        let selectedNode = range.startContainer

        if (selectedNode.nodeType !== Node.ELEMENT_NODE) {
            selectedNode = selectedNode.parentNode
        }

        const parent = React.findDOMNode(this)

        if (selectedNode.parentNode !== parent) {
            return -1
        }

        let selectedLine = 0
        while ((selectedNode = selectedNode.previousSibling) !== null) {
            selectedLine++
        }
        return selectedLine
    }

    setSelectedLine(line) {
        if (line < 0) {
            return
        }
        if (window.getSelection && document.createRange) {
            const selection = getSelection()
            selection.removeAllRanges()
            const children = React.findDOMNode(this).children
            if (line < children.length) {
                const range = document.createRange()
                range.setStart(children[line], 1)
                range.setEnd(children[line], 1)
                selection.addRange(range)
            }
        }
    }

    render() {
        return (

        )
    }

    handleBlur() {
        this.emitChange(true)
    }

    handleInput() {
        this.emitChange(false)
    }

    emitChange(force) {
        const lines = []
        for (let child of React.findDOMNode(this).children) {
            lines.push(child.textContent)
        }
        if (force || lines.length !== this.props.sourceCode.instructions.length) {
            MachineActions.compile(lines)
        }
    }
}

EditorAssembler.propTypes = {
    sourceCode: React.PropTypes.object.isRequired
}
<commit_msg>Fix copy paste problem<commit_after>import React from 'react'

import * as MachineActions from '../actions/MachineActions'

export default class EditorAssembler extends React.Component {

    componentDidMount() {
        this.updateContent()
    }

    componentDidUpdate() {
        this.updateContent()
    }

    updateContent() {
        const selectedLine = this.getSelectedLine()
        React.findDOMNode(this).innerHTML = this.props.sourceCode.instructions.map(instruction =>
            `<li class="${instruction.type}">${instruction.assembler}</li>`).join('')
        this.setSelectedLine(selectedLine)
    }

    getSelectedLine() {
        if (!window.getSelection) {
            return -1
        }

        const selection = getSelection()

        if (selection.rangeCount <= 0) {
            return -1
        }

        const range = selection.getRangeAt(0)
        let selectedNode = range.startContainer

        if (selectedNode.nodeType !== Node.ELEMENT_NODE) {
            selectedNode = selectedNode.parentNode
        }

        const parent = React.findDOMNode(this)

        if (selectedNode.parentNode !== parent) {
            return -1
        }

        let selectedLine = 0
        while ((selectedNode = selectedNode.previousSibling) !== null) {
            selectedLine++
        }
        return selectedLine
    }

    setSelectedLine(line) {
        if (line < 0) {
            return
        }
        if (window.getSelection && document.createRange) {
            const selection = getSelection()
            selection.removeAllRanges()
            const children = React.findDOMNode(this).children
            if (line < children.length) {
                const range = document.createRange()
                range.setStart(children[line], 1)
                range.setEnd(children[line], 1)
                selection.addRange(range)
            }
        }
    }

    render() {
        return (

        )
    }

    handleBlur() {
        this.emitChange(true)
    }

    handleInput() {
        this.emitChange(false)
    }

    emitChange(force) {
        let lines = []
        for (let child of React.findDOMNode(this).children) {
            lines = lines.concat(child.textContent.split('\n'))
        }
        if (force || lines.length !== this.props.sourceCode.instructions.length) {
            MachineActions.compile(lines)
        }
    }
}

EditorAssembler.propTypes = {
    sourceCode: React.PropTypes.object.isRequired
}
<|endoftext|>


<commit_before>'use strict';

const has = require('has');
const { filterTree } = require('../lib/util');
const unique = (array) => Array.from(new Set(array));

/**
 * Get used table names from AST
 *
 * @type {Function}
 * @param {Object} node
 * @return {Array.<string>} Array of table names
 * @private
 */
const getTableExpressions = filterTree((node) => node.type && node.type === 'column_ref');

/**
 * Get attributes/aliases used in AST
 *
 * @type {Function}
 * @param {Object} node
 * @return {Array.<string>} Array of table names
 * @private
 */
const getAttributeExpressions = filterTree(
    (node) => has(node, 'table') && node.table === null && node.type && node.type === 'column_ref'
);

/**
 * Extract required tables
 *
 * @param {Object} ast Abstract Syntax Tree
 * @return {Array.<string>} Array of used tables
 * @private
 */
function getRequiredTables(ast) {
    const tableExpressions = ['columns', 'where', 'groupby', 'orderby']
        .filter((clause) => has(ast, clause) && ast[clause] !== null)
        .map((clause) => ast[clause])
        // TODO: replace reduce/push by flatMap(getTableExpressions) when available
        .reduce((expressions, expr) => {
            expressions.push(...getTableExpressions(expr));
            return expressions;
        }, []);

    if (ast.from.length > 1) {
        ast.from
            // extract joined tables that are not marked as required
            .filter((expr) => {
                const table = expr.as !== '' ? expr.as : expr.table;
                return expr.join !== undefined && tableExpressions.some((tblExpr) => tblExpr.table === table);
            })
            // get tables used in joins
            .forEach((join) => tableExpressions.push(...getTableExpressions(join.on)));
    }

    const requiredTables = tableExpressions.map((expr) => expr.table);

    return unique(requiredTables);
}

/**
 * Extract required aliases
 *
 * @param {Object} ast Abstract Syntax Tree
 * @return {Array.<string>} Array of used attributes/aliases
 */
function getRequiredAliases(ast) {
    const requiredAliases = ['groupby', 'orderby']
        .filter((clause) => has(ast, clause) && ast[clause] !== null)
        .map((clause) => ast[clause])
        .reduce((aliasExpressions, expr) => {
            aliasExpressions.push(...getAttributeExpressions(expr));
            return aliasExpressions;
        }, [])
        .map((expr) => expr.column);

    return unique(requiredAliases);
}

/**
 * Remove unnecessary expressions (attributes/columns or LEFT JOINs) from AST/query.
 *
 * @param {Object} ast Abstract Syntax Tree
 * @param {Array.<string>} requestedAttrs Attributes from Flora request
 * @param {boolean=} isLimitPer
 * @return {Object}
 */
function optimizeAST(ast, requestedAttrs, isLimitPer = false) {
    if (!ast.type || ast.type !== 'select') {
        return ast;
    }

    if (isLimitPer) {
        const subSelect = ast.from[1].expr;
        ast.from[1].expr = optimizeAST(subSelect, requestedAttrs);
        return ast;
    }

    const requiredAliases = getRequiredAliases(ast);
    const requiredAttrs = requiredAliases ? [...requestedAttrs, ...requiredAliases] : [];

    ast.columns = ast.columns.filter((column) => {
        // remove attributes that are not queried
        const attribute = column.as !== null ? column.as : column.expr.column;
        return requiredAttrs.includes(attribute);
    });

    const requiredTables = getRequiredTables(ast);
    ast.from = ast.from.filter((expr) => {
        const joinTable = expr.as !== null ? expr.as : expr.table;
        if (!expr.join) return true; // FROM clause
        if (expr.join !== 'LEFT JOIN') return true; // do not remove other types than LEFT JOIN
        return requiredTables.includes(joinTable);
    });

    return ast;
}

module.exports = optimizeAST;
<commit_msg>Fix alias check<commit_after>'use strict';

const has = require('has');
const { filterTree } = require('../lib/util');
const unique = (array) => Array.from(new Set(array));

/**
 * Get used table names from AST
 *
 * @type {Function}
 * @param {Object} node
 * @return {Array.<string>} Array of table names
 * @private
 */
const getTableExpressions = filterTree((node) => node.type && node.type === 'column_ref');

/**
 * Get attributes/aliases used in AST
 *
 * @type {Function}
 * @param {Object} node
 * @return {Array.<string>} Array of table names
 * @private
 */
const getAttributeExpressions = filterTree(
    (node) => has(node, 'table') && node.table === null && node.type && node.type === 'column_ref'
);

/**
 * Extract required tables
 *
 * @param {Object} ast Abstract Syntax Tree
 * @return {Array.<string>} Array of used tables
 * @private
 */
function getRequiredTables(ast) {
    const tableExpressions = ['columns', 'where', 'groupby', 'orderby']
        .filter((clause) => has(ast, clause) && ast[clause] !== null)
        .map((clause) => ast[clause])
        // TODO: replace reduce/push by flatMap(getTableExpressions) when available
        .reduce((expressions, expr) => {
            expressions.push(...getTableExpressions(expr));
            return expressions;
        }, []);

    if (ast.from.length > 1) {
        ast.from
            // extract joined tables that are not marked as required
            .filter((expr) => {
                const table = expr.as !== null ? expr.as : expr.table;
                return expr.join !== undefined && tableExpressions.some((tblExpr) => tblExpr.table === table);
            })
            // get tables used in joins
            .forEach((join) => tableExpressions.push(...getTableExpressions(join.on)));
    }

    const requiredTables = tableExpressions.map((expr) => expr.table);

    return unique(requiredTables);
}

/**
 * Extract required aliases
 *
 * @param {Object} ast Abstract Syntax Tree
 * @return {Array.<string>} Array of used attributes/aliases
 */
function getRequiredAliases(ast) {
    const requiredAliases = ['groupby', 'orderby']
        .filter((clause) => has(ast, clause) && ast[clause] !== null)
        .map((clause) => ast[clause])
        .reduce((aliasExpressions, expr) => {
            aliasExpressions.push(...getAttributeExpressions(expr));
            return aliasExpressions;
        }, [])
        .map((expr) => expr.column);

    return unique(requiredAliases);
}

/**
 * Remove unnecessary expressions (attributes/columns or LEFT JOINs) from AST/query.
 *
 * @param {Object} ast Abstract Syntax Tree
 * @param {Array.<string>} requestedAttrs Attributes from Flora request
 * @param {boolean=} isLimitPer
 * @return {Object}
 */
function optimizeAST(ast, requestedAttrs, isLimitPer = false) {
    if (!ast.type || ast.type !== 'select') {
        return ast;
    }

    if (isLimitPer) {
        const subSelect = ast.from[1].expr;
        ast.from[1].expr = optimizeAST(subSelect, requestedAttrs);
        return ast;
    }

    const requiredAliases = getRequiredAliases(ast);
    const requiredAttrs = requiredAliases ? [...requestedAttrs, ...requiredAliases] : [];

    ast.columns = ast.columns.filter((column) => {
        // remove attributes that are not queried
        const attribute = column.as !== null ? column.as : column.expr.column;
        return requiredAttrs.includes(attribute);
    });

    const requiredTables = getRequiredTables(ast);
    ast.from = ast.from.filter((expr) => {
        const joinTable = expr.as !== null ? expr.as : expr.table;
        if (!expr.join) return true; // FROM clause
        if (expr.join !== 'LEFT JOIN') return true; // do not remove other types than LEFT JOIN
        return requiredTables.includes(joinTable);
    });

    return ast;
}

module.exports = optimizeAST;
<|endoftext|>


<commit_before>var assert = require('assert-plus');
var logger = require('../logger/logger').logger;
var StageError = require('../error/stageError').StageError;
var AbstractStage = require('../stage/abstractStage').AbstractStage;
var cheerio = require('cheerio');

var exports = {};

var CONTEXT_VAR = 'context';

var isEmptySelector = function (selector) {
  return selector.length < 1;
};

exports.TYPE = 'selector';

exports.createContext = function (content) {
  return cheerio.load(content, {
    normalizeWhitespace: true,
    xmlMode: true,
    decodeEntities: true
  });
};

exports.prepareContext = function (options, content) {
  assert.object(options, 'options');

  options[exports.TYPE] = {};
  options[exports.TYPE][CONTEXT_VAR] = exports.createContext(content);
};

exports.SelectorStage = function SelectorStage(selector, contextName, handlers) {
  AbstractStage.call(this);
  this.selector = selector;
  this.contextName = contextName;
  this.handlers = [];

  handlers = handlers || [];

  if (typeof handlers === 'string') {
    handlers = [handlers];
  }

  var self = this;

  this.getName = function () {
    return exports.TYPE;
  };

  this.getSelector = function () {
    return this.selector;
  };

  this.val = function val() {
    this.handlers.push(function () {
      return this.val();
    });

    return self;
  };

  this.data = function data() {
    this.handlers.push(function () {
      return this.data();
    });

    return self;
  };

  this.html = function html() {
    this.handlers.push(function () {
      return this.html();
    });

    return self;
  };

  this.text = function text() {
    this.handlers.push(function () {
      return this.text();
    });

    return self;
  };

  this.attr = function attr(attrValue) {
    this.handlers.push(function () {
      return this.attr(attrValue);
    });

    return self;
  };

  this.find = function find(findValue) {
    this.handlers.push(function () {
      return this.find(findValue);
    });

    return self;
  };

  this.parent = function parent() {
    this.handlers.push(function () {
      return this.parent();
    });

    return self;
  };

  this.next = function next() {
    this.handlers.push(function () {
      return this.next();
    });

    return self;
  };

  this.prev = function prev() {
    this.handlers.push(function () {
      return this.prev();
    });

    return self;
  };

  this.children = function children(childrenValue) {
    this.handlers.push(function () {
      return this.children(childrenValue);
    });

    return self;
  };

  this.last = function last() {
    this.handlers.push(function last() {
      return this.last();
    });

    return self;
  };

  //default text handler
  if (handlers) {
    var re = /(.+)=(.+)/;

    for (var i in handlers) {
      if (handlers.hasOwnProperty(i)) {
        var handler = handlers[i];

        var value = undefined;
        var matches = handler.match(re);

        if (matches) {
          value = matches[2];
          handler = matches[1];
        }

        switch (handler) {
          case 'html' :
            this.html();
            break;
          case 'val' :
            this.val();
            break;
          case 'data' :
            this.data();
            break;
          case 'attr' :
            this.attr(value);
            break;
          case 'find' :
            this.find(value);
            break;
          case 'parent' :
            this.parent();
            break;
          case 'next' :
            this.next();
            break;
          case 'prev' :
            this.prev();
            break;
          case 'children' :
            this.children();
            break;
          case 'last' :
            this.last();
            break;
          default:
//            this.text();
        }
      }
    }
  }

  if (!this.handlers || this.handlers.length < 1) {
    this.text();
  }

  assert.arrayOfFunc(this.handlers, 'this.handlers');

  this.execute = function (value, options, callback) {
    logger.debug('Executing selector stage with selector: ' + this.selector + ' for value: ' + value);

    assert.object(options, 'options');

    var err = null;
    var result = null;

    if (!this.selector) {
      err = new StageError('Missing "selector" for selectorStage');
      return callback(err, result);
    }

    if (value) {
      logger.debug('Use custom context for selector: ' + this.selector + ' for value: ' + value);
      exports.prepareContext(options, value);
    }

    assert.object(options[exports.TYPE], 'options.' + exports.TYPE);
    assert.func(options[exports.TYPE][CONTEXT_VAR], 'options.' + exports.TYPE + '.' + CONTEXT_VAR);
    var $$ = options[exports.TYPE][CONTEXT_VAR];

    if (this.contextName) {
      logger.debug('Executing selector: ' + this.selector + ' witch contextName: ' + this.contextName);
    }

    var selectorValue = $$(this.selector, this.contextName);

    if (!isEmptySelector(selectorValue)) {
      var size = this.handlers.length;
      var handler = null;

      if (size > 1) {
        for (var i in this.handlers) {
          if (this.handlers.hasOwnProperty(i)) {
            handler = this.handlers[i];

            if (i < size - 1) {
              selectorValue = handler.bind(selectorValue)();
            }
          }
        }
      }

      handler = this.handlers[size - 1];
      assert.func(handler, 'handler');

      if (selectorValue.length < 2) {
        result = handler.bind(selectorValue)();
      }
      else {
        var result = [];

        selectorValue.each(function () {

          var val = handler.bind($$(this))();
          result.push(val);
        });
      }
    }
    else {
      logger.info('Unable to find value for given selector: ' + this.selector);
    }

    return callback(err, result);
  };

};

module.exports = exports;<commit_msg>Changed selector stage<commit_after>var assert = require('assert-plus');
var logger = require('../logger/logger').logger;
var StageError = require('../error/stageError').StageError;
var AbstractStage = require('../stage/abstractStage').AbstractStage;
var cheerio = require('cheerio');

var exports = {};

var CONTEXT_VAR = 'context';

var isEmptySelector = function (selector) {
  return selector.length < 1;
};

exports.TYPE = 'selector';

exports.createContext = function (content) {
  return cheerio.load(content, {
    normalizeWhitespace: true,
    xmlMode: true,
    decodeEntities: true
  });
};

exports.prepareContext = function (options, content) {
  assert.object(options, 'options');

  options[exports.TYPE] = {};
  options[exports.TYPE][CONTEXT_VAR] = exports.createContext(content);
};

exports.SelectorStage = function SelectorStage(selector, contextName, handlers) {
  AbstractStage.call(this);
  this.selector = selector;
  this.contextName = contextName || undefined;
  this.handlers = [];

  if (typeof handlers === 'string') {
    handlers = [handlers];
  }

  handlers = handlers || [];

  var self = this;

  this.getName = function () {
    return exports.TYPE;
  };

  this.getSelector = function () {
    return this.selector;
  };

  this.val = function val() {
    this.handlers.push(function val() {
      return this.val();
    });

    return self;
  };

  this.data = function data() {
    this.handlers.push(function data() {
      return this.data();
    });

    return self;
  };

  this.html = function html() {
    this.handlers.push(function html() {
      return this.html();
    });

    return self;
  };

  this.text = function text() {
    this.handlers.push(function text() {
      return this.text();
    });

    return self;
  };

  this.attr = function attr(attrValue) {
    this.handlers.push(function attr() {
      return this.attr(attrValue);
    });

    return self;
  };

  this.find = function find(findValue) {
    this.handlers.push(function find() {
      return this.find(findValue);
    });

    return self;
  };

  this.parent = function parent() {
    this.handlers.push(function parent() {
      return this.parent();
    });

    return self;
  };

  this.next = function next() {
    this.handlers.push(function next() {
      return this.next();
    });

    return self;
  };

  this.prev = function prev() {
    this.handlers.push(function prev() {
      return this.prev();
    });

    return self;
  };

  this.children = function children(childrenValue) {
    this.handlers.push(function children() {
      return this.children(childrenValue);
    });

    return self;
  };

  this.last = function last() {
    this.handlers.push(function last() {
      return this.last();
    });

    return self;
  };

  this.first = function first() {
    this.handlers.push(function first() {
      return this.first();
    });

    return self;
  };

  //default text handler
  if (handlers) {
    var re = /(.+)=(.+)/;

    for (var i in handlers) {
      if (handlers.hasOwnProperty(i)) {
        var handler = handlers[i];

        var value = undefined;
        var matches = handler.match(re);

        if (matches) {
          value = matches[2];
          handler = matches[1];
        }

        switch (handler) {
          case 'html' :
            this.html();
            break;
          case 'text' :
            this.text();
            break;
          case 'val' :
            this.val();
            break;
          case 'data' :
            this.data();
            break;
          case 'attr' :
            this.attr(value);
            break;
          case 'find' :
            this.find(value);
            break;
          case 'parent' :
            this.parent();
            break;
          case 'next' :
            this.next();
            break;
          case 'prev' :
            this.prev();
            break;
          case 'children' :
            this.children(value);
            break;
          case 'last' :
            this.last();
            break;
          case 'first' :
            this.first();
            break;
          default:
            logger.warn('Invalid handler: ' + handlers[i]);
        }
      }
    }
  }

  if (!this.handlers || this.handlers.length < 1) {
    this.text();
  }

  assert.arrayOfFunc(this.handlers, 'this.handlers');

  this.execute = function (value, options, callback) {
    logger.debug('Executing selector stage with selector: ' + this.selector + ' for value: ' + value);

    assert.object(options, 'options');

    var err = null;
    var result = null;

    if (!this.selector) {
      err = new StageError('Missing "selector" for selectorStage');
      return callback(err, result);
    }

    if (value) {
      logger.debug('Use custom context for selector: ' + this.selector + ' for value: ' + value);
      exports.prepareContext(options, value);
    }

    assert.object(options[exports.TYPE], 'options.' + exports.TYPE);
    assert.func(options[exports.TYPE][CONTEXT_VAR], 'options.' + exports.TYPE + '.' + CONTEXT_VAR);
    var $$ = options[exports.TYPE][CONTEXT_VAR];

    if (this.contextName) {
      logger.debug('Executing selector: ' + this.selector + ' witch contextName: ' + this.contextName);
    }

    var selectorValue = $$(this.selector, this.contextName);

    if (!isEmptySelector(selectorValue)) {
      var size = this.handlers.length;
      var handler = null;

      if (size > 1) {
        for (var i in this.handlers) {
          if (this.handlers.hasOwnProperty(i)) {
            handler = this.handlers[i];

            if (i < size - 1) {
              selectorValue = handler.bind(selectorValue)();
            }
          }
        }
      }

      handler = this.handlers[size - 1];
      assert.func(handler, 'handler');

      if (selectorValue.length < 2) {
        result = handler.bind(selectorValue)();
      }
      else {
        var result = [];

        selectorValue.each(function () {

          var val = handler.bind($$(this))();
          result.push(val);
        });
      }
    }
    else {
      logger.info('Unable to find value for given selector: ' + this.selector);
    }

    return callback(err, result);
  };

};

module.exports = exports;<|endoftext|>


<commit_before>"use babel"

helpers = require('atom-linter')
path    = require('path')

// This provides linter support for Perl 6 using linter
// Please see https://atom.io/packages/linter
module.exports =
class Perl6Linter {

  constructor() {
    this.name          = 'Perl 6 Syntax Check'
    this.grammarScopes = ['source.perl6', 'source.perl6fe']
    this.scope         = 'file'
    this.lintOnFly     = true
  }

  lint(textEditor) {
    command = "perl6"
    args = ["-Ilib", '-c', "-"]

    // Find project directory for the text editor provided
    projectDir = atom.project.getDirectories().find(
      (dir) => {
        return dir.contains(textEditor.getPath() )
      }
    )
    projectDir = projectDir.path ? projectDir.path : null;

    options = {
      cwd: projectDir,
      stream : "",
      stdin  : textEditor.getText()
    }
    return helpers.exec(command, args, options).then( (output) => {
      console.log(output)

      // return nothing if no errors are found
      if (output.stdout.startsWith("Syntax OK") && output.stderr == "") {
        return []
      }

      // Try to find the error message and line number
      regex = /.+?[\r\n]((?:.|[\r\n])+\s+at.+?(\d+)\s+.+)/
      stderr = output.stderr
      match = regex.exec(stderr)
      if (match) {
        // Success; Remove the ansi escape sequence noise from the message
        message = match[1].replace(/\x1b\[\d+(;\d+)?m/g, "")
        line    = match[2] - 1
      } else {
        // We failed, at least show the message without line number information
        message = stderr.replace("===SORRY!===", "")
        line    = 0
      }

      // The error message is for the whole line
      colEnd = textEditor.getBuffer().lineLengthForRow(line)

      // Return the message to atom lint plugin
      return [{
        type: 'Error',
        text: message,
        range:[[line, 0], [line, colEnd]],
        filePath: textEditor.getPath()
      }]
    })
  }
}<commit_msg>Always remove ANSI escape sequences (syntax check linter)<commit_after>"use babel"

helpers = require('atom-linter')
path    = require('path')

// This provides linter support for Perl 6 using linter
// Please see https://atom.io/packages/linter
module.exports =
class Perl6Linter {

  constructor() {
    this.name          = 'Perl 6 Syntax Check'
    this.grammarScopes = ['source.perl6', 'source.perl6fe']
    this.scope         = 'file'
    this.lintOnFly     = true
  }

  lint(textEditor) {
    command = "perl6"
    args = ["-Ilib", '-c', "-"]

    // Find project directory for the text editor provided
    projectDir = atom.project.getDirectories().find(
      (dir) => {
        return dir.contains(textEditor.getPath() )
      }
    )
    projectDir = projectDir.path ? projectDir.path : null;

    options = {
      cwd: projectDir,
      stream : "",
      stdin  : textEditor.getText()
    }
    return helpers.exec(command, args, options).then( (output) => {
      console.log(output)

      // return nothing if no errors are found
      if (output.stdout.startsWith("Syntax OK") && output.stderr == "") {
        return []
      }

      // Try to find the error message and line number
      regex = /.+?[\r\n]((?:.|[\r\n])+\s+at.+?(\d+)\s+.+)/
      stderr = output.stderr
      match = regex.exec(stderr)
      if (match) {
        // Success; Remove the ansi escape sequence noise from the message
        message = match[1]
        line    = match[2] - 1
      } else {
        // We failed, at least show the message without line number information
        message = stderr.replace("===SORRY!===", "")
        line    = 0
      }

      // The error message is for the whole line
      colEnd = textEditor.getBuffer().lineLengthForRow(line)

      // Return the message to atom lint plugin
      return [{
        type: 'Error',
        text: message.replace(/\x1b\[\d+(;\d+)?m/g, ""),
        range:[[line, 0], [line, colEnd]],
        filePath: textEditor.getPath()
      }]
    })
  }
}<|endoftext|>


<commit_before>"use babel"

helpers = require('atom-linter')
path    = require('path')

getLibDir = (filepath) => {
  projpaths = atom.project.getPaths()
  home =
    process.platform.startsWith('win') ? process.env.HOMEPATH : process.env.HOME
  curpath = path.dirname(filepath)
  while (curpath != path.dirname(curpath)) {
    if( projpaths.find( (p) => p == curpath)) { return false }
    if (curpath == home)      { return false }
    if (path.basename(curpath) == 'lib') {
      return "-I#{curpath}"
    }
    curpath = path.dirname(curpath)
  }
  return false
}

// This provides linter support for Perl 6 using linter
// Please see https://atom.io/packages/linter
module.exports =
class Perl6Linter {

  constructor() {
    this.name          = 'Perl 6 Syntax Check'
    this.grammarScopes = ['source.perl6', 'source.perl6fe']
    this.scope         = 'file'
    this.lintOnFly     = true
  }

  lint(textEditor) {
    command = "perl6"
    lib = getLibDir(textEditor.getPath())
    args = [`-I#{lib}`, '-c', "-"]
    options = {
      stream : "",
      stdin  : textEditor.getText()
    }
    return helpers.exec(command, args, options).then( (output) => {
      console.log(output)

      // return nothing if no errors are found
      if (output.stdout.startsWith("Syntax OK") && output.stderr == "") {
        return []
      }

      // Try to find the error message and line number
      regex = /(.+)\sat\s.+\:(\d+)/
      stderr = output.stderr
      match = regex.exec(stderr)
      if (match) {
        // Success!
        message = match[1]
        line    = match[2] - 1
      } else {
        // We failed, at least show the message without line number information
        message = stderr.replace("===SORRY!===\n", "")
        line    = 0
      }

      // The error message is for the whole line
      colEnd = textEditor.getBuffer().lineLengthForRow(line)

      // Return the message to atom lint plugin
      return [{
        type: 'Error',
        text: message,
        range:[[line, 0], [line, colEnd]],
        filePath: textEditor.getPath()
      }]
    })
  }
}<commit_msg>Fix replace str<commit_after>"use babel"

helpers = require('atom-linter')
path    = require('path')

getLibDir = (filepath) => {
  projpaths = atom.project.getPaths()
  home =
    process.platform.startsWith('win') ? process.env.HOMEPATH : process.env.HOME
  curpath = path.dirname(filepath)
  while (curpath != path.dirname(curpath)) {
    if( projpaths.find( (p) => p == curpath)) { return false }
    if (curpath == home)      { return false }
    if (path.basename(curpath) == 'lib') {
      return "-I#{curpath}"
    }
    curpath = path.dirname(curpath)
  }
  return false
}

// This provides linter support for Perl 6 using linter
// Please see https://atom.io/packages/linter
module.exports =
class Perl6Linter {

  constructor() {
    this.name          = 'Perl 6 Syntax Check'
    this.grammarScopes = ['source.perl6', 'source.perl6fe']
    this.scope         = 'file'
    this.lintOnFly     = true
  }

  lint(textEditor) {
    command = "perl6"
    lib = getLibDir(textEditor.getPath())
    args = [`-I#{lib}`, '-c', "-"]
    options = {
      stream : "",
      stdin  : textEditor.getText()
    }
    return helpers.exec(command, args, options).then( (output) => {
      console.log(output)

      // return nothing if no errors are found
      if (output.stdout.startsWith("Syntax OK") && output.stderr == "") {
        return []
      }

      // Try to find the error message and line number
      regex = /(.+)\sat\s.+\:(\d+)/
      stderr = output.stderr
      match = regex.exec(stderr)
      if (match) {
        // Success!
        message = match[1]
        line    = match[2] - 1
      } else {
        // We failed, at least show the message without line number information
        message = stderr.replace("===SORRY!===", "")
        line    = 0
      }

      // The error message is for the whole line
      colEnd = textEditor.getBuffer().lineLengthForRow(line)

      // Return the message to atom lint plugin
      return [{
        type: 'Error',
        text: message,
        range:[[line, 0], [line, colEnd]],
        filePath: textEditor.getPath()
      }]
    })
  }
}<|endoftext|>


<commit_before>module.exports = async (ctx, task) => {
    const got = require('got');
    let response;

    try {
        response = await got('https://api.github.com/repos/TryGhost/Ghost/releases', {json: true});
    } catch (err) {
        task.title = 'Unable to fetch release notes';
        return;
    }

    const relevantNotes = response.body.filter(note => note.tag_name === ctx.version)[0];

    if (!relevantNotes) {
        task.title = 'Release notes were not found';
        return;
    }

    task.title = 'Fetched release notes';
    ctx.ui.log(`\n${relevantNotes.body}\n`, 'green');
};
<commit_msg>fix(notes): add 5 second timeout for release notes call (#1355)<commit_after>module.exports = async (ctx, task) => {
    const got = require('got');
    let response;

    try {
        response = await got('https://api.github.com/repos/TryGhost/Ghost/releases', {json: true, timeout: 5000});
    } catch (err) {
        task.title = 'Unable to fetch release notes';
        return;
    }

    const relevantNotes = response.body.filter(note => note.tag_name === ctx.version)[0];

    if (!relevantNotes) {
        task.title = 'Release notes were not found';
        return;
    }

    task.title = 'Fetched release notes';
    ctx.ui.log(`\n${relevantNotes.body}\n`, 'green');
};
<|endoftext|>


<commit_before>var mapping = {
	styles: ['css', 'less', 'scss', 'styl'],
	scripts: ['js', 'jsx', 'es6', 'es', 'coffee'],
	templates: ['jade', 'json', 'html', 'htm'],
	images: ['jpg', 'jpeg', 'png', 'svg']
}

module.exports = function(gulp, config, watch) {

	if(config.mapping) {
		Object.keys(config.mapping).forEach(function(key) {
			mapping[key] = config.mapping[key]
		})
	}

	var fileExtensions = ['css','styl','scss','less','js','jsx','es6','es','coffee','jade','json','html','htm']
	Object.keys(mapping).forEach(function(key) {
		mapping[key] = mapping[key].map(function(i) {
			var ext = '.' + i.replace(/^\./, '') // remove . from the beginning of the string
			if(fileExtensions.indexOf(key) == -1) {
				fileExtensions.push(ext.substring(1))
			}
			return new RegExp(ext + '$')
		})
	})

	return function(done) {
		var c = require('better-console')
		c.info('Watching sources for change and recompilation...')

		var minimatch = require('minimatch')
		var path = require('path')
		var runcmd = require('../helpers/runcmd')
		var glob = '**/*.{' + fileExtensions.join() + '}'
		var globDist = config.dist_folder + '/**/*.*'

		var completeHandler = function(e) {
			if(config.hooks && config.hooks.watch) runcmd(config.hooks.watch)
		}

		var changeHandler = function(filepath) {
			// Filter dist sources
			if (minimatch(filepath, globDist)) {
				return
			}

			config._lastChanged = filepath

			var handler = false

			Object.keys(mapping).forEach(function (key) {

				mapping[key].forEach(function(regexp) {
					if(filepath.match(regexp)) {
						handler = key
					}
				})
			})

			if (!handler) {
				c.warn('! unknown extension', path.extname(filepath), filepath)
				return
			}

			gulp.start(handler, completeHandler)
		}

		watch(glob, changeHandler)

		done()
	}
}
<commit_msg>watch_sources: multiple handlers for one file type Use case: template or stylesheet files can be required into js files Previous implementation was broken anyway, it executed just last matched handler<commit_after>var mapping = {
	styles: ['css', 'less', 'scss', 'styl'],
	scripts: ['js', 'jsx', 'es6', 'es', 'coffee'],
	templates: ['jade', 'json', 'html', 'htm'],
	images: ['jpg', 'jpeg', 'png', 'svg']
}

module.exports = function(gulp, config, watch) {

	if(config.mapping) {
		Object.keys(config.mapping).forEach(function(key) {
			mapping[key] = config.mapping[key]
		})
	}

	var fileExtensions = ['css','styl','scss','less','js','jsx','es6','es','coffee','jade','json','html','htm']
	Object.keys(mapping).forEach(function(key) {
		mapping[key] = mapping[key].map(function(i) {
			var ext = '.' + i.replace(/^\./, '') // remove . from the beginning of the string
			if(fileExtensions.indexOf(key) == -1) {
				fileExtensions.push(ext.substring(1))
			}
			return new RegExp(ext + '$')
		})
	})

	return function(done) {
		var c = require('better-console')
		c.info('Watching sources for change and recompilation...')

		var minimatch = require('minimatch')
		var path = require('path')
		var runcmd = require('../helpers/runcmd')
		var glob = '**/*.{' + fileExtensions.join() + '}'
		var globDist = config.dist_folder + '/**/*.*'

		var completeHandler = function(e) {
			if(config.hooks && config.hooks.watch) runcmd(config.hooks.watch)
		}

		var changeHandler = function(filepath) {
			// Filter dist sources
			if (minimatch(filepath, globDist)) {
				return
			}

			config._lastChanged = filepath

			var handlers = []

			Object.keys(mapping).forEach(function (key) {

				mapping[key].forEach(function(regexp) {
					if(filepath.match(regexp)) {
						handlers.push(key)
					}
				})
			})

			if (!handlers.length) {
				c.warn('! unknown extension', path.extname(filepath), filepath)
				return
			}

			handlers.forEach(function(handler) {
				gulp.start(handler, completeHandler)
			})

		}

		watch(glob, changeHandler)

		done()
	}
}
<|endoftext|>


<commit_before>UM.prototype.umEditGroupHelpers = {
    groupschema: function () {
        return Group.simpleSchema();
    },
    group: function () {
        return Groups.findOne({
            _id: FlowRouter.getParam("groupId")
        });
    },
    agency: function () {
        if (SchemaPlain.user.agency)
            return true;
    },
    projects: function () {
        if (SchemaPlain.user.projects)
            return true;
    },
    getLeaders: function () {
        return LeaderSearch.getData({
            transform: function (matchText, regExp) {
                return matchText;
            },
            sort: {
                isoScore: -1
            }
        });
    },
    email: function () {
        if (this.emails)
            return this.emails[0].address;
    },
    getSubGroups: function () {
        return SubGroupSearch.getData({
            transform: function (matchText, regExp) {
                return matchText;
            },
            sort: {
                isoScore: -1
            }
        });
    },
    getUsersForGroup: function () {
        return UserSearch.getData({
            transform: function (matchText, regExp) {
                return matchText;
            },
            sort: {
                isoScore: -1
            }
        });
    },
    user: function () {
        if (this.id && typeof this.id !== 'undefined') {
            var user = Meteor.users.findOne({
                _id: this.id
            });
        }
        if (user) {
            return user.emails[0].address;
        }
    },
    parentGroupName: function () {
        if (this.parentGroup && typeof this.parentGroup !== 'undefined')
            return Groups.findOne({
                _id: this.parentGroup
            }).groupname;
    },
    leaderEmail: function () {
        if (typeof this.leader !== 'undefined')
            var leader = Meteor.users.findOne({
                _id: this.leader
            });
        if (leader)
            return leader.emails[0].address;
    },
    abort: function () {
        return __('abort');
    },
    remove: function () {
        return __('remove');
    },
    save: function () {
        return __('save');
    },
    groups: function () {
        return Groups;
    }
};

UM.prototype.umEditGroupEvents = {
    'click #removeGroup': function () {
        groupId = FlowRouter.getParam("groupId");
        Meteor.call('removeGroup', groupId, function (err, res) {
            console.log(err);
            if (!err)
                Router.go('/showGroups');
        });
    },
    'click .fullname': function (e) {
        //yes :P
        var val = $(e.target).html();
        if (this.emails && this.emails[0] && this.emails[0].address) {
            val = this.emails[0].address;
        }
        $('#leader').val(val);

    },
    'click .parentGroup': function (e) {
        //yes :P
        var val = $(e.target).html();
        if (this.groupname) {
            val = this.groupname;
        }
        $('#parentGroupName').val(val);
    },
    'click .user': function (e) {
        //yes :P
        $('#userEmail').val($(e.target).html());
    },
    'click .clickableSpan': function (e) {
        var groupId = FlowRouter.getParam("groupId");
        // UserSearch.search();
        Meteor.call('addUserToGroup', this._id, groupId);
    },
    'keyup #users ': function (e) {
        UserSearch.search(e.target.value);
    },
    'click #removeUser': function (e) {
        var groupId = FlowRouter.getParam("groupId");
        Meteor.call('removeUserFromGroup', this.id, this.useremail,
            groupId);
    },
    'click .userGroupRoles': function (e) {
        Router.go('/editGroup/' + FlowRouter.getParam("groupId") +
            '/addUserToGroupRole/' + this.id);
    }
};
<commit_msg>clear the input field and close the dropdown when member was added<commit_after>UM.prototype.umEditGroupHelpers = {
    groupschema: function () {
        return Group.simpleSchema();
    },
    group: function () {
        return Groups.findOne({
            _id: FlowRouter.getParam("groupId")
        });
    },
    agency: function () {
        if (SchemaPlain.user.agency)
            return true;
    },
    projects: function () {
        if (SchemaPlain.user.projects)
            return true;
    },
    getLeaders: function () {
        return LeaderSearch.getData({
            transform: function (matchText, regExp) {
                return matchText;
            },
            sort: {
                isoScore: -1
            }
        });
    },
    email: function () {
        if (this.emails)
            return this.emails[0].address;
    },
    getSubGroups: function () {
        return SubGroupSearch.getData({
            transform: function (matchText, regExp) {
                return matchText;
            },
            sort: {
                isoScore: -1
            }
        });
    },
    getUsersForGroup: function () {
        return UserSearch.getData({
            transform: function (matchText, regExp) {
                return matchText;
            },
            sort: {
                isoScore: -1
            }
        });
    },
    user: function () {
        if (this.id && typeof this.id !== 'undefined') {
            var user = Meteor.users.findOne({
                _id: this.id
            });
        }
        if (user) {
            return user.emails[0].address;
        }
    },
    parentGroupName: function () {
        if (this.parentGroup && typeof this.parentGroup !== 'undefined')
            return Groups.findOne({
                _id: this.parentGroup
            }).groupname;
    },
    leaderEmail: function () {
        if (typeof this.leader !== 'undefined')
            var leader = Meteor.users.findOne({
                _id: this.leader
            });
        if (leader)
            return leader.emails[0].address;
    },
    abort: function () {
        return __('abort');
    },
    remove: function () {
        return __('remove');
    },
    save: function () {
        return __('save');
    },
    groups: function () {
        return Groups;
    }
};

UM.prototype.umEditGroupEvents = {
    'click #removeGroup': function () {
        groupId = FlowRouter.getParam("groupId");
        Meteor.call('removeGroup', groupId, function (err, res) {
            console.log(err);
            if (!err)
                Router.go('/showGroups');
        });
    },
    'click .fullname': function (e) {
        //yes :P
        var val = $(e.target).html();
        if (this.emails && this.emails[0] && this.emails[0].address) {
            val = this.emails[0].address;
        }
        $('#leader').val(val);

    },
    'click .parentGroup': function (e) {
        //yes :P
        var val = $(e.target).html();
        if (this.groupname) {
            val = this.groupname;
        }
        $('#parentGroupName').val(val);
    },
    'click .user': function (e) {
        //yes :P
        $('#userEmail').val($(e.target).html());
    },
    'click .clickableSpan': function (e, tmpl) {
        // clear the input field and close the dropdown
        tmpl.$('#users').val('');
        UserSearch.search();
        // add the user to the group
        var groupId = FlowRouter.getParam("groupId");
        Meteor.call('addUserToGroup', this._id, groupId);
    },
    'keyup #users ': function (e) {
        UserSearch.search(e.target.value);
    },
    'click #removeUser': function (e) {
        var groupId = FlowRouter.getParam("groupId");
        Meteor.call('removeUserFromGroup', this.id, this.useremail,
            groupId);
    },
    'click .userGroupRoles': function (e) {
        Router.go('/editGroup/' + FlowRouter.getParam("groupId") +
            '/addUserToGroupRole/' + this.id);
    }
};
<|endoftext|>


<commit_before>// Copyright (c) 2018, Compiler Explorer Team
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
"use strict";

const
    BaseTool = require('./base-tool');

class PaholeTool extends BaseTool {
    constructor(toolInfo, env) {
        super(toolInfo, env);
    }

    runTool(sourcefile, args, compilerExe, outputFilename, option, filters) {
        if(!filters.binary)
        {
            // Pahole needs a compiled file in order to process it
            var compiledFile = outputFilename.replace("output.s", "output.o");
            var compilerOptions = [
                "-c",
                outputFilename,
                "-o",
                compiledFile,
            ];
            this.exec(compilerExe, compilerOptions);
            return super.runTool(compiledFile, args);
        }
        return super.runTool(outputFilename, args);
    }
}

module.exports = PaholeTool;
<commit_msg>Tooling : use promise when compiling for pahole<commit_after>// Copyright (c) 2018, Compiler Explorer Team
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
"use strict";

const
    BaseTool = require('./base-tool');

class PaholeTool extends BaseTool {
    constructor(toolInfo, env) {
        super(toolInfo, env);
    }

    runTool(sourcefile, args, compilerExe, outputFilename, option, filters) {
        if(!filters.binary)
        {
            // Pahole needs a compiled file in order to process it
            var compiledFile = outputFilename.replace("output.s", "output.o");
            var compilerOptions = [
                "-c",
                outputFilename,
                "-o",
                compiledFile,
            ];
            this.exec(compilerExe, compilerOptions).then(result => {
                return super.runTool(compiledFile, args);
            });
        }
        return super.runTool(outputFilename, args);
    }
}

module.exports = PaholeTool;
<|endoftext|>