<commit_before>'use babel';

// eslint-disable-next-line import/no-extraneous-dependencies, import/extensions
import { CompositeDisposable } from 'atom';

let helpers;
let path;

// Local variables
const parseRegex = /\[(\d+)(?:, \d+)*\]:(.*) \[.+\/(.+).md\]/g;

const loadDeps = () => {
  if (!helpers) {
    helpers = require('atom-linter');
  }
  if (!path) {
    path = require('path');
  }
};

export default {
  activate() {
    this.idleCallbacks = new Set();
    let depsCallbackID;
    const installLinterReekDeps = () => {
      this.idleCallbacks.delete(depsCallbackID);
      if (!atom.inSpecMode()) {
        require('atom-package-deps').install('linter-reek');
      }
      loadDeps();
      if (atom.inDevMode()) {
        // eslint-disable-next-line no-console
        console.log('linter-reek: All dependencies installed.');
      }
    };
    depsCallbackID = window.requestIdleCallback(installLinterReekDeps);
    this.idleCallbacks.add(depsCallbackID);

    this.subscriptions = new CompositeDisposable();
    this.subscriptions.add(atom.config.observe(
      'linter-reek.executablePath',
      (value) => { this.executablePath = value; },
    ));

    if (atom.inDevMode()) {
      /* eslint-disable no-console */
      console.log('linter-reek: Reek linter is now activated.');
      console.log(`linter-reek: Command path: ${this.executablePath}`);
      /* eslint-enable no-console */
    }
  },

  deactivate() {
    this.idleCallbacks.forEach(callbackID => window.cancelIdleCallback(callbackID));
    this.idleCallbacks.clear();
    this.subscriptions.dispose();
  },

  provideLinter() {
    return {
      name: 'reek',
      grammarScopes: ['source.ruby', 'source.ruby.rails', 'source.ruby.rspec'],
      scope: 'file',
      lintsOnChange: false,
      lint: async (TextEditor) => {
        const filePath = TextEditor.getPath();
        if (!filePath) {
          // Somehow a TextEditor without a path was passed in
          return null;
        }

        const fileText = TextEditor.getText();
        loadDeps();

        const execOpts = {
          cwd: path.dirname(filePath),
          ignoreExitCode: true,
        };

        let output;
        try {
          output = await helpers.exec(this.executablePath, [filePath], execOpts);
        } catch (e) {
          if (e.message !== 'Process execution timed out') throw e;
          atom.notifications.addInfo('linter-reek: Linter timed out', {
            description: 'A timeout occured while executing reek, it could be due to lower resources ' +
                         'or a temporary overload, try a few seconds later, please.'
          });
          return null;
        }

        if (TextEditor.getText() !== fileText) {
          // Editor contents have changed, tell Linter not to update
          return null;
        }

        const messages = [];

        let match = parseRegex.exec(output);
        while (match !== null) {
          const line = Number.parseInt(match[1], 10) - 1;
          const ruleLink = `https://github.com/troessner/reek/blob/master/docs/${match[3]}.md`;
          messages.push({
            url: ruleLink,
            severity: 'warning',
            excerpt: `${match[2]}`,
            location: {
              file: filePath,
              position: helpers.generateRange(TextEditor, line),
            },
          });
          match = parseRegex.exec(output);
        }
        return messages;
      },
    };
  },
};
<commit_msg>Fixed missed comma<commit_after>'use babel';

// eslint-disable-next-line import/no-extraneous-dependencies, import/extensions
import { CompositeDisposable } from 'atom';

let helpers;
let path;

// Local variables
const parseRegex = /\[(\d+)(?:, \d+)*\]:(.*) \[.+\/(.+).md\]/g;

const loadDeps = () => {
  if (!helpers) {
    helpers = require('atom-linter');
  }
  if (!path) {
    path = require('path');
  }
};

export default {
  activate() {
    this.idleCallbacks = new Set();
    let depsCallbackID;
    const installLinterReekDeps = () => {
      this.idleCallbacks.delete(depsCallbackID);
      if (!atom.inSpecMode()) {
        require('atom-package-deps').install('linter-reek');
      }
      loadDeps();
      if (atom.inDevMode()) {
        // eslint-disable-next-line no-console
        console.log('linter-reek: All dependencies installed.');
      }
    };
    depsCallbackID = window.requestIdleCallback(installLinterReekDeps);
    this.idleCallbacks.add(depsCallbackID);

    this.subscriptions = new CompositeDisposable();
    this.subscriptions.add(atom.config.observe(
      'linter-reek.executablePath',
      (value) => { this.executablePath = value; },
    ));

    if (atom.inDevMode()) {
      /* eslint-disable no-console */
      console.log('linter-reek: Reek linter is now activated.');
      console.log(`linter-reek: Command path: ${this.executablePath}`);
      /* eslint-enable no-console */
    }
  },

  deactivate() {
    this.idleCallbacks.forEach(callbackID => window.cancelIdleCallback(callbackID));
    this.idleCallbacks.clear();
    this.subscriptions.dispose();
  },

  provideLinter() {
    return {
      name: 'reek',
      grammarScopes: ['source.ruby', 'source.ruby.rails', 'source.ruby.rspec'],
      scope: 'file',
      lintsOnChange: false,
      lint: async (TextEditor) => {
        const filePath = TextEditor.getPath();
        if (!filePath) {
          // Somehow a TextEditor without a path was passed in
          return null;
        }

        const fileText = TextEditor.getText();
        loadDeps();

        const execOpts = {
          cwd: path.dirname(filePath),
          ignoreExitCode: true,
        };

        let output;
        try {
          output = await helpers.exec(this.executablePath, [filePath], execOpts);
        } catch (e) {
          if (e.message !== 'Process execution timed out') throw e;
          atom.notifications.addInfo('linter-reek: Linter timed out', {
            description: 'A timeout occured while executing reek, it could be due to lower resources ' +
                         'or a temporary overload, try a few seconds later, please.',
          });
          return null;
        }

        if (TextEditor.getText() !== fileText) {
          // Editor contents have changed, tell Linter not to update
          return null;
        }

        const messages = [];

        let match = parseRegex.exec(output);
        while (match !== null) {
          const line = Number.parseInt(match[1], 10) - 1;
          const ruleLink = `https://github.com/troessner/reek/blob/master/docs/${match[3]}.md`;
          messages.push({
            url: ruleLink,
            severity: 'warning',
            excerpt: `${match[2]}`,
            location: {
              file: filePath,
              position: helpers.generateRange(TextEditor, line),
            },
          });
          match = parseRegex.exec(output);
        }
        return messages;
      },
    };
  },
};
<|endoftext|>


<commit_before>/**
 * @file Anchor component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';

import CircularLoading from '../CircularLoading';
import TipProvider from '../TipProvider';
import Theme from '../Theme';

import Util from '../_vendors/Util';

export default class Anchor extends Component {

    static Theme = Theme;

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.state = {
            focused: false
        };

        this.touchTapHandler = ::this.touchTapHandler;
        this.focusHandler = ::this.focusHandler;
        this.blurHandler = ::this.blurHandler;

    }

    touchTapHandler(e) {
        e.preventDefault();
        const {disabled, isLoading, onTouchTap} = this.props;
        !disabled && !isLoading && onTouchTap && onTouchTap(e);
    }

    focusHandler(e) {
        this.setState({
            focused: true
        }, () => {
            const {onFocus} = this.props;
            onFocus && onFocus(e);
        });
    }

    blurHandler(e) {
        this.setState({
            focused: false
        }, () => {
            const {onBlur} = this.props;
            onBlur && onBlur(e);
        });
    }

    render() {

        const {

                children, className, style, theme,
                iconCls, rightIconCls, disabled, isLoading, tip, tipPosition,

                ...restProps

            } = this.props,
            {focused} = this.state,

            anchorClassName = (focused ? ' focused' : '') + (theme ? ` theme-${theme}` : '')
                + (className ? ' ' + className : ''),

            loadingIconPosition = (rightIconCls && !iconCls) ? 'right' : 'left';

        return (
            <TipProvider text={tip}
                         position={tipPosition}>

                    {
                        isLoading && loadingIconPosition === 'left' ?
                            <CircularLoading className="anchor-icon anchor-icon-left button-loading-icon"
                                             size="small"/>
                            :
                            (
                                iconCls ?
                                    <i className={`anchor-icon anchor-icon-left ${iconCls}`}
                                       aria-hidden="true">
                                    :
                                    null
                            )
                    }

                    {children}

                    {
                        isLoading && loadingIconPosition === 'right' ?
                            <CircularLoading className="anchor-icon anchor-icon-right button-loading-icon"
                                             size="small"/>
                            :
                            (
                                rightIconCls ?
                                    <i className={`anchor-icon anchor-icon-right ${rightIconCls}`}
                                       aria-hidden="true">
                                    :
                                    null
                            )
                    }

            </TipProvider>
        );

    }
};

Anchor.propTypes = {

    className: PropTypes.string,
    style: PropTypes.object,
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    href: PropTypes.string,
    alt: PropTypes.string,
    target: PropTypes.string,

    disabled: PropTypes.bool,
    readOnly: PropTypes.bool,
    isLoading: PropTypes.bool,

    iconCls: PropTypes.string,
    rightIconCls: PropTypes.string,

    tip: PropTypes.string,
    tipPosition: PropTypes.string,

    onTouchTap: PropTypes.func,
    onFocus: PropTypes.func,
    onBlur: PropTypes.func

};

Anchor.defaultProps = {

    className: null,
    style: null,
    theme: Theme.DEFAULT,

    href: 'javascript:void(0)',
    alt: null,
    target: '_blank',

    disabled: false,
    readOnly: false,
    isLoading: false,

    iconCls: null,
    rightIconCls: null

};<commit_msg>update Anchor<commit_after>/**
 * @file Anchor component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';

import CircularLoading from '../CircularLoading';
import TipProvider from '../TipProvider';
import Theme from '../Theme';

import Util from '../_vendors/Util';

export default class Anchor extends Component {

    static Theme = Theme;
    static propTypes = {

        className: PropTypes.string,
        style: PropTypes.object,
        theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

        href: PropTypes.string,
        alt: PropTypes.string,
        target: PropTypes.string,

        disabled: PropTypes.bool,
        readOnly: PropTypes.bool,
        isLoading: PropTypes.bool,

        iconCls: PropTypes.string,
        rightIconCls: PropTypes.string,

        tip: PropTypes.string,
        tipPosition: PropTypes.string,

        onTouchTap: PropTypes.func,
        onFocus: PropTypes.func,
        onBlur: PropTypes.func

    };
    static defaultProps = {

        className: null,
        style: null,
        theme: Theme.DEFAULT,

        href: 'javascript:void(0)',
        alt: null,
        target: '_blank',

        disabled: false,
        readOnly: false,
        isLoading: false,

        iconCls: null,
        rightIconCls: null

    };

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.state = {
            focused: false
        };

        this.touchTapHandler = ::this.touchTapHandler;
        this.focusHandler = ::this.focusHandler;
        this.blurHandler = ::this.blurHandler;

    }

    touchTapHandler(e) {
        e.preventDefault();
        const {disabled, isLoading, onTouchTap} = this.props;
        !disabled && !isLoading && onTouchTap && onTouchTap(e);
    }

    focusHandler(e) {
        this.setState({
            focused: true
        }, () => {
            const {onFocus} = this.props;
            onFocus && onFocus(e);
        });
    }

    blurHandler(e) {
        this.setState({
            focused: false
        }, () => {
            const {onBlur} = this.props;
            onBlur && onBlur(e);
        });
    }

    render() {

        const {

                children, className, style, theme,
                iconCls, rightIconCls, disabled, isLoading, tip, tipPosition,

                ...restProps

            } = this.props,
            {focused} = this.state,

            anchorClassName = (focused ? ' focused' : '') + (theme ? ` theme-${theme}` : '')
                + (className ? ' ' + className : ''),

            loadingIconPosition = (rightIconCls && !iconCls) ? 'right' : 'left';

        return (
            <TipProvider text={tip}
                         position={tipPosition}>

                    {
                        isLoading && loadingIconPosition === 'left' ?
                            <CircularLoading className="anchor-icon anchor-icon-left button-loading-icon"
                                             size="small"/>
                            :
                            (
                                iconCls ?
                                    <i className={`anchor-icon anchor-icon-left ${iconCls}`}
                                       aria-hidden="true">
                                    :
                                    null
                            )
                    }

                    {children}

                    {
                        isLoading && loadingIconPosition === 'right' ?
                            <CircularLoading className="anchor-icon anchor-icon-right button-loading-icon"
                                             size="small"/>
                            :
                            (
                                rightIconCls ?
                                    <i className={`anchor-icon anchor-icon-right ${rightIconCls}`}
                                       aria-hidden="true">
                                    :
                                    null
                            )
                    }

            </TipProvider>
        );

    }
};<|endoftext|>


<commit_before>var _gulp   = require('gulp');
var _rename = require('gulp-rename');
//var _core = require('./vendor/spryker/zed-package/gulpfile');

var _path   = require('path');
var _del    = require('del');

var _dirCore = 'vendor/spryker/zed-package/src/ProjectA/Zed';
var _dirProj = 'src/Pyz/Zed';
var _dirPub  = 'static/public/Zed/bundles';

var _dirStatPub = '/Static/Public';

function _buildSource(type) {
	var source = {
		'css'    : 'styles/**/*.css',
		'js'     : 'scripts/**/*.js',
		'images' : 'images/**/*.{svg,png,jpeg,gif}',
		'fonts'  : 'fonts/**/*.{svg,woff,otf,ttf,eot}'
	};

	return [
		_path.join(_dirCore, '*', _dirStatPub, source[type]),
		_path.join(_dirProj, '*', _dirStatPub, source[type])
	];
}

function _changeDest(path) {
	path.dirname = path.dirname.replace(_dirStatPub, '');
}

function _copy(type) {
	return _gulp.src(_buildSource(type))
		.pipe(_rename(_changeDest))
		.pipe(_gulp.dest(_dirPub));
}

_gulp.task('clean-css', function(done) {
	_del(_dirPub + '/*/styles', done);
});

_gulp.task('clean-js', function(done) {
	_del(_dirPub + '/*/scripts', done);
});

_gulp.task('clean-images', function(done) {
	_del(_dirPub + '/*/images', done);
});

_gulp.task('clean-fonts', function(done) {
	_del(_dirPub + '/*/fonts', done);
});

_gulp.task('copy-css', ['clean-css'], function() {
	return _copy('css');
});

_gulp.task('copy-js', ['clean-js'], function() {
	return _copy('js');
});

_gulp.task('copy-images', ['clean-images'], function() {
	return _copy('images');
});

_gulp.task('copy-fonts', ['clean-fonts'], function() {
	return _copy('fonts');
});

_gulp.task('watcher', ['dev'], function() {
	_gulp.watch([
		_dirCore + '/*/Static/Public/*/styles/**/*.css',
		_dirProj + '/*/Static/Public/*/styles/**/*.css'
	], ['clean-css', 'copy-css']);

	_gulp.watch([
		_dirCore + '/*/Static/Public/*/scripts/**/*.js',
		_dirProj + '/*/Static/Public/*/scripts/**/*.js'
	],['clean-js', 'copy-js']);

	_gulp.watch([
		_dirCore + '/*/Static/Public/*/images/**/*.{svg,png,jpeg,gif}',
		_dirProj + '/*/Static/Public/*/images/**/*.{svg,png,jpeg,gif}'
	], ['clean-images', 'copy-images']);

	_gulp.watch([
		_dirCore + '/*/Static/Public/*/fonts/**/*.{svg,woff,otf,ttf,eot}',
		_dirProj + '/*/Static/Public/*/fonts/**/*.{svg,woff,otf,ttf,eot}'
	], ['clean-fonts', 'copy-fonts']);
});

_gulp.task('dev', [
	'clean-css',
	'clean-js',
	'clean-images',
	'clean-fonts',
	'copy-css',
	'copy-js',
	'copy-images',
	'copy-fonts'
]);

_gulp.task('dist', [
	'clean-css',
	'clean-js',
	'clean-images',
	'clean-fonts',
	'copy-css',
	'copy-js',
	'copy-images',
	'copy-fonts'
]);

_gulp.task('default', [
	'dist'
]);<commit_msg>Added core tasks to Zed Gulpfile<commit_after>var _gulp   = require('gulp');
var _rename = require('gulp-rename');
var _core   = require('../../vendor/spryker/zed-package/gulpfile');

var _path   = require('path');
var _del    = require('del');

var _dirCore = 'vendor/spryker/zed-package/src/ProjectA/Zed';
var _dirProj = 'src/Pyz/Zed';
var _dirPub  = 'static/public/Zed/bundles';

var _dirStatPub = '/Static/Public';

function _buildSource(type) {
	var source = {
		'css'    : 'styles/**/*.css',
		'js'     : 'scripts/**/*.js',
		'images' : 'images/**/*.{svg,png,jpeg,gif}',
		'fonts'  : 'fonts/**/*.{svg,woff,otf,ttf,eot}'
	};

	return [
		_path.join(_dirCore, '*', _dirStatPub, source[type]),
		_path.join(_dirProj, '*', _dirStatPub, source[type])
	];
}

function _changeDest(path) {
	path.dirname = path.dirname.replace(_dirStatPub, '');
}

function _copy(type) {
	return _gulp.src(_buildSource(type))
		.pipe(_rename(_changeDest))
		.pipe(_gulp.dest(_dirPub));
}

_gulp.task('clean-css', function(done) {
	_del(_dirPub + '/*/styles', done);
});

_gulp.task('clean-js', function(done) {
	_del(_dirPub + '/*/scripts', done);
});

_gulp.task('clean-images', function(done) {
	_del(_dirPub + '/*/images', done);
});

_gulp.task('clean-fonts', function(done) {
	_del(_dirPub + '/*/fonts', done);
});

_gulp.task('copy-css', ['clean-css'], function() {
	return _copy('css');
});

_gulp.task('copy-js', ['clean-js'], function() {
	return _copy('js');
});

_gulp.task('copy-images', ['clean-images'], function() {
	return _copy('images');
});

_gulp.task('copy-fonts', ['clean-fonts'], function() {
	return _copy('fonts');
});

_gulp.task('core-dev', function(done) {
	_core.createCoreResources('./vendor/spryker/zed-package', 'dev', done);
});

_gulp.task('core-dist', function(done) {
	_core.createCoreResources('./vendor/spryker/zed-package', 'dist', done);
});

_gulp.task('watcher', function() {
	_core.watchCoreResources('./vendor/spryker/zed-package', function(task) {
		var map = {
			'dev-css'    : 'copy-css',
			'dev-js'     : 'copy-js',
			'dev-images' : 'copy-images',
			'dev-fonts'  : 'copy-fonts'
		};

		if (task in map) _gulp.start(map[task]);
	});
});

_gulp.task('dev', [
	'clean-css',
	'clean-js',
	'clean-images',
	'clean-fonts',
	'copy-css',
	'copy-js',
	'copy-images',
	'copy-fonts'
]);

_gulp.task('dist', [
	'clean-css',
	'clean-js',
	'clean-images',
	'clean-fonts',
	'copy-css',
	'copy-js',
	'copy-images',
	'copy-fonts'
]);

_gulp.task('dev-all', ['core-dev'], function(done) {
	_gulp.start([
		'clean-css',
		'clean-js',
		'clean-images',
		'clean-fonts',
		'copy-css',
		'copy-js',
		'copy-images',
		'copy-fonts'
	], done);
});

_gulp.task('dist-all', ['core-dist'], function(done) {
	_gulp.start([
		'clean-css',
		'clean-js',
		'clean-images',
		'clean-fonts',
		'copy-css',
		'copy-js',
		'copy-images',
		'copy-fonts'
	], done);
});

_gulp.task('default', [
	'dist'
]);<|endoftext|>


<commit_before>/**
 * Module dependencies
 */

var package = require('../package');
var encode = require('websafe-base64').encode;
var slug = require('slug');
var map = require('map');

/**
 * Initialize our regular expression for url construction/deconstruction
 */

var regexp = /:([\w-]+)/g;

/**
 * Register it with angular
 */

package.directive('hyperLink', [
  function() {
    return {
      link: function($scope, elem, attrs) {
        elem.addClass('ng-hyper-loading');

        var keys = parse(attrs.hyperLink);

        var exp = '[' + keys.toString() + ']';

        $scope.$watch(exp, function() {
          var loaded = true;

          var href = attrs.hyperLink.replace(regexp, function(full, key) {
            if ($scope[key] || $scope[key] === 0) return fmt($scope[key]);
            loaded = false;
            return '-';
          });

          // we're still waiting for properties to come in
          if (!loaded) return;

          elem.attr('href', href);
          elem.removeClass('ng-hyper-loading');
          elem.addClass('ng-hyper-loaded');
        }, true);
      }
    };
  }
]);

/**
 * Parse the link
 */

exports.parse = parse;
function parse(link) {
  return map(link.match(regexp), function(key) {
    return key.substr(1);
  });
}

/**
 * Format a value for the url
 */

exports.fmt = fmt;
function fmt(v) {
  if (v && v.href) return encode(v.href);
  return slug(v);
}
<commit_msg>add support for older browsers in hyper-link<commit_after>/**
 * Module dependencies
 */

var package = require('../package');
var encode = require('websafe-base64').encode;
var slug = require('slug');
var map = require('map');

/**
 * Initialize our regular expression for url construction/deconstruction
 */

var regexp = /:([\w-]+)/g;

/**
 * Register it with angular
 */

package.directive('hyperLink', [
  function() {
    return {
      link: function($scope, elem, attrs) {
        elem.addClass('ng-hyper-loading');

        var keys = parse(attrs.hyperLink);

        var exp = '[' + keys.toString() + ']';

        $scope.$watch(exp, function() {
          var loaded = true;

          var href = attrs.hyperLink.replace(regexp, function(full, key) {
            if ($scope[key] || $scope[key] === 0) return fmt($scope[key]);
            loaded = false;
            return '-';
          });

          // we're still waiting for properties to come in
          if (!loaded) return;

          // If we're in a browser that doesn't support push state
          if (!window.history.pushState) href = '/#!' + href;

          elem.attr('href', href);
          elem.removeClass('ng-hyper-loading');
          elem.addClass('ng-hyper-loaded');
        }, true);
      }
    };
  }
]);

/**
 * Parse the link
 */

exports.parse = parse;
function parse(link) {
  return map(link.match(regexp), function(key) {
    return key.substr(1);
  });
}

/**
 * Format a value for the url
 */

exports.fmt = fmt;
function fmt(v) {
  if (v && v.href) return encode(v.href);
  return slug(v);
}
<|endoftext|>


<commit_before>function log(message) {
  //console.log(message);
}

// Detect a github page. I use this method instead of an URL check to support github enterprise
// instances.
function isGithubSite() {
  return $('meta[property="og:site_name"]').attr('content') === 'GitHub';
}

function isBlobPage() {
  var matcher =/^(\/[-A-Za-z0-9_.]+){2}\/blob\//;
  return matcher.exec(window.location.pathname);
}

function getRawFileURL() {
  return window.location.origin.replace('://', '://raw.') + window.location.pathname.replace('/blob', '');
}

function getRawFileMastBranchURL(rawFileURL) {
  return rawFileURL.replace(/^(http[s]?\:\/\/raw\.([-A-Za-z0-9_.]+\/){3})([-A-Za-z0-9_.]+)([-A-Za-z0-9_./]+)/,
    function(match, protocolServerUserFork, _notused_, branch, path) {
      return protocolServerUserFork + 'master' + path;
    });
}

function getBlobFileURL(rawFileURL, lineNumber) {
  return rawFileURL.replace(/^(http[s]?\:\/\/)raw\.(([-A-Za-z0-9_.]+\/){3})([-A-Za-z0-9_./]+)/,
    function(match, protocol, serverUserFork, _notused_, branchPath) {
      return protocol + serverUserFork + 'blob/' + branchPath;
    }) + '#L' + lineNumber;
}

function ctagsLanguageKey(language) {
  return language.replace(/\+/g,'');
}

function saveCtags(lang, ctags) {
  var langKey = ctagsLanguageKey(lang);

  var obj= {};
  obj[langKey] = ctags;

  chrome.storage.local.set(obj, function() {
    log('Ctags saved: ' + lang);
  });
}

function loadCtags(lang, callback) {
  var langKey = ctagsLanguageKey(lang);
  chrome.storage.local.get(lang, function(value) {
    if (value && value[langKey]) {
      log('Ctags loaded: ' + lang);
      callback(value[langKey]);
    } else {
      callback({});
    }
  })
};

function equalCount(a, b) {
  for (var i=0, n = Math.min(a.length, b.length); i<n && a.charAt(i) === b.charAt(i); ++i);
  return i;
}

function bestBlobURLForCtag(rawSourceFile, links) {

  console.log(rawSourceFile, links);

  var rawSourceFileMaster = getRawFileMastBranchURL(rawSourceFile);
  var bestLink = links[0];
  var bestLinkEquality = equalCount(bestLink[0], rawSourceFile);
  var abort = false;

  links.forEach(function(link, index, array) {
    if (abort)
      return;

    if (rawSourceFile === link[0]) {
      bestLink = link;
      abort = true;
    } else {

      var equalityToRaw = equalCount(link[0], rawSourceFile);
      var equalityToRawMaster = equalCount(link[0], rawSourceFileMaster);
      var linkEquality = Math.min(equalityToRaw, equalityToRawMaster);

      if (linkEquality > bestLinkEquality) {
        bestLink = link;
        bestLinkEquality = linkEquality;
      }

    }
  });

  return getBlobFileURL(bestLink[0], bestLink[1]);
}

function generateCtags(rawFileURL) {
  log('Generating Ctags for ' + rawFileURL);
  Module['CTags_parseFile'](rawFileURL);
}

var current_language = 'unknown';
var current_ctags = {};

function updateGithubSourceCodeLines() {
  $('.line span').live('mouseover', function() {
      if (!$(this).data('ctagsApplied')) {

        var links = current_ctags[this.innerText];

        if (links)
        {
          // TODO: pick the best link here!
          var blobFileURL = bestBlobURLForCtag(getRawFileURL(), links);

          $(this).html('' + $(this).html() + '');
        }

        // We don't want to check ctags for this  again
        $(this).data('ctagsApplied', true);
      }
  });
}

function initCtags() {

  // Add callback for new found ctags
  Module['CTags_setOnTagEntry'](function(name, kind, lineNumber, sourceFile, language) {
    log('Found tag: ' + name);

    if (language !== current_language) {
      log.error('Oops. Wrong language?!');
      return;
    }

    var tagArray = current_ctags[name];
    if (!tagArray) {
      current_ctags[name] = tagArray = [];
    }

    // Check if the
    var index;
    if (tagArray.some(function (tag, i) { index = i; return tag[0] === sourceFile; })) {
      if (tagArray[index][1] !== lineNumber) {
        log('Update tag: ' + name + ' -> ' + lineNumber + ':' + sourceFile);
        tagArray[index][1] = lineNumber;
      }
    } else {
      log('Add tag: ' + name + ' -> ' + lineNumber + ':' + sourceFile);
      tagArray.push([sourceFile, lineNumber]);
    }
  });

  Module['CTags_setOnParsingCompleted'](function(sourceFile) {
    saveCtags(current_language, current_ctags);

    // Reset source code lines that have no  ctags links, yet
    $('.line span').map(function() {
      if ($(this).children().length)
        $(this).data('ctagsApplied', false);
    });
  });

  // Read language of current file
  var currentRawFileURL = getRawFileURL();
  current_language = Module['CTags_getLanguage'](currentRawFileURL);
  log('Language detected: ' + current_language);

  if (current_language && current_language != 'unknown') {
    loadCtags(current_language, function(loadedTags) {
      current_ctags = loadedTags;
      generateCtags(currentRawFileURL);
    });
  } else {
    log('Unknown language: ' + currentRawFileURL);
  }
}

chrome.extension.onRequest.addListener(function(request, sender, callback)
{
  if (isBlobPage() && isGithubSite()) {
    initCtags();
    updateGithubSourceCodeLines();
  }
});
<commit_msg>Cleanup<commit_after>function log(message) {
  //console.log(message);
}

// Detect a github page. I use this method instead of an URL check to support github enterprise
// instances.
function isGithubSite() {
  return $('meta[property="og:site_name"]').attr('content') === 'GitHub';
}

function isBlobPage() {
  var matcher =/^(\/[-A-Za-z0-9_.]+){2}\/blob\//;
  return matcher.exec(window.location.pathname);
}

function getRawFileURL() {
  return window.location.origin.replace('://', '://raw.') + window.location.pathname.replace('/blob', '');
}

function getRawFileMastBranchURL(rawFileURL) {
  return rawFileURL.replace(/^(http[s]?\:\/\/raw\.([-A-Za-z0-9_.]+\/){3})([-A-Za-z0-9_.]+)([-A-Za-z0-9_./]+)/,
    function(match, protocolServerUserFork, _notused_, branch, path) {
      return protocolServerUserFork + 'master' + path;
    });
}

function getBlobFileURL(rawFileURL, lineNumber) {
  return rawFileURL.replace(/^(http[s]?\:\/\/)raw\.(([-A-Za-z0-9_.]+\/){3})([-A-Za-z0-9_./]+)/,
    function(match, protocol, serverUserFork, _notused_, branchPath) {
      return protocol + serverUserFork + 'blob/' + branchPath;
    }) + '#L' + lineNumber;
}

function ctagsLanguageKey(language) {
  return language.replace(/\+/g,'');
}

function saveCtags(lang, ctags) {
  var langKey = ctagsLanguageKey(lang);

  var obj= {};
  obj[langKey] = ctags;

  chrome.storage.local.set(obj, function() {
    log('Ctags saved: ' + lang);
  });
}

function loadCtags(lang, callback) {
  var langKey = ctagsLanguageKey(lang);
  chrome.storage.local.get(lang, function(value) {
    if (value && value[langKey]) {
      log('Ctags loaded: ' + lang);
      callback(value[langKey]);
    } else {
      callback({});
    }
  })
};

function equalCount(a, b) {
  for (var i=0, n = Math.min(a.length, b.length); i<n && a.charAt(i) === b.charAt(i); ++i);
  return i;
}

function bestBlobURLForCtag(rawSourceFile, links) {

  console.log(rawSourceFile, links);

  var rawSourceFileMaster = getRawFileMastBranchURL(rawSourceFile);
  var bestLink = links[0];
  var bestLinkEquality = equalCount(bestLink[0], rawSourceFile);
  var abort = false;

  links.forEach(function(link, index, array) {
    if (abort)
      return;

    if (rawSourceFile === link[0]) {
      bestLink = link;
      abort = true;
    } else {

      var equalityToRaw = equalCount(link[0], rawSourceFile);
      var equalityToRawMaster = equalCount(link[0], rawSourceFileMaster);
      var linkEquality = Math.min(equalityToRaw, equalityToRawMaster);

      if (linkEquality > bestLinkEquality) {
        bestLink = link;
        bestLinkEquality = linkEquality;
      }

    }
  });

  return getBlobFileURL(bestLink[0], bestLink[1]);
}

function generateCtags(rawFileURL) {
  log('Generating Ctags for ' + rawFileURL);
  Module['CTags_parseFile'](rawFileURL);
}

var current_language = 'unknown';
var current_ctags = {};

function updateGithubSourceCodeLines() {
  $('.line span').live('mouseover', function() {
      if (!$(this).data('ctagsApplied')) {

        var links = current_ctags[this.innerText];

        if (links)
        {
          var blobFileURL = bestBlobURLForCtag(getRawFileURL(), links);

          $(this).html('' + $(this).html() + '');
        }

        // We don't want to check ctags for this  again
        $(this).data('ctagsApplied', true);
      }
  });
}

function initCtags() {

  // Add callback for new found ctags
  Module['CTags_setOnTagEntry'](function(name, kind, lineNumber, sourceFile, language) {
    log('Found tag: ' + name);

    if (language !== current_language) {
      log.error('Oops. Wrong language?!');
      return;
    }

    var tagArray = current_ctags[name];
    if (!tagArray) {
      current_ctags[name] = tagArray = [];
    }

    var index;
    if (tagArray.some(function (tag, i) { index = i; return tag[0] === sourceFile; })) {
      if (tagArray[index][1] !== lineNumber) {
        log('Update tag: ' + name + ' -> ' + lineNumber + ':' + sourceFile);
        tagArray[index][1] = lineNumber;
      }
    } else {
      log('Add tag: ' + name + ' -> ' + lineNumber + ':' + sourceFile);
      tagArray.push([sourceFile, lineNumber]);
    }
  });

  Module['CTags_setOnParsingCompleted'](function(sourceFile) {
    saveCtags(current_language, current_ctags);

    // Reset source code lines that have no  ctags links, yet
    $('.line span').map(function() {
      if ($(this).children().length)
        $(this).data('ctagsApplied', false);
    });
  });

  // Read language of current file
  var currentRawFileURL = getRawFileURL();
  current_language = Module['CTags_getLanguage'](currentRawFileURL);
  log('Language detected: ' + current_language);

  if (current_language && current_language != 'unknown') {
    loadCtags(current_language, function(loadedTags) {
      current_ctags = loadedTags;
      generateCtags(currentRawFileURL);
    });
  } else {
    log('Unknown language: ' + currentRawFileURL);
  }
}

chrome.extension.onRequest.addListener(function(request, sender, callback)
{
  if (isBlobPage() && isGithubSite()) {
    initCtags();
    updateGithubSourceCodeLines();
  }
});
<|endoftext|>


<commit_before>var clip = require('copy-paste').global();

var socket = require('socket.io-client')(process.argv[2]);
var id = undefined;
if(process.argv[3])
	id = process.argv[3];

socket.on('connect', function () { console.log("socket connected"); });
socket.on('id', function(i)
{
	if(!id)
		id = i;

	console.log("My id is: " + id);
	socket.on(id + "", function(msg)
	{
		console.log("Adding " + msg + " to the clipboard");
		clip.copy(msg);
	});
})
//socket.emit('private message', { user: 'me', msg: 'whazzzup?' });<commit_msg>Delete node-client.js<commit_after><|endoftext|>


<commit_before>/* eslint-env jest, node */

// monkey patch node's console :-/
console.debug = console.debug || console.info;

import _ from 'lodash';
import { __deleteEverything__, configActions, configActionTypes } from '../actions';
import { Field, Form } from '../form';
import { store } from '../store';
import { DEFAULT_CLUSTER_CONFIG } from '../cluster-config';
import { toError, toAsyncError, toIgnore } from '../utils';
// TODO: (kans) test these things
// toExtraData, toInFly, toExtraDataInFly, toExtraDataError

const invalid = 'is invalid';
const fieldName = 'aField';

const expectCC = (path, expected, f) => {
  const value = _.get(store.getState().clusterConfig, f ? f(path) : path);
  expect(value).toEqual(expected);
};

const resetCC = () => store.dispatch({
  type: configActionTypes.SET, payload: DEFAULT_CLUSTER_CONFIG,
});

const updateField = (field, value) => store.dispatch(configActions.updateField(field, value));

beforeEach(() => store.dispatch(__deleteEverything__()));

test('updates a Field', () => {
  expect.assertions(4);

  const name = 'aField';
  const aField = new Field(name, {
    default: 'a',
    validator: (value, cc) => {
      expect(value).toEqual('b');
      expect(cc[name]).toEqual('b');
    },
  });

  new Form('aForm', [aField]);
  resetCC();

  expectCC(name, 'a');
  updateField(name, 'b');
  expectCC(name, 'b');
});

test('field dependency validator is called', done => {
  expect.assertions(1);

  const aName = 'aField';

  const aField = new Field(aName, {default: 'a'});
  const bField = new Field('bField', {
    default: 'c',
    dependencies: [aName],
    validator: (value, cc) => {
      expect(cc[aName]).toEqual('b');
      done();
    },
  });

  new Form('aForm', [aField, bField]);

  resetCC();
  updateField(aName, 'b');
});

test('form validator is called', done => {
  expect.assertions(3);

  new Form('aForm', [new Field(fieldName, {default: 'a'})], {
    validator: (value, cc, oldValue) => {
      expectCC(fieldName, 'b');
      expect(value[fieldName]).toEqual('b');
      expect(oldValue[fieldName]).toEqual('a');
      done();
    },
  });

  resetCC();
  updateField(fieldName, 'b');
});

test('sync invalidation', () => {
  expect.assertions(3);

  const field = new Field(fieldName, {
    default: 'a',
    validator: value => value === 'b' && invalid,
  });

  new Form('aForm', [field]);

  resetCC();
  expectCC(fieldName, undefined, toError);

  updateField(fieldName, 'b');
  expectCC(fieldName, invalid, toError);

  updateField(fieldName, 'a');
  expectCC(fieldName, undefined, toError);
});

test('async invalidation', async done => {
  expect.assertions(5);

  const field = new Field(fieldName, {
    default: 'a',
    asyncValidator: (dispatch, getState, value, oldValue, isNow) => {
      expect(isNow()).toEqual(true);
      return value === 'b' && invalid;
    },
  });

  new Form('aForm', [field]);

  expectCC(fieldName, undefined, toAsyncError);

  await updateField(fieldName, 'b');
  expectCC(fieldName, invalid, toAsyncError);

  await updateField(fieldName, 'a');
  expectCC(fieldName, undefined, toAsyncError);

  done();
});

test('async (promise) invalidation', async done => {
  expect.assertions(3);

  const field = new Field(fieldName, {
    default: 'a',
    asyncValidator: (dispatch, getState, value) => new Promise((resolve, reject) =>
      value === 'b'
        ? process.nextTick(() => reject(invalid))
        : process.nextTick(resolve)
    ),
  });

  new Form('aForm', [field]);

  expectCC(fieldName, undefined, toAsyncError);
  await updateField(fieldName, 'b');

  expectCC(fieldName, invalid, toAsyncError);

  await updateField(fieldName, 'c');
  expectCC(fieldName, undefined, toAsyncError);

  done();
});

test('sync/async invalidation', async done => {
  expect.assertions(5);

  const field = new Field(fieldName, {
    default: 'a',
    validator: value => value === 'b' && invalid,
    asyncValidator: (dispatch, getState, value) => value === 'c' && invalid,
  });

  new Form('aForm', [field]);

  expectCC(fieldName, undefined, toError);

  await updateField(fieldName, 'b');
  expectCC(fieldName, invalid, toError);
  expectCC(fieldName, undefined, toAsyncError);

  await updateField(fieldName, 'c');
  expectCC(fieldName, invalid, toAsyncError);
  expectCC(fieldName, undefined, toError);

  done();
});

test('ignores', async done => {
  expect.assertions(6);

  const field1 = new Field(fieldName, { default: 'a'});

  const fieldName2 = 'bField';
  const field2 = new Field(fieldName2, {
    default: 'a',
    validator: () => invalid,
    dependencies: [fieldName],
    ignoreWhen: cc => cc[fieldName] === 'b',
  });

  const form = new Form('aForm', [field1, field2]);

  await updateField(fieldName2, 'b');
  expectCC(fieldName2, undefined, toIgnore);
  expect(form.isValid(store.getState().clusterConfig)).toEqual(false);
  await updateField(fieldName, 'b');

  expectCC(fieldName2, true, toIgnore);
  expectCC(fieldName2, invalid, toError);

  const cc = store.getState().clusterConfig;
  expect(field2.isValid(cc)).toEqual(true);
  expect(form.isValid(cc)).toEqual(true);

  done();
});
<commit_msg>frontend/tests: add test for inflight check<commit_after>/* eslint-env jest, node */

// monkey patch node's console :-/
console.debug = console.debug || console.info;

import _ from 'lodash';
import { __deleteEverything__, configActions, configActionTypes } from '../actions';
import { Field, Form } from '../form';
import { store } from '../store';
import { DEFAULT_CLUSTER_CONFIG } from '../cluster-config';
import { toError, toAsyncError, toIgnore, toInFly } from '../utils';
// TODO: (kans) test these things
// toExtraData, toExtraDataInFly, toExtraDataError

const invalid = 'is invalid';
const fieldName = 'aField';

const expectCC = (path, expected, f) => {
  const value = _.get(store.getState().clusterConfig, f ? f(path) : path);
  expect(value).toEqual(expected);
};

const resetCC = () => store.dispatch({
  type: configActionTypes.SET, payload: DEFAULT_CLUSTER_CONFIG,
});

const updateField = (field, value) => store.dispatch(configActions.updateField(field, value));

beforeEach(() => store.dispatch(__deleteEverything__()));

test('updates a Field', () => {
  expect.assertions(4);

  const name = 'aField';
  const aField = new Field(name, {
    default: 'a',
    validator: (value, cc) => {
      expect(value).toEqual('b');
      expect(cc[name]).toEqual('b');
    },
  });

  new Form('aForm', [aField]);
  resetCC();

  expectCC(name, 'a');
  updateField(name, 'b');
  expectCC(name, 'b');
});

test('field dependency validator is called', done => {
  expect.assertions(1);

  const aName = 'aField';

  const aField = new Field(aName, {default: 'a'});
  const bField = new Field('bField', {
    default: 'c',
    dependencies: [aName],
    validator: (value, cc) => {
      expect(cc[aName]).toEqual('b');
      done();
    },
  });

  new Form('aForm', [aField, bField]);

  resetCC();
  updateField(aName, 'b');
});

test('form validator is called', done => {
  expect.assertions(3);

  new Form('aForm', [new Field(fieldName, {default: 'a'})], {
    validator: (value, cc, oldValue) => {
      expectCC(fieldName, 'b');
      expect(value[fieldName]).toEqual('b');
      expect(oldValue[fieldName]).toEqual('a');
      done();
    },
  });

  resetCC();
  updateField(fieldName, 'b');
});

test('sync invalidation', () => {
  expect.assertions(3);

  const field = new Field(fieldName, {
    default: 'a',
    validator: value => value === 'b' && invalid,
  });

  new Form('aForm', [field]);

  resetCC();
  expectCC(fieldName, undefined, toError);

  updateField(fieldName, 'b');
  expectCC(fieldName, invalid, toError);

  updateField(fieldName, 'a');
  expectCC(fieldName, undefined, toError);
});

test('async invalidation', async done => {
  expect.assertions(5);

  const field = new Field(fieldName, {
    default: 'a',
    asyncValidator: (dispatch, getState, value, oldValue, isNow) => {
      expect(isNow()).toEqual(true);
      return value === 'b' && invalid;
    },
  });

  new Form('aForm', [field]);

  expectCC(fieldName, undefined, toAsyncError);

  await updateField(fieldName, 'b');
  expectCC(fieldName, invalid, toAsyncError);

  await updateField(fieldName, 'a');
  expectCC(fieldName, undefined, toAsyncError);

  done();
});

test('async (promise) invalidation', async done => {
  expect.assertions(3);

  const field = new Field(fieldName, {
    default: 'a',
    asyncValidator: (dispatch, getState, value) => new Promise((resolve, reject) =>
      value === 'b'
        ? process.nextTick(() => reject(invalid))
        : process.nextTick(resolve)
    ),
  });

  new Form('aForm', [field]);

  expectCC(fieldName, undefined, toAsyncError);
  await updateField(fieldName, 'b');

  expectCC(fieldName, invalid, toAsyncError);

  await updateField(fieldName, 'c');
  expectCC(fieldName, undefined, toAsyncError);

  done();
});

test('sync/async invalidation', async done => {
  expect.assertions(5);

  const field = new Field(fieldName, {
    default: 'a',
    validator: value => value === 'b' && invalid,
    asyncValidator: (dispatch, getState, value) => value === 'c' && invalid,
  });

  new Form('aForm', [field]);

  expectCC(fieldName, undefined, toError);

  await updateField(fieldName, 'b');
  expectCC(fieldName, invalid, toError);
  expectCC(fieldName, undefined, toAsyncError);

  await updateField(fieldName, 'c');
  expectCC(fieldName, invalid, toAsyncError);
  expectCC(fieldName, undefined, toError);

  done();
});

test('ignores', async done => {
  expect.assertions(6);

  const field1 = new Field(fieldName, { default: 'a'});

  const fieldName2 = 'bField';
  const field2 = new Field(fieldName2, {
    default: 'a',
    validator: () => invalid,
    dependencies: [fieldName],
    ignoreWhen: cc => cc[fieldName] === 'b',
  });

  const form = new Form('aForm', [field1, field2]);

  await updateField(fieldName2, 'b');
  expectCC(fieldName2, undefined, toIgnore);
  expect(form.isValid(store.getState().clusterConfig)).toEqual(false);
  await updateField(fieldName, 'b');

  expectCC(fieldName2, true, toIgnore);
  expectCC(fieldName2, invalid, toError);

  const cc = store.getState().clusterConfig;
  expect(field2.isValid(cc)).toEqual(true);
  expect(form.isValid(cc)).toEqual(true);

  done();
});

test('inFly', async done => {
  expect.assertions(3);

  const field = new Field(fieldName, {
    default: 'a',
    asyncValidator: () => new Promise(accept => {
      expectCC(fieldName, true, toInFly);
      accept();
      expectCC(fieldName, false, toInFly);
    }),
  });

  new Form('aForm', [field]);

  expectCC(fieldName, undefined, toInFly);
  await updateField(fieldName, 'b');
  done();
});
<|endoftext|>


<commit_before><commit_msg>GeoMapComponent modified, rady for spi v0.7<commit_after><|endoftext|>


<commit_before>function collectUsage(msg) {
    var err = System.err;

    err.print(msg + "\n");
    err.print("Usage:  collect.js width height\n");
    err.print("  Collects as many pages into one page.\n");
    err.print("  width / height: resulting page.\n");
    quit(1);
}

function checkCollectArgs(args) {
    if (args.length != 2) {
	collectUsage("collect.js needs two arguments.");
    } else {
	width = mm2pt(parseInt(args[0]));
	height = mm2pt(parseInt(args[1]));
    }
    return { width: width, height: height }
}

function collect(args) {
    var err = System.err;

    var params = checkCollectArgs(args);

    var stdin = new BufferedInputStream(System["in"]);
    var pdfIn = new PdfReader(stdin);
    var w = params["width"];
    var h = params["height"];

    var stdout = new BufferedOutputStream(System.out);
    var pageCount = pdfIn.getNumberOfPages();
    var pageSize = pdfIn.getPageSize(1);
    var wd = pageSize.getWidth();
    var ht = pageSize.getHeight();

    var document = new Document(new Rectangle(w, h));
    var writer = PdfWriter.getInstance(document, stdout);

    var xcopies = Math.floor(w / wd);
    var ycopies = Math.floor(h / ht);

    document.open();

    err.println("collect (" + xcopies + " x " + ycopies + ")");

    var x0 = 0.5 * (w - wd * xcopies);
    var y0 = 0.5 * (h - ht * ycopies);

    var c = 1.0;
    var s = 0.0;
    var x = x0;
    var y = y0;

    var cb = writer.getDirectContent();
    for (var page = 0; page < pageCount; page++) {
	if (0 === (page % (xcopies * ycopies))) {
	    err.print("[");
	    document.newPage();
	    x = x0;
	    y = y0;
	} else {
	    x = x + wd;
	}
	if (x > w) {
	    x = x0;
	    y = y + ht;
	}

	var pg = writer.getImportedPage(pdfIn, page + 1);
	cb.addTemplate(pg, c, s, -s, c, x, y);

	err.print("[" + (page + 1) + "]");
    }
    err.print("]");
    err.println();
    document.close();

}

registerModule({'command': 'collect',
		'name': 'collect pages into on PDFs',
		'usage': collectUsage,
		'entry': collect});
<commit_msg>COLLECT: allow some margin to make pages fit<commit_after>function collectUsage(msg) {
    var err = System.err;

    err.print(msg + "\n");
    err.print("Usage:  collect.js width height\n");
    err.print("  Collects as many pages into one page.\n");
    err.print("  width / height: resulting page.\n");
    quit(1);
}

function checkCollectArgs(args) {
    if (args.length != 2) {
	collectUsage("collect.js needs two arguments.");
    } else {
	width = mm2pt(parseInt(args[0]));
	height = mm2pt(parseInt(args[1]));
    }
    return { width: width, height: height }
}

function collect(args) {
    var err = System.err;

    var params = checkCollectArgs(args);

    var stdin = new BufferedInputStream(System["in"]);
    var pdfIn = new PdfReader(stdin);
    var w = params["width"];
    var h = params["height"];

    var stdout = new BufferedOutputStream(System.out);
    var pageCount = pdfIn.getNumberOfPages();
    var pageSize = pdfIn.getPageSize(1);
    var wd = pageSize.getWidth();
    var ht = pageSize.getHeight();

    var document = new Document(new Rectangle(w, h));
    var writer = PdfWriter.getInstance(document, stdout);

    var xcopies = Math.round(w / wd, 0);
    var ycopies = Math.round(h / ht, 0);

    document.open();

    err.println("collect (" + xcopies + " x " + ycopies + ")");

    var x0 = 0.5 * (w - wd * xcopies);
    var y0 = 0.5 * (h - ht * ycopies);

    var c = 1.0;
    var s = 0.0;
    var x = x0;
    var y = y0;

    var cb = writer.getDirectContent();
    for (var page = 0; page < pageCount; page++) {
	if (0 === (page % (xcopies * ycopies))) {
	    err.print("[");
	    document.newPage();
	    x = x0;
	    y = y0;
	} else {
	    x = x + wd;
	}
	if (x > w) {
	    x = x0;
	    y = y + ht;
	}

	var pg = writer.getImportedPage(pdfIn, page + 1);
	cb.addTemplate(pg, c, s, -s, c, x, y);

	err.print("[" + (page + 1) + "]");
    }
    err.print("]");
    err.println();
    document.close();

}

registerModule({'command': 'collect',
		'name': 'collect pages into on PDFs',
		'usage': collectUsage,
		'entry': collect});
<|endoftext|>


<commit_before>/**
 * Created by fei on 2017/03/29.
 */
"use strict";

const fs = require("fs");
const path = require("path");

const async = require("async");

class Boot {
    constructor(akyuu) {
        this.akyuu = akyuu;
        this.logger = akyuu.logger.get("boot-loader");
        this.dir = path.resolve(akyuu.projectRoot, "boots");
        this.tasks = [];
    }

    _loadTasks(dir) {
        let tasks = [];
        let stat;

        try {
            stat = fs.statSync(dir);
        } catch(e) {
            this.logger.warn(`Can't load tasks: ${e.message}`, {
                path: dir,
                error: e
            });
            return tasks;
        }

        if(!stat.isDirectory()) {
            return tasks;
        } else {
            let files;
            try {
                files = fs.readdirSync(dir);
            } catch(e) {
                throw e;
            }

            for(let i = 0; i < files.length; i++) {
                const filePath = path.resolve(dir, files[i]);
                stat = fs.statSync(filePath);
                if(stat.isDirectory()) {
                    tasks = tasks.concat(this._loadTasks(filePath));
                } else {
                    if(!files[i].endsWith(".js")) continue;

                    tasks.push({
                        name: path.basename(files[i]),
                        path: filePath,
                        beforeInit: require(filePath).beforeInit,
                        function: require(filePath).boot
                    });
                }
            }

            return tasks;
        }
    }

    load(beforeInit, callback) {
        const self = this;
        let tasks;
        try {
            tasks = this._loadTasks(this.dir);
        } catch(error) {
            this.logger.error(error);
            return process.exit(1);
        }

        const results = [];
        async.eachLimit(tasks, 10, function(task, callback) {
            if(!!task.beforeInit !== beforeInit) return process.nextTick(function() { return callback(); });

            if(task.function.length > 1) {
                task.function(self.akyuu, function(error, result) {
                    if(error) {
                        return callback(error);
                    }
                    self.logger.info(`Boot task \`${task.name}\` run success.`);
                    if(result) results.push({ name: task.name, result: result });
                    return callback();
                });
            } else {
                try {
                    const result = task.function(self.akyuu);
                    self.logger.info(`Boot task \`${task.name}\` run success.`);
                    if(result) results.push({ name: task.name, result: result });
                    return process.nextTick(function() { return callback(null, result); });
                } catch(error) {
                    self.logger.error(`Boot task \`${task.name}\` run error.`);
                    return process.nextTick(function() { return callback(error); });
                }
            }
        }, function(error) {
            if(error) {
                self.logger.error(error);
                return callback(error);
            }

            return callback(null, results);
        });
    }
}

module.exports = Boot;
<commit_msg>fix: distinguish boot load before or after init error<commit_after>/**
 * Created by fei on 2017/03/29.
 */
"use strict";

const fs = require("fs");
const path = require("path");

const async = require("async");

class Boot {
    constructor(akyuu) {
        this.akyuu = akyuu;
        this.logger = akyuu.logger.get("boot-loader");
        this.dir = path.resolve(akyuu.projectRoot, "boots");
        this.tasks = [];
    }

    _loadTasks(dir, beforeInit) {
        let tasks = [];
        let stat;

        try {
            stat = fs.statSync(dir);
        } catch(e) {
            this.logger.warn(`Can't load tasks: ${e.message}`);
            return tasks;
        }

        if(!stat.isDirectory()) {
            return tasks;
        } else {
            let files;
            try {
                files = fs.readdirSync(dir);
            } catch(e) {
                throw e;
            }

            for(let i = 0; i < files.length; i++) {
                const filePath = path.resolve(dir, files[i]);
                stat = fs.statSync(filePath);
                if(stat.isDirectory()) {
                    tasks = tasks.concat(this._loadTasks(filePath, beforeInit));
                } else {
                    if(beforeInit && !files[i].endsWith('.before.js')) {
                        continue;
                    }
                    if(!beforeInit && !files[i].endsWith('.after.js')) {
                        continue;
                    }

                    tasks.push({
                        name: path.basename(files[i]),
                        path: filePath,
                        function: require(filePath).boot
                    });
                }
            }

            return tasks;
        }
    }

    load(beforeInit, callback) {
        const self = this;

        let tasks;
        try {
            tasks = self._loadTasks(self.dir, beforeInit);
        } catch(error) {
            this.logger.error(error);
            return process.exit(1);
        }

        const results = [];
        async.eachLimit(tasks, 10, function(task, callback) {
            if(task.function.length > 1) {
                task.function(self.akyuu, function(error, result) {
                    if(error) {
                        return callback(error);
                    }
                    self.logger.info(`Boot task \`${task.name}\` run success.`);
                    if(result) results.push({ name: task.name, result: result });
                    return callback();
                });
            } else {
                try {
                    const result = task.function(self.akyuu);
                    self.logger.info(`Boot task \`${task.name}\` run success.`);
                    if(result) results.push({ name: task.name, result: result });
                    return process.nextTick(function() { return callback(null, result); });
                } catch(error) {
                    self.logger.error(`Boot task \`${task.name}\` run error.`);
                    return process.nextTick(function() { return callback(error); });
                }
            }
        }, function(error) {
            if(error) {
                self.logger.error(error);
                return callback(error);
            }

            return callback(null, results);
        });
    }
}

module.exports = Boot;
<|endoftext|>


<commit_before><commit_msg>resolve type parameter refs for open union/intersections<commit_after><|endoftext|>


<commit_before><commit_msg>Create init.js<commit_after><|endoftext|>


<commit_before>// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
  "use strict";

  function wordRegexp(words) {
    return new RegExp("^((" + words.join(")|(") + "))\\b");
  }

  var wordOperators = wordRegexp(["and", "or", "not", "is", "in"]);
  var commonKeywords = ["as", "assert", "break", "class", "continue",
                        "def", "del", "elif", "else", "except", "finally",
                        "for", "from", "global", "if", "import",
                        "lambda", "pass", "raise", "return",
                        "try", "while", "with", "yield"];
  var commonBuiltins = ["abs", "all", "any", "bin", "bool", "bytearray", "callable", "chr",
                        "classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod",
                        "enumerate", "eval", "filter", "float", "format", "frozenset",
                        "getattr", "globals", "hasattr", "hash", "help", "hex", "id",
                        "input", "int", "isinstance", "issubclass", "iter", "len",
                        "list", "locals", "map", "max", "memoryview", "min", "next",
                        "object", "oct", "open", "ord", "pow", "property", "range",
                        "repr", "reversed", "round", "set", "setattr", "slice",
                        "sorted", "staticmethod", "str", "sum", "super", "tuple",
                        "type", "vars", "zip", "__import__", "NotImplemented",
                        "Ellipsis", "__debug__"];
  var py2 = {builtins: ["apply", "basestring", "buffer", "cmp", "coerce", "execfile",
                        "file", "intern", "long", "raw_input", "reduce", "reload",
                        "unichr", "unicode", "xrange", "False", "True", "None"],
             keywords: ["exec", "print"]};
  var py3 = {builtins: ["ascii", "bytes", "exec", "print"],
             keywords: ["nonlocal", "False", "True", "None"]};

  CodeMirror.registerHelper("hintWords", "python", commonKeywords.concat(commonBuiltins));

  function top(state) {
    return state.scopes[state.scopes.length - 1];
  }

  CodeMirror.defineMode("python", function(conf, parserConf) {
    var ERRORCLASS = "error";

    var singleOperators = parserConf.singleOperators || new RegExp("^[\\+\\-\\*/%&|\\^~<>!]");
    var singleDelimiters = parserConf.singleDelimiters || new RegExp("^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]");
    var doubleOperators = parserConf.doubleOperators || new RegExp("^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))");
    var doubleDelimiters = parserConf.doubleDelimiters || new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
    var tripleDelimiters = parserConf.tripleDelimiters || new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))");
    var identifiers = parserConf.identifiers|| new RegExp("^[_A-Za-z][_A-Za-z0-9]*");
    var hangingIndent = parserConf.hangingIndent || conf.indentUnit;

    var myKeywords = commonKeywords, myBuiltins = commonBuiltins;
    if(parserConf.extra_keywords != undefined){
      myKeywords = myKeywords.concat(parserConf.extra_keywords);
    }
    if(parserConf.extra_builtins != undefined){
      myBuiltins = myBuiltins.concat(parserConf.extra_builtins);
    }
    if (parserConf.version && parseInt(parserConf.version, 10) == 3) {
      myKeywords = myKeywords.concat(py3.keywords);
      myBuiltins = myBuiltins.concat(py3.builtins);
      var stringPrefixes = new RegExp("^(([rb]|(br))?('{3}|\"{3}|['\"]))", "i");
    } else {
      myKeywords = myKeywords.concat(py2.keywords);
      myBuiltins = myBuiltins.concat(py2.builtins);
      var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
    }
    var keywords = wordRegexp(myKeywords);
    var builtins = wordRegexp(myBuiltins);

    // tokenizers
    function tokenBase(stream, state) {
      // Handle scope changes
      if (stream.sol() && top(state).type == "py") {
        var scopeOffset = top(state).offset;
        if (stream.eatSpace()) {
          var lineOffset = stream.indentation();
          if (lineOffset > scopeOffset)
            pushScope(stream, state, "py");
          else if (lineOffset < scopeOffset && dedent(stream, state))
            state.errorToken = true;
          return null;
        } else {
          var style = tokenBaseInner(stream, state);
          if (scopeOffset > 0 && dedent(stream, state))
            style += " " + ERRORCLASS;
          return style;
        }
      }
      return tokenBaseInner(stream, state);
    }

    function tokenBaseInner(stream, state) {
      if (stream.eatSpace()) return null;

      var ch = stream.peek();

      // Handle Comments
      if (ch == "#") {
        stream.skipToEnd();
        return "comment";
      }

      // Handle Number Literals
      if (stream.match(/^[0-9\.]/, false)) {
        var floatLiteral = false;
        // Floats
        if (stream.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
        if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; }
        if (stream.match(/^\.\d+/)) { floatLiteral = true; }
        if (floatLiteral) {
          // Float literals may be "imaginary"
          stream.eat(/J/i);
          return "number";
        }
        // Integers
        var intLiteral = false;
        // Hex
        if (stream.match(/^0x[0-9a-f]+/i)) intLiteral = true;
        // Binary
        if (stream.match(/^0b[01]+/i)) intLiteral = true;
        // Octal
        if (stream.match(/^0o[0-7]+/i)) intLiteral = true;
        // Decimal
        if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) {
          // Decimal literals may be "imaginary"
          stream.eat(/J/i);
          // TODO - Can you have imaginary longs?
          intLiteral = true;
        }
        // Zero by itself with no other piece of number.
        if (stream.match(/^0(?![\dx])/i)) intLiteral = true;
        if (intLiteral) {
          // Integer literals may be "long"
          stream.eat(/L/i);
          return "number";
        }
      }

      // Handle Strings
      if (stream.match(stringPrefixes)) {
        state.tokenize = tokenStringFactory(stream.current());
        return state.tokenize(stream, state);
      }

      // Handle operators and Delimiters
      if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters))
        return null;

      if (stream.match(doubleOperators)
          || stream.match(singleOperators)
          || stream.match(wordOperators))
        return "operator";

      if (stream.match(singleDelimiters))
        return null;

      if (stream.match(keywords))
        return "keyword";

      if (stream.match(builtins))
        return "builtin";

      if (stream.match(/^(self|cls)\b/))
        return "variable-2";

      if (stream.match(identifiers)) {
        if (state.lastToken == "def" || state.lastToken == "class")
          return "def";
        return "variable";
      }

      // Handle non-detected items
      stream.next();
      return ERRORCLASS;
    }

    function tokenStringFactory(delimiter) {
      while ("rub".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)
        delimiter = delimiter.substr(1);

      var singleline = delimiter.length == 1;
      var OUTCLASS = "string";

      function tokenString(stream, state) {
        while (!stream.eol()) {
          stream.eatWhile(/[^'"\\]/);
          if (stream.eat("\\")) {
            stream.next();
            if (singleline && stream.eol())
              return OUTCLASS;
          } else if (stream.match(delimiter)) {
            state.tokenize = tokenBase;
            return OUTCLASS;
          } else {
            stream.eat(/['"]/);
          }
        }
        if (singleline) {
          if (parserConf.singleLineStringErrors)
            return ERRORCLASS;
          else
            state.tokenize = tokenBase;
        }
        return OUTCLASS;
      }
      tokenString.isString = true;
      return tokenString;
    }

    function pushScope(stream, state, type) {
      var offset = 0, align = null;
      if (type == "py") {
        while (top(state).type != "py")
          state.scopes.pop();
      }
      offset = top(state).offset + (type == "py" ? conf.indentUnit : hangingIndent);
      if (type != "py" && !stream.match(/^(\s|#.*)*$/, false))
        align = stream.column() + 1;
      state.scopes.push({offset: offset, type: type, align: align});
    }

    function dedent(stream, state) {
      var indented = stream.indentation();
      while (top(state).offset > indented) {
        if (top(state).type != "py") return true;
        state.scopes.pop();
      }
      return top(state).offset != indented;
    }

    function tokenLexer(stream, state) {
      var style = state.tokenize(stream, state);
      var current = stream.current();

      // Handle '.' connected identifiers
      if (current == ".") {
        style = stream.match(identifiers, false) ? null : ERRORCLASS;
        if (style == null && state.lastStyle == "meta") {
          // Apply 'meta' style to '.' connected identifiers when
          // appropriate.
          style = "meta";
        }
        return style;
      }

      // Handle decorators
      if (current == "@")
        return stream.match(identifiers, false) ? "meta" : ERRORCLASS;

      if ((style == "variable" || style == "builtin")
          && state.lastStyle == "meta")
        style = "meta";

      // Handle scope changes.
      if (current == "pass" || current == "return")
        state.dedent += 1;

      if (current == "lambda") state.lambda = true;
      if (current == ":" && !state.lambda && top(state).type == "py")
        pushScope(stream, state, "py");

      var delimiter_index = current.length == 1 ? "[({".indexOf(current) : -1;
      if (delimiter_index != -1)
        pushScope(stream, state, "])}".slice(delimiter_index, delimiter_index+1));

      delimiter_index = "])}".indexOf(current);
      if (delimiter_index != -1) {
        if (top(state).type == current) state.scopes.pop();
        else return ERRORCLASS;
      }
      if (state.dedent > 0 && stream.eol() && top(state).type == "py") {
        if (state.scopes.length > 1) state.scopes.pop();
        state.dedent -= 1;
      }

      return style;
    }

    var external = {
      startState: function(basecolumn) {
        return {
          tokenize: tokenBase,
          scopes: [{offset: basecolumn || 0, type: "py", align: null}],
          lastStyle: null,
          lastToken: null,
          lambda: false,
          dedent: 0
        };
      },

      token: function(stream, state) {
        var addErr = state.errorToken;
        if (addErr) state.errorToken = false;
        var style = tokenLexer(stream, state);

        state.lastStyle = style;

        var current = stream.current();
        if (current && style)
          state.lastToken = current;

        if (stream.eol() && state.lambda)
          state.lambda = false;
        return addErr ? style + " " + ERRORCLASS : style;
      },

      indent: function(state, textAfter) {
        if (state.tokenize != tokenBase)
          return state.tokenize.isString ? CodeMirror.Pass : 0;

        var scope = top(state);
        var closing = textAfter && textAfter.charAt(0) == scope.type;
        if (scope.align != null)
          return scope.align - (closing ? 1 : 0);
        else
          return scope.offset - (closing ? conf.indentUnit : 0);
      },

      lineComment: "#",
      fold: "indent"
    };
    return external;
  });

  CodeMirror.defineMIME("text/x-python", "python");

  var words = function(str) { return str.split(" "); };

  CodeMirror.defineMIME("text/x-cython", {
    name: "python",
    extra_keywords: words("by cdef cimport cpdef ctypedef enum except"+
                          "extern gil include nogil property public"+
                          "readonly struct union DEF IF ELIF ELSE")
  });

});
<commit_msg>[python mode] Return to parent indentation level when scope is closed.<commit_after>// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
  "use strict";

  function wordRegexp(words) {
    return new RegExp("^((" + words.join(")|(") + "))\\b");
  }

  var wordOperators = wordRegexp(["and", "or", "not", "is", "in"]);
  var commonKeywords = ["as", "assert", "break", "class", "continue",
                        "def", "del", "elif", "else", "except", "finally",
                        "for", "from", "global", "if", "import",
                        "lambda", "pass", "raise", "return",
                        "try", "while", "with", "yield"];
  var commonBuiltins = ["abs", "all", "any", "bin", "bool", "bytearray", "callable", "chr",
                        "classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod",
                        "enumerate", "eval", "filter", "float", "format", "frozenset",
                        "getattr", "globals", "hasattr", "hash", "help", "hex", "id",
                        "input", "int", "isinstance", "issubclass", "iter", "len",
                        "list", "locals", "map", "max", "memoryview", "min", "next",
                        "object", "oct", "open", "ord", "pow", "property", "range",
                        "repr", "reversed", "round", "set", "setattr", "slice",
                        "sorted", "staticmethod", "str", "sum", "super", "tuple",
                        "type", "vars", "zip", "__import__", "NotImplemented",
                        "Ellipsis", "__debug__"];
  var py2 = {builtins: ["apply", "basestring", "buffer", "cmp", "coerce", "execfile",
                        "file", "intern", "long", "raw_input", "reduce", "reload",
                        "unichr", "unicode", "xrange", "False", "True", "None"],
             keywords: ["exec", "print"]};
  var py3 = {builtins: ["ascii", "bytes", "exec", "print"],
             keywords: ["nonlocal", "False", "True", "None"]};

  CodeMirror.registerHelper("hintWords", "python", commonKeywords.concat(commonBuiltins));

  function top(state) {
    return state.scopes[state.scopes.length - 1];
  }

  CodeMirror.defineMode("python", function(conf, parserConf) {
    var ERRORCLASS = "error";

    var singleOperators = parserConf.singleOperators || new RegExp("^[\\+\\-\\*/%&|\\^~<>!]");
    var singleDelimiters = parserConf.singleDelimiters || new RegExp("^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]");
    var doubleOperators = parserConf.doubleOperators || new RegExp("^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))");
    var doubleDelimiters = parserConf.doubleDelimiters || new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))");
    var tripleDelimiters = parserConf.tripleDelimiters || new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))");
    var identifiers = parserConf.identifiers|| new RegExp("^[_A-Za-z][_A-Za-z0-9]*");
    var hangingIndent = parserConf.hangingIndent || conf.indentUnit;

    var myKeywords = commonKeywords, myBuiltins = commonBuiltins;
    if(parserConf.extra_keywords != undefined){
      myKeywords = myKeywords.concat(parserConf.extra_keywords);
    }
    if(parserConf.extra_builtins != undefined){
      myBuiltins = myBuiltins.concat(parserConf.extra_builtins);
    }
    if (parserConf.version && parseInt(parserConf.version, 10) == 3) {
      myKeywords = myKeywords.concat(py3.keywords);
      myBuiltins = myBuiltins.concat(py3.builtins);
      var stringPrefixes = new RegExp("^(([rb]|(br))?('{3}|\"{3}|['\"]))", "i");
    } else {
      myKeywords = myKeywords.concat(py2.keywords);
      myBuiltins = myBuiltins.concat(py2.builtins);
      var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i");
    }
    var keywords = wordRegexp(myKeywords);
    var builtins = wordRegexp(myBuiltins);

    // tokenizers
    function tokenBase(stream, state) {
      // Handle scope changes
      if (stream.sol() && top(state).type == "py") {
        var scopeOffset = top(state).offset;
        if (stream.eatSpace()) {
          var lineOffset = stream.indentation();
          if (lineOffset > scopeOffset)
            pushScope(stream, state, "py");
          else if (lineOffset < scopeOffset && dedent(stream, state))
            state.errorToken = true;
          return null;
        } else {
          var style = tokenBaseInner(stream, state);
          if (scopeOffset > 0 && dedent(stream, state))
            style += " " + ERRORCLASS;
          return style;
        }
      }
      return tokenBaseInner(stream, state);
    }

    function tokenBaseInner(stream, state) {
      if (stream.eatSpace()) return null;

      var ch = stream.peek();

      // Handle Comments
      if (ch == "#") {
        stream.skipToEnd();
        return "comment";
      }

      // Handle Number Literals
      if (stream.match(/^[0-9\.]/, false)) {
        var floatLiteral = false;
        // Floats
        if (stream.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; }
        if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; }
        if (stream.match(/^\.\d+/)) { floatLiteral = true; }
        if (floatLiteral) {
          // Float literals may be "imaginary"
          stream.eat(/J/i);
          return "number";
        }
        // Integers
        var intLiteral = false;
        // Hex
        if (stream.match(/^0x[0-9a-f]+/i)) intLiteral = true;
        // Binary
        if (stream.match(/^0b[01]+/i)) intLiteral = true;
        // Octal
        if (stream.match(/^0o[0-7]+/i)) intLiteral = true;
        // Decimal
        if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) {
          // Decimal literals may be "imaginary"
          stream.eat(/J/i);
          // TODO - Can you have imaginary longs?
          intLiteral = true;
        }
        // Zero by itself with no other piece of number.
        if (stream.match(/^0(?![\dx])/i)) intLiteral = true;
        if (intLiteral) {
          // Integer literals may be "long"
          stream.eat(/L/i);
          return "number";
        }
      }

      // Handle Strings
      if (stream.match(stringPrefixes)) {
        state.tokenize = tokenStringFactory(stream.current());
        return state.tokenize(stream, state);
      }

      // Handle operators and Delimiters
      if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters))
        return null;

      if (stream.match(doubleOperators)
          || stream.match(singleOperators)
          || stream.match(wordOperators))
        return "operator";

      if (stream.match(singleDelimiters))
        return null;

      if (stream.match(keywords))
        return "keyword";

      if (stream.match(builtins))
        return "builtin";

      if (stream.match(/^(self|cls)\b/))
        return "variable-2";

      if (stream.match(identifiers)) {
        if (state.lastToken == "def" || state.lastToken == "class")
          return "def";
        return "variable";
      }

      // Handle non-detected items
      stream.next();
      return ERRORCLASS;
    }

    function tokenStringFactory(delimiter) {
      while ("rub".indexOf(delimiter.charAt(0).toLowerCase()) >= 0)
        delimiter = delimiter.substr(1);

      var singleline = delimiter.length == 1;
      var OUTCLASS = "string";

      function tokenString(stream, state) {
        while (!stream.eol()) {
          stream.eatWhile(/[^'"\\]/);
          if (stream.eat("\\")) {
            stream.next();
            if (singleline && stream.eol())
              return OUTCLASS;
          } else if (stream.match(delimiter)) {
            state.tokenize = tokenBase;
            return OUTCLASS;
          } else {
            stream.eat(/['"]/);
          }
        }
        if (singleline) {
          if (parserConf.singleLineStringErrors)
            return ERRORCLASS;
          else
            state.tokenize = tokenBase;
        }
        return OUTCLASS;
      }
      tokenString.isString = true;
      return tokenString;
    }

    function pushScope(stream, state, type) {
      var offset = 0, align = null;
      if (type == "py") {
        while (top(state).type != "py")
          state.scopes.pop();
      }
      offset = top(state).offset + (type == "py" ? conf.indentUnit : hangingIndent);
      if (type != "py" && !stream.match(/^(\s|#.*)*$/, false))
        align = stream.column() + 1;
      state.scopes.push({offset: offset, type: type, align: align});
    }

    function dedent(stream, state) {
      var indented = stream.indentation();
      while (top(state).offset > indented) {
        if (top(state).type != "py") return true;
        state.scopes.pop();
      }
      return top(state).offset != indented;
    }

    function tokenLexer(stream, state) {
      var style = state.tokenize(stream, state);
      var current = stream.current();

      // Handle '.' connected identifiers
      if (current == ".") {
        style = stream.match(identifiers, false) ? null : ERRORCLASS;
        if (style == null && state.lastStyle == "meta") {
          // Apply 'meta' style to '.' connected identifiers when
          // appropriate.
          style = "meta";
        }
        return style;
      }

      // Handle decorators
      if (current == "@")
        return stream.match(identifiers, false) ? "meta" : ERRORCLASS;

      if ((style == "variable" || style == "builtin")
          && state.lastStyle == "meta")
        style = "meta";

      // Handle scope changes.
      if (current == "pass" || current == "return")
        state.dedent += 1;

      if (current == "lambda") state.lambda = true;
      if (current == ":" && !state.lambda && top(state).type == "py")
        pushScope(stream, state, "py");

      var delimiter_index = current.length == 1 ? "[({".indexOf(current) : -1;
      if (delimiter_index != -1)
        pushScope(stream, state, "])}".slice(delimiter_index, delimiter_index+1));

      delimiter_index = "])}".indexOf(current);
      if (delimiter_index != -1) {
        if (top(state).type == current) state.scopes.pop();
        else return ERRORCLASS;
      }
      if (state.dedent > 0 && stream.eol() && top(state).type == "py") {
        if (state.scopes.length > 1) state.scopes.pop();
        state.dedent -= 1;
      }

      return style;
    }

    var external = {
      startState: function(basecolumn) {
        return {
          tokenize: tokenBase,
          scopes: [{offset: basecolumn || 0, type: "py", align: null}],
          lastStyle: null,
          lastToken: null,
          lambda: false,
          dedent: 0
        };
      },

      token: function(stream, state) {
        var addErr = state.errorToken;
        if (addErr) state.errorToken = false;
        var style = tokenLexer(stream, state);

        state.lastStyle = style;

        var current = stream.current();
        if (current && style)
          state.lastToken = current;

        if (stream.eol() && state.lambda)
          state.lambda = false;
        return addErr ? style + " " + ERRORCLASS : style;
      },

      indent: function(state, textAfter) {
        if (state.tokenize != tokenBase)
          return state.tokenize.isString ? CodeMirror.Pass : 0;

        var scope = top(state);
        var closing = textAfter && textAfter.charAt(0) == scope.type;
        if (scope.align != null)
          return scope.align - (closing ? 1 : 0);
        else if (closing && state.scopes.length > 1)
          return state.scopes[state.scopes.length - 2].offset;
        else
          return scope.offset;
      },

      lineComment: "#",
      fold: "indent"
    };
    return external;
  });

  CodeMirror.defineMIME("text/x-python", "python");

  var words = function(str) { return str.split(" "); };

  CodeMirror.defineMIME("text/x-cython", {
    name: "python",
    extra_keywords: words("by cdef cimport cpdef ctypedef enum except"+
                          "extern gil include nogil property public"+
                          "readonly struct union DEF IF ELIF ELSE")
  });

});
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';

const sizerStyle = {
	position: 'absolute',
	top: 0,
	left: 0,
	visibility: 'hidden',
	height: 0,
	overflow: 'scroll',
	whiteSpace: 'pre',
};

const INPUT_PROPS_BLACKLIST = [
	'injectStyles',
	'inputClassName',
	'inputRef',
	'inputStyle',
	'minWidth',
	'onAutosize',
	'placeholderIsMinWidth',
];

const cleanInputProps = (inputProps) => {
	INPUT_PROPS_BLACKLIST.forEach(field => delete inputProps[field]);
	return inputProps;
};

const copyStyles = (styles, node) => {
	node.style.fontSize = styles.fontSize;
	node.style.fontFamily = styles.fontFamily;
	node.style.fontWeight = styles.fontWeight;
	node.style.fontStyle = styles.fontStyle;
	node.style.letterSpacing = styles.letterSpacing;
	node.style.textTransform = styles.textTransform;
};

const isIE = /MSIE |Trident\/|Edge\//.test(window.navigator.userAgent);

const generateId = () => {
	// we only need an auto-generated ID for stylesheet injection, which is only
	// used for IE. so if the browser is not IE, this should return undefined.
	return isIE ? '_' + Math.random().toString(36).substr(2, 12) : undefined;
};

class AutosizeInput extends Component {
	constructor (props) {
		super(props);
		this.state = {
			inputWidth: props.minWidth,
			inputId: props.id || generateId(),
		};
	}
	componentDidMount () {
		this.mounted = true;
		this.copyInputStyles();
		this.updateInputWidth();
	}
	componentWillReceiveProps (nextProps) {
		const { id } = nextProps;
		if (id !== this.props.id) {
			this.setState({ inputId: id || generateId() });
		}
	}
	componentDidUpdate (prevProps, prevState) {
		if (prevState.inputWidth !== this.state.inputWidth) {
			if (typeof this.props.onAutosize === 'function') {
				this.props.onAutosize(this.state.inputWidth);
			}
		}
		this.updateInputWidth();
	}
	componentWillUnmount () {
		this.mounted = false;
	}
	inputRef = (el) => {
		this.input = el;
		if (typeof this.props.inputRef === 'function') {
			this.props.inputRef(el);
		}
	}
	placeHolderSizerRef = (el) => {
		this.placeHolderSizer = el;
	}
	sizerRef = (el) => {
		this.sizer = el;
	}
	copyInputStyles () {
		if (!this.mounted || !window.getComputedStyle) {
			return;
		}
		const inputStyles = this.input && window.getComputedStyle(this.input);
		if (!inputStyles) {
			return;
		}
		copyStyles(inputStyles, this.sizer);
		if (this.placeHolderSizer) {
			copyStyles(inputStyles, this.placeHolderSizer);
		}
	}
	updateInputWidth () {
		if (!this.mounted || !this.sizer || typeof this.sizer.scrollWidth === 'undefined') {
			return;
		}
		let newInputWidth;
		if (this.props.placeholder && (!this.props.value || (this.props.value && this.props.placeholderIsMinWidth))) {
			newInputWidth = Math.max(this.sizer.scrollWidth, this.placeHolderSizer.scrollWidth) + 2;
		} else {
			newInputWidth = this.sizer.scrollWidth + 2;
		}
		// allow for stepper UI on number types
		if (this.props.type === 'number') {
			newInputWidth += 16;
		}
		if (newInputWidth < this.props.minWidth) {
			newInputWidth = this.props.minWidth;
		}
		if (newInputWidth !== this.state.inputWidth) {
			this.setState({
				inputWidth: newInputWidth,
			});
		}
	}
	getInput () {
		return this.input;
	}
	focus () {
		this.input.focus();
	}
	blur () {
		this.input.blur();
	}
	select () {
		this.input.select();
	}
	renderStyles () {
		// this method injects styles to hide IE's clear indicator, which messes
		// with input size detection. the stylesheet is only injected when the
		// browser is IE, and can also be disabled by the `injectStyles` prop.
		const { injectStyles } = this.props;
		return isIE && injectStyles ? (


<commit_before>const FriendlyErrorsWebpackPlugin = require( 'friendly-errors-webpack-plugin' );
const ExtractTextPlugin = require( 'extract-text-webpack-plugin' );
const _ = require( './utils' );

module.exports = function ( options ) {
	const webpackConfig = {
		entry: options.entry ? _.cwd( options.entry ) : _.cwd( 'src/index.js' ),
		output: {
			path: _.cwd( 'lib' ),
			filename: 'index.js',
			libraryTarget: 'umd',
			library: options.name || ''
		},
		module: {
			loaders: [
				{
					test: /\.rgl$/,
					loader: 'pure',
				},
				{
					test: /\.js$/,
					loader: 'babel',
					exclude: /node_modules/,
					query: {
						babelrc: false,
						presets: [
							require.resolve( 'babel-preset-es2015' ),
						],
						plugins: [
							require.resolve( 'babel-plugin-add-module-exports' ),
						],
					},
				},
				{
					test: /\.(css|less)$/,
					exclude: /node_modules/,
					loader: ExtractTextPlugin.extract( 'style-loader', 'css-loader!postcss-loader!less-loader' ),
				},
				{
					test: /\.(ttf|woff|eot|svg)(\?t=\d+)*$/,
					exclude: /node_modules/,
					loader: 'url-loader?limit=102400&name=[name].[ext]?[hash:8]'
				},
			]
		},
		postcss() {
			return [ require( 'autoprefixer' )() ];
		},
		resolveLoader: {
			root: [
				_.dir( '../node_modules' ),
			],
		},
		resolve: {
			extensions: [ '', '.js', '.rgl' ],
			// 由于软连接后peerDependencies不会主动查找上层node_modules，指定fallback
			fallback: _.cwd( 'node_modules' ),
		},
		externals: [],
		plugins: [
			new FriendlyErrorsWebpackPlugin( {
				clearConsole: false,
			} ),
			new ExtractTextPlugin( 'index.css' ),
		]
	};

	// 将所有pure-*置为外部依赖
	if ( !options.bundle ) {
		webpackConfig.externals.push( pureAsExternals );
	}

	if ( options.preferSource ) {
		webpackConfig.resolve.packageMains = [ 'source:main', 'play:main', 'jsnext:main', 'browser', 'main' ];
	}

	function pureAsExternals( context, request, callback ) {
		if ( request.startsWith( 'pure-' ) ) {
			return callback( null, 'umd ' + request );
		}

		callback();
	}

	return webpackConfig;
};
<commit_msg>Change external condition to @pure/<commit_after>const FriendlyErrorsWebpackPlugin = require( 'friendly-errors-webpack-plugin' );
const ExtractTextPlugin = require( 'extract-text-webpack-plugin' );
const _ = require( './utils' );

module.exports = function ( options ) {
	const webpackConfig = {
		entry: options.entry ? _.cwd( options.entry ) : _.cwd( 'src/index.js' ),
		output: {
			path: _.cwd( 'lib' ),
			filename: 'index.js',
			libraryTarget: 'umd',
			library: options.name || ''
		},
		module: {
			loaders: [
				{
					test: /\.rgl$/,
					loader: 'pure',
				},
				{
					test: /\.js$/,
					loader: 'babel',
					exclude: /node_modules/,
					query: {
						babelrc: false,
						presets: [
							require.resolve( 'babel-preset-es2015' ),
						],
						plugins: [
							require.resolve( 'babel-plugin-add-module-exports' ),
						],
					},
				},
				{
					test: /\.(css|less)$/,
					exclude: /node_modules/,
					loader: ExtractTextPlugin.extract( 'style-loader', 'css-loader!postcss-loader!less-loader' ),
				},
				{
					test: /\.(ttf|woff|eot|svg)(\?t=\d+)*$/,
					exclude: /node_modules/,
					loader: 'url-loader?limit=102400&name=[name].[ext]?[hash:8]'
				},
			]
		},
		postcss() {
			return [ require( 'autoprefixer' )() ];
		},
		resolveLoader: {
			root: [
				_.dir( '../node_modules' ),
			],
		},
		resolve: {
			extensions: [ '', '.js', '.rgl' ],
			// 由于软连接后peerDependencies不会主动查找上层node_modules，指定fallback
			fallback: _.cwd( 'node_modules' ),
		},
		externals: [],
		plugins: [
			new FriendlyErrorsWebpackPlugin( {
				clearConsole: false,
			} ),
			new ExtractTextPlugin( 'index.css' ),
		]
	};

	// 将所有pure-*置为外部依赖
	if ( !options.bundle ) {
		webpackConfig.externals.push( pureAsExternals );
	}

	if ( options.preferSource ) {
		webpackConfig.resolve.packageMains = [ 'source:main', 'play:main', 'jsnext:main', 'browser', 'main' ];
	}

	function pureAsExternals( context, request, callback ) {
		if ( request.startsWith( '@pure/' ) ) {
			return callback( null, 'umd ' + request );
		}

		callback();
	}

	return webpackConfig;
};
<|endoftext|>


<commit_before>var address = require('./address.config.js');

module.exports = {
	// production 配置
	production: {
		assetsPublicPath: address.CDN_ADDRESS + '/dist/', // html 中引用资源的位置 // TODO: CDN地址 https://jm-team.github.io/dist/
		debug: false // debug:true devtool:"#source-map"
	},

	// dev 配置
	dev: {
		assetsPublicPath: '/dist/',
		devServer: {
			host: 'localhost', // 默认localhost <hostname/ip>: hostname or IP. 0.0.0.0 binds to all hosts.
			port: 8081, // http://localhost:8081/
			proxyTarget: address.SERVER_ADDRESS //'http://dev-webapi.jm.com' // api服务器地址
		}
	},

	// echarts 配置
	echarts: {
		enabled: true
	}
};
<commit_msg>chore echarts enabled false<commit_after>var address = require('./address.config.js');

module.exports = {
	// production 配置
	production: {
		assetsPublicPath: address.CDN_ADDRESS + '/dist/', // html 中引用资源的位置 // TODO: CDN地址 https://jm-team.github.io/dist/
		debug: false // debug:true devtool:"#source-map"
	},

	// dev 配置
	dev: {
		assetsPublicPath: '/dist/',
		devServer: {
			host: 'localhost', // 默认localhost <hostname/ip>: hostname or IP. 0.0.0.0 binds to all hosts.
			port: 8081, // http://localhost:8081/
			proxyTarget: address.SERVER_ADDRESS //'http://dev-webapi.jm.com' // api服务器地址
		}
	},

	// echarts 配置
	echarts: {
		enabled: false
	}
};
<|endoftext|>