<commit_before>/**
 * @module zrender/core/util
 */
define(function(require) {

    // 用于处理merge时无法遍历Date等对象的问题
    var BUILTIN_OBJECT = {
        '[object Function]': 1,
        '[object RegExp]': 1,
        '[object Date]': 1,
        '[object Error]': 1,
        '[object CanvasGradient]': 1,
        '[object CanvasPattern]': 1,
        // In node-canvas Image can be Canvas.Image
        '[object Image]': 1
    };

    var objToString = Object.prototype.toString;

    var arrayProto = Array.prototype;
    var nativeForEach = arrayProto.forEach;
    var nativeFilter = arrayProto.filter;
    var nativeSlice = arrayProto.slice;
    var nativeMap = arrayProto.map;
    var nativeReduce = arrayProto.reduce;

    /**
     * @param {*} source
     * @return {*} 拷贝后的新对象
     */
    function clone(source) {
        if (typeof source == 'object' && source !== null) {
            var result = source;
            if (source instanceof Array) {
                result = [];
                for (var i = 0, len = source.length; i < len; i++) {
                    result[i] = clone(source[i]);
                }
            }
            else if (
                !isBuildInObject(source)
                // 是否为 dom 对象
                && !isDom(source)
            ) {
                result = {};
                for (var key in source) {
                    if (source.hasOwnProperty(key)) {
                        result[key] = clone(source[key]);
                    }
                }
            }

            return result;
        }

        return source;
    }

    /**
     * @memberOf module:zrender/core/util
     * @param {*} target
     * @param {*} source
     * @param {boolean} [overwrite=false]
     */
    function merge(target, source, overwrite) {
        // We should escapse that source is string
        // and enter for ... in ...
        if (!isObject(source) || !isObject(target)) {
            return overwrite ? clone(source) : target;
        }

        for (var key in source) {
            if (source.hasOwnProperty(key)) {
                var targetProp = target[key];
                var sourceProp = source[key];

                if (isObject(sourceProp)
                    && isObject(targetProp)
                    && !isArray(sourceProp)
                    && !isArray(targetProp)
                    && !isDom(sourceProp)
                    && !isDom(targetProp)
                    && !isBuildInObject(sourceProp)
                    && !isBuildInObject(targetProp)
                ) {
                    // 如果需要递归覆盖，就递归调用merge
                    merge(targetProp, sourceProp, overwrite);
                }
                else if (overwrite || !(key in target)) {
                    // 否则只处理overwrite为true，或者在目标对象中没有此属性的情况
                    // NOTE，在 target[key] 不存在的时候也是直接覆盖
                    target[key] = clone(source[key], true);
                }
            }
        }

        return target;
    }

    /**
     * @param {Array} targetAndSources The first item is target, and the rests are source.
     * @param {boolean} [overwrite=false]
     * @return {*} target
     */
    function mergeAll(targetAndSources, overwrite) {
        var result = targetAndSources[0];
        for (var i = 1, len = targetAndSources.length; i < len; i++) {
            result = merge(result, targetAndSources[i], overwrite);
        }
        return result;
    }

    /**
     * @param {*} target
     * @param {*} source
     * @memberOf module:zrender/core/util
     */
    function extend(target, source) {
        for (var key in source) {
            if (source.hasOwnProperty(key)) {
                target[key] = source[key];
            }
        }
        return target;
    }

    /**
     * @param {*} target
     * @param {*} source
     * @param {boolen} [overlay=false]
     * @memberOf module:zrender/core/util
     */
    function defaults(target, source, overlay) {
        for (var key in source) {
            if (source.hasOwnProperty(key)
                && (overlay ? source[key] != null : target[key] == null)
            ) {
                target[key] = source[key];
            }
        }
        return target;
    }

    function createCanvas() {
        return document.createElement('canvas');
    }
    // FIXME
    var _ctx;
    function getContext() {
        if (!_ctx) {
            // Use util.createCanvas instead of createCanvas
            // because createCanvas may be overwritten in different environment
            _ctx = util.createCanvas().getContext('2d');
        }
        return _ctx;
    }

    /**
     * 查询数组中元素的index
     * @memberOf module:zrender/core/util
     */
    function indexOf(array, value) {
        if (array) {
            if (array.indexOf) {
                return array.indexOf(value);
            }
            for (var i = 0, len = array.length; i < len; i++) {
                if (array[i] === value) {
                    return i;
                }
            }
        }
        return -1;
    }

    /**
     * 构造类继承关系
     *
     * @memberOf module:zrender/core/util
     * @param {Function} clazz 源类
     * @param {Function} baseClazz 基类
     */
    function inherits(clazz, baseClazz) {
        var clazzPrototype = clazz.prototype;
        function F() {}
        F.prototype = baseClazz.prototype;
        clazz.prototype = new F();

        for (var prop in clazzPrototype) {
            clazz.prototype[prop] = clazzPrototype[prop];
        }
        clazz.prototype.constructor = clazz;
        clazz.superClass = baseClazz;
    }

    /**
     * @memberOf module:zrender/core/util
     * @param {Object|Function} target
     * @param {Object|Function} sorce
     * @param {boolean} overlay
     */
    function mixin(target, source, overlay) {
        target = 'prototype' in target ? target.prototype : target;
        source = 'prototype' in source ? source.prototype : source;

        defaults(target, source, overlay);
    }

    /**
     * @param {Array|TypedArray} data
     */
    function isArrayLike(data) {
        if (! data) {
            return;
        }
        if (typeof data == 'string') {
            return false;
        }
        return typeof data.length == 'number';
    }

    /**
     * 数组或对象遍历
     * @memberOf module:zrender/core/util
     * @param {Object|Array} obj
     * @param {Function} cb
     * @param {*} [context]
     */
    function each(obj, cb, context) {
        if (!(obj && cb)) {
            return;
        }
        if (obj.forEach && obj.forEach === nativeForEach) {
            obj.forEach(cb, context);
        }
        else if (obj.length === +obj.length) {
            for (var i = 0, len = obj.length; i < len; i++) {
                cb.call(context, obj[i], i, obj);
            }
        }
        else {
            for (var key in obj) {
                if (obj.hasOwnProperty(key)) {
                    cb.call(context, obj[key], key, obj);
                }
            }
        }
    }

    /**
     * 数组映射
     * @memberOf module:zrender/core/util
     * @param {Array} obj
     * @param {Function} cb
     * @param {*} [context]
     * @return {Array}
     */
    function map(obj, cb, context) {
        if (!(obj && cb)) {
            return;
        }
        if (obj.map && obj.map === nativeMap) {
            return obj.map(cb, context);
        }
        else {
            var result = [];
            for (var i = 0, len = obj.length; i < len; i++) {
                result.push(cb.call(context, obj[i], i, obj));
            }
            return result;
        }
    }

    /**
     * @memberOf module:zrender/core/util
     * @param {Array} obj
     * @param {Function} cb
     * @param {Object} [memo]
     * @param {*} [context]
     * @return {Array}
     */
    function reduce(obj, cb, memo, context) {
        if (!(obj && cb)) {
            return;
        }
        if (obj.reduce && obj.reduce === nativeReduce) {
            return obj.reduce(cb, memo, context);
        }
        else {
            for (var i = 0, len = obj.length; i < len; i++) {
                memo = cb.call(context, memo, obj[i], i, obj);
            }
            return memo;
        }
    }

    /**
     * 数组过滤
     * @memberOf module:zrender/core/util
     * @param {Array} obj
     * @param {Function} cb
     * @param {*} [context]
     * @return {Array}
     */
    function filter(obj, cb, context) {
        if (!(obj && cb)) {
            return;
        }
        if (obj.filter && obj.filter === nativeFilter) {
            return obj.filter(cb, context);
        }
        else {
            var result = [];
            for (var i = 0, len = obj.length; i < len; i++) {
                if (cb.call(context, obj[i], i, obj)) {
                    result.push(obj[i]);
                }
            }
            return result;
        }
    }

    /**
     * 数组项查找
     * @memberOf module:zrender/core/util
     * @param {Array} obj
     * @param {Function} cb
     * @param {*} [context]
     * @return {Array}
     */
    function find(obj, cb, context) {
        if (!(obj && cb)) {
            return;
        }
        for (var i = 0, len = obj.length; i < len; i++) {
            if (cb.call(context, obj[i], i, obj)) {
                return obj[i];
            }
        }
    }

    /**
     * @memberOf module:zrender/core/util
     * @param {Function} func
     * @param {*} context
     * @return {Function}
     */
    function bind(func, context) {
        var args = nativeSlice.call(arguments, 2);
        return function () {
            return func.apply(context, args.concat(nativeSlice.call(arguments)));
        };
    }

    /**
     * @memberOf module:zrender/core/util
     * @param {Function} func
     * @return {Function}
     */
    function curry(func) {
        var args = nativeSlice.call(arguments, 1);
        return function () {
            return func.apply(this, args.concat(nativeSlice.call(arguments)));
        };
    }

    /**
     * @memberOf module:zrender/core/util
     * @param {*} value
     * @return {boolean}
     */
    function isArray(value) {
        return objToString.call(value) === '[object Array]';
    }

    /**
     * @memberOf module:zrender/core/util
     * @param {*} value
     * @return {boolean}
     */
    function isFunction(value) {
        return typeof value === 'function';
    }

    /**
     * @memberOf module:zrender/core/util
     * @param {*} value
     * @return {boolean}
     */
    function isString(value) {
        return objToString.call(value) === '[object String]';
    }

    /**
     * @memberOf module:zrender/core/util
     * @param {*} value
     * @return {boolean}
     */
    function isObject(value) {
        // Avoid a V8 JIT bug in Chrome 19-20.
        // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
        var type = typeof value;
        return type === 'function' || (!!value && type == 'object');
    }

    /**
     * @memberOf module:zrender/core/util
     * @param {*} value
     * @return {boolean}
     */
    function isBuildInObject(value) {
        return !!BUILTIN_OBJECT[objToString.call(value)];
    }

    /**
     * @memberOf module:zrender/core/util
     * @param {*} value
     * @return {boolean}
     */
    function isDom(value) {
        return value && value.nodeType === 1
               && typeof(value.nodeName) == 'string';
    }

    /**
     * If value1 is not null, then return value1, otherwise judget rest of values.
     * @memberOf module:zrender/core/util
     * @return {*} Final value
     */
    function retrieve(values) {
        for (var i = 0, len = arguments.length; i < len; i++) {
            if (arguments[i] != null) {
                return arguments[i];
            }
        }
    }

    /**
     * @memberOf module:zrender/core/util
     * @param {Array} arr
     * @param {number} startIndex
     * @param {number} endIndex
     * @return {Array}
     */
    function slice() {
        return Function.call.apply(nativeSlice, arguments);
    }

    /**
     * @memberOf module:zrender/core/util
     * @param {boolean} condition
     * @param {string} message
     */
    function assert(condition, message) {
        if (!condition) {
            throw new Error(message);
        }
    }

    var util = {
        inherits: inherits,
        mixin: mixin,
        clone: clone,
        merge: merge,
        mergeAll: mergeAll,
        extend: extend,
        defaults: defaults,
        getContext: getContext,
        createCanvas: createCanvas,
        indexOf: indexOf,
        slice: slice,
        find: find,
        isArrayLike: isArrayLike,
        each: each,
        map: map,
        reduce: reduce,
        filter: filter,
        bind: bind,
        curry: curry,
        isArray: isArray,
        isString: isString,
        isObject: isObject,
        isFunction: isFunction,
        isBuildInObject: isBuildInObject,
        isDom: isDom,
        retrieve: retrieve,
        assert: assert,
        noop: function () {}
    };
    return util;
});
<commit_msg>export zrUtil.clone<commit_after>/**
 * @module zrender/core/util
 */
define(function(require) {

    // 用于处理merge时无法遍历Date等对象的问题
    var BUILTIN_OBJECT = {
        '[object Function]': 1,
        '[object RegExp]': 1,
        '[object Date]': 1,
        '[object Error]': 1,
        '[object CanvasGradient]': 1,
        '[object CanvasPattern]': 1,
        // In node-canvas Image can be Canvas.Image
        '[object Image]': 1
    };

    var TYPED_ARRAY = {
        '[object Int8Array]': 1,
        '[object Uint8Array]': 1,
        '[object Uint8ClampedArray]': 1,
        '[object Int16Array]': 1,
        '[object Uint16Array]': 1,
        '[object Int32Array]': 1,
        '[object Uint32Array]': 1,
        '[object Float32Array]': 1,
        '[object Float64Array]': 1
    };

    var objToString = Object.prototype.toString;

    var arrayProto = Array.prototype;
    var nativeForEach = arrayProto.forEach;
    var nativeFilter = arrayProto.filter;
    var nativeSlice = arrayProto.slice;
    var nativeMap = arrayProto.map;
    var nativeReduce = arrayProto.reduce;

    /**
     * Those data types can be cloned:
     *     Plain object, Array, TypedArray, number, string, null, undefined.
     * Those data types will be assgined using the orginal data:
     *     BUILTIN_OBJECT
     * Instance of user defined class will be cloned to a plain object, without
     * properties in prototype.
     * Other data types is not supported (not sure what will happen).
     *
     * Caution: do not support clone Date, for performance consideration.
     * (There might be a large number of date in `series.data`).
     * So date should not be modified in and out of echarts.
     *
     * @param {*} source
     * @return {*} new
     */
    function clone(source) {
        if (source == null || typeof source != 'object') {
            return source;
        }

        var result = source;
        var typeStr = objToString.call(source);

        if (typeStr === '[object Array]') {
            result = [];
            for (var i = 0, len = source.length; i < len; i++) {
                result[i] = clone(source[i]);
            }
        }
        else if (TYPED_ARRAY[typeStr]) {
            result = source.constructor.from(source);
        }
        else if (!BUILTIN_OBJECT[typeStr] && !isDom(source)) {
            result = {};
            for (var key in source) {
                if (source.hasOwnProperty(key)) {
                    result[key] = clone(source[key]);
                }
            }
        }

        return result;
    }

    /**
     * @memberOf module:zrender/core/util
     * @param {*} target
     * @param {*} source
     * @param {boolean} [overwrite=false]
     */
    function merge(target, source, overwrite) {
        // We should escapse that source is string
        // and enter for ... in ...
        if (!isObject(source) || !isObject(target)) {
            return overwrite ? clone(source) : target;
        }

        for (var key in source) {
            if (source.hasOwnProperty(key)) {
                var targetProp = target[key];
                var sourceProp = source[key];

                if (isObject(sourceProp)
                    && isObject(targetProp)
                    && !isArray(sourceProp)
                    && !isArray(targetProp)
                    && !isDom(sourceProp)
                    && !isDom(targetProp)
                    && !isBuildInObject(sourceProp)
                    && !isBuildInObject(targetProp)
                ) {
                    // 如果需要递归覆盖，就递归调用merge
                    merge(targetProp, sourceProp, overwrite);
                }
                else if (overwrite || !(key in target)) {
                    // 否则只处理overwrite为true，或者在目标对象中没有此属性的情况
                    // NOTE，在 target[key] 不存在的时候也是直接覆盖
                    target[key] = clone(source[key], true);
                }
            }
        }

        return target;
    }

    /**
     * @param {Array} targetAndSources The first item is target, and the rests are source.
     * @param {boolean} [overwrite=false]
     * @return {*} target
     */
    function mergeAll(targetAndSources, overwrite) {
        var result = targetAndSources[0];
        for (var i = 1, len = targetAndSources.length; i < len; i++) {
            result = merge(result, targetAndSources[i], overwrite);
        }
        return result;
    }

    /**
     * @param {*} target
     * @param {*} source
     * @memberOf module:zrender/core/util
     */
    function extend(target, source) {
        for (var key in source) {
            if (source.hasOwnProperty(key)) {
                target[key] = source[key];
            }
        }
        return target;
    }

    /**
     * @param {*} target
     * @param {*} source
     * @param {boolen} [overlay=false]
     * @memberOf module:zrender/core/util
     */
    function defaults(target, source, overlay) {
        for (var key in source) {
            if (source.hasOwnProperty(key)
                && (overlay ? source[key] != null : target[key] == null)
            ) {
                target[key] = source[key];
            }
        }
        return target;
    }

    function createCanvas() {
        return document.createElement('canvas');
    }
    // FIXME
    var _ctx;
    function getContext() {
        if (!_ctx) {
            // Use util.createCanvas instead of createCanvas
            // because createCanvas may be overwritten in different environment
            _ctx = util.createCanvas().getContext('2d');
        }
        return _ctx;
    }

    /**
     * 查询数组中元素的index
     * @memberOf module:zrender/core/util
     */
    function indexOf(array, value) {
        if (array) {
            if (array.indexOf) {
                return array.indexOf(value);
            }
            for (var i = 0, len = array.length; i < len; i++) {
                if (array[i] === value) {
                    return i;
                }
            }
        }
        return -1;
    }

    /**
     * 构造类继承关系
     *
     * @memberOf module:zrender/core/util
     * @param {Function} clazz 源类
     * @param {Function} baseClazz 基类
     */
    function inherits(clazz, baseClazz) {
        var clazzPrototype = clazz.prototype;
        function F() {}
        F.prototype = baseClazz.prototype;
        clazz.prototype = new F();

        for (var prop in clazzPrototype) {
            clazz.prototype[prop] = clazzPrototype[prop];
        }
        clazz.prototype.constructor = clazz;
        clazz.superClass = baseClazz;
    }

    /**
     * @memberOf module:zrender/core/util
     * @param {Object|Function} target
     * @param {Object|Function} sorce
     * @param {boolean} overlay
     */
    function mixin(target, source, overlay) {
        target = 'prototype' in target ? target.prototype : target;
        source = 'prototype' in source ? source.prototype : source;

        defaults(target, source, overlay);
    }

    /**
     * @param {Array|TypedArray} data
     */
    function isArrayLike(data) {
        if (! data) {
            return;
        }
        if (typeof data == 'string') {
            return false;
        }
        return typeof data.length == 'number';
    }

    /**
     * 数组或对象遍历
     * @memberOf module:zrender/core/util
     * @param {Object|Array} obj
     * @param {Function} cb
     * @param {*} [context]
     */
    function each(obj, cb, context) {
        if (!(obj && cb)) {
            return;
        }
        if (obj.forEach && obj.forEach === nativeForEach) {
            obj.forEach(cb, context);
        }
        else if (obj.length === +obj.length) {
            for (var i = 0, len = obj.length; i < len; i++) {
                cb.call(context, obj[i], i, obj);
            }
        }
        else {
            for (var key in obj) {
                if (obj.hasOwnProperty(key)) {
                    cb.call(context, obj[key], key, obj);
                }
            }
        }
    }

    /**
     * 数组映射
     * @memberOf module:zrender/core/util
     * @param {Array} obj
     * @param {Function} cb
     * @param {*} [context]
     * @return {Array}
     */
    function map(obj, cb, context) {
        if (!(obj && cb)) {
            return;
        }
        if (obj.map && obj.map === nativeMap) {
            return obj.map(cb, context);
        }
        else {
            var result = [];
            for (var i = 0, len = obj.length; i < len; i++) {
                result.push(cb.call(context, obj[i], i, obj));
            }
            return result;
        }
    }

    /**
     * @memberOf module:zrender/core/util
     * @param {Array} obj
     * @param {Function} cb
     * @param {Object} [memo]
     * @param {*} [context]
     * @return {Array}
     */
    function reduce(obj, cb, memo, context) {
        if (!(obj && cb)) {
            return;
        }
        if (obj.reduce && obj.reduce === nativeReduce) {
            return obj.reduce(cb, memo, context);
        }
        else {
            for (var i = 0, len = obj.length; i < len; i++) {
                memo = cb.call(context, memo, obj[i], i, obj);
            }
            return memo;
        }
    }

    /**
     * 数组过滤
     * @memberOf module:zrender/core/util
     * @param {Array} obj
     * @param {Function} cb
     * @param {*} [context]
     * @return {Array}
     */
    function filter(obj, cb, context) {
        if (!(obj && cb)) {
            return;
        }
        if (obj.filter && obj.filter === nativeFilter) {
            return obj.filter(cb, context);
        }
        else {
            var result = [];
            for (var i = 0, len = obj.length; i < len; i++) {
                if (cb.call(context, obj[i], i, obj)) {
                    result.push(obj[i]);
                }
            }
            return result;
        }
    }

    /**
     * 数组项查找
     * @memberOf module:zrender/core/util
     * @param {Array} obj
     * @param {Function} cb
     * @param {*} [context]
     * @return {Array}
     */
    function find(obj, cb, context) {
        if (!(obj && cb)) {
            return;
        }
        for (var i = 0, len = obj.length; i < len; i++) {
            if (cb.call(context, obj[i], i, obj)) {
                return obj[i];
            }
        }
    }

    /**
     * @memberOf module:zrender/core/util
     * @param {Function} func
     * @param {*} context
     * @return {Function}
     */
    function bind(func, context) {
        var args = nativeSlice.call(arguments, 2);
        return function () {
            return func.apply(context, args.concat(nativeSlice.call(arguments)));
        };
    }

    /**
     * @memberOf module:zrender/core/util
     * @param {Function} func
     * @return {Function}
     */
    function curry(func) {
        var args = nativeSlice.call(arguments, 1);
        return function () {
            return func.apply(this, args.concat(nativeSlice.call(arguments)));
        };
    }

    /**
     * @memberOf module:zrender/core/util
     * @param {*} value
     * @return {boolean}
     */
    function isArray(value) {
        return objToString.call(value) === '[object Array]';
    }

    /**
     * @memberOf module:zrender/core/util
     * @param {*} value
     * @return {boolean}
     */
    function isFunction(value) {
        return typeof value === 'function';
    }

    /**
     * @memberOf module:zrender/core/util
     * @param {*} value
     * @return {boolean}
     */
    function isString(value) {
        return objToString.call(value) === '[object String]';
    }

    /**
     * @memberOf module:zrender/core/util
     * @param {*} value
     * @return {boolean}
     */
    function isObject(value) {
        // Avoid a V8 JIT bug in Chrome 19-20.
        // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
        var type = typeof value;
        return type === 'function' || (!!value && type == 'object');
    }

    /**
     * @memberOf module:zrender/core/util
     * @param {*} value
     * @return {boolean}
     */
    function isBuildInObject(value) {
        return !!BUILTIN_OBJECT[objToString.call(value)];
    }

    /**
     * @memberOf module:zrender/core/util
     * @param {*} value
     * @return {boolean}
     */
    function isDom(value) {
        return typeof value === 'object'
            && typeof value.nodeType === 'number'
            && typeof value.ownerDocument === 'object';
    }

    /**
     * If value1 is not null, then return value1, otherwise judget rest of values.
     * @memberOf module:zrender/core/util
     * @return {*} Final value
     */
    function retrieve(values) {
        for (var i = 0, len = arguments.length; i < len; i++) {
            if (arguments[i] != null) {
                return arguments[i];
            }
        }
    }

    /**
     * @memberOf module:zrender/core/util
     * @param {Array} arr
     * @param {number} startIndex
     * @param {number} endIndex
     * @return {Array}
     */
    function slice() {
        return Function.call.apply(nativeSlice, arguments);
    }

    /**
     * @memberOf module:zrender/core/util
     * @param {boolean} condition
     * @param {string} message
     */
    function assert(condition, message) {
        if (!condition) {
            throw new Error(message);
        }
    }

    var util = {
        inherits: inherits,
        mixin: mixin,
        clone: clone,
        merge: merge,
        mergeAll: mergeAll,
        extend: extend,
        defaults: defaults,
        getContext: getContext,
        createCanvas: createCanvas,
        indexOf: indexOf,
        slice: slice,
        find: find,
        isArrayLike: isArrayLike,
        each: each,
        map: map,
        reduce: reduce,
        filter: filter,
        bind: bind,
        curry: curry,
        isArray: isArray,
        isString: isString,
        isObject: isObject,
        isFunction: isFunction,
        isBuildInObject: isBuildInObject,
        isDom: isDom,
        retrieve: retrieve,
        assert: assert,
        noop: function () {}
    };
    return util;
});
<|endoftext|>


<commit_before>/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

//
// Basic node example that prints document metadata and text content.
// Requires single file built version of PDF.js -- please run
// `gulp singlefile` before running the example.
//

// Run `gulp dist-install` to generate 'pdfjs-dist' npm package files.
const pdfjsLib = require("pdfjs-dist/legacy/build/pdf.js");

// Loading file from file system into typed array
const pdfPath =
  process.argv[2] || "../../web/compressed.tracemonkey-pldi-09.pdf";

// Will be using promises to load document, pages and misc data instead of
// callback.
const loadingTask = pdfjsLib.getDocument(pdfPath);
loadingTask.promise
  .then(function (doc) {
    const numPages = doc.numPages;
    console.log("# Document Loaded");
    console.log("Number of Pages: " + numPages);
    console.log();

    let lastPromise; // will be used to chain promises
    lastPromise = doc.getMetadata().then(function (data) {
      console.log("# Metadata Is Loaded");
      console.log("## Info");
      console.log(JSON.stringify(data.info, null, 2));
      console.log();
      if (data.metadata) {
        console.log("## Metadata");
        console.log(JSON.stringify(data.metadata.getAll(), null, 2));
        console.log();
      }
    });

    const loadPage = function (pageNum) {
      return doc.getPage(pageNum).then(function (page) {
        console.log("# Page " + pageNum);
        const viewport = page.getViewport({ scale: 1.0 });
        console.log("Size: " + viewport.width + "x" + viewport.height);
        console.log();
        return page
          .getTextContent()
          .then(function (content) {
            // Content contains lots of information about the text layout and
            // styles, but we need only strings at the moment
            const strings = content.items.map(function (item) {
              return item.str;
            });
            console.log("## Text Content");
            console.log(strings.join(" "));
            // Release page resources.
            page.cleanup();
          })
          .then(function () {
            console.log();
          });
      });
    };
    // Loading of the first page will wait on metadata and subsequent loadings
    // will wait on the previous pages.
    for (let i = 1; i <= numPages; i++) {
      lastPromise = lastPromise.then(loadPage.bind(null, i));
    }
    return lastPromise;
  })
  .then(
    function () {
      console.log("# End of Document");
    },
    function (err) {
      console.error("Error: " + err);
    }
  );
<commit_msg>Remove mention of `gulp singlefile`-command from `examples/node/getinfo.js`<commit_after>/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

//
// Basic node example that prints document metadata and text content.
//

// Run `gulp dist-install` to generate 'pdfjs-dist' npm package files.
const pdfjsLib = require("pdfjs-dist/legacy/build/pdf.js");

// Loading file from file system into typed array
const pdfPath =
  process.argv[2] || "../../web/compressed.tracemonkey-pldi-09.pdf";

// Will be using promises to load document, pages and misc data instead of
// callback.
const loadingTask = pdfjsLib.getDocument(pdfPath);
loadingTask.promise
  .then(function (doc) {
    const numPages = doc.numPages;
    console.log("# Document Loaded");
    console.log("Number of Pages: " + numPages);
    console.log();

    let lastPromise; // will be used to chain promises
    lastPromise = doc.getMetadata().then(function (data) {
      console.log("# Metadata Is Loaded");
      console.log("## Info");
      console.log(JSON.stringify(data.info, null, 2));
      console.log();
      if (data.metadata) {
        console.log("## Metadata");
        console.log(JSON.stringify(data.metadata.getAll(), null, 2));
        console.log();
      }
    });

    const loadPage = function (pageNum) {
      return doc.getPage(pageNum).then(function (page) {
        console.log("# Page " + pageNum);
        const viewport = page.getViewport({ scale: 1.0 });
        console.log("Size: " + viewport.width + "x" + viewport.height);
        console.log();
        return page
          .getTextContent()
          .then(function (content) {
            // Content contains lots of information about the text layout and
            // styles, but we need only strings at the moment
            const strings = content.items.map(function (item) {
              return item.str;
            });
            console.log("## Text Content");
            console.log(strings.join(" "));
            // Release page resources.
            page.cleanup();
          })
          .then(function () {
            console.log();
          });
      });
    };
    // Loading of the first page will wait on metadata and subsequent loadings
    // will wait on the previous pages.
    for (let i = 1; i <= numPages; i++) {
      lastPromise = lastPromise.then(loadPage.bind(null, i));
    }
    return lastPromise;
  })
  .then(
    function () {
      console.log("# End of Document");
    },
    function (err) {
      console.error("Error: " + err);
    }
  );
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  extends: [
    './rules/best-practices',
    './rules/node',
    './rules/possible-errors',
    './rules/strict-mode',
    './rules/stylistic-issues',
    './rules/variables',
  ].map(require.resolve),
  parserOptions: {
    ecmaVersion: 5,
  },
};
<commit_msg>:fire: Remove the legacy preset<commit_after><|endoftext|>


<commit_before>/* This loader renders the template with underscore if no other loader was found */
'use strict';

var _ = require('lodash');
var loaderUtils = require('loader-utils');

module.exports = function (source) {
  if (this.cacheable) {
    this.cacheable();
  }
  var allLoadersButThisOne = this.loaders.filter(function (loader) {
    // Loader API changed from `loader.module` to `loader.normal` in Webpack 2.
    return (loader.module || loader.normal) !== module.exports;
  });
  // This loader shouldn't kick in if there is any other loader
  if (allLoadersButThisOne.length > 0) {
    return source;
  }
  // Skip .js files
  if (/\.js$/.test(this.request)) {
    return source;
  }

  // The following part renders the tempalte with lodash as aminimalistic loader
  //
  // Get templating options
  var options = loaderUtils.parseQuery(this.query);
  // Webpack 2 does not allow with() statements, which lodash templates use to unwrap
  // the parameters passed to the compiled template inside the scope. We therefore
  // need to unwrap them ourselves here. This is essentially what lodash does internally
  // To tell lodash it should not use with we set a variable
  var template = _.template(source, _.defaults(options, { variable: 'data' }));
  // All templateVariables which should be available
  // @see HtmlWebpackPlugin.prototype.executeTemplate
  var templateVariables = [
    'compilation',
    'webpack',
    'webpackConfig',
    'htmlWebpackPlugin'
  ];
  return 'var _ = require(' + loaderUtils.stringifyRequest(this, require.resolve('lodash')) + ');' +
    'module.exports = function (templateParams) {' +
      // Declare the template variables in the outer scope of the
      // lodash template to unwrap them
      templateVariables.map(function (variableName) {
        return 'var ' + variableName + ' = templateParams.' + variableName;
      }).join(';') + ';' +
      // Execute the lodash template
      'return (' + template.source + ')();' +
    '}';
};
<commit_msg>this.resourcePath will avoid not skipping resource file with query params. (#588)<commit_after>/* This loader renders the template with underscore if no other loader was found */
'use strict';

var _ = require('lodash');
var loaderUtils = require('loader-utils');

module.exports = function (source) {
  if (this.cacheable) {
    this.cacheable();
  }
  var allLoadersButThisOne = this.loaders.filter(function (loader) {
    // Loader API changed from `loader.module` to `loader.normal` in Webpack 2.
    return (loader.module || loader.normal) !== module.exports;
  });
  // This loader shouldn't kick in if there is any other loader
  if (allLoadersButThisOne.length > 0) {
    return source;
  }
  // Skip .js files
  if (/\.js$/.test(this.resourcePath)) {
    return source;
  }

  // The following part renders the tempalte with lodash as aminimalistic loader
  //
  // Get templating options
  var options = loaderUtils.parseQuery(this.query);
  // Webpack 2 does not allow with() statements, which lodash templates use to unwrap
  // the parameters passed to the compiled template inside the scope. We therefore
  // need to unwrap them ourselves here. This is essentially what lodash does internally
  // To tell lodash it should not use with we set a variable
  var template = _.template(source, _.defaults(options, { variable: 'data' }));
  // All templateVariables which should be available
  // @see HtmlWebpackPlugin.prototype.executeTemplate
  var templateVariables = [
    'compilation',
    'webpack',
    'webpackConfig',
    'htmlWebpackPlugin'
  ];
  return 'var _ = require(' + loaderUtils.stringifyRequest(this, require.resolve('lodash')) + ');' +
    'module.exports = function (templateParams) {' +
      // Declare the template variables in the outer scope of the
      // lodash template to unwrap them
      templateVariables.map(function (variableName) {
        return 'var ' + variableName + ' = templateParams.' + variableName;
      }).join(';') + ';' +
      // Execute the lodash template
      'return (' + template.source + ')();' +
    '}';
};
<|endoftext|>


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

    function fetchJsonLd(url, callback, element) {
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.onload = function(e) {
            callback(element, e.target.response);
        };
        xmlHttp.open('GET', url, true);
        xmlHttp.setRequestHeader('Accept', 'application/ld+json');
        xmlHttp.send(null);
    }

    function formatDate(date) {
        // TODO Don't hardcode nl but base this on user's locale
        return date.toLocaleString('nl', {day: 'numeric', month: 'short', year: 'numeric'});
    }

    function getLinkElement(element) {
        return element.getElementsByTagName('a')[0];
    }

    function loadJsonLd(element, data) {
        var embedSize = element.getAttribute('embed-size') ? element.getAttribute('embed-size') : 'small';

        var json = JSON.parse(data),
            html =
                '';

        if (json['http://purl.org/dc/terms/publisher']) {
            html +=
            '
' +
            '
bron: '+json['http://purl.org/dc/terms/publisher']['@id']+'
' +
            '
 ' +
            '
' +
            '
ga naar '+json['http://purl.org/dc/terms/publisher']['@id']+'
' +
            '
 ';
        }

        if (json['http://xmlns.com/foaf/0.1/thumbnail']) {
            html +=
                '    <picture>' +
                '        ' +
                '    </picture>';
        }

        html +=
            '
 ' +
            '
' + json['http://purl.org/dc/terms/title']  + '
';
        if (json['http://purl.org/dc/terms/alternative']) {
            html += '
' + json['http://purl.org/dc/terms/alternative'] + '
';
        }
        html += '<time class="published ginger-embed__time" datetime="' + json['http://purl.org/dc/terms/issued'] + '">' + formatDate(new Date(json['http://purl.org/dc/terms/issued']), "YYYY") + '</time>' +
            '
 ' +
            '        ' + json['http://purl.org/dc/terms/abstract'] + '' +
            '
' + json['http://purl.org/dc/terms/description'] + '
' +
            '';

        element.innerHTML = html;
    }

    document.addEventListener('DOMContentLoaded', function() {
        Array.from(document.getElementsByTagName('ginger-embed')).forEach(function (element) {
            var url = getLinkElement(element).getAttribute('data-rdf');
            fetchJsonLd(url, loadJsonLd, element);
        });
    });
})();
<commit_msg>[rdf] Convert \n to
<commit_after>(function() {
    'use strict';

    function fetchJsonLd(url, callback, element) {
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.onload = function(e) {
            callback(element, e.target.response);
        };
        xmlHttp.open('GET', url, true);
        xmlHttp.setRequestHeader('Accept', 'application/ld+json');
        xmlHttp.send(null);
    }

    function formatDate(date) {
        // TODO Don't hardcode nl but base this on user's locale
        return date.toLocaleString('nl', {day: 'numeric', month: 'short', year: 'numeric'});
    }

    function getLinkElement(element) {
        return element.getElementsByTagName('a')[0];
    }

    function loadJsonLd(element, data) {
        var embedSize = element.getAttribute('embed-size') ? element.getAttribute('embed-size') : 'small';

        var json = JSON.parse(data),
            html =
                '';

        if (json['http://purl.org/dc/terms/publisher']) {
            html +=
            '
' +
            '
bron: '+json['http://purl.org/dc/terms/publisher']['@id']+'
' +
            '
 ' +
            '
' +
            '
ga naar '+json['http://purl.org/dc/terms/publisher']['@id']+'
' +
            '
 ';
        }

        if (json['http://xmlns.com/foaf/0.1/thumbnail']) {
            html +=
                '    <picture>' +
                '        ' +
                '    </picture>';
        }

        html +=
            '
 ' +
            '
' + json['http://purl.org/dc/terms/title']  + '
';
        if (json['http://purl.org/dc/terms/alternative']) {
            html += '
' + json['http://purl.org/dc/terms/alternative'] + '
';
        }
        html += '<time class="published ginger-embed__time" datetime="' + json['http://purl.org/dc/terms/issued'] + '">' + formatDate(new Date(json['http://purl.org/dc/terms/issued']), "YYYY") + '</time>' +
            '
 ' +
            '        ' + json['http://purl.org/dc/terms/abstract'] + '' +
            '
' + json['http://purl.org/dc/terms/description'].replace(/\n/, '
') + '
' +
            '';

        element.innerHTML = html;
    }

    document.addEventListener('DOMContentLoaded', function() {
        Array.from(document.getElementsByTagName('ginger-embed')).forEach(function (element) {
            var url = getLinkElement(element).getAttribute('data-rdf');
            fetchJsonLd(url, loadJsonLd, element);
        });
    });
})();
<|endoftext|>


<commit_before>const YouTube = require('simple-youtube-api');
const Api = new YouTube('  Y  o  u  r     A  p  i     K  e  y  ');

Api.playlistById('PL2BN1Zd8U_MsyMeK8r9Vdv1lnQGtoJaSa')
    .then(results => {
        console.log(`The playlist's title is ${results[0].title}`);
    })
    .catch(console.log);

/*

    - - - - - - - - - - - - - - - - - - - -
        playlistById:

        Parameters:
        - Playlist ID

        Returns:
        - Promise <Array, Error>

        Properties:
        - title
        - id
        - description
        - url
        - publishedAt
        - channel
          > title
          > id

*/
<commit_msg>Add getVideos to playlistById<commit_after>const YouTube = require('simple-youtube-api');
const Api = new YouTube('  Y  o  u  r     A  p  i     K  e  y  ');

Api.playlistById('PL2BN1Zd8U_MsyMeK8r9Vdv1lnQGtoJaSa')
    .then(results => {
        console.log(`The playlist's title is ${results[0].title}`);

        results[0].getVideos()
            .then(videos => {
                console.log(`This playlist has ${videos.length} videos.`);
            })
            .catch(console.log);
    })
    .catch(console.log);

/*

    - - - - - - - - - - - - - - - - - - - -
        playlistById:

        Parameters:
        - Playlist ID

        Returns:
        - Promise <Array, Error>

        Properties:
        - title
        - id
        - description
        - url
        - publishedAt
        - channel
          > title
          > id

        Functions:
        - getVideos
          >  Returns:
          >  - Promise <Array, Error>

*/
<|endoftext|>


<commit_before>/**
 * ETPL (Enterprise Template)
 * Copyright 2013 Baidu Inc. All rights reserved.
 *
 * @file 加载模板的amd模块
 * @author errorrik(errorrik@gmail.com)
 */

define(
    function (require, exports, module) {
        var etpl = require('.');

        return {
            load: function (resourceId, req, load) {
                var xhr = window.XMLHttpRequest
                    ? new XMLHttpRequest()
                    : new ActiveXObject('Microsoft.XMLHTTP');

                xhr.open( 'GET', req.toUrl( resourceId ), true );
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4) {
                        if (xhr.status >= 200 && xhr.status < 300) {
                            var source = xhr.responseText;
                            var moduleConfig = module.config();
                            if (moduleConfig.autoCompile
                                || moduleConfig.autoCompile == null
                            ) {
                                etpl.compile(source);
                            }

                            load(source);
                        }

                        xhr.onreadystatechange = new Function();
                        xhr = null;
                    }
                };

                xhr.send(null);
            }
        };
    }
);
<commit_msg>follow efe js code style<commit_after>/**
 * ETPL (Enterprise Template)
 * Copyright 2013 Baidu Inc. All rights reserved.
 *
 * @file 加载模板的amd模块
 * @author errorrik(errorrik@gmail.com)
 */

define(
    function (require, exports, module) {
        var etpl = require('.');

        return {
            load: function (resourceId, req, load) {
                var xhr = window.XMLHttpRequest
                    ? new XMLHttpRequest()
                    : new ActiveXObject('Microsoft.XMLHTTP');

                xhr.open('GET', req.toUrl(resourceId), true);

                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4) {
                        if (xhr.status >= 200 && xhr.status < 300) {
                            var source = xhr.responseText;
                            var moduleConfig = module.config();
                            if (moduleConfig.autoCompile
                                || moduleConfig.autoCompile == null
                            ) {
                                etpl.compile(source);
                            }

                            load(source);
                        }

                        xhr.onreadystatechange = new Function();
                        xhr = null;
                    }
                };

                xhr.send(null);
            }
        };
    }
);
<|endoftext|>


<commit_before>'use strict'

// Setup
const path = require('path')
const fork = require('child_process').fork
const errProps = [
  'name',
  'message',
  'fileName',
  'lineNumber',
  'stack',
  'meta'
]
const logger = {
  debug: (err) => logIt(err, 'debug'),
  info: (err) => logIt(err, 'info'),
  warn: (err) => logIt(err, 'warn'),
  fatal: (err) => logIt(err, 'fatal')
}
// Globals
let commitLogToFile = fork(path.join(__dirname, 'logger_to_file.js'))
let appName = 'oacpApp'
let logLevel = 'warn'
let logBase = __dirname
let toConsole = true
let toFile = true
let toDb = false
let whitelist

// Get new fork if this one closes
commitLogToFile.on('close', () => {
  commitLogToFile = fork(path.join(__dirname, 'logger_to_file.js'))
})

// Exports
module.exports = logger
module.exports.setOpts = (opts) => {
  opts = opts || {}
  appName = opts.appName || appName
  logLevel = opts.logLevel || logLevel
  logBase = opts.logBase || logBase
  toConsole = opts.toConsole
  toFile = opts.toFile
  toDb = opts.toDb
  whitelist = opts.whitelist
}

// Helpers
function today () {
  let d = new Date()
  return (
    `0${d.getMonth() + 1}`.slice(-2) + '_' +
    `0${d.getDate()}`.slice(-2) + '_' +
    d.getFullYear()
  )
}

function levelToInt (level) {
  switch (level) {
    case 'info': return 1
    case 'warn': return 2
    case 'fatal': return 3
    default: return 0
  }
}

function logIt (err, level) {
  if (levelToInt(level) < levelToInt(logLevel)) return
  if (whitelist) {
    let name = err.name || err.toString()
    if (name && whitelist.indexOf(name) !== -1) return
  }
  let logFilePath = path.join(logBase, `${appName}_${today()}.json`)
  let log = {}
  log.time = Date.now()
  log.level = level
  if (typeof err === 'string') log.message = err
  else errProps.forEach((p) => { if (err[p]) log[p] = err[p] })
  if (!log.name && !log.message) log.message = err
  let logText = `${level.toUpperCase()}:`
  logText += `\nTimestamp: ${new Date(log.time).toLocaleString()}`
  if (log.name) logText += `\nName: ${log.name}`
  if (log.message) logText += `\nMessage: ${log.message}`
  if (log.fileName) logText += `\nFilename: ${log.fileName}`
  if (log.lineNumber) logText += `\nLine Number: ${log.lineNumber}`
  if (log.stack) logText += `\nStack:\n ${log.stack}`
  if (log.meta) logText += `\nMeta:\n ${JSON.stringify(log.meta)}`
  logText += '\n'
  if (toFile) {
    try {
      commitLogToFile.send({logFilePath, log})
    } catch (e) {
      commitLogToFile = fork(path.join(__dirname, 'logger_to_file.js'))
    }
  }
  if (toDb) {
    // not implemented
  }
  if (toConsole) {
    switch (level) {
      case 'info': return console.info(logText)
      case 'warn': return console.warn(logText)
      case 'fatal': return console.error(logText)
      default: return console.log(logText)
    }
  }
}
<commit_msg>Log more stuffs<commit_after>'use strict'

// Setup
const path = require('path')
const fork = require('child_process').fork
const errProps = [
  'name',
  'message',
  'fileName',
  'lineNumber',
  'stack',
  'meta'
]
const logger = {
  debug: (err) => logIt(err, 'debug'),
  info: (err) => logIt(err, 'info'),
  warn: (err) => logIt(err, 'warn'),
  fatal: (err) => logIt(err, 'fatal')
}
// Globals
let commitLogToFile = fork(path.join(__dirname, 'logger_to_file.js'))
let appName = 'oacpApp'
let logLevel = 'warn'
let logBase = __dirname
let toConsole = true
let toFile = true
let toDb = false
let whitelist

// Get new fork if this one closes
commitLogToFile.on('close', () => {
  commitLogToFile = fork(path.join(__dirname, 'logger_to_file.js'))
})

// Exports
module.exports = logger
module.exports.setOpts = (opts) => {
  opts = opts || {}
  appName = opts.appName || appName
  logLevel = opts.logLevel || logLevel
  logBase = opts.logBase || logBase
  toConsole = opts.toConsole
  toFile = opts.toFile
  toDb = opts.toDb
  whitelist = opts.whitelist
}

// Helpers
function today () {
  let d = new Date()
  return (
    `0${d.getMonth() + 1}`.slice(-2) + '_' +
    `0${d.getDate()}`.slice(-2) + '_' +
    d.getFullYear()
  )
}

function levelToInt (level) {
  switch (level) {
    case 'info': return 1
    case 'warn': return 2
    case 'fatal': return 3
    default: return 0
  }
}

function initCap (str) {
  str = str || ''
  return `${str.charAt(0).toUpperCase()}${str.slice(1)}`
}

function logIt (err, level) {
  if (levelToInt(level) < levelToInt(logLevel)) return
  if (whitelist) {
    let name = err.name || err.toString()
    if (name && whitelist.indexOf(name) !== -1) return
  }
  let logFilePath = path.join(logBase, `${appName}_${today()}.json`)
  let log = {}
  log.time = Date.now()
  log.level = level
  if (typeof err === 'string') log.message = err
  else {
    Object.assign(log, err)
    errProps.forEach((p) => { if (err[p]) log[p] = err[p] })
  }
  if (!log.name && !log.message) log.message = err
  let logProps = Object.getOwnPropertyNames(log)
  let logText = `${level.toUpperCase()}:`
  logText += `\nTimestamp: ${new Date(log.time).toLocaleString()}`
  logProps.forEach((k) => {
    if (k === 'time' || k === 'level') return
    let val = typeof log[k] === 'object' ? JSON.stringify(log[k]) : log[k]
    logText += `\n${initCap(k)}: ${val}`
  })
  if (toFile) {
    try {
      commitLogToFile.send({logFilePath, log})
    } catch (e) {
      commitLogToFile = fork(path.join(__dirname, 'logger_to_file.js'))
    }
  }
  if (toDb) {
    // not implemented
  }
  if (toConsole) {
    switch (level) {
      case 'info': return console.info(logText)
      case 'warn': return console.warn(logText)
      case 'fatal': return console.error(logText)
      default: return console.log(logText)
    }
  }
}
<|endoftext|>


<commit_before>//
//  logger.js
//  origin-service
//
//  Created by Luka Mirosevic on 12/06/2014.
//  Copyright (c) 2014 Goonbee. All rights reserved.
//

var winston = require('winston'),
    Logentries = require('winston-logentries'),
    nconf = require('nconf'),
    path = require('path');

logentriesAccountKey = nconf.get('LOGENTRIES_ACCOUNT_KEY');

// basic transports
transports = [
  new winston.transports.Console({level: 'info'}),
  // new winston.transports.File({filename: path.join(__dirname, '../log/node.log'), level: 'info'}),
];

// additional transports
if (logentriesAccountKey) transports.push(new winston.transports.Logentries({token: logentriesAccountKey, level: 'info'}));

// set up the logger
var logger = new (winston.Logger)({
  transports: transports
});

// export it out
module.exports = logger;
<commit_msg>re-enabled file logging<commit_after>//
//  logger.js
//  origin-service
//
//  Created by Luka Mirosevic on 12/06/2014.
//  Copyright (c) 2014 Goonbee. All rights reserved.
//

var winston = require('winston'),
    Logentries = require('winston-logentries'),
    nconf = require('nconf'),
    path = require('path');

logentriesAccountKey = nconf.get('LOGENTRIES_ACCOUNT_KEY');

// basic transports
transports = [
  new winston.transports.Console({level: 'info'}),
  new winston.transports.File({filename: path.join(__dirname, '../log/node.log'), level: 'info'}),
];

// additional transports
if (logentriesAccountKey) transports.push(new winston.transports.Logentries({token: logentriesAccountKey, level: 'info'}));

// set up the logger
var logger = new (winston.Logger)({
  transports: transports
});

// export it out
module.exports = logger;
<|endoftext|>


<commit_before>var _ = require('underscore');
var logLevels = require('log4js').levels;

function Logger(log4js) {
  this.log4js = log4js;
}

Logger.prototype._log = function(level, message, extra) {
  var fields = _.extend({}, extra);
  if (message instanceof Error) {
    var error = message;
    message = error.message;
    fields.error = error;
  }
  this.log4js.log(level, message, fields);
};

['trace', 'debug', 'info', 'warn', 'error', 'fatal'].forEach(function(level) {
  Logger.prototype[level] = function(message, extra) {
    this._log(logLevels[level.toUpperCase()], message, extra);
  };
});

module.exports = Logger;
<commit_msg>Accept Context objects as extra in Logger<commit_after>var _ = require('underscore');
var logLevels = require('log4js').levels;
var Context = require('./context');

function Logger(log4js) {
  this.log4js = log4js;
}

/**
 * @param {String} level
 * @param {String} message
 * @param {Context|Object} extra
 * @private
 */
Logger.prototype._log = function(level, message, extra) {
  if (extra instanceof Context) {
    extra = extra.toHash();
  }
  var fields = _.extend({}, extra);
  if (message instanceof Error) {
    var error = message;
    message = error.message;
    fields.error = error;
  }
  this.log4js.log(level, message, fields);
};

['trace', 'debug', 'info', 'warn', 'error', 'fatal'].forEach(function(level) {
  Logger.prototype[level] = function(message, extra) {
    this._log(logLevels[level.toUpperCase()], message, extra);
  };
});

module.exports = Logger;
<|endoftext|>


<commit_before>var _ = require('underscore'),
    async = require('async'),
    build = require('./build'),
    combine = require('./jsCombine'),
    configLoader = require('./config'),
    Context = require('./context'),
    EventEmitter = require('events').EventEmitter,
    fs = require('fs'),
    fu = require('./fileUtil'),
    Mixin = require('./mixins'),
    plugin = require('./plugin'),
    watch = require('./watcher.js');

exports.build = build;
exports.fileUtil = fu;
exports.plugin = plugin.plugin;
exports.combine = combine.combine;
exports.config = configLoader;

/**
 *
 * @name init
 * @function This function initializes a Lumbar instance
 * @param {string} lumbarFile The lumbarFile is the main
 *  file. Its responsible to define all the platforms,
 *  packages, modules, and templates for Lumbar to use.
 * @param {Object} options supports the following options:
 *   packageConfigFile (string): name of the package config file.
 *   outdir (string): path to directory of where to output the files.
 *   minimize (boolean): Should we minimize the files?
 * @return {Object.<Function>}
 */
exports.init = function(lumbarFile, options) {
    var outdir = options.outdir,
        plugins = plugin.create(options),
        mixins = new Mixin(options),
        config,
        configCache,
        context;

    function logError(err) {
      if (err) {
        event.emit('error', err);
      }
    }

    function loadConfig(path, callback) {
      try {
        fu.resetCache();

        configCache = {};
        config = configLoader.load(path);
        plugins.initialize(config);

        config.outdir = options.outdir = outdir || config.attributes.output;

        context = new Context(options, config, plugins, mixins, event);
        context.options = options;
        context.configCache = configCache;

        mixins.initialize(context, function(err) {
          if (err) {
            callback(err);
          }

          plugins.loadConfig(context, function(err) {
            if (err) {
              callback(err);
            }

            // Ensure that we have the proper build output
            if (!config.outdir) {
              return callback(new Error('Output must be defined on the command line or config file.'));
            }
            context.outdir = config.outdir;

            fu.ensureDirs(config.outdir + '/.', function(err) {
              var stat = fs.statSync(config.outdir);
              if (!stat.isDirectory()) {
                callback(new Error("Output must be a directory"));
              } else {
                callback();
              }
            });
          });
        });
      } catch (err) {
        callback(err);
      }
    }

    function buildPlatform(context, callback) {
      var modes = context.mode ? [context.mode] : plugins.modes();

      async.forEach(modes, function(mode, callback) {
          buildMode(mode, context, callback);
        },
        callback);
    }
    function buildMode(mode, context, callback) {
      var modules = context.module ? [context.module] : config.moduleList(context.package);

      context = context.clone();
      context.mode = mode;

      if (context.fileConfig) {
        processConfig(context.fileConfig, callback);
      } else {
        plugins.outputConfigs(context, function(err, configs) {
          if (err) {
            return callback(err);
          }
          async.forEach(configs, processConfig, callback);
        });
      }

      function processConfig(fileConfig, callback) {
        var fileContext = context.clone(true);
        fileContext.fileConfig = fileConfig;
        fileContext.resources = [];
        fileContext.combineResources = {};
        fileContext.fileCache = fileContext.combined ? {} : undefined;

        async.forEach(modules, function(module, callback) {
          var moduleContext = fileContext.clone();
          moduleContext.module = module;

          buildModule(moduleContext, callback);
        },
        function(err) {
          if (err) {
            return callback(err);
          }

          plugins.modeComplete(fileContext, callback);
        });
      }
    }
    function buildModule(context, callback) {
      context.module = config.module(context.module);
      context.fileCache = context.combined ? context.fileCache : {};
      context.moduleCache = {};

      var resource = context.resource;
      if (resource) {
        resource = resource.originalResource || resource;
        processResources([resource]);
      } else {
        // Load all resources associated with this module
        build.loadResources(context, function(err, resources) {
          if (err) {
            return callback(err);
          }
          processResources(resources);
        });
      }

      function processResources(resources) {
        build.processResources(resources, context, function(err, resources) {
          if (err) {
            return callback(err);
          }

          context.moduleResources = resources;
          plugins.module(context, callback);
        });
      }
    }

    var event = new EventEmitter(),
        watching = {};

    function watchOutputHandler(status) {
      // If we are already watching a file don't do it again. Note that this prevents inputs
      // from changing without the config also changing.
      if (watching[status.fileName]) {
        return;
      }

      var originalConfig = config;
      var rebuild = _.debounce(function() {
        if (config !== originalConfig) {
          // Ignore builds that may have occured at the same time as a config file change (i.e. a branch switch)
          return;
        }

        buildPlatform(context.clone(status), logError);
      }, 500);

      var input = status.inputs.map(function(input) { return fu.resolvePath(input.dir || input); });
      watch.watchFile({ virtual: status.fileName }, input, function(type, filename, sourceChange) {
          event.emit('watch-change', {fileName: sourceChange, output: status.fileName});
          fu.resetCache(sourceChange);
          rebuild();
        });
      watching[status.fileName] = true;
    }

    return _.extend(event, {
      config: function() {
        return config;
      },

      use: function(plugin) {
        plugins.use(plugin);
      },
      /**
       *
       * @name build
       * @function This function builds out the package(s).
       * @param {string} packageName the name of the package listed under
       *  'packages' from the lumbarFile passed in during the call to init().
       * @param {Function} callback the node process Function
       */
      build: function(packageName, moduleName, callback) {
        if (!callback) {
          callback = moduleName;
          moduleName = undefined;
        }

        loadConfig(lumbarFile, function(err) {
          if (err) {
            return callback(err);
          }

          var options = {
            'module': moduleName
          };
          if (typeof packageName === "object") {
            options = packageName;
            packageName = options.package;
          }

          var packageNames = packageName ? [packageName] : config.packageList(),
              contexts = [];

          packageNames.forEach(function(pkg) {
            options.package = pkg;

            var platforms = config.platformList(pkg);
            platforms.forEach(function(platform) {
              options.platform = platform;

              var newContext = context.clone(options);
              contexts.push(newContext);
            });
          });

          async.forEach(contexts, buildPlatform, callback);
        });
      },
      watch: function(packageName, moduleName, callback) {
        if (!fs.watch) {
          throw new Error('Watch requires fs.watch, introduced in Node v0.6.0');
        }

        var self = this;
        loadConfig(lumbarFile, function(err) {
          if (err) {
            logError(err);
          }

          if (!callback) {
            callback = moduleName;
            moduleName = undefined;
          }

          var packages = packageName ? [packageName] : config.packageList();

          // Watch for changes in the config file
          // WARN : This isn't really safe for multiple executions, this is a concious design decision
          watch.watchFile(lumbarFile, [], function() {
            event.emit('watch-change', {fileName: lumbarFile, config: true});
            config = undefined;

            // Cleanup what we can, breaking things along the way
            watch.unwatchAll();
            watching = {};

            // Give it a chance to cleanup before start recreating. Attempting to avoid the too many files error.
            setTimeout(function() {
              self.watch(packageName, callback);
            }, 1000);
          });

          // Watch the individual components
          event.removeListener('output', watchOutputHandler);
          event.on('output', watchOutputHandler);

          // Actual build everything
          packages.forEach(function(name) {
            self.build(name, moduleName, logError);
          });
        });
      },
      unwatch: function() {
        watch.unwatchAll();
      }
    });
};
<commit_msg>Short circuit on mixin load failure<commit_after>var _ = require('underscore'),
    async = require('async'),
    build = require('./build'),
    combine = require('./jsCombine'),
    configLoader = require('./config'),
    Context = require('./context'),
    EventEmitter = require('events').EventEmitter,
    fs = require('fs'),
    fu = require('./fileUtil'),
    Mixin = require('./mixins'),
    plugin = require('./plugin'),
    watch = require('./watcher.js');

exports.build = build;
exports.fileUtil = fu;
exports.plugin = plugin.plugin;
exports.combine = combine.combine;
exports.config = configLoader;

/**
 *
 * @name init
 * @function This function initializes a Lumbar instance
 * @param {string} lumbarFile The lumbarFile is the main
 *  file. Its responsible to define all the platforms,
 *  packages, modules, and templates for Lumbar to use.
 * @param {Object} options supports the following options:
 *   packageConfigFile (string): name of the package config file.
 *   outdir (string): path to directory of where to output the files.
 *   minimize (boolean): Should we minimize the files?
 * @return {Object.<Function>}
 */
exports.init = function(lumbarFile, options) {
    var outdir = options.outdir,
        plugins = plugin.create(options),
        mixins = new Mixin(options),
        config,
        configCache,
        context;

    function logError(err) {
      if (err) {
        event.emit('error', err);
      }
    }

    function loadConfig(path, callback) {
      try {
        fu.resetCache();

        configCache = {};
        config = configLoader.load(path);
        plugins.initialize(config);

        config.outdir = options.outdir = outdir || config.attributes.output;

        context = new Context(options, config, plugins, mixins, event);
        context.options = options;
        context.configCache = configCache;

        mixins.initialize(context, function(err) {
          if (err) {
            return callback(err);
          }

          plugins.loadConfig(context, function(err) {
            if (err) {
              return callback(err);
            }

            // Ensure that we have the proper build output
            if (!config.outdir) {
              return callback(new Error('Output must be defined on the command line or config file.'));
            }
            context.outdir = config.outdir;

            fu.ensureDirs(config.outdir + '/.', function(err) {
              var stat = fs.statSync(config.outdir);
              if (!stat.isDirectory()) {
                callback(new Error("Output must be a directory"));
              } else {
                callback();
              }
            });
          });
        });
      } catch (err) {
        callback(err);
      }
    }

    function buildPlatform(context, callback) {
      var modes = context.mode ? [context.mode] : plugins.modes();

      async.forEach(modes, function(mode, callback) {
          buildMode(mode, context, callback);
        },
        callback);
    }
    function buildMode(mode, context, callback) {
      var modules = context.module ? [context.module] : config.moduleList(context.package);

      context = context.clone();
      context.mode = mode;

      if (context.fileConfig) {
        processConfig(context.fileConfig, callback);
      } else {
        plugins.outputConfigs(context, function(err, configs) {
          if (err) {
            return callback(err);
          }
          async.forEach(configs, processConfig, callback);
        });
      }

      function processConfig(fileConfig, callback) {
        var fileContext = context.clone(true);
        fileContext.fileConfig = fileConfig;
        fileContext.resources = [];
        fileContext.combineResources = {};
        fileContext.fileCache = fileContext.combined ? {} : undefined;

        async.forEach(modules, function(module, callback) {
          var moduleContext = fileContext.clone();
          moduleContext.module = module;

          buildModule(moduleContext, callback);
        },
        function(err) {
          if (err) {
            return callback(err);
          }

          plugins.modeComplete(fileContext, callback);
        });
      }
    }
    function buildModule(context, callback) {
      context.module = config.module(context.module);
      context.fileCache = context.combined ? context.fileCache : {};
      context.moduleCache = {};

      var resource = context.resource;
      if (resource) {
        resource = resource.originalResource || resource;
        processResources([resource]);
      } else {
        // Load all resources associated with this module
        build.loadResources(context, function(err, resources) {
          if (err) {
            return callback(err);
          }
          processResources(resources);
        });
      }

      function processResources(resources) {
        build.processResources(resources, context, function(err, resources) {
          if (err) {
            return callback(err);
          }

          context.moduleResources = resources;
          plugins.module(context, callback);
        });
      }
    }

    var event = new EventEmitter(),
        watching = {};

    function watchOutputHandler(status) {
      // If we are already watching a file don't do it again. Note that this prevents inputs
      // from changing without the config also changing.
      if (watching[status.fileName]) {
        return;
      }

      var originalConfig = config;
      var rebuild = _.debounce(function() {
        if (config !== originalConfig) {
          // Ignore builds that may have occured at the same time as a config file change (i.e. a branch switch)
          return;
        }

        buildPlatform(context.clone(status), logError);
      }, 500);

      var input = status.inputs.map(function(input) { return fu.resolvePath(input.dir || input); });
      watch.watchFile({ virtual: status.fileName }, input, function(type, filename, sourceChange) {
          event.emit('watch-change', {fileName: sourceChange, output: status.fileName});
          fu.resetCache(sourceChange);
          rebuild();
        });
      watching[status.fileName] = true;
    }

    return _.extend(event, {
      config: function() {
        return config;
      },

      use: function(plugin) {
        plugins.use(plugin);
      },
      /**
       *
       * @name build
       * @function This function builds out the package(s).
       * @param {string} packageName the name of the package listed under
       *  'packages' from the lumbarFile passed in during the call to init().
       * @param {Function} callback the node process Function
       */
      build: function(packageName, moduleName, callback) {
        if (!callback) {
          callback = moduleName;
          moduleName = undefined;
        }

        loadConfig(lumbarFile, function(err) {
          if (err) {
            return callback(err);
          }

          var options = {
            'module': moduleName
          };
          if (typeof packageName === "object") {
            options = packageName;
            packageName = options.package;
          }

          var packageNames = packageName ? [packageName] : config.packageList(),
              contexts = [];

          packageNames.forEach(function(pkg) {
            options.package = pkg;

            var platforms = config.platformList(pkg);
            platforms.forEach(function(platform) {
              options.platform = platform;

              var newContext = context.clone(options);
              contexts.push(newContext);
            });
          });

          async.forEach(contexts, buildPlatform, callback);
        });
      },
      watch: function(packageName, moduleName, callback) {
        if (!fs.watch) {
          throw new Error('Watch requires fs.watch, introduced in Node v0.6.0');
        }

        var self = this;
        loadConfig(lumbarFile, function(err) {
          if (err) {
            logError(err);
          }

          if (!callback) {
            callback = moduleName;
            moduleName = undefined;
          }

          var packages = packageName ? [packageName] : config.packageList();

          // Watch for changes in the config file
          // WARN : This isn't really safe for multiple executions, this is a concious design decision
          watch.watchFile(lumbarFile, [], function() {
            event.emit('watch-change', {fileName: lumbarFile, config: true});
            config = undefined;

            // Cleanup what we can, breaking things along the way
            watch.unwatchAll();
            watching = {};

            // Give it a chance to cleanup before start recreating. Attempting to avoid the too many files error.
            setTimeout(function() {
              self.watch(packageName, callback);
            }, 1000);
          });

          // If we have errored do not exec everything as it could be in an indeterminate state
          if (err) {
            return;
          }

          // Watch the individual components
          event.removeListener('output', watchOutputHandler);
          event.on('output', watchOutputHandler);

          // Actual build everything
          packages.forEach(function(name) {
            self.build(name, moduleName, logError);
          });
        });
      },
      unwatch: function() {
        watch.unwatchAll();
      }
    });
};
<|endoftext|>


<commit_before>import {
    geoExtent,
    geoLineIntersection,
    geoMetersToLat,
    geoMetersToLon,
    geoSphericalDistance,
    geoVecInterp,
} from '../geo';
import {
    utilDisplayLabel
} from '../util';
import {
    actionAddMidpoint,
    actionChangeTags
} from '../actions';
import { t } from '../util/locale';
import {
    validationIssue,
    validationIssueFix
} from '../core/validator';

/**
 * Look for roads that can be connected to other roads with a short extension
 */
export function validationAlmostJunction() {

    function isHighway(entity) {
        return entity.type === 'way' && entity.tags.highway && entity.tags.highway !== 'no';
    }
    function isNoexit(node) {
        return node.tags.noexit && node.tags.noexit === 'yes';
    }

    function findConnectableEndNodesByExtension(way, graph, tree) {
        var results = [],
            nidFirst = way.nodes[0],
            nidLast = way.nodes[way.nodes.length - 1],
            nodeFirst = graph.entity(nidFirst),
            nodeLast = graph.entity(nidLast);

        if (nidFirst === nidLast) return results;
        if (!isNoexit(nodeFirst) && graph.parentWays(nodeFirst).length === 1) {
            var connNearFirst = canConnectByExtend(way, 0, graph, tree);
            if (connNearFirst !== null) {
                results.push({
                    node: nodeFirst,
                    wid: connNearFirst.wid,
                    edge: connNearFirst.edge,
                    cross_loc: connNearFirst.cross_loc
                });
            }
        }
        if (!isNoexit(nodeLast) && graph.parentWays(nodeLast).length === 1) {
            var connNearLast = canConnectByExtend(way, way.nodes.length - 1, graph, tree);
            if (connNearLast !== null) {
                results.push({
                    node: nodeLast,
                    wid: connNearLast.wid,
                    edge: connNearLast.edge,
                    cross_loc: connNearLast.cross_loc
                });
            }
        }
        return results;
    }

    function canConnectByExtend(way, endNodeIdx, graph, tree) {
        var EXTEND_TH_METERS = 5,
            tipNid = way.nodes[endNodeIdx],  // the 'tip' node for extension point
            midNid = endNodeIdx === 0 ? way.nodes[1] : way.nodes[way.nodes.length - 2],  // the other node of the edge
            tipNode = graph.entity(tipNid),
            midNode = graph.entity(midNid),
            lon = tipNode.loc[0],
            lat = tipNode.loc[1],
            lon_range = geoMetersToLon(EXTEND_TH_METERS, lat) / 2,
            lat_range = geoMetersToLat(EXTEND_TH_METERS) / 2,
            queryExtent = geoExtent([
                [lon - lon_range, lat - lat_range],
                [lon + lon_range, lat + lat_range]
            ]);

        // first, extend the edge of [midNode -> tipNode] by EXTEND_TH_METERS and find the "extended tip" location
        var edgeLen = geoSphericalDistance(midNode.loc, tipNode.loc),
            t = EXTEND_TH_METERS / edgeLen + 1.0,
            extTipLoc = geoVecInterp(midNode.loc, tipNode.loc, t);

        // then, check if the extension part [tipNode.loc -> extTipLoc] intersects any other ways
        var intersected = tree.intersects(queryExtent, graph);
        for (var i = 0; i < intersected.length; i++) {
            if (!isHighway(intersected[i]) || intersected[i].id === way.id) continue;
            var way2 = intersected[i];
            for (var j = 0; j < way2.nodes.length - 1; j++) {
                var nA = graph.entity(way2.nodes[j]),
                    nB = graph.entity(way2.nodes[j + 1]),
                    crossLoc = geoLineIntersection([tipNode.loc, extTipLoc], [nA.loc, nB.loc]);
                if (crossLoc !== null) {
                    return {
                        wid: way2.id,
                        edge: [nA.id, nB.id],
                        cross_loc: crossLoc
                    };
                }
            }
        }
        return null;
    }

    var type = 'almost_junction';

    var validation = function(endHighway, context) {
        var graph = context.graph();
        var tree = context.history().tree();
        var issues = [];
        if (!isHighway(endHighway)) return issues;
        var extendableNodes = findConnectableEndNodesByExtension(endHighway, graph, tree);
        for (var j = 0; j < extendableNodes.length; j++) {
            var node = extendableNodes[j].node;
            var edgeHighway = graph.entity(extendableNodes[j].wid);

            var fixes = [
              new validationIssueFix({
                  title: t('issues.fix.connect_almost_junction.title'),
                  onClick: function() {
                      var endNode = this.issue.entities[1],
                          targetEdge = this.issue.info.edge,
                          crossLoc = this.issue.info.cross_loc;
                      context.perform(
                          actionAddMidpoint({loc: crossLoc, edge: targetEdge}, endNode),
                          t('issues.fix.connect_almost_junction.undo_redo')
                      );
                  }
              })
            ];
            if (Object.keys(node.tags).length === 0) {
                // node has no tags, suggest noexit fix
                fixes.push(new validationIssueFix({
                    title: t('issues.fix.tag_as_disconnected.title'),
                    onClick: function() {
                        var nodeID = this.issue.entities[1].id;
                        context.perform(
                            actionChangeTags(nodeID, {noexit: 'yes'}),
                            t('issues.fix.tag_as_disconnected.undo_redo')
                        );
                    }
                }));
            }
            issues.push(new validationIssue({
                type: type,
                severity: 'warning',
                message: t('issues.almost_junction.message', {
                    feature: utilDisplayLabel(endHighway, context),
                    feature2: utilDisplayLabel(edgeHighway, context)
                }),
                tooltip: t('issues.almost_junction.highway-highway.tip'),
                entities: [endHighway, node, edgeHighway],
                coordinates: extendableNodes[j].node.loc,
                info: {
                    edge: extendableNodes[j].edge,
                    cross_loc: extendableNodes[j].cross_loc
                },
                fixes: fixes
            }));
        }

        return issues;
    };

    validation.type = type;

    return validation;
}
<commit_msg>Add self-intersection check before flagging almost junction issues<commit_after>import _cloneDeep from 'lodash-es/cloneDeep';
import {
    geoExtent,
    geoLineIntersection,
    geoMetersToLat,
    geoMetersToLon,
    geoSphericalDistance,
    geoVecInterp,
    geoHasSelfIntersections
} from '../geo';
import {
    utilDisplayLabel
} from '../util';
import {
    actionAddMidpoint,
    actionChangeTags
} from '../actions';
import { t } from '../util/locale';
import {
    validationIssue,
    validationIssueFix
} from '../core/validator';

/**
 * Look for roads that can be connected to other roads with a short extension
 */
export function validationAlmostJunction() {

    function isHighway(entity) {
        return entity.type === 'way' && entity.tags.highway && entity.tags.highway !== 'no';
    }
    function isNoexit(node) {
        return node.tags.noexit && node.tags.noexit === 'yes';
    }

    function findConnectableEndNodesByExtension(way, graph, tree) {
        var results = [],
            nidFirst = way.nodes[0],
            nidLast = way.nodes[way.nodes.length - 1],
            nodeFirst = graph.entity(nidFirst),
            nodeLast = graph.entity(nidLast);

        if (nidFirst === nidLast) return results;

        var testNodes;

        if (!isNoexit(nodeFirst) && graph.parentWays(nodeFirst).length === 1) {
            var connNearFirst = canConnectByExtend(way, 0, graph, tree);
            if (connNearFirst !== null) {
                testNodes = _cloneDeep(graph.childNodes(way));
                testNodes[0].loc = connNearFirst.cross_loc;
                // don't flag issue if connecting the ways would cause self-intersection
                if (!geoHasSelfIntersections(testNodes, nodeFirst.id)) {
                    results.push({
                        node: nodeFirst,
                        wid: connNearFirst.wid,
                        edge: connNearFirst.edge,
                        cross_loc: connNearFirst.cross_loc
                    });
                }
            }
        }
        if (!isNoexit(nodeLast) && graph.parentWays(nodeLast).length === 1) {
            var connNearLast = canConnectByExtend(way, way.nodes.length - 1, graph, tree);
            if (connNearLast !== null) {
                testNodes = _cloneDeep(graph.childNodes(way));
                testNodes[testNodes.length-1].loc = connNearLast.cross_loc;
                // don't flag issue if connecting the ways would cause self-intersection
                if (!geoHasSelfIntersections(testNodes, nodeLast.id)) {
                    results.push({
                        node: nodeLast,
                        wid: connNearLast.wid,
                        edge: connNearLast.edge,
                        cross_loc: connNearLast.cross_loc
                    });
                }
            }
        }
        return results;
    }

    function canConnectByExtend(way, endNodeIdx, graph, tree) {
        var EXTEND_TH_METERS = 5,
            tipNid = way.nodes[endNodeIdx],  // the 'tip' node for extension point
            midNid = endNodeIdx === 0 ? way.nodes[1] : way.nodes[way.nodes.length - 2],  // the other node of the edge
            tipNode = graph.entity(tipNid),
            midNode = graph.entity(midNid),
            lon = tipNode.loc[0],
            lat = tipNode.loc[1],
            lon_range = geoMetersToLon(EXTEND_TH_METERS, lat) / 2,
            lat_range = geoMetersToLat(EXTEND_TH_METERS) / 2,
            queryExtent = geoExtent([
                [lon - lon_range, lat - lat_range],
                [lon + lon_range, lat + lat_range]
            ]);

        // first, extend the edge of [midNode -> tipNode] by EXTEND_TH_METERS and find the "extended tip" location
        var edgeLen = geoSphericalDistance(midNode.loc, tipNode.loc),
            t = EXTEND_TH_METERS / edgeLen + 1.0,
            extTipLoc = geoVecInterp(midNode.loc, tipNode.loc, t);

        // then, check if the extension part [tipNode.loc -> extTipLoc] intersects any other ways
        var intersected = tree.intersects(queryExtent, graph);
        for (var i = 0; i < intersected.length; i++) {
            if (!isHighway(intersected[i]) || intersected[i].id === way.id) continue;
            var way2 = intersected[i];
            for (var j = 0; j < way2.nodes.length - 1; j++) {
                var nA = graph.entity(way2.nodes[j]),
                    nB = graph.entity(way2.nodes[j + 1]),
                    crossLoc = geoLineIntersection([tipNode.loc, extTipLoc], [nA.loc, nB.loc]);
                if (crossLoc !== null) {
                    return {
                        wid: way2.id,
                        edge: [nA.id, nB.id],
                        cross_loc: crossLoc
                    };
                }
            }
        }
        return null;
    }

    var type = 'almost_junction';

    var validation = function(endHighway, context) {

        if (!isHighway(endHighway)) return [];

        var graph = context.graph();
        var tree = context.history().tree();

        var issues = [];
        var extendableNodeInfos = findConnectableEndNodesByExtension(endHighway, graph, tree);
        extendableNodeInfos.forEach(function(extendableNodeInfo) {
            var node = extendableNodeInfo.node;
            var edgeHighway = graph.entity(extendableNodeInfo.wid);
            var fixes = [
              new validationIssueFix({
                  title: t('issues.fix.connect_almost_junction.title'),
                  onClick: function() {
                      var endNode = this.issue.entities[1],
                          targetEdge = this.issue.info.edge,
                          crossLoc = this.issue.info.cross_loc;
                      context.perform(
                          actionAddMidpoint({loc: crossLoc, edge: targetEdge}, endNode),
                          t('issues.fix.connect_almost_junction.undo_redo')
                      );
                  }
              })
            ];
            if (Object.keys(node.tags).length === 0) {
                // node has no tags, suggest noexit fix
                fixes.push(new validationIssueFix({
                    title: t('issues.fix.tag_as_disconnected.title'),
                    onClick: function() {
                        var nodeID = this.issue.entities[1].id;
                        context.perform(
                            actionChangeTags(nodeID, {noexit: 'yes'}),
                            t('issues.fix.tag_as_disconnected.undo_redo')
                        );
                    }
                }));
            }
            issues.push(new validationIssue({
                type: type,
                severity: 'warning',
                message: t('issues.almost_junction.message', {
                    feature: utilDisplayLabel(endHighway, context),
                    feature2: utilDisplayLabel(edgeHighway, context)
                }),
                tooltip: t('issues.almost_junction.highway-highway.tip'),
                entities: [endHighway, node, edgeHighway],
                coordinates: extendableNodeInfo.node.loc,
                info: {
                    edge: extendableNodeInfo.edge,
                    cross_loc: extendableNodeInfo.cross_loc
                },
                fixes: fixes
            }));
        });

        return issues;
    };

    validation.type = type;

    return validation;
}
<|endoftext|>


<commit_before>'use babel';

const {CompositeDisposable} = require('atom');
const validUrl = require('valid-url');

class mdwrap {
  constructor() {
    this.subscriptions = new CompositeDisposable;

    this.subscriptions.add(
      atom.commands.add(
        'atom-workspace', {
          'atom-markdown-wrapper:paste': this.paste,
          'atom-markdown-wrapper:image': this.image,
          'atom-markdown-wrapper:bold': this.bold,
          'atom-markdown-wrapper:italic': this.italic
        }
      )
    )
  }

  destroy() {
    this.subscriptions.dispose();
  }

  paste(editor, selection, clipboard) {
    let insert;

    if (editor && selection && clipboard) {
      insert = '[$selection]($href)'
        .replace('$selection', selection)
        .replace('$href', clipboard);
    }

    if (!validUrl.isWebUri(clipboard) && !clipboard.match(/^\#/)) {
      throw new Error('Not a valid URL or #anchor');
    }

    editor.insertText(insert);

    return insert;
  }

  image(editor, selection, clipboard) {
    let insert;

    if (editor && clipboard) {
      insert = '![$selection]($href)'
        .replace('$selection', selection || '')
        .replace('$href', clipboard);
    }

    if (!validUrl.isWebUri(clipboard)) {
      throw new Error('Not a valid image URL');
    }

    editor.insertText(insert);

    return insert;
  }

  bold(editor, selection) {
    let insert;

    if (editor && selection) {
      insert = '**$selection**'
        .replace('$selection', selection);
    }
    editor.insertText(insert);

    return insert;
  }

  italic(editor, selection) {
    let insert;

    if (editor && selection) {
      insert = '_$selection_'
        .replace('$selection', selection);
    }
    editor.insertText(insert);

    return insert;
  }
}

module.exports = mdwrap;
<commit_msg>Fix editor.insertText is not a function bug<commit_after>'use babel';

const {CompositeDisposable} = require('atom');
const validUrl = require('valid-url');

class mdwrap {
  constructor() {
    this.subscriptions = new CompositeDisposable;

    this.subscriptions.add(
      atom.commands.add('atom-workspace', {
        'atom-markdown-wrapper:paste': this.paste,
        'atom-markdown-wrapper:image': this.image,
        'atom-markdown-wrapper:bold': this.bold,
        'atom-markdown-wrapper:italic': this.italic
      })
    )
  }

  destroy() {
    this.subscriptions.dispose();
  }

  paste(editor, selection, clipboard) {
    // abort early
    if (!editor.insertText || !clipboard) {
      return;
    }

    let insert;

    if (editor && selection && clipboard) {
      insert = '[$selection]($href)'
        .replace('$selection', selection)
        .replace('$href', clipboard);
    }

    if (!validUrl.isWebUri(clipboard) && !clipboard.match(/^\#/)) {
      throw new Error('Not a valid URL or #anchor');
    }

    editor.insertText(insert);

    return insert;
  }

  image(editor, selection, clipboard) {
    // abort early
    if (!editor.insertText || !clipboard) {
      return;
    }

    let insert;

    if (editor && clipboard) {
      insert = '![$selection]($href)'
        .replace('$selection', selection || '')
        .replace('$href', clipboard);
    }

    if (!validUrl.isWebUri(clipboard)) {
      throw new Error('Not a valid image URL');
    }

    editor.insertText(insert);

    return insert;
  }

  bold(editor, selection) {
    // abort early
    if (!editor.insertText) {
      return;
    }

    let insert;

    if (editor && selection) {
      insert = '**$selection**'
        .replace('$selection', selection);
    }
    editor.insertText(insert);

    return insert;
  }

  italic(editor, selection) {
    // abort early
    if (!editor.insertText) {
      return;
    }

    let insert;

    if (editor && selection) {
      insert = '_$selection_'
        .replace('$selection', selection);
    }
    editor.insertText(insert);

    return insert;
  }
}

module.exports = mdwrap;
<|endoftext|>


<commit_before>var pkg = require( './packages' );

module.exports = {
	'application/javascript' : function( file, content ) {
		try {
			return pkg.ugy.minify( file );
		}             // in these case a create file has been triggered when the file is saved but not valid
		catch ( e ) { // todo: should we check if the file is in a valid state, period, before re-writing it?
			console.log( e );
			return null;
		}
	},
	'text/css'               : function( content ) {
		try { return pkg.clean_css.process( content ); }
		catch ( e ) { return null; }
	}
};

<commit_msg>update uglify-js version<commit_after>var pkg = require( './packages' );

module.exports = {
	'application/javascript' : function( file, content ) {
		try {
			return pkg.ugy.minify( file ).code;
		}             // in these case a create file has been triggered when the file is saved but not valid
		catch ( e ) { // todo: should we check if the file is in a valid state, period, before re-writing it?
			console.log( e );
			return null;
		}
	},
	'text/css'               : function( content ) {
		try { return pkg.clean_css.process( content ); }
		catch ( e ) { return null; }
	}
};

<|endoftext|>


<commit_before>// mktemp Copyright(c) 2013 sasa+1
// https://github.com/sasaplus1/mktemp
// Released under the MIT License.

var fs = require('fs'),
    mkrand = require('./mkrand');

module.exports.createFile = function(path, callback) {
  var filename = mkrand(path);

  fs.writeFile(filename, '', function(err) {
    callback(err, filename);
  });
};

module.exports.createFileSync = function(path) {
  var filename = mkrand(path);

  fs.writeFileSync(filename, '');
  return filename;
};

module.exports.createDir = function(path, mode, callback) {
  var dirname = mkrand(path);

  if (typeof mode === 'function' && callback === void 0) {
    callback = mode;
    mode = 511; /*=0777*/
  }

  fs.mkdir(dirname, mode, function(err) {
    callback(err, dirname);
  });
};

module.exports.createDirSync = function(path, mode) {
  var dirname = mkrand(path);

  fs.mkdirSync(dirname, mode || 511 /*=0777*/);
  return dirname;
};
<commit_msg>関数として宣言してからエクスポートするように<commit_after>// mktemp Copyright(c) 2013 sasa+1
// https://github.com/sasaplus1/mktemp
// Released under the MIT License.

var fs = require('fs'),
    mkrand = require('./mkrand');

function createFile(path, callback) {
  var filename = mkrand(path);

  fs.writeFile(filename, '', function(err) {
    callback(err, filename);
  });
};

function createFileSync(path) {
  var filename = mkrand(path);

  fs.writeFileSync(filename, '');
  return filename;
};

function createDir(path, mode, callback) {
  var dirname = mkrand(path);

  if (typeof mode === 'function' && callback === void 0) {
    callback = mode;
    mode = 511; /*=0777*/
  }

  fs.mkdir(dirname, mode, function(err) {
    callback(err, dirname);
  });
};

function createDirSync(path, mode) {
  var dirname = mkrand(path);

  fs.mkdirSync(dirname, mode || 511 /*=0777*/);
  return dirname;
};

module.exports = {
  createFile: createFile,
  createFileSync: createFileSync,
  createDir: createDir,
  createDirSync: createDirSync
};
<|endoftext|>